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