-
Notifications
You must be signed in to change notification settings - Fork 0
/
ky.min.js
9 lines (9 loc) · 8.36 KB
/
ky.min.js
1
2
3
4
5
6
7
8
9
/**
* Minified by jsDelivr using Terser v5.3.0.
* Original file: /npm/[email protected]/index.js
*
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
*/
/*! MIT License © Sindre Sorhus */
const globals={},getGlobal=t=>"undefined"!=typeof self&&self&&t in self?self:"undefined"!=typeof window&&window&&t in window?window:"undefined"!=typeof global&&global&&t in global?global:"undefined"!=typeof globalThis&&globalThis?globalThis:void 0,globalProperties=["Headers","Request","Response","ReadableStream","fetch","AbortController","FormData"];for(const t of globalProperties)Object.defineProperty(globals,t,{get(){const e=getGlobal(t),s=e&&e[t];return"function"==typeof s?s.bind(e):s}});const isObject=t=>null!==t&&"object"==typeof t,supportsAbortController="function"==typeof globals.AbortController,supportsStreams="function"==typeof globals.ReadableStream,supportsFormData="function"==typeof globals.FormData,mergeHeaders=(t,e)=>{const s=new globals.Headers(t||{}),r=e instanceof globals.Headers,o=new globals.Headers(e||{});for(const[t,e]of o)r&&"undefined"===e||void 0===e?s.delete(t):s.set(t,e);return s},deepMerge=(...t)=>{let e={},s={};for(const r of t){if(Array.isArray(r))Array.isArray(e)||(e=[]),e=[...e,...r];else if(isObject(r)){for(let[t,s]of Object.entries(r))isObject(s)&&Reflect.has(e,t)&&(s=deepMerge(e[t],s)),e={...e,[t]:s};isObject(r.headers)&&(s=mergeHeaders(s,r.headers))}e.headers=s}return e},requestMethods=["get","post","put","patch","head","delete"],responseTypes={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},retryMethods=["get","put","head","delete","options","trace"],retryStatusCodes=[408,413,429,500,502,503,504],retryAfterStatusCodes=[413,429,503],stop=Symbol("stop");class HTTPError extends Error{constructor(t){super(t.statusText||String(0===t.status||t.status?t.status:"Unknown response error")),this.name="HTTPError",this.response=t}}class TimeoutError extends Error{constructor(t){super("Request timed out"),this.name="TimeoutError",this.request=t}}const delay=t=>new Promise(e=>setTimeout(e,t)),timeout=(t,e,s)=>new Promise((r,o)=>{const n=setTimeout(()=>{e&&e.abort(),o(new TimeoutError(t))},s.timeout);s.fetch(t).then(r).catch(o).then(()=>{clearTimeout(n)})}),normalizeRequestMethod=t=>requestMethods.includes(t)?t.toUpperCase():t,defaultRetryOptions={limit:2,methods:retryMethods,statusCodes:retryStatusCodes,afterStatusCodes:retryAfterStatusCodes},normalizeRetryOptions=(t={})=>{if("number"==typeof t)return{...defaultRetryOptions,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{...defaultRetryOptions,...t,afterStatusCodes:retryAfterStatusCodes}},maxSafeTimeout=2147483647;class Ky{constructor(t,e={}){if(this._retryCount=0,this._input=t,this._options={credentials:this._input.credentials||"same-origin",...e,headers:mergeHeaders(this._input.headers,e.headers),hooks:deepMerge({beforeRequest:[],beforeRetry:[],afterResponse:[]},e.hooks),method:normalizeRequestMethod(e.method||this._input.method),prefixUrl:String(e.prefixUrl||""),retry:normalizeRetryOptions(e.retry),throwHttpErrors:!1!==e.throwHttpErrors,timeout:void 0===e.timeout?1e4:e.timeout,fetch:e.fetch||globals.fetch},"string"!=typeof this._input&&!(this._input instanceof URL||this._input instanceof globals.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(supportsAbortController&&(this.abortController=new globals.AbortController,this._options.signal&&this._options.signal.addEventListener("abort",()=>{this.abortController.abort()}),this._options.signal=this.abortController.signal),this.request=new globals.Request(this._input,this._options),this._options.searchParams){const t="?"+new URLSearchParams(this._options.searchParams).toString(),e=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,t);!(supportsFormData&&this._options.body instanceof globals.FormData||this._options.body instanceof URLSearchParams)||this._options.headers&&this._options.headers["content-type"]||this.request.headers.delete("content-type"),this.request=new globals.Request(new globals.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","application/json"),this.request=new globals.Request(this.request,{body:this._options.body}));const s=async()=>{if(this._options.timeout>2147483647)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await delay(1);let t=await this._fetch();for(const e of this._options.hooks.afterResponse){const s=await e(this.request,this._options,this._decorateResponse(t.clone()));s instanceof globals.Response&&(t=s)}if(this._decorateResponse(t),!t.ok&&this._options.throwHttpErrors)throw new HTTPError(t);if(this._options.onDownloadProgress){if("function"!=typeof this._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!supportsStreams)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return this._stream(t.clone(),this._options.onDownloadProgress)}return t},r=this._options.retry.methods.includes(this.request.method.toLowerCase())?this._retry(s):s();for(const[t,s]of Object.entries(responseTypes))r[t]=async()=>{this.request.headers.set("accept",this.request.headers.get("accept")||s);const o=(await r).clone();if("json"===t){if(204===o.status)return"";if(e.parseJson)return e.parseJson(await o.text())}return o[t]()};return r}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(t instanceof TimeoutError)){if(t instanceof HTTPError){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}return.3*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 s=Math.min(this._calculateRetryDelay(e),2147483647);if(0!==s&&this._retryCount>0){await delay(s);for(const t of this._options.hooks.beforeRetry){if(await t({request:this.request,options:this._options,error:e,retryCount:this._retryCount})===stop)return}return this._retry(t)}if(this._options.throwHttpErrors)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()):(t=this.request.clone(),e=this.abortController,s=this._options,new Promise((r,o)=>{const n=setTimeout(()=>{e&&e.abort(),o(new TimeoutError(t))},s.timeout);s.fetch(t).then(r).catch(o).then(()=>{clearTimeout(n)})}));var t,e,s}_stream(t,e){const s=Number(t.headers.get("content-length"))||0;let r=0;return new globals.Response(new globals.ReadableStream({start(o){const n=t.body.getReader();e&&e({percent:0,transferredBytes:0,totalBytes:s},new Uint8Array),async function t(){const{done:i,value:a}=await n.read();if(i)o.close();else{if(e){r+=a.byteLength;e({percent:0===s?0:r/s,transferredBytes:r,totalBytes:s},a)}o.enqueue(a),t()}}()}}))}}const validateAndMerge=(...t)=>{for(const e of t)if((!isObject(e)||Array.isArray(e))&&void 0!==e)throw new TypeError("The `options` argument must be an object");return deepMerge({},...t)},createInstance=t=>{const e=(e,s)=>new Ky(e,validateAndMerge(t,s));for(const s of requestMethods)e[s]=(e,r)=>new Ky(e,validateAndMerge(t,r,{method:s}));return e.HTTPError=HTTPError,e.TimeoutError=TimeoutError,e.create=t=>createInstance(validateAndMerge(t)),e.extend=e=>createInstance(validateAndMerge(t,e)),e.stop=stop,e};export default createInstance();
//# sourceMappingURL=/sm/c26db4d4d89b8503d06730d1e9a11c8e8c3eff84c673fc5b355ad299e502fd27.map