|
| 1 | +import { Readable } from 'node:stream'; |
| 2 | +import { EventStreamMarshaller } from '@smithy/eventstream-serde-node'; |
| 3 | +import { APIError } from '@anthropic-ai/sdk'; |
| 4 | +import { Stream, fromUtf8, toUtf8 } from '../src/core/streaming'; |
| 5 | + |
| 6 | +function encodeChunkFrame(payload: unknown): ReadableStream { |
| 7 | + const marshaller = new EventStreamMarshaller({ utf8Encoder: toUtf8, utf8Decoder: fromUtf8 }); |
| 8 | + const inner = JSON.stringify(payload); |
| 9 | + const body = fromUtf8(JSON.stringify({ bytes: Buffer.from(inner).toString('base64') })); |
| 10 | + const serialized = marshaller.serialize( |
| 11 | + (async function* () { |
| 12 | + yield { |
| 13 | + headers: { |
| 14 | + ':message-type': { type: 'string', value: 'event' }, |
| 15 | + ':event-type': { type: 'string', value: 'chunk' }, |
| 16 | + ':content-type': { type: 'string', value: 'application/json' }, |
| 17 | + }, |
| 18 | + body, |
| 19 | + }; |
| 20 | + })(), |
| 21 | + (msg: any) => msg, |
| 22 | + ); |
| 23 | + return Readable.toWeb(Readable.from(serialized)) as ReadableStream; |
| 24 | +} |
| 25 | + |
| 26 | +describe('Bedrock Stream.fromSSEResponse', () => { |
| 27 | + test('throws APIError when a chunk frame contains an Anthropic error payload', async () => { |
| 28 | + const response = new Response( |
| 29 | + encodeChunkFrame({ type: 'error', error: { type: 'overloaded_error', message: 'test' } }), |
| 30 | + ); |
| 31 | + const stream = Stream.fromSSEResponse(response, new AbortController()); |
| 32 | + |
| 33 | + let caught: unknown; |
| 34 | + try { |
| 35 | + for await (const _ of stream) { |
| 36 | + // consume |
| 37 | + } |
| 38 | + } catch (e) { |
| 39 | + caught = e; |
| 40 | + } |
| 41 | + |
| 42 | + expect(caught).toBeInstanceOf(APIError); |
| 43 | + expect(String(caught)).not.toContain('Unexpected event order'); |
| 44 | + expect((caught as APIError).type).toBe('overloaded_error'); |
| 45 | + }); |
| 46 | + |
| 47 | + test('yields normal chunk payloads unchanged', async () => { |
| 48 | + const response = new Response( |
| 49 | + encodeChunkFrame({ type: 'message_start', message: { id: 'msg_1', role: 'assistant' } }), |
| 50 | + ); |
| 51 | + const stream = Stream.fromSSEResponse<any>(response, new AbortController()); |
| 52 | + |
| 53 | + const events: any[] = []; |
| 54 | + for await (const ev of stream) events.push(ev); |
| 55 | + |
| 56 | + expect(events).toHaveLength(1); |
| 57 | + expect(events[0].type).toBe('message_start'); |
| 58 | + }); |
| 59 | +}); |
0 commit comments