diff --git a/browser/hyperfetch-browser.min.js b/browser/hyperfetch-browser.min.js index 7f45710..dac768c 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():"function"==typeof define&&define.amd?define("hypf",[],t):"object"==typeof exports?exports.hypf=t():e.hypf=t()}(self,(()=>(()=>{"use strict";var e={d:(t,o)=>{for(var r in o)e.o(o,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:o[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{default:()=>g});const o=2147483647,r=.3,n=1,i="function"==typeof globalThis.AbortController,s="function"==typeof globalThis.ReadableStream,l="function"==typeof globalThis.WritableStream,a="function"==typeof globalThis.WebSocket,c="function"==typeof globalThis.RTCPeerConnection,u=(globalThis.FormData,"undefined"!=typeof process&&"node"===process.release.name),f=()=>i?globalThis.abortController:null,d=(e,t)=>1e3*Math.pow(2,e)*t,p=e=>1e3*Math.random()*e;const b=(e="",t={},f,{baseUrl:y,hooks:g,DEBUG:h}=Object.create(null))=>{return m=void 0,T=void 0,v=function*(){var m;const{method:T="GET",retries:j=0,backoff:v=d,jitter:O=!1,jitterFactor:R=n,backoffFactor:w=r,timeout:S=o,retryOnTimeout:E=!1,params:C,headers:P={},signal:x}=t,F=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{globalThis.abortController.abort(),(null==g?void 0:g.postTimeout)&&g.postTimeout(e,t)}),S):void 0,p=C?((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()})(o,C):o;s&&!l&&u&&(F.duplex="half"),!s&&l&&u&&(F.duplex="half"),s&&l&&u&&(F.duplex="half"),c&&u&&(F.duplex="half"),a&&u&&(F.duplex="half");const b=t.body instanceof FormData?t.body:f?JSON.stringify(f):void 0,h=Object.assign(Object.assign({method:T,signal:i?globalThis.abortSignal:null,headers:r},F),{body:b});b instanceof FormData&&h.headers.delete("Content-Type");const j=fetch(p,h);clearTimeout(d);const v=yield j,O=v.headers.get("content-type"),R=O&&O.includes("application/json")?yield v.json():yield v.text();if(!v.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}(v,R);return(null==g?void 0:g.postRequest)&&g.postRequest(e,t,f,[null,R]),[null,R]}catch(o){if((null==g?void 0:g.postRequest)&&o instanceof Error&&g.postRequest(e,t,f,[o,null]),o instanceof Error)if("AbortError"===o.name)console.error("Request aborted:",o);else{if(E&&"TimeoutError"===o.name&&j&&j>0){const o=O&&R?p(R):v(j,w||r);h&&console.warn(`Request timed out. Retrying in ${o}ms... (Remaining retries: ${j})`),(null==g?void 0:g.preRetry)&&g.preRetry(e,t,j,j),yield new Promise((e=>setTimeout(e,o)));const[n,i]=yield b(e,Object.assign(Object.assign({},t),{retries:j-1}),f);return(null==g?void 0:g.postRetry)&&g.postRetry(e,t,f,[n,i],j,j-1),[n,i]}if(t.retries&&t.retries>0){const o=t.jitter&&t.jitterFactor?p(t.jitterFactor):v(t.retries,t.backoffFactor?t.backoffFactor:r);h&&console.warn(`Request failed. Retrying in ${o}ms... (Remaining retries: ${t.retries})`),(null==g?void 0:g.preRetry)&&g.preRetry(e,t,t.retries,t.retries),yield new Promise((e=>setTimeout(e,o)));const[n,i]=yield b(e,Object.assign(Object.assign({},t),{retries:t.retries-1}),f);return(null==g?void 0:g.postRetry)&&g.postRetry(e,t,f,[n,i],t.retries,t.retries-1),[n,i]}}return o instanceof Error?[o,null]:[null,null]}},new((j=void 0)||(j=Promise))((function(e,t){function o(e){try{n(v.next(e))}catch(e){t(e)}}function r(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 j?n:new j((function(e){e(n)}))).then(o,r)}n((v=v.apply(m,T||[])).next())}));var m,T,j,v},y=(e,t="GET",o={},r,n)=>b(e,Object.assign({method:t},o),r,n),g={init:function(e,t,o=!1){if("undefined"==typeof fetch)throw new Error("This library is intended for use in the browser environment only.");const r={baseUrl:e,hooks:t,DEBUG:o};return{get:(e,t,o)=>y(e,"GET",t,o,r),post:(e,t,o)=>y(e,"POST",t,o,r),put:(e,t,o)=>y(e,"PUT",t,o,r),delete:(e,t,o)=>y(e,"DELETE",t,o,r),patch:(e,t,o)=>y(e,"PATCH",t,o,r),options:(e,t,o)=>y(e,"OPTIONS",t,o,r),getAbortController:f}}};return t})())); +!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:()=>j});var i=r(324),s=r.n(i);const a=2147483647,l=.3,u=1,c="function"==typeof globalThis.AbortController,f="function"==typeof globalThis.ReadableStream,d="function"==typeof globalThis.WritableStream,p="function"==typeof globalThis.WebSocket,y="function"==typeof globalThis.RTCPeerConnection,b=(globalThis.FormData,void 0!==s()&&"node"===s().release.name),g=()=>c?r.g.abortController:null,h=(e,t)=>1e3*Math.pow(2,e)*t,m=e=>1e3*Math.random()*e;const T=(e="",t={},o,{baseUrl:n,hooks:i,DEBUG:s}=Object.create(null))=>{return g=void 0,v=void 0,O=function*(){var g;const{method:v="GET",retries:j=0,backoff:O=h,jitter:w=!1,jitterFactor:R=u,backoffFactor:x=l,timeout:S=a,retryOnTimeout:E=!1,params:C,headers:P={},signal:F}=t,k=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)}),S):void 0,h=C?((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,C):s;f&&!d&&b&&(k.duplex="half"),!f&&d&&b&&(k.duplex="half"),f&&d&&b&&(k.duplex="half"),y&&b&&(k.duplex="half"),p&&b&&(k.duplex="half");const m=t.body instanceof FormData?t.body:o?JSON.stringify(o):void 0,T=Object.assign(Object.assign({method:v,signal:c?r.g.abortSignal:null,headers:a},k),{body:m});m instanceof FormData&&T.headers.delete("Content-Type");const j=fetch(h,T);clearTimeout(u);const O=yield j,w=O.headers.get("content-type"),R=w&&w.includes("application/json")?yield O.json():yield O.text();if(!O.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}(O,R);return(null==i?void 0:i.postRequest)&&i.postRequest(e,t,o,[null,R]),[null,R]}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)console.error("Request aborted:",r);else{if(E&&"TimeoutError"===r.name&&j&&j>0){const r=w&&R?m(R):O(j,x||l);s&&console.warn(`Request timed out. Retrying in ${r}ms... (Remaining retries: ${j})`),(null==i?void 0:i.preRetry)&&i.preRetry(e,t,j,j),yield new Promise((e=>setTimeout(e,r)));const[n,a]=yield T(e,Object.assign(Object.assign({},t),{retries:j-1}),o);return(null==i?void 0:i.postRetry)&&i.postRetry(e,t,o,[n,a],j,j-1),[n,a]}if(t.retries&&t.retries>0){const r=t.jitter&&t.jitterFactor?m(t.jitterFactor):O(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 T(e,Object.assign(Object.assign({},t),{retries:t.retries-1}),o);return(null==i?void 0:i.postRetry)&&i.postRetry(e,t,o,[n,a],t.retries,t.retries-1),[n,a]}}return r instanceof Error?[r,null]:[null,null]}},new((j=void 0)||(j=Promise))((function(e,t){function o(e){try{n(O.next(e))}catch(e){t(e)}}function r(e){try{n(O.throw(e))}catch(e){t(e)}}function n(t){var n;t.done?e(t.value):(n=t.value,n instanceof j?n:new j((function(e){e(n)}))).then(o,r)}n((O=O.apply(g,v||[])).next())}));var g,v,j,O},v=(e,t="GET",o={},r,n)=>T(e,Object.assign({method:t},o),r,n),j={init:function(e,t,o=!1){if("undefined"==typeof fetch)throw new Error("This library is intended for use in the browser environment only.");const r={baseUrl:e,hooks:t,DEBUG:o};return{get:(e,t,o)=>v(e,"GET",t,o,r),post:(e,t,o)=>v(e,"POST",t,o,r),put:(e,t,o)=>v(e,"PUT",t,o,r),delete:(e,t,o)=>v(e,"DELETE",t,o,r),patch:(e,t,o)=>v(e,"PATCH",t,o,r),options:(e,t,o)=>v(e,"OPTIONS",t,o,r),getAbortController:g}}};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 d17d993..161c1cf 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,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,OAAQ,GAAIH,GACO,iBAAZC,QACdA,QAAc,KAAID,IAElBD,EAAW,KAAIC,GAChB,CATD,CASGK,MAAM,I,mBCRT,IAAIC,EAAsB,CCA1BA,EAAwB,CAACL,EAASM,KACjC,IAAI,IAAIC,KAAOD,EACXD,EAAoBG,EAAEF,EAAYC,KAASF,EAAoBG,EAAER,EAASO,IAC5EE,OAAOC,eAAeV,EAASO,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,IAE1E,ECNDF,EAAwB,CAACQ,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,GCClFT,EAAyBL,IACH,oBAAXkB,QAA0BA,OAAOC,aAC1CV,OAAOC,eAAeV,EAASkB,OAAOC,YAAa,CAAEC,MAAO,WAE7DX,OAAOC,eAAeV,EAAS,aAAc,CAAEoB,OAAO,GAAO,G,mCCJvD,MAAMC,EAAsB,WAEtBC,EAAyB,GACzBC,EAAwB,EAExBC,EAAmE,mBAA/BC,WAAWC,gBAC/CC,EAAiE,mBAA9BF,WAAWG,eAC9CC,EAAkE,mBAA9BJ,WAAWK,eAC/CC,EAAuD,mBAAzBN,WAAWO,UACzCC,EAA4D,mBAAjCR,WAAWS,kBAEtCC,GAD6BV,WAAWW,SACZ,oBAAZC,SAAoD,SAAzBA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EAASC,IAAS2E,EAAmB7E,EAAK,UAAWC,EAASC,EAAM4E,GACnFxF,mBAAkB,EAEtB,G","sources":["webpack://hypf/webpack/universalModuleDefinition","webpack://hypf/webpack/bootstrap","webpack://hypf/webpack/runtime/define property getters","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();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"hypf\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"hypf\"] = factory();\n\telse\n\t\troot[\"hypf\"] = factory();\n})(self, () => {\nreturn ","// The require scope\nvar __webpack_require__ = {};\n\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__.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};","// Default maximum recommended timeout in milliseconds (adjust as needed)\nexport const DEFAULT_MAX_TIMEOUT = 2147483647\n\nexport const DEFAULT_BACKOFF_FACTOR = 0.3\nexport const DEFAULT_JITTER_FACTOR = 1\n\nexport const isAbortControllerSupported = typeof globalThis.AbortController === 'function'\nexport const isReadableStreamSupported = typeof globalThis.ReadableStream === 'function'\nexport const isWriteableStreamSupported = typeof globalThis.WritableStream === 'function'\nexport const isWebsocketSupported = typeof globalThis.WebSocket === 'function'\nexport const isWebRTCSupported = typeof globalThis.RTCPeerConnection === 'function'\nexport const isFormDataSupported = typeof globalThis.FormData === 'function'\nexport const isNode = typeof process !== 'undefined' && process.release.name === 'node'\n","import { isAbortControllerSupported } from './constant.js'\n\n// Expose the AbortController instance through the library interface\nexport const getAbortController = () =>\n isAbortControllerSupported ? globalThis.abortController : null\n","export const defaultBackoff = (retryCount: number, factor: number) =>\n Math.pow(2, retryCount) * 1000 * factor // Exponential backoff, starting from 1 second\n\nexport const defaultJitter = (factor: number) => Math.random() * 1000 * factor // Randomized delay up to 1 second\n","import type { InitOptions } from '../types/init.js'\nimport type { RequestFunction } from '../types/request.js'\n\nimport {\n DEFAULT_BACKOFF_FACTOR,\n DEFAULT_JITTER_FACTOR,\n DEFAULT_MAX_TIMEOUT,\n isAbortControllerSupported,\n isNode,\n isReadableStreamSupported,\n isWebRTCSupported,\n isWebsocketSupported,\n isWriteableStreamSupported,\n} from './constant.js'\n\nimport { appendParams } from './append-params.js'\nimport { createHTTPError } from './create-http-error.js'\nimport { defaultBackoff, defaultJitter } from './default-retries.js'\n\nexport const createRequest: RequestFunction = async (\n url = '',\n options = {},\n data,\n { baseUrl, hooks, DEBUG }: InitOptions = Object.create(null)\n): Promise<[Error | null, null]> => {\n const {\n method = 'GET',\n retries = 0,\n backoff = defaultBackoff,\n jitter = false,\n jitterFactor = DEFAULT_JITTER_FACTOR,\n backoffFactor = DEFAULT_BACKOFF_FACTOR,\n timeout = DEFAULT_MAX_TIMEOUT,\n retryOnTimeout = false,\n params,\n headers = {},\n signal,\n ...otherOptions\n } = options\n\n try {\n // Execute pre-request hook\n if (hooks?.preRequest) {\n hooks.preRequest(url, options)\n }\n\n const fullUrl = `${baseUrl}${url}`\n\n const reqHeaders = new Headers(headers)\n\n // Automatically detect and add Content-Length based on payload length\n const textEncoder = new TextEncoder()\n if (!reqHeaders.get('Content-Length') && data) {\n if (typeof data === 'string') {\n reqHeaders.set('Content-Length', String(textEncoder.encode(data).length))\n } else if (reqHeaders.get('Content-Length')?.includes('application/json')) {\n reqHeaders.set('Content-Length', String(textEncoder.encode(JSON.stringify(data)).length))\n }\n }\n\n // Set default Content-Type to application/json if not provided\n if (!reqHeaders.get('Content-Type') && data && typeof data === 'object') {\n if (!(((data as { body: FormData })?.body || data) instanceof FormData)) {\n reqHeaders.set('Content-Type', 'application/json')\n }\n }\n\n // Execute pre-timeout hook\n if (hooks?.preTimeout) {\n hooks.preTimeout(url, options)\n }\n\n if (isAbortControllerSupported) {\n // Expose the AbortController instance\n globalThis.abortController = new AbortController()\n\n // Use the external AbortController instance\n globalThis.abortSignal = signal ? signal : globalThis.abortController.signal\n }\n\n const timeoutId =\n timeout && isAbortControllerSupported\n ? setTimeout(() => {\n globalThis.abortController.abort()\n\n // Execute post-timeout hook\n if (hooks?.postTimeout) {\n hooks.postTimeout(url, options)\n }\n }, timeout)\n : undefined\n\n // Append params to the URL\n const urlWithParams = params ? appendParams(fullUrl, params) : fullUrl\n\n if (isReadableStreamSupported && !isWriteableStreamSupported && isNode) {\n // @ts-expect-error - Duplex types is not supported\n otherOptions.duplex = 'half'\n }\n if (!isReadableStreamSupported && isWriteableStreamSupported && isNode) {\n // @ts-expect-error - Duplex types is not supported\n otherOptions.duplex = 'half'\n }\n if (isReadableStreamSupported && isWriteableStreamSupported && isNode) {\n // @ts-expect-error - Duplex types is not supported\n otherOptions.duplex = 'half'\n }\n // WebRTC is supported, allowing for full duplex communication.\n if (isWebRTCSupported && isNode) {\n // @ts-expect-error - Duplex types is not supported\n otherOptions.duplex = 'half'\n }\n // WebSockets are supported, and thus full duplex communication is possible.\n if (isWebsocketSupported && isNode) {\n // @ts-expect-error - Duplex types is not supported\n otherOptions.duplex = 'half'\n }\n\n const requestBody =\n options.body instanceof FormData ? options.body : data ? JSON.stringify(data) : undefined\n\n const requestOptions = {\n method,\n signal: isAbortControllerSupported ? globalThis.abortSignal : null,\n headers: reqHeaders,\n ...otherOptions,\n body: requestBody,\n }\n\n if (requestBody instanceof FormData) {\n requestOptions.headers.delete('Content-Type')\n }\n\n const responsePromise = fetch(urlWithParams, requestOptions)\n\n clearTimeout(timeoutId)\n\n const response = await responsePromise\n\n const contentType = response.headers.get('content-type')\n\n const responseData =\n contentType && contentType.includes('application/json')\n ? await response.json()\n : await response.text()\n\n if (!response.ok) {\n throw createHTTPError(response, responseData)\n }\n\n // Execute post-request hook\n if (hooks?.postRequest) {\n hooks.postRequest(url, options, data, [null, responseData])\n }\n\n return [null, responseData]\n } catch (error) {\n // Execute post-request hook for errors\n if (hooks?.postRequest) {\n if (error instanceof Error) {\n hooks.postRequest(url, options, data, [error, null])\n }\n }\n\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n console.error('Request aborted:', error)\n } else if (retryOnTimeout && error.name === 'TimeoutError' && retries && retries > 0) {\n const delay =\n jitter && jitterFactor\n ? defaultJitter(jitterFactor)\n : backoff(retries, backoffFactor ? backoffFactor : DEFAULT_BACKOFF_FACTOR)\n if (DEBUG) {\n console.warn(\n `Request timed out. Retrying in ${delay}ms... (Remaining retries: ${retries})`\n )\n }\n // Execute pre-retry hook\n if (hooks?.preRetry) {\n hooks.preRetry(url, options, retries, retries)\n }\n await new Promise((resolve) => setTimeout(resolve, delay))\n const [retryErr, retryData] = await createRequest(\n url,\n { ...options, retries: retries - 1 },\n data\n )\n // Execute post-retry hook\n if (hooks?.postRetry) {\n hooks.postRetry(url, options, data, [retryErr, retryData], retries, retries - 1)\n }\n return [retryErr, retryData]\n } else if (options.retries && options.retries > 0) {\n const delay =\n options.jitter && options.jitterFactor\n ? defaultJitter(options.jitterFactor)\n : backoff(\n options.retries,\n options.backoffFactor ? options.backoffFactor : DEFAULT_BACKOFF_FACTOR\n )\n if (DEBUG) {\n console.warn(\n `Request failed. Retrying in ${delay}ms... (Remaining retries: ${options.retries})`\n )\n }\n // Execute pre-retry hook\n if (hooks?.preRetry) {\n hooks.preRetry(url, options, options.retries, options.retries)\n }\n await new Promise((resolve) => setTimeout(resolve, delay))\n const [retryErr, retryData] = await createRequest(\n url,\n { ...options, retries: options.retries - 1 },\n data\n )\n // Execute post-retry hook\n if (hooks?.postRetry) {\n hooks.postRetry(\n url,\n options,\n data,\n [retryErr, retryData],\n options.retries,\n options.retries - 1\n )\n }\n return [retryErr, retryData]\n }\n }\n\n if (error instanceof Error) {\n return [error, null]\n }\n\n return [null, null]\n }\n}\n","export 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 */\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 } from '../types/request.js'\nimport type { InitOptions } from '../types/init.js'\n\nimport { createRequest } from './create-request.js'\n\nexport const httpMethodFunction = (\n url: string,\n method: RequestMethod = 'GET',\n options = {},\n data: unknown,\n initOptions: InitOptions\n) => {\n return createRequest(url, { method, ...options }, data, initOptions)\n}\n","import type { Hooks } from './types/hooks.js'\nimport type { HttpRequestFunctions } from './types/request.js'\n\nimport { getAbortController } from './utils/get-abort-controller.js'\nimport { httpMethodFunction } from './utils/create-http-method.js'\n\nfunction init(baseUrl?: string, hooks?: Hooks, DEBUG: boolean = false): HttpRequestFunctions {\n // Check if fetch is available\n if (typeof fetch === 'undefined') {\n throw new Error('This library is intended for use in the browser environment only.')\n }\n\n const initOptions = {\n baseUrl,\n hooks,\n DEBUG,\n }\n\n return {\n get: (url, options, data) => httpMethodFunction(url, 'GET', options, data, initOptions),\n post: (url, options, data) => httpMethodFunction(url, 'POST', options, data, initOptions),\n put: (url, options, data) => httpMethodFunction(url, 'PUT', options, data, initOptions),\n delete: (url, options, data) => httpMethodFunction(url, 'DELETE', options, data, initOptions),\n patch: (url, options, data) => httpMethodFunction(url, 'PATCH', options, data, initOptions),\n options: (url, options, data) => httpMethodFunction(url, 'OPTIONS', options, data, initOptions),\n getAbortController,\n }\n}\n\nexport default { init }\n"],"names":["root","factory","exports","module","define","amd","self","__webpack_require__","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","DEFAULT_MAX_TIMEOUT","DEFAULT_BACKOFF_FACTOR","DEFAULT_JITTER_FACTOR","isAbortControllerSupported","globalThis","AbortController","isReadableStreamSupported","ReadableStream","isWriteableStreamSupported","WritableStream","isWebsocketSupported","WebSocket","isWebRTCSupported","RTCPeerConnection","isNode","FormData","process","release","name","getAbortController","abortController","defaultBackoff","retryCount","factor","Math","pow","defaultJitter","random","createRequest","url","options","data","baseUrl","hooks","DEBUG","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","undefined","urlWithParams","URL","entries","forEach","searchParams","append","toString","appendParams","duplex","requestBody","requestOptions","delete","responsePromise","fetch","clearTimeout","response","contentType","responseData","json","text","ok","status","statusText","trim","error","Error","createHTTPError","postRequest","console","delay","warn","preRetry","Promise","resolve","retryErr","retryData","postRetry","httpMethodFunction","initOptions","init","post","put","patch"],"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,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C/E,EAAKC,EAASC,IAAS0E,EAAmB5E,EAAK,OAAQC,EAASC,EAAM2E,GAC7EG,IAAK,CAAChF,EAAKC,EAASC,IAAS0E,EAAmB5E,EAAK,MAAOC,EAASC,EAAM2E,GAC3E3B,OAAQ,CAAClD,EAAKC,EAASC,IAAS0E,EAAmB5E,EAAK,SAAUC,EAASC,EAAM2E,GACjFI,MAAO,CAACjF,EAAKC,EAASC,IAAS0E,EAAmB5E,EAAK,QAASC,EAASC,EAAM2E,GAC/E5E,QAAS,CAACD,EAAKC,EAASC,IAAS0E,EAAmB5E,EAAK,UAAWC,EAASC,EAAM2E,GACnFvF,mBAAkB,EAEtB,G","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};","import process from 'node:process'\n\n// Default maximum recommended timeout in milliseconds (adjust as needed)\nexport const DEFAULT_MAX_TIMEOUT = 2147483647\n\nexport const DEFAULT_BACKOFF_FACTOR = 0.3\nexport const DEFAULT_JITTER_FACTOR = 1\n\nexport const isAbortControllerSupported = typeof globalThis.AbortController === 'function'\nexport const isReadableStreamSupported = typeof globalThis.ReadableStream === 'function'\nexport const isWriteableStreamSupported = typeof globalThis.WritableStream === 'function'\nexport const isWebsocketSupported = typeof globalThis.WebSocket === 'function'\nexport const isWebRTCSupported = typeof globalThis.RTCPeerConnection === 'function'\nexport const isFormDataSupported = typeof globalThis.FormData === 'function'\nexport const isNode = typeof process !== 'undefined' && process.release.name === 'node'\n","import { isAbortControllerSupported } from './constant.js'\n\n// Expose the AbortController instance through the library interface\nexport const getAbortController = () => (isAbortControllerSupported ? global.abortController : null)\n","export const defaultBackoff = (retryCount: number, factor: number) =>\n Math.pow(2, retryCount) * 1000 * factor // Exponential backoff, starting from 1 second\n\nexport const defaultJitter = (factor: number) => Math.random() * 1000 * factor // Randomized delay up to 1 second\n","import type { InitOptions } from '../types/init.js'\nimport type { RequestFunction } from '../types/request.js'\n\nimport {\n DEFAULT_BACKOFF_FACTOR,\n DEFAULT_JITTER_FACTOR,\n DEFAULT_MAX_TIMEOUT,\n isAbortControllerSupported,\n isNode,\n isReadableStreamSupported,\n isWebRTCSupported,\n isWebsocketSupported,\n isWriteableStreamSupported,\n} from './constant.js'\n\nimport { appendParams } from './append-params.js'\nimport { createHTTPError } from './create-http-error.js'\nimport { defaultBackoff, defaultJitter } from './default-retries.js'\n\nexport const createRequest: RequestFunction = async (\n url = '',\n options = {},\n data,\n { baseUrl, hooks, DEBUG }: InitOptions = Object.create(null)\n): Promise<[Error | null, null]> => {\n const {\n method = 'GET',\n retries = 0,\n backoff = defaultBackoff,\n jitter = false,\n jitterFactor = DEFAULT_JITTER_FACTOR,\n backoffFactor = DEFAULT_BACKOFF_FACTOR,\n timeout = DEFAULT_MAX_TIMEOUT,\n retryOnTimeout = false,\n params,\n headers = {},\n signal,\n ...otherOptions\n } = options\n\n try {\n // Execute pre-request hook\n if (hooks?.preRequest) {\n hooks.preRequest(url, options)\n }\n\n const fullUrl = `${baseUrl}${url}`\n\n const reqHeaders = new Headers(headers)\n\n // Automatically detect and add Content-Length based on payload length\n const textEncoder = new TextEncoder()\n if (!reqHeaders.get('Content-Length') && data) {\n if (typeof data === 'string') {\n reqHeaders.set('Content-Length', String(textEncoder.encode(data).length))\n } else if (reqHeaders.get('Content-Length')?.includes('application/json')) {\n reqHeaders.set('Content-Length', String(textEncoder.encode(JSON.stringify(data)).length))\n }\n }\n\n // Set default Content-Type to application/json if not provided\n if (!reqHeaders.get('Content-Type') && data && typeof data === 'object') {\n if (!(((data as { body: FormData })?.body || data) instanceof FormData)) {\n reqHeaders.set('Content-Type', 'application/json')\n }\n }\n\n // Execute pre-timeout hook\n if (hooks?.preTimeout) {\n hooks.preTimeout(url, options)\n }\n\n if (isAbortControllerSupported) {\n // Expose the AbortController instance\n global.abortController = new AbortController()\n\n // Use the external AbortController instance\n global.abortSignal = signal ? signal : global.abortController.signal\n }\n\n const timeoutId =\n timeout && isAbortControllerSupported\n ? setTimeout(() => {\n global.abortController.abort()\n\n // Execute post-timeout hook\n if (hooks?.postTimeout) {\n hooks.postTimeout(url, options)\n }\n }, timeout)\n : undefined\n\n // Append params to the URL\n const urlWithParams = params ? appendParams(fullUrl, params) : fullUrl\n\n if (isReadableStreamSupported && !isWriteableStreamSupported && isNode) {\n // @ts-expect-error - Duplex types is not supported\n otherOptions.duplex = 'half'\n }\n if (!isReadableStreamSupported && isWriteableStreamSupported && isNode) {\n // @ts-expect-error - Duplex types is not supported\n otherOptions.duplex = 'half'\n }\n if (isReadableStreamSupported && isWriteableStreamSupported && isNode) {\n // @ts-expect-error - Duplex types is not supported\n otherOptions.duplex = 'half'\n }\n // WebRTC is supported, allowing for full duplex communication.\n if (isWebRTCSupported && isNode) {\n // @ts-expect-error - Duplex types is not supported\n otherOptions.duplex = 'half'\n }\n // WebSockets are supported, and thus full duplex communication is possible.\n if (isWebsocketSupported && isNode) {\n // @ts-expect-error - Duplex types is not supported\n otherOptions.duplex = 'half'\n }\n\n const requestBody =\n options.body instanceof FormData ? options.body : data ? JSON.stringify(data) : undefined\n\n const requestOptions = {\n method,\n signal: isAbortControllerSupported ? global.abortSignal : null,\n headers: reqHeaders,\n ...otherOptions,\n body: requestBody,\n }\n\n if (requestBody instanceof FormData) {\n requestOptions.headers.delete('Content-Type')\n }\n\n const responsePromise = fetch(urlWithParams, requestOptions)\n\n clearTimeout(timeoutId)\n\n const response = await responsePromise\n\n const contentType = response.headers.get('content-type')\n\n const responseData =\n contentType && contentType.includes('application/json')\n ? await response.json()\n : await response.text()\n\n if (!response.ok) {\n throw createHTTPError(response, responseData)\n }\n\n // Execute post-request hook\n if (hooks?.postRequest) {\n hooks.postRequest(url, options, data, [null, responseData])\n }\n\n return [null, responseData]\n } catch (error) {\n // Execute post-request hook for errors\n if (hooks?.postRequest) {\n if (error instanceof Error) {\n hooks.postRequest(url, options, data, [error, null])\n }\n }\n\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n console.error('Request aborted:', error)\n } else if (retryOnTimeout && error.name === 'TimeoutError' && retries && retries > 0) {\n const delay =\n jitter && jitterFactor\n ? defaultJitter(jitterFactor)\n : backoff(retries, backoffFactor ? backoffFactor : DEFAULT_BACKOFF_FACTOR)\n if (DEBUG) {\n console.warn(\n `Request timed out. Retrying in ${delay}ms... (Remaining retries: ${retries})`\n )\n }\n // Execute pre-retry hook\n if (hooks?.preRetry) {\n hooks.preRetry(url, options, retries, retries)\n }\n await new Promise((resolve) => setTimeout(resolve, delay))\n const [retryErr, retryData] = await createRequest(\n url,\n { ...options, retries: retries - 1 },\n data\n )\n // Execute post-retry hook\n if (hooks?.postRetry) {\n hooks.postRetry(url, options, data, [retryErr, retryData], retries, retries - 1)\n }\n return [retryErr, retryData]\n } else if (options.retries && options.retries > 0) {\n const delay =\n options.jitter && options.jitterFactor\n ? defaultJitter(options.jitterFactor)\n : backoff(\n options.retries,\n options.backoffFactor ? options.backoffFactor : DEFAULT_BACKOFF_FACTOR\n )\n if (DEBUG) {\n console.warn(\n `Request failed. Retrying in ${delay}ms... (Remaining retries: ${options.retries})`\n )\n }\n // Execute pre-retry hook\n if (hooks?.preRetry) {\n hooks.preRetry(url, options, options.retries, options.retries)\n }\n await new Promise((resolve) => setTimeout(resolve, delay))\n const [retryErr, retryData] = await createRequest(\n url,\n { ...options, retries: options.retries - 1 },\n data\n )\n // Execute post-retry hook\n if (hooks?.postRetry) {\n hooks.postRetry(\n url,\n options,\n data,\n [retryErr, retryData],\n options.retries,\n options.retries - 1\n )\n }\n return [retryErr, retryData]\n }\n }\n\n if (error instanceof Error) {\n return [error, null]\n }\n\n return [null, null]\n }\n}\n","export 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 */\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 } from '../types/request.js'\nimport type { InitOptions } from '../types/init.js'\n\nimport { createRequest } from './create-request.js'\n\nexport const httpMethodFunction = (\n url: string,\n method: RequestMethod = 'GET',\n options = {},\n data: unknown,\n initOptions: InitOptions\n) => {\n return createRequest(url, { method, ...options }, data, initOptions)\n}\n","import type { Hooks } from './types/hooks.js'\nimport type { HttpRequestFunctions } from './types/request.js'\n\nimport { getAbortController } from './utils/get-abort-controller.js'\nimport { httpMethodFunction } from './utils/create-http-method.js'\n\nfunction init(baseUrl?: string, hooks?: Hooks, DEBUG: boolean = false): HttpRequestFunctions {\n // Check if fetch is available\n if (typeof fetch === 'undefined') {\n throw new Error('This library is intended for use in the browser environment only.')\n }\n\n const initOptions = {\n baseUrl,\n hooks,\n DEBUG,\n }\n\n return {\n get: (url, options, data) => httpMethodFunction(url, 'GET', options, data, initOptions),\n post: (url, options, data) => httpMethodFunction(url, 'POST', options, data, initOptions),\n put: (url, options, data) => httpMethodFunction(url, 'PUT', options, data, initOptions),\n delete: (url, options, data) => httpMethodFunction(url, 'DELETE', options, data, initOptions),\n patch: (url, options, data) => httpMethodFunction(url, 'PATCH', options, data, initOptions),\n options: (url, options, data) => httpMethodFunction(url, 'OPTIONS', options, data, initOptions),\n getAbortController,\n }\n}\n\nexport default { init }\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","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","requestOptions","delete","responsePromise","fetch","clearTimeout","response","contentType","responseData","json","text","ok","status","statusText","trim","error","Error","createHTTPError","postRequest","console","delay","warn","preRetry","Promise","resolve","retryErr","retryData","postRetry","httpMethodFunction","initOptions","init","post","put","patch"],"sourceRoot":""} \ No newline at end of file diff --git a/src/types/global.d.ts b/src/types/global.d.ts index 4afecd5..0672cd5 100644 --- a/src/types/global.d.ts +++ b/src/types/global.d.ts @@ -1,5 +1,5 @@ /* eslint-disable no-var */ -declare module globalThis { +declare module global { var abortController: AbortController var abortSignal: AbortSignal } diff --git a/src/utils/create-request.ts b/src/utils/create-request.ts index 67fb092..100d32e 100644 --- a/src/utils/create-request.ts +++ b/src/utils/create-request.ts @@ -72,16 +72,16 @@ export const createRequest: RequestFunction = async ( if (isAbortControllerSupported) { // Expose the AbortController instance - globalThis.abortController = new AbortController() + global.abortController = new AbortController() // Use the external AbortController instance - globalThis.abortSignal = signal ? signal : globalThis.abortController.signal + global.abortSignal = signal ? signal : global.abortController.signal } const timeoutId = timeout && isAbortControllerSupported ? setTimeout(() => { - globalThis.abortController.abort() + global.abortController.abort() // Execute post-timeout hook if (hooks?.postTimeout) { @@ -121,7 +121,7 @@ export const createRequest: RequestFunction = async ( const requestOptions = { method, - signal: isAbortControllerSupported ? globalThis.abortSignal : null, + signal: isAbortControllerSupported ? global.abortSignal : null, headers: reqHeaders, ...otherOptions, body: requestBody, diff --git a/src/utils/get-abort-controller.ts b/src/utils/get-abort-controller.ts index 8d68025..a06bed4 100644 --- a/src/utils/get-abort-controller.ts +++ b/src/utils/get-abort-controller.ts @@ -1,5 +1,4 @@ import { isAbortControllerSupported } from './constant.js' // Expose the AbortController instance through the library interface -export const getAbortController = () => - isAbortControllerSupported ? globalThis.abortController : null +export const getAbortController = () => (isAbortControllerSupported ? global.abortController : null) diff --git a/webpack.config.ts b/webpack.config.ts index d99d684..c4a889d 100644 --- a/webpack.config.ts +++ b/webpack.config.ts @@ -1,29 +1,32 @@ // @ts-check -const path = require("path"); +const path = require('path') module.exports = /** @type { import('webpack').Configuration } */ { - mode: "production", - entry: "./src/index.ts", - devtool: "source-map", + mode: 'production', + entry: './src/index.ts', + devtool: 'source-map', output: { library: { - name: "hypf", - type: "umd", + name: 'hypf', + type: 'umd', umdNamedDefine: true, }, - path: path.resolve(__dirname, "browser"), - filename: "hyperfetch-browser.min.js", + path: path.resolve(__dirname, 'browser'), + filename: 'hyperfetch-browser.min.js', + }, + externals: { + 'node:process': '{}', }, resolve: { extensionAlias: { - ".js": [".js", ".ts"], + '.js': ['.js', '.ts'], }, - extensions: [".ts", ".js"], + extensions: ['.ts', '.js'], }, module: { rules: [ // all files with a `.ts`, `.cts`, `.mts` or `.tsx` extension will be handled by `ts-loader` - { test: /\.([cm]?ts|tsx)$/, loader: "ts-loader" }, + { test: /\.([cm]?ts|tsx)$/, loader: 'ts-loader' }, ], }, -}; +}