67 lines
2.1 KiB
TypeScript
67 lines
2.1 KiB
TypeScript
import { render } from 'ink';
|
||
import { PassThrough } from 'node:stream';
|
||
import type { ReactElement } from 'react';
|
||
|
||
const ANSI_RE = /\x1b\[[0-9;?]*[a-zA-Z]|\x1b\][^\x07]*\x07|\x1b[()][B0]|\x1b[=>]/g;
|
||
|
||
/**
|
||
* 用真实 ink render + PassThrough 流构建测试 harness。
|
||
* output() 返回全部渲染输出的 ANSI 剥离文本(用于包含性断言)。
|
||
*/
|
||
export function renderHarness(element: ReactElement) {
|
||
const stdout = new PassThrough() as unknown as NodeJS.WriteStream;
|
||
(stdout as unknown as Record<string, unknown>).isTTY = true;
|
||
(stdout as unknown as Record<string, unknown>).columns = 120;
|
||
(stdout as unknown as Record<string, unknown>).rows = 40;
|
||
|
||
const chunks: string[] = [];
|
||
stdout.on('data', (chunk: Buffer) => {
|
||
chunks.push(chunk.toString());
|
||
});
|
||
|
||
const stdin = new PassThrough() as unknown as NodeJS.ReadStream;
|
||
const stdinAny = stdin as unknown as Record<string, unknown>;
|
||
stdinAny.isTTY = true;
|
||
stdinAny.setRawMode = (mode: boolean) => {
|
||
stdinAny.isRaw = mode;
|
||
return stdin;
|
||
};
|
||
stdinAny.ref = () => {};
|
||
stdinAny.unref = () => {};
|
||
|
||
const instance = render(element, {
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
stdin: stdin as any,
|
||
stdout,
|
||
exitOnCtrlC: false,
|
||
patchConsole: false,
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
} as any);
|
||
|
||
// 写入队列:逐字符 flush,避免 PassThrough 将连续写入合并为一个 data 事件
|
||
let chain: Promise<void> = Promise.resolve();
|
||
const enqueue = (data: string) => {
|
||
const parts = data.startsWith('\x1b') ? [data] : [...data];
|
||
for (const part of parts) {
|
||
chain = chain.then(async () => {
|
||
stdin.write(part);
|
||
await new Promise((resolve) => setImmediate(resolve));
|
||
});
|
||
}
|
||
};
|
||
|
||
return {
|
||
write: enqueue,
|
||
/** 将整段字符串作为单个 data 事件写入(模拟粘贴/终端合并字节)。 */
|
||
writeRaw: (data: string) => {
|
||
stdin.write(data);
|
||
},
|
||
output: () => chunks.join('').replace(ANSI_RE, ''),
|
||
stop: async () => {
|
||
await chain;
|
||
instance.unmount();
|
||
await instance.waitUntilExit;
|
||
},
|
||
};
|
||
}
|