@shipworthy/openapi-fetch 0.0.0-stage → 0.0.2

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.
package/dist/index.cjs ADDED
@@ -0,0 +1,538 @@
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ //#region src/headers.ts
6
+ /** Iterate any `HeadersOptions` form (plain object, `Headers`, or `[name, value]` tuples) as entries */
7
+ function headerEntries(h) {
8
+ if (h instanceof Headers) return h.entries();
9
+ if (Array.isArray(h)) return new Headers(h).entries();
10
+ return Object.entries(h);
11
+ }
12
+ /** Merge headers a and b, with b taking priority */
13
+ function mergeHeaders(...allHeaders) {
14
+ const finalHeaders = new Headers();
15
+ for (const h of allHeaders) {
16
+ if (!h || typeof h !== "object") continue;
17
+ for (const [k, v] of headerEntries(h)) if (v === null) finalHeaders.delete(k);
18
+ else if (Array.isArray(v)) for (const v2 of v) finalHeaders.append(k, String(v2));
19
+ else if (v !== void 0) finalHeaders.set(k, String(v));
20
+ }
21
+ return finalHeaders;
22
+ }
23
+ //#endregion
24
+ //#region src/serializers/body.ts
25
+ /** Serialize body object to string */
26
+ function defaultBodySerializer(body, headers) {
27
+ if (body instanceof FormData) return body;
28
+ if (headers) {
29
+ if ((typeof headers.get === "function" ? headers.get("Content-Type") ?? headers.get("content-type") : headers["Content-Type"] ?? headers["content-type"]) === "application/x-www-form-urlencoded") return new URLSearchParams(body).toString();
30
+ }
31
+ return JSON.stringify(body);
32
+ }
33
+ //#endregion
34
+ //#region src/serializers/param.ts
35
+ /** Serialize primitive params to string */
36
+ function serializePrimitiveParam(name, value, options) {
37
+ if (value === void 0 || value === null) return "";
38
+ if (typeof value === "object") throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");
39
+ return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;
40
+ }
41
+ /** Serialize object param to string */
42
+ function serializeObjectParam(name, value, options) {
43
+ if (!value || typeof value !== "object") return "";
44
+ const values = [];
45
+ const joiner = {
46
+ simple: ",",
47
+ label: ".",
48
+ matrix: ";"
49
+ }[options.style] || "&";
50
+ if (options.style !== "deepObject" && options.explode === false) {
51
+ for (const k in value) values.push(k, options.allowReserved === true ? value[k] : encodeURIComponent(String(value[k])));
52
+ const final = values.join(",");
53
+ switch (options.style) {
54
+ case "form": return `${name}=${final}`;
55
+ case "label": return `.${final}`;
56
+ case "matrix": return `;${name}=${final}`;
57
+ default: return final;
58
+ }
59
+ }
60
+ for (const k in value) {
61
+ const finalName = options.style === "deepObject" ? `${name}[${k}]` : k;
62
+ values.push(serializePrimitiveParam(finalName, value[k], options));
63
+ }
64
+ const final = values.join(joiner);
65
+ return options.style === "label" || options.style === "matrix" ? `${joiner}${final}` : final;
66
+ }
67
+ /** Serialize array param (shallow only) */
68
+ function serializeArrayParam(name, value, options) {
69
+ if (!Array.isArray(value)) return "";
70
+ if (options.explode === false) {
71
+ const joiner = {
72
+ form: ",",
73
+ spaceDelimited: "%20",
74
+ pipeDelimited: "|"
75
+ }[options.style] || ",";
76
+ const final = (options.allowReserved === true ? value : value.map((v) => encodeURIComponent(String(v)))).join(joiner);
77
+ switch (options.style) {
78
+ case "simple": return final;
79
+ case "label": return `.${final}`;
80
+ case "matrix": return `;${name}=${final}`;
81
+ default: return `${name}=${final}`;
82
+ }
83
+ }
84
+ const joiner = {
85
+ simple: ",",
86
+ label: ".",
87
+ matrix: ";"
88
+ }[options.style] || "&";
89
+ const values = [];
90
+ for (const v of value) if (options.style === "simple" || options.style === "label") values.push(options.allowReserved === true ? v : encodeURIComponent(String(v)));
91
+ else values.push(serializePrimitiveParam(name, v, options));
92
+ return options.style === "label" || options.style === "matrix" ? `${joiner}${values.join(joiner)}` : values.join(joiner);
93
+ }
94
+ //#endregion
95
+ //#region src/serializers/cookie.ts
96
+ /**
97
+ * Serialize cookie params to a `Cookie` header value using the OpenAPI default
98
+ * (style: form, explode: true). Arrays repeat the name, objects emit one pair per key,
99
+ * and values are URI-encoded. `undefined` and `null` values are skipped.
100
+ * @see https://swagger.io/docs/specification/serialization/#cookie
101
+ */
102
+ function serializeCookieParams(cookieParams) {
103
+ const pairs = [];
104
+ if (!cookieParams || typeof cookieParams !== "object") return "";
105
+ const push = (name, value) => {
106
+ if (value === void 0 || value === null) return;
107
+ pairs.push(serializePrimitiveParam(name, value));
108
+ };
109
+ for (const name in cookieParams) {
110
+ const value = cookieParams[name];
111
+ if (Array.isArray(value)) for (const v of value) push(name, v);
112
+ else if (value !== null && typeof value === "object") for (const [k, v] of Object.entries(value)) push(k, v);
113
+ else push(name, value);
114
+ }
115
+ return pairs.join("; ");
116
+ }
117
+ //#endregion
118
+ //#region src/serializers/path.ts
119
+ const PATH_PARAM_RE = /\{[^{}]+\}/g;
120
+ /**
121
+ * Handle different OpenAPI 3.x serialization styles
122
+ * @see https://swagger.io/docs/specification/serialization/#path
123
+ */
124
+ function defaultPathSerializer(pathname, pathParams) {
125
+ let nextURL = pathname;
126
+ for (const match of pathname.match(PATH_PARAM_RE) ?? []) {
127
+ let name = match.substring(1, match.length - 1);
128
+ let explode = false;
129
+ let style = "simple";
130
+ if (name.endsWith("*")) {
131
+ explode = true;
132
+ name = name.substring(0, name.length - 1);
133
+ }
134
+ if (name.startsWith(".")) {
135
+ style = "label";
136
+ name = name.substring(1);
137
+ } else if (name.startsWith(";")) {
138
+ style = "matrix";
139
+ name = name.substring(1);
140
+ }
141
+ if (!pathParams || pathParams[name] === void 0 || pathParams[name] === null) continue;
142
+ const value = pathParams[name];
143
+ if (Array.isArray(value)) {
144
+ nextURL = nextURL.replace(match, serializeArrayParam(name, value, {
145
+ style,
146
+ explode
147
+ }));
148
+ continue;
149
+ }
150
+ if (typeof value === "object") {
151
+ nextURL = nextURL.replace(match, serializeObjectParam(name, value, {
152
+ style,
153
+ explode
154
+ }));
155
+ continue;
156
+ }
157
+ if (style === "matrix") {
158
+ nextURL = nextURL.replace(match, `;${serializePrimitiveParam(name, value)}`);
159
+ continue;
160
+ }
161
+ nextURL = nextURL.replace(match, style === "label" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value));
162
+ }
163
+ return nextURL;
164
+ }
165
+ //#endregion
166
+ //#region src/serializers/query.ts
167
+ /** Serialize query params to string */
168
+ function createQuerySerializer(options) {
169
+ return function querySerializer(queryParams) {
170
+ const search = [];
171
+ if (queryParams && typeof queryParams === "object") for (const name in queryParams) {
172
+ const value = queryParams[name];
173
+ if (value === void 0 || value === null) continue;
174
+ if (Array.isArray(value)) {
175
+ if (value.length === 0) continue;
176
+ search.push(serializeArrayParam(name, value, {
177
+ style: "form",
178
+ explode: true,
179
+ ...options?.array,
180
+ allowReserved: options?.allowReserved || false
181
+ }));
182
+ continue;
183
+ }
184
+ if (typeof value === "object") {
185
+ search.push(serializeObjectParam(name, value, {
186
+ style: "deepObject",
187
+ explode: true,
188
+ ...options?.object,
189
+ allowReserved: options?.allowReserved || false
190
+ }));
191
+ continue;
192
+ }
193
+ search.push(serializePrimitiveParam(name, value, options));
194
+ }
195
+ return search.join("&");
196
+ };
197
+ }
198
+ //#endregion
199
+ //#region src/serializers/url.ts
200
+ /** Construct URL string from baseUrl and handle path and query params */
201
+ function createFinalURL(pathname, options) {
202
+ let finalURL = `${options.baseUrl}${pathname}`;
203
+ if (options.params?.path) finalURL = options.pathSerializer(finalURL, options.params.path);
204
+ let search = options.querySerializer(options.params.query ?? {});
205
+ if (search.startsWith("?")) search = search.substring(1);
206
+ if (search) finalURL += `?${search}`;
207
+ return finalURL;
208
+ }
209
+ /** Remove trailing slash from url */
210
+ function removeTrailingSlash(url) {
211
+ if (url.endsWith("/")) return url.substring(0, url.length - 1);
212
+ return url;
213
+ }
214
+ //#endregion
215
+ //#region src/client.ts
216
+ function supportsRequestInitExt() {
217
+ const nodeProcess = globalThis.process;
218
+ return typeof nodeProcess === "object" && Number.parseInt(nodeProcess?.versions?.node?.substring(0, 2) ?? "") >= 18 && nodeProcess?.versions?.undici;
219
+ }
220
+ /** Returns a cheap, non-cryptographically-secure random ID. */
221
+ function randomID() {
222
+ return Math.random().toString(36).slice(2, 11);
223
+ }
224
+ /**
225
+ * Create an openapi-fetch client.
226
+ */
227
+ function createClient(clientOptions) {
228
+ let { baseUrl = "", Request: CustomRequest = globalThis.Request, fetch: baseFetch = globalThis.fetch, querySerializer: globalQuerySerializer, bodySerializer: globalBodySerializer, pathSerializer: globalPathSerializer, headers: baseHeaders, requestInitExt, ...baseOptions } = { ...clientOptions };
229
+ requestInitExt = supportsRequestInitExt() ? requestInitExt : void 0;
230
+ baseUrl = removeTrailingSlash(baseUrl);
231
+ const globalMiddlewares = [];
232
+ /**
233
+ * Per-request fetch (keeps settings created in createClient()
234
+ */
235
+ async function coreFetch(schemaPath, fetchOptions) {
236
+ const { baseUrl: localBaseUrl, fetch = baseFetch, Request = CustomRequest, headers, params = {}, parseAs = "json", querySerializer: requestQuerySerializer, bodySerializer = globalBodySerializer ?? defaultBodySerializer, pathSerializer: requestPathSerializer, body, middleware: requestMiddlewares = [], ...init } = fetchOptions || {};
237
+ let finalBaseUrl = baseUrl;
238
+ if (localBaseUrl) finalBaseUrl = removeTrailingSlash(localBaseUrl) ?? baseUrl;
239
+ let querySerializer = typeof globalQuerySerializer === "function" ? globalQuerySerializer : createQuerySerializer(globalQuerySerializer);
240
+ if (requestQuerySerializer) querySerializer = typeof requestQuerySerializer === "function" ? requestQuerySerializer : createQuerySerializer({
241
+ ...typeof globalQuerySerializer === "object" ? globalQuerySerializer : {},
242
+ ...requestQuerySerializer
243
+ });
244
+ const pathSerializer = requestPathSerializer || globalPathSerializer || defaultPathSerializer;
245
+ const serializedBody = body === void 0 ? void 0 : bodySerializer(body, mergeHeaders(baseHeaders, headers, params.header));
246
+ const finalHeaders = mergeHeaders(serializedBody === void 0 || serializedBody instanceof FormData ? {} : { "Content-Type": "application/json" }, baseHeaders, headers, params.header);
247
+ const serializedCookies = serializeCookieParams(params.cookie);
248
+ if (serializedCookies) {
249
+ const existingCookie = finalHeaders.get("Cookie");
250
+ finalHeaders.set("Cookie", existingCookie ? `${existingCookie}; ${serializedCookies}` : serializedCookies);
251
+ }
252
+ const finalMiddlewares = [...globalMiddlewares, ...requestMiddlewares];
253
+ const requestInit = {
254
+ redirect: "follow",
255
+ ...baseOptions,
256
+ ...init,
257
+ body: serializedBody,
258
+ headers: finalHeaders
259
+ };
260
+ let id;
261
+ let options;
262
+ let request = new Request(createFinalURL(schemaPath, {
263
+ baseUrl: finalBaseUrl,
264
+ params,
265
+ querySerializer,
266
+ pathSerializer
267
+ }), requestInit);
268
+ let response;
269
+ /** Add custom parameters to Request object */
270
+ for (const key in init) if (!(key in request)) request[key] = init[key];
271
+ if (finalMiddlewares.length) {
272
+ id = randomID();
273
+ options = Object.freeze({
274
+ baseUrl: finalBaseUrl,
275
+ fetch,
276
+ parseAs,
277
+ querySerializer,
278
+ bodySerializer,
279
+ pathSerializer
280
+ });
281
+ for (const m of finalMiddlewares) if (m && typeof m === "object" && typeof m.onRequest === "function") {
282
+ const result = await m.onRequest({
283
+ request,
284
+ schemaPath,
285
+ params,
286
+ options,
287
+ id
288
+ });
289
+ if (result) {
290
+ if (result instanceof Request) request = result;
291
+ else if (result instanceof Response) {
292
+ response = result;
293
+ break;
294
+ } else throw new Error("onRequest: must return new Request() or Response() when modifying the request");
295
+ }
296
+ }
297
+ }
298
+ if (!response) {
299
+ try {
300
+ response = await fetch(request, requestInitExt);
301
+ } catch (error) {
302
+ let errorAfterMiddleware = error;
303
+ if (finalMiddlewares.length) for (let i = finalMiddlewares.length - 1; i >= 0; i--) {
304
+ const m = finalMiddlewares[i];
305
+ if (m && typeof m === "object" && typeof m.onError === "function") {
306
+ const result = await m.onError({
307
+ request,
308
+ error: errorAfterMiddleware,
309
+ schemaPath,
310
+ params,
311
+ options,
312
+ id
313
+ });
314
+ if (result) {
315
+ if (result instanceof Response) {
316
+ response = result;
317
+ break;
318
+ }
319
+ if (result instanceof Error) {
320
+ errorAfterMiddleware = result;
321
+ continue;
322
+ }
323
+ throw new Error("onError: must return new Response() or instance of Error");
324
+ }
325
+ }
326
+ }
327
+ if (!response) throw errorAfterMiddleware;
328
+ }
329
+ if (finalMiddlewares.length) for (let i = finalMiddlewares.length - 1; i >= 0; i--) {
330
+ const m = finalMiddlewares[i];
331
+ if (m && typeof m === "object" && typeof m.onResponse === "function") {
332
+ const result = await m.onResponse({
333
+ request,
334
+ response,
335
+ schemaPath,
336
+ params,
337
+ options,
338
+ id
339
+ });
340
+ if (result) {
341
+ if (!(result instanceof Response)) throw new Error("onResponse: must return new Response() when modifying the response");
342
+ response = result;
343
+ }
344
+ }
345
+ }
346
+ }
347
+ const finalResponse = response;
348
+ const contentLength = finalResponse.headers.get("Content-Length");
349
+ if (finalResponse.status === 204 || request.method === "HEAD" || contentLength === "0" && !finalResponse.headers.get("Transfer-Encoding")?.includes("chunked")) return finalResponse.ok ? {
350
+ data: void 0,
351
+ response: finalResponse
352
+ } : {
353
+ error: void 0,
354
+ response: finalResponse
355
+ };
356
+ if (finalResponse.ok) {
357
+ const getResponseData = async () => {
358
+ if (parseAs === "stream") return finalResponse.body;
359
+ if (parseAs === "json" && !contentLength) {
360
+ const raw = await finalResponse.text();
361
+ return raw ? JSON.parse(raw) : void 0;
362
+ }
363
+ return await finalResponse[parseAs]();
364
+ };
365
+ return {
366
+ data: await getResponseData(),
367
+ response: finalResponse
368
+ };
369
+ }
370
+ const raw = await finalResponse.text();
371
+ if (!raw) return {
372
+ error: void 0,
373
+ response: finalResponse
374
+ };
375
+ let error = raw;
376
+ try {
377
+ error = JSON.parse(raw);
378
+ } catch {}
379
+ return {
380
+ error,
381
+ response: finalResponse
382
+ };
383
+ }
384
+ return {
385
+ request(method, url, init) {
386
+ return coreFetch(url, {
387
+ ...init,
388
+ method: method.toUpperCase()
389
+ });
390
+ },
391
+ /** Call a GET endpoint */
392
+ GET(url, init) {
393
+ return coreFetch(url, {
394
+ ...init,
395
+ method: "GET"
396
+ });
397
+ },
398
+ /** Call a PUT endpoint */
399
+ PUT(url, init) {
400
+ return coreFetch(url, {
401
+ ...init,
402
+ method: "PUT"
403
+ });
404
+ },
405
+ /** Call a POST endpoint */
406
+ POST(url, init) {
407
+ return coreFetch(url, {
408
+ ...init,
409
+ method: "POST"
410
+ });
411
+ },
412
+ /** Call a DELETE endpoint */
413
+ DELETE(url, init) {
414
+ return coreFetch(url, {
415
+ ...init,
416
+ method: "DELETE"
417
+ });
418
+ },
419
+ /** Call a OPTIONS endpoint */
420
+ OPTIONS(url, init) {
421
+ return coreFetch(url, {
422
+ ...init,
423
+ method: "OPTIONS"
424
+ });
425
+ },
426
+ /** Call a HEAD endpoint */
427
+ HEAD(url, init) {
428
+ return coreFetch(url, {
429
+ ...init,
430
+ method: "HEAD"
431
+ });
432
+ },
433
+ /** Call a PATCH endpoint */
434
+ PATCH(url, init) {
435
+ return coreFetch(url, {
436
+ ...init,
437
+ method: "PATCH"
438
+ });
439
+ },
440
+ /** Call a TRACE endpoint */
441
+ TRACE(url, init) {
442
+ return coreFetch(url, {
443
+ ...init,
444
+ method: "TRACE"
445
+ });
446
+ },
447
+ /** Register middleware */
448
+ use(...middleware) {
449
+ for (const m of middleware) {
450
+ if (!m) continue;
451
+ if (typeof m !== "object" || !("onRequest" in m || "onResponse" in m || "onError" in m)) throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");
452
+ globalMiddlewares.push(m);
453
+ }
454
+ },
455
+ /** Unregister middleware */
456
+ eject(...middleware) {
457
+ for (const m of middleware) {
458
+ const i = globalMiddlewares.indexOf(m);
459
+ if (i !== -1) globalMiddlewares.splice(i, 1);
460
+ }
461
+ }
462
+ };
463
+ }
464
+ //#endregion
465
+ //#region src/path-client.ts
466
+ var PathCallForwarder = class {
467
+ client;
468
+ url;
469
+ constructor(client, url) {
470
+ this.client = client;
471
+ this.url = url;
472
+ }
473
+ GET = (init) => {
474
+ return this.client.GET(this.url, init);
475
+ };
476
+ PUT = (init) => {
477
+ return this.client.PUT(this.url, init);
478
+ };
479
+ POST = (init) => {
480
+ return this.client.POST(this.url, init);
481
+ };
482
+ DELETE = (init) => {
483
+ return this.client.DELETE(this.url, init);
484
+ };
485
+ OPTIONS = (init) => {
486
+ return this.client.OPTIONS(this.url, init);
487
+ };
488
+ HEAD = (init) => {
489
+ return this.client.HEAD(this.url, init);
490
+ };
491
+ PATCH = (init) => {
492
+ return this.client.PATCH(this.url, init);
493
+ };
494
+ TRACE = (init) => {
495
+ return this.client.TRACE(this.url, init);
496
+ };
497
+ };
498
+ var PathClientProxyHandler = class {
499
+ client = null;
500
+ get(coreClient, url) {
501
+ const forwarder = new PathCallForwarder(coreClient, url);
502
+ this.client[url] = forwarder;
503
+ return forwarder;
504
+ }
505
+ };
506
+ /**
507
+ * Wrap openapi-fetch client to support a path based API.
508
+ */
509
+ function wrapAsPathBasedClient(coreClient) {
510
+ const handler = new PathClientProxyHandler();
511
+ const proxy = new Proxy(coreClient, handler);
512
+ function ClientCtor() {}
513
+ ClientCtor.prototype = proxy;
514
+ const client = new ClientCtor();
515
+ handler.client = client;
516
+ return client;
517
+ }
518
+ /**
519
+ * Convenience method to an openapi-fetch path based client.
520
+ * Strictly equivalent to `wrapAsPathBasedClient(createClient(...))`.
521
+ */
522
+ function createPathBasedClient(clientOptions) {
523
+ return wrapAsPathBasedClient(createClient(clientOptions));
524
+ }
525
+ //#endregion
526
+ exports.createClient = createClient;
527
+ exports.createFinalURL = createFinalURL;
528
+ exports.createPathBasedClient = createPathBasedClient;
529
+ exports.createQuerySerializer = createQuerySerializer;
530
+ exports.default = createClient;
531
+ exports.defaultBodySerializer = defaultBodySerializer;
532
+ exports.defaultPathSerializer = defaultPathSerializer;
533
+ exports.mergeHeaders = mergeHeaders;
534
+ exports.removeTrailingSlash = removeTrailingSlash;
535
+ exports.serializeArrayParam = serializeArrayParam;
536
+ exports.serializeObjectParam = serializeObjectParam;
537
+ exports.serializePrimitiveParam = serializePrimitiveParam;
538
+ exports.wrapAsPathBasedClient = wrapAsPathBasedClient;