@npora/request 0.1.2 → 0.2.1

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 CHANGED
@@ -4,7 +4,10 @@ var RequestError = class extends Error {
4
4
  super(message);
5
5
  this.name = "RequestError";
6
6
  this.code = options.code;
7
- this.status = options.status;
7
+ this.status = options.status ?? options.response?.status;
8
+ this.data = options.data ?? options.response?.data;
9
+ this.response = options.response;
10
+ this.config = options.config ?? options.response?.config;
8
11
  this.cause = options.cause;
9
12
  Object.setPrototypeOf(this, new.target.prototype);
10
13
  }
@@ -19,7 +22,20 @@ function createTimeoutSignal(signal, timeout) {
19
22
  };
20
23
  }
21
24
  const controller = new AbortController();
22
- const timer = setTimeout(() => {
25
+ let timer;
26
+ let onAbort;
27
+ const clear = () => {
28
+ if (timer !== void 0) {
29
+ clearTimeout(timer);
30
+ timer = void 0;
31
+ }
32
+ if (signal && onAbort) {
33
+ signal.removeEventListener("abort", onAbort);
34
+ onAbort = void 0;
35
+ }
36
+ };
37
+ timer = setTimeout(() => {
38
+ clear();
23
39
  controller.abort(
24
40
  new RequestError(`Request timeout after ${timeout}ms`, {
25
41
  code: "TIMEOUT_ERROR"
@@ -28,17 +44,20 @@ function createTimeoutSignal(signal, timeout) {
28
44
  }, timeout);
29
45
  if (signal) {
30
46
  if (signal.aborted) {
47
+ clear();
31
48
  controller.abort(signal.reason);
32
49
  } else {
50
+ onAbort = () => {
51
+ clear();
52
+ controller.abort(
53
+ signal.reason ?? new RequestError("Request aborted", {
54
+ code: "ABORT_ERROR"
55
+ })
56
+ );
57
+ };
33
58
  signal.addEventListener(
34
59
  "abort",
35
- () => {
36
- controller.abort(
37
- signal.reason ?? new RequestError("Request aborted", {
38
- code: "ABORT_ERROR"
39
- })
40
- );
41
- },
60
+ onAbort,
42
61
  {
43
62
  once: true
44
63
  }
@@ -47,9 +66,7 @@ function createTimeoutSignal(signal, timeout) {
47
66
  }
48
67
  return {
49
68
  signal: controller.signal,
50
- clear: () => {
51
- clearTimeout(timer);
52
- }
69
+ clear
53
70
  };
54
71
  }
55
72
  function noop() {
@@ -58,11 +75,15 @@ function noop() {
58
75
  // src/utils/buildRequest.ts
59
76
  function buildRequest(config) {
60
77
  const headers = new Headers(config.headers);
78
+ return buildRequestWithHeaders(config, headers);
79
+ }
80
+ function buildRequestWithHeaders(config, headers) {
61
81
  const body = buildBody(config, headers);
62
82
  const timeoutSignal = createTimeoutSignal(config.signal, config.timeout);
63
83
  return {
64
84
  url: buildURL(config),
65
85
  init: {
86
+ ...config.fetchOptions,
66
87
  method: config.method ?? "GET",
67
88
  headers,
68
89
  body,
@@ -72,8 +93,7 @@ function buildRequest(config) {
72
93
  };
73
94
  }
74
95
  function buildURL(config) {
75
- const baseURL = config.baseURL ?? "";
76
- const url = `${baseURL}${config.url}`;
96
+ const url = joinURL(config.baseURL, config.url);
77
97
  if (!config.query) {
78
98
  return url;
79
99
  }
@@ -81,12 +101,47 @@ function buildURL(config) {
81
101
  if (!query) {
82
102
  return url;
83
103
  }
84
- return url.includes("?") ? `${url}&${query}` : `${url}?${query}`;
104
+ const hashIndex = url.indexOf("#");
105
+ const target = hashIndex === -1 ? url : url.slice(0, hashIndex);
106
+ const hash = hashIndex === -1 ? "" : url.slice(hashIndex);
107
+ const separator = target.includes("?") ? "&" : "?";
108
+ return `${target}${separator}${query}${hash}`;
109
+ }
110
+ function joinURL(baseURL, url) {
111
+ if (!baseURL || isAbsoluteURL(url)) {
112
+ return url;
113
+ }
114
+ if (!url) {
115
+ return baseURL;
116
+ }
117
+ let baseEnd = baseURL.length;
118
+ let urlStart = 0;
119
+ while (baseEnd > 0 && baseURL.charCodeAt(baseEnd - 1) === 47) {
120
+ baseEnd -= 1;
121
+ }
122
+ while (urlStart < url.length && url.charCodeAt(urlStart) === 47) {
123
+ urlStart += 1;
124
+ }
125
+ return `${baseURL.slice(0, baseEnd)}/${url.slice(urlStart)}`;
126
+ }
127
+ function isAbsoluteURL(url) {
128
+ if (url.startsWith("//")) {
129
+ return true;
130
+ }
131
+ const colon = url.indexOf(":");
132
+ if (colon <= 0) {
133
+ return false;
134
+ }
135
+ return /^[a-z][a-z\d+\-.]*$/i.test(
136
+ url.slice(0, colon)
137
+ );
85
138
  }
86
139
  function stringifyQuery(query) {
87
140
  const params = new URLSearchParams();
88
- for (const [key, value] of Object.entries(query)) {
89
- appendQuery(params, key, value);
141
+ for (const key in query) {
142
+ if (Object.prototype.hasOwnProperty.call(query, key)) {
143
+ appendQuery(params, key, query[key]);
144
+ }
90
145
  }
91
146
  return params.toString();
92
147
  }
@@ -96,7 +151,9 @@ function appendQuery(params, key, value) {
96
151
  }
97
152
  if (Array.isArray(value)) {
98
153
  for (const item of value) {
99
- appendQuery(params, key, item);
154
+ if (item !== null && item !== void 0) {
155
+ params.append(key, String(item));
156
+ }
100
157
  }
101
158
  return;
102
159
  }
@@ -131,8 +188,10 @@ function buildURLSearchParams(form) {
131
188
  return form;
132
189
  }
133
190
  const params = new URLSearchParams();
134
- for (const [key, value] of Object.entries(form)) {
135
- appendQuery(params, key, value);
191
+ for (const key in form) {
192
+ if (Object.prototype.hasOwnProperty.call(form, key)) {
193
+ appendQuery(params, key, form[key]);
194
+ }
136
195
  }
137
196
  return params;
138
197
  }
@@ -141,8 +200,10 @@ function buildFormData(input) {
141
200
  return input;
142
201
  }
143
202
  const formData = new FormData();
144
- for (const [key, value] of Object.entries(input)) {
145
- appendFormDataValue(formData, key, value);
203
+ for (const key in input) {
204
+ if (Object.prototype.hasOwnProperty.call(input, key)) {
205
+ appendFormDataValue(formData, key, input[key]);
206
+ }
146
207
  }
147
208
  return formData;
148
209
  }
@@ -173,7 +234,7 @@ function isPlainObject(value) {
173
234
 
174
235
  // src/utils/parseResponse.ts
175
236
  async function parseResponse(response, config) {
176
- if (response.status === 204 || response.status === 205) {
237
+ if (config.method === "HEAD" || response.status === 204 || response.status === 205) {
177
238
  return void 0;
178
239
  }
179
240
  const responseType = config.responseType ?? detectResponseType(response);
@@ -196,6 +257,7 @@ async function parseResponse(response, config) {
196
257
  throw new RequestError("Failed to parse response", {
197
258
  code: "PARSER_ERROR",
198
259
  status: response.status,
260
+ config,
199
261
  cause: error
200
262
  });
201
263
  }
@@ -208,21 +270,104 @@ function detectResponseType(response) {
208
270
  return "text";
209
271
  }
210
272
 
273
+ // src/utils/validateRequestConfig.ts
274
+ var BODY_FIELDS = [
275
+ "body",
276
+ "json",
277
+ "form",
278
+ "formData"
279
+ ];
280
+ function validateRequestConfig(config) {
281
+ validateURL(config);
282
+ validateTimeout(config);
283
+ const headers = validateHeaders(config);
284
+ validateBody(config);
285
+ return headers;
286
+ }
287
+ function validateURL(config) {
288
+ if (typeof config.url !== "string") {
289
+ throw configError("Request url must be a string", config);
290
+ }
291
+ }
292
+ function validateTimeout(config) {
293
+ if (config.timeout === void 0) {
294
+ return;
295
+ }
296
+ if (!Number.isFinite(config.timeout) || config.timeout < 0) {
297
+ throw configError(
298
+ "Request timeout must be a finite, non-negative number",
299
+ config
300
+ );
301
+ }
302
+ }
303
+ function validateHeaders(config) {
304
+ try {
305
+ return new Headers(config.headers);
306
+ } catch (error) {
307
+ throw configError("Request headers are invalid", config, error);
308
+ }
309
+ }
310
+ function validateBody(config) {
311
+ let activeField;
312
+ for (const key of BODY_FIELDS) {
313
+ const value = config[key];
314
+ if (value === void 0 || value === null) {
315
+ continue;
316
+ }
317
+ if (activeField) {
318
+ const activeFields = BODY_FIELDS.filter((field) => {
319
+ const fieldValue = config[field];
320
+ return fieldValue !== void 0 && fieldValue !== null;
321
+ });
322
+ throw configError(
323
+ `Request body options are mutually exclusive: ${activeFields.join(", ")}`,
324
+ config
325
+ );
326
+ }
327
+ activeField = key;
328
+ }
329
+ const method = config.method ?? "GET";
330
+ if (activeField && (method === "GET" || method === "HEAD")) {
331
+ throw configError(
332
+ `${method} requests cannot include a body`,
333
+ config
334
+ );
335
+ }
336
+ }
337
+ function configError(message, config, cause) {
338
+ return new RequestError(message, {
339
+ code: "CONFIG_ERROR",
340
+ config,
341
+ cause
342
+ });
343
+ }
344
+
211
345
  // src/adapters/FetchAdapter.ts
212
346
  var FetchAdapter = class {
213
347
  async request(config) {
214
- const request = buildRequest(config);
348
+ return this.execute(
349
+ config,
350
+ validateRequestConfig(config),
351
+ true
352
+ );
353
+ }
354
+ requestValidated(config, validatedHeaders, preserveRaw = true) {
355
+ return this.execute(
356
+ config,
357
+ validatedHeaders,
358
+ preserveRaw
359
+ );
360
+ }
361
+ async execute(config, headers, preserveRaw) {
362
+ let request;
215
363
  try {
364
+ request = buildRequestWithHeaders(config, headers);
216
365
  const response = await fetch(request.url, request.init);
217
366
  const validateStatus = config.validateStatus ?? defaultValidateStatus;
218
- if (!validateStatus(response.status)) {
219
- throw new RequestError(response.statusText || "Request failed", {
220
- code: "HTTP_ERROR",
221
- status: response.status
222
- });
223
- }
224
- const data = await parseResponse(response, config);
225
- return {
367
+ const validStatus = validateStatus(response.status);
368
+ const parseTarget = config.responseType === "stream" || !preserveRaw && validStatus ? response : response.clone();
369
+ const data = await parseResponse(parseTarget, config);
370
+ const nporaResponse = {
226
371
  data,
227
372
  status: response.status,
228
373
  statusText: response.statusText,
@@ -230,27 +375,50 @@ var FetchAdapter = class {
230
375
  config,
231
376
  raw: response
232
377
  };
378
+ if (!validStatus) {
379
+ throw new RequestError(response.statusText || "Request failed", {
380
+ code: "HTTP_ERROR",
381
+ response: nporaResponse
382
+ });
383
+ }
384
+ return nporaResponse;
233
385
  } catch (error) {
234
386
  if (error instanceof RequestError) {
235
387
  throw error;
236
388
  }
389
+ if (!request) {
390
+ throw new RequestError("Failed to build request", {
391
+ code: "CONFIG_ERROR",
392
+ config,
393
+ cause: error
394
+ });
395
+ }
237
396
  const signal = request.init.signal;
238
397
  const reason = signal?.reason;
239
398
  if (signal?.aborted) {
240
399
  if (reason instanceof RequestError) {
241
- throw reason;
400
+ throw new RequestError(reason.message, {
401
+ code: reason.code,
402
+ status: reason.status,
403
+ data: reason.data,
404
+ response: reason.response,
405
+ config: reason.config ?? config,
406
+ cause: reason
407
+ });
242
408
  }
243
409
  throw new RequestError("Request aborted", {
244
410
  code: "ABORT_ERROR",
411
+ config,
245
412
  cause: error
246
413
  });
247
414
  }
248
415
  throw new RequestError("Network request failed", {
249
416
  code: "NETWORK_ERROR",
417
+ config,
250
418
  cause: error
251
419
  });
252
420
  } finally {
253
- request.clear();
421
+ request?.clear();
254
422
  }
255
423
  }
256
424
  };
@@ -298,13 +466,94 @@ var ConfigMerger = class {
298
466
  * Merge request configuration.
299
467
  */
300
468
  static merge(defaults, config) {
301
- return {
469
+ return this.mergeConfig(defaults, config);
470
+ }
471
+ /**
472
+ * Merge two sets of client defaults.
473
+ */
474
+ static mergeDefaults(defaults, overrides) {
475
+ return this.mergeConfig(defaults, overrides);
476
+ }
477
+ static mergeConfig(defaults, config) {
478
+ const result = {
302
479
  ...defaults,
303
- ...config,
304
- headers: this.mergeHeaders(
480
+ ...config
481
+ };
482
+ if (defaults.fetchOptions || config.fetchOptions) {
483
+ result.fetchOptions = this.mergeFetchOptions(
484
+ defaults.fetchOptions,
485
+ config.fetchOptions
486
+ );
487
+ }
488
+ if (defaults.headers || config.headers) {
489
+ result.headers = this.mergeHeaders(
305
490
  defaults.headers,
306
491
  config.headers
307
- )
492
+ );
493
+ }
494
+ if (defaults.query || config.query) {
495
+ result.query = this.mergeObject(
496
+ defaults.query,
497
+ config.query
498
+ );
499
+ }
500
+ if (defaults.extensions || config.extensions) {
501
+ result.extensions = this.mergeExtensions(
502
+ defaults.extensions,
503
+ config.extensions
504
+ );
505
+ }
506
+ if (defaults.retry !== void 0 || config.retry !== void 0) {
507
+ result.retry = this.mergeRetry(
508
+ defaults.retry,
509
+ config.retry
510
+ );
511
+ }
512
+ if (defaults.cache || config.cache) {
513
+ result.cache = this.mergeObject(
514
+ defaults.cache,
515
+ config.cache
516
+ );
517
+ }
518
+ if (defaults.auth || config.auth) {
519
+ result.auth = this.mergeObject(
520
+ defaults.auth,
521
+ config.auth
522
+ );
523
+ }
524
+ if (defaults.logger || config.logger) {
525
+ result.logger = this.mergeObject(
526
+ defaults.logger,
527
+ config.logger
528
+ );
529
+ }
530
+ if (defaults.upload || config.upload) {
531
+ result.upload = this.mergeObject(
532
+ defaults.upload,
533
+ config.upload
534
+ );
535
+ }
536
+ if (defaults.download || config.download) {
537
+ result.download = this.mergeObject(
538
+ defaults.download,
539
+ config.download
540
+ );
541
+ }
542
+ if (this.hasBodyConfig(defaults) || this.hasBodyConfig(config)) {
543
+ Object.assign(
544
+ result,
545
+ this.mergeBodyConfig(defaults, config)
546
+ );
547
+ }
548
+ return result;
549
+ }
550
+ static mergeFetchOptions(defaults, options) {
551
+ if (!defaults && !options) {
552
+ return void 0;
553
+ }
554
+ return {
555
+ ...defaults,
556
+ ...options
308
557
  };
309
558
  }
310
559
  /**
@@ -314,31 +563,135 @@ var ConfigMerger = class {
314
563
  if (!defaults && !headers) {
315
564
  return void 0;
316
565
  }
317
- return {
318
- ...this.normalizeHeaders(defaults),
319
- ...this.normalizeHeaders(headers)
320
- };
566
+ const result = {};
567
+ this.appendHeaders(result, defaults);
568
+ this.appendHeaders(result, headers);
569
+ return result;
321
570
  }
322
- /**
323
- * Normalize headers.
324
- */
325
- static normalizeHeaders(headers) {
571
+ static appendHeaders(result, headers) {
326
572
  if (!headers) {
327
- return {};
573
+ return;
328
574
  }
329
575
  if (headers instanceof Headers) {
330
- const result = {};
331
576
  headers.forEach((value, key) => {
332
- result[key] = value;
577
+ setHeader(result, key, value);
333
578
  });
334
- return result;
579
+ return;
335
580
  }
336
581
  if (Array.isArray(headers)) {
337
- return Object.fromEntries(headers);
582
+ for (const [key, value] of headers) {
583
+ setHeader(
584
+ result,
585
+ key.toLowerCase(),
586
+ String(value)
587
+ );
588
+ }
589
+ return;
590
+ }
591
+ for (const key in headers) {
592
+ if (Object.prototype.hasOwnProperty.call(headers, key)) {
593
+ setHeader(
594
+ result,
595
+ key.toLowerCase(),
596
+ String(headers[key])
597
+ );
598
+ }
599
+ }
600
+ }
601
+ static mergeObject(defaults, value) {
602
+ if (!defaults && !value) {
603
+ return void 0;
604
+ }
605
+ return {
606
+ ...defaults,
607
+ ...value
608
+ };
609
+ }
610
+ static mergeRetry(defaults, retry) {
611
+ if (retry === void 0) {
612
+ return defaults;
613
+ }
614
+ if (typeof retry === "number") {
615
+ return retry;
616
+ }
617
+ const normalizedDefaults = typeof defaults === "number" ? {
618
+ retries: defaults
619
+ } : defaults;
620
+ return {
621
+ ...normalizedDefaults,
622
+ ...retry
623
+ };
624
+ }
625
+ static mergeExtensions(defaults, extensions) {
626
+ if (!defaults && !extensions) {
627
+ return void 0;
628
+ }
629
+ const result = {
630
+ ...defaults,
631
+ ...extensions
632
+ };
633
+ for (const key in extensions) {
634
+ if (!Object.prototype.hasOwnProperty.call(
635
+ extensions,
636
+ key
637
+ )) {
638
+ continue;
639
+ }
640
+ const defaultValue = defaults?.[key];
641
+ const requestValue = extensions?.[key];
642
+ if (isPlainObject2(defaultValue) && isPlainObject2(requestValue)) {
643
+ result[key] = {
644
+ ...defaultValue,
645
+ ...requestValue
646
+ };
647
+ }
648
+ }
649
+ return result;
650
+ }
651
+ static hasBodyConfig(config) {
652
+ return config.body !== void 0 || config.json !== void 0 || config.form !== void 0 || config.formData !== void 0 || Object.prototype.hasOwnProperty.call(config, "body") || Object.prototype.hasOwnProperty.call(config, "json") || Object.prototype.hasOwnProperty.call(config, "form") || Object.prototype.hasOwnProperty.call(config, "formData");
653
+ }
654
+ static mergeBodyConfig(defaults, config) {
655
+ const keys = [
656
+ "body",
657
+ "json",
658
+ "form",
659
+ "formData"
660
+ ];
661
+ const hasRequestBodyConfig = keys.some((key) => {
662
+ return Object.prototype.hasOwnProperty.call(config, key);
663
+ });
664
+ if (!hasRequestBodyConfig) {
665
+ return {
666
+ body: defaults.body,
667
+ json: defaults.json,
668
+ form: defaults.form,
669
+ formData: defaults.formData
670
+ };
338
671
  }
339
- return headers;
672
+ return {
673
+ body: config.body,
674
+ json: config.json,
675
+ form: config.form,
676
+ formData: config.formData
677
+ };
340
678
  }
341
679
  };
680
+ function isPlainObject2(value) {
681
+ return Object.prototype.toString.call(value) === "[object Object]";
682
+ }
683
+ function setHeader(headers, key, value) {
684
+ if (key === "__proto__") {
685
+ Object.defineProperty(headers, key, {
686
+ value,
687
+ enumerable: true,
688
+ configurable: true,
689
+ writable: true
690
+ });
691
+ return;
692
+ }
693
+ headers[key] = value;
694
+ }
342
695
 
343
696
  // src/core/RequestContext.ts
344
697
  var RequestContext = class {
@@ -355,36 +708,75 @@ var Pipeline = class {
355
708
  this.interceptors = interceptors;
356
709
  this.hooks = hooks;
357
710
  }
358
- async execute(config) {
711
+ async execute(config, preserveRaw = true) {
359
712
  const context = new RequestContext(config);
713
+ let validatedHeaders;
360
714
  try {
361
- context.config = await this.interceptors.request.run(context.config);
362
- await this.hooks.runRequest(context);
715
+ try {
716
+ if (this.interceptors.request.active) {
717
+ context.config = await this.interceptors.request.run(
718
+ context.config
719
+ );
720
+ }
721
+ let headers = validateRequestConfig(context.config);
722
+ if (this.hooks.hasRequestHooks) {
723
+ await this.hooks.runRequest(context);
724
+ headers = validateRequestConfig(context.config);
725
+ }
726
+ validatedHeaders = headers;
727
+ } catch (error) {
728
+ return this.fail(context, error);
729
+ }
363
730
  if (context.response) {
364
- return context.response;
731
+ try {
732
+ return await this.processResponse(context);
733
+ } catch (error) {
734
+ return this.fail(context, error);
735
+ }
365
736
  }
366
737
  let attempt = 0;
367
738
  while (true) {
368
739
  try {
369
- context.response = await this.adapter.request(context.config);
370
- context.response = await this.interceptors.response.run(
371
- context.response
740
+ const headers = validatedHeaders;
741
+ validatedHeaders = void 0;
742
+ context.response = headers && this.adapter.requestValidated ? await this.adapter.requestValidated(
743
+ context.config,
744
+ headers,
745
+ preserveRaw || this.hooks.hasResponseHooks || this.interceptors.response.active
746
+ ) : await this.adapter.request(
747
+ context.config
372
748
  );
373
- await this.hooks.runResponse(context);
374
- return context.response;
749
+ return await this.processResponse(context);
375
750
  } catch (error) {
376
- context.error = error;
377
- await this.hooks.runError(context);
378
- const decision = await this.hooks.resolveRetry(context, attempt);
751
+ const errorHooksSucceeded = await this.notifyError(
752
+ context,
753
+ error
754
+ );
755
+ if (!errorHooksSucceeded) {
756
+ return this.fail(context, context.error, false);
757
+ }
758
+ if (!this.hooks.hasRetryHooks) {
759
+ return this.fail(context, context.error, false);
760
+ }
761
+ let decision;
762
+ try {
763
+ decision = await this.hooks.resolveRetry(context, attempt);
764
+ } catch (retryError) {
765
+ return this.fail(context, retryError);
766
+ }
379
767
  if (!decision.retry) {
380
- context.error = await this.interceptors.error.run(context.error);
381
- throw context.error;
768
+ return this.fail(context, context.error, false);
382
769
  }
383
770
  context.error = void 0;
384
771
  context.response = void 0;
385
772
  attempt += 1;
386
- if (decision.delay && decision.delay > 0) {
387
- await sleep(decision.delay);
773
+ try {
774
+ await waitForRetry(
775
+ decision.delay ?? 0,
776
+ context.config
777
+ );
778
+ } catch (waitError) {
779
+ return this.fail(context, waitError);
388
780
  }
389
781
  }
390
782
  }
@@ -392,10 +784,85 @@ var Pipeline = class {
392
784
  context.endTime = Date.now();
393
785
  }
394
786
  }
787
+ async processResponse(context) {
788
+ if (this.hooks.hasResponseHooks) {
789
+ await this.hooks.runResponse(context);
790
+ }
791
+ if (this.interceptors.response.active) {
792
+ context.response = await this.interceptors.response.run(
793
+ context.response
794
+ );
795
+ }
796
+ return context.response;
797
+ }
798
+ async notifyError(context, error) {
799
+ context.error = error;
800
+ if (this.hooks.hasErrorHooks) {
801
+ try {
802
+ await this.hooks.runError(context);
803
+ return true;
804
+ } catch (hookError) {
805
+ context.error = hookError;
806
+ return false;
807
+ }
808
+ }
809
+ return true;
810
+ }
811
+ async fail(context, error, notifyHooks = true) {
812
+ if (notifyHooks) {
813
+ await this.notifyError(context, error);
814
+ } else {
815
+ context.error = error;
816
+ }
817
+ if (this.interceptors.error.active) {
818
+ context.error = await this.interceptors.error.run(
819
+ context.error
820
+ );
821
+ }
822
+ throw context.error;
823
+ }
395
824
  };
396
- function sleep(milliseconds) {
397
- return new Promise((resolve) => {
398
- setTimeout(resolve, milliseconds);
825
+ function waitForRetry(milliseconds, config) {
826
+ const signal = config.signal;
827
+ if (signal?.aborted) {
828
+ return Promise.reject(createAbortError(signal.reason, config));
829
+ }
830
+ if (milliseconds <= 0) {
831
+ return Promise.resolve();
832
+ }
833
+ return new Promise((resolve, reject) => {
834
+ const timer = setTimeout(() => {
835
+ cleanup();
836
+ resolve();
837
+ }, milliseconds);
838
+ const onAbort = () => {
839
+ clearTimeout(timer);
840
+ cleanup();
841
+ reject(createAbortError(signal?.reason, config));
842
+ };
843
+ const cleanup = () => {
844
+ signal?.removeEventListener("abort", onAbort);
845
+ };
846
+ signal?.addEventListener("abort", onAbort, {
847
+ once: true
848
+ });
849
+ });
850
+ }
851
+ function createAbortError(reason, config) {
852
+ if (reason instanceof RequestError) {
853
+ return new RequestError(reason.message, {
854
+ code: reason.code,
855
+ status: reason.status,
856
+ data: reason.data,
857
+ response: reason.response,
858
+ config: reason.config ?? config,
859
+ cause: reason
860
+ });
861
+ }
862
+ return new RequestError("Request aborted during retry delay", {
863
+ code: "ABORT_ERROR",
864
+ config,
865
+ cause: reason
399
866
  });
400
867
  }
401
868
 
@@ -404,64 +871,100 @@ var InterceptorManager = class {
404
871
  constructor() {
405
872
  this.id = 0;
406
873
  this.interceptors = /* @__PURE__ */ new Map();
874
+ this.orderedInterceptors = [];
407
875
  }
408
- use(interceptor) {
876
+ get active() {
877
+ return this.orderedInterceptors.length > 0;
878
+ }
879
+ use(interceptor, options = {}) {
409
880
  const id = this.id++;
410
- this.interceptors.set(id, interceptor);
881
+ this.interceptors.set(id, {
882
+ id,
883
+ interceptor,
884
+ priority: normalizePriority(options.priority)
885
+ });
886
+ this.refreshOrder();
411
887
  return id;
412
888
  }
413
889
  eject(id) {
414
- this.interceptors.delete(id);
890
+ if (this.interceptors.delete(id)) {
891
+ this.refreshOrder();
892
+ }
415
893
  }
416
894
  clear() {
417
895
  this.interceptors.clear();
896
+ this.orderedInterceptors = [];
418
897
  }
419
898
  async run(value) {
420
899
  let result = value;
421
- for (const interceptor of this.interceptors.values()) {
422
- result = await interceptor(result);
900
+ for (const entry of this.orderedInterceptors) {
901
+ result = await entry.interceptor(result);
423
902
  }
424
903
  return result;
425
904
  }
905
+ refreshOrder() {
906
+ this.orderedInterceptors = [
907
+ ...this.interceptors.values()
908
+ ].sort(
909
+ (first, second) => {
910
+ return second.priority - first.priority || first.id - second.id;
911
+ }
912
+ );
913
+ }
426
914
  };
915
+ function normalizePriority(priority) {
916
+ return Number.isFinite(priority) ? priority ?? 0 : 0;
917
+ }
427
918
 
428
919
  // src/interceptors/PluginHooks.ts
429
920
  var PluginHooks = class {
430
921
  constructor() {
431
- this.requestHooks = [];
432
- this.responseHooks = [];
433
- this.errorHooks = [];
434
- this.retryHooks = [];
922
+ this.requestHooks = new HookRegistry();
923
+ this.responseHooks = new HookRegistry();
924
+ this.errorHooks = new HookRegistry();
925
+ this.retryHooks = new HookRegistry();
926
+ }
927
+ get hasRequestHooks() {
928
+ return this.requestHooks.active;
435
929
  }
436
- onRequest(hook) {
437
- this.requestHooks.push(hook);
930
+ get hasResponseHooks() {
931
+ return this.responseHooks.active;
438
932
  }
439
- onResponse(hook) {
440
- this.responseHooks.push(hook);
933
+ get hasErrorHooks() {
934
+ return this.errorHooks.active;
441
935
  }
442
- onError(hook) {
443
- this.errorHooks.push(hook);
936
+ get hasRetryHooks() {
937
+ return this.retryHooks.active;
444
938
  }
445
- onRetry(hook) {
446
- this.retryHooks.push(hook);
939
+ onRequest(hook, options = {}) {
940
+ return this.requestHooks.register(hook, options);
941
+ }
942
+ onResponse(hook, options = {}) {
943
+ return this.responseHooks.register(hook, options);
944
+ }
945
+ onError(hook, options = {}) {
946
+ return this.errorHooks.register(hook, options);
947
+ }
948
+ onRetry(hook, options = {}) {
949
+ return this.retryHooks.register(hook, options);
447
950
  }
448
951
  async runRequest(context) {
449
- for (const hook of this.requestHooks) {
952
+ for (const hook of this.requestHooks.values()) {
450
953
  await hook(context);
451
954
  }
452
955
  }
453
956
  async runResponse(context) {
454
- for (const hook of this.responseHooks) {
957
+ for (const hook of this.responseHooks.values()) {
455
958
  await hook(context);
456
959
  }
457
960
  }
458
961
  async runError(context) {
459
- for (const hook of this.errorHooks) {
962
+ for (const hook of this.errorHooks.values()) {
460
963
  await hook(context);
461
964
  }
462
965
  }
463
966
  async resolveRetry(context, attempt) {
464
- for (const hook of this.retryHooks) {
967
+ for (const hook of this.retryHooks.values()) {
465
968
  const decision = await hook(context, attempt);
466
969
  if (decision) {
467
970
  return decision;
@@ -473,11 +976,175 @@ var PluginHooks = class {
473
976
  };
474
977
  }
475
978
  };
979
+ var HookRegistry = class {
980
+ constructor() {
981
+ this.id = 0;
982
+ this.hooks = /* @__PURE__ */ new Map();
983
+ this.orderedHooks = [];
984
+ }
985
+ get active() {
986
+ return this.orderedHooks.length > 0;
987
+ }
988
+ register(hook, options) {
989
+ const id = this.id++;
990
+ this.hooks.set(id, {
991
+ id,
992
+ hook,
993
+ priority: normalizePriority2(options.priority)
994
+ });
995
+ this.refreshOrder();
996
+ return () => {
997
+ if (this.hooks.delete(id)) {
998
+ this.refreshOrder();
999
+ }
1000
+ };
1001
+ }
1002
+ values() {
1003
+ return this.orderedHooks;
1004
+ }
1005
+ refreshOrder() {
1006
+ this.orderedHooks = [
1007
+ ...this.hooks.values()
1008
+ ].sort((first, second) => {
1009
+ return second.priority - first.priority || first.id - second.id;
1010
+ }).map((entry) => entry.hook);
1011
+ }
1012
+ };
1013
+ function normalizePriority2(priority) {
1014
+ return Number.isFinite(priority) ? priority ?? 0 : 0;
1015
+ }
1016
+
1017
+ // src/plugins/PluginError.ts
1018
+ var PluginError = class extends Error {
1019
+ constructor(message, options) {
1020
+ super(message);
1021
+ this.name = "PluginError";
1022
+ this.code = options.code;
1023
+ this.plugin = options.plugin;
1024
+ this.relatedPlugin = options.relatedPlugin;
1025
+ Object.setPrototypeOf(this, new.target.prototype);
1026
+ }
1027
+ };
1028
+
1029
+ // src/plugins/PluginScope.ts
1030
+ function createPluginScope(interceptors, hooks, priority = 0) {
1031
+ const cleanups = [];
1032
+ const context = {
1033
+ interceptors: {
1034
+ request: createScopedInterceptor(
1035
+ interceptors.request,
1036
+ priority,
1037
+ cleanups
1038
+ ),
1039
+ response: createScopedInterceptor(
1040
+ interceptors.response,
1041
+ priority,
1042
+ cleanups
1043
+ ),
1044
+ error: createScopedInterceptor(
1045
+ interceptors.error,
1046
+ priority,
1047
+ cleanups
1048
+ )
1049
+ },
1050
+ hooks: createScopedHooks(hooks, priority, cleanups)
1051
+ };
1052
+ return {
1053
+ context,
1054
+ addCleanup(cleanup) {
1055
+ cleanups.push(once(cleanup));
1056
+ },
1057
+ cleanup() {
1058
+ let firstError;
1059
+ for (const cleanup of [...cleanups].reverse()) {
1060
+ try {
1061
+ cleanup();
1062
+ } catch (error) {
1063
+ firstError ?? (firstError = error);
1064
+ }
1065
+ }
1066
+ cleanups.length = 0;
1067
+ if (firstError !== void 0) {
1068
+ throw firstError;
1069
+ }
1070
+ }
1071
+ };
1072
+ }
1073
+ function createScopedInterceptor(manager, pluginPriority, cleanups) {
1074
+ const ids = /* @__PURE__ */ new Set();
1075
+ cleanups.push(() => {
1076
+ for (const id of ids) {
1077
+ manager.eject(id);
1078
+ }
1079
+ ids.clear();
1080
+ });
1081
+ return {
1082
+ use(interceptor, options = {}) {
1083
+ const id = manager.use(interceptor, {
1084
+ priority: options.priority ?? pluginPriority
1085
+ });
1086
+ ids.add(id);
1087
+ return id;
1088
+ },
1089
+ eject(id) {
1090
+ manager.eject(id);
1091
+ ids.delete(id);
1092
+ }
1093
+ };
1094
+ }
1095
+ function createScopedHooks(hooks, pluginPriority, cleanups) {
1096
+ return {
1097
+ onRequest(hook, options) {
1098
+ return trackHook(
1099
+ hooks.onRequest(hook, withPriority(options, pluginPriority)),
1100
+ cleanups
1101
+ );
1102
+ },
1103
+ onResponse(hook, options) {
1104
+ return trackHook(
1105
+ hooks.onResponse(hook, withPriority(options, pluginPriority)),
1106
+ cleanups
1107
+ );
1108
+ },
1109
+ onError(hook, options) {
1110
+ return trackHook(
1111
+ hooks.onError(hook, withPriority(options, pluginPriority)),
1112
+ cleanups
1113
+ );
1114
+ },
1115
+ onRetry(hook, options) {
1116
+ return trackHook(
1117
+ hooks.onRetry(hook, withPriority(options, pluginPriority)),
1118
+ cleanups
1119
+ );
1120
+ }
1121
+ };
1122
+ }
1123
+ function trackHook(dispose, cleanups) {
1124
+ const trackedDispose = once(dispose);
1125
+ cleanups.push(trackedDispose);
1126
+ return trackedDispose;
1127
+ }
1128
+ function withPriority(options, pluginPriority) {
1129
+ return {
1130
+ priority: options?.priority ?? pluginPriority
1131
+ };
1132
+ }
1133
+ function once(cleanup) {
1134
+ let active = true;
1135
+ return () => {
1136
+ if (!active) {
1137
+ return;
1138
+ }
1139
+ active = false;
1140
+ cleanup();
1141
+ };
1142
+ }
476
1143
 
477
1144
  // src/client/Client.ts
478
- var Client = class {
1145
+ var Client = class _Client {
479
1146
  constructor(options = {}) {
480
- this.installedPlugins = /* @__PURE__ */ new Set();
1147
+ this.installedPlugins = /* @__PURE__ */ new Map();
481
1148
  this.hooks = new PluginHooks();
482
1149
  this.interceptors = {
483
1150
  request: new InterceptorManager(),
@@ -486,24 +1153,95 @@ var Client = class {
486
1153
  };
487
1154
  const { adapter = new FetchAdapter(), ...defaults } = options;
488
1155
  this.defaults = defaults;
1156
+ this.adapter = adapter;
489
1157
  this.pipeline = this.createPipeline(adapter);
490
1158
  }
1159
+ /**
1160
+ * Create an isolated client that inherits this client's defaults.
1161
+ */
1162
+ extend(options = {}) {
1163
+ const {
1164
+ adapter = this.adapter,
1165
+ ...overrides
1166
+ } = options;
1167
+ const defaults = ConfigMerger.mergeDefaults(
1168
+ this.defaults,
1169
+ overrides
1170
+ );
1171
+ return new _Client({
1172
+ ...defaults,
1173
+ adapter
1174
+ });
1175
+ }
491
1176
  use(plugin) {
492
1177
  if (this.installedPlugins.has(plugin.name)) {
493
1178
  return this;
494
1179
  }
495
- plugin.install({
496
- interceptors: this.interceptors,
497
- hooks: this.hooks
498
- });
499
- this.installedPlugins.add(plugin.name);
1180
+ this.validatePlugin(plugin);
1181
+ const scope = createPluginScope(
1182
+ this.interceptors,
1183
+ this.hooks,
1184
+ plugin.priority
1185
+ );
1186
+ try {
1187
+ const cleanup = plugin.install(scope.context);
1188
+ if (cleanup) {
1189
+ scope.addCleanup(cleanup);
1190
+ }
1191
+ this.installedPlugins.set(plugin.name, {
1192
+ plugin,
1193
+ cleanup: scope.cleanup
1194
+ });
1195
+ } catch (error) {
1196
+ try {
1197
+ scope.cleanup();
1198
+ } catch {
1199
+ }
1200
+ throw error;
1201
+ }
1202
+ return this;
1203
+ }
1204
+ unuse(pluginName) {
1205
+ const installed = this.installedPlugins.get(pluginName);
1206
+ if (!installed) {
1207
+ return this;
1208
+ }
1209
+ const dependent = this.findDependent(pluginName);
1210
+ if (dependent) {
1211
+ throw new PluginError(
1212
+ `Cannot remove plugin "${pluginName}" while "${dependent}" depends on it`,
1213
+ {
1214
+ code: "DEPENDENCY_IN_USE",
1215
+ plugin: pluginName,
1216
+ relatedPlugin: dependent
1217
+ }
1218
+ );
1219
+ }
1220
+ try {
1221
+ installed.cleanup();
1222
+ } finally {
1223
+ this.installedPlugins.delete(pluginName);
1224
+ }
500
1225
  return this;
501
1226
  }
1227
+ hasPlugin(pluginName) {
1228
+ return this.installedPlugins.has(pluginName);
1229
+ }
502
1230
  async request(config) {
503
- const mergedConfig = ConfigMerger.merge(this.defaults, config);
504
- const response = await this.pipeline.execute(mergedConfig);
1231
+ const mergedConfig = ConfigMerger.merge(
1232
+ this.defaults,
1233
+ config
1234
+ );
1235
+ const response = await this.pipeline.execute(
1236
+ mergedConfig,
1237
+ false
1238
+ );
505
1239
  return response.data;
506
1240
  }
1241
+ async requestResponse(config) {
1242
+ const mergedConfig = ConfigMerger.merge(this.defaults, config);
1243
+ return this.pipeline.execute(mergedConfig);
1244
+ }
507
1245
  get(url, config = {}) {
508
1246
  return this.request({
509
1247
  ...config,
@@ -511,6 +1249,13 @@ var Client = class {
511
1249
  method: "GET"
512
1250
  });
513
1251
  }
1252
+ getResponse(url, config = {}) {
1253
+ return this.requestResponse({
1254
+ ...config,
1255
+ url,
1256
+ method: "GET"
1257
+ });
1258
+ }
514
1259
  post(url, config = {}) {
515
1260
  return this.request({
516
1261
  ...config,
@@ -518,6 +1263,13 @@ var Client = class {
518
1263
  method: "POST"
519
1264
  });
520
1265
  }
1266
+ postResponse(url, config = {}) {
1267
+ return this.requestResponse({
1268
+ ...config,
1269
+ url,
1270
+ method: "POST"
1271
+ });
1272
+ }
521
1273
  put(url, config = {}) {
522
1274
  return this.request({
523
1275
  ...config,
@@ -525,6 +1277,13 @@ var Client = class {
525
1277
  method: "PUT"
526
1278
  });
527
1279
  }
1280
+ putResponse(url, config = {}) {
1281
+ return this.requestResponse({
1282
+ ...config,
1283
+ url,
1284
+ method: "PUT"
1285
+ });
1286
+ }
528
1287
  patch(url, config = {}) {
529
1288
  return this.request({
530
1289
  ...config,
@@ -532,6 +1291,13 @@ var Client = class {
532
1291
  method: "PATCH"
533
1292
  });
534
1293
  }
1294
+ patchResponse(url, config = {}) {
1295
+ return this.requestResponse({
1296
+ ...config,
1297
+ url,
1298
+ method: "PATCH"
1299
+ });
1300
+ }
535
1301
  delete(url, config = {}) {
536
1302
  return this.request({
537
1303
  ...config,
@@ -539,9 +1305,92 @@ var Client = class {
539
1305
  method: "DELETE"
540
1306
  });
541
1307
  }
1308
+ deleteResponse(url, config = {}) {
1309
+ return this.requestResponse({
1310
+ ...config,
1311
+ url,
1312
+ method: "DELETE"
1313
+ });
1314
+ }
1315
+ head(url, config = {}) {
1316
+ return this.request({
1317
+ ...config,
1318
+ url,
1319
+ method: "HEAD"
1320
+ });
1321
+ }
1322
+ headResponse(url, config = {}) {
1323
+ return this.requestResponse({
1324
+ ...config,
1325
+ url,
1326
+ method: "HEAD"
1327
+ });
1328
+ }
1329
+ options(url, config = {}) {
1330
+ return this.request({
1331
+ ...config,
1332
+ url,
1333
+ method: "OPTIONS"
1334
+ });
1335
+ }
1336
+ optionsResponse(url, config = {}) {
1337
+ return this.requestResponse({
1338
+ ...config,
1339
+ url,
1340
+ method: "OPTIONS"
1341
+ });
1342
+ }
542
1343
  createPipeline(adapter) {
543
1344
  return new Pipeline(adapter, this.interceptors, this.hooks);
544
1345
  }
1346
+ validatePlugin(plugin) {
1347
+ const missingDependency = plugin.requires?.find((name) => {
1348
+ return !this.installedPlugins.has(name);
1349
+ });
1350
+ if (missingDependency) {
1351
+ throw new PluginError(
1352
+ `Plugin "${plugin.name}" requires "${missingDependency}"`,
1353
+ {
1354
+ code: "MISSING_DEPENDENCY",
1355
+ plugin: plugin.name,
1356
+ relatedPlugin: missingDependency
1357
+ }
1358
+ );
1359
+ }
1360
+ const directConflict = plugin.conflicts?.find((name) => {
1361
+ return this.installedPlugins.has(name);
1362
+ });
1363
+ if (directConflict) {
1364
+ throw new PluginError(
1365
+ `Plugin "${plugin.name}" conflicts with "${directConflict}"`,
1366
+ {
1367
+ code: "PLUGIN_CONFLICT",
1368
+ plugin: plugin.name,
1369
+ relatedPlugin: directConflict
1370
+ }
1371
+ );
1372
+ }
1373
+ for (const installed of this.installedPlugins.values()) {
1374
+ if (installed.plugin.conflicts?.includes(plugin.name)) {
1375
+ throw new PluginError(
1376
+ `Plugin "${plugin.name}" conflicts with "${installed.plugin.name}"`,
1377
+ {
1378
+ code: "PLUGIN_CONFLICT",
1379
+ plugin: plugin.name,
1380
+ relatedPlugin: installed.plugin.name
1381
+ }
1382
+ );
1383
+ }
1384
+ }
1385
+ }
1386
+ findDependent(pluginName) {
1387
+ for (const installed of this.installedPlugins.values()) {
1388
+ if (installed.plugin.requires?.includes(pluginName)) {
1389
+ return installed.plugin.name;
1390
+ }
1391
+ }
1392
+ return void 0;
1393
+ }
545
1394
  };
546
1395
 
547
1396
  // src/client/createClient.ts
@@ -549,6 +1398,11 @@ function createClient(options = {}) {
549
1398
  return new Client(options);
550
1399
  }
551
1400
 
1401
+ // src/plugins/resolveExtensionConfig.ts
1402
+ function resolveExtensionConfig(config, key, legacy) {
1403
+ return config.extensions?.[key] ?? legacy;
1404
+ }
1405
+
552
1406
  // src/plugins/authPlugin.ts
553
1407
  function authPlugin(options = {}) {
554
1408
  let refreshPromise;
@@ -575,17 +1429,18 @@ function authPlugin(options = {}) {
575
1429
  const refreshedToken = await refreshAccessToken(
576
1430
  options.refreshToken
577
1431
  );
578
- if (refreshedToken) {
579
- await options.storage?.set(refreshedToken);
580
- }
581
- const token = refreshedToken || await resolvePluginToken(options);
582
- if (!token) {
1432
+ const authorization = await resolveAuthorization(
1433
+ requestContext.config,
1434
+ options,
1435
+ typeof refreshedToken === "string" ? refreshedToken : void 0
1436
+ );
1437
+ if (!authorization.token) {
583
1438
  return void 0;
584
1439
  }
585
1440
  requestContext.config = setAuthorizationHeader(
586
1441
  requestContext.config,
587
- token,
588
- options.scheme
1442
+ authorization.token,
1443
+ authorization.scheme
589
1444
  );
590
1445
  return {
591
1446
  retry: true,
@@ -599,7 +1454,12 @@ function authPlugin(options = {}) {
599
1454
  };
600
1455
  async function refreshAccessToken(refreshToken) {
601
1456
  if (!refreshPromise) {
602
- refreshPromise = Promise.resolve(refreshToken()).finally(() => {
1457
+ refreshPromise = Promise.resolve(refreshToken()).then(async (token) => {
1458
+ if (token) {
1459
+ await options.storage?.set(token);
1460
+ }
1461
+ return token;
1462
+ }).finally(() => {
603
1463
  refreshPromise = void 0;
604
1464
  });
605
1465
  }
@@ -607,17 +1467,28 @@ function authPlugin(options = {}) {
607
1467
  }
608
1468
  }
609
1469
  async function applyAuthorization(config, options) {
610
- const requestAuth = config.auth;
611
- const token = requestAuth?.token ? await resolveToken(requestAuth.token) : await resolvePluginToken(options);
612
- if (!token) {
1470
+ const authorization = await resolveAuthorization(config, options);
1471
+ if (!authorization.token) {
613
1472
  return config;
614
1473
  }
615
1474
  return setAuthorizationHeader(
616
1475
  config,
617
- token,
618
- requestAuth?.scheme ?? options.scheme
1476
+ authorization.token,
1477
+ authorization.scheme
619
1478
  );
620
1479
  }
1480
+ async function resolveAuthorization(config, options, tokenOverride) {
1481
+ const requestAuth = resolveExtensionConfig(
1482
+ config,
1483
+ "auth",
1484
+ config.auth
1485
+ );
1486
+ const token = tokenOverride ?? (requestAuth?.token ? await resolveToken(requestAuth.token) : await resolvePluginToken(options));
1487
+ return {
1488
+ token,
1489
+ scheme: requestAuth?.scheme ?? options.scheme
1490
+ };
1491
+ }
621
1492
  async function resolvePluginToken(options) {
622
1493
  const configuredToken = await resolveToken(options.token);
623
1494
  if (configuredToken) {
@@ -645,17 +1516,47 @@ function defaultShouldRefresh(error) {
645
1516
  }
646
1517
 
647
1518
  // src/plugins/cachePlugin.ts
648
- var cacheStore = /* @__PURE__ */ new Map();
649
- function cachePlugin() {
650
- return {
1519
+ var DEFAULT_CACHE_METHODS = [
1520
+ "GET",
1521
+ "HEAD"
1522
+ ];
1523
+ var DEFAULT_VARY_HEADERS = [
1524
+ "authorization",
1525
+ "cookie",
1526
+ "accept",
1527
+ "accept-language"
1528
+ ];
1529
+ var cacheGeneration = 0;
1530
+ function cachePlugin(options = {}) {
1531
+ const cacheStore = /* @__PURE__ */ new Map();
1532
+ const cacheHits = /* @__PURE__ */ new WeakSet();
1533
+ const methods = new Set(
1534
+ options.methods ?? DEFAULT_CACHE_METHODS
1535
+ );
1536
+ const varyHeaders = options.varyHeaders ?? DEFAULT_VARY_HEADERS;
1537
+ let localGeneration = cacheGeneration;
1538
+ const plugin = {
651
1539
  name: "cache",
1540
+ clear() {
1541
+ cacheStore.clear();
1542
+ localGeneration = cacheGeneration;
1543
+ },
652
1544
  install(context) {
653
1545
  context.hooks.onRequest((requestContext) => {
654
- const cache = requestContext.config.cache;
655
- if (!cache?.enabled) {
1546
+ syncGeneration();
1547
+ const cache = resolveExtensionConfig(
1548
+ requestContext.config,
1549
+ "cache",
1550
+ requestContext.config.cache
1551
+ );
1552
+ if (!cache?.enabled || !isCacheableRequest(requestContext.config, methods)) {
656
1553
  return;
657
1554
  }
658
- const key = createCacheKey(requestContext.config);
1555
+ const key = createCacheKey(
1556
+ requestContext.config,
1557
+ cache,
1558
+ varyHeaders
1559
+ );
659
1560
  const record = cacheStore.get(key);
660
1561
  if (!record) {
661
1562
  return;
@@ -665,72 +1566,472 @@ function cachePlugin() {
665
1566
  return;
666
1567
  }
667
1568
  requestContext.response = {
668
- data: record.data,
669
- status: 200,
670
- statusText: "OK",
671
- headers: new Headers(),
1569
+ data: cloneCacheValue(record.data),
1570
+ status: record.status,
1571
+ statusText: record.statusText,
1572
+ headers: new Headers(record.headers),
672
1573
  config: requestContext.config,
673
- raw: new Response()
1574
+ raw: cloneRawResponse(record)
674
1575
  };
1576
+ cacheHits.add(requestContext);
675
1577
  });
676
1578
  context.hooks.onResponse((requestContext) => {
677
- const cache = requestContext.config.cache;
678
- if (!cache?.enabled || !requestContext.response) {
1579
+ syncGeneration();
1580
+ if (cacheHits.has(requestContext)) {
1581
+ return;
1582
+ }
1583
+ const cache = resolveExtensionConfig(
1584
+ requestContext.config,
1585
+ "cache",
1586
+ requestContext.config.cache
1587
+ );
1588
+ if (!cache?.enabled || !requestContext.response || !isCacheableRequest(requestContext.config, methods)) {
679
1589
  return;
680
1590
  }
681
- const key = createCacheKey(requestContext.config);
1591
+ const key = createCacheKey(
1592
+ requestContext.config,
1593
+ cache,
1594
+ varyHeaders
1595
+ );
682
1596
  const ttl = cache.ttl ?? 3e4;
1597
+ if (ttl <= 0) {
1598
+ cacheStore.delete(key);
1599
+ return;
1600
+ }
683
1601
  cacheStore.set(key, {
684
- data: requestContext.response.data,
685
- expiresAt: Date.now() + ttl
1602
+ data: cloneCacheValue(requestContext.response.data),
1603
+ expiresAt: Date.now() + ttl,
1604
+ status: requestContext.response.status,
1605
+ statusText: requestContext.response.statusText,
1606
+ headers: new Headers(requestContext.response.headers),
1607
+ raw: cloneResponse(requestContext.response.raw)
686
1608
  });
687
1609
  });
688
1610
  }
689
1611
  };
1612
+ return plugin;
1613
+ function syncGeneration() {
1614
+ if (localGeneration === cacheGeneration) {
1615
+ return;
1616
+ }
1617
+ cacheStore.clear();
1618
+ localGeneration = cacheGeneration;
1619
+ }
690
1620
  }
691
1621
  function clearCache() {
692
- cacheStore.clear();
1622
+ cacheGeneration += 1;
1623
+ }
1624
+ function isCacheableRequest(config, methods) {
1625
+ return methods.has(config.method ?? "GET") && config.responseType !== "stream";
693
1626
  }
694
- function createCacheKey(config) {
695
- if (config.cache?.key) {
696
- return config.cache.key;
1627
+ function createCacheKey(config, cache, varyHeaders) {
1628
+ if (cache.key) {
1629
+ return cache.key;
697
1630
  }
1631
+ const headers = new Headers(config.headers);
698
1632
  return JSON.stringify({
699
1633
  method: config.method ?? "GET",
700
1634
  baseURL: config.baseURL,
701
1635
  url: config.url,
702
- query: config.query
1636
+ query: normalizeQuery(config.query),
1637
+ responseType: config.responseType ?? "auto",
1638
+ headers: Object.fromEntries(
1639
+ varyHeaders.map((name) => [
1640
+ name.toLowerCase(),
1641
+ headers.get(name)
1642
+ ])
1643
+ )
1644
+ });
1645
+ }
1646
+ function normalizeQuery(query) {
1647
+ if (!query) {
1648
+ return [];
1649
+ }
1650
+ const entries = [];
1651
+ for (const key of Object.keys(query).sort()) {
1652
+ appendQueryValue(entries, key, query[key]);
1653
+ }
1654
+ return entries;
1655
+ }
1656
+ function appendQueryValue(entries, key, value) {
1657
+ if (value === null || value === void 0) {
1658
+ return;
1659
+ }
1660
+ if (Array.isArray(value)) {
1661
+ for (const item of value) {
1662
+ appendQueryValue(entries, key, item);
1663
+ }
1664
+ return;
1665
+ }
1666
+ entries.push([key, String(value)]);
1667
+ }
1668
+ function cloneRawResponse(record) {
1669
+ if (record.raw) {
1670
+ const cloned = cloneResponse(record.raw);
1671
+ if (cloned) {
1672
+ return cloned;
1673
+ }
1674
+ }
1675
+ return new Response(null, {
1676
+ status: record.status,
1677
+ statusText: record.statusText,
1678
+ headers: record.headers
1679
+ });
1680
+ }
1681
+ function cloneResponse(response) {
1682
+ try {
1683
+ return response.clone();
1684
+ } catch {
1685
+ return void 0;
1686
+ }
1687
+ }
1688
+ function cloneCacheValue(value) {
1689
+ if (typeof structuredClone !== "function") {
1690
+ return value;
1691
+ }
1692
+ try {
1693
+ return structuredClone(value);
1694
+ } catch {
1695
+ return value;
1696
+ }
1697
+ }
1698
+
1699
+ // src/plugins/xhrTransport.ts
1700
+ function xhrRequest(config, options = {}) {
1701
+ let request;
1702
+ let xhr;
1703
+ try {
1704
+ request = buildRequest(config);
1705
+ xhr = new XMLHttpRequest();
1706
+ } catch (error) {
1707
+ request?.clear();
1708
+ return Promise.reject(
1709
+ createConfigError(config, error)
1710
+ );
1711
+ }
1712
+ const signal = request.init.signal;
1713
+ return new Promise((resolve, reject) => {
1714
+ let settled = false;
1715
+ const cleanup = () => {
1716
+ signal?.removeEventListener("abort", onSignalAbort);
1717
+ request.clear();
1718
+ xhr.onload = null;
1719
+ xhr.onerror = null;
1720
+ xhr.onabort = null;
1721
+ xhr.onprogress = null;
1722
+ if (xhr.upload) {
1723
+ xhr.upload.onprogress = null;
1724
+ }
1725
+ };
1726
+ const resolveOnce = (response) => {
1727
+ if (settled) {
1728
+ return;
1729
+ }
1730
+ settled = true;
1731
+ cleanup();
1732
+ resolve(response);
1733
+ };
1734
+ const rejectOnce = (error) => {
1735
+ if (settled) {
1736
+ return;
1737
+ }
1738
+ settled = true;
1739
+ cleanup();
1740
+ reject(error);
1741
+ };
1742
+ const abortWith = (error) => {
1743
+ rejectOnce(error);
1744
+ xhr.abort();
1745
+ };
1746
+ const onSignalAbort = () => {
1747
+ abortWith(
1748
+ createAbortError2(signal?.reason, config)
1749
+ );
1750
+ };
1751
+ xhr.onload = () => {
1752
+ void processResponse(xhr, config).then(
1753
+ resolveOnce,
1754
+ rejectOnce
1755
+ );
1756
+ };
1757
+ xhr.onerror = () => {
1758
+ rejectOnce(
1759
+ new RequestError("Network request failed", {
1760
+ code: "NETWORK_ERROR",
1761
+ config
1762
+ })
1763
+ );
1764
+ };
1765
+ xhr.onabort = () => {
1766
+ rejectOnce(
1767
+ createAbortError2(signal?.reason, config)
1768
+ );
1769
+ };
1770
+ xhr.onprogress = createProgressHandler(
1771
+ options.onDownloadProgress,
1772
+ abortWith
1773
+ );
1774
+ if (xhr.upload) {
1775
+ xhr.upload.onprogress = createProgressHandler(
1776
+ options.onUploadProgress,
1777
+ abortWith
1778
+ );
1779
+ }
1780
+ try {
1781
+ xhr.open(
1782
+ request.init.method ?? "GET",
1783
+ request.url,
1784
+ true
1785
+ );
1786
+ xhr.responseType = "blob";
1787
+ xhr.withCredentials = request.init.credentials === "include";
1788
+ new Headers(request.init.headers).forEach(
1789
+ (value, name) => {
1790
+ xhr.setRequestHeader(name, value);
1791
+ }
1792
+ );
1793
+ if (signal?.aborted) {
1794
+ onSignalAbort();
1795
+ return;
1796
+ }
1797
+ signal?.addEventListener("abort", onSignalAbort, {
1798
+ once: true
1799
+ });
1800
+ const body = request.init.body;
1801
+ if (typeof ReadableStream !== "undefined" && body instanceof ReadableStream) {
1802
+ abortWith(
1803
+ new RequestError(
1804
+ "XMLHttpRequest cannot send a ReadableStream body",
1805
+ {
1806
+ code: "CONFIG_ERROR",
1807
+ config
1808
+ }
1809
+ )
1810
+ );
1811
+ return;
1812
+ }
1813
+ xhr.send(body);
1814
+ } catch (error) {
1815
+ abortWith(createConfigError(config, error));
1816
+ }
703
1817
  });
704
1818
  }
1819
+ async function processResponse(xhr, config) {
1820
+ if (xhr.status === 0) {
1821
+ throw new RequestError("Network request failed", {
1822
+ code: "NETWORK_ERROR",
1823
+ config
1824
+ });
1825
+ }
1826
+ try {
1827
+ const headers = parseHeaders(
1828
+ xhr.getAllResponseHeaders()
1829
+ );
1830
+ const blob = xhr.response instanceof Blob ? xhr.response : new Blob(
1831
+ xhr.response === null ? [] : [xhr.response],
1832
+ {
1833
+ type: headers.get("content-type") ?? ""
1834
+ }
1835
+ );
1836
+ const raw = new Response(
1837
+ isNullBodyStatus(xhr.status) ? null : blob,
1838
+ {
1839
+ status: xhr.status,
1840
+ statusText: xhr.statusText,
1841
+ headers
1842
+ }
1843
+ );
1844
+ const parseTarget = config.responseType === "stream" ? raw : raw.clone();
1845
+ const data = await parseResponse(
1846
+ parseTarget,
1847
+ config
1848
+ );
1849
+ const response = {
1850
+ data,
1851
+ status: xhr.status,
1852
+ statusText: xhr.statusText,
1853
+ headers,
1854
+ config,
1855
+ raw
1856
+ };
1857
+ const validateStatus = config.validateStatus ?? defaultValidateStatus2;
1858
+ if (!validateStatus(xhr.status)) {
1859
+ throw new RequestError(
1860
+ xhr.statusText || "Request failed",
1861
+ {
1862
+ code: "HTTP_ERROR",
1863
+ response
1864
+ }
1865
+ );
1866
+ }
1867
+ return response;
1868
+ } catch (error) {
1869
+ if (error instanceof RequestError) {
1870
+ throw error;
1871
+ }
1872
+ throw new RequestError(
1873
+ "Failed to process XMLHttpRequest response",
1874
+ {
1875
+ code: "PARSER_ERROR",
1876
+ config,
1877
+ cause: error
1878
+ }
1879
+ );
1880
+ }
1881
+ }
1882
+ function createProgressHandler(callback, abortWith) {
1883
+ if (!callback) {
1884
+ return null;
1885
+ }
1886
+ return (event) => {
1887
+ try {
1888
+ callback(
1889
+ createProgress(
1890
+ event.loaded,
1891
+ event.lengthComputable ? event.total : void 0
1892
+ )
1893
+ );
1894
+ } catch (error) {
1895
+ abortWith(error);
1896
+ }
1897
+ };
1898
+ }
1899
+ function createProgress(loaded, total) {
1900
+ if (total === void 0 || total === 0) {
1901
+ return {
1902
+ loaded,
1903
+ total
1904
+ };
1905
+ }
1906
+ return {
1907
+ loaded,
1908
+ total,
1909
+ progress: Math.min(loaded / total, 1)
1910
+ };
1911
+ }
1912
+ function parseHeaders(value) {
1913
+ const headers = new Headers();
1914
+ for (const line of value.split(/\r?\n/)) {
1915
+ const separator = line.indexOf(":");
1916
+ if (separator > 0) {
1917
+ headers.append(
1918
+ line.slice(0, separator).trim(),
1919
+ line.slice(separator + 1).trim()
1920
+ );
1921
+ }
1922
+ }
1923
+ return headers;
1924
+ }
1925
+ function createAbortError2(reason, config) {
1926
+ if (reason instanceof RequestError) {
1927
+ return new RequestError(reason.message, {
1928
+ code: reason.code,
1929
+ status: reason.status,
1930
+ data: reason.data,
1931
+ response: reason.response,
1932
+ config: reason.config ?? config,
1933
+ cause: reason
1934
+ });
1935
+ }
1936
+ return new RequestError("Request aborted", {
1937
+ code: "ABORT_ERROR",
1938
+ config,
1939
+ cause: reason
1940
+ });
1941
+ }
1942
+ function createConfigError(config, cause) {
1943
+ return new RequestError(
1944
+ "Failed to create XMLHttpRequest",
1945
+ {
1946
+ code: "CONFIG_ERROR",
1947
+ config,
1948
+ cause
1949
+ }
1950
+ );
1951
+ }
1952
+ function isNullBodyStatus(status) {
1953
+ return status === 204 || status === 205 || status === 304;
1954
+ }
1955
+ function defaultValidateStatus2(status) {
1956
+ return status >= 200 && status < 300;
1957
+ }
705
1958
 
706
1959
  // src/plugins/downloadPlugin.ts
707
- function downloadPlugin() {
1960
+ function downloadPlugin(options = {}) {
1961
+ const xhrContexts = /* @__PURE__ */ new WeakSet();
708
1962
  return {
709
1963
  name: "download",
710
1964
  install(context) {
711
1965
  context.interceptors.request.use((config) => {
712
- if (!config.download) {
1966
+ const download = resolveExtensionConfig(
1967
+ config,
1968
+ "download",
1969
+ config.download
1970
+ );
1971
+ if (!download) {
713
1972
  return config;
714
1973
  }
715
- const responseType = config.download.onProgress ? "stream" : config.responseType ?? "blob";
1974
+ const responseType = download.onProgress && !shouldUseXHR(options.transport) ? "stream" : config.responseType ?? "blob";
716
1975
  return {
717
1976
  ...config,
718
1977
  responseType
719
1978
  };
720
1979
  });
721
- context.interceptors.response.use(async (response) => {
722
- const download = response.config.download;
1980
+ context.hooks.onRequest(async (requestContext) => {
1981
+ if (requestContext.response) {
1982
+ return;
1983
+ }
1984
+ const download = resolveExtensionConfig(
1985
+ requestContext.config,
1986
+ "download",
1987
+ requestContext.config.download
1988
+ );
1989
+ const onProgress = download?.onProgress;
1990
+ if (!onProgress || !shouldUseXHR(options.transport)) {
1991
+ return;
1992
+ }
1993
+ if (typeof XMLHttpRequest === "undefined") {
1994
+ throw new RequestError(
1995
+ "XMLHttpRequest is unavailable for download progress",
1996
+ {
1997
+ code: "CONFIG_ERROR",
1998
+ config: requestContext.config
1999
+ }
2000
+ );
2001
+ }
2002
+ requestContext.response = await xhrRequest(
2003
+ requestContext.config,
2004
+ {
2005
+ onDownloadProgress: onProgress
2006
+ }
2007
+ );
2008
+ xhrContexts.add(requestContext);
2009
+ });
2010
+ context.hooks.onResponse(async (requestContext) => {
2011
+ if (xhrContexts.has(requestContext)) {
2012
+ return;
2013
+ }
2014
+ const response = requestContext.response;
2015
+ if (!response) {
2016
+ return;
2017
+ }
2018
+ const download = resolveExtensionConfig(
2019
+ response.config,
2020
+ "download",
2021
+ response.config.download
2022
+ );
723
2023
  const onProgress = download?.onProgress;
724
2024
  if (!download || !onProgress) {
725
- return response;
2025
+ return;
726
2026
  }
727
2027
  const stream = response.data;
728
- if (!(stream instanceof ReadableStream)) {
2028
+ if (typeof ReadableStream === "undefined" || !(stream instanceof ReadableStream)) {
729
2029
  throw new RequestError(
730
2030
  "Download response stream is unavailable",
731
2031
  {
732
2032
  code: "PARSER_ERROR",
733
- status: response.status
2033
+ status: response.status,
2034
+ config: response.config
734
2035
  }
735
2036
  );
736
2037
  }
@@ -739,7 +2040,7 @@ function downloadPlugin() {
739
2040
  response,
740
2041
  onProgress
741
2042
  );
742
- return {
2043
+ requestContext.response = {
743
2044
  ...response,
744
2045
  data: blob
745
2046
  };
@@ -747,6 +2048,18 @@ function downloadPlugin() {
747
2048
  }
748
2049
  };
749
2050
  }
2051
+ function shouldUseXHR(transport = "auto") {
2052
+ if (transport === "xhr") {
2053
+ return true;
2054
+ }
2055
+ if (transport === "fetch") {
2056
+ return false;
2057
+ }
2058
+ return !supportsFetchResponseStream() && typeof XMLHttpRequest !== "undefined";
2059
+ }
2060
+ function supportsFetchResponseStream() {
2061
+ return typeof ReadableStream !== "undefined" && typeof Response !== "undefined" && "body" in Response.prototype;
2062
+ }
750
2063
  async function consumeDownloadStream(stream, response, onProgress) {
751
2064
  const reader = stream.getReader();
752
2065
  const chunks = [];
@@ -761,11 +2074,16 @@ async function consumeDownloadStream(stream, response, onProgress) {
761
2074
  break;
762
2075
  }
763
2076
  const chunk = result.value;
764
- const buffer = copyToArrayBuffer(chunk);
765
- chunks.push(buffer);
2077
+ chunks.push(toDownloadBuffer(chunk));
766
2078
  loaded += chunk.byteLength;
767
- onProgress(createProgress(loaded, total));
2079
+ onProgress(createProgress2(loaded, total));
768
2080
  }
2081
+ } catch (error) {
2082
+ try {
2083
+ await reader.cancel(error);
2084
+ } catch {
2085
+ }
2086
+ throw error;
769
2087
  } finally {
770
2088
  reader.releaseLock();
771
2089
  }
@@ -773,7 +2091,16 @@ async function consumeDownloadStream(stream, response, onProgress) {
773
2091
  type: response.headers.get("content-type") ?? ""
774
2092
  });
775
2093
  }
776
- function copyToArrayBuffer(chunk) {
2094
+ function toDownloadBuffer(chunk) {
2095
+ if (chunk.buffer instanceof ArrayBuffer) {
2096
+ if (chunk.byteOffset === 0 && chunk.byteLength === chunk.buffer.byteLength) {
2097
+ return chunk.buffer;
2098
+ }
2099
+ return chunk.buffer.slice(
2100
+ chunk.byteOffset,
2101
+ chunk.byteOffset + chunk.byteLength
2102
+ );
2103
+ }
777
2104
  const copy = new Uint8Array(chunk.byteLength);
778
2105
  copy.set(chunk);
779
2106
  return copy.buffer;
@@ -788,7 +2115,7 @@ function parseContentLength(value) {
788
2115
  }
789
2116
  return total;
790
2117
  }
791
- function createProgress(loaded, total) {
2118
+ function createProgress2(loaded, total) {
792
2119
  if (total === void 0 || total === 0) {
793
2120
  return {
794
2121
  loaded,
@@ -808,42 +2135,125 @@ function loggerPlugin(defaultOptions = {}) {
808
2135
  name: "logger",
809
2136
  install(context) {
810
2137
  context.interceptors.request.use((config) => {
811
- const logger = config.logger ?? defaultOptions;
2138
+ const logger = resolveExtensionConfig(
2139
+ config,
2140
+ "logger",
2141
+ config.logger
2142
+ ) ?? defaultOptions;
812
2143
  if (logger.enabled === false) {
813
2144
  return config;
814
2145
  }
815
2146
  console.log("[Npora Request]", {
816
2147
  type: "request",
817
2148
  method: config.method ?? "GET",
818
- url: config.url
2149
+ url: redactURL(config.url)
819
2150
  });
820
2151
  return config;
821
2152
  });
822
2153
  context.interceptors.response.use((response) => {
823
- const logger = response.config.logger ?? defaultOptions;
2154
+ const logger = resolveExtensionConfig(
2155
+ response.config,
2156
+ "logger",
2157
+ response.config.logger
2158
+ ) ?? defaultOptions;
824
2159
  if (logger.enabled === false) {
825
2160
  return response;
826
2161
  }
827
2162
  console.log("[Npora Request]", {
828
2163
  type: "response",
829
2164
  method: response.config.method ?? "GET",
830
- url: response.config.url,
2165
+ url: redactURL(response.config.url),
831
2166
  status: response.status
832
2167
  });
833
2168
  return response;
834
2169
  });
835
2170
  context.interceptors.error.use((error) => {
836
- console.error("[Npora Request]", {
837
- type: "error",
838
- error
839
- });
2171
+ const config = error instanceof RequestError ? error.config : void 0;
2172
+ const logger = config ? resolveExtensionConfig(
2173
+ config,
2174
+ "logger",
2175
+ config.logger
2176
+ ) ?? defaultOptions : defaultOptions;
2177
+ if (logger.enabled === false) {
2178
+ return error;
2179
+ }
2180
+ console.error(
2181
+ "[Npora Request]",
2182
+ createErrorLog(error)
2183
+ );
840
2184
  return error;
841
2185
  });
842
2186
  }
843
2187
  };
844
2188
  }
2189
+ var SENSITIVE_QUERY_KEYS = /* @__PURE__ */ new Set([
2190
+ "access_token",
2191
+ "api-key",
2192
+ "api_key",
2193
+ "apikey",
2194
+ "authorization",
2195
+ "client_secret",
2196
+ "password",
2197
+ "refresh_token",
2198
+ "secret",
2199
+ "sig",
2200
+ "signature",
2201
+ "token"
2202
+ ]);
2203
+ function redactURL(url) {
2204
+ const queryIndex = url.indexOf("?");
2205
+ if (queryIndex === -1) {
2206
+ return url;
2207
+ }
2208
+ const hashIndex = url.indexOf("#", queryIndex);
2209
+ const pathname = url.slice(0, queryIndex);
2210
+ const query = url.slice(
2211
+ queryIndex + 1,
2212
+ hashIndex === -1 ? void 0 : hashIndex
2213
+ );
2214
+ const hash = hashIndex === -1 ? "" : url.slice(hashIndex);
2215
+ const params = new URLSearchParams(query);
2216
+ for (const key of [...params.keys()]) {
2217
+ if (SENSITIVE_QUERY_KEYS.has(key.toLowerCase())) {
2218
+ params.set(key, "[REDACTED]");
2219
+ }
2220
+ }
2221
+ const redactedQuery = params.toString();
2222
+ return `${pathname}${redactedQuery ? `?${redactedQuery}` : ""}${hash}`;
2223
+ }
2224
+ function createErrorLog(error) {
2225
+ if (error instanceof RequestError) {
2226
+ return {
2227
+ type: "error",
2228
+ name: error.name,
2229
+ message: error.message,
2230
+ code: error.code,
2231
+ status: error.status,
2232
+ method: error.config?.method ?? "GET",
2233
+ url: error.config ? redactURL(error.config.url) : void 0
2234
+ };
2235
+ }
2236
+ if (error instanceof Error) {
2237
+ return {
2238
+ type: "error",
2239
+ name: error.name,
2240
+ message: error.message
2241
+ };
2242
+ }
2243
+ return {
2244
+ type: "error",
2245
+ message: String(error)
2246
+ };
2247
+ }
845
2248
 
846
2249
  // src/plugins/retryPlugin.ts
2250
+ var DEFAULT_RETRY_METHODS = [
2251
+ "GET",
2252
+ "HEAD",
2253
+ "OPTIONS",
2254
+ "PUT",
2255
+ "DELETE"
2256
+ ];
847
2257
  function retryPlugin(defaultOptions = {}) {
848
2258
  return {
849
2259
  name: "retry",
@@ -853,12 +2263,22 @@ function retryPlugin(defaultOptions = {}) {
853
2263
  return void 0;
854
2264
  }
855
2265
  const retryOptions = normalizeRetryOptions(
856
- requestContext.config.retry,
2266
+ resolveExtensionConfig(
2267
+ requestContext.config,
2268
+ "retry",
2269
+ requestContext.config.retry
2270
+ ),
857
2271
  defaultOptions
858
2272
  );
859
2273
  if (attempt >= retryOptions.retries) {
860
2274
  return void 0;
861
2275
  }
2276
+ if (!canRetryRequest(
2277
+ requestContext.config,
2278
+ retryOptions.methods
2279
+ )) {
2280
+ return void 0;
2281
+ }
862
2282
  const shouldRetry = await retryOptions.shouldRetry(
863
2283
  requestContext.error,
864
2284
  attempt
@@ -866,11 +2286,16 @@ function retryPlugin(defaultOptions = {}) {
866
2286
  if (!shouldRetry) {
867
2287
  return void 0;
868
2288
  }
2289
+ const configuredDelay = await retryOptions.delay(
2290
+ attempt,
2291
+ requestContext.error
2292
+ );
2293
+ const retryAfter = retryOptions.respectRetryAfter ? parseRetryAfter(requestContext.error) : void 0;
869
2294
  return {
870
2295
  retry: true,
871
- delay: await retryOptions.delay(
872
- attempt,
873
- requestContext.error
2296
+ delay: normalizeRetryDelay(
2297
+ retryAfter ?? configuredDelay,
2298
+ retryOptions.maxDelay
874
2299
  )
875
2300
  };
876
2301
  });
@@ -881,7 +2306,10 @@ function normalizeRetryOptions(retry, defaults = {}) {
881
2306
  if (typeof retry === "number") {
882
2307
  return {
883
2308
  retries: normalizeRetries(retry),
2309
+ methods: normalizeMethods(defaults.methods),
884
2310
  delay: normalizeDelay(defaults.delay),
2311
+ respectRetryAfter: defaults.respectRetryAfter ?? true,
2312
+ maxDelay: normalizeMaxDelay(defaults.maxDelay),
885
2313
  shouldRetry: defaults.shouldRetry ?? defaultShouldRetry
886
2314
  };
887
2315
  }
@@ -889,12 +2317,31 @@ function normalizeRetryOptions(retry, defaults = {}) {
889
2317
  retries: normalizeRetries(
890
2318
  retry?.retries ?? defaults.retries ?? 0
891
2319
  ),
2320
+ methods: normalizeMethods(
2321
+ retry?.methods ?? defaults.methods
2322
+ ),
892
2323
  delay: normalizeDelay(
893
2324
  retry?.delay ?? defaults.delay
894
2325
  ),
2326
+ respectRetryAfter: retry?.respectRetryAfter ?? defaults.respectRetryAfter ?? true,
2327
+ maxDelay: normalizeMaxDelay(
2328
+ retry?.maxDelay ?? defaults.maxDelay
2329
+ ),
895
2330
  shouldRetry: retry?.shouldRetry ?? defaults.shouldRetry ?? defaultShouldRetry
896
2331
  };
897
2332
  }
2333
+ function normalizeMethods(methods) {
2334
+ return new Set(methods ?? DEFAULT_RETRY_METHODS);
2335
+ }
2336
+ function normalizeMaxDelay(maxDelay) {
2337
+ if (maxDelay === void 0) {
2338
+ return 6e4;
2339
+ }
2340
+ if (!Number.isFinite(maxDelay)) {
2341
+ return maxDelay > 0 ? Number.MAX_SAFE_INTEGER : 0;
2342
+ }
2343
+ return Math.max(0, maxDelay);
2344
+ }
898
2345
  function normalizeRetries(retries) {
899
2346
  if (!Number.isFinite(retries)) {
900
2347
  return 0;
@@ -911,6 +2358,40 @@ function normalizeDelay(delay) {
911
2358
  function defaultRetryDelay(attempt) {
912
2359
  return Math.min(100 * 2 ** attempt, 1e3);
913
2360
  }
2361
+ function normalizeRetryDelay(delay, maxDelay) {
2362
+ if (!Number.isFinite(delay)) {
2363
+ return delay > 0 ? maxDelay : 0;
2364
+ }
2365
+ return Math.min(Math.max(0, delay), maxDelay);
2366
+ }
2367
+ function canRetryRequest(config, methods) {
2368
+ const method = config.method ?? "GET";
2369
+ if (!methods.has(method)) {
2370
+ return false;
2371
+ }
2372
+ return !isReadableStream(config.body);
2373
+ }
2374
+ function isReadableStream(value) {
2375
+ return typeof ReadableStream !== "undefined" && value instanceof ReadableStream;
2376
+ }
2377
+ function parseRetryAfter(error) {
2378
+ if (!(error instanceof RequestError)) {
2379
+ return void 0;
2380
+ }
2381
+ const value = error.response?.headers.get("retry-after");
2382
+ if (!value) {
2383
+ return void 0;
2384
+ }
2385
+ const seconds = Number(value);
2386
+ if (Number.isFinite(seconds)) {
2387
+ return Math.max(0, seconds * 1e3);
2388
+ }
2389
+ const date = Date.parse(value);
2390
+ if (Number.isNaN(date)) {
2391
+ return void 0;
2392
+ }
2393
+ return Math.max(0, date - Date.now());
2394
+ }
914
2395
  function defaultShouldRetry(error) {
915
2396
  if (!(error instanceof RequestError)) {
916
2397
  return false;
@@ -930,16 +2411,48 @@ function uploadPlugin() {
930
2411
  name: "upload",
931
2412
  install(context) {
932
2413
  context.interceptors.request.use((config) => {
933
- if (!config.upload) {
2414
+ const upload = resolveExtensionConfig(
2415
+ config,
2416
+ "upload",
2417
+ config.upload
2418
+ );
2419
+ if (!upload) {
934
2420
  return config;
935
2421
  }
936
2422
  return {
937
2423
  ...config,
938
2424
  method: config.method ?? "POST",
939
- formData: config.upload.data,
940
- upload: void 0
2425
+ formData: upload.data
941
2426
  };
942
2427
  });
2428
+ context.hooks.onRequest(async (requestContext) => {
2429
+ if (requestContext.response) {
2430
+ return;
2431
+ }
2432
+ const upload = resolveExtensionConfig(
2433
+ requestContext.config,
2434
+ "upload",
2435
+ requestContext.config.upload
2436
+ );
2437
+ if (!upload?.onProgress) {
2438
+ return;
2439
+ }
2440
+ if (typeof XMLHttpRequest === "undefined") {
2441
+ throw new RequestError(
2442
+ "XMLHttpRequest is unavailable for upload progress",
2443
+ {
2444
+ code: "CONFIG_ERROR",
2445
+ config: requestContext.config
2446
+ }
2447
+ );
2448
+ }
2449
+ requestContext.response = await xhrRequest(
2450
+ requestContext.config,
2451
+ {
2452
+ onUploadProgress: upload.onProgress
2453
+ }
2454
+ );
2455
+ });
943
2456
  }
944
2457
  };
945
2458
  }
@@ -948,6 +2461,7 @@ export {
948
2461
  FetchAdapter,
949
2462
  InterceptorManager,
950
2463
  MockAdapter,
2464
+ PluginError,
951
2465
  RequestError,
952
2466
  authPlugin,
953
2467
  cachePlugin,