Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(sdk-js): keep raw path query values ahead of its fragment

Yudhi Armyndharisf8339d1e33c6
diff --git a/sdk/javascript/src/http.ts b/sdk/javascript/src/http.ts
index 4a7eafb75..7e046052e 100644
--- a/sdk/javascript/src/http.ts
+++ b/sdk/javascript/src/http.ts
@@ -67,16 +67,20 @@ export function encodeSegment(segment: string | number): string {
/** Build a URL with serialized query params, omitting `undefined`/`null` values. */
export function buildUrl(baseUrl: string, path: string, query?: object): string {
- const url = `${baseUrl.replace(/\/$/, '')}${path}`;
- if (!query) return url;
+ const base = baseUrl.replace(/\/$/, '');
+ if (!query) return `${base}${path}`;
const params = new URLSearchParams();
for (const [key, value] of Object.entries(query)) {
if (value === undefined || value === null) continue;
params.append(key, String(value));
}
const qs = params.toString();
- // A raw path may already carry a query string; extend it rather than start a second one.
- return qs ? `${url}${path.includes('?') ? '&' : '?'}${qs}` : url;
+ if (!qs) return `${base}${path}`;
+ // A raw path may already carry a query string; extend it rather than start a second one. The values go
+ // ahead of any fragment, since fetch drops everything after a '#' and the server would never see them.
+ const hash = path.indexOf('#');
+ const head = hash === -1 ? path : path.slice(0, hash);
+ return `${base}${head}${head.includes('?') ? '&' : '?'}${qs}${hash === -1 ? '' : path.slice(hash)}`;
}
/**
diff --git a/sdk/javascript/test/client.test.ts b/sdk/javascript/test/client.test.ts
index b9aa7827a..3307c1d00 100644
--- a/sdk/javascript/test/client.test.ts
+++ b/sdk/javascript/test/client.test.ts
@@ -161,6 +161,21 @@ describe('OpenWAClient', () => {
expect(t.lastCall!.url).toBe('http://localhost:2785/api/sessions?limit=5&name=x');
});
+ it('puts query params before the fragment of a raw path', async () => {
+ const cases: Array<[string, string]> = [
+ ['/api/sessions#tab', '/api/sessions?name=x#tab'],
+ ['/api/sessions?limit=5#tab', '/api/sessions?limit=5&name=x#tab'],
+ ['/api/sessions#tab?fake=1', '/api/sessions?name=x#tab?fake=1'],
+ ['/api/sessions#', '/api/sessions?name=x#'],
+ ];
+ for (const [path, expected] of cases) {
+ const t = new MockTransport().passthrough({ status: 200, body: [] });
+ await client(t).request({ method: 'GET', path, query: { name: 'x' } });
+ expect(t.lastCall!.url).toBe(`http://localhost:2785${expected}`);
+ expect(new URL(t.lastCall!.url).searchParams.get('name')).toBe('x');
+ }
+ });
+
it('maps a 404 to OpenWANotFoundError with parsed body', async () => {
const t = new MockTransport().on('GET', '/api/sessions/missing', {
status: 404,