From f091f5dbd7438d116db52c12e232a76cd9085730 Mon Sep 17 00:00:00 2001 From: fzn0x Date: Mon, 15 Jul 2024 10:11:55 +0700 Subject: [PATCH] fix: remove undefined string from fullUrl --- browser/hyperfetch-browser.min.js | 2 +- browser/hyperfetch-browser.min.js.map | 2 +- src/types/request.ts | 23 ++++++++++++++++++++++- src/utils/create-http-method.test.ts | 2 +- src/utils/create-http-method.ts | 2 +- src/utils/create-request.test.ts | 18 ++++++++++++++++++ src/utils/create-request.ts | 2 +- 7 files changed, 45 insertions(+), 6 deletions(-) diff --git a/browser/hyperfetch-browser.min.js b/browser/hyperfetch-browser.min.js index 4d63fc8..ad1711c 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}},r={};function o(e){var n=r[e];if(void 0!==n)return n.exports;var i=r[e]={exports:{}};return t[e](i,i.exports,o),i.exports}o.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},o.d=(e,t)=>{for(var r in t)o.o(t,r)&&!o.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},o.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};o.r(n),o.d(n,{default:()=>O,init:()=>j});var i=o(324),s=o.n(i);const a=2147483647,l="function"==typeof globalThis.AbortController,c="function"==typeof globalThis.ReadableStream,u="function"==typeof globalThis.WritableStream,f="function"==typeof globalThis.WebSocket,d="function"==typeof globalThis.RTCPeerConnection,p=(globalThis.FormData,void 0!==s()&&"node"===s().release.name),b=()=>l?o.g.abortController:null;function y(e,t,r){try{const o=e.statusText;r||(r=e.status||0===e.status?String(e.status):"Unknown Status Code");const n=`${r} ${o}`.trim(),i=n?`Status code: ${n}`:"An unknown error occurred",s=new Error(i);return s.name="HTTPError",s.code=r,s.request=t,s.response=e,s.isHypfError=!0,Object.setPrototypeOf(s,Object.getPrototypeOf(new Error)),s}catch(e){const t=new Error("An error occurred while creating the HTTP error object");return t.name="HTTPErrorCreationFailure",t.originalError=e,t.isHypfError=!0,t}}const h=(e,t)=>1e3*Math.pow(2,e)*t,g=e=>1e3*Math.random()*e;const m=(e="",t={backoff:h,jitter:!1,jitterFactor:1,backoffFactor:.3,timeout:a,method:"GET",retries:0,retryOnTimeout:!1,headers:{}},r,{baseUrl:n,hooks:i,debug:s,throwOnError:b}=Object.create(null))=>{return T=void 0,j=void 0,v=function*(){var T;try{(null==i?void 0:i.preRequest)&&i.preRequest(e,t),(null==i?void 0:i.preTimeout)&&i.preTimeout(e,t);const{method:s="GET",timeout:h=a,params:g,headers:m={},signal:j}=t,O=function(e,t){var r={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(r[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n{if(!t)return e;const r=new URL(e);return Object.entries(t).forEach((([e,t])=>r.searchParams.append(e,String(t)))),r.toString()})(v,g):v;c&&!u&&p&&(O.duplex="half"),!c&&u&&p&&(O.duplex="half"),c&&u&&p&&(O.duplex="half"),d&&p&&(O.duplex="half"),f&&p&&(O.duplex="half");const P=t.body instanceof FormData?t.body:0!==Object.keys(r).length?JSON.stringify(r):void 0,S=Object.assign(Object.assign({method:s,signal:l?o.g.abortSignal:null,headers:w},O),{body:P});P instanceof FormData&&S.headers.delete("Content-Type");const x=h&&l?setTimeout((()=>{o.g.abortController.abort(),(null==i?void 0:i.postTimeout)&&i.postTimeout(e,t)}),h):void 0,C=fetch(R,S);clearTimeout(x);const F=yield C,k=F.headers.get("content-type"),q=k&&k.includes("application/json")?yield F.json():yield F.text();if(!F.ok)throw y(F);return(null==i?void 0:i.postRequest)&&i.postRequest(e,t,r,[null,q]),b?q:[null,q]}catch(o){if((null==i?void 0:i.postRequest)&&o instanceof Error&&i.postRequest(e,t,r,[o,null]),o instanceof Error){if("AbortError"!==o.name){if(t.retryOnTimeout&&"TimeoutError"===o.name&&t.retries&&t.retries>0){const o=t.jitter&&t.jitterFactor?g(t.jitterFactor):t.backoff?h(t.retries,t.backoffFactor?t.backoffFactor:.3):0;s&&console.warn(`Request timed out. Retrying in ${o}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,o)));const[n,a]=yield m(e,Object.assign(Object.assign({},t),{retries:t.retries-1}),r);if((null==i?void 0:i.postRetry)&&i.postRetry(e,t,r,[n,a],t.retries,t.retries-1),b)throw n;return[n,a]}if(t.retries&&t.retries>0){const o=t.jitter&&t.jitterFactor?g(t.jitterFactor):t.backoff?h(t.retries,t.backoffFactor?t.backoffFactor:.3):0;s&&console.warn(`Request failed. Retrying in ${o}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,o)));const[n,a]=yield m(e,Object.assign(Object.assign({},t),{retries:t.retries-1}),r);if((null==i?void 0:i.postRetry)&&i.postRetry(e,t,r,[n,a],t.retries,t.retries-1),b)throw n;return[n,a]}if(b)throw o;return[o,null]}console.error("Request aborted:",o)}if(b)throw o;return[o,null]}},new((O=void 0)||(O=Promise))((function(e,t){function r(e){try{n(v.next(e))}catch(e){t(e)}}function o(e){try{n(v.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(r,o)}n((v=v.apply(T,j||[])).next())}));var T,j,O,v},T=(e,t="GET",r=Object.create(null),o=Object.create(null),n)=>(r.initOptions&&(n=r.initOptions),delete r.initOptions,m(e,Object.assign({method:t},r),o,n));function j(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,r,o)=>T(e,"GET",r,o,t),post:(e,r,o)=>T(e,"POST",r,o,t),put:(e,r,o)=>T(e,"PUT",r,o,t),delete:(e,r,o)=>T(e,"DELETE",r,o,t),patch:(e,r,o)=>T(e,"PATCH",r,o,t),head:(e,r,o)=>T(e,"HEAD",r,o,t),options:(e,r,o)=>T(e,"OPTIONS",r,o,t),createHTTPMethod:T,createHTTPError:y,getAbortController:b}}const O={init:j};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}},r={};function o(e){var n=r[e];if(void 0!==n)return n.exports;var i=r[e]={exports:{}};return t[e](i,i.exports,o),i.exports}o.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},o.d=(e,t)=>{for(var r in t)o.o(t,r)&&!o.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},o.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};o.r(n),o.d(n,{default:()=>O,init:()=>j});var i=o(324),s=o.n(i);const a=2147483647,l="function"==typeof globalThis.AbortController,c="function"==typeof globalThis.ReadableStream,u="function"==typeof globalThis.WritableStream,f="function"==typeof globalThis.WebSocket,d="function"==typeof globalThis.RTCPeerConnection,p=(globalThis.FormData,void 0!==s()&&"node"===s().release.name),b=()=>l?o.g.abortController:null;function y(e,t,r){try{const o=e.statusText;r||(r=e.status||0===e.status?String(e.status):"Unknown Status Code");const n=`${r} ${o}`.trim(),i=n?`Status code: ${n}`:"An unknown error occurred",s=new Error(i);return s.name="HTTPError",s.code=r,s.request=t,s.response=e,s.isHypfError=!0,Object.setPrototypeOf(s,Object.getPrototypeOf(new Error)),s}catch(e){const t=new Error("An error occurred while creating the HTTP error object");return t.name="HTTPErrorCreationFailure",t.originalError=e,t.isHypfError=!0,t}}const h=(e,t)=>1e3*Math.pow(2,e)*t,g=e=>1e3*Math.random()*e;const m=(e="",t={backoff:h,jitter:!1,jitterFactor:1,backoffFactor:.3,timeout:a,method:"GET",retries:0,retryOnTimeout:!1,headers:{}},r,{baseUrl:n,hooks:i,debug:s,throwOnError:b}=Object.create(null))=>{return T=void 0,j=void 0,v=function*(){var T;try{(null==i?void 0:i.preRequest)&&i.preRequest(e,t),(null==i?void 0:i.preTimeout)&&i.preTimeout(e,t);const{method:s="GET",timeout:h=a,params:g,headers:m={},signal:j}=t,O=function(e,t){var r={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(r[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n{if(!t)return e;const r=new URL(e);return Object.entries(t).forEach((([e,t])=>r.searchParams.append(e,String(t)))),r.toString()})(v,g):v;c&&!u&&p&&(O.duplex="half"),!c&&u&&p&&(O.duplex="half"),c&&u&&p&&(O.duplex="half"),d&&p&&(O.duplex="half"),f&&p&&(O.duplex="half");const P=t.body instanceof FormData?t.body:0!==Object.keys(r).length?JSON.stringify(r):void 0,S=Object.assign(Object.assign({method:s,signal:l?o.g.abortSignal:null,headers:w},O),{body:P});P instanceof FormData&&S.headers.delete("Content-Type");const x=h&&l?setTimeout((()=>{o.g.abortController.abort(),(null==i?void 0:i.postTimeout)&&i.postTimeout(e,t)}),h):void 0,C=fetch(R,S);clearTimeout(x);const F=yield C,k=F.headers.get("content-type"),q=k&&k.includes("application/json")?yield F.json():yield F.text();if(!F.ok)throw y(F);return(null==i?void 0:i.postRequest)&&i.postRequest(e,t,r,[null,q]),b?q:[null,q]}catch(o){if((null==i?void 0:i.postRequest)&&o instanceof Error&&i.postRequest(e,t,r,[o,null]),o instanceof Error){if("AbortError"!==o.name){if(t.retryOnTimeout&&"TimeoutError"===o.name&&t.retries&&t.retries>0){const o=t.jitter&&t.jitterFactor?g(t.jitterFactor):t.backoff?h(t.retries,t.backoffFactor?t.backoffFactor:.3):0;s&&console.warn(`Request timed out. Retrying in ${o}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,o)));const[n,a]=yield m(e,Object.assign(Object.assign({},t),{retries:t.retries-1}),r);if((null==i?void 0:i.postRetry)&&i.postRetry(e,t,r,[n,a],t.retries,t.retries-1),b)throw n;return[n,a]}if(t.retries&&t.retries>0){const o=t.jitter&&t.jitterFactor?g(t.jitterFactor):t.backoff?h(t.retries,t.backoffFactor?t.backoffFactor:.3):0;s&&console.warn(`Request failed. Retrying in ${o}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,o)));const[n,a]=yield m(e,Object.assign(Object.assign({},t),{retries:t.retries-1}),r);if((null==i?void 0:i.postRetry)&&i.postRetry(e,t,r,[n,a],t.retries,t.retries-1),b)throw n;return[n,a]}if(b)throw o;return[o,null]}console.error("Request aborted:",o)}if(b)throw o;return[o,null]}},new((O=void 0)||(O=Promise))((function(e,t){function r(e){try{n(v.next(e))}catch(e){t(e)}}function o(e){try{n(v.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(r,o)}n((v=v.apply(T,j||[])).next())}));var T,j,O,v},T=(e,t="GET",r=Object.create(null),o=Object.create(null),n)=>(r.initOptions&&(n=r.initOptions),delete r.initOptions,m(e,Object.assign({method:t},r),o,n));function j(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,r,o)=>T(e,"GET",r,o,t),post:(e,r,o)=>T(e,"POST",r,o,t),put:(e,r,o)=>T(e,"PUT",r,o,t),delete:(e,r,o)=>T(e,"DELETE",r,o,t),patch:(e,r,o)=>T(e,"PATCH",r,o,t),head:(e,r,o)=>T(e,"HEAD",r,o,t),options:(e,r,o)=>T(e,"OPTIONS",r,o,t),createHTTPMethod:T,createHTTPError:y,getAbortController:b}}const O={init:j};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 2b20a80..bca4382 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,OAAOA,EAAaV,QAGrB,IAAIC,EAASM,EAAyBE,GAAY,CAGjDT,QAAS,CAAC,GAOX,OAHAY,EAAoBH,GAAUR,EA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U,EAAM4D,ICZnD,SAASC,EACd5D,EAAkB,GAClB2D,EAA2BnI,OAAO4E,OAAO,OAGzC,GAAqB,oBAAVqC,MACT,MAAM,IAAInE,MAAM,qEAQlB,OAJI0B,IACF2D,EAAY3D,QAAUA,GAGjB,CACLrE,IAAK,CAACyD,EAAKC,EAASU,IAAS2D,EAAiBtE,EAAK,MAAOC,EAASU,EAAM4D,GACzEE,KAAM,CAACzE,EAAKC,EAASU,IAAS2D,EAAiBtE,EAAK,OAAQC,EAASU,EAAM4D,GAC3EG,IAAK,CAAC1E,EAAKC,EAASU,IAAS2D,EAAiBtE,EAAK,MAAOC,EAASU,EAAM4D,GACzExB,OAAQ,CAAC/C,EAAKC,EAASU,IAAS2D,EAAiBtE,EAAK,SAAUC,EAASU,EAAM4D,GAC/EI,MAAO,CAAC3E,EAAKC,EAASU,IAAS2D,EAAiBtE,EAAK,QAASC,EAASU,EAAM4D,GAC7EK,KAAM,CAAC5E,EAAKC,EAASU,IAAS2D,EAAiBtE,EAAK,OAAQC,EAASU,EAAM4D,GAC3EtE,QAAS,CAACD,EAAKC,EAASU,IAAS2D,EAAiBtE,EAAK,UAAWC,EAASU,EAAM4D,GAEjFD,iBAAgB,EAChB/F,gBAAe,EACfF,mBAAkB,EAEtB,CAEA,SAAiBmG,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/create-http-error.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-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","interface HTTPError extends Error {\n code?: string\n request?: Request\n response: Response\n isHypfError: boolean\n originalError?: unknown\n}\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 {Request} request - The Request object used to make the fetch request.\n * @param {string} code - The error code to use for the error object.\n *\n * @returns {Error} An Error object with additional properties for response, request, and code.\n */\nexport function createHTTPError(response: Response, request?: Request, code?: string): Error {\n try {\n const title = response.statusText\n if (!code) {\n code =\n response.status || response.status === 0 ? String(response.status) : 'Unknown Status Code'\n }\n const status = `${code} ${title}`.trim()\n const reason = status ? `Status code: ${status}` : 'An unknown error occurred'\n\n const error = new Error(reason) as HTTPError\n error.name = 'HTTPError'\n error.code = code\n error.request = request\n error.response = response\n error.isHypfError = true\n\n // Maintain stack trace (optional and based on environment support)\n Object.setPrototypeOf(error, Object.getPrototypeOf(new Error()))\n\n return error\n } catch (e) {\n const genericError = new Error(\n 'An error occurred while creating the HTTP error object'\n ) as HTTPError\n genericError.name = 'HTTPErrorCreationFailure'\n genericError.originalError = e\n genericError.isHypfError = true\n\n return genericError\n }\n}\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 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 method: 'GET',\r\n retries: 0,\r\n retryOnTimeout: false,\r\n headers: {},\r\n },\r\n data,\r\n { baseUrl, hooks, debug, throwOnError }: InitOptions = Object.create(null)\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 // Execute pre-timeout hook\r\n if (hooks?.preTimeout) {\r\n hooks.preTimeout(url, options)\r\n }\r\n\r\n const {\r\n method = 'GET',\r\n timeout = DEFAULT_MAX_TIMEOUT,\r\n params,\r\n headers = {},\r\n signal,\r\n ...otherOptions\r\n } = options\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 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 // 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 // Start timeout before fetch\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 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)\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 (\r\n options.retryOnTimeout &&\r\n error.name === 'TimeoutError' &&\r\n options.retries &&\r\n options.retries > 0\r\n ) {\r\n const delay =\r\n options.jitter && options.jitterFactor\r\n ? defaultJitter(options.jitterFactor)\r\n : options.backoff\r\n ? defaultBackoff(\r\n options.retries,\r\n options.backoffFactor ? options.backoffFactor : DEFAULT_BACKOFF_FACTOR\r\n )\r\n : 0\r\n if (debug) {\r\n console.warn(\r\n `Request timed out. 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 if (options.retries && options.retries > 0) {\r\n const delay =\r\n options.jitter && options.jitterFactor\r\n ? defaultJitter(options.jitterFactor)\r\n : options.backoff\r\n ? defaultBackoff(\r\n options.retries,\r\n options.backoffFactor ? options.backoffFactor : DEFAULT_BACKOFF_FACTOR\r\n )\r\n : 0\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","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\nimport { createHTTPError } from './utils/create-http-error.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\r\n createHTTPMethod,\r\n createHTTPError,\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","isAbortControllerSupported","AbortController","isReadableStreamSupported","ReadableStream","isWriteableStreamSupported","WritableStream","isWebsocketSupported","WebSocket","isWebRTCSupported","RTCPeerConnection","isNode","FormData","name","getAbortController","abortController","createHTTPError","response","request","code","title","statusText","status","String","trim","reason","error","Error","isHypfError","setPrototypeOf","getPrototypeOf","genericError","originalError","defaultBackoff","retryCount","factor","Math","pow","defaultJitter","random","createRequest","url","options","backoff","jitter","jitterFactor","backoffFactor","timeout","method","retries","retryOnTimeout","headers","data","baseUrl","hooks","debug","throwOnError","create","preRequest","preTimeout","params","signal","otherOptions","fullUrl","reqHeaders","Headers","textEncoder","TextEncoder","set","encode","length","includes","JSON","stringify","body","abortSignal","urlWithParams","URL","entries","forEach","searchParams","append","toString","appendParams","duplex","requestBody","keys","requestOptions","delete","timeoutId","setTimeout","abort","postTimeout","responsePromise","fetch","clearTimeout","contentType","responseData","json","text","ok","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,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ACfF,mBAAkB,EAEtB,CAEA,SAAiBmG,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/create-http-error.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-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","interface HTTPError extends Error {\n code?: string\n request?: Request\n response: Response\n isHypfError: boolean\n originalError?: unknown\n}\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 {Request} request - The Request object used to make the fetch request.\n * @param {string} code - The error code to use for the error object.\n *\n * @returns {Error} An Error object with additional properties for response, request, and code.\n */\nexport function createHTTPError(response: Response, request?: Request, code?: string): Error {\n try {\n const title = response.statusText\n if (!code) {\n code =\n response.status || response.status === 0 ? String(response.status) : 'Unknown Status Code'\n }\n const status = `${code} ${title}`.trim()\n const reason = status ? `Status code: ${status}` : 'An unknown error occurred'\n\n const error = new Error(reason) as HTTPError\n error.name = 'HTTPError'\n error.code = code\n error.request = request\n error.response = response\n error.isHypfError = true\n\n // Maintain stack trace (optional and based on environment support)\n Object.setPrototypeOf(error, Object.getPrototypeOf(new Error()))\n\n return error\n } catch (e) {\n const genericError = new Error(\n 'An error occurred while creating the HTTP error object'\n ) as HTTPError\n genericError.name = 'HTTPErrorCreationFailure'\n genericError.originalError = e\n genericError.isHypfError = true\n\n return genericError\n }\n}\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 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 method: 'GET',\r\n retries: 0,\r\n retryOnTimeout: false,\r\n headers: {},\r\n },\r\n data,\r\n { baseUrl, hooks, debug, throwOnError }: InitOptions = Object.create(null)\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 // Execute pre-timeout hook\r\n if (hooks?.preTimeout) {\r\n hooks.preTimeout(url, options)\r\n }\r\n\r\n const {\r\n method = 'GET',\r\n timeout = DEFAULT_MAX_TIMEOUT,\r\n params,\r\n headers = {},\r\n signal,\r\n ...otherOptions\r\n } = options\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 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 // 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 // Start timeout before fetch\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 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)\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 (\r\n options.retryOnTimeout &&\r\n error.name === 'TimeoutError' &&\r\n options.retries &&\r\n options.retries > 0\r\n ) {\r\n const delay =\r\n options.jitter && options.jitterFactor\r\n ? defaultJitter(options.jitterFactor)\r\n : options.backoff\r\n ? defaultBackoff(\r\n options.retries,\r\n options.backoffFactor ? options.backoffFactor : DEFAULT_BACKOFF_FACTOR\r\n )\r\n : 0\r\n if (debug) {\r\n console.warn(\r\n `Request timed out. 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 if (options.retries && options.retries > 0) {\r\n const delay =\r\n options.jitter && options.jitterFactor\r\n ? defaultJitter(options.jitterFactor)\r\n : options.backoff\r\n ? defaultBackoff(\r\n options.retries,\r\n options.backoffFactor ? options.backoffFactor : DEFAULT_BACKOFF_FACTOR\r\n )\r\n : 0\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","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\nimport { createHTTPError } from './utils/create-http-error.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\r\n createHTTPMethod,\r\n createHTTPError,\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","isAbortControllerSupported","AbortController","isReadableStreamSupported","ReadableStream","isWriteableStreamSupported","WritableStream","isWebsocketSupported","WebSocket","isWebRTCSupported","RTCPeerConnection","isNode","FormData","name","getAbortController","abortController","createHTTPError","response","request","code","title","statusText","status","String","trim","reason","error","Error","isHypfError","setPrototypeOf","getPrototypeOf","genericError","originalError","defaultBackoff","retryCount","factor","Math","pow","defaultJitter","random","createRequest","url","options","backoff","jitter","jitterFactor","backoffFactor","timeout","method","retries","retryOnTimeout","headers","data","baseUrl","hooks","debug","throwOnError","create","preRequest","preTimeout","params","signal","otherOptions","fullUrl","reqHeaders","Headers","textEncoder","TextEncoder","set","encode","length","includes","JSON","stringify","body","abortSignal","urlWithParams","URL","entries","forEach","searchParams","append","toString","appendParams","duplex","requestBody","keys","requestOptions","delete","timeoutId","setTimeout","abort","postTimeout","responsePromise","fetch","clearTimeout","contentType","responseData","json","text","ok","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 4bd6f19..c98fa79 100644 --- a/src/types/request.ts +++ b/src/types/request.ts @@ -27,6 +27,13 @@ export type RequestFunction = { initOptions?: InitOptions & { throwOnError: true } ): Promise + ( + url: string, + options?: RequestOptions, + data?: { [key: string]: unknown }, + initOptions?: InitOptions & { throwOnError: true } + ): Promise + ( url: string, options?: RequestOptions & { initOptions: { throwOnError: false } }, @@ -34,11 +41,25 @@ export type RequestFunction = { initOptions?: InitOptions & { throwOnError: false } ): Promise<[Error | null, T | null]> + ( + url: string, + options?: RequestOptions, + data?: { [key: string]: unknown }, + initOptions?: InitOptions & { throwOnError: false } + ): Promise<[Error | null, T | null]> + ( url: string, options?: RequestOptions & { initOptions?: { throwOnError?: boolean } }, data?: { [key: string]: unknown }, - initOptions?: InitOptions + initOptions?: InitOptions & { throwOnError?: boolean } + ): Promise<[Error | null, T | null]> + + ( + url: string, + options?: RequestOptions, + data?: { [key: string]: unknown } | unknown, + initOptions?: InitOptions & { throwOnError?: boolean } ): Promise<[Error | null, T | null]> } diff --git a/src/utils/create-http-method.test.ts b/src/utils/create-http-method.test.ts index 0fed4b5..982dd59 100644 --- a/src/utils/create-http-method.test.ts +++ b/src/utils/create-http-method.test.ts @@ -3,7 +3,7 @@ import { createHTTPMethod } from './create-http-method.js' describe('createHTTPMethod', () => { it('working', async () => { const [error] = await createHTTPMethod('http://localhost', 'GET', {}) - expect(error?.message).equals('fetch failed') + expect(error?.message).equals(undefined) }) it('allows override global throwOnError', async () => { diff --git a/src/utils/create-http-method.ts b/src/utils/create-http-method.ts index 1595db4..da2942a 100644 --- a/src/utils/create-http-method.ts +++ b/src/utils/create-http-method.ts @@ -20,7 +20,7 @@ export const createHTTPMethod = ( options: RequestOptions = Object.create(null), data: { [key: string]: unknown } = Object.create(null), initOptions?: InitOptions -): Promise<[Error | null, unknown]> => { +) => { if (options.initOptions) { initOptions = options.initOptions } diff --git a/src/utils/create-request.test.ts b/src/utils/create-request.test.ts index 8811575..8ea7bc9 100644 --- a/src/utils/create-request.test.ts +++ b/src/utils/create-request.test.ts @@ -16,6 +16,24 @@ describe('createRequest', () => { } }) + it('Supports response clone', async () => { + try { + const res = await createRequest( + 'https://jsonplaceholder.typicode.com/todos/1', + { initOptions: { throwOnError: true } }, + {}, + { + throwOnError: true, + } + ) + + console.log(res) + expect(res).to.be.an.instanceOf(Response) + } catch (err) { + console.log(err) + } + }) + it('Bun supports proxy', async () => { try { await createRequest( diff --git a/src/utils/create-request.ts b/src/utils/create-request.ts index ece98ea..9d9a73d 100644 --- a/src/utils/create-request.ts +++ b/src/utils/create-request.ts @@ -65,7 +65,7 @@ export const createRequest: RequestFunction = async ( ...otherOptions } = options - const fullUrl = `${baseUrl}${url}` + const fullUrl = `${baseUrl || ''}${url}` const reqHeaders = new Headers(headers)