@microlink/mql 0.10.19 → 0.10.22

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/mql.js CHANGED
@@ -7,8 +7,14 @@
7
7
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
8
8
 
9
9
  function getAugmentedNamespace(n) {
10
- if (n.__esModule) return n;
11
- var a = Object.defineProperty({}, '__esModule', {value: true});
10
+ var f = n.default;
11
+ if (typeof f == "function") {
12
+ var a = function () {
13
+ return f.apply(this, arguments);
14
+ };
15
+ a.prototype = f.prototype;
16
+ } else a = {};
17
+ Object.defineProperty(a, '__esModule', {value: true});
12
18
  Object.keys(n).forEach(function (k) {
13
19
  var d = Object.getOwnPropertyDescriptor(n, k);
14
20
  Object.defineProperty(a, k, d.get ? d : {
@@ -132,6 +138,11 @@
132
138
  return;
133
139
  }
134
140
 
141
+ // `Function#arguments` and `Function#caller` should not be copied. They were reported to be present in `Reflect.ownKeys` for some devices in React Native (#41), so we explicitly ignore them here.
142
+ if (property === 'arguments' || property === 'caller') {
143
+ return;
144
+ }
145
+
135
146
  const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
136
147
  const fromDescriptor = Object.getOwnPropertyDescriptor(from, property);
137
148
 
@@ -211,7 +222,7 @@
211
222
  }
212
223
  };
213
224
 
214
- const {isFunction, composeErrorMessage} = helpers;
225
+ const { isFunction, composeErrorMessage } = helpers;
215
226
 
216
227
  function interfaceObject (error, ...props) {
217
228
  Object.assign(error, ...props);
@@ -219,8 +230,8 @@
219
230
  error.description = isFunction(error.message) ? error.message(error) : error.message;
220
231
 
221
232
  error.message = error.code
222
- ? composeErrorMessage(error.code, error.description)
223
- : error.description;
233
+ ? composeErrorMessage(error.code, error.description)
234
+ : error.description;
224
235
  }
225
236
 
226
237
  var addErrorProps$1 = interfaceObject;
@@ -229,12 +240,12 @@
229
240
  const mimicFn$1 = mimicFn_1;
230
241
 
231
242
  const addErrorProps = addErrorProps$1;
232
- const {isString} = helpers;
243
+ const { isString } = helpers;
233
244
 
234
245
  function createExtendError$1 (ErrorClass, classProps) {
235
246
  function ExtendError (props) {
236
247
  const error = new ErrorClass();
237
- const errorProps = isString(props) ? {message: props} : props;
248
+ const errorProps = isString(props) ? { message: props } : props;
238
249
  addErrorProps(error, classProps, errorProps);
239
250
 
240
251
  error.stack = cleanStack(error.stack);
@@ -249,7 +260,7 @@
249
260
 
250
261
  var createExtendError_1 = createExtendError$1;
251
262
 
252
- const {inherits} = helpers;
263
+ const { inherits } = helpers;
253
264
  const mimicFn = mimicFn_1;
254
265
 
255
266
  const REGEX_CLASS_NAME = /[^0-9a-zA-Z_$]/;
@@ -270,7 +281,9 @@
270
281
  writable: true
271
282
  });
272
283
 
273
- Error.captureStackTrace(this, this.constructor);
284
+ if ('captureStackTrace' in Error) {
285
+ Error.captureStackTrace(this, this.constructor);
286
+ }
274
287
  }
275
288
 
276
289
  inherits(ErrorClass, Error);
@@ -303,6 +316,12 @@
303
316
 
304
317
  const isObject = input => input !== null && typeof input === 'object';
305
318
 
319
+ const isBuffer = input =>
320
+ input != null &&
321
+ input.constructor != null &&
322
+ typeof input.constructor.isBuffer === 'function' &&
323
+ input.constructor.isBuffer(input);
324
+
306
325
  const parseBody = (input, error, url) => {
307
326
  try {
308
327
  return JSON.parse(input)
@@ -323,13 +342,13 @@
323
342
  const factory$1 = ({
324
343
  VERSION,
325
344
  MicrolinkError,
326
- isUrlHttp,
345
+ urlHttp,
327
346
  stringify,
328
347
  got,
329
348
  flatten
330
349
  }) => {
331
350
  const assertUrl = (url = '') => {
332
- if (!isUrlHttp(url)) {
351
+ if (!urlHttp(url)) {
333
352
  const message = `The \`url\` as \`${url}\` is not valid. Ensure it has protocol (http or https) and hostname.`;
334
353
  throw new MicrolinkError({
335
354
  status: 'fail',
@@ -360,12 +379,12 @@
360
379
  } catch (err) {
361
380
  const { response = {} } = err;
362
381
  const { statusCode, body: rawBody, headers, url: uri = apiUrl } = response;
363
- const isBuffer = Buffer.isBuffer(rawBody);
382
+ const isBodyBuffer = isBuffer(rawBody);
364
383
 
365
384
  const body =
366
- isObject(rawBody) && !isBuffer
385
+ isObject(rawBody) && !isBodyBuffer
367
386
  ? rawBody
368
- : parseBody(isBuffer ? rawBody.toString() : rawBody, err, uri);
387
+ : parseBody(isBodyBuffer ? rawBody.toString() : rawBody, err, uri);
369
388
 
370
389
  if (body.code === 'EFATALCLIENT' && retryCount++ < 2) {
371
390
  return fetchFromApi(apiUrl, opts, retryCount)
@@ -427,414 +446,414 @@
427
446
  var ky$1 = {exports: {}};
428
447
 
429
448
  (function (module, exports) {
430
- (function (global, factory) {
431
- factory(exports) ;
432
- })(commonjsGlobal, (function (exports) {
433
- // eslint-lint-disable-next-line @typescript-eslint/naming-convention
434
- class HTTPError extends Error {
435
- constructor(response, request, options) {
436
- const code = (response.status || response.status === 0) ? response.status : '';
437
- const title = response.statusText || '';
438
- const status = `${code} ${title}`.trim();
439
- const reason = status ? `status code ${status}` : 'an unknown error';
440
- super(`Request failed with ${reason}`);
441
- this.name = 'HTTPError';
442
- this.response = response;
443
- this.request = request;
444
- this.options = options;
445
- }
446
- }
447
-
448
- class TimeoutError extends Error {
449
- constructor(request) {
450
- super('Request timed out');
451
- this.name = 'TimeoutError';
452
- this.request = request;
453
- }
454
- }
455
-
456
- // eslint-disable-next-line @typescript-eslint/ban-types
457
- const isObject = (value) => value !== null && typeof value === 'object';
458
-
459
- const validateAndMerge = (...sources) => {
460
- for (const source of sources) {
461
- if ((!isObject(source) || Array.isArray(source)) && typeof source !== 'undefined') {
462
- throw new TypeError('The `options` argument must be an object');
463
- }
464
- }
465
- return deepMerge({}, ...sources);
466
- };
467
- const mergeHeaders = (source1 = {}, source2 = {}) => {
468
- const result = new globalThis.Headers(source1);
469
- const isHeadersInstance = source2 instanceof globalThis.Headers;
470
- const source = new globalThis.Headers(source2);
471
- for (const [key, value] of source.entries()) {
472
- if ((isHeadersInstance && value === 'undefined') || value === undefined) {
473
- result.delete(key);
474
- }
475
- else {
476
- result.set(key, value);
477
- }
478
- }
479
- return result;
480
- };
481
- // TODO: Make this strongly-typed (no `any`).
482
- const deepMerge = (...sources) => {
483
- let returnValue = {};
484
- let headers = {};
485
- for (const source of sources) {
486
- if (Array.isArray(source)) {
487
- if (!Array.isArray(returnValue)) {
488
- returnValue = [];
489
- }
490
- returnValue = [...returnValue, ...source];
491
- }
492
- else if (isObject(source)) {
493
- for (let [key, value] of Object.entries(source)) {
494
- if (isObject(value) && key in returnValue) {
495
- value = deepMerge(returnValue[key], value);
496
- }
497
- returnValue = { ...returnValue, [key]: value };
498
- }
499
- if (isObject(source.headers)) {
500
- headers = mergeHeaders(headers, source.headers);
501
- returnValue.headers = headers;
502
- }
503
- }
504
- }
505
- return returnValue;
506
- };
507
-
508
- const supportsAbortController = typeof globalThis.AbortController === 'function';
509
- const supportsStreams = typeof globalThis.ReadableStream === 'function';
510
- const supportsFormData = typeof globalThis.FormData === 'function';
511
- const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'];
512
- const responseTypes = {
513
- json: 'application/json',
514
- text: 'text/*',
515
- formData: 'multipart/form-data',
516
- arrayBuffer: '*/*',
517
- blob: '*/*',
518
- };
519
- // The maximum value of a 32bit int (see issue #117)
520
- const maxSafeTimeout = 2147483647;
521
- const stop = Symbol('stop');
522
-
523
- const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
524
- const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];
525
- const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
526
- const retryAfterStatusCodes = [413, 429, 503];
527
- const defaultRetryOptions = {
528
- limit: 2,
529
- methods: retryMethods,
530
- statusCodes: retryStatusCodes,
531
- afterStatusCodes: retryAfterStatusCodes,
532
- maxRetryAfter: Number.POSITIVE_INFINITY,
533
- };
534
- const normalizeRetryOptions = (retry = {}) => {
535
- if (typeof retry === 'number') {
536
- return {
537
- ...defaultRetryOptions,
538
- limit: retry,
539
- };
540
- }
541
- if (retry.methods && !Array.isArray(retry.methods)) {
542
- throw new Error('retry.methods must be an array');
543
- }
544
- if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
545
- throw new Error('retry.statusCodes must be an array');
546
- }
547
- return {
548
- ...defaultRetryOptions,
549
- ...retry,
550
- afterStatusCodes: retryAfterStatusCodes,
551
- };
552
- };
553
-
554
- // `Promise.race()` workaround (#91)
555
- const timeout = async (request, abortController, options) => new Promise((resolve, reject) => {
556
- const timeoutId = setTimeout(() => {
557
- if (abortController) {
558
- abortController.abort();
559
- }
560
- reject(new TimeoutError(request));
561
- }, options.timeout);
562
- /* eslint-disable promise/prefer-await-to-then */
563
- void options
564
- .fetch(request)
565
- .then(resolve)
566
- .catch(reject)
567
- .then(() => {
568
- clearTimeout(timeoutId);
569
- });
570
- /* eslint-enable promise/prefer-await-to-then */
571
- });
572
- const delay = async (ms) => new Promise(resolve => {
573
- setTimeout(resolve, ms);
574
- });
575
-
576
- class Ky {
577
- // eslint-disable-next-line complexity
578
- constructor(input, options = {}) {
579
- var _a, _b;
580
- this._retryCount = 0;
581
- this._input = input;
582
- this._options = {
583
- // TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
584
- credentials: this._input.credentials || 'same-origin',
585
- ...options,
586
- headers: mergeHeaders(this._input.headers, options.headers),
587
- hooks: deepMerge({
588
- beforeRequest: [],
589
- beforeRetry: [],
590
- beforeError: [],
591
- afterResponse: [],
592
- }, options.hooks),
593
- method: normalizeRequestMethod((_a = options.method) !== null && _a !== void 0 ? _a : this._input.method),
594
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
595
- prefixUrl: String(options.prefixUrl || ''),
596
- retry: normalizeRetryOptions(options.retry),
597
- throwHttpErrors: options.throwHttpErrors !== false,
598
- timeout: typeof options.timeout === 'undefined' ? 10000 : options.timeout,
599
- fetch: (_b = options.fetch) !== null && _b !== void 0 ? _b : globalThis.fetch.bind(globalThis),
600
- };
601
- if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {
602
- throw new TypeError('`input` must be a string, URL, or Request');
603
- }
604
- if (this._options.prefixUrl && typeof this._input === 'string') {
605
- if (this._input.startsWith('/')) {
606
- throw new Error('`input` must not begin with a slash when using `prefixUrl`');
607
- }
608
- if (!this._options.prefixUrl.endsWith('/')) {
609
- this._options.prefixUrl += '/';
610
- }
611
- this._input = this._options.prefixUrl + this._input;
612
- }
613
- if (supportsAbortController) {
614
- this.abortController = new globalThis.AbortController();
615
- if (this._options.signal) {
616
- this._options.signal.addEventListener('abort', () => {
617
- this.abortController.abort();
618
- });
619
- }
620
- this._options.signal = this.abortController.signal;
621
- }
622
- this.request = new globalThis.Request(this._input, this._options);
623
- if (this._options.searchParams) {
624
- // eslint-disable-next-line unicorn/prevent-abbreviations
625
- const textSearchParams = typeof this._options.searchParams === 'string'
626
- ? this._options.searchParams.replace(/^\?/, '')
627
- : new URLSearchParams(this._options.searchParams).toString();
628
- // eslint-disable-next-line unicorn/prevent-abbreviations
629
- const searchParams = '?' + textSearchParams;
630
- const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
631
- // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
632
- if (((supportsFormData && this._options.body instanceof globalThis.FormData)
633
- || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
634
- this.request.headers.delete('content-type');
635
- }
636
- this.request = new globalThis.Request(new globalThis.Request(url, this.request), this._options);
637
- }
638
- if (this._options.json !== undefined) {
639
- this._options.body = JSON.stringify(this._options.json);
640
- this.request.headers.set('content-type', 'application/json');
641
- this.request = new globalThis.Request(this.request, { body: this._options.body });
642
- }
643
- }
644
- // eslint-disable-next-line @typescript-eslint/promise-function-async
645
- static create(input, options) {
646
- const ky = new Ky(input, options);
647
- const fn = async () => {
648
- if (ky._options.timeout > maxSafeTimeout) {
649
- throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
650
- }
651
- // Delay the fetch so that body method shortcuts can set the Accept header
652
- await Promise.resolve();
653
- let response = await ky._fetch();
654
- for (const hook of ky._options.hooks.afterResponse) {
655
- // eslint-disable-next-line no-await-in-loop
656
- const modifiedResponse = await hook(ky.request, ky._options, ky._decorateResponse(response.clone()));
657
- if (modifiedResponse instanceof globalThis.Response) {
658
- response = modifiedResponse;
659
- }
660
- }
661
- ky._decorateResponse(response);
662
- if (!response.ok && ky._options.throwHttpErrors) {
663
- let error = new HTTPError(response, ky.request, ky._options);
664
- for (const hook of ky._options.hooks.beforeError) {
665
- // eslint-disable-next-line no-await-in-loop
666
- error = await hook(error);
667
- }
668
- throw error;
669
- }
670
- // If `onDownloadProgress` is passed, it uses the stream API internally
671
- /* istanbul ignore next */
672
- if (ky._options.onDownloadProgress) {
673
- if (typeof ky._options.onDownloadProgress !== 'function') {
674
- throw new TypeError('The `onDownloadProgress` option must be a function');
675
- }
676
- if (!supportsStreams) {
677
- throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');
678
- }
679
- return ky._stream(response.clone(), ky._options.onDownloadProgress);
680
- }
681
- return response;
682
- };
683
- const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());
684
- const result = (isRetriableMethod ? ky._retry(fn) : fn());
685
- for (const [type, mimeType] of Object.entries(responseTypes)) {
686
- result[type] = async () => {
687
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
688
- ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);
689
- const response = (await result).clone();
690
- if (type === 'json') {
691
- if (response.status === 204) {
692
- return '';
693
- }
694
- if (options.parseJson) {
695
- return options.parseJson(await response.text());
696
- }
697
- }
698
- return response[type]();
699
- };
700
- }
701
- return result;
702
- }
703
- _calculateRetryDelay(error) {
704
- this._retryCount++;
705
- if (this._retryCount < this._options.retry.limit && !(error instanceof TimeoutError)) {
706
- if (error instanceof HTTPError) {
707
- if (!this._options.retry.statusCodes.includes(error.response.status)) {
708
- return 0;
709
- }
710
- const retryAfter = error.response.headers.get('Retry-After');
711
- if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
712
- let after = Number(retryAfter);
713
- if (Number.isNaN(after)) {
714
- after = Date.parse(retryAfter) - Date.now();
715
- }
716
- else {
717
- after *= 1000;
718
- }
719
- if (typeof this._options.retry.maxRetryAfter !== 'undefined' && after > this._options.retry.maxRetryAfter) {
720
- return 0;
721
- }
722
- return after;
723
- }
724
- if (error.response.status === 413) {
725
- return 0;
726
- }
727
- }
728
- const BACKOFF_FACTOR = 0.3;
729
- return BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000;
730
- }
731
- return 0;
732
- }
733
- _decorateResponse(response) {
734
- if (this._options.parseJson) {
735
- response.json = async () => this._options.parseJson(await response.text());
736
- }
737
- return response;
738
- }
739
- async _retry(fn) {
740
- try {
741
- return await fn();
742
- // eslint-disable-next-line @typescript-eslint/no-implicit-any-catch
743
- }
744
- catch (error) {
745
- const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
746
- if (ms !== 0 && this._retryCount > 0) {
747
- await delay(ms);
748
- for (const hook of this._options.hooks.beforeRetry) {
749
- // eslint-disable-next-line no-await-in-loop
750
- const hookResult = await hook({
751
- request: this.request,
752
- options: this._options,
753
- error: error,
754
- retryCount: this._retryCount,
755
- });
756
- // If `stop` is returned from the hook, the retry process is stopped
757
- if (hookResult === stop) {
758
- return;
759
- }
760
- }
761
- return this._retry(fn);
762
- }
763
- throw error;
764
- }
765
- }
766
- async _fetch() {
767
- for (const hook of this._options.hooks.beforeRequest) {
768
- // eslint-disable-next-line no-await-in-loop
769
- const result = await hook(this.request, this._options);
770
- if (result instanceof Request) {
771
- this.request = result;
772
- break;
773
- }
774
- if (result instanceof Response) {
775
- return result;
776
- }
777
- }
778
- if (this._options.timeout === false) {
779
- return this._options.fetch(this.request.clone());
780
- }
781
- return timeout(this.request.clone(), this.abortController, this._options);
782
- }
783
- /* istanbul ignore next */
784
- _stream(response, onDownloadProgress) {
785
- const totalBytes = Number(response.headers.get('content-length')) || 0;
786
- let transferredBytes = 0;
787
- return new globalThis.Response(new globalThis.ReadableStream({
788
- async start(controller) {
789
- const reader = response.body.getReader();
790
- if (onDownloadProgress) {
791
- onDownloadProgress({ percent: 0, transferredBytes: 0, totalBytes }, new Uint8Array());
792
- }
793
- async function read() {
794
- const { done, value } = await reader.read();
795
- if (done) {
796
- controller.close();
797
- return;
798
- }
799
- if (onDownloadProgress) {
800
- transferredBytes += value.byteLength;
801
- const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
802
- onDownloadProgress({ percent, transferredBytes, totalBytes }, value);
803
- }
804
- controller.enqueue(value);
805
- await read();
806
- }
807
- await read();
808
- },
809
- }));
810
- }
811
- }
812
-
813
- /*! MIT License © Sindre Sorhus */
814
- const createInstance = (defaults) => {
815
- // eslint-disable-next-line @typescript-eslint/promise-function-async
816
- const ky = (input, options) => Ky.create(input, validateAndMerge(defaults, options));
817
- for (const method of requestMethods) {
818
- // eslint-disable-next-line @typescript-eslint/promise-function-async
819
- ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));
820
- }
821
- ky.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
822
- ky.extend = (newDefaults) => createInstance(validateAndMerge(defaults, newDefaults));
823
- ky.stop = stop;
824
- return ky;
825
- };
826
- const ky = createInstance();
827
-
828
- exports.HTTPError = HTTPError;
829
- exports.TimeoutError = TimeoutError;
830
- exports["default"] = ky;
831
-
832
- Object.defineProperty(exports, '__esModule', { value: true });
833
-
834
- }));
835
- }(ky$1, ky$1.exports));
836
-
837
- const isUrlHttp = lightweight;
449
+ (function (global, factory) {
450
+ factory(exports) ;
451
+ })(commonjsGlobal, (function (exports) {
452
+ // eslint-lint-disable-next-line @typescript-eslint/naming-convention
453
+ class HTTPError extends Error {
454
+ constructor(response, request, options) {
455
+ const code = (response.status || response.status === 0) ? response.status : '';
456
+ const title = response.statusText || '';
457
+ const status = `${code} ${title}`.trim();
458
+ const reason = status ? `status code ${status}` : 'an unknown error';
459
+ super(`Request failed with ${reason}`);
460
+ this.name = 'HTTPError';
461
+ this.response = response;
462
+ this.request = request;
463
+ this.options = options;
464
+ }
465
+ }
466
+
467
+ class TimeoutError extends Error {
468
+ constructor(request) {
469
+ super('Request timed out');
470
+ this.name = 'TimeoutError';
471
+ this.request = request;
472
+ }
473
+ }
474
+
475
+ // eslint-disable-next-line @typescript-eslint/ban-types
476
+ const isObject = (value) => value !== null && typeof value === 'object';
477
+
478
+ const validateAndMerge = (...sources) => {
479
+ for (const source of sources) {
480
+ if ((!isObject(source) || Array.isArray(source)) && typeof source !== 'undefined') {
481
+ throw new TypeError('The `options` argument must be an object');
482
+ }
483
+ }
484
+ return deepMerge({}, ...sources);
485
+ };
486
+ const mergeHeaders = (source1 = {}, source2 = {}) => {
487
+ const result = new globalThis.Headers(source1);
488
+ const isHeadersInstance = source2 instanceof globalThis.Headers;
489
+ const source = new globalThis.Headers(source2);
490
+ for (const [key, value] of source.entries()) {
491
+ if ((isHeadersInstance && value === 'undefined') || value === undefined) {
492
+ result.delete(key);
493
+ }
494
+ else {
495
+ result.set(key, value);
496
+ }
497
+ }
498
+ return result;
499
+ };
500
+ // TODO: Make this strongly-typed (no `any`).
501
+ const deepMerge = (...sources) => {
502
+ let returnValue = {};
503
+ let headers = {};
504
+ for (const source of sources) {
505
+ if (Array.isArray(source)) {
506
+ if (!Array.isArray(returnValue)) {
507
+ returnValue = [];
508
+ }
509
+ returnValue = [...returnValue, ...source];
510
+ }
511
+ else if (isObject(source)) {
512
+ for (let [key, value] of Object.entries(source)) {
513
+ if (isObject(value) && key in returnValue) {
514
+ value = deepMerge(returnValue[key], value);
515
+ }
516
+ returnValue = { ...returnValue, [key]: value };
517
+ }
518
+ if (isObject(source.headers)) {
519
+ headers = mergeHeaders(headers, source.headers);
520
+ returnValue.headers = headers;
521
+ }
522
+ }
523
+ }
524
+ return returnValue;
525
+ };
526
+
527
+ const supportsAbortController = typeof globalThis.AbortController === 'function';
528
+ const supportsStreams = typeof globalThis.ReadableStream === 'function';
529
+ const supportsFormData = typeof globalThis.FormData === 'function';
530
+ const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'];
531
+ const responseTypes = {
532
+ json: 'application/json',
533
+ text: 'text/*',
534
+ formData: 'multipart/form-data',
535
+ arrayBuffer: '*/*',
536
+ blob: '*/*',
537
+ };
538
+ // The maximum value of a 32bit int (see issue #117)
539
+ const maxSafeTimeout = 2147483647;
540
+ const stop = Symbol('stop');
541
+
542
+ const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
543
+ const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];
544
+ const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
545
+ const retryAfterStatusCodes = [413, 429, 503];
546
+ const defaultRetryOptions = {
547
+ limit: 2,
548
+ methods: retryMethods,
549
+ statusCodes: retryStatusCodes,
550
+ afterStatusCodes: retryAfterStatusCodes,
551
+ maxRetryAfter: Number.POSITIVE_INFINITY,
552
+ };
553
+ const normalizeRetryOptions = (retry = {}) => {
554
+ if (typeof retry === 'number') {
555
+ return {
556
+ ...defaultRetryOptions,
557
+ limit: retry,
558
+ };
559
+ }
560
+ if (retry.methods && !Array.isArray(retry.methods)) {
561
+ throw new Error('retry.methods must be an array');
562
+ }
563
+ if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
564
+ throw new Error('retry.statusCodes must be an array');
565
+ }
566
+ return {
567
+ ...defaultRetryOptions,
568
+ ...retry,
569
+ afterStatusCodes: retryAfterStatusCodes,
570
+ };
571
+ };
572
+
573
+ // `Promise.race()` workaround (#91)
574
+ const timeout = async (request, abortController, options) => new Promise((resolve, reject) => {
575
+ const timeoutId = setTimeout(() => {
576
+ if (abortController) {
577
+ abortController.abort();
578
+ }
579
+ reject(new TimeoutError(request));
580
+ }, options.timeout);
581
+ /* eslint-disable promise/prefer-await-to-then */
582
+ void options
583
+ .fetch(request)
584
+ .then(resolve)
585
+ .catch(reject)
586
+ .then(() => {
587
+ clearTimeout(timeoutId);
588
+ });
589
+ /* eslint-enable promise/prefer-await-to-then */
590
+ });
591
+ const delay = async (ms) => new Promise(resolve => {
592
+ setTimeout(resolve, ms);
593
+ });
594
+
595
+ class Ky {
596
+ // eslint-disable-next-line complexity
597
+ constructor(input, options = {}) {
598
+ var _a, _b;
599
+ this._retryCount = 0;
600
+ this._input = input;
601
+ this._options = {
602
+ // TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
603
+ credentials: this._input.credentials || 'same-origin',
604
+ ...options,
605
+ headers: mergeHeaders(this._input.headers, options.headers),
606
+ hooks: deepMerge({
607
+ beforeRequest: [],
608
+ beforeRetry: [],
609
+ beforeError: [],
610
+ afterResponse: [],
611
+ }, options.hooks),
612
+ method: normalizeRequestMethod((_a = options.method) !== null && _a !== void 0 ? _a : this._input.method),
613
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
614
+ prefixUrl: String(options.prefixUrl || ''),
615
+ retry: normalizeRetryOptions(options.retry),
616
+ throwHttpErrors: options.throwHttpErrors !== false,
617
+ timeout: typeof options.timeout === 'undefined' ? 10000 : options.timeout,
618
+ fetch: (_b = options.fetch) !== null && _b !== void 0 ? _b : globalThis.fetch.bind(globalThis),
619
+ };
620
+ if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {
621
+ throw new TypeError('`input` must be a string, URL, or Request');
622
+ }
623
+ if (this._options.prefixUrl && typeof this._input === 'string') {
624
+ if (this._input.startsWith('/')) {
625
+ throw new Error('`input` must not begin with a slash when using `prefixUrl`');
626
+ }
627
+ if (!this._options.prefixUrl.endsWith('/')) {
628
+ this._options.prefixUrl += '/';
629
+ }
630
+ this._input = this._options.prefixUrl + this._input;
631
+ }
632
+ if (supportsAbortController) {
633
+ this.abortController = new globalThis.AbortController();
634
+ if (this._options.signal) {
635
+ this._options.signal.addEventListener('abort', () => {
636
+ this.abortController.abort();
637
+ });
638
+ }
639
+ this._options.signal = this.abortController.signal;
640
+ }
641
+ this.request = new globalThis.Request(this._input, this._options);
642
+ if (this._options.searchParams) {
643
+ // eslint-disable-next-line unicorn/prevent-abbreviations
644
+ const textSearchParams = typeof this._options.searchParams === 'string'
645
+ ? this._options.searchParams.replace(/^\?/, '')
646
+ : new URLSearchParams(this._options.searchParams).toString();
647
+ // eslint-disable-next-line unicorn/prevent-abbreviations
648
+ const searchParams = '?' + textSearchParams;
649
+ const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
650
+ // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
651
+ if (((supportsFormData && this._options.body instanceof globalThis.FormData)
652
+ || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
653
+ this.request.headers.delete('content-type');
654
+ }
655
+ this.request = new globalThis.Request(new globalThis.Request(url, this.request), this._options);
656
+ }
657
+ if (this._options.json !== undefined) {
658
+ this._options.body = JSON.stringify(this._options.json);
659
+ this.request.headers.set('content-type', 'application/json');
660
+ this.request = new globalThis.Request(this.request, { body: this._options.body });
661
+ }
662
+ }
663
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
664
+ static create(input, options) {
665
+ const ky = new Ky(input, options);
666
+ const fn = async () => {
667
+ if (ky._options.timeout > maxSafeTimeout) {
668
+ throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
669
+ }
670
+ // Delay the fetch so that body method shortcuts can set the Accept header
671
+ await Promise.resolve();
672
+ let response = await ky._fetch();
673
+ for (const hook of ky._options.hooks.afterResponse) {
674
+ // eslint-disable-next-line no-await-in-loop
675
+ const modifiedResponse = await hook(ky.request, ky._options, ky._decorateResponse(response.clone()));
676
+ if (modifiedResponse instanceof globalThis.Response) {
677
+ response = modifiedResponse;
678
+ }
679
+ }
680
+ ky._decorateResponse(response);
681
+ if (!response.ok && ky._options.throwHttpErrors) {
682
+ let error = new HTTPError(response, ky.request, ky._options);
683
+ for (const hook of ky._options.hooks.beforeError) {
684
+ // eslint-disable-next-line no-await-in-loop
685
+ error = await hook(error);
686
+ }
687
+ throw error;
688
+ }
689
+ // If `onDownloadProgress` is passed, it uses the stream API internally
690
+ /* istanbul ignore next */
691
+ if (ky._options.onDownloadProgress) {
692
+ if (typeof ky._options.onDownloadProgress !== 'function') {
693
+ throw new TypeError('The `onDownloadProgress` option must be a function');
694
+ }
695
+ if (!supportsStreams) {
696
+ throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');
697
+ }
698
+ return ky._stream(response.clone(), ky._options.onDownloadProgress);
699
+ }
700
+ return response;
701
+ };
702
+ const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());
703
+ const result = (isRetriableMethod ? ky._retry(fn) : fn());
704
+ for (const [type, mimeType] of Object.entries(responseTypes)) {
705
+ result[type] = async () => {
706
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
707
+ ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);
708
+ const response = (await result).clone();
709
+ if (type === 'json') {
710
+ if (response.status === 204) {
711
+ return '';
712
+ }
713
+ if (options.parseJson) {
714
+ return options.parseJson(await response.text());
715
+ }
716
+ }
717
+ return response[type]();
718
+ };
719
+ }
720
+ return result;
721
+ }
722
+ _calculateRetryDelay(error) {
723
+ this._retryCount++;
724
+ if (this._retryCount < this._options.retry.limit && !(error instanceof TimeoutError)) {
725
+ if (error instanceof HTTPError) {
726
+ if (!this._options.retry.statusCodes.includes(error.response.status)) {
727
+ return 0;
728
+ }
729
+ const retryAfter = error.response.headers.get('Retry-After');
730
+ if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
731
+ let after = Number(retryAfter);
732
+ if (Number.isNaN(after)) {
733
+ after = Date.parse(retryAfter) - Date.now();
734
+ }
735
+ else {
736
+ after *= 1000;
737
+ }
738
+ if (typeof this._options.retry.maxRetryAfter !== 'undefined' && after > this._options.retry.maxRetryAfter) {
739
+ return 0;
740
+ }
741
+ return after;
742
+ }
743
+ if (error.response.status === 413) {
744
+ return 0;
745
+ }
746
+ }
747
+ const BACKOFF_FACTOR = 0.3;
748
+ return BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000;
749
+ }
750
+ return 0;
751
+ }
752
+ _decorateResponse(response) {
753
+ if (this._options.parseJson) {
754
+ response.json = async () => this._options.parseJson(await response.text());
755
+ }
756
+ return response;
757
+ }
758
+ async _retry(fn) {
759
+ try {
760
+ return await fn();
761
+ // eslint-disable-next-line @typescript-eslint/no-implicit-any-catch
762
+ }
763
+ catch (error) {
764
+ const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
765
+ if (ms !== 0 && this._retryCount > 0) {
766
+ await delay(ms);
767
+ for (const hook of this._options.hooks.beforeRetry) {
768
+ // eslint-disable-next-line no-await-in-loop
769
+ const hookResult = await hook({
770
+ request: this.request,
771
+ options: this._options,
772
+ error: error,
773
+ retryCount: this._retryCount,
774
+ });
775
+ // If `stop` is returned from the hook, the retry process is stopped
776
+ if (hookResult === stop) {
777
+ return;
778
+ }
779
+ }
780
+ return this._retry(fn);
781
+ }
782
+ throw error;
783
+ }
784
+ }
785
+ async _fetch() {
786
+ for (const hook of this._options.hooks.beforeRequest) {
787
+ // eslint-disable-next-line no-await-in-loop
788
+ const result = await hook(this.request, this._options);
789
+ if (result instanceof Request) {
790
+ this.request = result;
791
+ break;
792
+ }
793
+ if (result instanceof Response) {
794
+ return result;
795
+ }
796
+ }
797
+ if (this._options.timeout === false) {
798
+ return this._options.fetch(this.request.clone());
799
+ }
800
+ return timeout(this.request.clone(), this.abortController, this._options);
801
+ }
802
+ /* istanbul ignore next */
803
+ _stream(response, onDownloadProgress) {
804
+ const totalBytes = Number(response.headers.get('content-length')) || 0;
805
+ let transferredBytes = 0;
806
+ return new globalThis.Response(new globalThis.ReadableStream({
807
+ async start(controller) {
808
+ const reader = response.body.getReader();
809
+ if (onDownloadProgress) {
810
+ onDownloadProgress({ percent: 0, transferredBytes: 0, totalBytes }, new Uint8Array());
811
+ }
812
+ async function read() {
813
+ const { done, value } = await reader.read();
814
+ if (done) {
815
+ controller.close();
816
+ return;
817
+ }
818
+ if (onDownloadProgress) {
819
+ transferredBytes += value.byteLength;
820
+ const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
821
+ onDownloadProgress({ percent, transferredBytes, totalBytes }, value);
822
+ }
823
+ controller.enqueue(value);
824
+ await read();
825
+ }
826
+ await read();
827
+ },
828
+ }));
829
+ }
830
+ }
831
+
832
+ /*! MIT License © Sindre Sorhus */
833
+ const createInstance = (defaults) => {
834
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
835
+ const ky = (input, options) => Ky.create(input, validateAndMerge(defaults, options));
836
+ for (const method of requestMethods) {
837
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
838
+ ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));
839
+ }
840
+ ky.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
841
+ ky.extend = (newDefaults) => createInstance(validateAndMerge(defaults, newDefaults));
842
+ ky.stop = stop;
843
+ return ky;
844
+ };
845
+ const ky = createInstance();
846
+
847
+ exports.HTTPError = HTTPError;
848
+ exports.TimeoutError = TimeoutError;
849
+ exports["default"] = ky;
850
+
851
+ Object.defineProperty(exports, '__esModule', { value: true });
852
+
853
+ }));
854
+ } (ky$1, ky$1.exports));
855
+
856
+ const urlHttp = lightweight;
838
857
  const { flattie: flatten } = dist;
839
858
  const { encode: stringify } = require$$2;
840
859
  const whoops = lib.exports;
@@ -873,11 +892,11 @@
873
892
 
874
893
  var browser = factory({
875
894
  MicrolinkError,
876
- isUrlHttp,
895
+ urlHttp,
877
896
  stringify,
878
897
  got,
879
898
  flatten,
880
- VERSION: '0.10.19'
899
+ VERSION: '0.10.22'
881
900
  });
882
901
 
883
902
  return browser;