@microlink/mql 0.11.5-1 → 0.11.5
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/LICENSE.md +0 -0
- package/lightweight/index.js +1 -2
- package/package.json +20 -21
- package/src/ky.js +47 -6
- package/src/lightweight.js +2 -2
package/LICENSE.md
CHANGED
|
File without changes
|
package/lightweight/index.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
function t(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function e(t){if(t.__esModule)return t;var e=t.default;if("function"==typeof e){var r=function t(){return this instanceof t?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach((function(e){var s=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(r,e,s.get?s:{enumerable:!0,get:function(){return t[e]}})})),r}var r={exports:{}};const s=/^https?:\/\//i;const o={FREE:"https://api.microlink.io/",PRO:"https://pro.microlink.io/"},n=t=>null!==t&&"object"==typeof t;var i=({VERSION:t,MicrolinkError:e,urlHttp:r,got:s,flatten:i})=>{const a=t=>{if(!n(t))return;const e=i(t);return Object.keys(e).reduce(((t,r)=>(t[`data.${r}`]=e[r].toString(),t)),{})},u=async(t,r={})=>{try{const e=await s(t,r);return"buffer"===r.responseType?{body:e.body,response:e}:{...e.body,response:e}}catch(r){const{response:s={}}=r,{statusCode:i,body:a,headers:u={},url:l=t}=s,c=null!=(o=a)&&null!=o.constructor&&"function"==typeof o.constructor.isBuffer&&o.constructor.isBuffer(o),h=n(a)&&!c?a:((t,e,r)=>{try{return JSON.parse(t)}catch(s){const o=t||e.message;return{status:"error",data:{url:o},more:"https://microlink.io/efatalclient",code:"EFATALCLIENT",message:o,url:r}}})(c?a.toString():a,r,l);throw new e({...h,message:h.message,url:l,statusCode:i,headers:u})}var o},l=(t,{data:e,apiKey:r,endpoint:s,retry:n,cache:u,...l}={},{responseType:c="json",headers:h,...p}={})=>{const f=!!r;return[`${s||o[f?"PRO":"FREE"]}?${new URLSearchParams({url:t,...a(e),...i(l)}).toString()}`,{...p,responseType:c,cache:u,retry:n,headers:f?{...h,"x-api-key":r}:{...h}}]},c=t=>async(s,o,n)=>{((t="")=>{if(!r(t)){const r=`The \`url\` as \`${t}\` is not valid. Ensure it has protocol (http or https) and hostname.`;throw new e({status:"fail",data:{url:r},more:"https://microlink.io/docs/api/api-parameters/url",code:"EINVALURLCLIENT",message:r,url:t})}})(s);const[i,a]=l(s,o,{...t,...n});return u(i,a)},h=c();return h.MicrolinkError=e,h.getApiUrl=l,h.fetchFromApi=u,h.mapRules=a,h.version=t,h.stream=s.stream,h.buffer=c({responseType:"buffer"}),h};class a extends Error{constructor(t,e,r){const s=`${t.status||0===t.status?t.status:""} ${t.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=t,this.request=e,this.options=r}}class u extends Error{constructor(t){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=t}}const l=t=>null!==t&&"object"==typeof t,c=(...t)=>{for(const e of t)if((!l(e)||Array.isArray(e))&&void 0!==e)throw new TypeError("The `options` argument must be an object");return p({},...t)},h=(t={},e={})=>{const r=new globalThis.Headers(t),s=e instanceof globalThis.Headers,o=new globalThis.Headers(e);for(const[t,e]of o.entries())s&&"undefined"===e||void 0===e?r.delete(t):r.set(t,e);return r},p=(...t)=>{let e={},r={};for(const s of t)if(Array.isArray(s))Array.isArray(e)||(e=[]),e=[...e,...s];else if(l(s)){for(let[t,r]of Object.entries(s))l(r)&&t in e&&(r=p(e[t],r)),e={...e,[t]:r};l(s.headers)&&(r=h(r,s.headers),e.headers=r)}return e},f=(()=>{let t=!1,e=!1;const r="function"==typeof globalThis.ReadableStream,s="function"==typeof globalThis.Request;return r&&s&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type")),t&&!e})(),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:"*/*"},w=2147483647,g=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=t=>m.includes(t)?t.toUpperCase():t,E=[413,429,503],q={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:E,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:t=>.3*2**(t-1)*1e3},x=(t={})=>{if("number"==typeof t)return{...q,limit:t};if(t.methods&&!Array.isArray(t.methods))throw new Error("retry.methods must be an array");if(t.statusCodes&&!Array.isArray(t.statusCodes))throw new Error("retry.statusCodes must be an array");return{...q,...t,afterStatusCodes:E}};class P{static create(t,e){const r=new P(t,e),s=async()=>{if("number"==typeof r._options.timeout&&r._options.timeout>w)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let t=await r._fetch();for(const e of r._options.hooks.afterResponse){const s=await e(r.request,r._options,r._decorateResponse(t.clone()));s instanceof globalThis.Response&&(t=s)}if(r._decorateResponse(t),!t.ok&&r._options.throwHttpErrors){let e=new a(t,r.request,r._options);for(const t of r._options.hooks.beforeError)e=await t(e);throw e}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(t.clone(),r._options.onDownloadProgress)}return t},o=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(s):s();for(const[t,s]of Object.entries(_))o[t]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||s);const n=(await o).clone();if("json"===t){if(204===n.status)return"";if(0===(await n.clone().arrayBuffer()).byteLength)return"";if(e.parseJson)return e.parseJson(await n.text())}return n[t]()};return o}constructor(t,e={}){if(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=t,this._options={credentials:this._input.credentials||"same-origin",...e,headers:h(this._input.headers,e.headers),hooks:p({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:v(e.method??this._input.method),prefixUrl:String(e.prefixUrl||""),retry:x(e.retry),throwHttpErrors:!1!==e.throwHttpErrors,timeout:e.timeout??1e4,fetch:e.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 t=this._options.signal;this._options.signal.addEventListener("abort",(()=>{this.abortController.abort(t.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 t="?"+("string"==typeof this._options.searchParams?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),e=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,t);!(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(e,{...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(t){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(t instanceof u)){if(t instanceof a){if(!this._options.retry.statusCodes.includes(t.response.status))return 0;const e=t.response.headers.get("Retry-After");if(e&&this._options.retry.afterStatusCodes.includes(t.response.status)){let t=Number(e);return Number.isNaN(t)?t=Date.parse(e)-Date.now():t*=1e3,void 0!==this._options.retry.maxRetryAfter&&t>this._options.retry.maxRetryAfter?0:t}if(413===t.response.status)return 0}const e=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,e)}return 0}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(e){const r=Math.min(this._calculateRetryDelay(e),w);if(0!==r&&this._retryCount>0){await async function(t,{signal:e}){return new Promise(((r,s)=>{function o(){clearTimeout(n),s(e.reason)}e&&(e.throwIfAborted(),e.addEventListener("abort",o,{once:!0}));const n=setTimeout((()=>{e?.removeEventListener("abort",o),r()}),t)}))}(r,{signal:this._options.signal});for(const t of this._options.hooks.beforeRetry){if(await t({request:this.request,options:this._options,error:e,retryCount:this._retryCount})===g)return}return this._retry(t)}throw e}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const e=await t(this.request,this._options);if(e instanceof Request){this.request=e;break}if(e instanceof Response)return e}const t=((t,e)=>{const r={};for(const s in e)s in R||s in T||s in t||(r[s]=e[s]);return r})(this.request,this._options);return!1===this._options.timeout?this._options.fetch(this.request.clone(),t):async function(t,e,r,s){return new Promise(((o,n)=>{const i=setTimeout((()=>{r&&r.abort(),n(new u(t))}),s.timeout);s.fetch(t,e).then(o).catch(n).then((()=>{clearTimeout(i)}))}))}(this.request.clone(),t,this.abortController,this._options)}_stream(t,e){const r=Number(t.headers.get("content-length"))||0;let s=0;return 204===t.status?(e&&e({percent:1,totalBytes:r,transferredBytes:s},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(o){const n=t.body.getReader();e&&e({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array),await async function t(){const{done:i,value:a}=await n.read();if(i)o.close();else{if(e){s+=a.byteLength;e({percent:0===r?0:s/r,transferredBytes:s,totalBytes:r},a)}o.enqueue(a),await t()}}()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}
|
|
2
|
-
/*! MIT License © Sindre Sorhus */const j=t=>{const e=(e,r)=>P.create(e,c(t,r));for(const r of m)e[r]=(e,s)=>P.create(e,c(t,s,{method:r}));return e.create=t=>j(c(t)),e.extend=e=>j(c(t,e)),e.stop=g,e},C=j();var O,A=e(Object.freeze({__proto__:null,HTTPError:a,TimeoutError:u,default:C})),k={};const S=t=>{try{const{href:e}=new URL(t);return s.test(e)&&e}catch(t){return!1}},U=i,{default:L}=A;class N extends Error{constructor(t){super(),this.name="MicrolinkError",Object.assign(this,t),this.description=this.message,this.message=this.code?`${this.code}, ${this.description}`:this.description}}const I=U({MicrolinkError:N,urlHttp:S,got:async(t,e)=>{try{e.retry>0&&(e.retry=e.retry+1),void 0===e.timeout&&(e.timeout=!1);const r=await L(t,e),s=await r.json(),{headers:o,status:n}=r;return{url:r.url,body:s,headers:o,statusCode:n}}catch(t){if(t.response){const{response:e}=t;t.response={...e,headers:Array.from(e.headers.entries()).reduce(((t,[e,r])=>(t[e]=r,t)),{}),statusCode:e.status,body:await e.text()}}throw t}},flatten:function(){if(O)return k;function t(e,r,s,o,n){var i,a=n?n+s:n;if(null==o)r&&(e[n]=o);else if("object"!=typeof o)e[n]=o;else if(Array.isArray(o))for(i=0;i<o.length;i++)t(e,r,s,o[i],a+i);else for(i in o)t(e,r,s,o[i],a+i)}return O=1,k.flattie=function(e,r,s){var o={};return"object"==typeof e&&t(o,!!s,r||".",e,""),o},k}().flattie,VERSION:"0.11.5-0"});r.exports=I;var D=r.exports.MicrolinkError=I.MicrolinkError,M=r.exports.getApiUrl=I.getApiUrl,H=r.exports.mapRules=I.mapRules,$=r.exports.version=I.version,B=t(r.exports);export{D as MicrolinkError,B as default,M as getApiUrl,H as mapRules,$ as version};
|
|
1
|
+
function t(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function e(t){if(t.__esModule)return t;var e=t.default;if("function"==typeof e){var r=function t(){return this instanceof t?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach((function(e){var s=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(r,e,s.get?s:{enumerable:!0,get:function(){return t[e]}})})),r}var r={exports:{}};const s=/^https?:\/\//i;var o={};function n(t,e,r,s,o){var i,a=o?o+r:o;if(null==s)e&&(t[o]=s);else if("object"!=typeof s)t[o]=s;else if(Array.isArray(s))for(i=0;i<s.length;i++)n(t,e,r,s[i],a+i);else for(i in s)n(t,e,r,s[i],a+i)}o.flattie=function(t,e,r){var s={};return"object"==typeof t&&n(s,!!r,e||".",t,""),s};const i={FREE:"https://api.microlink.io/",PRO:"https://pro.microlink.io/"},a=t=>null!==t&&"object"==typeof t;var u=({VERSION:t,MicrolinkError:e,urlHttp:r,got:s,flatten:o})=>{const n=t=>{if(!a(t))return;const e=o(t);return Object.keys(e).reduce(((t,r)=>(t[`data.${r}`]=e[r].toString(),t)),{})},u=async(t,r={})=>{try{const e=await s(t,r);return"buffer"===r.responseType?{body:e.body,response:e}:{...e.body,response:e}}catch(r){const{response:s={}}=r,{statusCode:n,body:i,headers:u={},url:l=t}=s,c=null!=(o=i)&&null!=o.constructor&&"function"==typeof o.constructor.isBuffer&&o.constructor.isBuffer(o),h=a(i)&&!c?i:((t,e,r)=>{try{return JSON.parse(t)}catch(s){const o=t||e.message;return{status:"error",data:{url:o},more:"https://microlink.io/efatalclient",code:"EFATALCLIENT",message:o,url:r}}})(c?i.toString():i,r,l);throw new e({...h,message:h.message,url:l,statusCode:n,headers:u})}var o},l=(t,{data:e,apiKey:r,endpoint:s,retry:a,cache:u,...l}={},{responseType:c="json",headers:h,...p}={})=>{const f=!!r;return[`${s||i[f?"PRO":"FREE"]}?${new URLSearchParams({url:t,...n(e),...o(l)}).toString()}`,{...p,responseType:c,cache:u,retry:a,headers:f?{...h,"x-api-key":r}:{...h}}]},c=t=>async(s,o,n)=>{((t="")=>{if(!r(t)){const r=`The \`url\` as \`${t}\` is not valid. Ensure it has protocol (http or https) and hostname.`;throw new e({status:"fail",data:{url:r},more:"https://microlink.io/docs/api/api-parameters/url",code:"EINVALURLCLIENT",message:r,url:t})}})(s);const[i,a]=l(s,o,{...t,...n});return u(i,a)},h=c();return h.MicrolinkError=e,h.getApiUrl=l,h.fetchFromApi=u,h.mapRules=n,h.version=t,h.stream=s.stream,h.buffer=c({responseType:"buffer"}),h};class l extends Error{constructor(t,e,r){const s=`${t.status||0===t.status?t.status:""} ${t.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=t,this.request=e,this.options=r}}class c extends Error{constructor(t){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=t}}const h=t=>null!==t&&"object"==typeof t,p=(...t)=>{for(const e of t)if((!h(e)||Array.isArray(e))&&void 0!==e)throw new TypeError("The `options` argument must be an object");return d({},...t)},f=(t={},e={})=>{const r=new globalThis.Headers(t),s=e instanceof globalThis.Headers,o=new globalThis.Headers(e);for(const[t,e]of o.entries())s&&"undefined"===e||void 0===e?r.delete(t):r.set(t,e);return r},d=(...t)=>{let e={},r={};for(const s of t)if(Array.isArray(s))Array.isArray(e)||(e=[]),e=[...e,...s];else if(h(s)){for(let[t,r]of Object.entries(s))h(r)&&t in e&&(r=d(e[t],r)),e={...e,[t]:r};h(s.headers)&&(r=f(r,s.headers),e.headers=r)}return e},y=(()=>{let t=!1,e=!1;const r="function"==typeof globalThis.ReadableStream,s="function"==typeof globalThis.Request;return r&&s&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type")),t&&!e})(),b="function"==typeof globalThis.AbortController,m="function"==typeof globalThis.ReadableStream,_="function"==typeof globalThis.FormData,w=["get","post","put","patch","head","delete"],g={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},T=2147483647,R=Symbol("stop"),v={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},E={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},q=t=>w.includes(t)?t.toUpperCase():t,x=[413,429,503],P={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:t=>.3*2**(t-1)*1e3},j=(t={})=>{if("number"==typeof t)return{...P,limit:t};if(t.methods&&!Array.isArray(t.methods))throw new Error("retry.methods must be an array");if(t.statusCodes&&!Array.isArray(t.statusCodes))throw new Error("retry.statusCodes must be an array");return{...P,...t,afterStatusCodes:x}};class C{static create(t,e){const r=new C(t,e),s=async()=>{if("number"==typeof r._options.timeout&&r._options.timeout>T)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let t=await r._fetch();for(const e of r._options.hooks.afterResponse){const s=await e(r.request,r._options,r._decorateResponse(t.clone()));s instanceof globalThis.Response&&(t=s)}if(r._decorateResponse(t),!t.ok&&r._options.throwHttpErrors){let e=new l(t,r.request,r._options);for(const t of r._options.hooks.beforeError)e=await t(e);throw e}if(r._options.onDownloadProgress){if("function"!=typeof r._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!m)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(t.clone(),r._options.onDownloadProgress)}return t},o=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(s):s();for(const[t,s]of Object.entries(g))o[t]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||s);const n=(await o).clone();if("json"===t){if(204===n.status)return"";if(0===(await n.clone().arrayBuffer()).byteLength)return"";if(e.parseJson)return e.parseJson(await n.text())}return n[t]()};return o}constructor(t,e={}){if(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=t,this._options={credentials:this._input.credentials||"same-origin",...e,headers:f(this._input.headers,e.headers),hooks:d({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:q(e.method??this._input.method),prefixUrl:String(e.prefixUrl||""),retry:j(e.retry),throwHttpErrors:!1!==e.throwHttpErrors,timeout:e.timeout??1e4,fetch:e.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(b){if(this.abortController=new globalThis.AbortController,this._options.signal){const t=this._options.signal;this._options.signal.addEventListener("abort",(()=>{this.abortController.abort(t.reason)}))}this._options.signal=this.abortController.signal}if(y&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const t="?"+("string"==typeof this._options.searchParams?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),e=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,t);!(_&&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(e,{...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(t){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(t instanceof c)){if(t instanceof l){if(!this._options.retry.statusCodes.includes(t.response.status))return 0;const e=t.response.headers.get("Retry-After");if(e&&this._options.retry.afterStatusCodes.includes(t.response.status)){let t=Number(e);return Number.isNaN(t)?t=Date.parse(e)-Date.now():t*=1e3,void 0!==this._options.retry.maxRetryAfter&&t>this._options.retry.maxRetryAfter?0:t}if(413===t.response.status)return 0}const e=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,e)}return 0}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(e){const r=Math.min(this._calculateRetryDelay(e),T);if(0!==r&&this._retryCount>0){await async function(t,{signal:e}){return new Promise(((r,s)=>{function o(){clearTimeout(n),s(e.reason)}e&&(e.throwIfAborted(),e.addEventListener("abort",o,{once:!0}));const n=setTimeout((()=>{e?.removeEventListener("abort",o),r()}),t)}))}(r,{signal:this._options.signal});for(const t of this._options.hooks.beforeRetry){if(await t({request:this.request,options:this._options,error:e,retryCount:this._retryCount})===R)return}return this._retry(t)}throw e}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const e=await t(this.request,this._options);if(e instanceof Request){this.request=e;break}if(e instanceof Response)return e}const t=((t,e)=>{const r={};for(const s in e)s in E||s in v||s in t||(r[s]=e[s]);return r})(this.request,this._options);return!1===this._options.timeout?this._options.fetch(this.request.clone(),t):async function(t,e,r,s){return new Promise(((o,n)=>{const i=setTimeout((()=>{r&&r.abort(),n(new c(t))}),s.timeout);s.fetch(t,e).then(o).catch(n).then((()=>{clearTimeout(i)}))}))}(this.request.clone(),t,this.abortController,this._options)}_stream(t,e){const r=Number(t.headers.get("content-length"))||0;let s=0;return 204===t.status?(e&&e({percent:1,totalBytes:r,transferredBytes:s},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(o){const n=t.body.getReader();e&&e({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array),await async function t(){const{done:i,value:a}=await n.read();if(i)o.close();else{if(e){s+=a.byteLength;e({percent:0===r?0:s/r,transferredBytes:s,totalBytes:r},a)}o.enqueue(a),await t()}}()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}const O=t=>{const e=(e,r)=>C.create(e,p(t,r));for(const r of w)e[r]=(e,s)=>C.create(e,p(t,s,{method:r}));return e.create=t=>O(p(t)),e.extend=e=>O(p(t,e)),e.stop=R,e},A=O();var k=e(Object.freeze({__proto__:null,HTTPError:l,TimeoutError:c,default:A}));const S=t=>{try{const{href:e}=new URL(t);return s.test(e)&&e}catch(t){return!1}},{flattie:U}=o,L=u,{default:N}=k;class I extends Error{constructor(t){super(),this.name="MicrolinkError",Object.assign(this,t),this.description=this.message,this.message=this.code?`${this.code}, ${this.description}`:this.description}}const D=L({MicrolinkError:I,urlHttp:S,got:async(t,e)=>{try{e.retry>0&&(e.retry=e.retry+1),void 0===e.timeout&&(e.timeout=!1);const r=await N(t,e),s=await r.json(),{headers:o,status:n}=r;return{url:r.url,body:s,headers:o,statusCode:n}}catch(t){if(t.response){const{response:e}=t;t.response={...e,headers:Array.from(e.headers.entries()).reduce(((t,[e,r])=>(t[e]=r,t)),{}),statusCode:e.status,body:await e.text()}}throw t}},flatten:U,VERSION:"0.11.5"});r.exports=D;var M=r.exports.MicrolinkError=D.MicrolinkError,H=r.exports.getApiUrl=D.getApiUrl,$=r.exports.mapRules=D.mapRules,B=r.exports.version=D.version,F=t(r.exports);export{M as MicrolinkError,F as default,H as getApiUrl,$ as mapRules,B as version};
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@microlink/mql",
|
|
3
3
|
"description": "Microlink Query Language. The official HTTP client to interact with Microlink API for Node.js, browsers & Deno.",
|
|
4
4
|
"homepage": "https://microlink.io/mql",
|
|
5
|
-
"version": "0.11.5
|
|
5
|
+
"version": "0.11.5",
|
|
6
6
|
"types": "lightweight/index.d.ts",
|
|
7
7
|
"main": "src/node.js",
|
|
8
8
|
"browser": "src/lightweight.js",
|
|
@@ -77,7 +77,6 @@
|
|
|
77
77
|
"npm-check-updates": "latest",
|
|
78
78
|
"prettier-standard": "latest",
|
|
79
79
|
"rollup": "latest",
|
|
80
|
-
"rollup-plugin-cjs-es": "latest",
|
|
81
80
|
"rollup-plugin-filesize": "latest",
|
|
82
81
|
"rollup-plugin-rewrite": "latest",
|
|
83
82
|
"rollup-plugin-visualizer": "latest",
|
|
@@ -98,6 +97,24 @@
|
|
|
98
97
|
"src/ky.js",
|
|
99
98
|
"src/node.js"
|
|
100
99
|
],
|
|
100
|
+
"scripts": {
|
|
101
|
+
"build": "rollup -c rollup.config.js --bundleConfigAsCjs",
|
|
102
|
+
"clean": "rm -rf node_modules",
|
|
103
|
+
"clean:build": "rm -rf dist lightweight/index.js",
|
|
104
|
+
"contributors": "(npx git-authors-cli && npx finepack --sort-ignore-object-at ava && git add package.json && git commit -m 'build: contributors' --no-verify) || true",
|
|
105
|
+
"dev": "npm run build -- -w",
|
|
106
|
+
"lint": "standard && tsd",
|
|
107
|
+
"postrelease": "npm run release:tags && npm run release:github && (ci-publish || npm publish --access=public)",
|
|
108
|
+
"prebuild": "npm run clean:build",
|
|
109
|
+
"prerelease": "npm run update:check",
|
|
110
|
+
"pretest": "npm run lint && npm run build",
|
|
111
|
+
"release": "standard-version -a",
|
|
112
|
+
"release:github": "conventional-github-releaser -p angular",
|
|
113
|
+
"release:tags": "git push --follow-tags origin HEAD:master",
|
|
114
|
+
"test": "c8 ava --verbose",
|
|
115
|
+
"update": "ncu -u",
|
|
116
|
+
"update:check": "ncu -- --error-level 2"
|
|
117
|
+
},
|
|
101
118
|
"license": "MIT",
|
|
102
119
|
"ava": {
|
|
103
120
|
"files": [
|
|
@@ -141,23 +158,5 @@
|
|
|
141
158
|
},
|
|
142
159
|
"tsd": {
|
|
143
160
|
"directory": "test"
|
|
144
|
-
},
|
|
145
|
-
"scripts": {
|
|
146
|
-
"build": "rollup -c rollup.config.js --bundleConfigAsCjs",
|
|
147
|
-
"clean": "rm -rf node_modules",
|
|
148
|
-
"clean:build": "rm -rf dist lightweight/index.js",
|
|
149
|
-
"contributors": "(npx git-authors-cli && npx finepack --sort-ignore-object-at ava && git add package.json && git commit -m 'build: contributors' --no-verify) || true",
|
|
150
|
-
"dev": "npm run build -- -w",
|
|
151
|
-
"lint": "standard && tsd",
|
|
152
|
-
"postrelease": "npm run release:tags && npm run release:github && (ci-publish || npm publish --access=public)",
|
|
153
|
-
"prebuild": "npm run clean:build",
|
|
154
|
-
"prerelease": "npm run update:check",
|
|
155
|
-
"pretest": "npm run lint && npm run build",
|
|
156
|
-
"release": "standard-version -a",
|
|
157
|
-
"release:github": "conventional-github-releaser -p angular",
|
|
158
|
-
"release:tags": "git push --follow-tags origin HEAD:master",
|
|
159
|
-
"test": "c8 ava --verbose",
|
|
160
|
-
"update": "ncu -u",
|
|
161
|
-
"update:check": "ncu -- --error-level 2"
|
|
162
161
|
}
|
|
163
|
-
}
|
|
162
|
+
}
|
package/src/ky.js
CHANGED
|
@@ -135,6 +135,35 @@
|
|
|
135
135
|
// The maximum value of a 32bit int (see issue #117)
|
|
136
136
|
const maxSafeTimeout = 2147483647;
|
|
137
137
|
const stop = Symbol('stop');
|
|
138
|
+
const kyOptionKeys = {
|
|
139
|
+
json: true,
|
|
140
|
+
parseJson: true,
|
|
141
|
+
searchParams: true,
|
|
142
|
+
prefixUrl: true,
|
|
143
|
+
retry: true,
|
|
144
|
+
timeout: true,
|
|
145
|
+
hooks: true,
|
|
146
|
+
throwHttpErrors: true,
|
|
147
|
+
onDownloadProgress: true,
|
|
148
|
+
fetch: true,
|
|
149
|
+
};
|
|
150
|
+
const requestOptionsRegistry = {
|
|
151
|
+
method: true,
|
|
152
|
+
headers: true,
|
|
153
|
+
body: true,
|
|
154
|
+
mode: true,
|
|
155
|
+
credentials: true,
|
|
156
|
+
cache: true,
|
|
157
|
+
redirect: true,
|
|
158
|
+
referrer: true,
|
|
159
|
+
referrerPolicy: true,
|
|
160
|
+
integrity: true,
|
|
161
|
+
keepalive: true,
|
|
162
|
+
signal: true,
|
|
163
|
+
window: true,
|
|
164
|
+
dispatcher: true,
|
|
165
|
+
duplex: true,
|
|
166
|
+
};
|
|
138
167
|
|
|
139
168
|
const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
|
|
140
169
|
const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];
|
|
@@ -147,6 +176,7 @@
|
|
|
147
176
|
afterStatusCodes: retryAfterStatusCodes,
|
|
148
177
|
maxRetryAfter: Number.POSITIVE_INFINITY,
|
|
149
178
|
backoffLimit: Number.POSITIVE_INFINITY,
|
|
179
|
+
delay: attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000,
|
|
150
180
|
};
|
|
151
181
|
const normalizeRetryOptions = (retry = {}) => {
|
|
152
182
|
if (typeof retry === 'number') {
|
|
@@ -169,7 +199,7 @@
|
|
|
169
199
|
};
|
|
170
200
|
|
|
171
201
|
// `Promise.race()` workaround (#91)
|
|
172
|
-
async function timeout(request, abortController, options) {
|
|
202
|
+
async function timeout(request, init, abortController, options) {
|
|
173
203
|
return new Promise((resolve, reject) => {
|
|
174
204
|
const timeoutId = setTimeout(() => {
|
|
175
205
|
if (abortController) {
|
|
@@ -178,7 +208,7 @@
|
|
|
178
208
|
reject(new TimeoutError(request));
|
|
179
209
|
}, options.timeout);
|
|
180
210
|
void options
|
|
181
|
-
.fetch(request)
|
|
211
|
+
.fetch(request, init)
|
|
182
212
|
.then(resolve)
|
|
183
213
|
.catch(reject)
|
|
184
214
|
.then(() => {
|
|
@@ -205,6 +235,16 @@
|
|
|
205
235
|
});
|
|
206
236
|
}
|
|
207
237
|
|
|
238
|
+
const findUnknownOptions = (request, options) => {
|
|
239
|
+
const unknownOptions = {};
|
|
240
|
+
for (const key in options) {
|
|
241
|
+
if (!(key in requestOptionsRegistry) && !(key in kyOptionKeys) && !(key in request)) {
|
|
242
|
+
unknownOptions[key] = options[key];
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return unknownOptions;
|
|
246
|
+
};
|
|
247
|
+
|
|
208
248
|
class Ky {
|
|
209
249
|
static create(input, options) {
|
|
210
250
|
const ky = new Ky(input, options);
|
|
@@ -396,8 +436,8 @@
|
|
|
396
436
|
return 0;
|
|
397
437
|
}
|
|
398
438
|
}
|
|
399
|
-
const
|
|
400
|
-
return Math.min(this._options.retry.backoffLimit,
|
|
439
|
+
const retryDelay = this._options.retry.delay(this._retryCount);
|
|
440
|
+
return Math.min(this._options.retry.backoffLimit, retryDelay);
|
|
401
441
|
}
|
|
402
442
|
return 0;
|
|
403
443
|
}
|
|
@@ -445,10 +485,11 @@
|
|
|
445
485
|
return result;
|
|
446
486
|
}
|
|
447
487
|
}
|
|
488
|
+
const nonRequestOptions = findUnknownOptions(this.request, this._options);
|
|
448
489
|
if (this._options.timeout === false) {
|
|
449
|
-
return this._options.fetch(this.request.clone());
|
|
490
|
+
return this._options.fetch(this.request.clone(), nonRequestOptions);
|
|
450
491
|
}
|
|
451
|
-
return timeout(this.request.clone(), this.abortController, this._options);
|
|
492
|
+
return timeout(this.request.clone(), nonRequestOptions, this.abortController, this._options);
|
|
452
493
|
}
|
|
453
494
|
/* istanbul ignore next */
|
|
454
495
|
_stream(response, onDownloadProgress) {
|
package/src/lightweight.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict'
|
|
2
2
|
|
|
3
3
|
const urlHttp = require('url-http/lightweight')
|
|
4
|
-
|
|
4
|
+
const { flattie: flatten } = require('flattie')
|
|
5
5
|
const factory = require('./factory')
|
|
6
6
|
const { default: ky } = require('ky')
|
|
7
7
|
|
|
@@ -49,7 +49,7 @@ const mql = factory({
|
|
|
49
49
|
MicrolinkError,
|
|
50
50
|
urlHttp,
|
|
51
51
|
got,
|
|
52
|
-
flatten
|
|
52
|
+
flatten,
|
|
53
53
|
VERSION: '__MQL_VERSION__'
|
|
54
54
|
})
|
|
55
55
|
|