### Install @microsoft/fetch-event-source Source: https://github.com/azure/fetch-event-source/blob/main/README.md Install the library using npm. ```sh npm install @microsoft/fetch-event-source ``` -------------------------------- ### SSE Comment Lines Example Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/server-sent-events-spec.md Demonstrates the use of comment lines, starting with ':', which are ignored by the client and can be used for keep-alive mechanisms. ```text : This is a comment : Server is alive data: Normal message ``` -------------------------------- ### Basic Server-Sent Events Example Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/TABLE_OF_CONTENTS.md A simple example demonstrating how to consume server-sent events from an API endpoint. It logs received messages to the console. ```typescript import { fetchEventSource } from '@microsoft/fetch-event-source'; await fetchEventSource('/api/sse', { onmessage(ev) { console.log(ev.data); } }); ``` -------------------------------- ### SSE Line Structure Examples Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/server-sent-events-spec.md Illustrates the basic line structures in an SSE stream: empty lines, comments, and field-value pairs. ```text field:value field: value (space after colon is optional) : this is a comment (empty line) ``` -------------------------------- ### Initial Client Request for SSE Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/server-sent-events-spec.md The client initiates a Server-Sent Events connection by sending a GET request with the 'Accept' header set to 'text/event-stream'. ```http GET /api/sse HTTP/1.1 Accept: text/event-stream ``` -------------------------------- ### FetchEventSource Usage Example Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/types.md Demonstrates how to use fetchEventSource with custom options for POST requests, including headers, body, and event handlers for opening, messages, and errors. ```typescript import { fetchEventSource, FetchEventSourceInit } from '@microsoft/fetch-event-source'; const options: FetchEventSourceInit = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'value' }), onopen(response) { if (!response.ok) throw new Error('Server error'); }, onmessage(ev) { console.log(ev.data); }, onerror(err) { console.error('Connection error:', err); return 5000; // retry after 5 seconds } }; await fetchEventSource('/api/sse', options); ``` -------------------------------- ### Complete Server-Sent Events Stream Example Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/server-sent-events-spec.md A comprehensive example of a Server-Sent Events stream, showcasing various message types, IDs, events, data payloads, and comments. ```text : Server started id: 0 event: connection data: Connected to event stream id: 1 event: update data: {"user": "alice", "action": "login"} id: 2 data: {"timestamp": "2024-01-15T10:30:00Z"} id: 3 event: error data: Something went wrong retry: 5000 id: 4 event: heartbeat data: : Another comment id: 5 data: Line 1 data: Line 2 data: Line 3 ``` -------------------------------- ### Basic Usage of fetchEventSource Source: https://github.com/azure/fetch-event-source/blob/main/README.md Replace the native EventSource with fetchEventSource for improved control. This example shows how to listen for messages. ```ts // BEFORE: const sse = new EventSource('/api/sse'); sse.onmessage = (ev) => { console.log(ev.data); }; // AFTER: import { fetchEventSource } from '@microsoft/fetch-event-source'; await fetchEventSource('/api/sse', { onmessage(ev) { console.log(ev.data); } }); ``` -------------------------------- ### Complete Export Example - TypeScript Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/module-exports.md Demonstrates importing all public exports from the library and using the fetchEventSource function. Also shows how to access the EventStreamContentType constant. ```typescript // Import all public exports import { fetchEventSource, // function FetchEventSourceInit, // type EventSourceMessage, // type EventStreamContentType // constant } from '@microsoft/fetch-event-source'; // Use the function const promise: Promise = fetchEventSource('/api/sse', { onmessage(ev: EventSourceMessage) { console.log(ev.data); } }); // Check content type const ct: string = EventStreamContentType; // 'text/event-stream' ``` -------------------------------- ### Tree Shaking Example with Import Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/module-exports.md Demonstrates how tree shaking works by importing only 'fetchEventSource'. Bundlers will remove unused exports like EventStreamContentType, FetchEventSourceInit, and EventSourceMessage if they are not referenced. ```typescript // Only fetchEventSource and its dependencies are bundled import { fetchEventSource } from '@microsoft/fetch-event-source'; // EventStreamContentType, FetchEventSourceInit, EventSourceMessage // are removed by the bundler if not used ``` -------------------------------- ### SSE Message Structure Example Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/server-sent-events-spec.md Demonstrates the structure of Server-Sent Events messages, where an empty line signifies the end of a message and triggers a callback. ```text id: 1 event: update data: Message data id: 2 event: notification data: Another message ``` -------------------------------- ### Install TextDecoder Polyfill for Old Browsers Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/architecture.md Use this require statement to install the TextDecoder polyfill for older browsers like IE and Edge. This allows `fetchEventSource` to function correctly in environments that do not natively support the TextDecoder API. ```typescript require('fast-text-encoding'); // TextDecoder polyfill ``` -------------------------------- ### SSE Event Field Example Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/server-sent-events-spec.md Demonstrates setting the 'event' field to identify the message type, along with 'data'. ```text event: notification data: Hello World ``` -------------------------------- ### SSE Field Parsing Rules Examples Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/server-sent-events-spec.md Illustrates the rules for parsing fields within Server-Sent Events, including handling of colons, spaces, and unknown fields. ```text data:hello ``` ```text data: hello ``` ```text data: hello ``` ```text data ``` ```text unknown:value ``` ```text :comment ``` -------------------------------- ### SSE Retry Field Example Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/server-sent-events-spec.md Shows how the 'retry' field sets the reconnection interval in milliseconds for the client. ```text retry: 10000 data: This message sets a 10-second retry interval ``` -------------------------------- ### Custom Fetch with Request Signing for SSE Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/examples.md Implement custom request signing for server-sent events by providing a custom `fetch` function to `fetchEventSource`. This example shows how to add timestamp and signature headers. ```typescript import { fetchEventSource } from '@microsoft/fetch-event-source'; async function signRequest(input, init) { const timestamp = Date.now().toString(); const signature = await generateSignature(input, timestamp); return fetch(input, { ...init, headers: { ...init?.headers, 'X-Timestamp': timestamp, 'X-Signature': signature } }); } await fetchEventSource('/api/sse', { fetch: signRequest, onmessage(ev) { console.log(ev.data); } }); ``` -------------------------------- ### onclose Callback Example Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/FetchEventSourceInit.md Implement the onclose callback for handling clean connection closures. This is useful for logging or initiating a retry by throwing an error, which will then be handled by the onerror callback. ```typescript onclose() { console.log('Connection closed'); throw new Error('Reconnect'); // forces a retry via onerror } ``` -------------------------------- ### onopen Callback Example Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/FetchEventSourceInit.md Implement the onopen callback to validate the HTTP response and read metadata before event stream parsing begins. Handle different status codes by throwing errors for fatal issues or retriable issues. ```typescript async onopen(response) { if (response.ok && response.status === 200) { console.log('Connected'); } else if (response.status === 401) { throw new Error('Unauthorized'); // fatal } else { throw new Error('Server error'); // retriable } } ``` -------------------------------- ### Fetch EventSource with Advanced Error Handling Source: https://github.com/azure/fetch-event-source/blob/main/README.md Implement robust error handling for Server-Sent Events. This example defines custom error types for retriable and fatal errors, and configures callbacks for opening the connection, receiving messages, closing the connection, and handling errors. ```ts class RetriableError extends Error { } class FatalError extends Error { } fetchEventSource('/api/sse', { async onopen(response) { if (response.ok && response.headers.get('content-type') === EventStreamContentType) { return; // everything's good } else if (response.status >= 400 && response.status < 500 && response.status !== 429) { // client-side errors are usually non-retriable: throw new FatalError(); } else { throw new RetriableError(); } }, onmessage(msg) { // if the server emits an error message, throw an exception // so it gets handled by the onerror callback below: if (msg.event === 'FatalError') { throw new FatalError(msg.data); } }, onclose() { // if the server closes the connection unexpectedly, retry: throw new RetriableError(); }, onerror(err) { if (err instanceof FatalError) { throw err; // rethrow to stop the operation } else { // do nothing to automatically retry. You can also // return a specific retry interval here. } } }); ``` -------------------------------- ### SSE ID Field Example Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/server-sent-events-spec.md Illustrates using the 'id' field to set the message ID and the client's last event ID for reconnection. ```text id: 1 data: First message id: 2 data: Second message ``` -------------------------------- ### SSE Data Field Examples Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/server-sent-events-spec.md Shows how the 'data' field is used to append and concatenate message content. Multiple 'data' lines are joined by newline characters. ```text data: This is the data line data: Line 1 data: Line 2 data: Line 3 ``` -------------------------------- ### onerror Callback Example Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/FetchEventSourceInit.md Configure the onerror callback to manage error handling and retry logic. Return a number to specify a retry delay in milliseconds, return undefined for the default delay, or throw an error to stop retrying permanently. ```typescript onerror(err) { if (err instanceof TypeError) { // Network error, retriable return 5000; // retry after 5 seconds } else if (err.message.includes('401')) { // Authentication error, fatal throw err; } // Default: retry after 1000ms } ``` -------------------------------- ### onmessage Callback Example Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/FetchEventSourceInit.md Use the onmessage callback to process each incoming event after it has been fully parsed. This callback is invoked for all events, including those with custom event types. Errors thrown here are caught and passed to the onerror handler. ```typescript onmessage(ev) { if (ev.event === 'error') { throw new Error(ev.data); } console.log(`${ev.event}: ${ev.data}`); } ``` -------------------------------- ### Clone and Set Up Repository Source: https://github.com/azure/fetch-event-source/blob/main/CONTRIBUTING.md Clone your fork of the repository and set up the upstream remote for the original project. ```bash git clone https://github.com//fetch-event-source.git cd fetch-event-source git remote add upstream https://github.com/Azure/fetch-event-source.git ``` -------------------------------- ### Basic Usage Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/fetchEventSource.md Demonstrates the simplest way to use fetchEventSource to connect to an SSE endpoint and handle incoming messages. ```APIDOC ## Basic Usage Connects to an SSE endpoint and logs received messages. ### Method fetchEventSource ### Endpoint /api/sse ### Parameters #### Query Parameters - **onmessage** (function) - Required - Callback function to handle incoming messages. ### Request Example ```typescript import { fetchEventSource } from '@microsoft/fetch-event-source'; await fetchEventSource('/api/sse', { onmessage(ev) { console.log('Received:', ev.data); } }); ``` ``` -------------------------------- ### Parsed EventSourceMessage Objects Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/server-sent-events-spec.md Represents the parsed `EventSourceMessage` objects resulting from the complete SSE stream example, showing how data and metadata are structured. ```typescript EventSourceMessage { id: '0', event: 'connection', data: 'Connected to event stream', retry: undefined } EventSourceMessage { id: '1', event: 'update', data: '{"user": "alice", "action": "login"}', retry: undefined } EventSourceMessage { id: '2', event: '', data: '{"timestamp": "2024-01-15T10:30:00Z"}', retry: undefined } EventSourceMessage { id: '3', event: 'error', data: 'Something went wrong', retry: 5000 } EventSourceMessage { id: '4', event: 'heartbeat', data: '', retry: undefined } EventSourceMessage { id: '5', event: '', data: 'Line 1\nLine 2\nLine 3', retry: undefined } ``` -------------------------------- ### Checkout Main and Pull Source: https://github.com/azure/fetch-event-source/blob/main/CONTRIBUTING.md Ensure your local main branch is up-to-date by checking it out and pulling changes from the origin. ```bash git checkout main && git pull origin main ``` -------------------------------- ### Complete FetchEventSource Configuration Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/FetchEventSourceInit.md Demonstrates a comprehensive configuration for fetchEventSource, including Fetch API options, event stream handlers, and connection control. Use this to set up a robust server-sent event connection. ```typescript import { fetchEventSource, FetchEventSourceInit } from '@microsoft/fetch-event-source'; const config: FetchEventSourceInit = { // Fetch API options method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer token' }, body: JSON.stringify({ userId: 42 }), credentials: 'include', signal: abortController.signal, // Event stream options async onopen(response) { if (!response.ok) throw new Error('Server error'); }, onmessage(ev) { console.log(`${ev.event}: ${ev.data}`); }, onclose() { console.log('Connection closed'); }, onerror(err) { console.error('Error:', err); return 3000; // retry in 3 seconds }, // Connection control openWhenHidden: false, // Custom fetch fetch: customFetchImplementation }; await fetchEventSource('/api/sse', config); ``` -------------------------------- ### FetchEventSourceInit Configuration Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/FetchEventSourceInit.md The FetchEventSourceInit type allows for detailed configuration of the Server-Sent Events connection. It accepts standard Fetch API options such as method, headers, body, credentials, and signal, alongside specific callbacks for managing the event stream lifecycle: onopen, onmessage, onclose, and onerror. It also provides options for connection control like openWhenHidden and allows for a custom fetch implementation. ```APIDOC ## FetchEventSourceInit Configuration Options This object is used to configure the `fetchEventSource` function. ### Fetch API Options These are standard Fetch API options that can be passed directly. - **method** (string) - The HTTP method to use (e.g., 'GET', 'POST'). - **headers** (Headers | Record) - Request headers. - **body** (string | FormData | Blob | URLSearchParams | null) - Request body. - **credentials** ('include' | 'same-origin' | 'omit') - Controls whether cookies are sent with the request. - **signal** (AbortSignal) - An AbortSignal to cancel the request. ### Event Stream Options Callbacks to handle different stages of the event stream. - **onopen** (function(response: Response): Promise | void) - Called when the connection is opened. Receives the Fetch API Response object. Should throw an error if the response is not OK. - **onmessage** (function(event: EventSourceMessage): void) - Called for each message received from the server. Receives an EventSourceMessage object containing `event`, `data`, and `id`. - **onclose** (function(): void) - Called when the connection is closed. - **onerror** (function(err: any): number | void) - Called when an error occurs. Can return a number representing the retry delay in milliseconds. ### Connection Control - **openWhenHidden** (boolean) - If true, the connection will remain open even when the page is hidden. Defaults to `false`. ### Custom Fetch - **fetch** (function(input: RequestInfo | URL, init?: RequestInit): Promise) - A custom implementation of the Fetch API to use for establishing the connection. ``` -------------------------------- ### Validate Event Stream Content Type Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/constants.md Example of how to use EventStreamContentType to validate the content type of a server-sent event stream response in an onopen handler. ```typescript import { fetchEventSource, EventStreamContentType } from '@microsoft/fetch-event-source'; await fetchEventSource('/api/sse', { async onopen(response) { const contentType = response.headers.get('content-type'); if (contentType?.startsWith(EventStreamContentType)) { // Valid event stream return; } else { throw new Error(`Expected ${EventStreamContentType}, got ${contentType}`); } }, onmessage(ev) { console.log(ev.data); } }); ``` -------------------------------- ### Fetch Event Source Visibility Control Phase Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/architecture.md Explains the visibility control phase, managing connection behavior based on document visibility changes to abort or resume requests. ```mermaid document visibility changes ↓ visibilitychange event ↓ ┌──────────────────────┬──────────────────────┐ │ │ │ [hidden: true] [hidden: false] │ │ Abort current Resume with last request event ID │ │ Close connection create() again └──────────────────────┴──────────────────────┘ ``` -------------------------------- ### Using a Custom Fetch Implementation Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/fetchEventSource.md Shows how to provide a custom fetch function to fetchEventSource, allowing for additional logic such as request signing or logging before the actual fetch call is made. ```typescript const customFetch = async (input, init) => { // Add custom logic, e.g., request signing, logging return fetch(input, init); }; await fetchEventSource('/api/sse', { fetch: customFetch, onmessage(ev) { console.log(ev.data); } }); ``` -------------------------------- ### Importing Core Components Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/README.md Import the main function, configuration interface, message type, and constants from the package. ```typescript import { fetchEventSource, FetchEventSourceInit, EventSourceMessage, EventStreamContentType } from '@microsoft/fetch-event-source'; ``` -------------------------------- ### SSE Comment Keep-Alive Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/server-sent-events-spec.md Servers can send comments (lines starting with ':') to keep the connection alive without triggering client-side callbacks. These are typically sent at regular intervals. ```sse : Server is alive : Another keep-alive comment every 15 seconds ``` -------------------------------- ### Custom Fetch Implementation Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/fetchEventSource.md Explains how to provide a custom `fetch` implementation to `fetchEventSource` for advanced use cases like request modification or logging. ```APIDOC ## Custom Fetch Implementation Allows providing a custom `fetch` function to `fetchEventSource` for advanced control over the request. ### Method fetchEventSource ### Endpoint /api/sse ### Parameters #### Query Parameters - **fetch** (function) - Optional - A custom function that mimics the browser's `fetch` API. - **onmessage** (function) - Required - Callback function to handle incoming messages. ### Request Example ```typescript const customFetch = async (input, init) => { // Add custom logic, e.g., request signing, logging return fetch(input, init); }; await fetchEventSource('/api/sse', { fetch: customFetch, onmessage(ev) { console.log(ev.data); } }); ``` ``` -------------------------------- ### Basic Message Handling with fetchEventSource Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/EventSourceMessage.md Demonstrates the fundamental usage of fetchEventSource to connect to an SSE endpoint and process incoming messages. It logs the ID, event type, and data of each message received. ```typescript import { fetchEventSource } from '@microsoft/fetch-event-source'; await fetchEventSource('/api/sse', { onmessage(ev) { console.log('ID:', ev.id); console.log('Event:', ev.event); console.log('Data:', ev.data); if (ev.retry) { console.log('Server retry interval:', ev.retry, 'ms'); } } }); ``` -------------------------------- ### Basic fetchEventSource Usage Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/fetchEventSource.md Demonstrates the most basic usage of fetchEventSource to connect to an SSE endpoint and log incoming messages. ```typescript import { fetchEventSource } from '@microsoft/fetch-event-source'; await fetchEventSource('/api/sse', { onmessage(ev) { console.log('Received:', ev.data); } }); ``` -------------------------------- ### Fetch Event Source Initialization Options Interface Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/README.md Defines the configuration options for `fetchEventSource`, extending standard RequestInit with event stream specific callbacks and settings. ```typescript interface FetchEventSourceInit extends RequestInit { headers?: Record; onopen?: (response: Response) => Promise; onmessage?: (ev: EventSourceMessage) => void; onclose?: () => void; onerror?: (err: any) => number | void; openWhenHidden?: boolean; fetch?: typeof fetch; } ``` -------------------------------- ### Fetch Event Source Request Phase Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/architecture.md Illustrates the initial request phase of the fetchEventSource function, including AbortController creation and the fetch call. ```mermaid fetchEventSource(url, options) ↓ Create AbortController ↓ Setup visibility listener (if openWhenHidden: false) ↓ fetch(url, { method, headers, body, signal, ...rest }) ↓ Response received ↓ onopen(response) validation ↓ [if validation fails → caught by onerror] ``` -------------------------------- ### Fetch EventSource with POST and Body Source: https://github.com/azure/fetch-event-source/blob/main/README.md Demonstrates how to use fetchEventSource with custom HTTP methods, headers, and a request body, similar to the standard fetch API. An AbortController is used to cancel the request. ```ts const ctrl = new AbortController(); fetchEventSource('/api/sse', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ foo: 'bar' }), signal: ctrl.signal, }); ``` -------------------------------- ### Package.json Export Resolution Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/module-exports.md Defines the main, module, and types entry points for package distribution. ```json { "main": "lib/cjs/index.js", "module": "lib/esm/index.js", "types": "lib/cjs/index.d.ts" } ``` -------------------------------- ### POST Request with Custom Headers and Body Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/fetchEventSource.md Shows how to make a POST request with custom headers and a request body, useful for authenticated or data-rich SSE connections. ```APIDOC ## POST Request with Custom Headers and Body Makes a POST request to an SSE endpoint with custom headers and a JSON body. ### Method fetchEventSource ### Endpoint /api/sse ### Parameters #### Query Parameters - **method** (string) - Optional - Defaults to 'GET'. Set to 'POST' for POST requests. - **headers** (object) - Optional - Custom headers to send with the request. - **body** (string) - Optional - The request body, typically JSON stringified. - **onmessage** (function) - Required - Callback function to handle incoming messages. ### Request Example ```typescript await fetchEventSource('/api/sse', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer token' }, body: JSON.stringify({ userId: 123 }), onmessage(ev) { console.log(ev.data); } }); ``` ``` -------------------------------- ### Publish Prerelease Version Source: https://github.com/azure/fetch-event-source/blob/main/CONTRIBUTING.md Publish a prerelease version of the package using npm, tagged for prerelease. ```bash npm publish . --tag prerelease ``` -------------------------------- ### Import Pattern 4: CommonJS Require - JavaScript Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/module-exports.md Demonstrates how to import specific exports using the CommonJS `require` syntax, suitable for Node.js environments. ```javascript const { fetchEventSource, EventStreamContentType } = require('@microsoft/fetch-event-source'); fetchEventSource('/api/sse', { onmessage(ev) { console.log(ev.data); } }); ``` -------------------------------- ### POST Request with Custom Headers and Body Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/fetchEventSource.md Shows how to make a POST request using fetchEventSource, including setting custom headers and sending a JSON body. ```typescript await fetchEventSource('/api/sse', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer token' }, body: JSON.stringify({ userId: 123 }), onmessage(ev) { console.log(ev.data); } }); ``` -------------------------------- ### Response Validation with onopen Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/fetchEventSource.md Illustrates how to use the `onopen` callback to perform custom validation on the server's response before accepting the connection. ```APIDOC ## With Response Validation Validates the server's response in the `onopen` callback, handling retriable and fatal errors. ### Method fetchEventSource ### Endpoint /api/sse ### Parameters #### Query Parameters - **onopen** (function) - Optional - Callback function executed when the connection is opened. Can be used for response validation. - **onmessage** (function) - Required - Callback function to handle incoming messages. ### Request Example ```typescript await fetchEventSource('/api/sse', { async onopen(response) { if (response.ok) { return; // validation passed } else if (response.status >= 400 && response.status < 500 && response.status !== 429) { throw new Error(`Client error: ${response.status}`); // fatal } else { throw new Error('Server error, will retry'); // retriable } }, onmessage(ev) { console.log(ev.data); } }); ``` ``` -------------------------------- ### Cancellation with AbortController Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/fetchEventSource.md Demonstrates how to cancel an ongoing SSE request using an `AbortController`. ```APIDOC ## Cancellation with AbortController Cancels an ongoing Server-Sent Events request using an `AbortController`. ### Method fetchEventSource ### Endpoint /api/sse ### Parameters #### Query Parameters - **signal** (AbortSignal) - Optional - An `AbortSignal` to control the request's lifecycle. - **onmessage** (function) - Required - Callback function to handle incoming messages. ### Request Example ```typescript const ctrl = new AbortController(); const promise = fetchEventSource('/api/sse', { signal: ctrl.signal, onmessage(ev) { console.log(ev.data); } }); // Cancel the request ctrl.abort(); ``` ``` -------------------------------- ### fetch Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/FetchEventSourceInit.md Allows specifying a custom Fetch API implementation to use instead of the global `window.fetch`. This is useful for request/response interception, custom network implementations, mocking in tests, or adding request signing/auth headers. The provided function must match the Fetch API signature. ```APIDOC ## fetch ### Description A custom Fetch API implementation to use instead of the global `window.fetch`. Enables: - Request/response interception - Custom network implementations - Mocking in tests - Request signing or auth headers ### Default `window.fetch` ### Type Must match the Fetch API signature `(input: RequestInfo, init?: RequestInit) => Promise` ### Example ```typescript const signedFetch = async (input, init) => { // Add signed headers const headers = { ...init?.headers, 'X-Signature': generateSignature() }; return fetch(input, { ...init, headers }); }; await fetchEventSource('/api/sse', { fetch: signedFetch, onmessage(ev) { console.log(ev.data); } }); ``` ``` -------------------------------- ### Handle Multi-Line Data in SSE Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/examples.md Demonstrates how to handle SSE messages that contain multi-line data by splitting the `ev.data` string by newline characters. ```typescript import { fetchEventSource } from '@microsoft/fetch-event-source'; await fetchEventSource('/api/sse', { onmessage(ev) { // Server sent multi-line data: // data: Line 1 // data: Line 2 // data: Line 3 // (empty line) const lines = ev.data.split('\n'); console.log(`Received ${lines.length} lines:`, lines); // Or parse as JSON with newlines const jsonData = lines.map(line => JSON.parse(line)); } }); ``` -------------------------------- ### FetchEventSourceInit Configuration Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/architecture.md Defines the `FetchEventSourceInit` type, which extends `RequestInit` from the Fetch API and adds event handlers and specific options for event sourcing. ```typescript RequestInit ├── method ├── headers ├── body ├── credentials ├── cache ├── mode ├── redirect ├── referrer ├── referrerPolicy ├── integrity └── signal + FetchEventSourceInit-specific ├── onopen ├── onmessage ├── onclose ├── onerror ├── openWhenHidden └── fetch = FetchEventSourceInit (complete config) ``` -------------------------------- ### headers Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/FetchEventSourceInit.md Defines request headers as a plain object (`Record`). Unlike standard `RequestInit`, this option does not support Header objects. The `Accept` header is automatically set to `text/event-stream` if not explicitly provided. ```APIDOC ## headers ### Description Request headers as a plain object. **Note**: Unlike standard `RequestInit`, `FetchEventSourceInit` requires headers to be in `Record` format; Header objects are not supported. ### Default `{ accept: 'text/event-stream' }` The `accept` header is automatically set to `text/event-stream` if not provided. ### Example ```typescript await fetchEventSource('/api/sse', { headers: { 'Authorization': 'Bearer token123', 'X-Custom-Header': 'value', 'Accept': 'text/event-stream; charset=utf-8' }, onmessage(ev) { console.log(ev.data); } }); ``` ``` -------------------------------- ### Create a New Topic Branch Source: https://github.com/azure/fetch-event-source/blob/main/CONTRIBUTING.md Create a new branch for your feature, change, or fix, branching off the main development branch. ```bash git checkout -b ``` -------------------------------- ### FetchEventSourceInit Type Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/TABLE_OF_CONTENTS.md Configuration interface for fetchEventSource, allowing customization of request headers, event handlers, and other options. ```APIDOC ## FetchEventSourceInit ### Description An interface that defines the configuration options for the `fetchEventSource` function. It allows for customization of the underlying Fetch API request and the handling of incoming events. ### Fields - **method**: `HttpMethod` (Optional) - The HTTP method to use (e.g., 'GET', 'POST'). Defaults to 'GET'. - **headers**: `HeadersInit` (Optional) - Headers to send with the request. - **body**: `BodyInit` (Optional) - The request body. - **signal**: `AbortSignal` (Optional) - An AbortSignal to cancel the request. - **open**: `() => void` (Optional) - Callback function executed when the connection is opened. - **event**: `(event: string) => void` (Optional) - Callback function executed when a generic event is received. - **message**: `(event: string, data: EventSourceMessage) => void` (Optional) - Callback function executed for each message event. - **error**: `(error: any) => void` (Optional) - Callback function executed when an error occurs. - **close**: `() => void` (Optional) - Callback function executed when the connection is closed. ``` -------------------------------- ### Server SSE Response Headers Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/server-sent-events-spec.md The server should respond with 'Content-Type: text/event-stream', 'Cache-Control: no-cache', and 'Connection: keep-alive' to establish and maintain the SSE connection. ```http HTTP/1.1 200 OK Content-Type: text/event-stream Cache-Control: no-cache Connection: keep-alive ``` -------------------------------- ### CommonJS Build Import Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/module-exports.md Import statement for Node.js and CommonJS bundlers. ```javascript const { fetchEventSource, EventStreamContentType } = require('@microsoft/fetch-event-source'); ``` -------------------------------- ### Use Server-Side Recommended Retry Intervals Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/examples.md Allows the server to specify the retry interval for failed connections via the `retry` field in SSE messages. The client respects this recommendation. ```typescript let recommendedRetry = 1000; await fetchEventSource('/api/sse', { onmessage(ev) { // Server can recommend retry timing if (ev.retry) { recommendedRetry = ev.retry; console.log(`Server recommends retry interval: ${ev.retry}ms`); } console.log(ev.data); }, onerror(err) { console.log(`Retrying in ${recommendedRetry}ms`); return recommendedRetry; } }); ``` -------------------------------- ### Update Local Repository Source: https://github.com/azure/fetch-event-source/blob/main/CONTRIBUTING.md Fetch the latest changes from the upstream repository to your local main branch. ```bash git checkout main git pull upstream main ``` -------------------------------- ### Fetch Event Source Error Handling and Retry Phase Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/architecture.md Outlines the error handling and retry mechanism, including how errors are caught, processed, and trigger retries or promise resolution. ```mermaid Error occurs (network, parsing, callback exception) ↓ [if input signal aborted → resolve promise] ↓ onerror(err) callback ↓ ┌─────────────────────────┬────────────────┐ │ │ │ [throw] [return number] [return undefined] │ │ │ resolve(promise) retry after X ms retry after 1000ms ↓ setTimeout(create) ↓ [go back to Request Phase] ``` -------------------------------- ### Inherited RequestInit Properties Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/FetchEventSourceInit.md FetchEventSourceInit inherits properties from the standard Fetch API's RequestInit interface, allowing for detailed customization of the underlying HTTP request. ```APIDOC ## Inherited RequestInit Properties The interface extends `RequestInit`, providing access to standard Fetch API options: | Property | Type | Description | |----------|------|-------------| | method | `string` | HTTP method (GET, POST, PUT, DELETE, etc.) | | headers | `HeadersInit` | Request headers (overridden by `FetchEventSourceInit` to require `Record`) | | body | `BodyInit` | Request body (string, FormData, URLSearchParams, ReadableStream, etc.) | | credentials | `RequestCredentials` | Credential mode: 'omit', 'same-origin', 'include' | | cache | `RequestCache` | Cache behavior: 'default', 'no-store', 'reload', 'no-cache', 'force-cache', 'only-if-cached' | | mode | `RequestMode` | CORS mode: 'cors', 'no-cors', 'same-origin', 'navigate' | | redirect | `RequestRedirect` | Redirect behavior: 'follow', 'error', 'manual' | | referrer | `string` | Referer header | | referrerPolicy | `ReferrerPolicy` | Referer policy | | integrity | `string` | Subresource integrity hash | | signal | `AbortSignal` | AbortController signal for cancellation | ``` -------------------------------- ### onopen Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/FetchEventSourceInit.md Callback invoked when the HTTP response is received, before event stream parsing begins. Useful for response validation or metadata reading. Errors thrown here can be fatal or retriable. ```APIDOC ## onopen ### Description Invoked when the HTTP response is received, before event stream parsing begins. Use this to validate the response or read response metadata. **Default behavior** (if not provided): - Checks that `Content-Type` header starts with `text/event-stream` - Throws an error if validation fails **Behavior on error**: - Throw any error to treat it as a fatal error and reject the promise - Throw a retriable error to retry according to `onerror` logic - Return normally to proceed with event parsing ### Signature ```typescript onopen?: (response: Response) => Promise ``` ### Example ```typescript async onopen(response) { if (response.ok && response.status === 200) { console.log('Connected'); } else if (response.status === 401) { throw new Error('Unauthorized'); // fatal } else { throw new Error('Server error'); // retriable } } ``` ``` -------------------------------- ### Push Topic Branch Source: https://github.com/azure/fetch-event-source/blob/main/CONTRIBUTING.md Push your local topic branch to your forked repository on GitHub. ```bash git push origin ``` -------------------------------- ### ES Module Build Import Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/module-exports.md Import statement for modern bundlers and browser environments. ```typescript import { fetchEventSource, EventStreamContentType } from '@microsoft/fetch-event-source'; ``` -------------------------------- ### Custom Fetch Implementation Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/FetchEventSourceInit.md Provide a custom fetch function to intercept requests, implement custom network logic, or mock network behavior for testing. The custom function must adhere to the standard Fetch API signature. ```typescript const signedFetch = async (input, init) => { // Add signed headers const headers = { ...init?.headers, 'X-Signature': generateSignature() }; return fetch(input, { ...init, headers }); }; await fetchEventSource('/api/sse', { fetch: signedFetch, onmessage(ev) { console.log(ev.data); } }); ``` -------------------------------- ### TypeScript Configuration Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/module-exports.md Configuration options for the TypeScript compiler, enabling strict mode and declaration generation. ```json { "compilerOptions": { "strict": true, "declaration": true, "target": "ES2017", "skipLibCheck": true } } ``` -------------------------------- ### Custom Error Handling and Retry Logic Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/fetchEventSource.md Details how to implement custom error handling and retry strategies using the `onerror` and `onclose` callbacks. ```APIDOC ## With Error Handling and Custom Retry Logic Implements custom error handling and retry logic using `onerror` and `onclose` callbacks. ### Method fetchEventSource ### Endpoint /api/sse ### Parameters #### Query Parameters - **onmessage** (function) - Required - Callback function to handle incoming messages. Can throw custom errors. - **onclose** (function) - Optional - Callback function executed when the connection is closed. Can be used to signal errors. - **onerror** (function) - Optional - Callback function to handle errors. Can return a number (milliseconds) to specify retry delay, or throw an error to stop. ### Request Example ```typescript class FatalError extends Error {} await fetchEventSource('/api/sse', { onmessage(ev) { if (ev.event === 'error') { throw new FatalError(ev.data); } console.log(ev.data); }, onclose() { throw new Error('Connection closed unexpectedly'); }, onerror(err) { if (err instanceof FatalError) { throw err; // stop permanently } console.error('Error, retrying in 2 seconds:', err); return 2000; // retry after 2 seconds } }); ``` ``` -------------------------------- ### SSE Consumption with Query Parameters Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/examples.md Consumes Server-Sent Events from an endpoint with specified query parameters for filtering. ```typescript const params = new URLSearchParams({ userId: '42', filter: 'active' }); await fetchEventSource(`/api/sse?${params}`, { onmessage(ev) { console.log(ev.data); } }); ``` -------------------------------- ### Validate Server Response with Early Abort Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/architecture.md Use `onopen` to check the initial server response. Throw an error to abort the connection if the response is not OK. ```typescript fetchEventSource(url, { async onopen(response) { if (!response.ok) { throw new Error('Server error'); } }, onerror(err) { throw err; // Stop } }); ``` -------------------------------- ### SSE Consumption with Custom Headers and Authentication Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/examples.md Consumes Server-Sent Events with custom headers, including an Authorization token retrieved from local storage. ```typescript const token = localStorage.getItem('auth-token'); await fetchEventSource('/api/sse', { headers: { 'Authorization': `Bearer ${token}`, 'X-Request-ID': crypto.randomUUID() }, onmessage(ev) { console.log(ev.data); } }); ``` -------------------------------- ### Custom Error Handling and Retry Logic Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/fetchEventSource.md Demonstrates advanced error handling by defining custom error types and controlling retry behavior. It shows how to stop retries for fatal errors and specify a custom retry interval for others. ```typescript class FatalError extends Error {} await fetchEventSource('/api/sse', { onmessage(ev) { if (ev.event === 'error') { throw new FatalError(ev.data); } console.log(ev.data); }, onclose() { throw new Error('Connection closed unexpectedly'); }, onerror(err) { if (err instanceof FatalError) { throw err; // stop permanently } console.error('Error, retrying in 2 seconds:', err); return 2000; // retry after 2 seconds } }); ``` -------------------------------- ### SSE Consumption with POST Request and JSON Body Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/examples.md Sends a POST request with a JSON body to an SSE endpoint and logs received messages. ```typescript const userId = 123; await fetchEventSource('/api/sse', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'text/event-stream' }, body: JSON.stringify({ userId }), onmessage(ev) { console.log('Event:', ev.data); } }); ``` -------------------------------- ### Response Validation with Custom onopen Logic Source: https://github.com/azure/fetch-event-source/blob/main/_autodocs/api-reference/fetchEventSource.md Illustrates how to implement custom validation logic within the `onopen` callback to handle different response statuses, distinguishing between retriable and fatal errors. ```typescript await fetchEventSource('/api/sse', { async onopen(response) { if (response.ok) { return; // validation passed } else if (response.status >= 400 && response.status < 500 && response.status !== 429) { throw new Error(`Client error: ${response.status}`); // fatal } else { throw new Error('Server error, will retry'); // retriable } }, onmessage(ev) { console.log(ev.data); } }); ```