diff --git a/packages/prompts/src/__tests__/output.spec.ts b/packages/prompts/src/__tests__/output.spec.ts index b814cdbc7f..237b08e4ea 100644 --- a/packages/prompts/src/__tests__/output.spec.ts +++ b/packages/prompts/src/__tests__/output.spec.ts @@ -115,6 +115,26 @@ describe('output identity', () => { } }); + it('writes the whole streamed message using the selected output and its width', async () => { + const c = capture(10); + const write = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + await stream.message(['first', 'second'], { output: c.output, symbol: '!' }); + expect(c.text()).toBe('! first\n second\n'); + expect(write).not.toHaveBeenCalled(); + }); + + it('keeps streamed chunks together when the output has no columns', async () => { + let content = ''; + const output = new Writable({ + write(chunk, _, done) { + content += chunk.toString(); + done(); + }, + }); + await stream.message(['some', 'thing', ' else'], { output, symbol: '!' }); + expect(content).toBe('! something else\n'); + }); + it('uses one space in animated spinner frames', () => { vi.stubEnv('CI', ''); vi.useFakeTimers(); diff --git a/packages/prompts/src/stream.ts b/packages/prompts/src/stream.ts index 15dfa2da60..7d8138e37c 100644 --- a/packages/prompts/src/stream.ts +++ b/packages/prompts/src/stream.ts @@ -7,17 +7,12 @@ import type { LogMessageOptions } from './log.js'; const prefix = ' '; -// TODO (43081j): this currently doesn't support custom `output` writable -// because we rely on `columns` existing (i.e. `process.stdout.columns). -// -// If we want to support `output` being passed in, we will need to use -// a condition like `if (output instance Writable)` to check if it has columns export const stream = { message: async ( iterable: Iterable | AsyncIterable, - { symbol = '' }: LogMessageOptions = {}, + { symbol = '', output = process.stdout }: LogMessageOptions = {}, ) => { - process.stdout.write(symbol ? `${symbol} ` : ''); + output.write(symbol ? `${symbol} ` : ''); const initialWidth = symbol ? 2 : 0; let lineWidth = initialWidth; for await (let chunk of iterable) { @@ -26,15 +21,17 @@ export const stream = { lineWidth = initialWidth + strip(chunk.slice(chunk.lastIndexOf('\n'))).length; } const chunkLen = strip(chunk).length; - if (lineWidth + chunkLen < process.stdout.columns) { + const columns = + 'columns' in output && typeof output.columns === 'number' ? output.columns : Infinity; + if (lineWidth + chunkLen < columns) { lineWidth += chunkLen; - process.stdout.write(chunk); + output.write(chunk); } else { - process.stdout.write(`\n${prefix}${chunk.trimStart()}`); + output.write(`\n${prefix}${chunk.trimStart()}`); lineWidth = initialWidth + strip(chunk.trimStart()).length; } } - process.stdout.write('\n'); + output.write('\n'); }, info: (iterable: Iterable | AsyncIterable) => { return stream.message(iterable, { symbol: color.blue(S_INFO) });