@@ -135,33 +135,67 @@ function cohereChatStreamEventShapes(): SSEEventShape[] {
135135}
136136
137137/**
138- * Parse a Cohere v2 SSE body. Every frame is `event: <type>` + `data: <json>`
139- * whose JSON `type` equals the event name; a final `data: [DONE]` sentinel is
140- * allowed and dropped. Any other frame throws, so a framing change is loud
141- * instead of silently parsing to an empty list.
138+ * Parse a Cohere v2 SSE body by the SSE spec (WHATWG event-stream): lines end
139+ * in `\n`, `\r\n` or `\r`; a blank line dispatches the event; `:` lines are
140+ * comments; one space after the field colon is optional; `id`/`retry` and
141+ * unknown fields are ignored; multiple `data` lines join with `\n`; a final
142+ * event without a blank line is still dispatched. A `data: [DONE]` sentinel
143+ * with no event name ends the stream and is dropped.
144+ *
145+ * Still strict on content: each event's data must be a JSON object whose
146+ * `type` equals the event name (an event without `event:` is named `message`
147+ * by the spec, so it fails that check), and nothing may follow `[DONE]`.
142148 */
143149function parseCohereSSE ( body : string ) : { type : string ; data : Record < string , unknown > } [ ] {
144- const frames = body
145- . replace ( / \r \n / g, "\n" )
146- . split ( "\n\n" )
147- . filter ( ( frame ) => frame . trim ( ) !== "" ) ;
148- if ( frames . at ( - 1 ) === "data: [DONE]" ) frames . pop ( ) ;
149- return frames . map ( ( frame ) => {
150- const lines = frame . split ( "\n" ) ;
151- if ( lines . length !== 2 || ! lines [ 0 ] . startsWith ( "event: " ) || ! lines [ 1 ] . startsWith ( "data: " ) ) {
152- throw new Error ( `Unsupported Cohere SSE frame: ${ JSON . stringify ( frame ) } ` ) ;
150+ const events : { type : string ; data : Record < string , unknown > } [ ] = [ ] ;
151+ let eventName = "" ;
152+ let dataLines : string [ ] = [ ] ;
153+ let done = false ;
154+
155+ const dispatch = ( ) => {
156+ const name = eventName || "message" ;
157+ const hadData = dataLines . length > 0 ;
158+ const raw = dataLines . join ( "\n" ) ;
159+ eventName = "" ;
160+ dataLines = [ ] ;
161+ if ( ! hadData ) return ;
162+ if ( done ) throw new Error ( `Cohere SSE event after [DONE]: ${ JSON . stringify ( raw ) } ` ) ;
163+ if ( name === "message" && raw === "[DONE]" ) {
164+ done = true ;
165+ return ;
166+ }
167+ let data : unknown ;
168+ try {
169+ data = JSON . parse ( raw ) ;
170+ } catch {
171+ throw new Error ( `Cohere SSE data is not JSON: ${ JSON . stringify ( raw ) } ` ) ;
153172 }
154- const type = lines [ 0 ] . slice ( "event: " . length ) ;
155- const data : unknown = JSON . parse ( lines [ 1 ] . slice ( "data: " . length ) ) ;
156173 if ( data === null || typeof data !== "object" || Array . isArray ( data ) ) {
157- throw new Error ( `Cohere SSE data is not an object: ${ JSON . stringify ( frame ) } ` ) ;
174+ throw new Error ( `Cohere SSE data is not an object: ${ JSON . stringify ( raw ) } ` ) ;
158175 }
159176 const record = data as Record < string , unknown > ;
160- if ( record . type !== type ) {
161- throw new Error ( `Cohere SSE event name ${ type } != data.type ${ String ( record . type ) } ` ) ;
177+ if ( record . type !== name ) {
178+ throw new Error ( `Cohere SSE event name ${ name } != data.type ${ String ( record . type ) } ` ) ;
162179 }
163- return { type, data : record } ;
164- } ) ;
180+ events . push ( { type : name , data : record } ) ;
181+ } ;
182+
183+ for ( const line of body . split ( / \r \n | \r | \n / ) ) {
184+ if ( line === "" ) {
185+ dispatch ( ) ;
186+ continue ;
187+ }
188+ if ( line . startsWith ( ":" ) ) continue ;
189+ const colon = line . indexOf ( ":" ) ;
190+ const field = colon === - 1 ? line : line . slice ( 0 , colon ) ;
191+ let value = colon === - 1 ? "" : line . slice ( colon + 1 ) ;
192+ if ( value . startsWith ( " " ) ) value = value . slice ( 1 ) ;
193+ if ( field === "event" ) eventName = value ;
194+ else if ( field === "data" ) dataLines . push ( value ) ;
195+ // id, retry and unknown fields are ignored per the SSE spec.
196+ }
197+ dispatch ( ) ;
198+ return events ;
165199}
166200
167201// ---------------------------------------------------------------------------
@@ -556,12 +590,41 @@ describe("parseCohereSSE", () => {
556590 ] ) ;
557591 } ) ;
558592
559- it ( "rejects frames it does not understand instead of dropping them" , ( ) => {
560- expect ( ( ) => parseCohereSSE ( 'data: {"type":"message-start"}\n\n' ) ) . toThrow ( / U n s u p p o r t e d / ) ;
593+ it ( "accepts legal SSE variants a server or proxy may send" , ( ) => {
594+ const start = '{"type":"message-start","id":"x"}' ;
595+ const end = '{"type":"message-end","delta":{}}' ;
596+ const expected = [ "message-start" , "message-end" ] ;
597+ const variants : Record < string , string > = {
598+ canonical : `event: message-start\ndata: ${ start } \n\nevent: message-end\ndata: ${ end } \n\ndata: [DONE]\n\n` ,
599+ "single trailing newline" : `event: message-start\ndata: ${ start } \n\nevent: message-end\ndata: ${ end } \n` ,
600+ "no trailing newline" : `event: message-start\ndata: ${ start } \n\nevent: message-end\ndata: ${ end } ` ,
601+ "no space after colon" : `event:message-start\ndata:${ start } \n\nevent:message-end\ndata:${ end } \n\n` ,
602+ "keepalive comments" : `: ping\n\nevent: message-start\n:mid-frame comment\ndata: ${ start } \n\n:\n\nevent: message-end\ndata: ${ end } \n\n` ,
603+ "id and retry fields" : `retry: 3000\n\nid: 1\nevent: message-start\ndata: ${ start } \n\nid: 2\nevent: message-end\nretry: 10\ndata: ${ end } \n\n` ,
604+ CRLF : `event: message-start\r\ndata: ${ start } \r\n\r\nevent: message-end\r\ndata: ${ end } \r\n\r\ndata: [DONE]\r\n\r\n` ,
605+ CR : `event: message-start\rdata: ${ start } \r\revent: message-end\rdata: ${ end } \r\r` ,
606+ "multi-line data" : `event: message-start\ndata: {"type":\ndata: "message-start"}\n\nevent: message-end\ndata: ${ end } \n\n` ,
607+ } ;
608+ for ( const [ name , body ] of Object . entries ( variants ) ) {
609+ expect (
610+ parseCohereSSE ( body ) . map ( ( e ) => e . type ) ,
611+ name ,
612+ ) . toEqual ( expected ) ;
613+ }
614+ } ) ;
615+
616+ it ( "rejects malformed data, mismatched names and events after [DONE]" , ( ) => {
617+ expect ( ( ) => parseCohereSSE ( "event: message-start\ndata: {not json\n\n" ) ) . toThrow ( / n o t J S O N / ) ;
618+ expect ( ( ) => parseCohereSSE ( "event: content-end\ndata: [1]\n\n" ) ) . toThrow ( / n o t a n o b j e c t / ) ;
619+ expect ( ( ) => parseCohereSSE ( "event: content-end\ndata: null\n\n" ) ) . toThrow ( / n o t a n o b j e c t / ) ;
561620 expect ( ( ) => parseCohereSSE ( 'event: content-end\ndata: {"type":"content-start"}\n\n' ) ) . toThrow (
562621 / e v e n t n a m e / ,
563622 ) ;
564- expect ( ( ) => parseCohereSSE ( "event: content-end\ndata: [1]\n\n" ) ) . toThrow ( / n o t a n o b j e c t / ) ;
623+ // No event: line -> the spec names it "message", which never matches data.type.
624+ expect ( ( ) => parseCohereSSE ( 'data: {"type":"message-start"}\n\n' ) ) . toThrow ( / e v e n t n a m e / ) ;
625+ expect ( ( ) =>
626+ parseCohereSSE ( 'data: [DONE]\n\nevent: content-end\ndata: {"type":"content-end"}\n\n' ) ,
627+ ) . toThrow ( / a f t e r \[ D O N E \] / ) ;
565628 } ) ;
566629} ) ;
567630
0 commit comments