@microlink/mql 0.11.0-5 → 0.11.0-7

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/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-5",
6
- "types": "index.d.ts",
5
+ "version": "0.11.0-7",
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": "./dist/lightweight.mjs",
12
+ "import": "./lightweight/index.js",
13
13
  "require": "./src/node.js"
14
14
  }
15
15
  },
@@ -92,10 +92,13 @@
92
92
  "node": ">= 12"
93
93
  },
94
94
  "files": [
95
- "dist",
96
- "index.d.ts",
97
- "lightweight",
98
- "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"
99
102
  ],
100
103
  "license": "MIT",
101
104
  "ava": {
@@ -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: {
@@ -1,2 +0,0 @@
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};
package/dist/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 * as 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-4'
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 };
@@ -1,173 +0,0 @@
1
- type ColorScheme = | "dark" | "light";
2
-
3
- type WaitUntilEvent = "load" | "domcontentloaded" | "networkidle0" | "networkidle2";
4
-
5
- type PixelUnit = string | number;
6
-
7
- type ScreenshotOverlay = {
8
- background?: string,
9
- browser?: 'dark' | 'light'
10
- }
11
-
12
- type PdfMargin = {
13
- top?: string | number;
14
- bottom?: string | number;
15
- left?: string | number;
16
- right?: string | number;
17
- }
18
-
19
- type PdfOptions = {
20
- format?: string;
21
- height?: PixelUnit;
22
- landscape?: string;
23
- margin?: string | PdfMargin;
24
- pageRanges?: string;
25
- scale?: number;
26
- width?: PixelUnit;
27
- }
28
-
29
- type ScreenshotOptions = {
30
- codeScheme?: string;
31
- omitBackground?: boolean;
32
- type?: "jpeg" | "png";
33
- element?: string;
34
- fullPage?: boolean;
35
- overlay?: ScreenshotOverlay
36
- }
37
-
38
- export type MqlOptions = {
39
- endpoint?: string;
40
- apiKey?: string;
41
- retry?: number;
42
- cache?: Map<string, any>;
43
- }
44
-
45
- type MqlQuery = {
46
- [field: string]: MqlQueryOptions;
47
- }
48
-
49
- type MqlQueryOptions = {
50
- attr?: string | string[] | MqlQuery;
51
- evaluate?: string;
52
- selector?: string | string[];
53
- selectorAll?: string | string[];
54
- type?: "audio" | "author" | "auto" | "boolean" | "date" | "description" | "email" | "image" | "ip" | "lang" | "logo" | "number" | "object" | "publisher" | "regexp" | "string" | "title" | "url" | "video";
55
- }
56
-
57
- export type MicrolinkApiOptions = {
58
- adblock?: boolean;
59
- animations?: boolean;
60
- audio?: boolean;
61
- click?: string | string[];
62
- colorScheme?: ColorScheme;
63
- data?: MqlQuery;
64
- device?: string;
65
- embed?: string;
66
- filename?: string;
67
- filter?: string;
68
- force?: boolean;
69
- function?: string;
70
- headers?: Record<string, string>;
71
- iframe?: boolean | { maxWidth?: number, maxHeight?: number };
72
- insights?: boolean | { lighthouse?: boolean | object, technologies?: boolean };
73
- javascript?: boolean;
74
- mediaType?: string;
75
- meta?: boolean | { logo: { square: boolean } };
76
- modules?: string | string[];
77
- palette?: boolean;
78
- pdf?: boolean | PdfOptions;
79
- ping?: boolean | object;
80
- prerender?: boolean | "auto";
81
- proxy?: string | { countryCode?: string };
82
- retry?: number;
83
- screenshot?: boolean | ScreenshotOptions;
84
- scripts?: string | string[];
85
- scroll?: string;
86
- styles?: string | string[];
87
- staleTtl?: string | number;
88
- timeout?: number;
89
- ttl?: string | number;
90
- video?: boolean;
91
- viewport?: object;
92
- waitForSelector?: string;
93
- waitForTimeout?: number;
94
- waitUntil?: WaitUntilEvent | WaitUntilEvent[];
95
- }
96
-
97
- type IframeInfo = {
98
- html: string;
99
- scripts: Record<string, unknown>;
100
- }
101
-
102
- type MediaInfo = {
103
- url: string;
104
- type?: string;
105
- palette?: string[];
106
- background_color?: string;
107
- color?: string;
108
- alternative_color?: string;
109
- width?: number;
110
- height?: number;
111
- duration?: number;
112
- duration_pretty?: string;
113
- }
114
-
115
- type MqlResponseData = {
116
- // A human-readable representation of the author's name.
117
- author?: string | null;
118
- // An ISO 8601 representation of the date the article was published.
119
- date?: string | null;
120
- // The publisher's chosen description of the article.
121
- description?: string | null;
122
- // An ISO 639-1 representation of the url content language.
123
- lang?: string | null;
124
- // An image URL that best represents the publisher brand.
125
- logo?: MediaInfo | null;
126
- // A human-readable representation of the publisher's name.
127
- publisher?: string | null;
128
- // The publisher's chosen title of the article.
129
- title?: string | null;
130
- // The URL of the article.
131
- url?: string;
132
- image?: MediaInfo | null;
133
- screenshot?: MediaInfo | null;
134
- video?: MediaInfo | null;
135
- audio?: MediaInfo | null;
136
- iframe?: IframeInfo | null;
137
- function?: MqlFunctionResult;
138
- }
139
-
140
- type MqlFunctionResult = {
141
- isFulfilled: boolean;
142
- isRejected: boolean;
143
- value: any;
144
- };
145
-
146
- type MqlStatus = "success" | "fail" | "error";
147
-
148
- export type MqlPayload = {
149
- status: MqlStatus;
150
- data: MqlResponseData;
151
- statusCode: number;
152
- headers: { [key: string]: string };
153
- more?: string,
154
- code?: string,
155
- url?: string
156
- }
157
-
158
- export type MqlResponse = MqlPayload & {
159
- response: {
160
- url: string;
161
- statusCode: number;
162
- headers: Headers;
163
- body: MqlPayload
164
- };
165
- }
166
-
167
- declare function mql(
168
- url: string,
169
- opts?: MqlOptions & MicrolinkApiOptions,
170
- gotOpts?: object
171
- ): Promise<MqlResponse>;
172
-
173
- export default mql;
@@ -1,5 +0,0 @@
1
- {
2
- "main": "index.js",
3
- "type": "module",
4
- "types": "index.d.ts"
5
- }
@@ -1,55 +0,0 @@
1
- 'use strict'
2
-
3
- const urlHttp = require('url-http/lightweight')
4
- const { flattie: flatten } = require('flattie')
5
-
6
- const factory = require('./factory')
7
- const { default: ky } = require('ky')
8
-
9
- class MicrolinkError extends Error {
10
- constructor (props) {
11
- super()
12
- this.name = 'MicrolinkError'
13
- Object.assign(this, props)
14
- this.description = this.message
15
- this.message = this.code
16
- ? `${this.code}, ${this.description}`
17
- : this.description
18
- }
19
- }
20
-
21
- const got = async (url, opts) => {
22
- try {
23
- if (opts.retry > 0) opts.retry = opts.retry + 1
24
- if (opts.timeout === undefined) opts.timeout = false
25
- const response = await ky(url, opts)
26
- const body = await response.json()
27
- const { headers, status: statusCode } = response
28
- return { url: response.url, body, headers, statusCode }
29
- } catch (err) {
30
- if (err.response) {
31
- const { response } = err
32
- err.response = {
33
- ...response,
34
- headers: Array.from(response.headers.entries()).reduce(
35
- (acc, [key, value]) => {
36
- acc[key] = value
37
- return acc
38
- },
39
- {}
40
- ),
41
- statusCode: response.status,
42
- body: await response.text()
43
- }
44
- }
45
- throw err
46
- }
47
- }
48
-
49
- module.exports = factory({
50
- MicrolinkError,
51
- urlHttp,
52
- got,
53
- flatten,
54
- VERSION: require('../package.json').version
55
- })