@microlink/mql 0.13.1 → 0.13.2

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