@microlink/mql 0.11.0-4 → 0.11.0-6

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