@@ -5,6 +5,8 @@ import { convertAsyncIterableToArray } from '../test/convert-async-iterable-to-a
55import { convertReadableStreamToArray } from '../test/convert-readable-stream-to-array' ;
66import { MockLanguageModelV1 } from '../test/mock-language-model-v1' ;
77import { experimental_streamText } from './stream-text' ;
8+ import { ServerResponse } from 'node:http' ;
9+ import { createMockServerResponse } from '../test/mock-server-response' ;
810
911describe ( 'result.textStream' , ( ) => {
1012 it ( 'should send text deltas' , async ( ) => {
@@ -260,6 +262,53 @@ describe('result.toAIStream', () => {
260262 } ) ;
261263} ) ;
262264
265+ describe ( 'result.pipeAIStreamToResponse' , async ( ) => {
266+ it ( 'should write text deltas to a Node.js response-like object' , async ( ) => {
267+ const mockResponse = createMockServerResponse ( ) ;
268+
269+ const result = await experimental_streamText ( {
270+ model : new MockLanguageModelV1 ( {
271+ doStream : async ( ) => {
272+ return {
273+ stream : convertArrayToReadableStream ( [
274+ { type : 'text-delta' , textDelta : 'Hello' } ,
275+ { type : 'text-delta' , textDelta : ', ' } ,
276+ { type : 'text-delta' , textDelta : 'world!' } ,
277+ ] ) ,
278+ rawCall : { rawPrompt : 'prompt' , rawSettings : { } } ,
279+ } ;
280+ } ,
281+ } ) ,
282+ prompt : 'test-input' ,
283+ } ) ;
284+
285+ result . pipeAIStreamToResponse ( mockResponse ) ;
286+
287+ // Wait for the stream to finish writing to the mock response
288+ await new Promise ( resolve => {
289+ const checkIfEnded = ( ) => {
290+ if ( mockResponse . ended ) {
291+ resolve ( undefined ) ;
292+ } else {
293+ setImmediate ( checkIfEnded ) ;
294+ }
295+ } ;
296+ checkIfEnded ( ) ;
297+ } ) ;
298+
299+ const decoder = new TextDecoder ( ) ;
300+
301+ assert . strictEqual ( mockResponse . statusCode , 200 ) ;
302+ assert . deepStrictEqual ( mockResponse . headers , {
303+ 'Content-Type' : 'text/plain; charset=utf-8' ,
304+ } ) ;
305+ assert . deepStrictEqual (
306+ mockResponse . writtenChunks . map ( chunk => decoder . decode ( chunk ) ) ,
307+ [ '0:"Hello"\n' , '0:", "\n' , '0:"world!"\n' ] ,
308+ ) ;
309+ } ) ;
310+ } ) ;
311+
263312describe ( 'result.toTextStreamResponse' , ( ) => {
264313 it ( 'should create a Response with a text stream' , async ( ) => {
265314 const result = await experimental_streamText ( {
0 commit comments