diff --git a/browser/hyperfetch-browser.min.js b/browser/hyperfetch-browser.min.js index 2d40409..70aed0f 100644 --- a/browser/hyperfetch-browser.min.js +++ b/browser/hyperfetch-browser.min.js @@ -1,2 +1,2 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("{}")):"function"==typeof define&&define.amd?define("hypf",["{}"],t):"object"==typeof exports?exports.hypf=t(require("{}")):e.hypf=t(e["{}"])}(self,(e=>(()=>{"use strict";var t={324:t=>{t.exports=e}},o={};function r(e){var n=o[e];if(void 0!==n)return n.exports;var i=o[e]={exports:{}};return t[e](i,i.exports,r),i.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var o in t)r.o(t,o)&&!r.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};r.r(n),r.d(n,{default:()=>O,init:()=>v});var i=r(324),s=r.n(i);const a=2147483647,l=.3,c=1,u="function"==typeof globalThis.AbortController,f="function"==typeof globalThis.ReadableStream,d="function"==typeof globalThis.WritableStream,p="function"==typeof globalThis.WebSocket,b="function"==typeof globalThis.RTCPeerConnection,y=(globalThis.FormData,void 0!==s()&&"node"===s().release.name),g=()=>u?r.g.abortController:null,h=(e,t)=>1e3*Math.pow(2,e)*t,m=e=>1e3*Math.random()*e;const j=(e="",t={},o,{baseUrl:n,hooks:i,debug:s,throwOnError:g}=Object.create(null))=>{return T=void 0,v=void 0,w=function*(){var T;const{method:v="GET",retries:O=0,backoff:w=h,jitter:R=!1,jitterFactor:x=c,backoffFactor:S=l,timeout:E=a,retryOnTimeout:C=!1,params:P,headers:F={},signal:k}=t,q=function(e,t){var o={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(o[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(r=Object.getOwnPropertySymbols(e);n{r.g.abortController.abort(),(null==i?void 0:i.postTimeout)&&i.postTimeout(e,t)}),E):void 0,h=P?((e,t)=>{if(!t)return e;const o=new URL(e);return Object.entries(t).forEach((([e,t])=>o.searchParams.append(e,String(t)))),o.toString()})(s,P):s;f&&!d&&y&&(q.duplex="half"),!f&&d&&y&&(q.duplex="half"),f&&d&&y&&(q.duplex="half"),b&&y&&(q.duplex="half"),p&&y&&(q.duplex="half");const m=t.body instanceof FormData?t.body:0!==Object.keys(o).length?JSON.stringify(o):void 0,j=Object.assign(Object.assign({method:v,signal:u?r.g.abortSignal:null,headers:a},q),{body:m});m instanceof FormData&&j.headers.delete("Content-Type");const O=fetch(h,j);clearTimeout(c);const w=yield O,R=w.headers.get("content-type"),x=R&&R.includes("application/json")?yield w.json():yield w.text();if(!w.ok)throw function(e,t){const o=`${e.status||0===e.status?e.status:""} ${e.statusText||""}`.trim(),r=new Error(o?`status code ${o}`:"an unknown error");return r.name="HTTPError",r.response=e,r.data=t,r}(w,x);return(null==i?void 0:i.postRequest)&&i.postRequest(e,t,o,[null,x]),g?x:[null,x]}catch(r){if((null==i?void 0:i.postRequest)&&r instanceof Error&&i.postRequest(e,t,o,[r,null]),r instanceof Error){if("AbortError"!==r.name){if(C&&"TimeoutError"===r.name&&O&&O>0){const r=R&&x?m(x):w(O,S||l);s&&console.warn(`Request timed out. Retrying in ${r}ms... (Remaining retries: ${O})`),(null==i?void 0:i.preRetry)&&i.preRetry(e,t,O,O),yield new Promise((e=>setTimeout(e,r)));const[n,a]=yield j(e,Object.assign(Object.assign({},t),{retries:O-1}),o);if((null==i?void 0:i.postRetry)&&i.postRetry(e,t,o,[n,a],O,O-1),g)throw n;return[n,a]}if(t.retries&&t.retries>0){const r=t.jitter&&t.jitterFactor?m(t.jitterFactor):w(t.retries,t.backoffFactor?t.backoffFactor:l);s&&console.warn(`Request failed. Retrying in ${r}ms... (Remaining retries: ${t.retries})`),(null==i?void 0:i.preRetry)&&i.preRetry(e,t,t.retries,t.retries),yield new Promise((e=>setTimeout(e,r)));const[n,a]=yield j(e,Object.assign(Object.assign({},t),{retries:t.retries-1}),o);if((null==i?void 0:i.postRetry)&&i.postRetry(e,t,o,[n,a],t.retries,t.retries-1),g)throw n;return[n,a]}if(g)throw r;return[r,null]}console.error("Request aborted:",r)}if(g)throw r;return[r,null]}},new((O=void 0)||(O=Promise))((function(e,t){function o(e){try{n(w.next(e))}catch(e){t(e)}}function r(e){try{n(w.throw(e))}catch(e){t(e)}}function n(t){var n;t.done?e(t.value):(n=t.value,n instanceof O?n:new O((function(e){e(n)}))).then(o,r)}n((w=w.apply(T,v||[])).next())}));var T,v,O,w},T=(e,t="GET",o=Object.create(null),r=Object.create(null),n)=>(o.initOptions&&(n=o.initOptions),j(e,Object.assign({method:t},o),r,n));function v(e="",t=Object.create(null)){if("undefined"==typeof fetch)throw new Error("This library is intended for use in the browser environment only.");return e&&(t.baseUrl=e),{get:(e,o,r)=>T(e,"GET",o,r,t),post:(e,o,r)=>T(e,"POST",o,r,t),put:(e,o,r)=>T(e,"PUT",o,r,t),delete:(e,o,r)=>T(e,"DELETE",o,r,t),patch:(e,o,r)=>T(e,"PATCH",o,r,t),head:(e,o,r)=>T(e,"HEAD",o,r,t),options:(e,o,r)=>T(e,"OPTIONS",o,r,t),getAbortController:g}}const O={init:v};return n})())); +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("{}")):"function"==typeof define&&define.amd?define("hypf",["{}"],t):"object"==typeof exports?exports.hypf=t(require("{}")):e.hypf=t(e["{}"])}(self,(e=>(()=>{"use strict";var t={324:t=>{t.exports=e}},o={};function r(e){var n=o[e];if(void 0!==n)return n.exports;var i=o[e]={exports:{}};return t[e](i,i.exports,r),i.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var o in t)r.o(t,o)&&!r.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};r.r(n),r.d(n,{default:()=>v,init:()=>T});var i=r(324),s=r.n(i);const a=2147483647,l=.3,c=1,u="function"==typeof globalThis.AbortController,f="function"==typeof globalThis.ReadableStream,d="function"==typeof globalThis.WritableStream,p="function"==typeof globalThis.WebSocket,b="function"==typeof globalThis.RTCPeerConnection,y=(globalThis.FormData,void 0!==s()&&"node"===s().release.name),g=()=>u?r.g.abortController:null,h=(e,t)=>1e3*Math.pow(2,e)*t,m=e=>1e3*Math.random()*e;const j=(e="",t={},o,{baseUrl:n,hooks:i,debug:s,throwOnError:g}=Object.create(null))=>{return O=void 0,T=void 0,w=function*(){var O;const{method:T="GET",retries:v=0,backoff:w=h,jitter:R=!1,jitterFactor:x=c,backoffFactor:S=l,timeout:E=a,retryOnTimeout:C=!1,params:P,headers:F={},signal:k}=t,q=function(e,t){var o={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(o[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(r=Object.getOwnPropertySymbols(e);n{r.g.abortController.abort(),(null==i?void 0:i.postTimeout)&&i.postTimeout(e,t)}),E):void 0,h=P?((e,t)=>{if(!t)return e;const o=new URL(e);return Object.entries(t).forEach((([e,t])=>o.searchParams.append(e,String(t)))),o.toString()})(s,P):s;f&&!d&&y&&(q.duplex="half"),!f&&d&&y&&(q.duplex="half"),f&&d&&y&&(q.duplex="half"),b&&y&&(q.duplex="half"),p&&y&&(q.duplex="half");const m=t.body instanceof FormData?t.body:0!==Object.keys(o).length?JSON.stringify(o):void 0,j=Object.assign(Object.assign({method:T,signal:u?r.g.abortSignal:null,headers:a},q),{body:m});m instanceof FormData&&j.headers.delete("Content-Type");const v=fetch(h,j);clearTimeout(c);const w=yield v,R=w.headers.get("content-type"),x=R&&R.includes("application/json")?yield w.json():yield w.text();if(!w.ok)throw function(e,t){const o=`${e.status||0===e.status?e.status:""} ${e.statusText||""}`.trim(),r=new Error(o?`status code ${o}`:"an unknown error");return r.name="HTTPError",r.response=e,r.data=t,r}(w,x);return(null==i?void 0:i.postRequest)&&i.postRequest(e,t,o,[null,x]),g?x:[null,x]}catch(r){if((null==i?void 0:i.postRequest)&&r instanceof Error&&i.postRequest(e,t,o,[r,null]),r instanceof Error){if("AbortError"!==r.name){if(C&&"TimeoutError"===r.name&&v&&v>0){const r=R&&x?m(x):w(v,S||l);s&&console.warn(`Request timed out. Retrying in ${r}ms... (Remaining retries: ${v})`),(null==i?void 0:i.preRetry)&&i.preRetry(e,t,v,v),yield new Promise((e=>setTimeout(e,r)));const[n,a]=yield j(e,Object.assign(Object.assign({},t),{retries:v-1}),o);if((null==i?void 0:i.postRetry)&&i.postRetry(e,t,o,[n,a],v,v-1),g)throw n;return[n,a]}if(t.retries&&t.retries>0){const r=t.jitter&&t.jitterFactor?m(t.jitterFactor):w(t.retries,t.backoffFactor?t.backoffFactor:l);s&&console.warn(`Request failed. Retrying in ${r}ms... (Remaining retries: ${t.retries})`),(null==i?void 0:i.preRetry)&&i.preRetry(e,t,t.retries,t.retries),yield new Promise((e=>setTimeout(e,r)));const[n,a]=yield j(e,Object.assign(Object.assign({},t),{retries:t.retries-1}),o);if((null==i?void 0:i.postRetry)&&i.postRetry(e,t,o,[n,a],t.retries,t.retries-1),g)throw n;return[n,a]}if(g)throw r;return[r,null]}console.error("Request aborted:",r)}if(g)throw r;return[r,null]}},new((v=void 0)||(v=Promise))((function(e,t){function o(e){try{n(w.next(e))}catch(e){t(e)}}function r(e){try{n(w.throw(e))}catch(e){t(e)}}function n(t){var n;t.done?e(t.value):(n=t.value,n instanceof v?n:new v((function(e){e(n)}))).then(o,r)}n((w=w.apply(O,T||[])).next())}));var O,T,v,w},O=(e,t="GET",o=Object.create(null),r=Object.create(null),n)=>(o.initOptions&&(n=o.initOptions),delete o.initOptions,j(e,Object.assign({method:t},o),r,n));function T(e="",t=Object.create(null)){if("undefined"==typeof fetch)throw new Error("This library is intended for use in the browser environment only.");return e&&(t.baseUrl=e),{get:(e,o,r)=>O(e,"GET",o,r,t),post:(e,o,r)=>O(e,"POST",o,r,t),put:(e,o,r)=>O(e,"PUT",o,r,t),delete:(e,o,r)=>O(e,"DELETE",o,r,t),patch:(e,o,r)=>O(e,"PATCH",o,r,t),head:(e,o,r)=>O(e,"HEAD",o,r,t),options:(e,o,r)=>O(e,"OPTIONS",o,r,t),getAbortController:g}}const v={init:T};return n})())); //# sourceMappingURL=hyperfetch-browser.min.js.map \ No newline at end of file diff --git a/browser/hyperfetch-browser.min.js.map b/browser/hyperfetch-browser.min.js.map index 762c7b7..3fabf02 100644 --- a/browser/hyperfetch-browser.min.js.map +++ b/browser/hyperfetch-browser.min.js.map @@ -1 +1 @@ -{"version":3,"file":"hyperfetch-browser.min.js","mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,EAAQG,QAAQ,OACR,mBAAXC,QAAyBA,OAAOC,IAC9CD,OAAO,OAAQ,CAAC,MAAOJ,GACG,iBAAZC,QACdA,QAAc,KAAID,EAAQG,QAAQ,OAElCJ,EAAW,KAAIC,EAAQD,EAAK,MAC7B,CATD,CASGO,MAAOC,G,kCCTVL,EAAOD,QAAUM,C,GCCbC,EAA2B,CAAC,EAGhC,SAASC,EAAoBC,GAE5B,IAAIC,EAAeH,EAAyBE,GAC5C,QAAqBE,IAAjBD,EACH,OA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,EAAM6E,GAC3EG,IAAK,CAAClF,EAAKC,EAASC,IAAS4E,EAAiB9E,EAAK,MAAOC,EAASC,EAAM6E,GACzE3B,OAAQ,CAACpD,EAAKC,EAASC,IAAS4E,EAAiB9E,EAAK,SAAUC,EAASC,EAAM6E,GAC/EI,MAAO,CAACnF,EAAKC,EAASC,IAAS4E,EAAiB9E,EAAK,QAASC,EAASC,EAAM6E,GAC7EK,KAAM,CAACpF,EAAKC,EAASC,IAAS4E,EAAiB9E,EAAK,OAAQC,EAASC,EAAM6E,GAC3E9E,QAAS,CAACD,EAAKC,EAASC,IAAS4E,EAAiB9E,EAAK,UAAWC,EAASC,EAAM6E,GACjFzF,mBAAkB,EAEtB,CAEA,SAAiB0F,Q","sources":["webpack://hypf/webpack/universalModuleDefinition","webpack://hypf/external umd \"{}\"","webpack://hypf/webpack/bootstrap","webpack://hypf/webpack/runtime/compat get default export","webpack://hypf/webpack/runtime/define property getters","webpack://hypf/webpack/runtime/global","webpack://hypf/webpack/runtime/hasOwnProperty shorthand","webpack://hypf/webpack/runtime/make namespace object","webpack://hypf/./src/utils/constant.ts","webpack://hypf/./src/utils/get-abort-controller.ts","webpack://hypf/./src/utils/default-retries.ts","webpack://hypf/./src/utils/create-request.ts","webpack://hypf/./src/utils/append-params.ts","webpack://hypf/./src/utils/create-http-error.ts","webpack://hypf/./src/utils/create-http-method.ts","webpack://hypf/./src/index.ts"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"{}\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"hypf\", [\"{}\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"hypf\"] = factory(require(\"{}\"));\n\telse\n\t\troot[\"hypf\"] = factory(root[\"{}\"]);\n})(self, (__WEBPACK_EXTERNAL_MODULE__324__) => {\nreturn ","module.exports = __WEBPACK_EXTERNAL_MODULE__324__;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","// disabled in webpack\nimport process from 'node:process'\n\n/**\n * Default maximum recommended timeout in milliseconds.\n * @type {number}\n */\nexport const DEFAULT_MAX_TIMEOUT = 2147483647\n\n/**\n * Default factor for exponential backoff.\n * @type {number}\n */\nexport const DEFAULT_BACKOFF_FACTOR = 0.3\n\n/**\n * Default factor for jitter in delay.\n * @type {number}\n */\nexport const DEFAULT_JITTER_FACTOR = 1\n\n/**\n * Indicates if AbortController is supported.\n * @type {boolean}\n */\nexport const isAbortControllerSupported = typeof globalThis.AbortController === 'function'\n\n/**\n * Indicates if ReadableStream is supported.\n * @type {boolean}\n */\nexport const isReadableStreamSupported = typeof globalThis.ReadableStream === 'function'\n\n/**\n * Indicates if WritableStream is supported.\n * @type {boolean}\n */\nexport const isWriteableStreamSupported = typeof globalThis.WritableStream === 'function'\n\n/**\n * Indicates if WebSocket is supported.\n * @type {boolean}\n */\nexport const isWebsocketSupported = typeof globalThis.WebSocket === 'function'\n\n/**\n * Indicates if WebRTC is supported.\n * @type {boolean}\n */\nexport const isWebRTCSupported = typeof globalThis.RTCPeerConnection === 'function'\n\n/**\n * Indicates if FormData is supported.\n * @type {boolean}\n */\nexport const isFormDataSupported = typeof globalThis.FormData === 'function'\n\n/**\n * Indicates if the code is running in a Node.js environment.\n * @type {boolean}\n */\nexport const isNode = typeof process !== 'undefined' && process.release.name === 'node'\n","import { isAbortControllerSupported } from './constant.js'\n\n/**\n * Returns the AbortController instance if supported, otherwise returns null.\n *\n * @returns {AbortController|null} The AbortController instance or null if not supported.\n */\nexport const getAbortController = () => (isAbortControllerSupported ? global.abortController : null)\n","/**\n * Calculates the exponential backoff time.\n *\n * @param {number} retryCount - The number of retries attempted.\n * @param {number} factor - The factor to multiply the backoff time.\n *\n * @returns {number} The calculated backoff time in milliseconds.\n */\nexport const defaultBackoff = (retryCount: number, factor: number) =>\n Math.pow(2, retryCount) * 1000 * factor // Exponential backoff, starting from 1 second\n\n/**\n * Generates a random delay time with a given factor.\n *\n * @param {number} factor - The factor to multiply the jitter time.\n *\n * @returns {number} The calculated jitter time in milliseconds.\n */\nexport const defaultJitter = (factor: number) => Math.random() * 1000 * factor // Randomized delay up to 1 second\n","import type { InitOptions } from '../types/init.js'\r\nimport type { RequestFunction } from '../types/request.js'\r\n\r\nimport {\r\n DEFAULT_BACKOFF_FACTOR,\r\n DEFAULT_JITTER_FACTOR,\r\n DEFAULT_MAX_TIMEOUT,\r\n isAbortControllerSupported,\r\n isNode,\r\n isReadableStreamSupported,\r\n isWebRTCSupported,\r\n isWebsocketSupported,\r\n isWriteableStreamSupported,\r\n} from './constant.js'\r\n\r\nimport { appendParams } from './append-params.js'\r\nimport { createHTTPError } from './create-http-error.js'\r\nimport { defaultBackoff, defaultJitter } from './default-retries.js'\r\n\r\n/**\r\n * Creates and sends an HTTP request.\r\n *\r\n * @param {string} url - The URL to send the request to.\r\n * @param {object} options - The options for the request, including method, headers, etc.\r\n * @param {object} data - The data to be sent with the request.\r\n * @param {InitOptions} initOptions - Initialization options including baseUrl, hooks, etc.\r\n *\r\n * @returns {Promise<[Error | null, any]>} A promise that resolves with an array containing an error (if any) and the response data.\r\n *\r\n * @throws {Error} If the request fails and `throwOnError` is true.\r\n */\r\nexport const createRequest: RequestFunction = async (\r\n url = '',\r\n options = {},\r\n data,\r\n { baseUrl, hooks, debug, throwOnError }: InitOptions = Object.create(null)\r\n): Promise<[Error | null, null]> => {\r\n const {\r\n method = 'GET',\r\n retries = 0,\r\n backoff = defaultBackoff,\r\n jitter = false,\r\n jitterFactor = DEFAULT_JITTER_FACTOR,\r\n backoffFactor = DEFAULT_BACKOFF_FACTOR,\r\n timeout = DEFAULT_MAX_TIMEOUT,\r\n retryOnTimeout = false,\r\n params,\r\n headers = {},\r\n signal,\r\n ...otherOptions\r\n } = options\r\n\r\n try {\r\n // Execute pre-request hook\r\n if (hooks?.preRequest) {\r\n hooks.preRequest(url, options)\r\n }\r\n\r\n const fullUrl = `${baseUrl}${url}`\r\n\r\n const reqHeaders = new Headers(headers)\r\n\r\n // Automatically detect and add Content-Length based on payload length\r\n const textEncoder = new TextEncoder()\r\n if (!reqHeaders.get('Content-Length') && data) {\r\n if (typeof data === 'string') {\r\n reqHeaders.set('Content-Length', String(textEncoder.encode(data).length))\r\n } else if (reqHeaders.get('Content-Length')?.includes('application/json')) {\r\n reqHeaders.set('Content-Length', String(textEncoder.encode(JSON.stringify(data)).length))\r\n }\r\n }\r\n\r\n // Set default Content-Type to application/json if not provided\r\n if (!reqHeaders.get('Content-Type') && data && typeof data === 'object') {\r\n if (!(((data as { body: FormData })?.body || data) instanceof FormData)) {\r\n reqHeaders.set('Content-Type', 'application/json')\r\n }\r\n }\r\n\r\n // Execute pre-timeout hook\r\n if (hooks?.preTimeout) {\r\n hooks.preTimeout(url, options)\r\n }\r\n\r\n if (isAbortControllerSupported) {\r\n // Expose the AbortController instance\r\n global.abortController = new AbortController()\r\n\r\n // Use the external AbortController instance\r\n global.abortSignal = signal ? signal : global.abortController.signal\r\n }\r\n\r\n const timeoutId =\r\n timeout && isAbortControllerSupported\r\n ? setTimeout(() => {\r\n global.abortController.abort()\r\n\r\n // Execute post-timeout hook\r\n if (hooks?.postTimeout) {\r\n hooks.postTimeout(url, options)\r\n }\r\n }, timeout)\r\n : undefined\r\n\r\n // Append params to the URL\r\n const urlWithParams = params ? appendParams(fullUrl, params) : fullUrl\r\n\r\n if (isReadableStreamSupported && !isWriteableStreamSupported && isNode) {\r\n // @ts-expect-error - Duplex types is not supported\r\n otherOptions.duplex = 'half'\r\n }\r\n if (!isReadableStreamSupported && isWriteableStreamSupported && isNode) {\r\n // @ts-expect-error - Duplex types is not supported\r\n otherOptions.duplex = 'half'\r\n }\r\n if (isReadableStreamSupported && isWriteableStreamSupported && isNode) {\r\n // @ts-expect-error - Duplex types is not supported\r\n otherOptions.duplex = 'half'\r\n }\r\n // WebRTC is supported, allowing for full duplex communication.\r\n if (isWebRTCSupported && isNode) {\r\n // @ts-expect-error - Duplex types is not supported\r\n otherOptions.duplex = 'half'\r\n }\r\n // WebSockets are supported, and thus full duplex communication is possible.\r\n if (isWebsocketSupported && isNode) {\r\n // @ts-expect-error - Duplex types is not supported\r\n otherOptions.duplex = 'half'\r\n }\r\n\r\n const requestBody =\r\n options.body instanceof FormData\r\n ? options.body\r\n : Object.keys(data as { [key: string]: unknown }).length !== 0\r\n ? JSON.stringify(data)\r\n : undefined\r\n\r\n const requestOptions = {\r\n method,\r\n signal: isAbortControllerSupported ? global.abortSignal : null,\r\n headers: reqHeaders,\r\n ...otherOptions,\r\n body: requestBody,\r\n }\r\n\r\n if (requestBody instanceof FormData) {\r\n requestOptions.headers.delete('Content-Type')\r\n }\r\n\r\n const responsePromise = fetch(urlWithParams, requestOptions)\r\n\r\n clearTimeout(timeoutId)\r\n\r\n const response = await responsePromise\r\n\r\n const contentType = response.headers.get('content-type')\r\n\r\n const responseData =\r\n contentType && contentType.includes('application/json')\r\n ? await response.json()\r\n : await response.text()\r\n\r\n if (!response.ok) {\r\n throw createHTTPError(response, responseData)\r\n }\r\n\r\n // Execute post-request hook\r\n if (hooks?.postRequest) {\r\n hooks.postRequest(url, options, data, [null, responseData])\r\n }\r\n\r\n if (throwOnError) {\r\n return responseData\r\n }\r\n\r\n return [null, responseData]\r\n } catch (error) {\r\n // Execute post-request hook for errors\r\n if (hooks?.postRequest) {\r\n if (error instanceof Error) {\r\n hooks.postRequest(url, options, data, [error, null])\r\n }\r\n }\r\n\r\n if (error instanceof Error) {\r\n if (error.name === 'AbortError') {\r\n console.error('Request aborted:', error)\r\n } else if (retryOnTimeout && error.name === 'TimeoutError' && retries && retries > 0) {\r\n const delay =\r\n jitter && jitterFactor\r\n ? defaultJitter(jitterFactor)\r\n : backoff(retries, backoffFactor ? backoffFactor : DEFAULT_BACKOFF_FACTOR)\r\n if (debug) {\r\n console.warn(\r\n `Request timed out. Retrying in ${delay}ms... (Remaining retries: ${retries})`\r\n )\r\n }\r\n // Execute pre-retry hook\r\n if (hooks?.preRetry) {\r\n hooks.preRetry(url, options, retries, retries)\r\n }\r\n await new Promise((resolve) => setTimeout(resolve, delay))\r\n const [retryErr, retryData] = await createRequest(\r\n url,\r\n { ...options, retries: retries - 1 },\r\n data\r\n )\r\n // Execute post-retry hook\r\n if (hooks?.postRetry) {\r\n hooks.postRetry(url, options, data, [retryErr, retryData], retries, retries - 1)\r\n }\r\n\r\n if (throwOnError) {\r\n throw retryErr\r\n }\r\n\r\n return [retryErr, retryData]\r\n } else if (options.retries && options.retries > 0) {\r\n const delay =\r\n options.jitter && options.jitterFactor\r\n ? defaultJitter(options.jitterFactor)\r\n : backoff(\r\n options.retries,\r\n options.backoffFactor ? options.backoffFactor : DEFAULT_BACKOFF_FACTOR\r\n )\r\n if (debug) {\r\n console.warn(\r\n `Request failed. Retrying in ${delay}ms... (Remaining retries: ${options.retries})`\r\n )\r\n }\r\n // Execute pre-retry hook\r\n if (hooks?.preRetry) {\r\n hooks.preRetry(url, options, options.retries, options.retries)\r\n }\r\n await new Promise((resolve) => setTimeout(resolve, delay))\r\n const [retryErr, retryData] = await createRequest(\r\n url,\r\n { ...options, retries: options.retries - 1 },\r\n data\r\n )\r\n // Execute post-retry hook\r\n if (hooks?.postRetry) {\r\n hooks.postRetry(\r\n url,\r\n options,\r\n data,\r\n [retryErr, retryData],\r\n options.retries,\r\n options.retries - 1\r\n )\r\n }\r\n\r\n if (throwOnError) {\r\n throw retryErr\r\n }\r\n\r\n return [retryErr, retryData]\r\n } else {\r\n if (throwOnError) {\r\n throw error\r\n }\r\n\r\n return [error, null]\r\n }\r\n }\r\n\r\n if (throwOnError) {\r\n throw error\r\n }\r\n\r\n return [error as Error, null]\r\n }\r\n}\r\n","/**\n * Appends query parameters to a given URL.\n *\n * @param {string} url - The base URL to which the parameters will be appended.\n * @param {Record} [params] - An optional object containing the query parameters as key-value pairs.\n *\n * @returns {string} The URL with the appended query parameters.\n */\nexport const appendParams = (url: string, params?: Record): string => {\n if (!params) {\n return url\n }\n\n const urlWithParams = new URL(url)\n Object.entries(params).forEach(([key, value]) =>\n urlWithParams.searchParams.append(key, String(value))\n )\n\n return urlWithParams.toString()\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Creates an HTTP error object based on the response and response data.\n *\n * @param {Response} response - The Response object from the fetch request.\n * @param {Response} responseData - The data returned in the response.\n *\n * @returns {Error} An Error object with additional properties for response and responseData.\n */\nexport function createHTTPError(response: Response, responseData: Response) {\n const code = response.status || response.status === 0 ? response.status : ''\n const title = response.statusText || ''\n const status = `${code} ${title}`.trim()\n const reason = status ? `status code ${status}` : 'an unknown error'\n const error = new Error(reason)\n\n error.name = 'HTTPError'\n ;(error as any).response = response\n ;(error as any).data = responseData\n\n return error\n}\n","import type { RequestMethod, RequestOptions } from '../types/request.js'\nimport type { InitOptions } from '../types/init.js'\n\nimport { createRequest } from './create-request.js'\n\n/**\n * Creates and sends an HTTP request using the specified method.\n *\n * @param {string} url - The URL to send the request to.\n * @param {RequestMethod} [method='GET'] - The HTTP method to use for the request.\n * @param {object} [options=Object.create(null)] - The options for the request, including headers, retries, etc.\n * @param {object} [data=Object.create(null)] - The data to be sent with the request.\n * @param {InitOptions} [initOptions] - Initialization options including baseUrl, hooks, etc.\n *\n * @returns {Promise<[Error | null, any]>} A promise that resolves with an array containing an error (if any) and the response data.\n */\nexport const createHTTPMethod = (\n url: string,\n method: RequestMethod = 'GET',\n options: RequestOptions = Object.create(null),\n data: { [key: string]: unknown } = Object.create(null),\n initOptions?: InitOptions\n) => {\n if (options.initOptions) {\n initOptions = options.initOptions\n }\n\n return createRequest(url, { method, ...options }, data, initOptions)\n}\n","import type { InitOptions } from './types/init.js'\r\nimport type { HttpRequestFunctions } from './types/request.js'\r\n\r\nimport { getAbortController } from './utils/get-abort-controller.js'\r\nimport { createHTTPMethod } from './utils/create-http-method.js'\r\n\r\n/**\r\n * Initializes the HTTP request functions with a base URL and options.\r\n *\r\n * @param {string} [baseUrl=''] - The base URL for all requests.\r\n * @param {InitOptions} [initOptions=Object.create(null)] - Initialization options.\r\n *\r\n * @returns {HttpRequestFunctions} An object containing HTTP request functions.\r\n *\r\n * @throws {Error} If `fetch` is not available in the environment.\r\n */\r\nexport function init(\r\n baseUrl: string = '',\r\n initOptions: InitOptions = Object.create(null)\r\n): HttpRequestFunctions {\r\n // Check if fetch is available\r\n if (typeof fetch === 'undefined') {\r\n throw new Error('This library is intended for use in the browser environment only.')\r\n }\r\n\r\n // Override initOptions baseUrl if baseUrl exists\r\n if (baseUrl) {\r\n initOptions.baseUrl = baseUrl\r\n }\r\n\r\n return {\r\n get: (url, options, data) => createHTTPMethod(url, 'GET', options, data, initOptions),\r\n post: (url, options, data) => createHTTPMethod(url, 'POST', options, data, initOptions),\r\n put: (url, options, data) => createHTTPMethod(url, 'PUT', options, data, initOptions),\r\n delete: (url, options, data) => createHTTPMethod(url, 'DELETE', options, data, initOptions),\r\n patch: (url, options, data) => createHTTPMethod(url, 'PATCH', options, data, initOptions),\r\n head: (url, options, data) => createHTTPMethod(url, 'HEAD', options, data, initOptions),\r\n options: (url, options, data) => createHTTPMethod(url, 'OPTIONS', options, data, initOptions),\r\n getAbortController,\r\n }\r\n}\r\n\r\nexport default { init }\r\n"],"names":["root","factory","exports","module","require","define","amd","self","__WEBPACK_EXTERNAL_MODULE__324__","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__","n","getter","__esModule","d","a","definition","key","o","Object","defineProperty","enumerable","get","g","globalThis","this","Function","e","window","obj","prop","prototype","hasOwnProperty","call","r","Symbol","toStringTag","value","DEFAULT_MAX_TIMEOUT","DEFAULT_BACKOFF_FACTOR","DEFAULT_JITTER_FACTOR","isAbortControllerSupported","AbortController","isReadableStreamSupported","ReadableStream","isWriteableStreamSupported","WritableStream","isWebsocketSupported","WebSocket","isWebRTCSupported","RTCPeerConnection","isNode","FormData","name","getAbortController","abortController","defaultBackoff","retryCount","factor","Math","pow","defaultJitter","random","createRequest","url","options","data","baseUrl","hooks","debug","throwOnError","create","method","retries","backoff","jitter","jitterFactor","backoffFactor","timeout","retryOnTimeout","params","headers","signal","otherOptions","preRequest","fullUrl","reqHeaders","Headers","textEncoder","TextEncoder","set","String","encode","length","includes","JSON","stringify","body","preTimeout","abortSignal","timeoutId","setTimeout","abort","postTimeout","urlWithParams","URL","entries","forEach","searchParams","append","toString","appendParams","duplex","requestBody","keys","requestOptions","delete","responsePromise","fetch","clearTimeout","response","contentType","responseData","json","text","ok","status","statusText","trim","error","Error","createHTTPError","postRequest","delay","console","warn","preRetry","Promise","resolve","retryErr","retryData","postRetry","createHTTPMethod","initOptions","init","post","put","patch","head"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"hyperfetch-browser.min.js","mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,EAAQG,QAAQ,OACR,mBAAXC,QAAyBA,OAAOC,IAC9CD,OAAO,OAAQ,CAAC,MAAOJ,GACG,iBAAZC,QACdA,QAAc,KAAID,EAAQG,QAAQ,OAElCJ,EAAW,KAAIC,EAAQD,EAAK,MAC7B,CATD,CASGO,MAAOC,G,kCCTVL,EAAOD,QAAUM,C,GCCbC,EAA2B,CAAC,EAGhC,SAASC,EAAoBC,GAE5B,IAAIC,EAAeH,EAAyBE,GAC5C,QAAqBE,IAAjBD,EACH,OAAOA,EAAaV,QAGrB,IAAIC,EAASM,EAAyBE,GAAY,CAGjDT,QAAS,CAAC,GAOX,OAHAY,EAAoBH,GAAUR,EAAQA,EAAOD,QAASQ,GAG/CP,EAAOD,OACf,CCrBAQ,EAAoBK,EAAKZ,IACxB,IAAIa,EAASb,GAAUA,EAAOc,WAC7B,IAAOd,EAAiB,QACxB,IAAM,EAEP,OADAO,EAAoBQ,EAAEF,EAAQ,CAAEG,EAAGH,IAC5BA,CAAM,ECLdN,EAAoBQ,EAAI,CAAChB,EAASkB,KACjC,IAAI,IAAIC,KAAOD,EACXV,EAAoBY,EAAEF,EAAYC,KAASX,EAAoBY,EAAEpB,EAASmB,IAC5EE,OAAOC,eAAetB,EAASmB,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,IAE1E,ECNDX,EAAoBiB,EAAI,WACvB,GAA0B,iBAAfC,WAAyB,OAAOA,WAC3C,IACC,OAAOC,MAAQ,IAAIC,SAAS,cAAb,EAChB,CAAE,MAAOC,GACR,GAAsB,iBAAXC,OAAqB,O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,EAGR,MAAO,CAACA,EAAgB,KAC1B,CACF,E,YA5OI,K,6QA4OH,EGhQYa,EAAmB,CAC9B9E,EACAQ,EAAwB,MACxBP,EAA0B9C,OAAOoD,OAAO,MACxCL,EAAmC/C,OAAOoD,OAAO,MACjDwE,KAEI9E,EAAQ8E,cACVA,EAAc9E,EAAQ8E,oBAGjB9E,EAAQ8E,YAERhF,EAAcC,EAAK,OAAF,QAAIQ,UAAWP,GAAWC,EAAM6E,ICbnD,SAASC,EACd7E,EAAkB,GAClB4E,EAA2B5H,OAAOoD,OAAO,OAGzC,GAAqB,oBAAV+C,MACT,MAAM,IAAIY,MAAM,qEAQlB,OAJI/D,IACF4E,EAAY5E,QAAUA,GAGjB,CACL7C,IAAK,CAAC0C,EAAKC,EAASC,IAAS4E,EAAiB9E,EAAK,MAAOC,EAASC,EAAM6E,GACzEE,KAAM,CAACjF,EAAKC,EAASC,IAAS4E,EAAiB9E,EAAK,OAAQC,EAASC,EAAM6E,GAC3EG,IAAK,CAAClF,EAAKC,EAASC,IAAS4E,EAAiB9E,EAAK,MAAOC,EAASC,EAAM6E,GACzE3B,OAAQ,CAACpD,EAAKC,EAASC,IAAS4E,EAAiB9E,EAAK,SAAUC,EAASC,EAAM6E,GAC/EI,MAAO,CAACnF,EAAKC,EAASC,IAAS4E,EAAiB9E,EAAK,QAASC,EAASC,EAAM6E,GAC7EK,KAAM,CAACpF,EAAKC,EAASC,IAAS4E,EAAiB9E,EAAK,OAAQC,EAASC,EAAM6E,GAC3E9E,QAAS,CAACD,EAAKC,EAASC,IAAS4E,EAAiB9E,EAAK,UAAWC,EAASC,EAAM6E,GACjFzF,mBAAkB,EAEtB,CAEA,SAAiB0F,Q","sources":["webpack://hypf/webpack/universalModuleDefinition","webpack://hypf/external umd \"{}\"","webpack://hypf/webpack/bootstrap","webpack://hypf/webpack/runtime/compat get default export","webpack://hypf/webpack/runtime/define property getters","webpack://hypf/webpack/runtime/global","webpack://hypf/webpack/runtime/hasOwnProperty shorthand","webpack://hypf/webpack/runtime/make namespace object","webpack://hypf/./src/utils/constant.ts","webpack://hypf/./src/utils/get-abort-controller.ts","webpack://hypf/./src/utils/default-retries.ts","webpack://hypf/./src/utils/create-request.ts","webpack://hypf/./src/utils/append-params.ts","webpack://hypf/./src/utils/create-http-error.ts","webpack://hypf/./src/utils/create-http-method.ts","webpack://hypf/./src/index.ts"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"{}\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"hypf\", [\"{}\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"hypf\"] = factory(require(\"{}\"));\n\telse\n\t\troot[\"hypf\"] = factory(root[\"{}\"]);\n})(self, (__WEBPACK_EXTERNAL_MODULE__324__) => {\nreturn ","module.exports = __WEBPACK_EXTERNAL_MODULE__324__;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","// disabled in webpack\nimport process from 'node:process'\n\n/**\n * Default maximum recommended timeout in milliseconds.\n * @type {number}\n */\nexport const DEFAULT_MAX_TIMEOUT = 2147483647\n\n/**\n * Default factor for exponential backoff.\n * @type {number}\n */\nexport const DEFAULT_BACKOFF_FACTOR = 0.3\n\n/**\n * Default factor for jitter in delay.\n * @type {number}\n */\nexport const DEFAULT_JITTER_FACTOR = 1\n\n/**\n * Indicates if AbortController is supported.\n * @type {boolean}\n */\nexport const isAbortControllerSupported = typeof globalThis.AbortController === 'function'\n\n/**\n * Indicates if ReadableStream is supported.\n * @type {boolean}\n */\nexport const isReadableStreamSupported = typeof globalThis.ReadableStream === 'function'\n\n/**\n * Indicates if WritableStream is supported.\n * @type {boolean}\n */\nexport const isWriteableStreamSupported = typeof globalThis.WritableStream === 'function'\n\n/**\n * Indicates if WebSocket is supported.\n * @type {boolean}\n */\nexport const isWebsocketSupported = typeof globalThis.WebSocket === 'function'\n\n/**\n * Indicates if WebRTC is supported.\n * @type {boolean}\n */\nexport const isWebRTCSupported = typeof globalThis.RTCPeerConnection === 'function'\n\n/**\n * Indicates if FormData is supported.\n * @type {boolean}\n */\nexport const isFormDataSupported = typeof globalThis.FormData === 'function'\n\n/**\n * Indicates if the code is running in a Node.js environment.\n * @type {boolean}\n */\nexport const isNode = typeof process !== 'undefined' && process.release.name === 'node'\n","import { isAbortControllerSupported } from './constant.js'\n\n/**\n * Returns the AbortController instance if supported, otherwise returns null.\n *\n * @returns {AbortController|null} The AbortController instance or null if not supported.\n */\nexport const getAbortController = () => (isAbortControllerSupported ? global.abortController : null)\n","/**\n * Calculates the exponential backoff time.\n *\n * @param {number} retryCount - The number of retries attempted.\n * @param {number} factor - The factor to multiply the backoff time.\n *\n * @returns {number} The calculated backoff time in milliseconds.\n */\nexport const defaultBackoff = (retryCount: number, factor: number) =>\n Math.pow(2, retryCount) * 1000 * factor // Exponential backoff, starting from 1 second\n\n/**\n * Generates a random delay time with a given factor.\n *\n * @param {number} factor - The factor to multiply the jitter time.\n *\n * @returns {number} The calculated jitter time in milliseconds.\n */\nexport const defaultJitter = (factor: number) => Math.random() * 1000 * factor // Randomized delay up to 1 second\n","import type { InitOptions } from '../types/init.js'\r\nimport type { RequestFunction } from '../types/request.js'\r\n\r\nimport {\r\n DEFAULT_BACKOFF_FACTOR,\r\n DEFAULT_JITTER_FACTOR,\r\n DEFAULT_MAX_TIMEOUT,\r\n isAbortControllerSupported,\r\n isNode,\r\n isReadableStreamSupported,\r\n isWebRTCSupported,\r\n isWebsocketSupported,\r\n isWriteableStreamSupported,\r\n} from './constant.js'\r\n\r\nimport { appendParams } from './append-params.js'\r\nimport { createHTTPError } from './create-http-error.js'\r\nimport { defaultBackoff, defaultJitter } from './default-retries.js'\r\n\r\n/**\r\n * Creates and sends an HTTP request.\r\n *\r\n * @param {string} url - The URL to send the request to.\r\n * @param {object} options - The options for the request, including method, headers, etc.\r\n * @param {object} data - The data to be sent with the request.\r\n * @param {InitOptions} initOptions - Initialization options including baseUrl, hooks, etc.\r\n *\r\n * @returns {Promise<[Error | null, any]>} A promise that resolves with an array containing an error (if any) and the response data.\r\n *\r\n * @throws {Error} If the request fails and `throwOnError` is true.\r\n */\r\nexport const createRequest: RequestFunction = async (\r\n url = '',\r\n options = {},\r\n data,\r\n { baseUrl, hooks, debug, throwOnError }: InitOptions = Object.create(null)\r\n) => {\r\n const {\r\n method = 'GET',\r\n retries = 0,\r\n backoff = defaultBackoff,\r\n jitter = false,\r\n jitterFactor = DEFAULT_JITTER_FACTOR,\r\n backoffFactor = DEFAULT_BACKOFF_FACTOR,\r\n timeout = DEFAULT_MAX_TIMEOUT,\r\n retryOnTimeout = false,\r\n params,\r\n headers = {},\r\n signal,\r\n ...otherOptions\r\n } = options\r\n\r\n try {\r\n // Execute pre-request hook\r\n if (hooks?.preRequest) {\r\n hooks.preRequest(url, options)\r\n }\r\n\r\n const fullUrl = `${baseUrl}${url}`\r\n\r\n const reqHeaders = new Headers(headers)\r\n\r\n // Automatically detect and add Content-Length based on payload length\r\n const textEncoder = new TextEncoder()\r\n if (!reqHeaders.get('Content-Length') && data) {\r\n if (typeof data === 'string') {\r\n reqHeaders.set('Content-Length', String(textEncoder.encode(data).length))\r\n } else if (reqHeaders.get('Content-Length')?.includes('application/json')) {\r\n reqHeaders.set('Content-Length', String(textEncoder.encode(JSON.stringify(data)).length))\r\n }\r\n }\r\n\r\n // Set default Content-Type to application/json if not provided\r\n if (!reqHeaders.get('Content-Type') && data && typeof data === 'object') {\r\n if (!(((data as { body: FormData })?.body || data) instanceof FormData)) {\r\n reqHeaders.set('Content-Type', 'application/json')\r\n }\r\n }\r\n\r\n // Execute pre-timeout hook\r\n if (hooks?.preTimeout) {\r\n hooks.preTimeout(url, options)\r\n }\r\n\r\n if (isAbortControllerSupported) {\r\n // Expose the AbortController instance\r\n global.abortController = new AbortController()\r\n\r\n // Use the external AbortController instance\r\n global.abortSignal = signal ? signal : global.abortController.signal\r\n }\r\n\r\n const timeoutId =\r\n timeout && isAbortControllerSupported\r\n ? setTimeout(() => {\r\n global.abortController.abort()\r\n\r\n // Execute post-timeout hook\r\n if (hooks?.postTimeout) {\r\n hooks.postTimeout(url, options)\r\n }\r\n }, timeout)\r\n : undefined\r\n\r\n // Append params to the URL\r\n const urlWithParams = params ? appendParams(fullUrl, params) : fullUrl\r\n\r\n if (isReadableStreamSupported && !isWriteableStreamSupported && isNode) {\r\n // @ts-expect-error - Duplex types is not supported\r\n otherOptions.duplex = 'half'\r\n }\r\n if (!isReadableStreamSupported && isWriteableStreamSupported && isNode) {\r\n // @ts-expect-error - Duplex types is not supported\r\n otherOptions.duplex = 'half'\r\n }\r\n if (isReadableStreamSupported && isWriteableStreamSupported && isNode) {\r\n // @ts-expect-error - Duplex types is not supported\r\n otherOptions.duplex = 'half'\r\n }\r\n // WebRTC is supported, allowing for full duplex communication.\r\n if (isWebRTCSupported && isNode) {\r\n // @ts-expect-error - Duplex types is not supported\r\n otherOptions.duplex = 'half'\r\n }\r\n // WebSockets are supported, and thus full duplex communication is possible.\r\n if (isWebsocketSupported && isNode) {\r\n // @ts-expect-error - Duplex types is not supported\r\n otherOptions.duplex = 'half'\r\n }\r\n\r\n const requestBody =\r\n options.body instanceof FormData\r\n ? options.body\r\n : Object.keys(data as { [key: string]: unknown }).length !== 0\r\n ? JSON.stringify(data)\r\n : undefined\r\n\r\n const requestOptions = {\r\n method,\r\n signal: isAbortControllerSupported ? global.abortSignal : null,\r\n headers: reqHeaders,\r\n ...otherOptions,\r\n body: requestBody,\r\n }\r\n\r\n if (requestBody instanceof FormData) {\r\n requestOptions.headers.delete('Content-Type')\r\n }\r\n\r\n const responsePromise = fetch(urlWithParams, requestOptions)\r\n\r\n clearTimeout(timeoutId)\r\n\r\n const response = await responsePromise\r\n\r\n const contentType = response.headers.get('content-type')\r\n\r\n const responseData =\r\n contentType && contentType.includes('application/json')\r\n ? await response.json()\r\n : await response.text()\r\n\r\n if (!response.ok) {\r\n throw createHTTPError(response, responseData)\r\n }\r\n\r\n // Execute post-request hook\r\n if (hooks?.postRequest) {\r\n hooks.postRequest(url, options, data, [null, responseData])\r\n }\r\n\r\n if (throwOnError) {\r\n return responseData\r\n }\r\n\r\n return [null, responseData]\r\n } catch (error) {\r\n // Execute post-request hook for errors\r\n if (hooks?.postRequest) {\r\n if (error instanceof Error) {\r\n hooks.postRequest(url, options, data, [error, null])\r\n }\r\n }\r\n\r\n if (error instanceof Error) {\r\n if (error.name === 'AbortError') {\r\n console.error('Request aborted:', error)\r\n } else if (retryOnTimeout && error.name === 'TimeoutError' && retries && retries > 0) {\r\n const delay =\r\n jitter && jitterFactor\r\n ? defaultJitter(jitterFactor)\r\n : backoff(retries, backoffFactor ? backoffFactor : DEFAULT_BACKOFF_FACTOR)\r\n if (debug) {\r\n console.warn(\r\n `Request timed out. Retrying in ${delay}ms... (Remaining retries: ${retries})`\r\n )\r\n }\r\n // Execute pre-retry hook\r\n if (hooks?.preRetry) {\r\n hooks.preRetry(url, options, retries, retries)\r\n }\r\n await new Promise((resolve) => setTimeout(resolve, delay))\r\n const [retryErr, retryData] = await createRequest(\r\n url,\r\n { ...options, retries: retries - 1 },\r\n data\r\n )\r\n // Execute post-retry hook\r\n if (hooks?.postRetry) {\r\n hooks.postRetry(url, options, data, [retryErr, retryData], retries, retries - 1)\r\n }\r\n\r\n if (throwOnError) {\r\n throw retryErr\r\n }\r\n\r\n return [retryErr, retryData]\r\n } else if (options.retries && options.retries > 0) {\r\n const delay =\r\n options.jitter && options.jitterFactor\r\n ? defaultJitter(options.jitterFactor)\r\n : backoff(\r\n options.retries,\r\n options.backoffFactor ? options.backoffFactor : DEFAULT_BACKOFF_FACTOR\r\n )\r\n if (debug) {\r\n console.warn(\r\n `Request failed. Retrying in ${delay}ms... (Remaining retries: ${options.retries})`\r\n )\r\n }\r\n // Execute pre-retry hook\r\n if (hooks?.preRetry) {\r\n hooks.preRetry(url, options, options.retries, options.retries)\r\n }\r\n await new Promise((resolve) => setTimeout(resolve, delay))\r\n const [retryErr, retryData] = await createRequest(\r\n url,\r\n { ...options, retries: options.retries - 1 },\r\n data\r\n )\r\n // Execute post-retry hook\r\n if (hooks?.postRetry) {\r\n hooks.postRetry(\r\n url,\r\n options,\r\n data,\r\n [retryErr, retryData],\r\n options.retries,\r\n options.retries - 1\r\n )\r\n }\r\n\r\n if (throwOnError) {\r\n throw retryErr\r\n }\r\n\r\n return [retryErr, retryData]\r\n } else {\r\n if (throwOnError) {\r\n throw error\r\n }\r\n\r\n return [error, null]\r\n }\r\n }\r\n\r\n if (throwOnError) {\r\n throw error\r\n }\r\n\r\n return [error as Error, null]\r\n }\r\n}\r\n","/**\n * Appends query parameters to a given URL.\n *\n * @param {string} url - The base URL to which the parameters will be appended.\n * @param {Record} [params] - An optional object containing the query parameters as key-value pairs.\n *\n * @returns {string} The URL with the appended query parameters.\n */\nexport const appendParams = (url: string, params?: Record): string => {\n if (!params) {\n return url\n }\n\n const urlWithParams = new URL(url)\n Object.entries(params).forEach(([key, value]) =>\n urlWithParams.searchParams.append(key, String(value))\n )\n\n return urlWithParams.toString()\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Creates an HTTP error object based on the response and response data.\n *\n * @param {Response} response - The Response object from the fetch request.\n * @param {Response} responseData - The data returned in the response.\n *\n * @returns {Error} An Error object with additional properties for response and responseData.\n */\nexport function createHTTPError(response: Response, responseData: Response) {\n const code = response.status || response.status === 0 ? response.status : ''\n const title = response.statusText || ''\n const status = `${code} ${title}`.trim()\n const reason = status ? `status code ${status}` : 'an unknown error'\n const error = new Error(reason)\n\n error.name = 'HTTPError'\n ;(error as any).response = response\n ;(error as any).data = responseData\n\n return error\n}\n","import type { RequestMethod, RequestOptions } from '../types/request.js'\nimport type { InitOptions } from '../types/init.js'\n\nimport { createRequest } from './create-request.js'\n\n/**\n * Creates and sends an HTTP request using the specified method.\n *\n * @param {string} url - The URL to send the request to.\n * @param {RequestMethod} [method='GET'] - The HTTP method to use for the request.\n * @param {object} [options=Object.create(null)] - The options for the request, including headers, retries, etc.\n * @param {object} [data=Object.create(null)] - The data to be sent with the request.\n * @param {InitOptions} [initOptions] - Initialization options including baseUrl, hooks, etc.\n *\n * @returns {Promise<[Error | null, any]>} A promise that resolves with an array containing an error (if any) and the response data.\n */\nexport const createHTTPMethod = (\n url: string,\n method: RequestMethod = 'GET',\n options: RequestOptions = Object.create(null),\n data: { [key: string]: unknown } = Object.create(null),\n initOptions?: InitOptions\n) => {\n if (options.initOptions) {\n initOptions = options.initOptions\n }\n\n delete options.initOptions\n\n return createRequest(url, { method, ...options }, data, initOptions)\n}\n","import type { InitOptions } from './types/init.js'\r\nimport type { HttpRequestFunctions } from './types/request.js'\r\n\r\nimport { getAbortController } from './utils/get-abort-controller.js'\r\nimport { createHTTPMethod } from './utils/create-http-method.js'\r\n\r\n/**\r\n * Initializes the HTTP request functions with a base URL and options.\r\n *\r\n * @param {string} [baseUrl=''] - The base URL for all requests.\r\n * @param {InitOptions} [initOptions=Object.create(null)] - Initialization options.\r\n *\r\n * @returns {HttpRequestFunctions} An object containing HTTP request functions.\r\n *\r\n * @throws {Error} If `fetch` is not available in the environment.\r\n */\r\nexport function init(\r\n baseUrl: string = '',\r\n initOptions: InitOptions = Object.create(null)\r\n): HttpRequestFunctions {\r\n // Check if fetch is available\r\n if (typeof fetch === 'undefined') {\r\n throw new Error('This library is intended for use in the browser environment only.')\r\n }\r\n\r\n // Override initOptions baseUrl if baseUrl exists\r\n if (baseUrl) {\r\n initOptions.baseUrl = baseUrl\r\n }\r\n\r\n return {\r\n get: (url, options, data) => createHTTPMethod(url, 'GET', options, data, initOptions),\r\n post: (url, options, data) => createHTTPMethod(url, 'POST', options, data, initOptions),\r\n put: (url, options, data) => createHTTPMethod(url, 'PUT', options, data, initOptions),\r\n delete: (url, options, data) => createHTTPMethod(url, 'DELETE', options, data, initOptions),\r\n patch: (url, options, data) => createHTTPMethod(url, 'PATCH', options, data, initOptions),\r\n head: (url, options, data) => createHTTPMethod(url, 'HEAD', options, data, initOptions),\r\n options: (url, options, data) => createHTTPMethod(url, 'OPTIONS', options, data, initOptions),\r\n getAbortController,\r\n }\r\n}\r\n\r\nexport default { init }\r\n"],"names":["root","factory","exports","module","require","define","amd","self","__WEBPACK_EXTERNAL_MODULE__324__","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__","n","getter","__esModule","d","a","definition","key","o","Object","defineProperty","enumerable","get","g","globalThis","this","Function","e","window","obj","prop","prototype","hasOwnProperty","call","r","Symbol","toStringTag","value","DEFAULT_MAX_TIMEOUT","DEFAULT_BACKOFF_FACTOR","DEFAULT_JITTER_FACTOR","isAbortControllerSupported","AbortController","isReadableStreamSupported","ReadableStream","isWriteableStreamSupported","WritableStream","isWebsocketSupported","WebSocket","isWebRTCSupported","RTCPeerConnection","isNode","FormData","name","getAbortController","abortController","defaultBackoff","retryCount","factor","Math","pow","defaultJitter","random","createRequest","url","options","data","baseUrl","hooks","debug","throwOnError","create","method","retries","backoff","jitter","jitterFactor","backoffFactor","timeout","retryOnTimeout","params","headers","signal","otherOptions","preRequest","fullUrl","reqHeaders","Headers","textEncoder","TextEncoder","set","String","encode","length","includes","JSON","stringify","body","preTimeout","abortSignal","timeoutId","setTimeout","abort","postTimeout","urlWithParams","URL","entries","forEach","searchParams","append","toString","appendParams","duplex","requestBody","keys","requestOptions","delete","responsePromise","fetch","clearTimeout","response","contentType","responseData","json","text","ok","status","statusText","trim","error","Error","createHTTPError","postRequest","delay","console","warn","preRetry","Promise","resolve","retryErr","retryData","postRetry","createHTTPMethod","initOptions","init","post","put","patch","head"],"sourceRoot":""} \ No newline at end of file diff --git a/src/types/request.ts b/src/types/request.ts index 22ffdc0..d06bdc2 100644 --- a/src/types/request.ts +++ b/src/types/request.ts @@ -17,48 +17,57 @@ export interface RequestOptions extends RequestInit { initOptions?: InitOptions } -export type RequestFunction = ( - url: string, - options?: RequestOptions, - data?: { [key: string]: unknown }, - initOptions?: InitOptions -) => Promise<[Error | null, null]> +export type RequestFunction = { + ( + url: string, + options?: RequestOptions & { initOptions: { throwOnError: true } }, + data?: { [key: string]: unknown }, + initOptions?: InitOptions & { throwOnError: true } + ): Promise -export interface HttpRequestFunctions { - get( + ( url: string, - options?: RequestOptions, - data?: { [key: string]: unknown } + options?: RequestOptions & { initOptions: { throwOnError: false } }, + data?: { [key: string]: unknown }, + initOptions?: InitOptions & { throwOnError: false } ): Promise<[Error | null, T | null]> - post( - url: string, - options?: RequestOptions, - data?: { [key: string]: unknown } - ): Promise<[Error | null, T | null]> - put( + + ( url: string, - options?: RequestOptions, - data?: { [key: string]: unknown } + options?: RequestOptions & { initOptions?: { throwOnError?: boolean } }, + data?: { [key: string]: unknown }, + initOptions?: InitOptions ): Promise<[Error | null, T | null]> - delete( - url: string, - options?: RequestOptions, - data?: { [key: string]: unknown } - ): Promise<[Error | null, T | null]> - patch( +} + +export type HttpRequestFunction = { + ( url: string, - options?: RequestOptions, + options?: RequestOptions & { initOptions: { throwOnError: true } }, data?: { [key: string]: unknown } - ): Promise<[Error | null, T | null]> - head( + ): Promise + + ( url: string, - options?: RequestOptions, + options?: RequestOptions & { initOptions: { throwOnError: false } }, data?: { [key: string]: unknown } ): Promise<[Error | null, T | null]> - options( + + ( url: string, - options?: RequestOptions, + options?: RequestOptions & { initOptions?: { throwOnError?: boolean } }, data?: { [key: string]: unknown } ): Promise<[Error | null, T | null]> +} + +export interface HttpRequestFunctions { + get: HttpRequestFunction + post: HttpRequestFunction + put: HttpRequestFunction + delete: HttpRequestFunction + patch: HttpRequestFunction + head: HttpRequestFunction + options: HttpRequestFunction + getAbortController(): AbortController | null } diff --git a/src/utils/create-http-method.ts b/src/utils/create-http-method.ts index 4310c8c..da2942a 100644 --- a/src/utils/create-http-method.ts +++ b/src/utils/create-http-method.ts @@ -25,5 +25,7 @@ export const createHTTPMethod = ( initOptions = options.initOptions } + delete options.initOptions + return createRequest(url, { method, ...options }, data, initOptions) } diff --git a/src/utils/create-request.ts b/src/utils/create-request.ts index 8d5646f..ef1b942 100644 --- a/src/utils/create-request.ts +++ b/src/utils/create-request.ts @@ -34,7 +34,7 @@ export const createRequest: RequestFunction = async ( options = {}, data, { baseUrl, hooks, debug, throwOnError }: InitOptions = Object.create(null) -): Promise<[Error | null, null]> => { +) => { const { method = 'GET', retries = 0,