Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(sdk-js): call an injected fetch without a receiver

Yudhi Armyndharisec2106e767dc
diff --git a/sdk/javascript/src/http.ts b/sdk/javascript/src/http.ts
index dfadabbc7..27e0f9c83 100644
--- a/sdk/javascript/src/http.ts
+++ b/sdk/javascript/src/http.ts
@@ -147,8 +147,11 @@ async function send<T>(
headers['Content-Type'] = 'application/json';
headers['X-API-Key'] = config.apiKey;
+ // Called without a receiver: a platform fetch passed in as `fetch: globalThis.fetch` throws
+ // "Illegal invocation" in browsers and Workers when invoked as a method of `config`.
+ const doFetch = config.fetch;
try {
- const res = await config.fetch(url, {
+ const res = await doFetch(url, {
method: options.method,
headers,
body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
diff --git a/sdk/javascript/test/client.test.ts b/sdk/javascript/test/client.test.ts
index 15f573f01..a87edf9cc 100644
--- a/sdk/javascript/test/client.test.ts
+++ b/sdk/javascript/test/client.test.ts
@@ -333,4 +333,17 @@ describe('OpenWAClient', () => {
vi.unstubAllGlobals();
}
});
+
+ it('calls an injected platform fetch without the client config as receiver', async () => {
+ // `fetch: window.fetch` or `fetch: globalThis.fetch` hands over the unbound platform function.
+ const receivers: unknown[] = [];
+ const strictFetch = function (this: unknown) {
+ receivers.push(this);
+ if (this !== undefined && this !== globalThis) throw new TypeError('Illegal invocation');
+ return Promise.resolve(new Response('[]', { status: 200 }));
+ } as unknown as FetchLike;
+ const c = new OpenWAClient({ baseUrl: 'http://localhost', apiKey: 'k', fetch: strictFetch });
+ await expect(c.sessions.list()).resolves.toEqual([]);
+ expect(receivers).toEqual([undefined]);
+ });
});