Skip to content

Commit

Permalink
Merge pull request #109 from chrisdickinson/chris/20241230-add-events…
Browse files Browse the repository at this point in the history
…ourceinit

feat(client/sse): add {EventSource,Request}Init options param
  • Loading branch information
jspahrsummers authored Jan 2, 2025
2 parents f7a47cd + d55f966 commit 4658fd0
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions src/client/sse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,17 @@ export class SSEClientTransport implements Transport {
private _endpoint?: URL;
private _abortController?: AbortController;
private _url: URL;
private _eventSourceInit?: EventSourceInit;
private _requestInit?: RequestInit;

onclose?: () => void;
onerror?: (error: Error) => void;
onmessage?: (message: JSONRPCMessage) => void;

constructor(url: URL) {
constructor(url: URL, opts?: { eventSourceInit?: EventSourceInit, requestInit?: RequestInit }) {
this._url = url;
this._eventSourceInit = opts?.eventSourceInit;
this._requestInit = opts?.requestInit;
}

start(): Promise<void> {
Expand All @@ -29,7 +33,7 @@ export class SSEClientTransport implements Transport {
}

return new Promise((resolve, reject) => {
this._eventSource = new EventSource(this._url.href);
this._eventSource = new EventSource(this._url.href, this._eventSourceInit);
this._abortController = new AbortController();

this._eventSource.onerror = (event) => {
Expand Down Expand Up @@ -90,14 +94,17 @@ export class SSEClientTransport implements Transport {
}

try {
const response = await fetch(this._endpoint, {
const headers = new Headers(this._requestInit?.headers);
headers.set("content-type", "application/json");
const init = {
...this._requestInit,
method: "POST",
headers: {
"Content-Type": "application/json",
},
headers,
body: JSON.stringify(message),
signal: this._abortController?.signal,
});
signal: this._abortController?.signal
};

const response = await fetch(this._endpoint, init);

if (!response.ok) {
const text = await response.text().catch(() => null);
Expand Down

0 comments on commit 4658fd0

Please sign in to comment.