@panomc/client 0.0.0-stage → 1.0.0-dev.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,348 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import { createClient, unwrap, PanoApiError } from './index.js'
3
+
4
+ const json = (status, body, headers = {}) =>
5
+ new Response(body === undefined ? null : JSON.stringify(body), {
6
+ status,
7
+ headers: { 'content-type': 'application/json', ...headers }
8
+ })
9
+
10
+ /** fake fetch: handlers queue per "METHOD path", falls back to 200 {} ; records every call */
11
+ function fakeFetch(routes = {}) {
12
+ const calls = []
13
+ const fn = async (url, init = {}) => {
14
+ const u = new URL(url, 'http://pano.test')
15
+ const key = `${init.method || 'GET'} ${u.pathname}`
16
+ calls.push({ key, url: String(url), method: init.method || 'GET', headers: { ...init.headers }, body: init.body, init })
17
+ const handler = routes[key]
18
+ const next = Array.isArray(handler) ? handler.shift() : handler
19
+ if (next instanceof Error) throw next
20
+ if (typeof next === 'function') return next(init)
21
+ return next ?? json(200, {})
22
+ }
23
+ fn.calls = calls
24
+ fn.count = (key) => calls.filter((c) => c.key === key).length
25
+ return fn
26
+ }
27
+
28
+ const base = 'http://pano.test'
29
+ const POST = { method: 'POST', path: '/api/v1/things' }
30
+
31
+ describe('request building', () => {
32
+ test('url, query, path params, accept and locale', async () => {
33
+ const f = fakeFetch({ 'GET /api/v1/posts/a%20b': json(200, { items: [] }) })
34
+ const c = createClient({ baseUrl: base + '/', fetch: f, locale: 'tr', csrf: 'off' })
35
+ const r = await c.request(
36
+ { method: 'GET', path: '/api/v1/posts/{slug}' },
37
+ { path: { slug: 'a b' }, query: { page: 2, tag: ['x', 'y'], skip: undefined, none: null } }
38
+ )
39
+ expect(r).toEqual({ ok: true, status: 200, data: { items: [] } })
40
+ expect(f.calls[0].url).toBe(`${base}/api/v1/posts/a%20b?page=2&tag=x&tag=y`)
41
+ expect(f.calls[0].headers.Accept).toBe('application/json')
42
+ expect(f.calls[0].headers['Accept-Language']).toBe('tr')
43
+ })
44
+
45
+ test('proxy prefix as baseUrl', async () => {
46
+ const f = fakeFetch()
47
+ await createClient({ baseUrl: '/pano', fetch: f, csrf: 'off' }).request({ method: 'GET', path: '/api/v1/posts' })
48
+ expect(f.calls[0].url).toBe('/pano/api/v1/posts')
49
+ })
50
+
51
+ test('json body gets content-type, FormData passes through', async () => {
52
+ const f = fakeFetch()
53
+ const c = createClient({ baseUrl: base, fetch: f, csrf: 'off' })
54
+ await c.request(POST, { body: { a: 1 } })
55
+ expect(f.calls[0].body).toBe('{"a":1}')
56
+ expect(f.calls[0].headers['Content-Type']).toBe('application/json')
57
+
58
+ const form = new FormData()
59
+ form.append('f', 'v')
60
+ await c.request(POST, { body: form })
61
+ expect(f.calls[1].body).toBe(form)
62
+ expect(f.calls[1].headers['Content-Type']).toBeUndefined()
63
+ })
64
+
65
+ test('credentials default omit outside a browser, option wins, signal and headers pass', async () => {
66
+ const f = fakeFetch()
67
+ const ctl = new AbortController()
68
+ await createClient({ baseUrl: base, fetch: f }).request(
69
+ { method: 'GET', path: '/api/v1/x' },
70
+ { signal: ctl.signal, headers: { 'X-Extra': '1' } }
71
+ )
72
+ expect(f.calls[0].init.credentials).toBe('omit')
73
+ expect(f.calls[0].init.signal).toBe(ctl.signal)
74
+ expect(f.calls[0].headers['X-Extra']).toBe('1')
75
+ await createClient({ baseUrl: base, fetch: f, credentials: 'include', csrf: 'off' }).request({ method: 'GET', path: '/api/v1/x' })
76
+ expect(f.calls[1].init.credentials).toBe('include')
77
+ })
78
+
79
+ test('204 and empty bodies give undefined data', async () => {
80
+ const f = fakeFetch({ 'DELETE /api/v1/things': new Response(null, { status: 204 }) })
81
+ const r = await createClient({ baseUrl: base, fetch: f, csrf: 'off' }).request({ method: 'DELETE', path: '/api/v1/things' })
82
+ expect(r).toEqual({ ok: true, status: 204, data: undefined })
83
+ })
84
+
85
+ test('baseUrl is required', () => {
86
+ expect(() => createClient({})).toThrow(TypeError)
87
+ })
88
+ })
89
+
90
+ describe('front-end key, client IP, session token', () => {
91
+ test('key and ip are sent together', async () => {
92
+ const f = fakeFetch()
93
+ await createClient({ baseUrl: base, fetch: f, frontendKey: 'pfk_1', clientIp: '203.0.113.9' }).request({ method: 'GET', path: '/api/v1/x' })
94
+ expect(f.calls[0].headers['X-Pano-Frontend-Key']).toBe('pfk_1')
95
+ expect(f.calls[0].headers['X-Pano-Client-Ip']).toBe('203.0.113.9')
96
+ })
97
+
98
+ test('ip without key is never sent, also not through per-request headers', async () => {
99
+ const f = fakeFetch()
100
+ const c = createClient({ baseUrl: base, fetch: f, clientIp: '203.0.113.9' })
101
+ await c.request({ method: 'GET', path: '/api/v1/x' }, { headers: { 'x-pano-client-ip': '1.2.3.4', 'X-Pano-Frontend-Key': 'pfk_forged' } })
102
+ const names = Object.keys(f.calls[0].headers).map((n) => n.toLowerCase())
103
+ expect(names).not.toContain('x-pano-client-ip')
104
+ expect(names).not.toContain('x-pano-frontend-key')
105
+ })
106
+
107
+ test('key without ip sends the key only', async () => {
108
+ const f = fakeFetch()
109
+ await createClient({ baseUrl: base, fetch: f, frontendKey: 'pfk_1' }).request({ method: 'GET', path: '/api/v1/x' })
110
+ expect(f.calls[0].headers['X-Pano-Frontend-Key']).toBe('pfk_1')
111
+ expect(f.calls[0].headers['X-Pano-Client-Ip']).toBeUndefined()
112
+ })
113
+
114
+ test('sessionToken string and (async) function become Bearer; null sends none', async () => {
115
+ const f = fakeFetch()
116
+ await createClient({ baseUrl: base, fetch: f, sessionToken: 'tok' }).request({ method: 'GET', path: '/api/v1/x' })
117
+ expect(f.calls[0].headers.Authorization).toBe('Bearer tok')
118
+ let n = 0
119
+ const c = createClient({ baseUrl: base, fetch: f, sessionToken: async () => (n++ === 0 ? 'a' : null) })
120
+ await c.request({ method: 'GET', path: '/api/v1/x' })
121
+ await c.request({ method: 'GET', path: '/api/v1/x' })
122
+ expect(f.calls[1].headers.Authorization).toBe('Bearer a')
123
+ expect(f.calls[2].headers.Authorization).toBeUndefined()
124
+ })
125
+
126
+ test('a sessionToken turns csrf off by default', async () => {
127
+ const f = fakeFetch()
128
+ await createClient({ baseUrl: base, fetch: f, sessionToken: 'tok', credentials: 'include' }).request(POST, { body: {} })
129
+ expect(f.count('GET /api/v1/auth/csrf')).toBe(0)
130
+ })
131
+ })
132
+
133
+ describe('errors', () => {
134
+ test('envelope is parsed with message, details and fields', async () => {
135
+ const f = fakeFetch({
136
+ 'POST /api/v1/things': json(400, { error: { code: 'INVALID_INPUT', message: 'bad', fields: { name: 'REQUIRED' }, details: { a: 1 } } })
137
+ })
138
+ const r = await createClient({ baseUrl: base, fetch: f, csrf: 'off' }).request(POST, { body: {} })
139
+ expect(r).toEqual({ ok: false, status: 400, error: { code: 'INVALID_INPUT', message: 'bad', fields: { name: 'REQUIRED' }, details: { a: 1 } } })
140
+ })
141
+
142
+ test('a body that is not the envelope becomes HTTP_<status>', async () => {
143
+ const f = fakeFetch({ 'GET /api/v1/x': new Response('<html>bad gateway</html>', { status: 502 }) })
144
+ const r = await createClient({ baseUrl: base, fetch: f }).request({ method: 'GET', path: '/api/v1/x' })
145
+ expect(r.ok).toBe(false)
146
+ expect(r.status).toBe(502)
147
+ expect(r.error.code).toBe('HTTP_502')
148
+ })
149
+
150
+ test('network failure does not throw', async () => {
151
+ const f = fakeFetch({ 'GET /api/v1/x': new TypeError('fetch failed') })
152
+ const r = await createClient({ baseUrl: base, fetch: f }).request({ method: 'GET', path: '/api/v1/x' })
153
+ expect(r.ok).toBe(false)
154
+ expect(r.status).toBe(0)
155
+ expect(r.error.code).toBe('NETWORK_ERROR')
156
+ })
157
+
158
+ test('abort is a NETWORK_ERROR marked aborted', async () => {
159
+ const abort = new Error('aborted')
160
+ abort.name = 'AbortError'
161
+ const f = fakeFetch({ 'GET /api/v1/x': abort })
162
+ const r = await createClient({ baseUrl: base, fetch: f }).request({ method: 'GET', path: '/api/v1/x' })
163
+ expect(r.error.code).toBe('NETWORK_ERROR')
164
+ expect(r.error.details).toEqual({ aborted: true })
165
+ })
166
+
167
+ test('missing fetch gives NETWORK_ERROR', async () => {
168
+ const original = globalThis.fetch
169
+ globalThis.fetch = undefined
170
+ try {
171
+ const r = await createClient({ baseUrl: base }).request({ method: 'GET', path: '/api/v1/x' })
172
+ expect(r.error.code).toBe('NETWORK_ERROR')
173
+ } finally {
174
+ globalThis.fetch = original
175
+ }
176
+ })
177
+
178
+ test('onUnauthorized fires on 401, its throw is swallowed', async () => {
179
+ const f = fakeFetch({ 'GET /api/v1/me': json(401, { error: { code: 'NOT_LOGGED_IN' } }) })
180
+ const seen = []
181
+ const c = createClient({ baseUrl: base, fetch: f, onUnauthorized: (r) => { seen.push(r); throw new Error('boom') } })
182
+ const r = await c.request({ method: 'GET', path: '/api/v1/me' })
183
+ expect(r.status).toBe(401)
184
+ expect(seen).toHaveLength(1)
185
+ expect(seen[0].error.code).toBe('NOT_LOGGED_IN')
186
+ })
187
+
188
+ test('unwrap returns data or throws PanoApiError', async () => {
189
+ expect(unwrap({ ok: true, status: 200, data: 5 })).toBe(5)
190
+ try {
191
+ unwrap({ ok: false, status: 422, error: { code: 'INVALID_INPUT', message: 'bad', fields: { a: 'X' } } })
192
+ throw new Error('should throw')
193
+ } catch (e) {
194
+ expect(e).toBeInstanceOf(PanoApiError)
195
+ expect(e.code).toBe('INVALID_INPUT')
196
+ expect(e.status).toBe(422)
197
+ expect(e.fields).toEqual({ a: 'X' })
198
+ expect(e.message).toBe('bad')
199
+ }
200
+ })
201
+ })
202
+
203
+ describe('csrf auto', () => {
204
+ const auto = (routes) => {
205
+ const f = fakeFetch(routes)
206
+ return { f, c: createClient({ baseUrl: base, fetch: f, credentials: 'include' }) }
207
+ }
208
+
209
+ test('probes before the first mutation, caches, sends X-CSRF-Token', async () => {
210
+ const { f, c } = auto({ 'GET /api/v1/auth/csrf': json(200, { csrfToken: 'T1' }) })
211
+ await c.request({ method: 'GET', path: '/api/v1/x' })
212
+ expect(f.count('GET /api/v1/auth/csrf')).toBe(0)
213
+ await c.request(POST, { body: {} })
214
+ await c.request({ method: 'PUT', path: '/api/v1/things/1' }, { body: {} })
215
+ expect(f.count('GET /api/v1/auth/csrf')).toBe(1)
216
+ expect(f.calls[1].key).toBe('GET /api/v1/auth/csrf')
217
+ expect(f.calls[2].headers['X-CSRF-Token']).toBe('T1')
218
+ expect(f.calls[3].headers['X-CSRF-Token']).toBe('T1')
219
+ })
220
+
221
+ test('concurrent first mutations share one probe', async () => {
222
+ const { f, c } = auto({ 'GET /api/v1/auth/csrf': json(200, { csrfToken: 'T1' }) })
223
+ await Promise.all([c.request(POST, { body: {} }), c.request(POST, { body: {} })])
224
+ expect(f.count('GET /api/v1/auth/csrf')).toBe(1)
225
+ })
226
+
227
+ test('401 on the probe: no header, no onUnauthorized, cached as none', async () => {
228
+ const f = fakeFetch({ 'GET /api/v1/auth/csrf': json(401, { error: { code: 'NOT_LOGGED_IN' } }) })
229
+ let unauthorized = 0
230
+ const c = createClient({ baseUrl: base, fetch: f, credentials: 'include', onUnauthorized: () => unauthorized++ })
231
+ const r = await c.request(POST, { body: {} })
232
+ expect(r.ok).toBe(true)
233
+ await c.request(POST, { body: {} })
234
+ expect(unauthorized).toBe(0)
235
+ expect(f.count('GET /api/v1/auth/csrf')).toBe(1)
236
+ expect(f.calls[1].headers['X-CSRF-Token']).toBeUndefined()
237
+ expect(f.calls[2].headers['X-CSRF-Token']).toBeUndefined()
238
+ })
239
+
240
+ test('null token (Bearer) means no header', async () => {
241
+ const { f, c } = auto({ 'GET /api/v1/auth/csrf': json(200, { csrfToken: null }) })
242
+ await c.request(POST, { body: {} })
243
+ expect(f.calls[1].headers['X-CSRF-Token']).toBeUndefined()
244
+ })
245
+
246
+ test('a failed probe is not cached; the next mutation probes again', async () => {
247
+ const { f, c } = auto({ 'GET /api/v1/auth/csrf': [new TypeError('down'), json(200, { csrfToken: 'T2' })] })
248
+ await c.request(POST, { body: {} })
249
+ await c.request(POST, { body: {} })
250
+ expect(f.count('GET /api/v1/auth/csrf')).toBe(2)
251
+ expect(f.calls[3].headers['X-CSRF-Token']).toBe('T2')
252
+ })
253
+
254
+ test('a csrfToken in any response body replaces the cache', async () => {
255
+ const { f, c } = auto({
256
+ 'GET /api/v1/auth/csrf': json(200, { csrfToken: 'T1' }),
257
+ 'GET /api/v1/me': json(200, { csrfToken: 'T9' })
258
+ })
259
+ await c.request(POST, { body: {} })
260
+ await c.request({ method: 'GET', path: '/api/v1/me' })
261
+ await c.request(POST, { body: {} })
262
+ expect(f.calls.at(-1).headers['X-CSRF-Token']).toBe('T9')
263
+ expect(f.count('GET /api/v1/auth/csrf')).toBe(1)
264
+ })
265
+
266
+ test('cleared after a successful /api/v1/auth/ mutation, then probed again', async () => {
267
+ const { f, c } = auto({
268
+ 'GET /api/v1/auth/csrf': [json(200, { csrfToken: 'T1' }), json(401, { error: { code: 'NOT_LOGGED_IN' } })],
269
+ 'POST /api/v1/auth/logout': json(200, {})
270
+ })
271
+ await c.request({ method: 'POST', path: '/api/v1/auth/logout' }, { body: {} })
272
+ expect(f.calls[1].headers['X-CSRF-Token']).toBe('T1')
273
+ await c.request(POST, { body: {} })
274
+ expect(f.count('GET /api/v1/auth/csrf')).toBe(2)
275
+ expect(f.calls.at(-1).headers['X-CSRF-Token']).toBeUndefined()
276
+ })
277
+
278
+ test('a login body token is kept after the clear', async () => {
279
+ const { f, c } = auto({
280
+ 'GET /api/v1/auth/csrf': json(401, { error: { code: 'NOT_LOGGED_IN' } }),
281
+ 'POST /api/v1/auth/login': json(200, { csrfToken: 'L1' })
282
+ })
283
+ await c.request({ method: 'POST', path: '/api/v1/auth/login' }, { body: {} })
284
+ await c.request(POST, { body: {} })
285
+ expect(f.count('GET /api/v1/auth/csrf')).toBe(1)
286
+ expect(f.calls.at(-1).headers['X-CSRF-Token']).toBe('L1')
287
+ })
288
+
289
+ test('a failed /auth/ mutation does not clear', async () => {
290
+ const { f, c } = auto({
291
+ 'GET /api/v1/auth/csrf': json(200, { csrfToken: 'T1' }),
292
+ 'POST /api/v1/auth/login': json(400, { error: { code: 'WRONG_PASSWORD' } })
293
+ })
294
+ await c.request({ method: 'POST', path: '/api/v1/auth/login' }, { body: {} })
295
+ await c.request(POST, { body: {} })
296
+ expect(f.count('GET /api/v1/auth/csrf')).toBe(1)
297
+ })
298
+
299
+ test('INVALID_CSRF_TOKEN: clear, refetch, retry exactly once', async () => {
300
+ const invalid = () => json(403, { error: { code: 'INVALID_CSRF_TOKEN' } })
301
+ const { f, c } = auto({
302
+ 'GET /api/v1/auth/csrf': [json(200, { csrfToken: 'OLD' }), json(200, { csrfToken: 'NEW' })],
303
+ 'POST /api/v1/things': [invalid(), json(200, { done: true })]
304
+ })
305
+ const r = await c.request(POST, { body: { a: 1 } })
306
+ expect(r).toEqual({ ok: true, status: 200, data: { done: true } })
307
+ const posts = f.calls.filter((x) => x.key === 'POST /api/v1/things')
308
+ expect(posts.map((p) => p.headers['X-CSRF-Token'])).toEqual(['OLD', 'NEW'])
309
+ expect(posts[1].body).toBe('{"a":1}')
310
+ })
311
+
312
+ test('a second INVALID_CSRF_TOKEN is returned, no third attempt', async () => {
313
+ const invalid = () => json(403, { error: { code: 'INVALID_CSRF_TOKEN' } })
314
+ const { f, c } = auto({
315
+ 'GET /api/v1/auth/csrf': () => json(200, { csrfToken: 'T' }),
316
+ 'POST /api/v1/things': [invalid(), invalid(), invalid()]
317
+ })
318
+ const r = await c.request(POST, { body: {} })
319
+ expect(r.ok).toBe(false)
320
+ expect(r.error.code).toBe('INVALID_CSRF_TOKEN')
321
+ expect(f.count('POST /api/v1/things')).toBe(2)
322
+ })
323
+
324
+ test('GET never probes and never sends the header', async () => {
325
+ const { f, c } = auto({})
326
+ await c.request({ method: 'GET', path: '/api/v1/x' })
327
+ expect(f.calls).toHaveLength(1)
328
+ expect(f.calls[0].headers['X-CSRF-Token']).toBeUndefined()
329
+ })
330
+ })
331
+
332
+ describe('csrf off', () => {
333
+ test('never calls the endpoint, even on INVALID_CSRF_TOKEN', async () => {
334
+ const f = fakeFetch({ 'POST /api/v1/things': json(403, { error: { code: 'INVALID_CSRF_TOKEN' } }) })
335
+ const c = createClient({ baseUrl: base, fetch: f, credentials: 'include', csrf: 'off' })
336
+ const r = await c.request(POST, { body: {} })
337
+ expect(r.error.code).toBe('INVALID_CSRF_TOKEN')
338
+ expect(f.calls).toHaveLength(1)
339
+ expect(f.count('GET /api/v1/auth/csrf')).toBe(0)
340
+ expect(f.calls[0].headers['X-CSRF-Token']).toBeUndefined()
341
+ })
342
+
343
+ test('omit credentials defaults to off', async () => {
344
+ const f = fakeFetch()
345
+ await createClient({ baseUrl: base, fetch: f, credentials: 'omit' }).request(POST, { body: {} })
346
+ expect(f.count('GET /api/v1/auth/csrf')).toBe(0)
347
+ })
348
+ })