@microlink/mql 0.10.28 → 0.10.30

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.mjs ADDED
@@ -0,0 +1,723 @@
1
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
2
+
3
+ function getAugmentedNamespace(n) {
4
+ var f = n.default;
5
+ if (typeof f == "function") {
6
+ var a = function () {
7
+ return f.apply(this, arguments);
8
+ };
9
+ a.prototype = f.prototype;
10
+ } else a = {};
11
+ Object.defineProperty(a, '__esModule', {value: true});
12
+ Object.keys(n).forEach(function (k) {
13
+ var d = Object.getOwnPropertyDescriptor(n, k);
14
+ Object.defineProperty(a, k, d.get ? d : {
15
+ enumerable: true,
16
+ get: function () {
17
+ return n[k];
18
+ }
19
+ });
20
+ });
21
+ return a;
22
+ }
23
+
24
+ const URL$1 = globalThis.URL;
25
+
26
+ const REGEX_HTTP_PROTOCOL = /^https?:\/\//i;
27
+
28
+ var lightweight = url => {
29
+ try {
30
+ const { href } = new URL$1(url);
31
+ return REGEX_HTTP_PROTOCOL.test(href) && href
32
+ } catch (err) {
33
+ return false
34
+ }
35
+ };
36
+
37
+ var dist = {};
38
+
39
+ function iter(output, nullish, sep, val, key) {
40
+ var k, pfx = key ? (key + sep) : key;
41
+
42
+ if (val == null) {
43
+ if (nullish) output[key] = val;
44
+ } else if (typeof val != 'object') {
45
+ output[key] = val;
46
+ } else if (Array.isArray(val)) {
47
+ for (k=0; k < val.length; k++) {
48
+ iter(output, nullish, sep, val[k], pfx + k);
49
+ }
50
+ } else {
51
+ for (k in val) {
52
+ iter(output, nullish, sep, val[k], pfx + k);
53
+ }
54
+ }
55
+ }
56
+
57
+ function flattie(input, glue, toNull) {
58
+ var output = {};
59
+ if (typeof input == 'object') {
60
+ iter(output, !!toNull, glue || '.', input, '');
61
+ }
62
+ return output;
63
+ }
64
+
65
+ dist.flattie = flattie;
66
+
67
+ function encode(obj, pfx) {
68
+ var k, i, tmp, str='';
69
+
70
+ for (k in obj) {
71
+ if ((tmp = obj[k]) !== void 0) {
72
+ if (Array.isArray(tmp)) {
73
+ for (i=0; i < tmp.length; i++) {
74
+ str && (str += '&');
75
+ str += encodeURIComponent(k) + '=' + encodeURIComponent(tmp[i]);
76
+ }
77
+ } else {
78
+ str && (str += '&');
79
+ str += encodeURIComponent(k) + '=' + encodeURIComponent(tmp);
80
+ }
81
+ }
82
+ }
83
+
84
+ return (pfx || '') + str;
85
+ }
86
+
87
+ function toValue(mix) {
88
+ if (!mix) return '';
89
+ var str = decodeURIComponent(mix);
90
+ if (str === 'false') return false;
91
+ if (str === 'true') return true;
92
+ return (+str * 0 === 0) ? (+str) : str;
93
+ }
94
+
95
+ function decode(str) {
96
+ var tmp, k, out={}, arr=str.split('&');
97
+
98
+ while (tmp = arr.shift()) {
99
+ tmp = tmp.split('=');
100
+ k = tmp.shift();
101
+ if (out[k] !== void 0) {
102
+ out[k] = [].concat(out[k], toValue(tmp.shift()));
103
+ } else {
104
+ out[k] = toValue(tmp.shift());
105
+ }
106
+ }
107
+
108
+ return out;
109
+ }
110
+
111
+ var qss_m = /*#__PURE__*/Object.freeze({
112
+ __proto__: null,
113
+ encode: encode,
114
+ decode: decode
115
+ });
116
+
117
+ var require$$2 = /*@__PURE__*/getAugmentedNamespace(qss_m);
118
+
119
+ const ENDPOINT = {
120
+ FREE: 'https://api.microlink.io',
121
+ PRO: 'https://pro.microlink.io'
122
+ };
123
+
124
+ const isObject = input => input !== null && typeof input === 'object';
125
+
126
+ const isBuffer = input =>
127
+ input != null &&
128
+ input.constructor != null &&
129
+ typeof input.constructor.isBuffer === 'function' &&
130
+ input.constructor.isBuffer(input);
131
+
132
+ const parseBody = (input, error, url) => {
133
+ try {
134
+ return JSON.parse(input)
135
+ } catch (_) {
136
+ const message = input || error.message;
137
+
138
+ return {
139
+ status: 'error',
140
+ data: { url: message },
141
+ more: 'https://microlink.io/efatalclient',
142
+ code: 'EFATALCLIENT',
143
+ message,
144
+ url
145
+ }
146
+ }
147
+ };
148
+
149
+ const factory$1 = ({
150
+ VERSION,
151
+ MicrolinkError,
152
+ urlHttp,
153
+ stringify,
154
+ got,
155
+ flatten
156
+ }) => {
157
+ const assertUrl = (url = '') => {
158
+ if (!urlHttp(url)) {
159
+ const message = `The \`url\` as \`${url}\` is not valid. Ensure it has protocol (http or https) and hostname.`;
160
+ throw new MicrolinkError({
161
+ status: 'fail',
162
+ data: { url: message },
163
+ more: 'https://microlink.io/docs/api/api-parameters/url',
164
+ code: 'EINVALURLCLIENT',
165
+ message,
166
+ url
167
+ })
168
+ }
169
+ };
170
+
171
+ const mapRules = rules => {
172
+ if (!isObject(rules)) return
173
+ const flatRules = flatten(rules);
174
+ return Object.keys(flatRules).reduce((acc, key) => {
175
+ acc[`data.${key}`] = flatRules[key].toString();
176
+ return acc
177
+ }, {})
178
+ };
179
+
180
+ const fetchFromApi = async (apiUrl, opts = {}, retryCount = 0) => {
181
+ try {
182
+ const response = await got(apiUrl, opts);
183
+ return opts.responseType === 'buffer'
184
+ ? { body: response.body, response }
185
+ : { ...response.body, response }
186
+ } catch (err) {
187
+ const { response = {} } = err;
188
+ const {
189
+ statusCode,
190
+ body: rawBody,
191
+ headers = {},
192
+ url: uri = apiUrl
193
+ } = response;
194
+ const isBodyBuffer = isBuffer(rawBody);
195
+
196
+ const body =
197
+ isObject(rawBody) && !isBodyBuffer
198
+ ? rawBody
199
+ : parseBody(isBodyBuffer ? rawBody.toString() : rawBody, err, uri);
200
+
201
+ if (body.code === 'EFATALCLIENT' && retryCount++ < 2) {
202
+ return fetchFromApi(apiUrl, opts, retryCount)
203
+ }
204
+
205
+ throw new MicrolinkError({
206
+ ...body,
207
+ message: body.message,
208
+ url: uri,
209
+ statusCode,
210
+ headers
211
+ })
212
+ }
213
+ };
214
+
215
+ const getApiUrl = (
216
+ url,
217
+ { data, apiKey, endpoint, retry, cache, ...opts } = {},
218
+ { responseType = 'json', headers: gotHeaders, ...gotOpts } = {}
219
+ ) => {
220
+ const isPro = !!apiKey;
221
+ const apiEndpoint = endpoint || ENDPOINT[isPro ? 'PRO' : 'FREE'];
222
+
223
+ const apiUrl = `${apiEndpoint}?${stringify({
224
+ url,
225
+ ...mapRules(data),
226
+ ...flatten(opts)
227
+ })}`;
228
+
229
+ const headers = isPro
230
+ ? { ...gotHeaders, 'x-api-key': apiKey }
231
+ : { ...gotHeaders };
232
+ return [apiUrl, { ...gotOpts, responseType, cache, retry, headers }]
233
+ };
234
+
235
+ const createMql = defaultOpts => async (url, opts, gotOpts) => {
236
+ assertUrl(url);
237
+ const [apiUrl, fetchOpts] = getApiUrl(url, opts, {
238
+ ...defaultOpts,
239
+ ...gotOpts
240
+ });
241
+ return fetchFromApi(apiUrl, fetchOpts)
242
+ };
243
+
244
+ const mql = createMql();
245
+ mql.MicrolinkError = MicrolinkError;
246
+ mql.getApiUrl = getApiUrl;
247
+ mql.fetchFromApi = fetchFromApi;
248
+ mql.mapRules = mapRules;
249
+ mql.version = VERSION;
250
+ mql.stream = got.stream;
251
+ mql.buffer = createMql({ responseType: 'buffer' });
252
+
253
+ return mql
254
+ };
255
+
256
+ var factory_1 = factory$1;
257
+
258
+ var ky$1 = {exports: {}};
259
+
260
+ (function (module, exports) {
261
+ (function (global, factory) {
262
+ factory(exports) ;
263
+ })(commonjsGlobal, (function (exports) {
264
+ // eslint-lint-disable-next-line @typescript-eslint/naming-convention
265
+ class HTTPError extends Error {
266
+ constructor(response, request, options) {
267
+ const code = (response.status || response.status === 0) ? response.status : '';
268
+ const title = response.statusText || '';
269
+ const status = `${code} ${title}`.trim();
270
+ const reason = status ? `status code ${status}` : 'an unknown error';
271
+ super(`Request failed with ${reason}`);
272
+ this.name = 'HTTPError';
273
+ this.response = response;
274
+ this.request = request;
275
+ this.options = options;
276
+ }
277
+ }
278
+
279
+ class TimeoutError extends Error {
280
+ constructor(request) {
281
+ super('Request timed out');
282
+ this.name = 'TimeoutError';
283
+ this.request = request;
284
+ }
285
+ }
286
+
287
+ // eslint-disable-next-line @typescript-eslint/ban-types
288
+ const isObject = (value) => value !== null && typeof value === 'object';
289
+
290
+ const validateAndMerge = (...sources) => {
291
+ for (const source of sources) {
292
+ if ((!isObject(source) || Array.isArray(source)) && typeof source !== 'undefined') {
293
+ throw new TypeError('The `options` argument must be an object');
294
+ }
295
+ }
296
+ return deepMerge({}, ...sources);
297
+ };
298
+ const mergeHeaders = (source1 = {}, source2 = {}) => {
299
+ const result = new globalThis.Headers(source1);
300
+ const isHeadersInstance = source2 instanceof globalThis.Headers;
301
+ const source = new globalThis.Headers(source2);
302
+ for (const [key, value] of source.entries()) {
303
+ if ((isHeadersInstance && value === 'undefined') || value === undefined) {
304
+ result.delete(key);
305
+ }
306
+ else {
307
+ result.set(key, value);
308
+ }
309
+ }
310
+ return result;
311
+ };
312
+ // TODO: Make this strongly-typed (no `any`).
313
+ const deepMerge = (...sources) => {
314
+ let returnValue = {};
315
+ let headers = {};
316
+ for (const source of sources) {
317
+ if (Array.isArray(source)) {
318
+ if (!Array.isArray(returnValue)) {
319
+ returnValue = [];
320
+ }
321
+ returnValue = [...returnValue, ...source];
322
+ }
323
+ else if (isObject(source)) {
324
+ for (let [key, value] of Object.entries(source)) {
325
+ if (isObject(value) && key in returnValue) {
326
+ value = deepMerge(returnValue[key], value);
327
+ }
328
+ returnValue = { ...returnValue, [key]: value };
329
+ }
330
+ if (isObject(source.headers)) {
331
+ headers = mergeHeaders(headers, source.headers);
332
+ returnValue.headers = headers;
333
+ }
334
+ }
335
+ }
336
+ return returnValue;
337
+ };
338
+
339
+ const supportsAbortController = typeof globalThis.AbortController === 'function';
340
+ const supportsStreams = typeof globalThis.ReadableStream === 'function';
341
+ const supportsFormData = typeof globalThis.FormData === 'function';
342
+ const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'];
343
+ const responseTypes = {
344
+ json: 'application/json',
345
+ text: 'text/*',
346
+ formData: 'multipart/form-data',
347
+ arrayBuffer: '*/*',
348
+ blob: '*/*',
349
+ };
350
+ // The maximum value of a 32bit int (see issue #117)
351
+ const maxSafeTimeout = 2147483647;
352
+ const stop = Symbol('stop');
353
+
354
+ const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
355
+ const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];
356
+ const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
357
+ const retryAfterStatusCodes = [413, 429, 503];
358
+ const defaultRetryOptions = {
359
+ limit: 2,
360
+ methods: retryMethods,
361
+ statusCodes: retryStatusCodes,
362
+ afterStatusCodes: retryAfterStatusCodes,
363
+ maxRetryAfter: Number.POSITIVE_INFINITY,
364
+ };
365
+ const normalizeRetryOptions = (retry = {}) => {
366
+ if (typeof retry === 'number') {
367
+ return {
368
+ ...defaultRetryOptions,
369
+ limit: retry,
370
+ };
371
+ }
372
+ if (retry.methods && !Array.isArray(retry.methods)) {
373
+ throw new Error('retry.methods must be an array');
374
+ }
375
+ if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
376
+ throw new Error('retry.statusCodes must be an array');
377
+ }
378
+ return {
379
+ ...defaultRetryOptions,
380
+ ...retry,
381
+ afterStatusCodes: retryAfterStatusCodes,
382
+ };
383
+ };
384
+
385
+ // `Promise.race()` workaround (#91)
386
+ const timeout = async (request, abortController, options) => new Promise((resolve, reject) => {
387
+ const timeoutId = setTimeout(() => {
388
+ if (abortController) {
389
+ abortController.abort();
390
+ }
391
+ reject(new TimeoutError(request));
392
+ }, options.timeout);
393
+ void options
394
+ .fetch(request)
395
+ .then(resolve)
396
+ .catch(reject)
397
+ .then(() => {
398
+ clearTimeout(timeoutId);
399
+ });
400
+ });
401
+ const delay = async (ms) => new Promise(resolve => {
402
+ setTimeout(resolve, ms);
403
+ });
404
+
405
+ class Ky {
406
+ // eslint-disable-next-line complexity
407
+ constructor(input, options = {}) {
408
+ var _a, _b, _c;
409
+ this._retryCount = 0;
410
+ this._input = input;
411
+ this._options = {
412
+ // TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
413
+ credentials: this._input.credentials || 'same-origin',
414
+ ...options,
415
+ headers: mergeHeaders(this._input.headers, options.headers),
416
+ hooks: deepMerge({
417
+ beforeRequest: [],
418
+ beforeRetry: [],
419
+ beforeError: [],
420
+ afterResponse: [],
421
+ }, options.hooks),
422
+ method: normalizeRequestMethod((_a = options.method) !== null && _a !== void 0 ? _a : this._input.method),
423
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
424
+ prefixUrl: String(options.prefixUrl || ''),
425
+ retry: normalizeRetryOptions(options.retry),
426
+ throwHttpErrors: options.throwHttpErrors !== false,
427
+ timeout: typeof options.timeout === 'undefined' ? 10000 : options.timeout,
428
+ fetch: (_b = options.fetch) !== null && _b !== void 0 ? _b : globalThis.fetch.bind(globalThis),
429
+ };
430
+ if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {
431
+ throw new TypeError('`input` must be a string, URL, or Request');
432
+ }
433
+ if (this._options.prefixUrl && typeof this._input === 'string') {
434
+ if (this._input.startsWith('/')) {
435
+ throw new Error('`input` must not begin with a slash when using `prefixUrl`');
436
+ }
437
+ if (!this._options.prefixUrl.endsWith('/')) {
438
+ this._options.prefixUrl += '/';
439
+ }
440
+ this._input = this._options.prefixUrl + this._input;
441
+ }
442
+ if (supportsAbortController) {
443
+ this.abortController = new globalThis.AbortController();
444
+ if (this._options.signal) {
445
+ this._options.signal.addEventListener('abort', () => {
446
+ this.abortController.abort();
447
+ });
448
+ }
449
+ this._options.signal = this.abortController.signal;
450
+ }
451
+ this.request = new globalThis.Request(this._input, this._options);
452
+ if (this._options.searchParams) {
453
+ // eslint-disable-next-line unicorn/prevent-abbreviations
454
+ const textSearchParams = typeof this._options.searchParams === 'string'
455
+ ? this._options.searchParams.replace(/^\?/, '')
456
+ : new URLSearchParams(this._options.searchParams).toString();
457
+ // eslint-disable-next-line unicorn/prevent-abbreviations
458
+ const searchParams = '?' + textSearchParams;
459
+ const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
460
+ // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
461
+ if (((supportsFormData && this._options.body instanceof globalThis.FormData)
462
+ || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
463
+ this.request.headers.delete('content-type');
464
+ }
465
+ this.request = new globalThis.Request(new globalThis.Request(url, this.request), this._options);
466
+ }
467
+ if (this._options.json !== undefined) {
468
+ this._options.body = JSON.stringify(this._options.json);
469
+ this.request.headers.set('content-type', (_c = this._options.headers.get('content-type')) !== null && _c !== void 0 ? _c : 'application/json');
470
+ this.request = new globalThis.Request(this.request, { body: this._options.body });
471
+ }
472
+ }
473
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
474
+ static create(input, options) {
475
+ const ky = new Ky(input, options);
476
+ const fn = async () => {
477
+ if (ky._options.timeout > maxSafeTimeout) {
478
+ throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
479
+ }
480
+ // Delay the fetch so that body method shortcuts can set the Accept header
481
+ await Promise.resolve();
482
+ let response = await ky._fetch();
483
+ for (const hook of ky._options.hooks.afterResponse) {
484
+ // eslint-disable-next-line no-await-in-loop
485
+ const modifiedResponse = await hook(ky.request, ky._options, ky._decorateResponse(response.clone()));
486
+ if (modifiedResponse instanceof globalThis.Response) {
487
+ response = modifiedResponse;
488
+ }
489
+ }
490
+ ky._decorateResponse(response);
491
+ if (!response.ok && ky._options.throwHttpErrors) {
492
+ let error = new HTTPError(response, ky.request, ky._options);
493
+ for (const hook of ky._options.hooks.beforeError) {
494
+ // eslint-disable-next-line no-await-in-loop
495
+ error = await hook(error);
496
+ }
497
+ throw error;
498
+ }
499
+ // If `onDownloadProgress` is passed, it uses the stream API internally
500
+ /* istanbul ignore next */
501
+ if (ky._options.onDownloadProgress) {
502
+ if (typeof ky._options.onDownloadProgress !== 'function') {
503
+ throw new TypeError('The `onDownloadProgress` option must be a function');
504
+ }
505
+ if (!supportsStreams) {
506
+ throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');
507
+ }
508
+ return ky._stream(response.clone(), ky._options.onDownloadProgress);
509
+ }
510
+ return response;
511
+ };
512
+ const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());
513
+ const result = (isRetriableMethod ? ky._retry(fn) : fn());
514
+ for (const [type, mimeType] of Object.entries(responseTypes)) {
515
+ result[type] = async () => {
516
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
517
+ ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);
518
+ const awaitedResult = await result;
519
+ const response = awaitedResult.clone();
520
+ if (type === 'json') {
521
+ if (response.status === 204) {
522
+ return '';
523
+ }
524
+ if (options.parseJson) {
525
+ return options.parseJson(await response.text());
526
+ }
527
+ }
528
+ return response[type]();
529
+ };
530
+ }
531
+ return result;
532
+ }
533
+ _calculateRetryDelay(error) {
534
+ this._retryCount++;
535
+ if (this._retryCount < this._options.retry.limit && !(error instanceof TimeoutError)) {
536
+ if (error instanceof HTTPError) {
537
+ if (!this._options.retry.statusCodes.includes(error.response.status)) {
538
+ return 0;
539
+ }
540
+ const retryAfter = error.response.headers.get('Retry-After');
541
+ if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
542
+ let after = Number(retryAfter);
543
+ if (Number.isNaN(after)) {
544
+ after = Date.parse(retryAfter) - Date.now();
545
+ }
546
+ else {
547
+ after *= 1000;
548
+ }
549
+ if (typeof this._options.retry.maxRetryAfter !== 'undefined' && after > this._options.retry.maxRetryAfter) {
550
+ return 0;
551
+ }
552
+ return after;
553
+ }
554
+ if (error.response.status === 413) {
555
+ return 0;
556
+ }
557
+ }
558
+ const BACKOFF_FACTOR = 0.3;
559
+ return BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000;
560
+ }
561
+ return 0;
562
+ }
563
+ _decorateResponse(response) {
564
+ if (this._options.parseJson) {
565
+ response.json = async () => this._options.parseJson(await response.text());
566
+ }
567
+ return response;
568
+ }
569
+ async _retry(fn) {
570
+ try {
571
+ return await fn();
572
+ // eslint-disable-next-line @typescript-eslint/no-implicit-any-catch
573
+ }
574
+ catch (error) {
575
+ const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
576
+ if (ms !== 0 && this._retryCount > 0) {
577
+ await delay(ms);
578
+ for (const hook of this._options.hooks.beforeRetry) {
579
+ // eslint-disable-next-line no-await-in-loop
580
+ const hookResult = await hook({
581
+ request: this.request,
582
+ options: this._options,
583
+ error: error,
584
+ retryCount: this._retryCount,
585
+ });
586
+ // If `stop` is returned from the hook, the retry process is stopped
587
+ if (hookResult === stop) {
588
+ return;
589
+ }
590
+ }
591
+ return this._retry(fn);
592
+ }
593
+ throw error;
594
+ }
595
+ }
596
+ async _fetch() {
597
+ for (const hook of this._options.hooks.beforeRequest) {
598
+ // eslint-disable-next-line no-await-in-loop
599
+ const result = await hook(this.request, this._options);
600
+ if (result instanceof Request) {
601
+ this.request = result;
602
+ break;
603
+ }
604
+ if (result instanceof Response) {
605
+ return result;
606
+ }
607
+ }
608
+ if (this._options.timeout === false) {
609
+ return this._options.fetch(this.request.clone());
610
+ }
611
+ return timeout(this.request.clone(), this.abortController, this._options);
612
+ }
613
+ /* istanbul ignore next */
614
+ _stream(response, onDownloadProgress) {
615
+ const totalBytes = Number(response.headers.get('content-length')) || 0;
616
+ let transferredBytes = 0;
617
+ return new globalThis.Response(new globalThis.ReadableStream({
618
+ async start(controller) {
619
+ const reader = response.body.getReader();
620
+ if (onDownloadProgress) {
621
+ onDownloadProgress({ percent: 0, transferredBytes: 0, totalBytes }, new Uint8Array());
622
+ }
623
+ async function read() {
624
+ const { done, value } = await reader.read();
625
+ if (done) {
626
+ controller.close();
627
+ return;
628
+ }
629
+ if (onDownloadProgress) {
630
+ transferredBytes += value.byteLength;
631
+ const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
632
+ onDownloadProgress({ percent, transferredBytes, totalBytes }, value);
633
+ }
634
+ controller.enqueue(value);
635
+ await read();
636
+ }
637
+ await read();
638
+ },
639
+ }));
640
+ }
641
+ }
642
+
643
+ /*! MIT License © Sindre Sorhus */
644
+ const createInstance = (defaults) => {
645
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
646
+ const ky = (input, options) => Ky.create(input, validateAndMerge(defaults, options));
647
+ for (const method of requestMethods) {
648
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
649
+ ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));
650
+ }
651
+ ky.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
652
+ ky.extend = (newDefaults) => createInstance(validateAndMerge(defaults, newDefaults));
653
+ ky.stop = stop;
654
+ return ky;
655
+ };
656
+ const ky = createInstance();
657
+
658
+ exports.HTTPError = HTTPError;
659
+ exports.TimeoutError = TimeoutError;
660
+ exports["default"] = ky;
661
+
662
+ Object.defineProperty(exports, '__esModule', { value: true });
663
+
664
+ }));
665
+ } (ky$1, ky$1.exports));
666
+
667
+ const urlHttp = lightweight;
668
+ const { flattie: flatten } = dist;
669
+ const { encode: stringify } = require$$2;
670
+
671
+ const factory = factory_1;
672
+ const { default: ky } = ky$1.exports;
673
+
674
+ class MicrolinkError extends Error {
675
+ constructor (props) {
676
+ super();
677
+ this.name = 'MicrolinkError';
678
+ Object.assign(this, props);
679
+ this.description = this.message;
680
+ this.message = this.code
681
+ ? `${this.code}, ${this.description}`
682
+ : this.description;
683
+ }
684
+ }
685
+
686
+ const got = async (url, opts) => {
687
+ try {
688
+ if (opts.timeout === undefined) opts.timeout = false;
689
+ const response = await ky(url, opts);
690
+ const body = await response.json();
691
+ const { headers, status: statusCode } = response;
692
+ return { url: response.url, body, headers, statusCode }
693
+ } catch (err) {
694
+ if (err.response) {
695
+ const { response } = err;
696
+ err.response = {
697
+ ...response,
698
+ headers: Array.from(response.headers.entries()).reduce(
699
+ (acc, [key, value]) => {
700
+ acc[key] = value;
701
+ return acc
702
+ },
703
+ {}
704
+ ),
705
+ statusCode: response.status,
706
+ body: await response.text()
707
+ };
708
+ }
709
+ throw err
710
+ }
711
+ };
712
+
713
+ var browser = factory({
714
+ MicrolinkError,
715
+ urlHttp,
716
+ stringify,
717
+ got,
718
+ flatten,
719
+ VERSION: '0.10.30'
720
+ });
721
+
722
+ export { browser as default };
723
+ //# sourceMappingURL=mql.mjs.map