@roxyapi/sdk 1.0.1 → 1.0.4

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 DELETED
@@ -1,1054 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/client/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- buildClientParams: () => buildClientParams,
24
- createClient: () => createClient,
25
- createConfig: () => createConfig,
26
- formDataBodySerializer: () => formDataBodySerializer,
27
- jsonBodySerializer: () => jsonBodySerializer,
28
- mergeHeaders: () => mergeHeaders,
29
- serializeQueryKeyValue: () => serializeQueryKeyValue,
30
- urlSearchParamsBodySerializer: () => urlSearchParamsBodySerializer
31
- });
32
- module.exports = __toCommonJS(index_exports);
33
-
34
- // src/core/bodySerializer.gen.ts
35
- var serializeFormDataPair = (data, key, value) => {
36
- if (typeof value === "string" || value instanceof Blob) {
37
- data.append(key, value);
38
- } else if (value instanceof Date) {
39
- data.append(key, value.toISOString());
40
- } else {
41
- data.append(key, JSON.stringify(value));
42
- }
43
- };
44
- var serializeUrlSearchParamsPair = (data, key, value) => {
45
- if (typeof value === "string") {
46
- data.append(key, value);
47
- } else {
48
- data.append(key, JSON.stringify(value));
49
- }
50
- };
51
- var formDataBodySerializer = {
52
- bodySerializer: (body) => {
53
- const data = new FormData();
54
- Object.entries(body).forEach(([key, value]) => {
55
- if (value === void 0 || value === null) {
56
- return;
57
- }
58
- if (Array.isArray(value)) {
59
- value.forEach((v) => serializeFormDataPair(data, key, v));
60
- } else {
61
- serializeFormDataPair(data, key, value);
62
- }
63
- });
64
- return data;
65
- }
66
- };
67
- var jsonBodySerializer = {
68
- bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value)
69
- };
70
- var urlSearchParamsBodySerializer = {
71
- bodySerializer: (body) => {
72
- const data = new URLSearchParams();
73
- Object.entries(body).forEach(([key, value]) => {
74
- if (value === void 0 || value === null) {
75
- return;
76
- }
77
- if (Array.isArray(value)) {
78
- value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
79
- } else {
80
- serializeUrlSearchParamsPair(data, key, value);
81
- }
82
- });
83
- return data.toString();
84
- }
85
- };
86
-
87
- // src/core/params.gen.ts
88
- var extraPrefixesMap = {
89
- $body_: "body",
90
- $headers_: "headers",
91
- $path_: "path",
92
- $query_: "query"
93
- };
94
- var extraPrefixes = Object.entries(extraPrefixesMap);
95
- var buildKeyMap = (fields, map) => {
96
- if (!map) {
97
- map = /* @__PURE__ */ new Map();
98
- }
99
- for (const config of fields) {
100
- if ("in" in config) {
101
- if (config.key) {
102
- map.set(config.key, {
103
- in: config.in,
104
- map: config.map
105
- });
106
- }
107
- } else if ("key" in config) {
108
- map.set(config.key, {
109
- map: config.map
110
- });
111
- } else if (config.args) {
112
- buildKeyMap(config.args, map);
113
- }
114
- }
115
- return map;
116
- };
117
- var stripEmptySlots = (params) => {
118
- for (const [slot, value] of Object.entries(params)) {
119
- if (value && typeof value === "object" && !Array.isArray(value) && !Object.keys(value).length) {
120
- delete params[slot];
121
- }
122
- }
123
- };
124
- var buildClientParams = (args, fields) => {
125
- const params = {
126
- body: {},
127
- headers: {},
128
- path: {},
129
- query: {}
130
- };
131
- const map = buildKeyMap(fields);
132
- let config;
133
- for (const [index, arg] of args.entries()) {
134
- if (fields[index]) {
135
- config = fields[index];
136
- }
137
- if (!config) {
138
- continue;
139
- }
140
- if ("in" in config) {
141
- if (config.key) {
142
- const field = map.get(config.key);
143
- const name = field.map || config.key;
144
- if (field.in) {
145
- params[field.in][name] = arg;
146
- }
147
- } else {
148
- params.body = arg;
149
- }
150
- } else {
151
- for (const [key, value] of Object.entries(arg ?? {})) {
152
- const field = map.get(key);
153
- if (field) {
154
- if (field.in) {
155
- const name = field.map || key;
156
- params[field.in][name] = value;
157
- } else {
158
- params[field.map] = value;
159
- }
160
- } else {
161
- const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix));
162
- if (extra) {
163
- const [prefix, slot] = extra;
164
- params[slot][key.slice(prefix.length)] = value;
165
- } else if ("allowExtra" in config && config.allowExtra) {
166
- for (const [slot, allowed] of Object.entries(config.allowExtra)) {
167
- if (allowed) {
168
- params[slot][key] = value;
169
- break;
170
- }
171
- }
172
- }
173
- }
174
- }
175
- }
176
- }
177
- stripEmptySlots(params);
178
- return params;
179
- };
180
-
181
- // src/core/queryKeySerializer.gen.ts
182
- var queryKeyJsonReplacer = (_key, value) => {
183
- if (value === void 0 || typeof value === "function" || typeof value === "symbol") {
184
- return void 0;
185
- }
186
- if (typeof value === "bigint") {
187
- return value.toString();
188
- }
189
- if (value instanceof Date) {
190
- return value.toISOString();
191
- }
192
- return value;
193
- };
194
- var stringifyToJsonValue = (input) => {
195
- try {
196
- const json = JSON.stringify(input, queryKeyJsonReplacer);
197
- if (json === void 0) {
198
- return void 0;
199
- }
200
- return JSON.parse(json);
201
- } catch {
202
- return void 0;
203
- }
204
- };
205
- var isPlainObject = (value) => {
206
- if (value === null || typeof value !== "object") {
207
- return false;
208
- }
209
- const prototype = Object.getPrototypeOf(value);
210
- return prototype === Object.prototype || prototype === null;
211
- };
212
- var serializeSearchParams = (params) => {
213
- const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b));
214
- const result = {};
215
- for (const [key, value] of entries) {
216
- const existing = result[key];
217
- if (existing === void 0) {
218
- result[key] = value;
219
- continue;
220
- }
221
- if (Array.isArray(existing)) {
222
- existing.push(value);
223
- } else {
224
- result[key] = [existing, value];
225
- }
226
- }
227
- return result;
228
- };
229
- var serializeQueryKeyValue = (value) => {
230
- if (value === null) {
231
- return null;
232
- }
233
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
234
- return value;
235
- }
236
- if (value === void 0 || typeof value === "function" || typeof value === "symbol") {
237
- return void 0;
238
- }
239
- if (typeof value === "bigint") {
240
- return value.toString();
241
- }
242
- if (value instanceof Date) {
243
- return value.toISOString();
244
- }
245
- if (Array.isArray(value)) {
246
- return stringifyToJsonValue(value);
247
- }
248
- if (typeof URLSearchParams !== "undefined" && value instanceof URLSearchParams) {
249
- return serializeSearchParams(value);
250
- }
251
- if (isPlainObject(value)) {
252
- return stringifyToJsonValue(value);
253
- }
254
- return void 0;
255
- };
256
-
257
- // src/core/serverSentEvents.gen.ts
258
- var createSseClient = ({
259
- onRequest,
260
- onSseError,
261
- onSseEvent,
262
- responseTransformer,
263
- responseValidator,
264
- sseDefaultRetryDelay,
265
- sseMaxRetryAttempts,
266
- sseMaxRetryDelay,
267
- sseSleepFn,
268
- url,
269
- ...options
270
- }) => {
271
- let lastEventId;
272
- const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
273
- const createStream = async function* () {
274
- let retryDelay = sseDefaultRetryDelay ?? 3e3;
275
- let attempt = 0;
276
- const signal = options.signal ?? new AbortController().signal;
277
- while (true) {
278
- if (signal.aborted) break;
279
- attempt++;
280
- const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
281
- if (lastEventId !== void 0) {
282
- headers.set("Last-Event-ID", lastEventId);
283
- }
284
- try {
285
- const requestInit = {
286
- redirect: "follow",
287
- ...options,
288
- body: options.serializedBody,
289
- headers,
290
- signal
291
- };
292
- let request = new Request(url, requestInit);
293
- if (onRequest) {
294
- request = await onRequest(url, requestInit);
295
- }
296
- const _fetch = options.fetch ?? globalThis.fetch;
297
- const response = await _fetch(request);
298
- if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
299
- if (!response.body) throw new Error("No body in SSE response");
300
- const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
301
- let buffer = "";
302
- const abortHandler = () => {
303
- try {
304
- reader.cancel();
305
- } catch {
306
- }
307
- };
308
- signal.addEventListener("abort", abortHandler);
309
- try {
310
- while (true) {
311
- const { done, value } = await reader.read();
312
- if (done) break;
313
- buffer += value;
314
- buffer = buffer.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
315
- const chunks = buffer.split("\n\n");
316
- buffer = chunks.pop() ?? "";
317
- for (const chunk of chunks) {
318
- const lines = chunk.split("\n");
319
- const dataLines = [];
320
- let eventName;
321
- for (const line of lines) {
322
- if (line.startsWith("data:")) {
323
- dataLines.push(line.replace(/^data:\s*/, ""));
324
- } else if (line.startsWith("event:")) {
325
- eventName = line.replace(/^event:\s*/, "");
326
- } else if (line.startsWith("id:")) {
327
- lastEventId = line.replace(/^id:\s*/, "");
328
- } else if (line.startsWith("retry:")) {
329
- const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
330
- if (!Number.isNaN(parsed)) {
331
- retryDelay = parsed;
332
- }
333
- }
334
- }
335
- let data;
336
- let parsedJson = false;
337
- if (dataLines.length) {
338
- const rawData = dataLines.join("\n");
339
- try {
340
- data = JSON.parse(rawData);
341
- parsedJson = true;
342
- } catch {
343
- data = rawData;
344
- }
345
- }
346
- if (parsedJson) {
347
- if (responseValidator) {
348
- await responseValidator(data);
349
- }
350
- if (responseTransformer) {
351
- data = await responseTransformer(data);
352
- }
353
- }
354
- onSseEvent?.({
355
- data,
356
- event: eventName,
357
- id: lastEventId,
358
- retry: retryDelay
359
- });
360
- if (dataLines.length) {
361
- yield data;
362
- }
363
- }
364
- }
365
- } finally {
366
- signal.removeEventListener("abort", abortHandler);
367
- reader.releaseLock();
368
- }
369
- break;
370
- } catch (error) {
371
- onSseError?.(error);
372
- if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
373
- break;
374
- }
375
- const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
376
- await sleep(backoff);
377
- }
378
- }
379
- };
380
- const stream = createStream();
381
- return { stream };
382
- };
383
-
384
- // src/core/pathSerializer.gen.ts
385
- var separatorArrayExplode = (style) => {
386
- switch (style) {
387
- case "label":
388
- return ".";
389
- case "matrix":
390
- return ";";
391
- case "simple":
392
- return ",";
393
- default:
394
- return "&";
395
- }
396
- };
397
- var separatorArrayNoExplode = (style) => {
398
- switch (style) {
399
- case "form":
400
- return ",";
401
- case "pipeDelimited":
402
- return "|";
403
- case "spaceDelimited":
404
- return "%20";
405
- default:
406
- return ",";
407
- }
408
- };
409
- var separatorObjectExplode = (style) => {
410
- switch (style) {
411
- case "label":
412
- return ".";
413
- case "matrix":
414
- return ";";
415
- case "simple":
416
- return ",";
417
- default:
418
- return "&";
419
- }
420
- };
421
- var serializeArrayParam = ({
422
- allowReserved,
423
- explode,
424
- name,
425
- style,
426
- value
427
- }) => {
428
- if (!explode) {
429
- const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
430
- switch (style) {
431
- case "label":
432
- return `.${joinedValues2}`;
433
- case "matrix":
434
- return `;${name}=${joinedValues2}`;
435
- case "simple":
436
- return joinedValues2;
437
- default:
438
- return `${name}=${joinedValues2}`;
439
- }
440
- }
441
- const separator = separatorArrayExplode(style);
442
- const joinedValues = value.map((v) => {
443
- if (style === "label" || style === "simple") {
444
- return allowReserved ? v : encodeURIComponent(v);
445
- }
446
- return serializePrimitiveParam({
447
- allowReserved,
448
- name,
449
- value: v
450
- });
451
- }).join(separator);
452
- return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
453
- };
454
- var serializePrimitiveParam = ({
455
- allowReserved,
456
- name,
457
- value
458
- }) => {
459
- if (value === void 0 || value === null) {
460
- return "";
461
- }
462
- if (typeof value === "object") {
463
- throw new Error(
464
- "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
465
- );
466
- }
467
- return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
468
- };
469
- var serializeObjectParam = ({
470
- allowReserved,
471
- explode,
472
- name,
473
- style,
474
- value,
475
- valueOnly
476
- }) => {
477
- if (value instanceof Date) {
478
- return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
479
- }
480
- if (style !== "deepObject" && !explode) {
481
- let values = [];
482
- Object.entries(value).forEach(([key, v]) => {
483
- values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
484
- });
485
- const joinedValues2 = values.join(",");
486
- switch (style) {
487
- case "form":
488
- return `${name}=${joinedValues2}`;
489
- case "label":
490
- return `.${joinedValues2}`;
491
- case "matrix":
492
- return `;${name}=${joinedValues2}`;
493
- default:
494
- return joinedValues2;
495
- }
496
- }
497
- const separator = separatorObjectExplode(style);
498
- const joinedValues = Object.entries(value).map(
499
- ([key, v]) => serializePrimitiveParam({
500
- allowReserved,
501
- name: style === "deepObject" ? `${name}[${key}]` : key,
502
- value: v
503
- })
504
- ).join(separator);
505
- return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
506
- };
507
-
508
- // src/core/utils.gen.ts
509
- var PATH_PARAM_RE = /\{[^{}]+\}/g;
510
- var defaultPathSerializer = ({ path, url: _url }) => {
511
- let url = _url;
512
- const matches = _url.match(PATH_PARAM_RE);
513
- if (matches) {
514
- for (const match of matches) {
515
- let explode = false;
516
- let name = match.substring(1, match.length - 1);
517
- let style = "simple";
518
- if (name.endsWith("*")) {
519
- explode = true;
520
- name = name.substring(0, name.length - 1);
521
- }
522
- if (name.startsWith(".")) {
523
- name = name.substring(1);
524
- style = "label";
525
- } else if (name.startsWith(";")) {
526
- name = name.substring(1);
527
- style = "matrix";
528
- }
529
- const value = path[name];
530
- if (value === void 0 || value === null) {
531
- continue;
532
- }
533
- if (Array.isArray(value)) {
534
- url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
535
- continue;
536
- }
537
- if (typeof value === "object") {
538
- url = url.replace(
539
- match,
540
- serializeObjectParam({
541
- explode,
542
- name,
543
- style,
544
- value,
545
- valueOnly: true
546
- })
547
- );
548
- continue;
549
- }
550
- if (style === "matrix") {
551
- url = url.replace(
552
- match,
553
- `;${serializePrimitiveParam({
554
- name,
555
- value
556
- })}`
557
- );
558
- continue;
559
- }
560
- const replaceValue = encodeURIComponent(
561
- style === "label" ? `.${value}` : value
562
- );
563
- url = url.replace(match, replaceValue);
564
- }
565
- }
566
- return url;
567
- };
568
- var getUrl = ({
569
- baseUrl,
570
- path,
571
- query,
572
- querySerializer,
573
- url: _url
574
- }) => {
575
- const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
576
- let url = (baseUrl ?? "") + pathUrl;
577
- if (path) {
578
- url = defaultPathSerializer({ path, url });
579
- }
580
- let search = query ? querySerializer(query) : "";
581
- if (search.startsWith("?")) {
582
- search = search.substring(1);
583
- }
584
- if (search) {
585
- url += `?${search}`;
586
- }
587
- return url;
588
- };
589
- function getValidRequestBody(options) {
590
- const hasBody = options.body !== void 0;
591
- const isSerializedBody = hasBody && options.bodySerializer;
592
- if (isSerializedBody) {
593
- if ("serializedBody" in options) {
594
- const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
595
- return hasSerializedBody ? options.serializedBody : null;
596
- }
597
- return options.body !== "" ? options.body : null;
598
- }
599
- if (hasBody) {
600
- return options.body;
601
- }
602
- return void 0;
603
- }
604
-
605
- // src/core/auth.gen.ts
606
- var getAuthToken = async (auth, callback) => {
607
- const token = typeof callback === "function" ? await callback(auth) : callback;
608
- if (!token) {
609
- return;
610
- }
611
- if (auth.scheme === "bearer") {
612
- return `Bearer ${token}`;
613
- }
614
- if (auth.scheme === "basic") {
615
- return `Basic ${btoa(token)}`;
616
- }
617
- return token;
618
- };
619
-
620
- // src/client/utils.gen.ts
621
- var createQuerySerializer = ({
622
- parameters = {},
623
- ...args
624
- } = {}) => {
625
- const querySerializer = (queryParams) => {
626
- const search = [];
627
- if (queryParams && typeof queryParams === "object") {
628
- for (const name in queryParams) {
629
- const value = queryParams[name];
630
- if (value === void 0 || value === null) {
631
- continue;
632
- }
633
- const options = parameters[name] || args;
634
- if (Array.isArray(value)) {
635
- const serializedArray = serializeArrayParam({
636
- allowReserved: options.allowReserved,
637
- explode: true,
638
- name,
639
- style: "form",
640
- value,
641
- ...options.array
642
- });
643
- if (serializedArray) search.push(serializedArray);
644
- } else if (typeof value === "object") {
645
- const serializedObject = serializeObjectParam({
646
- allowReserved: options.allowReserved,
647
- explode: true,
648
- name,
649
- style: "deepObject",
650
- value,
651
- ...options.object
652
- });
653
- if (serializedObject) search.push(serializedObject);
654
- } else {
655
- const serializedPrimitive = serializePrimitiveParam({
656
- allowReserved: options.allowReserved,
657
- name,
658
- value
659
- });
660
- if (serializedPrimitive) search.push(serializedPrimitive);
661
- }
662
- }
663
- }
664
- return search.join("&");
665
- };
666
- return querySerializer;
667
- };
668
- var getParseAs = (contentType) => {
669
- if (!contentType) {
670
- return "stream";
671
- }
672
- const cleanContent = contentType.split(";")[0]?.trim();
673
- if (!cleanContent) {
674
- return;
675
- }
676
- if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
677
- return "json";
678
- }
679
- if (cleanContent === "multipart/form-data") {
680
- return "formData";
681
- }
682
- if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
683
- return "blob";
684
- }
685
- if (cleanContent.startsWith("text/")) {
686
- return "text";
687
- }
688
- return;
689
- };
690
- var checkForExistence = (options, name) => {
691
- if (!name) {
692
- return false;
693
- }
694
- if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
695
- return true;
696
- }
697
- return false;
698
- };
699
- var setAuthParams = async ({
700
- security,
701
- ...options
702
- }) => {
703
- for (const auth of security) {
704
- if (checkForExistence(options, auth.name)) {
705
- continue;
706
- }
707
- const token = await getAuthToken(auth, options.auth);
708
- if (!token) {
709
- continue;
710
- }
711
- const name = auth.name ?? "Authorization";
712
- switch (auth.in) {
713
- case "query":
714
- if (!options.query) {
715
- options.query = {};
716
- }
717
- options.query[name] = token;
718
- break;
719
- case "cookie":
720
- options.headers.append("Cookie", `${name}=${token}`);
721
- break;
722
- case "header":
723
- default:
724
- options.headers.set(name, token);
725
- break;
726
- }
727
- }
728
- };
729
- var buildUrl = (options) => getUrl({
730
- baseUrl: options.baseUrl,
731
- path: options.path,
732
- query: options.query,
733
- querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
734
- url: options.url
735
- });
736
- var mergeConfigs = (a, b) => {
737
- const config = { ...a, ...b };
738
- if (config.baseUrl?.endsWith("/")) {
739
- config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
740
- }
741
- config.headers = mergeHeaders(a.headers, b.headers);
742
- return config;
743
- };
744
- var headersEntries = (headers) => {
745
- const entries = [];
746
- headers.forEach((value, key) => {
747
- entries.push([key, value]);
748
- });
749
- return entries;
750
- };
751
- var mergeHeaders = (...headers) => {
752
- const mergedHeaders = new Headers();
753
- for (const header of headers) {
754
- if (!header) {
755
- continue;
756
- }
757
- const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
758
- for (const [key, value] of iterator) {
759
- if (value === null) {
760
- mergedHeaders.delete(key);
761
- } else if (Array.isArray(value)) {
762
- for (const v of value) {
763
- mergedHeaders.append(key, v);
764
- }
765
- } else if (value !== void 0) {
766
- mergedHeaders.set(
767
- key,
768
- typeof value === "object" ? JSON.stringify(value) : value
769
- );
770
- }
771
- }
772
- }
773
- return mergedHeaders;
774
- };
775
- var Interceptors = class {
776
- fns = [];
777
- clear() {
778
- this.fns = [];
779
- }
780
- eject(id) {
781
- const index = this.getInterceptorIndex(id);
782
- if (this.fns[index]) {
783
- this.fns[index] = null;
784
- }
785
- }
786
- exists(id) {
787
- const index = this.getInterceptorIndex(id);
788
- return Boolean(this.fns[index]);
789
- }
790
- getInterceptorIndex(id) {
791
- if (typeof id === "number") {
792
- return this.fns[id] ? id : -1;
793
- }
794
- return this.fns.indexOf(id);
795
- }
796
- update(id, fn) {
797
- const index = this.getInterceptorIndex(id);
798
- if (this.fns[index]) {
799
- this.fns[index] = fn;
800
- return id;
801
- }
802
- return false;
803
- }
804
- use(fn) {
805
- this.fns.push(fn);
806
- return this.fns.length - 1;
807
- }
808
- };
809
- var createInterceptors = () => ({
810
- error: new Interceptors(),
811
- request: new Interceptors(),
812
- response: new Interceptors()
813
- });
814
- var defaultQuerySerializer = createQuerySerializer({
815
- allowReserved: false,
816
- array: {
817
- explode: true,
818
- style: "form"
819
- },
820
- object: {
821
- explode: true,
822
- style: "deepObject"
823
- }
824
- });
825
- var defaultHeaders = {
826
- "Content-Type": "application/json"
827
- };
828
- var createConfig = (override = {}) => ({
829
- ...jsonBodySerializer,
830
- headers: defaultHeaders,
831
- parseAs: "auto",
832
- querySerializer: defaultQuerySerializer,
833
- ...override
834
- });
835
-
836
- // src/client/client.gen.ts
837
- var createClient = (config = {}) => {
838
- let _config = mergeConfigs(createConfig(), config);
839
- const getConfig = () => ({ ..._config });
840
- const setConfig = (config2) => {
841
- _config = mergeConfigs(_config, config2);
842
- return getConfig();
843
- };
844
- const interceptors = createInterceptors();
845
- const beforeRequest = async (options) => {
846
- const opts = {
847
- ..._config,
848
- ...options,
849
- fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
850
- headers: mergeHeaders(_config.headers, options.headers),
851
- serializedBody: void 0
852
- };
853
- if (opts.security) {
854
- await setAuthParams({
855
- ...opts,
856
- security: opts.security
857
- });
858
- }
859
- if (opts.requestValidator) {
860
- await opts.requestValidator(opts);
861
- }
862
- if (opts.body !== void 0 && opts.bodySerializer) {
863
- opts.serializedBody = opts.bodySerializer(opts.body);
864
- }
865
- if (opts.body === void 0 || opts.serializedBody === "") {
866
- opts.headers.delete("Content-Type");
867
- }
868
- const url = buildUrl(opts);
869
- return { opts, url };
870
- };
871
- const request = async (options) => {
872
- const { opts, url } = await beforeRequest(options);
873
- const requestInit = {
874
- redirect: "follow",
875
- ...opts,
876
- body: getValidRequestBody(opts)
877
- };
878
- let request2 = new Request(url, requestInit);
879
- for (const fn of interceptors.request.fns) {
880
- if (fn) {
881
- request2 = await fn(request2, opts);
882
- }
883
- }
884
- const _fetch = opts.fetch;
885
- let response;
886
- try {
887
- response = await _fetch(request2);
888
- } catch (error2) {
889
- let finalError2 = error2;
890
- for (const fn of interceptors.error.fns) {
891
- if (fn) {
892
- finalError2 = await fn(error2, void 0, request2, opts);
893
- }
894
- }
895
- finalError2 = finalError2 || {};
896
- if (opts.throwOnError) {
897
- throw finalError2;
898
- }
899
- return opts.responseStyle === "data" ? void 0 : {
900
- error: finalError2,
901
- request: request2,
902
- response: void 0
903
- };
904
- }
905
- for (const fn of interceptors.response.fns) {
906
- if (fn) {
907
- response = await fn(response, request2, opts);
908
- }
909
- }
910
- const result = {
911
- request: request2,
912
- response
913
- };
914
- if (response.ok) {
915
- const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
916
- if (response.status === 204 || response.headers.get("Content-Length") === "0") {
917
- let emptyData;
918
- switch (parseAs) {
919
- case "arrayBuffer":
920
- case "blob":
921
- case "text":
922
- emptyData = await response[parseAs]();
923
- break;
924
- case "formData":
925
- emptyData = new FormData();
926
- break;
927
- case "stream":
928
- emptyData = response.body;
929
- break;
930
- case "json":
931
- default:
932
- emptyData = {};
933
- break;
934
- }
935
- return opts.responseStyle === "data" ? emptyData : {
936
- data: emptyData,
937
- ...result
938
- };
939
- }
940
- let data;
941
- switch (parseAs) {
942
- case "arrayBuffer":
943
- case "blob":
944
- case "formData":
945
- case "text":
946
- data = await response[parseAs]();
947
- break;
948
- case "json": {
949
- const text = await response.text();
950
- data = text ? JSON.parse(text) : {};
951
- break;
952
- }
953
- case "stream":
954
- return opts.responseStyle === "data" ? response.body : {
955
- data: response.body,
956
- ...result
957
- };
958
- }
959
- if (parseAs === "json") {
960
- if (opts.responseValidator) {
961
- await opts.responseValidator(data);
962
- }
963
- if (opts.responseTransformer) {
964
- data = await opts.responseTransformer(data);
965
- }
966
- }
967
- return opts.responseStyle === "data" ? data : {
968
- data,
969
- ...result
970
- };
971
- }
972
- const textError = await response.text();
973
- let jsonError;
974
- try {
975
- jsonError = JSON.parse(textError);
976
- } catch {
977
- }
978
- const error = jsonError ?? textError;
979
- let finalError = error;
980
- for (const fn of interceptors.error.fns) {
981
- if (fn) {
982
- finalError = await fn(error, response, request2, opts);
983
- }
984
- }
985
- finalError = finalError || {};
986
- if (opts.throwOnError) {
987
- throw finalError;
988
- }
989
- return opts.responseStyle === "data" ? void 0 : {
990
- error: finalError,
991
- ...result
992
- };
993
- };
994
- const makeMethodFn = (method) => (options) => request({ ...options, method });
995
- const makeSseFn = (method) => async (options) => {
996
- const { opts, url } = await beforeRequest(options);
997
- return createSseClient({
998
- ...opts,
999
- body: opts.body,
1000
- headers: opts.headers,
1001
- method,
1002
- onRequest: async (url2, init) => {
1003
- let request2 = new Request(url2, init);
1004
- for (const fn of interceptors.request.fns) {
1005
- if (fn) {
1006
- request2 = await fn(request2, opts);
1007
- }
1008
- }
1009
- return request2;
1010
- },
1011
- serializedBody: getValidRequestBody(opts),
1012
- url
1013
- });
1014
- };
1015
- const _buildUrl = (options) => buildUrl({ ..._config, ...options });
1016
- return {
1017
- buildUrl: _buildUrl,
1018
- connect: makeMethodFn("CONNECT"),
1019
- delete: makeMethodFn("DELETE"),
1020
- get: makeMethodFn("GET"),
1021
- getConfig,
1022
- head: makeMethodFn("HEAD"),
1023
- interceptors,
1024
- options: makeMethodFn("OPTIONS"),
1025
- patch: makeMethodFn("PATCH"),
1026
- post: makeMethodFn("POST"),
1027
- put: makeMethodFn("PUT"),
1028
- request,
1029
- setConfig,
1030
- sse: {
1031
- connect: makeSseFn("CONNECT"),
1032
- delete: makeSseFn("DELETE"),
1033
- get: makeSseFn("GET"),
1034
- head: makeSseFn("HEAD"),
1035
- options: makeSseFn("OPTIONS"),
1036
- patch: makeSseFn("PATCH"),
1037
- post: makeSseFn("POST"),
1038
- put: makeSseFn("PUT"),
1039
- trace: makeSseFn("TRACE")
1040
- },
1041
- trace: makeMethodFn("TRACE")
1042
- };
1043
- };
1044
- // Annotate the CommonJS export names for ESM import in node:
1045
- 0 && (module.exports = {
1046
- buildClientParams,
1047
- createClient,
1048
- createConfig,
1049
- formDataBodySerializer,
1050
- jsonBodySerializer,
1051
- mergeHeaders,
1052
- serializeQueryKeyValue,
1053
- urlSearchParamsBodySerializer
1054
- });