Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(sdk-js): call the default fetch with the global receiver

Yudhi Armyndharis5c31999f7f6a
diff --git a/sdk/javascript/src/client.ts b/sdk/javascript/src/client.ts
index 6655555bc..5d5ddc698 100644
--- a/sdk/javascript/src/client.ts
+++ b/sdk/javascript/src/client.ts
@@ -67,7 +67,9 @@ export class OpenWAClient {
apiKey: options.apiKey,
timeoutMs: options.timeoutMs ?? 30000,
defaultHeaders: options.defaultHeaders ?? {},
- fetch: options.fetch ?? globalThis.fetch,
+ // Wrapped, not stored bare: `config.fetch(...)` would call it with `config` as `this`, which
+ // browsers and Workers reject with "Illegal invocation".
+ fetch: options.fetch ?? ((input, init) => globalThis.fetch(input, init)),
};
warnIfInsecureHttpUrl(options.baseUrl);
diff --git a/sdk/javascript/test/client.test.ts b/sdk/javascript/test/client.test.ts
index da2c2ffc5..c5e6b2fb7 100644
--- a/sdk/javascript/test/client.test.ts
+++ b/sdk/javascript/test/client.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import {
OpenWAClient,
OpenWAApiError,
@@ -267,4 +267,18 @@ describe('OpenWAClient', () => {
expect(t.lastCall!.headers['content-type']).toBe('application/json');
expect(t.lastCall!.headers['x-trace']).toBe('keep');
});
+
+ it('calls the global fetch unbound from the client config when none is injected', async () => {
+ // Browsers and Workers reject a fetch invoked as a method of another object ("Illegal invocation").
+ vi.stubGlobal('fetch', function (this: unknown) {
+ if (this !== undefined && this !== globalThis) throw new TypeError('Illegal invocation');
+ return Promise.resolve(new Response('[]', { status: 200 }));
+ });
+ try {
+ const c = new OpenWAClient({ baseUrl: 'http://localhost', apiKey: 'k' });
+ await expect(c.sessions.list()).resolves.toEqual([]);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
});