@microlink/mql 0.10.13 → 0.10.17

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/src/ky.js CHANGED
@@ -1,500 +1,402 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3
- typeof define === 'function' && define.amd ? define(factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.ky = factory());
5
- }(this, (function () { 'use strict';
6
-
7
- /*! MIT License © Sindre Sorhus */
8
-
9
- const isObject = value => value !== null && typeof value === 'object';
10
- const supportsAbortController = typeof globalThis.AbortController === 'function';
11
- const supportsStreams = typeof globalThis.ReadableStream === 'function';
12
- const supportsFormData = typeof globalThis.FormData === 'function';
13
-
14
- const mergeHeaders = (source1, source2) => {
15
- const result = new globalThis.Headers(source1 || {});
16
- const isHeadersInstance = source2 instanceof globalThis.Headers;
17
- const source = new globalThis.Headers(source2 || {});
18
-
19
- for (const [key, value] of source) {
20
- if ((isHeadersInstance && value === 'undefined') || value === undefined) {
21
- result.delete(key);
22
- } else {
23
- result.set(key, value);
24
- }
25
- }
26
-
27
- return result;
28
- };
29
-
30
- const deepMerge = (...sources) => {
31
- let returnValue = {};
32
- let headers = {};
33
-
34
- for (const source of sources) {
35
- if (Array.isArray(source)) {
36
- if (!(Array.isArray(returnValue))) {
37
- returnValue = [];
38
- }
39
-
40
- returnValue = [...returnValue, ...source];
41
- } else if (isObject(source)) {
42
- for (let [key, value] of Object.entries(source)) {
43
- if (isObject(value) && (key in returnValue)) {
44
- value = deepMerge(returnValue[key], value);
45
- }
46
-
47
- returnValue = {...returnValue, [key]: value};
48
- }
49
-
50
- if (isObject(source.headers)) {
51
- headers = mergeHeaders(headers, source.headers);
52
- }
53
- }
54
-
55
- returnValue.headers = headers;
56
- }
57
-
58
- return returnValue;
59
- };
60
-
61
- const requestMethods = [
62
- 'get',
63
- 'post',
64
- 'put',
65
- 'patch',
66
- 'head',
67
- 'delete'
68
- ];
69
-
70
- const responseTypes = {
71
- json: 'application/json',
72
- text: 'text/*',
73
- formData: 'multipart/form-data',
74
- arrayBuffer: '*/*',
75
- blob: '*/*'
76
- };
77
-
78
- const retryMethods = [
79
- 'get',
80
- 'put',
81
- 'head',
82
- 'delete',
83
- 'options',
84
- 'trace'
85
- ];
86
-
87
- const retryStatusCodes = [
88
- 408,
89
- 413,
90
- 429,
91
- 500,
92
- 502,
93
- 503,
94
- 504
95
- ];
96
-
97
- const retryAfterStatusCodes = [
98
- 413,
99
- 429,
100
- 503
101
- ];
102
-
103
- const stop = Symbol('stop');
104
-
105
- class HTTPError extends Error {
106
- constructor(response, request, options) {
107
- // Set the message to the status text, such as Unauthorized,
108
- // with some fallbacks. This message should never be undefined.
109
- super(
110
- response.statusText ||
111
- String(
112
- (response.status === 0 || response.status) ?
113
- response.status : 'Unknown response error'
114
- )
115
- );
116
- this.name = 'HTTPError';
117
- this.response = response;
118
- this.request = request;
119
- this.options = options;
120
- }
121
- }
122
-
123
- class TimeoutError extends Error {
124
- constructor(request) {
125
- super('Request timed out');
126
- this.name = 'TimeoutError';
127
- this.request = request;
128
- }
129
- }
130
-
131
- const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
132
-
133
- // `Promise.race()` workaround (#91)
134
- const timeout = (request, abortController, options) =>
135
- new Promise((resolve, reject) => {
136
- const timeoutID = setTimeout(() => {
137
- if (abortController) {
138
- abortController.abort();
139
- }
140
-
141
- reject(new TimeoutError(request));
142
- }, options.timeout);
143
-
144
- /* eslint-disable promise/prefer-await-to-then */
145
- options.fetch(request)
146
- .then(resolve)
147
- .catch(reject)
148
- .then(() => {
149
- clearTimeout(timeoutID);
150
- });
151
- /* eslint-enable promise/prefer-await-to-then */
152
- });
153
-
154
- const normalizeRequestMethod = input => requestMethods.includes(input) ? input.toUpperCase() : input;
155
-
156
- const defaultRetryOptions = {
157
- limit: 2,
158
- methods: retryMethods,
159
- statusCodes: retryStatusCodes,
160
- afterStatusCodes: retryAfterStatusCodes
161
- };
162
-
163
- const normalizeRetryOptions = (retry = {}) => {
164
- if (typeof retry === 'number') {
165
- return {
166
- ...defaultRetryOptions,
167
- limit: retry
168
- };
169
- }
170
-
171
- if (retry.methods && !Array.isArray(retry.methods)) {
172
- throw new Error('retry.methods must be an array');
173
- }
174
-
175
- if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
176
- throw new Error('retry.statusCodes must be an array');
177
- }
178
-
179
- return {
180
- ...defaultRetryOptions,
181
- ...retry,
182
- afterStatusCodes: retryAfterStatusCodes
183
- };
184
- };
185
-
186
- // The maximum value of a 32bit int (see issue #117)
187
- const maxSafeTimeout = 2147483647;
188
-
189
- class Ky {
190
- constructor(input, options = {}) {
191
- this._retryCount = 0;
192
- this._input = input;
193
- this._options = {
194
- // TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
195
- credentials: this._input.credentials || 'same-origin',
196
- ...options,
197
- headers: mergeHeaders(this._input.headers, options.headers),
198
- hooks: deepMerge({
199
- beforeRequest: [],
200
- beforeRetry: [],
201
- afterResponse: []
202
- }, options.hooks),
203
- method: normalizeRequestMethod(options.method || this._input.method),
204
- prefixUrl: String(options.prefixUrl || ''),
205
- retry: normalizeRetryOptions(options.retry),
206
- throwHttpErrors: options.throwHttpErrors !== false,
207
- timeout: typeof options.timeout === 'undefined' ? 10000 : options.timeout,
208
- fetch: options.fetch || globalThis.fetch.bind(globalThis)
209
- };
210
-
211
- if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {
212
- throw new TypeError('`input` must be a string, URL, or Request');
213
- }
214
-
215
- if (this._options.prefixUrl && typeof this._input === 'string') {
216
- if (this._input.startsWith('/')) {
217
- throw new Error('`input` must not begin with a slash when using `prefixUrl`');
218
- }
219
-
220
- if (!this._options.prefixUrl.endsWith('/')) {
221
- this._options.prefixUrl += '/';
222
- }
223
-
224
- this._input = this._options.prefixUrl + this._input;
225
- }
226
-
227
- if (supportsAbortController) {
228
- this.abortController = new globalThis.AbortController();
229
- if (this._options.signal) {
230
- this._options.signal.addEventListener('abort', () => {
231
- this.abortController.abort();
232
- });
233
- }
234
-
235
- this._options.signal = this.abortController.signal;
236
- }
237
-
238
- this.request = new globalThis.Request(this._input, this._options);
239
-
240
- if (this._options.searchParams) {
241
- const textSearchParams = typeof this._options.searchParams === 'string' ?
242
- this._options.searchParams.replace(/^\?/, '') :
243
- new URLSearchParams(this._options.searchParams).toString();
244
- const searchParams = '?' + textSearchParams;
245
- const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
246
-
247
- // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
248
- if (((supportsFormData && this._options.body instanceof globalThis.FormData) || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
249
- this.request.headers.delete('content-type');
250
- }
251
-
252
- this.request = new globalThis.Request(new globalThis.Request(url, this.request), this._options);
253
- }
254
-
255
- if (this._options.json !== undefined) {
256
- this._options.body = JSON.stringify(this._options.json);
257
- this.request.headers.set('content-type', 'application/json');
258
- this.request = new globalThis.Request(this.request, {body: this._options.body});
259
- }
260
-
261
- const fn = async () => {
262
- if (this._options.timeout > maxSafeTimeout) {
263
- throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
264
- }
265
-
266
- await delay(1);
267
- let response = await this._fetch();
268
-
269
- for (const hook of this._options.hooks.afterResponse) {
270
- // eslint-disable-next-line no-await-in-loop
271
- const modifiedResponse = await hook(
272
- this.request,
273
- this._options,
274
- this._decorateResponse(response.clone())
275
- );
276
-
277
- if (modifiedResponse instanceof globalThis.Response) {
278
- response = modifiedResponse;
279
- }
280
- }
281
-
282
- this._decorateResponse(response);
283
-
284
- if (!response.ok && this._options.throwHttpErrors) {
285
- throw new HTTPError(response, this.request, this._options);
286
- }
287
-
288
- // If `onDownloadProgress` is passed, it uses the stream API internally
289
- /* istanbul ignore next */
290
- if (this._options.onDownloadProgress) {
291
- if (typeof this._options.onDownloadProgress !== 'function') {
292
- throw new TypeError('The `onDownloadProgress` option must be a function');
293
- }
294
-
295
- if (!supportsStreams) {
296
- throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');
297
- }
298
-
299
- return this._stream(response.clone(), this._options.onDownloadProgress);
300
- }
301
-
302
- return response;
303
- };
304
-
305
- const isRetriableMethod = this._options.retry.methods.includes(this.request.method.toLowerCase());
306
- const result = isRetriableMethod ? this._retry(fn) : fn();
307
-
308
- for (const [type, mimeType] of Object.entries(responseTypes)) {
309
- result[type] = async () => {
310
- this.request.headers.set('accept', this.request.headers.get('accept') || mimeType);
311
-
312
- const response = (await result).clone();
313
-
314
- if (type === 'json') {
315
- if (response.status === 204) {
316
- return '';
317
- }
318
-
319
- if (options.parseJson) {
320
- return options.parseJson(await response.text());
321
- }
322
- }
323
-
324
- return response[type]();
325
- };
326
- }
327
-
328
- return result;
329
- }
330
-
331
- _calculateRetryDelay(error) {
332
- this._retryCount++;
333
-
334
- if (this._retryCount < this._options.retry.limit && !(error instanceof TimeoutError)) {
335
- if (error instanceof HTTPError) {
336
- if (!this._options.retry.statusCodes.includes(error.response.status)) {
337
- return 0;
338
- }
339
-
340
- const retryAfter = error.response.headers.get('Retry-After');
341
- if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
342
- let after = Number(retryAfter);
343
- if (Number.isNaN(after)) {
344
- after = Date.parse(retryAfter) - Date.now();
345
- } else {
346
- after *= 1000;
347
- }
348
-
349
- if (typeof this._options.retry.maxRetryAfter !== 'undefined' && after > this._options.retry.maxRetryAfter) {
350
- return 0;
351
- }
352
-
353
- return after;
354
- }
355
-
356
- if (error.response.status === 413) {
357
- return 0;
358
- }
359
- }
360
-
361
- const BACKOFF_FACTOR = 0.3;
362
- return BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000;
363
- }
364
-
365
- return 0;
366
- }
367
-
368
- _decorateResponse(response) {
369
- if (this._options.parseJson) {
370
- response.json = async () => {
371
- return this._options.parseJson(await response.text());
372
- };
373
- }
374
-
375
- return response;
376
- }
377
-
378
- async _retry(fn) {
379
- try {
380
- return await fn();
381
- } catch (error) {
382
- const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
383
- if (ms !== 0 && this._retryCount > 0) {
384
- await delay(ms);
385
-
386
- for (const hook of this._options.hooks.beforeRetry) {
387
- // eslint-disable-next-line no-await-in-loop
388
- const hookResult = await hook({
389
- request: this.request,
390
- options: this._options,
391
- error,
392
- retryCount: this._retryCount
393
- });
394
-
395
- // If `stop` is returned from the hook, the retry process is stopped
396
- if (hookResult === stop) {
397
- return;
398
- }
399
- }
400
-
401
- return this._retry(fn);
402
- }
403
-
404
- if (this._options.throwHttpErrors) {
405
- throw error;
406
- }
407
- }
408
- }
409
-
410
- async _fetch() {
411
- for (const hook of this._options.hooks.beforeRequest) {
412
- // eslint-disable-next-line no-await-in-loop
413
- const result = await hook(this.request, this._options);
414
-
415
- if (result instanceof Request) {
416
- this.request = result;
417
- break;
418
- }
419
-
420
- if (result instanceof Response) {
421
- return result;
422
- }
423
- }
424
-
425
- if (this._options.timeout === false) {
426
- return this._options.fetch(this.request.clone());
427
- }
428
-
429
- return timeout(this.request.clone(), this.abortController, this._options);
430
- }
431
-
432
- /* istanbul ignore next */
433
- _stream(response, onDownloadProgress) {
434
- const totalBytes = Number(response.headers.get('content-length')) || 0;
435
- let transferredBytes = 0;
436
-
437
- return new globalThis.Response(
438
- new globalThis.ReadableStream({
439
- async start(controller) {
440
- const reader = response.body.getReader();
441
-
442
- if (onDownloadProgress) {
443
- onDownloadProgress({percent: 0, transferredBytes: 0, totalBytes}, new Uint8Array());
444
- }
445
-
446
- async function read() {
447
- const {done, value} = await reader.read();
448
- if (done) {
449
- controller.close();
450
- return;
451
- }
452
-
453
- if (onDownloadProgress) {
454
- transferredBytes += value.byteLength;
455
- const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
456
- onDownloadProgress({percent, transferredBytes, totalBytes}, value);
457
- }
458
-
459
- controller.enqueue(value);
460
- await read();
461
- }
462
-
463
- await read();
464
- }
465
- })
466
- );
467
- }
468
- }
469
-
470
- const validateAndMerge = (...sources) => {
471
- for (const source of sources) {
472
- if ((!isObject(source) || Array.isArray(source)) && typeof source !== 'undefined') {
473
- throw new TypeError('The `options` argument must be an object');
474
- }
475
- }
476
-
477
- return deepMerge({}, ...sources);
478
- };
479
-
480
- const createInstance = defaults => {
481
- const ky = (input, options) => new Ky(input, validateAndMerge(defaults, options));
482
-
483
- for (const method of requestMethods) {
484
- ky[method] = (input, options) => new Ky(input, validateAndMerge(defaults, options, {method}));
485
- }
486
-
487
- ky.HTTPError = HTTPError;
488
- ky.TimeoutError = TimeoutError;
489
- ky.create = newDefaults => createInstance(validateAndMerge(newDefaults));
490
- ky.extend = newDefaults => createInstance(validateAndMerge(defaults, newDefaults));
491
- ky.stop = stop;
492
-
493
- return ky;
494
- };
495
-
496
- const ky = createInstance();
497
-
498
- return ky;
499
-
500
- })));
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ky = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ // eslint-lint-disable-next-line @typescript-eslint/naming-convention
8
+ class HTTPError extends Error {
9
+ constructor(response, request, options) {
10
+ const code = (response.status || response.status === 0) ? response.status : '';
11
+ const title = response.statusText || '';
12
+ const status = `${code} ${title}`.trim();
13
+ const reason = status ? `status code ${status}` : 'an unknown error';
14
+ super(`Request failed with ${reason}`);
15
+ this.name = 'HTTPError';
16
+ this.response = response;
17
+ this.request = request;
18
+ this.options = options;
19
+ }
20
+ }
21
+
22
+ class TimeoutError extends Error {
23
+ constructor(request) {
24
+ super('Request timed out');
25
+ this.name = 'TimeoutError';
26
+ this.request = request;
27
+ }
28
+ }
29
+
30
+ // eslint-disable-next-line @typescript-eslint/ban-types
31
+ const isObject = (value) => value !== null && typeof value === 'object';
32
+
33
+ const validateAndMerge = (...sources) => {
34
+ for (const source of sources) {
35
+ if ((!isObject(source) || Array.isArray(source)) && typeof source !== 'undefined') {
36
+ throw new TypeError('The `options` argument must be an object');
37
+ }
38
+ }
39
+ return deepMerge({}, ...sources);
40
+ };
41
+ const mergeHeaders = (source1 = {}, source2 = {}) => {
42
+ const result = new globalThis.Headers(source1);
43
+ const isHeadersInstance = source2 instanceof globalThis.Headers;
44
+ const source = new globalThis.Headers(source2);
45
+ for (const [key, value] of source.entries()) {
46
+ if ((isHeadersInstance && value === 'undefined') || value === undefined) {
47
+ result.delete(key);
48
+ }
49
+ else {
50
+ result.set(key, value);
51
+ }
52
+ }
53
+ return result;
54
+ };
55
+ // TODO: Make this strongly-typed (no `any`).
56
+ const deepMerge = (...sources) => {
57
+ let returnValue = {};
58
+ let headers = {};
59
+ for (const source of sources) {
60
+ if (Array.isArray(source)) {
61
+ if (!Array.isArray(returnValue)) {
62
+ returnValue = [];
63
+ }
64
+ returnValue = [...returnValue, ...source];
65
+ }
66
+ else if (isObject(source)) {
67
+ for (let [key, value] of Object.entries(source)) {
68
+ if (isObject(value) && key in returnValue) {
69
+ value = deepMerge(returnValue[key], value);
70
+ }
71
+ returnValue = { ...returnValue, [key]: value };
72
+ }
73
+ if (isObject(source.headers)) {
74
+ headers = mergeHeaders(headers, source.headers);
75
+ returnValue.headers = headers;
76
+ }
77
+ }
78
+ }
79
+ return returnValue;
80
+ };
81
+
82
+ const supportsAbortController = typeof globalThis.AbortController === 'function';
83
+ const supportsStreams = typeof globalThis.ReadableStream === 'function';
84
+ const supportsFormData = typeof globalThis.FormData === 'function';
85
+ const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'];
86
+ const responseTypes = {
87
+ json: 'application/json',
88
+ text: 'text/*',
89
+ formData: 'multipart/form-data',
90
+ arrayBuffer: '*/*',
91
+ blob: '*/*',
92
+ };
93
+ // The maximum value of a 32bit int (see issue #117)
94
+ const maxSafeTimeout = 2147483647;
95
+ const stop = Symbol('stop');
96
+
97
+ const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
98
+ const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];
99
+ const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
100
+ const retryAfterStatusCodes = [413, 429, 503];
101
+ const defaultRetryOptions = {
102
+ limit: 2,
103
+ methods: retryMethods,
104
+ statusCodes: retryStatusCodes,
105
+ afterStatusCodes: retryAfterStatusCodes,
106
+ maxRetryAfter: Number.POSITIVE_INFINITY,
107
+ };
108
+ const normalizeRetryOptions = (retry = {}) => {
109
+ if (typeof retry === 'number') {
110
+ return {
111
+ ...defaultRetryOptions,
112
+ limit: retry,
113
+ };
114
+ }
115
+ if (retry.methods && !Array.isArray(retry.methods)) {
116
+ throw new Error('retry.methods must be an array');
117
+ }
118
+ if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
119
+ throw new Error('retry.statusCodes must be an array');
120
+ }
121
+ return {
122
+ ...defaultRetryOptions,
123
+ ...retry,
124
+ afterStatusCodes: retryAfterStatusCodes,
125
+ };
126
+ };
127
+
128
+ // `Promise.race()` workaround (#91)
129
+ const timeout = async (request, abortController, options) => new Promise((resolve, reject) => {
130
+ const timeoutId = setTimeout(() => {
131
+ if (abortController) {
132
+ abortController.abort();
133
+ }
134
+ reject(new TimeoutError(request));
135
+ }, options.timeout);
136
+ /* eslint-disable promise/prefer-await-to-then */
137
+ void options
138
+ .fetch(request)
139
+ .then(resolve)
140
+ .catch(reject)
141
+ .then(() => {
142
+ clearTimeout(timeoutId);
143
+ });
144
+ /* eslint-enable promise/prefer-await-to-then */
145
+ });
146
+ const delay = async (ms) => new Promise(resolve => {
147
+ setTimeout(resolve, ms);
148
+ });
149
+
150
+ class Ky {
151
+ // eslint-disable-next-line complexity
152
+ constructor(input, options = {}) {
153
+ var _a, _b;
154
+ this._retryCount = 0;
155
+ this._input = input;
156
+ this._options = {
157
+ // TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
158
+ credentials: this._input.credentials || 'same-origin',
159
+ ...options,
160
+ headers: mergeHeaders(this._input.headers, options.headers),
161
+ hooks: deepMerge({
162
+ beforeRequest: [],
163
+ beforeRetry: [],
164
+ afterResponse: [],
165
+ }, options.hooks),
166
+ method: normalizeRequestMethod((_a = options.method) !== null && _a !== void 0 ? _a : this._input.method),
167
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
168
+ prefixUrl: String(options.prefixUrl || ''),
169
+ retry: normalizeRetryOptions(options.retry),
170
+ throwHttpErrors: options.throwHttpErrors !== false,
171
+ timeout: typeof options.timeout === 'undefined' ? 10000 : options.timeout,
172
+ fetch: (_b = options.fetch) !== null && _b !== void 0 ? _b : globalThis.fetch.bind(globalThis),
173
+ };
174
+ if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {
175
+ throw new TypeError('`input` must be a string, URL, or Request');
176
+ }
177
+ if (this._options.prefixUrl && typeof this._input === 'string') {
178
+ if (this._input.startsWith('/')) {
179
+ throw new Error('`input` must not begin with a slash when using `prefixUrl`');
180
+ }
181
+ if (!this._options.prefixUrl.endsWith('/')) {
182
+ this._options.prefixUrl += '/';
183
+ }
184
+ this._input = this._options.prefixUrl + this._input;
185
+ }
186
+ if (supportsAbortController) {
187
+ this.abortController = new globalThis.AbortController();
188
+ if (this._options.signal) {
189
+ this._options.signal.addEventListener('abort', () => {
190
+ this.abortController.abort();
191
+ });
192
+ }
193
+ this._options.signal = this.abortController.signal;
194
+ }
195
+ this.request = new globalThis.Request(this._input, this._options);
196
+ if (this._options.searchParams) {
197
+ // eslint-disable-next-line unicorn/prevent-abbreviations
198
+ const textSearchParams = typeof this._options.searchParams === 'string'
199
+ ? this._options.searchParams.replace(/^\?/, '')
200
+ : new URLSearchParams(this._options.searchParams).toString();
201
+ // eslint-disable-next-line unicorn/prevent-abbreviations
202
+ const searchParams = '?' + textSearchParams;
203
+ const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
204
+ // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
205
+ if (((supportsFormData && this._options.body instanceof globalThis.FormData)
206
+ || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
207
+ this.request.headers.delete('content-type');
208
+ }
209
+ this.request = new globalThis.Request(new globalThis.Request(url, this.request), this._options);
210
+ }
211
+ if (this._options.json !== undefined) {
212
+ this._options.body = JSON.stringify(this._options.json);
213
+ this.request.headers.set('content-type', 'application/json');
214
+ this.request = new globalThis.Request(this.request, { body: this._options.body });
215
+ }
216
+ }
217
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
218
+ static create(input, options) {
219
+ const ky = new Ky(input, options);
220
+ const fn = async () => {
221
+ if (ky._options.timeout > maxSafeTimeout) {
222
+ throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
223
+ }
224
+ // Delay the fetch so that body method shortcuts can set the Accept header
225
+ await Promise.resolve();
226
+ let response = await ky._fetch();
227
+ for (const hook of ky._options.hooks.afterResponse) {
228
+ // eslint-disable-next-line no-await-in-loop
229
+ const modifiedResponse = await hook(ky.request, ky._options, ky._decorateResponse(response.clone()));
230
+ if (modifiedResponse instanceof globalThis.Response) {
231
+ response = modifiedResponse;
232
+ }
233
+ }
234
+ ky._decorateResponse(response);
235
+ if (!response.ok && ky._options.throwHttpErrors) {
236
+ throw new HTTPError(response, ky.request, ky._options);
237
+ }
238
+ // If `onDownloadProgress` is passed, it uses the stream API internally
239
+ /* istanbul ignore next */
240
+ if (ky._options.onDownloadProgress) {
241
+ if (typeof ky._options.onDownloadProgress !== 'function') {
242
+ throw new TypeError('The `onDownloadProgress` option must be a function');
243
+ }
244
+ if (!supportsStreams) {
245
+ throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');
246
+ }
247
+ return ky._stream(response.clone(), ky._options.onDownloadProgress);
248
+ }
249
+ return response;
250
+ };
251
+ const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());
252
+ const result = (isRetriableMethod ? ky._retry(fn) : fn());
253
+ for (const [type, mimeType] of Object.entries(responseTypes)) {
254
+ result[type] = async () => {
255
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
256
+ ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);
257
+ const response = (await result).clone();
258
+ if (type === 'json') {
259
+ if (response.status === 204) {
260
+ return '';
261
+ }
262
+ if (options.parseJson) {
263
+ return options.parseJson(await response.text());
264
+ }
265
+ }
266
+ return response[type]();
267
+ };
268
+ }
269
+ return result;
270
+ }
271
+ _calculateRetryDelay(error) {
272
+ this._retryCount++;
273
+ if (this._retryCount < this._options.retry.limit && !(error instanceof TimeoutError)) {
274
+ if (error instanceof HTTPError) {
275
+ if (!this._options.retry.statusCodes.includes(error.response.status)) {
276
+ return 0;
277
+ }
278
+ const retryAfter = error.response.headers.get('Retry-After');
279
+ if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
280
+ let after = Number(retryAfter);
281
+ if (Number.isNaN(after)) {
282
+ after = Date.parse(retryAfter) - Date.now();
283
+ }
284
+ else {
285
+ after *= 1000;
286
+ }
287
+ if (typeof this._options.retry.maxRetryAfter !== 'undefined' && after > this._options.retry.maxRetryAfter) {
288
+ return 0;
289
+ }
290
+ return after;
291
+ }
292
+ if (error.response.status === 413) {
293
+ return 0;
294
+ }
295
+ }
296
+ const BACKOFF_FACTOR = 0.3;
297
+ return BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000;
298
+ }
299
+ return 0;
300
+ }
301
+ _decorateResponse(response) {
302
+ if (this._options.parseJson) {
303
+ response.json = async () => this._options.parseJson(await response.text());
304
+ }
305
+ return response;
306
+ }
307
+ async _retry(fn) {
308
+ try {
309
+ return await fn();
310
+ // eslint-disable-next-line @typescript-eslint/no-implicit-any-catch
311
+ }
312
+ catch (error) {
313
+ const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
314
+ if (ms !== 0 && this._retryCount > 0) {
315
+ await delay(ms);
316
+ for (const hook of this._options.hooks.beforeRetry) {
317
+ // eslint-disable-next-line no-await-in-loop
318
+ const hookResult = await hook({
319
+ request: this.request,
320
+ options: this._options,
321
+ error: error,
322
+ retryCount: this._retryCount,
323
+ });
324
+ // If `stop` is returned from the hook, the retry process is stopped
325
+ if (hookResult === stop) {
326
+ return;
327
+ }
328
+ }
329
+ return this._retry(fn);
330
+ }
331
+ throw error;
332
+ }
333
+ }
334
+ async _fetch() {
335
+ for (const hook of this._options.hooks.beforeRequest) {
336
+ // eslint-disable-next-line no-await-in-loop
337
+ const result = await hook(this.request, this._options);
338
+ if (result instanceof Request) {
339
+ this.request = result;
340
+ break;
341
+ }
342
+ if (result instanceof Response) {
343
+ return result;
344
+ }
345
+ }
346
+ if (this._options.timeout === false) {
347
+ return this._options.fetch(this.request.clone());
348
+ }
349
+ return timeout(this.request.clone(), this.abortController, this._options);
350
+ }
351
+ /* istanbul ignore next */
352
+ _stream(response, onDownloadProgress) {
353
+ const totalBytes = Number(response.headers.get('content-length')) || 0;
354
+ let transferredBytes = 0;
355
+ return new globalThis.Response(new globalThis.ReadableStream({
356
+ async start(controller) {
357
+ const reader = response.body.getReader();
358
+ if (onDownloadProgress) {
359
+ onDownloadProgress({ percent: 0, transferredBytes: 0, totalBytes }, new Uint8Array());
360
+ }
361
+ async function read() {
362
+ const { done, value } = await reader.read();
363
+ if (done) {
364
+ controller.close();
365
+ return;
366
+ }
367
+ if (onDownloadProgress) {
368
+ transferredBytes += value.byteLength;
369
+ const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
370
+ onDownloadProgress({ percent, transferredBytes, totalBytes }, value);
371
+ }
372
+ controller.enqueue(value);
373
+ await read();
374
+ }
375
+ await read();
376
+ },
377
+ }));
378
+ }
379
+ }
380
+
381
+ /*! MIT License © Sindre Sorhus */
382
+ const createInstance = (defaults) => {
383
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
384
+ const ky = (input, options) => Ky.create(input, validateAndMerge(defaults, options));
385
+ for (const method of requestMethods) {
386
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
387
+ ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));
388
+ }
389
+ ky.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
390
+ ky.extend = (newDefaults) => createInstance(validateAndMerge(defaults, newDefaults));
391
+ ky.stop = stop;
392
+ return ky;
393
+ };
394
+ const ky = createInstance();
395
+
396
+ exports.HTTPError = HTTPError;
397
+ exports.TimeoutError = TimeoutError;
398
+ exports["default"] = ky;
399
+
400
+ Object.defineProperty(exports, '__esModule', { value: true });
401
+
402
+ }));