2025-04-21 17:41:44 -07:00
|
|
|
/**
|
|
|
|
|
* @license
|
|
|
|
|
* Copyright 2025 Google LLC
|
|
|
|
|
* SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
export async function readStdin(): Promise<string> {
|
2025-08-14 20:08:59 +02:00
|
|
|
const MAX_STDIN_SIZE = 8 * 1024 * 1024; // 8MB
|
2025-04-21 17:41:44 -07:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
|
let data = '';
|
2025-08-14 20:08:59 +02:00
|
|
|
let totalSize = 0;
|
2025-04-21 17:41:44 -07:00
|
|
|
process.stdin.setEncoding('utf8');
|
|
|
|
|
|
2025-06-05 06:40:33 -07:00
|
|
|
const onReadable = () => {
|
2025-04-21 17:41:44 -07:00
|
|
|
let chunk;
|
|
|
|
|
while ((chunk = process.stdin.read()) !== null) {
|
2025-08-14 20:08:59 +02:00
|
|
|
if (totalSize + chunk.length > MAX_STDIN_SIZE) {
|
|
|
|
|
const remainingSize = MAX_STDIN_SIZE - totalSize;
|
|
|
|
|
data += chunk.slice(0, remainingSize);
|
|
|
|
|
console.warn(
|
|
|
|
|
`Warning: stdin input truncated to ${MAX_STDIN_SIZE} bytes.`,
|
|
|
|
|
);
|
|
|
|
|
process.stdin.destroy(); // Stop reading further
|
|
|
|
|
break;
|
|
|
|
|
}
|
2025-04-21 17:41:44 -07:00
|
|
|
data += chunk;
|
2025-08-14 20:08:59 +02:00
|
|
|
totalSize += chunk.length;
|
2025-04-21 17:41:44 -07:00
|
|
|
}
|
2025-06-05 06:40:33 -07:00
|
|
|
};
|
2025-04-21 17:41:44 -07:00
|
|
|
|
2025-06-05 06:40:33 -07:00
|
|
|
const onEnd = () => {
|
|
|
|
|
cleanup();
|
2025-04-21 17:41:44 -07:00
|
|
|
resolve(data);
|
2025-06-05 06:40:33 -07:00
|
|
|
};
|
2025-04-21 17:41:44 -07:00
|
|
|
|
2025-06-05 06:40:33 -07:00
|
|
|
const onError = (err: Error) => {
|
|
|
|
|
cleanup();
|
2025-04-21 17:41:44 -07:00
|
|
|
reject(err);
|
2025-06-05 06:40:33 -07:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const cleanup = () => {
|
|
|
|
|
process.stdin.removeListener('readable', onReadable);
|
|
|
|
|
process.stdin.removeListener('end', onEnd);
|
|
|
|
|
process.stdin.removeListener('error', onError);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
process.stdin.on('readable', onReadable);
|
|
|
|
|
process.stdin.on('end', onEnd);
|
|
|
|
|
process.stdin.on('error', onError);
|
2025-04-21 17:41:44 -07:00
|
|
|
});
|
|
|
|
|
}
|