@@ -17,6 +17,7 @@ import type {
1717 ServerRequest ,
1818 UpgradeWebSocketOptions ,
1919} from "./types.d.ts" ;
20+ import { assert } from "./util.ts" ;
2021
2122export interface ContextOptions <
2223 S extends AS = State ,
@@ -244,11 +245,25 @@ export class Context<
244245 * be sent to the client and be available in the client's `EventSource` that
245246 * initiated the connection.
246247 *
247- * This will set `.respond` to `false`. */
248+ * **Note** the body needs to be returned to the client to be able to
249+ * dispatch events, so dispatching events within the middleware will delay
250+ * sending the body back to the client.
251+ *
252+ * This will set the response body and update response headers to support
253+ * sending SSE events. Additional middleware should not modify the body.
254+ */
248255 sendEvents ( options ?: ServerSentEventTargetOptions ) : ServerSentEventTarget {
249256 if ( ! this . #sse) {
250- this . #sse = new ServerSentEventStreamTarget ( options ) ;
251- this . app . addEventListener ( "close" , ( ) => this . #sse?. close ( ) ) ;
257+ assert ( this . response . writable , "The response is not writable." ) ;
258+ const sse = this . #sse = new ServerSentEventStreamTarget ( options ) ;
259+ this . app . addEventListener ( "close" , ( ) => sse . close ( ) ) ;
260+ const [ bodyInit , { headers } ] = sse . asResponseInit ( {
261+ headers : this . response . headers ,
262+ } ) ;
263+ this . response . body = bodyInit ;
264+ if ( headers instanceof Headers ) {
265+ this . response . headers = headers ;
266+ }
252267 }
253268 return this . #sse;
254269 }
0 commit comments