@d1g1tal/transportr 3.3.0 → 3.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/dist/transportr.d.ts +6 -4
- package/dist/transportr.js +6 -6
- package/dist/transportr.js.map +4 -4
- package/package.json +4 -4
- package/dist/iife/content-type.js +0 -6
- package/dist/iife/content-type.js.map +0 -7
- package/dist/iife/request-header.js +0 -6
- package/dist/iife/request-header.js.map +0 -7
- package/dist/iife/request-method.js +0 -6
- package/dist/iife/request-method.js.map +0 -7
- package/dist/iife/response-header.js +0 -6
- package/dist/iife/response-header.js.map +0 -7
- package/dist/iife/transportr.js +0 -1303
- package/dist/iife/transportr.js.map +0 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,37 @@
|
|
|
1
|
+
## [3.3.2](https://github.com/D1g1talEntr0py/transportr/compare/v3.3.1...v3.3.2) (2026-04-11)
|
|
2
|
+
|
|
3
|
+
### Performance Improvements
|
|
4
|
+
|
|
5
|
+
* improve stream processing and options handling (da83c8fd54c83cb73e30cc82b12fa1fc74a92d77)
|
|
6
|
+
Enhances the handling of EventStream and NDJSON responses by introducing a robust `readDelimited` generator, correctly parsing Server-Sent Events according to spec. Refactors stream response handlers to use standard DOMParser where appropriate and properly manage object URLs safely with `withObjectURL`.
|
|
7
|
+
|
|
8
|
+
Optimizes request options processing to utilize native Headers and URLSearchParams constructors, avoiding deep merges where unnecessary.
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
### Miscellaneous Chores
|
|
12
|
+
|
|
13
|
+
* format and config updates (78c2e2826a1aad447869b1ca25d2afc79dadbf08)
|
|
14
|
+
Updates `.gitignore` to ignore the `benchmarks/` directory. Adjusts ESLint config to no longer require JSDoc for arrow functions. Disables IIFE generation in `tsconfig.json`.
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
### Tests
|
|
18
|
+
|
|
19
|
+
* add stream tests (58f0d8214aa8c35fb211e541d3946dcb6f23349b)
|
|
20
|
+
Adds thorough testing for the updated stream handling, including passing options as the first argument, stream error handling, and applying hooks.
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
### Build System
|
|
24
|
+
|
|
25
|
+
* update dependencies (162a4cc3a35ce06df2cdb5ba858a942b7639fcaa)
|
|
26
|
+
Updates various dependencies and their types, including `@d1g1tal/subscribr`, `@d1g1tal/tsbuild`, `@types/node`, and others in the lockfile.
|
|
27
|
+
|
|
28
|
+
## [3.3.1](https://github.com/D1g1talEntr0py/transportr/compare/v3.3.0...v3.3.1) (2026-04-09)
|
|
29
|
+
|
|
30
|
+
### Bug Fixes
|
|
31
|
+
|
|
32
|
+
* bypasses DOMPurify entirely for trusted content (bc6b70db9199f985ce908688fc4e0ac16e05ec6e)
|
|
33
|
+
Fixes an issue where the handler partially sanitized HTML even when scripts were allowed. Bypassing DOMPurify completely ensures that inline event handlers and other required attributes are preserved, allowing JavaScript to execute reliably when the caller explicitly trusts the content.
|
|
34
|
+
|
|
1
35
|
## [3.3.0](https://github.com/D1g1talEntr0py/transportr/compare/v3.2.2...v3.3.0) (2026-04-09)
|
|
2
36
|
|
|
3
37
|
### Features
|
package/dist/transportr.d.ts
CHANGED
|
@@ -598,7 +598,7 @@ type RequestNoBodyMethod = Exclude<RequestMethod, RequestBodyMethod>;
|
|
|
598
598
|
type RequestHeaders = Prettify<TypedHeaders & {
|
|
599
599
|
[K in Exclude<typeof RequestHeader[keyof typeof RequestHeader], keyof TypedHeaders>]?: string;
|
|
600
600
|
} & HeadersInit>;
|
|
601
|
-
type SearchParameters =
|
|
601
|
+
type SearchParameters = string | string[][] | Record<string, string> | URLSearchParams | undefined;
|
|
602
602
|
type AuthorizationScheme = 'Basic' | 'Bearer' | 'Digest' | 'HOBA' | 'Mutual' | 'Negotiate' | 'OAuth' | 'SCRAM-SHA-1' | 'SCRAM-SHA-256' | 'vapid';
|
|
603
603
|
type ResponseHandler<T extends ResponseBody = ResponseBody> = (response: Response) => Promise<T>;
|
|
604
604
|
type RequestLifecycleEvent = 'configured' | 'success' | 'error' | 'aborted' | 'timeout' | 'retry' | 'complete' | 'all-complete';
|
|
@@ -630,7 +630,7 @@ type MethodBody = {
|
|
|
630
630
|
method?: RequestBodyMethod;
|
|
631
631
|
body?: RequestBody;
|
|
632
632
|
} | {
|
|
633
|
-
method
|
|
633
|
+
method: RequestNoBodyMethod;
|
|
634
634
|
body?: never;
|
|
635
635
|
};
|
|
636
636
|
type RequestOptions = Prettify<{
|
|
@@ -764,9 +764,9 @@ declare const aborted: ResponseStatus;
|
|
|
764
764
|
/** Response status for timed out request */
|
|
765
765
|
declare const timedOut: ResponseStatus;
|
|
766
766
|
/** Default HTTP status codes that trigger a retry */
|
|
767
|
-
declare const retryStatusCodes:
|
|
767
|
+
declare const retryStatusCodes: Array<number>;
|
|
768
768
|
/** Default HTTP methods allowed to retry (idempotent methods only) */
|
|
769
|
-
declare const retryMethods:
|
|
769
|
+
declare const retryMethods: Array<RequestMethod>;
|
|
770
770
|
/** Default delay in ms before the first retry */
|
|
771
771
|
declare const retryDelay: number;
|
|
772
772
|
/** Default backoff factor applied after each retry attempt */
|
|
@@ -798,6 +798,8 @@ declare class Transportr {
|
|
|
798
798
|
private static signalControllers;
|
|
799
799
|
/** Map of in-flight deduplicated requests keyed by URL + method */
|
|
800
800
|
private static inflightRequests;
|
|
801
|
+
/** Cached config for the common "no retry" case (retry === undefined) */
|
|
802
|
+
private static readonly noRetryConfig;
|
|
801
803
|
/** Cache for parsed MediaType instances to avoid re-parsing the same content-type strings */
|
|
802
804
|
private static mediaTypeCache;
|
|
803
805
|
private static contentTypeHandlers;
|
package/dist/transportr.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
2
|
-
`,"\r"]),
|
|
1
|
+
var M=/^[-!#$%&'*+.^_`|~A-Za-z0-9]*$/u,Me=/(["\\])/ug,Ie=/^[\t\u0020-\u007E\u0080-\u00FF]*$/u,ae=class ue extends Map{constructor(e=[]){super(e)}static isValid(e,t){return M.test(e)&&Ie.test(t)}get(e){return super.get(e.toLowerCase())}has(e){return super.has(e.toLowerCase())}set(e,t){if(!ue.isValid(e,t))throw new Error(`Invalid media type parameter name/value: ${e}/${t}`);return super.set(e.toLowerCase(),t),this}delete(e){return super.delete(e.toLowerCase())}toString(){return Array.from(this).map(([e,t])=>`;${e}=${!t||!M.test(t)?`"${t.replace(Me,"\\$1")}"`:t}`).join("")}get[Symbol.toStringTag](){return"MediaTypeParameters"}},Le=new Set([" "," ",`
|
|
2
|
+
`,"\r"]),Ne=/[ \t\n\r]+$/u,De=/^[ \t\n\r]+|[ \t\n\r]+$/ug,_e=class O{static parse(e){e=e.replace(De,"");let t=0,[n,r]=O.collect(e,t,["/"]);if(t=r,!n.length||t>=e.length||!M.test(n))throw new TypeError(O.generateErrorMessage("type",n));++t;let[o,i]=O.collect(e,t,[";"],!0,!0);if(t=i,!o.length||!M.test(o))throw new TypeError(O.generateErrorMessage("subtype",o));let a=new ae;for(;t<e.length;){for(++t;Le.has(e[t]);)++t;let u;if([u,t]=O.collect(e,t,[";","="],!1),t>=e.length||e[t]===";")continue;++t;let p;if(e[t]==='"')for([p,t]=O.collectHttpQuotedString(e,t);t<e.length&&e[t]!==";";)++t;else if([p,t]=O.collect(e,t,[";"],!1,!0),!p)continue;u&&ae.isValid(u,p)&&!a.has(u)&&a.set(u,p)}return{type:n,subtype:o,parameters:a}}get[Symbol.toStringTag](){return"MediaTypeParser"}static collect(e,t,n,r=!0,o=!1){let i="";for(let{length:a}=e;t<a&&!n.includes(e[t]);t++)i+=e[t];return r&&(i=i.toLowerCase()),o&&(i=i.replace(Ne,"")),[i,t]}static collectHttpQuotedString(e,t){let n="";for(let r=e.length,o;++t<r&&(o=e[t])!=='"';)n+=o=="\\"&&++t<r?e[t]:o;return[n,t]}static generateErrorMessage(e,t){return`Invalid ${e} "${t}": only HTTP token code points are valid.`}},T=class le{_type;_subtype;_parameters;constructor(e,t={}){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("The parameters argument must be an object");({type:this._type,subtype:this._subtype,parameters:this._parameters}=_e.parse(e));for(let[n,r]of Object.entries(t))this._parameters.set(n,r)}static parse(e){try{return new le(e)}catch{}return null}get type(){return this._type}get subtype(){return this._subtype}get essence(){return`${this._type}/${this._subtype}`}get parameters(){return this._parameters}matches(e){return typeof e=="string"?this.essence.includes(e):this._type===e._type&&this._subtype===e._subtype}toString(){return`${this.essence}${this._parameters.toString()}`}get[Symbol.toStringTag](){return"MediaType"}};var je=class extends Map{set(s,e){return super.set(s,e instanceof Set?e:(super.get(s)??new Set).add(e)),this}getOrInsert(s,e){return this.has(s)?super.get(s):(super.set(s,e instanceof Set?e:(super.get(s)??new Set).add(e)),e)}getOrInsertComputed(s,e){if(this.has(s))return super.get(s);let t=e(s);return super.set(s,t instanceof Set?t:(super.get(s)??new Set).add(t)),t}find(s,e){let t=this.get(s);if(t!==void 0)return Array.from(t).find(e)}hasValue(s,e){let t=super.get(s);return t?t.has(e):!1}deleteValue(s,e){if(e===void 0)return this.delete(s);let t=super.get(s);if(t){let n=t.delete(e);return t.size===0&&super.delete(s),n}return!1}get[Symbol.toStringTag](){return"SetMultiMap"}},Fe=class{context;eventHandler;constructor(s,e){this.context=s,this.eventHandler=e}handle(s,e){this.eventHandler.call(this.context,s,e)}get[Symbol.toStringTag](){return"ContextEventHandler"}},Je=class{_eventName;_contextEventHandler;constructor(s,e){this._eventName=s,this._contextEventHandler=e}get eventName(){return this._eventName}get contextEventHandler(){return this._contextEventHandler}get[Symbol.toStringTag](){return"Subscription"}},I=class{subscribers=new je;errorHandler;setErrorHandler(s){this.errorHandler=s}subscribe(s,e,t=e,n){if(this.validateEventName(s),n?.once){let i=e;e=(a,u)=>{i.call(t,a,u),this.unsubscribe(o)}}let r=new Fe(t,e);this.subscribers.set(s,r);let o=new Je(s,r);return o}unsubscribe({eventName:s,contextEventHandler:e}){let t=this.subscribers.get(s)??new Set,n=t.delete(e);return n&&t.size===0&&this.subscribers.delete(s),n}publish(s,e=new CustomEvent(s),t){this.validateEventName(s),this.subscribers.get(s)?.forEach(n=>{try{n.handle(e,t)}catch(r){this.errorHandler?this.errorHandler(r,s,e,t):console.error(`Error in event handler for '${s}':`,r)}})}isSubscribed({eventName:s,contextEventHandler:e}){return this.subscribers.get(s)?.has(e)??!1}validateEventName(s){if(!s||typeof s!="string")throw new TypeError("Event name must be a non-empty string");if(s.trim()!==s)throw new Error("Event name cannot have leading or trailing whitespace")}destroy(){this.subscribers.clear()}get[Symbol.toStringTag](){return"Subscribr"}};var B=class extends Error{_entity;responseStatus;_url;_method;_timing;constructor(e,{message:t,cause:n,entity:r,url:o,method:i,timing:a}={}){super(t,{cause:n}),this._entity=r,this.responseStatus=e,this._url=o,this._method=i,this._timing=a}get entity(){return this._entity}get statusCode(){return this.responseStatus.code}get statusText(){return this.responseStatus?.text}get url(){return this._url}get method(){return this._method}get timing(){return this._timing}get name(){return"HttpError"}get[Symbol.toStringTag](){return this.name}};var w=class{_code;_text;constructor(e,t){this._code=e,this._text=t}get code(){return this._code}get text(){return this._text}get[Symbol.toStringTag](){return"ResponseStatus"}toString(){return`${this._code} ${this._text}`}};var v={charset:"utf-8"},de=/\/$/,ce="XSRF-TOKEN",pe="X-XSRF-TOKEN",m={PNG:new T("image/png"),TEXT:new T("text/plain",v),JSON:new T("application/json",v),HTML:new T("text/html",v),JAVA_SCRIPT:new T("text/javascript",v),CSS:new T("text/css",v),XML:new T("application/xml",v),BIN:new T("application/octet-stream"),EVENT_STREAM:new T("text/event-stream",v),NDJSON:new T("application/x-ndjson",v)},G=m.JSON.toString(),X=globalThis.location?.origin??"http://localhost",fe={DEFAULT:"default",FORCE_CACHE:"force-cache",NO_CACHE:"no-cache",NO_STORE:"no-store",ONLY_IF_CACHED:"only-if-cached",RELOAD:"reload"},b={CONFIGURED:"configured",SUCCESS:"success",ERROR:"error",ABORTED:"aborted",TIMEOUT:"timeout",RETRY:"retry",COMPLETE:"complete",ALL_COMPLETE:"all-complete"},P={ABORT:"abort",TIMEOUT:"timeout"},H={ABORT:"AbortError",TIMEOUT:"TimeoutError"},k={once:!0,passive:!0},L=()=>new CustomEvent(P.ABORT,{detail:{cause:H.ABORT}}),Re=()=>new CustomEvent(P.TIMEOUT,{detail:{cause:H.TIMEOUT}}),he=["POST","PUT","PATCH","DELETE"],ge=new w(500,"Internal Server Error"),me=new w(499,"Aborted"),ye=new w(504,"Request Timeout"),V=[408,413,429,500,502,503,504],z=["GET","PUT","HEAD","DELETE","OPTIONS"],N=300,D=2;var _=class{abortSignal;abortController=new AbortController;events=new Map;constructor({signal:e,timeout:t=1/0}={}){if(t<0)throw new RangeError("The timeout cannot be negative");let n=[this.abortController.signal];e!=null&&n.push(e),t!==1/0&&n.push(AbortSignal.timeout(t)),(this.abortSignal=AbortSignal.any(n)).addEventListener(P.ABORT,this,k)}handleEvent({target:{reason:e}}){this.abortController.signal.aborted||e instanceof DOMException&&e.name===H.TIMEOUT&&this.abortSignal.dispatchEvent(Re())}get signal(){return this.abortSignal}onAbort(e){return this.addEventListener(P.ABORT,e)}onTimeout(e){return this.addEventListener(P.TIMEOUT,e)}abort(e=L()){this.abortController.abort(e.detail?.cause)}destroy(){this.abortSignal.removeEventListener(P.ABORT,this,k);for(let[e,t]of this.events)this.abortSignal.removeEventListener(t,e,k);return this.events.clear(),this}addEventListener(e,t){return this.abortSignal.addEventListener(e,t,k),this.events.set(t,e),this}get[Symbol.toStringTag](){return"SignalController"}};var j,W,F=()=>j||(j=(typeof document>"u"||typeof DOMParser>"u"||typeof DocumentFragment>"u"?import("jsdom").then(({JSDOM:e})=>{let{window:t}=new e("<!DOCTYPE html><html><head></head><body></body></html>",{url:"http://localhost"});globalThis.window=t,Object.assign(globalThis,{document:t.document,DOMParser:t.DOMParser,DocumentFragment:t.DocumentFragment})}).catch(()=>{throw j=void 0,new Error("jsdom is required for HTML/XML/DOM features in Node.js environments. Install it with: npm install jsdom")}):Promise.resolve()).then(()=>import("./OP3JQ447.js")).then(({default:e})=>{W=e})),be=async(s,e)=>(await F(),new DOMParser().parseFromString(W.sanitize(await s.text()),e)),K=async(s,e)=>{await F();let t=URL.createObjectURL(await s.blob());try{return new Promise((n,r)=>e(t,n,r))}finally{URL.revokeObjectURL(t)}},Te=async s=>await s.text(),Y=s=>K(s,(e,t,n)=>{let r=document.createElement("script");Object.assign(r,{src:e,type:"text/javascript",async:!0}),r.onload=()=>{document.head.removeChild(r),t()},r.onerror=()=>{document.head.removeChild(r),n(new Error("Script failed to load"))},document.head.appendChild(r)}),Q=s=>K(s,(e,t,n)=>{let r=document.createElement("link");Object.assign(r,{href:e,type:"text/css",rel:"stylesheet"}),r.onload=()=>t(),r.onerror=()=>{document.head.removeChild(r),n(new Error("Stylesheet load failed"))},document.head.appendChild(r)}),Z=async s=>await s.json(),Ee=async s=>await s.blob(),ee=s=>K(s,(e,t,n)=>{let r=new Image;r.onload=()=>t(r),r.onerror=()=>n(new Error("Image failed to load")),r.src=e}),Se=async s=>await s.arrayBuffer(),te=async s=>Promise.resolve(s.body),se=async s=>be(s,"application/xml"),ne=async s=>be(s,"text/html"),Oe=async s=>(await F(),document.createRange().createContextualFragment(W.sanitize(await s.text()))),we=async s=>(await F(),document.createRange().createContextualFragment(await s.text()));async function*ve(s,e,t){let n=s.getReader(),r=new TextDecoder,o="";try{for(;;){let i;for(;(i=o.indexOf(e))!==-1;)yield o.slice(0,i),o=o.slice(i+e.length);let{done:a,value:u}=await n.read();if(a)break;o+=r.decode(u,{stream:!0})}if(t){let i=(o+r.decode()).trim();i&&(yield i)}}finally{await n.cancel()}}var $e=s=>{let e="message",t="",n,r=[],o=s.split(`
|
|
3
|
+
`);for(let i=0,a=o.length;i<a;i++){let u=o[i];if(u.charCodeAt(0)===58)continue;let p=u.indexOf(":"),R,d;switch(p===-1?(R=u,d=""):(R=u.slice(0,p),d=u.charCodeAt(p+1)===32?u.slice(p+2):u.slice(p+1)),R){case"event":e=d;break;case"data":r.push(d);break;case"id":t=d;break;case"retry":{let h=parseInt(d,10);isNaN(h)||(n=h);break}}}return r.length>0||e!=="message"?{event:e,data:r.join(`
|
|
4
|
+
`),id:t,retry:n}:void 0},qe=s=>({async*[Symbol.asyncIterator](){for await(let e of ve(s.body,`
|
|
3
5
|
|
|
4
|
-
|
|
5
|
-
`);for(let h=0;h<g.length;h++){let p=g[h];if(p.startsWith(":"))continue;let l=p.indexOf(":"),u,c;switch(l===-1?(u=p,c=""):(u=p.slice(0,l),c=p.slice(l+1),c.charCodeAt(0)===32&&(c=c.slice(1))),u){case"event":d.event=c;break;case"data":R.push(c);break;case"id":d.id=c;break;case"retry":{let S=parseInt(c,10);isNaN(S)||(d.retry=S);break}}}if(d.data=R.join(`
|
|
6
|
-
`),d.data||d.event!=="message")return{value:d,done:!1};continue}let i=await e.read();if(i.done){r=!0;break}n+=t.decode(i.value,{stream:!0})}return{value:void 0,done:!0}},async return(){return await e.cancel(),r=!0,{value:void 0,done:!0}}}}}),ve=s=>({[Symbol.asyncIterator](){let e=s.body.getReader(),t=new TextDecoder,n="",r=!1;return{async next(){for(;!r;){let o=n.indexOf(`
|
|
7
|
-
`);if(o!==-1){let a=n.slice(0,o).trim();if(n=n.slice(o+1),a)return{value:JSON.parse(a),done:!1};continue}let i=await e.read();if(i.done){r=!0;let a=(n+t.decode()).trim();if(n="",a)return{value:JSON.parse(a),done:!1};break}n+=t.decode(i.value,{stream:!0})}return{value:void 0,done:!0}},async return(){return await e.cancel(),r=!0,{value:void 0,done:!0}}}}});var qe=s=>s!==void 0&&he.includes(s),Pe=s=>s instanceof FormData||s instanceof Blob||s instanceof ArrayBuffer||s instanceof ReadableStream||s instanceof URLSearchParams||ArrayBuffer.isView(s),He=s=>{if(typeof document>"u"||!document.cookie)return;let e=`${s}=`,t=document.cookie.split(";");for(let n=0,r=t.length;n<r;n++){let o=t[n].trim();if(o.startsWith(e))return decodeURIComponent(o.slice(e.length))}},Ae=s=>JSON.stringify(s),J=s=>s!==null&&typeof s=="string",ke=s=>s instanceof ArrayBuffer||Object.prototype.toString.call(s)==="[object ArrayBuffer]",y=s=>s!==null&&typeof s=="object"&&!Array.isArray(s)&&Object.getPrototypeOf(s)===Object.prototype,$=(...s)=>{let e=s.length;if(e===0)return;if(e===1){let[n]=s;return y(n)?ne(n):n}let t={};for(let n of s){if(!y(n))return;for(let[r,o]of Object.entries(n)){let i=t[r];Array.isArray(o)?t[r]=[...o,...Array.isArray(i)?i.filter(a=>!o.includes(a)):[]]:y(o)?t[r]=y(i)?$(i,o):ne(o):t[r]=o}}return t};function ne(s){if(y(s)){let e={},t=Object.keys(s);for(let n=0,r=t.length,o;n<r;n++)o=t[n],e[o]=ne(s[o]);return e}return s}var Be=class s{_baseUrl;_options;subscribr;hooks={beforeRequest:[],afterResponse:[],beforeError:[]};static globalSubscribr=new M;static globalHooks={beforeRequest:[],afterResponse:[],beforeError:[]};static signalControllers=new Set;static inflightRequests=new Map;static mediaTypeCache=new Map(Object.values(m).map(e=>[e.toString(),e]));static contentTypeHandlers=[[m.TEXT.type,be],[m.JSON.subtype,Q],[m.BIN.subtype,ee],[m.HTML.subtype,se],[m.XML.subtype,te],[m.PNG.type,Z],[m.JAVA_SCRIPT.subtype,K],[m.CSS.subtype,Y]];constructor(e=V,t={}){y(e)&&([e,t]=[V,e]),this._baseUrl=s.getBaseUrl(e),this._options=s.createOptions(t,s.defaultRequestOptions),this.subscribr=new M}static CredentialsPolicy={INCLUDE:"include",OMIT:"omit",SAME_ORIGIN:"same-origin"};static RequestMode={CORS:"cors",NAVIGATE:"navigate",NO_CORS:"no-cors",SAME_ORIGIN:"same-origin"};static RequestPriority={HIGH:"high",LOW:"low",AUTO:"auto"};static RedirectPolicy={ERROR:"error",FOLLOW:"follow",MANUAL:"manual"};static ReferrerPolicy={NO_REFERRER:"no-referrer",NO_REFERRER_WHEN_DOWNGRADE:"no-referrer-when-downgrade",ORIGIN:"origin",ORIGIN_WHEN_CROSS_ORIGIN:"origin-when-cross-origin",SAME_ORIGIN:"same-origin",STRICT_ORIGIN:"strict-origin",STRICT_ORIGIN_WHEN_CROSS_ORIGIN:"strict-origin-when-cross-origin",UNSAFE_URL:"unsafe-url"};static RequestEvent=b;static defaultRequestOptions={body:void 0,cache:fe.NO_STORE,credentials:s.CredentialsPolicy.SAME_ORIGIN,headers:new Headers({"content-type":X,accept:X}),searchParams:void 0,integrity:void 0,keepalive:void 0,method:"GET",mode:s.RequestMode.CORS,priority:s.RequestPriority.AUTO,redirect:s.RedirectPolicy.FOLLOW,referrer:"about:client",referrerPolicy:s.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN,signal:void 0,timeout:3e4,global:!0};static register(e,t,n){return s.globalSubscribr.subscribe(e,t,n)}static unregister(e){return s.globalSubscribr.unsubscribe(e)}static abortAll(){for(let e of this.signalControllers)e.abort(N());this.signalControllers.clear()}static all(e){return Promise.all(e)}static async race(e){let t=[],n=new Array(e.length);for(let r=0;r<e.length;r++){let o=new AbortController;t.push(o),n[r]=e[r](o.signal)}try{return await Promise.race(n)}finally{for(let r of t)r.abort()}}static registerContentTypeHandler(e,t){s.contentTypeHandlers.unshift([e,t])}static unregisterContentTypeHandler(e){let t=s.contentTypeHandlers.findIndex(([n])=>n===e);return t===-1?!1:(s.contentTypeHandlers.splice(t,1),!0)}static addHooks(e){e.beforeRequest&&s.globalHooks.beforeRequest.push(...e.beforeRequest),e.afterResponse&&s.globalHooks.afterResponse.push(...e.afterResponse),e.beforeError&&s.globalHooks.beforeError.push(...e.beforeError)}static clearHooks(){s.globalHooks={beforeRequest:[],afterResponse:[],beforeError:[]}}static unregisterAll(){s.abortAll(),s.globalSubscribr=new M,s.clearHooks(),s.inflightRequests.clear()}get baseUrl(){return this._baseUrl}register(e,t,n){return this.subscribr.subscribe(e,t,n)}unregister(e){return this.subscribr.unsubscribe(e)}addHooks(e){return e.beforeRequest&&this.hooks.beforeRequest.push(...e.beforeRequest),e.afterResponse&&this.hooks.afterResponse.push(...e.afterResponse),e.beforeError&&this.hooks.beforeError.push(...e.beforeError),this}clearHooks(){return this.hooks.beforeRequest.length=0,this.hooks.afterResponse.length=0,this.hooks.beforeError.length=0,this}configure({headers:e,searchParams:t,hooks:n,...r}){return e&&s.mergeHeaders(this._options.headers,e),t&&s.mergeSearchParams(this._options.searchParams,t),Object.keys(r).length>0&&Object.assign(this._options,r),n&&this.addHooks(n),this}destroy(){this.clearHooks(),this.subscribr.destroy()}async get(e,t){return this._get(e,t)}async post(e,t,n){return this.executeBodyMethod("POST",e,t,n)}async put(e,t,n){return this.executeBodyMethod("PUT",e,t,n)}async patch(e,t,n){return this.executeBodyMethod("PATCH",e,t,n)}async delete(e,t,n){return this.executeBodyMethod("DELETE",e,t,n)}async head(e,t){return this.execute(e,t,{method:"HEAD"})}async options(e,t={}){y(e)&&([e,t]=[void 0,e]);let n=this.processRequestOptions(t,{method:"OPTIONS"}),{requestOptions:r}=n,o=r.unwrap!==!1,i=r.hooks;try{let a=s.createUrl(this._baseUrl,e,r.searchParams),d=[s.globalHooks.beforeRequest,this.hooks.beforeRequest,i?.beforeRequest];for(let p of d)if(p)for(let l of p){let u=await l(r,a);u&&(Object.assign(r,u),u.searchParams!==void 0&&(a=s.createUrl(this._baseUrl,e,r.searchParams)))}let R=await this._request(e,n),g=[s.globalHooks.afterResponse,this.hooks.afterResponse,i?.afterResponse];for(let p of g)if(p)for(let l of p){let u=await l(R,r);u&&(R=u)}let h=R.headers.get("allow")?.split(",").map(p=>p.trim());return this.publish({name:b.SUCCESS,data:h,global:t.global}),o?h:[!0,h]}catch(a){if(!o)return[!1,a];throw a}}async request(e,t={}){y(e)&&([e,t]=[void 0,e]);let n=this.processRequestOptions(t,{}),r=n.requestOptions.unwrap!==!1;try{let o=await this._request(e,n);return this.publish({name:b.SUCCESS,data:o,global:t.global}),r?o:[!0,o]}catch(o){if(!r)return[!1,o];throw o}}async getJson(e,t){return this._get(e,t,{headers:{accept:`${m.JSON}`}},Q)}async getXml(e,t){return this._get(e,t,{headers:{accept:`${m.XML}`}},te)}async getHtml(e,t,n){let r=await this._get(e,t,{headers:{accept:`${m.HTML}`}},se);return Array.isArray(r)?r:n&&r?r.querySelector(n):r}async getHtmlFragment(e,t,n){let r=(y(e)?e:t)?.allowScripts===!0,o=await this._get(e,t,{headers:{accept:`${m.HTML}`}},r?Oe:Se);return Array.isArray(o)?o:n&&o?o.querySelector(n):o}async getScript(e,t){return this._get(e,t,{headers:{accept:`${m.JAVA_SCRIPT}`}},K)}async getStylesheet(e,t){return this._get(e,t,{headers:{accept:`${m.CSS}`}},Y)}async getBlob(e,t){return this._get(e,t,{headers:{accept:"application/octet-stream"}},Te)}async getImage(e,t){return this._get(e,t,{headers:{accept:"image/*"}},Z)}async getBuffer(e,t){return this._get(e,t,{headers:{accept:"application/octet-stream"}},Ee)}async getStream(e,t){return this._get(e,t,{headers:{accept:"application/octet-stream"}},ee)}async getEventStream(e,t){y(e)&&([e,t]=[void 0,e]);let n=this.processRequestOptions(t??{},{method:t?.body?"POST":"GET",headers:{accept:`${m.EVENT_STREAM}`}}),{requestOptions:r}=n,o=r.unwrap!==!1,i=r.hooks;try{let a=s.createUrl(this._baseUrl,e,r.searchParams),d=[s.globalHooks.beforeRequest,this.hooks.beforeRequest,i?.beforeRequest];for(let l of d)if(l)for(let u of l){let c=await u(r,a);c&&(Object.assign(r,c),c.searchParams!==void 0&&(a=s.createUrl(this._baseUrl,e,r.searchParams)))}let g=await this._request(e,n),h=[s.globalHooks.afterResponse,this.hooks.afterResponse,i?.afterResponse];for(let l of h)if(l)for(let u of l){let c=await u(g,r);c&&(g=c)}this.publish({name:b.SUCCESS,data:g,global:n.global});let p=we(g);return o?p:[!0,p]}catch(a){if(!o)return[!1,a];throw a}}async getJsonStream(e,t){y(e)&&([e,t]=[void 0,e]);let n=this.processRequestOptions(t??{},{method:"GET",headers:{accept:`${m.NDJSON}`}}),{requestOptions:r}=n,o=r.unwrap!==!1,i=r.hooks;try{let a=s.createUrl(this._baseUrl,e,r.searchParams),d=[s.globalHooks.beforeRequest,this.hooks.beforeRequest,i?.beforeRequest];for(let l of d)if(l)for(let u of l){let c=await u(r,a);c&&(Object.assign(r,c),c.searchParams!==void 0&&(a=s.createUrl(this._baseUrl,e,r.searchParams)))}let g=await this._request(e,n),h=[s.globalHooks.afterResponse,this.hooks.afterResponse,i?.afterResponse];for(let l of h)if(l)for(let u of l){let c=await u(g,r);c&&(g=c)}this.publish({name:b.SUCCESS,data:g,global:n.global});let p=ve(g);return o?p:[!0,p]}catch(a){if(!o)return[!1,a];throw a}}async _get(e,t,n={},r){return this.execute(e,t,{...n,method:"GET",body:void 0},r)}async _request(e,{signalController:t,requestOptions:n,global:r}){s.signalControllers.add(t);let o=s.normalizeRetryOptions(n.retry),i=n.method??"GET",a=o.limit>0&&o.methods.includes(i),d=n.dedupe===!0&&(i==="GET"||i==="HEAD"),R=0,g=performance.now(),h=()=>{let p=performance.now();return{start:g,end:p,duration:p-g}};try{let p=s.createUrl(this._baseUrl,e,n.searchParams),l=d?`${i}:${p.href}`:"";if(d){let f=s.inflightRequests.get(l);if(f)return(await f).clone()}let u=n.body,c=n.onUploadProgress,S=async()=>{if(!c||u==null)return;let f=null;if(typeof u=="string")f=new TextEncoder().encode(u);else if(u instanceof Blob)f=new Uint8Array(await u.arrayBuffer());else if(ke(u))f=new Uint8Array(u);else if(ArrayBuffer.isView(u))f=new Uint8Array(u.buffer,u.byteOffset,u.byteLength);else if(!(u instanceof ReadableStream))return;let E=f?f.byteLength:null,L=f?new ReadableStream({start(P){P.enqueue(f),P.close()}}):u,O=0,C=new TransformStream({transform(P,G){O+=P.byteLength,c({loaded:O,total:E,percentage:E!==null&&E>0?Math.round(O/E*100):null}),G.enqueue(P)}});n.body=L.pipeThrough(C),Object.assign(n,{duplex:"half"})},re=async()=>{for(;;)try{await S();let f=await fetch(p,n);if(!f.ok){if(a&&R<o.limit&&o.statusCodes.includes(f.status)){R++,this.publish({name:b.RETRY,data:{attempt:R,status:f.status,method:i,path:e,timing:h()},global:r}),await s.retryDelay(o,R);continue}let E;try{E=await f.text()}catch{}throw await this.handleError(e,f,{entity:E,url:p,method:i,timing:h()},n)}return f}catch(f){if(f instanceof B)throw f;if(a&&R<o.limit){R++,this.publish({name:b.RETRY,data:{attempt:R,error:f.message,method:i,path:e,timing:h()},global:r}),await s.retryDelay(o,R);continue}throw await this.handleError(e,void 0,{cause:f,url:p,method:i,timing:h()},n)}},oe=f=>{let E=n.onDownloadProgress;if(!E||!f.body)return f;let L=f.headers.get("content-length"),O=L?parseInt(L,10):null,C=0,P=new TransformStream({transform(ie,Ce){C+=ie.byteLength,E({loaded:C,total:O,percentage:O!==null&&O>0?Math.round(C/O*100):null}),Ce.enqueue(ie)}}),G=f.body.pipeThrough(P);return new Response(G,{status:f.status,statusText:f.statusText,headers:f.headers})};if(d){let f=re();s.inflightRequests.set(l,f);try{let E=await f;return oe(E)}finally{s.inflightRequests.delete(l)}}return oe(await re())}finally{if(s.signalControllers.delete(t.destroy()),!n.signal?.aborted){let p=h();this.publish({name:b.COMPLETE,data:{timing:p},global:r}),s.signalControllers.size===0&&this.publish({name:b.ALL_COMPLETE,global:r})}}}static normalizeRetryOptions(e){return e===void 0?{limit:0,statusCodes:[],methods:[],delay:D,backoffFactor:_}:typeof e=="number"?{limit:e,statusCodes:[...z],methods:[...W],delay:D,backoffFactor:_}:{limit:e.limit??0,statusCodes:e.statusCodes??[...z],methods:e.methods??[...W],delay:e.delay??D,backoffFactor:e.backoffFactor??_}}static retryDelay(e,t){let n=typeof e.delay=="function"?e.delay(t):e.delay*e.backoffFactor**(t-1);return new Promise(r=>setTimeout(r,n))}executeBodyMethod(e,t,n,r,o){let[i,a,d]=J(t)?[t,n,r]:[void 0,t,n];return this.execute(i,Object.assign(d??{},{body:a,method:e}),{},o)}async execute(e,t={},n={},r){y(e)&&([e,t]=[void 0,e]);let o=this.processRequestOptions(t,n),{requestOptions:i}=o,a=i.unwrap!==!1,d=i.hooks;try{let R=s.createUrl(this._baseUrl,e,i.searchParams),g=[s.globalHooks.beforeRequest,this.hooks.beforeRequest,d?.beforeRequest];for(let l of g)if(l)for(let u of l){let c=await u(i,R);c&&(Object.assign(i,c),c.searchParams!==void 0&&(R=s.createUrl(this._baseUrl,e,i.searchParams)))}let h=await this._request(e,o),p=[s.globalHooks.afterResponse,this.hooks.afterResponse,d?.afterResponse];for(let l of p)if(l)for(let u of l){let c=await u(h,i);c&&(h=c)}try{!r&&h.status!==204&&(r=this.getResponseHandler(h.headers.get("content-type")));let l=await r?.(h);return this.publish({name:b.SUCCESS,data:l,global:o.global}),a?l:[!0,l]}catch(l){throw await this.handleError(e,h,{cause:l},i)}}catch(R){if(!a)return[!1,R];throw R}}static createOptions({headers:e,searchParams:t,...n},{headers:r,searchParams:o,...i}){return r=s.mergeHeaders(new Headers,e,r),o=s.mergeSearchParams(new URLSearchParams,t,o),{...$(i,n),headers:r,searchParams:o}}static mergeHeaders(e,...t){for(let n of t)if(n!==void 0){if(n instanceof Headers)n.forEach((r,o)=>e.set(o,r));else if(Array.isArray(n))for(let[r,o]of n)e.set(r,o);else if(y(n))for(let[r,o]of Object.entries(n))o!==void 0&&e.set(r,o)}return e}static mergeSearchParams(e,...t){for(let n of t)if(n!==void 0)if(n instanceof URLSearchParams)n.forEach((r,o)=>e.set(o,r));else if(J(n)||Array.isArray(n))for(let[r,o]of new URLSearchParams(n))e.set(r,o);else{let r=Object.keys(n);for(let o=0;o<r.length;o++){let i=r[o],a=n[i];a!==void 0&&e.set(i,String(a))}}return e}processRequestOptions({body:e,headers:t,searchParams:n,...r},{headers:o,searchParams:i,...a}){let d={...this._options,...r,...a,headers:s.mergeHeaders(new Headers,this._options.headers,t,o),searchParams:s.mergeSearchParams(new URLSearchParams,this._options.searchParams,n,i)};if(qe(d.method))if(Pe(e))Object.assign(d,{body:e}),d.headers.delete("content-type");else{let u=this._options.body,c=y(u)&&y(e)?$(u,e):e!==void 0?e:u,S=d.headers.get("content-type")?.includes("json")??!1;Object.assign(d,{body:S&&y(c)?Ae(c):c})}else d.headers.delete("content-type"),d.body instanceof URLSearchParams&&s.mergeSearchParams(d.searchParams,d.body),d.body=void 0;let{signal:R,timeout:g,global:h=!1,xsrf:p}=d;if(p){let{cookieName:u,headerName:c}=typeof p=="object"?p:{},S=He(u??ce);S&&d.headers.set(c??pe,S)}let l=new j({signal:R,timeout:g}).onAbort(u=>this.publish({name:b.ABORTED,event:u,global:h})).onTimeout(u=>this.publish({name:b.TIMEOUT,event:u,global:h}));return d.signal=l.signal,this.publish({name:b.CONFIGURED,data:d,global:h}),{signalController:l,requestOptions:d,global:h}}static getBaseUrl(e){if(e instanceof URL)return e;if(!J(e))throw new TypeError("Invalid URL");return new URL(e,e.startsWith("/")?globalThis.location.origin:void 0)}static getOrParseMediaType(e){if(e===null)return;let t=s.mediaTypeCache.get(e);if(t!==void 0)return t;if(t=T.parse(e)??void 0,t!==void 0){if(s.mediaTypeCache.size>=100){let n=s.mediaTypeCache.keys().next();n.done||s.mediaTypeCache.delete(n.value)}s.mediaTypeCache.set(e,t)}return t}static createUrl(e,t,n){let r=t?new URL(`${e.pathname.replace(le,"")}${t}`,e.origin):new URL(e);return n&&s.mergeSearchParams(r.searchParams,n),r}static generateResponseStatusFromError(e,{status:t,statusText:n}=new Response){switch(e){case A.ABORT:return me;case A.TIMEOUT:return ye;default:return t>=400?new v(t,n):ge}}async handleError(e,t,{cause:n,entity:r,url:o,method:i,timing:a}={},d){let R=i&&o?`${i} ${o.href} failed${t?` with status ${t.status}`:""}`:`An error has occurred with your request to: '${e}'`,g=new B(s.generateResponseStatusFromError(n?.name,t),{message:R,cause:n,entity:r,url:o,method:i,timing:a}),h=[s.globalHooks.beforeError,this.hooks.beforeError,d?.hooks?.beforeError];for(let p of h)if(p)for(let l of p){let u=await l(g);u instanceof B&&(g=u)}return this.publish({name:b.ERROR,data:g}),g}publish({name:e,event:t=new CustomEvent(e),data:n,global:r=!0}){r&&s.globalSubscribr.publish(e,t,n),this.subscribr.publish(e,t,n)}getResponseHandler(e){if(!e)return;let t=s.getOrParseMediaType(e);if(t){for(let[n,r]of s.contentTypeHandlers)if(t.matches(n))return r}}get[Symbol.toStringTag](){return"Transportr"}};export{Be as Transportr};
|
|
6
|
+
`,!1)){if(!e)continue;let t=$e(e);t&&(yield t)}}}),Pe=s=>({async*[Symbol.asyncIterator](){for await(let e of ve(s.body,`
|
|
7
|
+
`,!0)){let t=e.trim();t&&(yield JSON.parse(t))}}});var He=s=>s!==void 0&&he.includes(s),Ae=s=>s instanceof FormData||s instanceof Blob||s instanceof ArrayBuffer||s instanceof ReadableStream||s instanceof URLSearchParams||ArrayBuffer.isView(s),Be=s=>{if(typeof document>"u"||!document.cookie)return;let e=`${s}=`,t=document.cookie.split(";");for(let n=0,r=t.length;n<r;n++){let o=t[n].trim();if(o.startsWith(e))return decodeURIComponent(o.slice(e.length))}},Ce=s=>JSON.stringify(s),J=s=>s!==null&&typeof s=="string",ke=s=>s instanceof ArrayBuffer||Object.prototype.toString.call(s)==="[object ArrayBuffer]",y=s=>s!==null&&typeof s=="object"&&!Array.isArray(s)&&Object.getPrototypeOf(s)===Object.prototype,$=(...s)=>{let e=s.length;if(e===0)return;if(e===1){let[n]=s;return y(n)?re(n):n}let t={};for(let n of s){if(!y(n))return;for(let[r,o]of Object.entries(n)){let i=t[r];Array.isArray(o)?t[r]=[...o,...Array.isArray(i)?i.filter(a=>!o.includes(a)):[]]:y(o)?t[r]=y(i)?$(i,o):re(o):t[r]=o}}return t};function re(s){if(y(s)){let e={},t=Object.keys(s);for(let n=0,r=t.length,o;n<r;n++)o=t[n],e[o]=re(s[o]);return e}return s}var xe=class s{_baseUrl;_options;subscribr;hooks={beforeRequest:[],afterResponse:[],beforeError:[]};static globalSubscribr=new I;static globalHooks={beforeRequest:[],afterResponse:[],beforeError:[]};static signalControllers=new Set;static inflightRequests=new Map;static noRetryConfig={limit:0,statusCodes:[],methods:[],delay:N,backoffFactor:D};static mediaTypeCache=new Map(Object.values(m).map(e=>[e.toString(),e]));static contentTypeHandlers=[[m.TEXT.type,Te],[m.JSON.subtype,Z],[m.BIN.subtype,te],[m.HTML.subtype,ne],[m.XML.subtype,se],[m.PNG.type,ee],[m.JAVA_SCRIPT.subtype,Y],[m.CSS.subtype,Q]];constructor(e=X,t={}){y(e)&&([e,t]=[X,e]),this._baseUrl=s.getBaseUrl(e),this._options=s.createOptions(t,s.defaultRequestOptions),this.subscribr=new I}static CredentialsPolicy={INCLUDE:"include",OMIT:"omit",SAME_ORIGIN:"same-origin"};static RequestMode={CORS:"cors",NAVIGATE:"navigate",NO_CORS:"no-cors",SAME_ORIGIN:"same-origin"};static RequestPriority={HIGH:"high",LOW:"low",AUTO:"auto"};static RedirectPolicy={ERROR:"error",FOLLOW:"follow",MANUAL:"manual"};static ReferrerPolicy={NO_REFERRER:"no-referrer",NO_REFERRER_WHEN_DOWNGRADE:"no-referrer-when-downgrade",ORIGIN:"origin",ORIGIN_WHEN_CROSS_ORIGIN:"origin-when-cross-origin",SAME_ORIGIN:"same-origin",STRICT_ORIGIN:"strict-origin",STRICT_ORIGIN_WHEN_CROSS_ORIGIN:"strict-origin-when-cross-origin",UNSAFE_URL:"unsafe-url"};static RequestEvent=b;static defaultRequestOptions={body:void 0,cache:fe.NO_STORE,credentials:s.CredentialsPolicy.SAME_ORIGIN,headers:new Headers({"content-type":G,accept:G}),searchParams:void 0,integrity:void 0,keepalive:void 0,method:"GET",mode:s.RequestMode.CORS,priority:s.RequestPriority.AUTO,redirect:s.RedirectPolicy.FOLLOW,referrer:"about:client",referrerPolicy:s.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN,signal:void 0,timeout:3e4,global:!0};static register(e,t,n){return s.globalSubscribr.subscribe(e,t,n)}static unregister(e){return s.globalSubscribr.unsubscribe(e)}static abortAll(){for(let e of this.signalControllers)e.abort(L());this.signalControllers.clear()}static all(e){return Promise.all(e)}static async race(e){let t=[],n=new Array(e.length);for(let r=0;r<e.length;r++){let o=new AbortController;t.push(o),n[r]=e[r](o.signal)}try{return await Promise.race(n)}finally{for(let r of t)r.abort()}}static registerContentTypeHandler(e,t){s.contentTypeHandlers.unshift([e,t])}static unregisterContentTypeHandler(e){let t=s.contentTypeHandlers.findIndex(([n])=>n===e);return t===-1?!1:(s.contentTypeHandlers.splice(t,1),!0)}static addHooks(e){e.beforeRequest&&s.globalHooks.beforeRequest.push(...e.beforeRequest),e.afterResponse&&s.globalHooks.afterResponse.push(...e.afterResponse),e.beforeError&&s.globalHooks.beforeError.push(...e.beforeError)}static clearHooks(){s.globalHooks={beforeRequest:[],afterResponse:[],beforeError:[]}}static unregisterAll(){s.abortAll(),s.globalSubscribr=new I,s.clearHooks(),s.inflightRequests.clear()}get baseUrl(){return this._baseUrl}register(e,t,n){return this.subscribr.subscribe(e,t,n)}unregister(e){return this.subscribr.unsubscribe(e)}addHooks(e){return e.beforeRequest&&this.hooks.beforeRequest.push(...e.beforeRequest),e.afterResponse&&this.hooks.afterResponse.push(...e.afterResponse),e.beforeError&&this.hooks.beforeError.push(...e.beforeError),this}clearHooks(){return this.hooks.beforeRequest.length=0,this.hooks.afterResponse.length=0,this.hooks.beforeError.length=0,this}configure({headers:e,searchParams:t,hooks:n,...r}){return e&&s.mergeHeaders(this._options.headers,e),t&&s.mergeSearchParams(this._options.searchParams,t),Object.keys(r).length>0&&Object.assign(this._options,r),n&&this.addHooks(n),this}destroy(){this.clearHooks(),this.subscribr.destroy()}async get(e,t){return this._get(e,t)}async post(e,t,n){return this.executeBodyMethod("POST",e,t,n)}async put(e,t,n){return this.executeBodyMethod("PUT",e,t,n)}async patch(e,t,n){return this.executeBodyMethod("PATCH",e,t,n)}async delete(e,t,n){return this.executeBodyMethod("DELETE",e,t,n)}async head(e,t){return this.execute(e,t,{method:"HEAD"})}async options(e,t={}){y(e)&&([e,t]=[void 0,e]);let n=this.processRequestOptions(t,{method:"OPTIONS"}),{requestOptions:r}=n,o=r.unwrap!==!1,i=r.hooks;try{let a=s.createUrl(this._baseUrl,e,r.searchParams),u=[s.globalHooks.beforeRequest,this.hooks.beforeRequest,i?.beforeRequest];for(let c of u)if(c)for(let l of c){let g=await l(r,a);g&&(Object.assign(r,g),g.searchParams!==void 0&&(a=s.createUrl(this._baseUrl,e,r.searchParams)))}let p=await this._request(e,n),R=[s.globalHooks.afterResponse,this.hooks.afterResponse,i?.afterResponse];for(let c of R)if(c)for(let l of c){let g=await l(p,r);g&&(p=g)}let d=p.headers.get("allow"),h;if(d){let c=d.split(",");h=new Array(c.length);for(let l=0,g=c.length;l<g;l++)h[l]=c[l].trim()}return this.publish({name:b.SUCCESS,data:h,global:t.global}),o?h:[!0,h]}catch(a){if(!o)return[!1,a];throw a}}async request(e,t={}){y(e)&&([e,t]=[void 0,e]);let n=this.processRequestOptions(t,{}),r=n.requestOptions.unwrap!==!1;try{let o=await this._request(e,n);return this.publish({name:b.SUCCESS,data:o,global:t.global}),r?o:[!0,o]}catch(o){if(!r)return[!1,o];throw o}}async getJson(e,t){return this._get(e,t,{headers:{accept:`${m.JSON}`}},Z)}async getXml(e,t){return this._get(e,t,{headers:{accept:`${m.XML}`}},se)}async getHtml(e,t,n){let r=await this._get(e,t,{headers:{accept:`${m.HTML}`}},ne);return Array.isArray(r)?r:n&&r?r.querySelector(n):r}async getHtmlFragment(e,t,n){let r=(y(e)?e:t)?.allowScripts===!0,o=await this._get(e,t,{headers:{accept:`${m.HTML}`}},r?we:Oe);return Array.isArray(o)?o:n&&o?o.querySelector(n):o}async getScript(e,t){return this._get(e,t,{headers:{accept:`${m.JAVA_SCRIPT}`}},Y)}async getStylesheet(e,t){return this._get(e,t,{headers:{accept:`${m.CSS}`}},Q)}async getBlob(e,t){return this._get(e,t,{headers:{accept:"application/octet-stream"}},Ee)}async getImage(e,t){return this._get(e,t,{headers:{accept:"image/*"}},ee)}async getBuffer(e,t){return this._get(e,t,{headers:{accept:"application/octet-stream"}},Se)}async getStream(e,t){return this._get(e,t,{headers:{accept:"application/octet-stream"}},te)}async getEventStream(e,t){y(e)&&([e,t]=[void 0,e]);let n=this.processRequestOptions(t??{},{method:t?.body?"POST":"GET",headers:{accept:`${m.EVENT_STREAM}`}}),{requestOptions:r}=n,o=r.unwrap!==!1,i=r.hooks;try{let a=s.createUrl(this._baseUrl,e,r.searchParams),u=[s.globalHooks.beforeRequest,this.hooks.beforeRequest,i?.beforeRequest];for(let c of u)if(c)for(let l of c){let g=await l(r,a);g&&(Object.assign(r,g),g.searchParams!==void 0&&(a=s.createUrl(this._baseUrl,e,r.searchParams)))}let R=await this._request(e,n),d=[s.globalHooks.afterResponse,this.hooks.afterResponse,i?.afterResponse];for(let c of d)if(c)for(let l of c){let g=await l(R,r);g&&(R=g)}this.publish({name:b.SUCCESS,data:R,global:n.global});let h=qe(R);return o?h:[!0,h]}catch(a){if(!o)return[!1,a];throw a}}async getJsonStream(e,t){y(e)&&([e,t]=[void 0,e]);let n=this.processRequestOptions(t??{},{method:"GET",headers:{accept:`${m.NDJSON}`}}),{requestOptions:r}=n,o=r.unwrap!==!1,i=r.hooks;try{let a=s.createUrl(this._baseUrl,e,r.searchParams),u=[s.globalHooks.beforeRequest,this.hooks.beforeRequest,i?.beforeRequest];for(let c of u)if(c)for(let l of c){let g=await l(r,a);g&&(Object.assign(r,g),g.searchParams!==void 0&&(a=s.createUrl(this._baseUrl,e,r.searchParams)))}let R=await this._request(e,n),d=[s.globalHooks.afterResponse,this.hooks.afterResponse,i?.afterResponse];for(let c of d)if(c)for(let l of c){let g=await l(R,r);g&&(R=g)}this.publish({name:b.SUCCESS,data:R,global:n.global});let h=Pe(R);return o?h:[!0,h]}catch(a){if(!o)return[!1,a];throw a}}async _get(e,t,n={},r){return n.method="GET",n.body=void 0,this.execute(e,t,n,r)}async _request(e,{signalController:t,requestOptions:n,global:r}){s.signalControllers.add(t);let o=s.normalizeRetryOptions(n.retry),i=n.method??"GET",a=o.limit>0&&o.methods.includes(i),u=n.dedupe===!0&&(i==="GET"||i==="HEAD"),p=0,R=performance.now(),d=()=>{let h=performance.now();return{start:R,end:h,duration:h-R}};try{let h=s.createUrl(this._baseUrl,e,n.searchParams),c;if(u){c=`${i}:${h.href}`;let f=s.inflightRequests.get(c);if(f)return(await f).clone()}let l=n.body,g=n.onUploadProgress,A=async()=>{if(!g||l==null)return;let f=null;if(typeof l=="string")f=new TextEncoder().encode(l);else if(l instanceof Blob)f=new Uint8Array(await l.arrayBuffer());else if(ke(l))f=new Uint8Array(l);else if(ArrayBuffer.isView(l))f=new Uint8Array(l.buffer,l.byteOffset,l.byteLength);else if(!(l instanceof ReadableStream))return;let E=f?f.byteLength:null,x=f?new ReadableStream({start(q){q.enqueue(f),q.close()}}):l,S=0,C=new TransformStream({transform(q,U){S+=q.byteLength,g({loaded:S,total:E,percentage:E!==null&&E>0?Math.round(S/E*100):null}),U.enqueue(q)}});n.body=x.pipeThrough(C),Object.assign(n,{duplex:"half"})},oe=async()=>{for(;;)try{await A();let f=await fetch(h,n);if(!f.ok){if(a&&p<o.limit&&o.statusCodes.includes(f.status)){p++,this.publish({name:b.RETRY,data:{attempt:p,status:f.status,method:i,path:e,timing:d()},global:r}),await s.retryDelay(o,p);continue}let E;try{E=await f.text()}catch{}throw await this.handleError(e,f,{entity:E,url:h,method:i,timing:d()},n)}return f}catch(f){if(f instanceof B)throw f;if(a&&p<o.limit){p++,this.publish({name:b.RETRY,data:{attempt:p,error:f.message,method:i,path:e,timing:d()},global:r}),await s.retryDelay(o,p);continue}throw await this.handleError(e,void 0,{cause:f,url:h,method:i,timing:d()},n)}},ie=f=>{let E=n.onDownloadProgress;if(!E||!f.body)return f;let x=f.headers.get("content-length"),S=x?parseInt(x,10):null,C=0,q=new TransformStream({transform(U,Ue){C+=U.byteLength,E({loaded:C,total:S,percentage:S!==null&&S>0?Math.round(C/S*100):null}),Ue.enqueue(U)}});return new Response(f.body.pipeThrough(q),{status:f.status,statusText:f.statusText,headers:f.headers})};if(u){let f=oe();s.inflightRequests.set(c,f);try{return ie(await f)}finally{s.inflightRequests.delete(c)}}return ie(await oe())}finally{s.signalControllers.delete(t.destroy()),n.signal?.aborted||(this.publish({name:b.COMPLETE,data:{timing:d()},global:r}),s.signalControllers.size===0&&this.publish({name:b.ALL_COMPLETE,global:r}))}}static normalizeRetryOptions(e){return e===void 0?s.noRetryConfig:typeof e=="number"?{limit:e,statusCodes:V,methods:z,delay:N,backoffFactor:D}:{limit:e.limit??0,statusCodes:e.statusCodes??V,methods:e.methods??z,delay:e.delay??N,backoffFactor:e.backoffFactor??D}}static retryDelay(e,t){let n=typeof e.delay=="function"?e.delay(t):e.delay*e.backoffFactor**(t-1);return new Promise(r=>setTimeout(r,n))}executeBodyMethod(e,t,n,r,o){let[i,a,u]=J(t)?[t,n,r]:[void 0,t,n];return this.execute(i,Object.assign(u??{},{body:a,method:e}),{},o)}async execute(e,t={},n={},r){y(e)&&([e,t]=[void 0,e]);let o=this.processRequestOptions(t,n),{requestOptions:i}=o,a=i.unwrap!==!1,u=i.hooks;try{let p=s.createUrl(this._baseUrl,e,i.searchParams);for(let d of[s.globalHooks.beforeRequest,this.hooks.beforeRequest,u?.beforeRequest])if(d)for(let h of d){let c=await h(i,p);c&&(Object.assign(i,c),c.searchParams!==void 0&&(p=s.createUrl(this._baseUrl,e,i.searchParams)))}let R=await this._request(e,o);for(let d of[s.globalHooks.afterResponse,this.hooks.afterResponse,u?.afterResponse])if(d)for(let h of d){let c=await h(R,i);c&&(R=c)}try{!r&&R.status!==204&&(r=this.getResponseHandler(R.headers.get("content-type")));let d=await r?.(R);return this.publish({name:b.SUCCESS,data:d,global:o.global}),a?d:[!0,d]}catch(d){throw await this.handleError(e,R,{cause:d},i)}}catch(p){if(!a)return[!1,p];throw p}}static createOptions({headers:e,searchParams:t,...n},{headers:r,searchParams:o,...i}){return r=s.mergeHeaders(new Headers,e,r),o=s.mergeSearchParams(new URLSearchParams,t,o),{...$(i,n),headers:r,searchParams:o}}static mergeHeaders(e,...t){for(let n of t)if(n!==void 0)if(n instanceof Headers)n.forEach((r,o)=>e.set(o,r));else if(Array.isArray(n))for(let[r,o]of n)e.set(r,o);else{let r=Object.keys(n);for(let o=0,i=r.length;o<i;o++){let a=r[o],u=n[a];u!==void 0&&e.set(a,u)}}return e}static mergeSearchParams(e,...t){for(let n of t)if(n!==void 0)if(n instanceof URLSearchParams)n.forEach((r,o)=>e.set(o,r));else if(J(n)||Array.isArray(n))for(let[r,o]of new URLSearchParams(n))e.set(r,o);else{let r=Object.keys(n);for(let o=0;o<r.length;o++){let i=r[o],a=n[i];a!==void 0&&e.set(i,typeof a=="string"?a:String(a))}}return e}processRequestOptions({body:e,headers:t,searchParams:n,...r},{headers:o,searchParams:i,...a}){let u={...this._options,...r,...a,headers:s.mergeHeaders(new Headers(this._options.headers),t,o),searchParams:s.mergeSearchParams(new URLSearchParams(this._options.searchParams),n,i)};if(He(u.method))if(Ae(e))Object.assign(u,{body:e}),u.headers.delete("content-type");else{let l=this._options.body,g=y(l)&&y(e)?$(l,e):e!==void 0?e:l,A=u.headers.get("content-type")?.includes("json")??!1;Object.assign(u,{body:A&&y(g)?Ce(g):g})}else u.headers.delete("content-type"),u.body instanceof URLSearchParams&&s.mergeSearchParams(u.searchParams,u.body),u.body=void 0;let{signal:p,timeout:R,global:d=!1,xsrf:h}=u;if(h){let{cookieName:l,headerName:g}=typeof h=="object"?h:{},A=Be(l??ce);A&&u.headers.set(g??pe,A)}let c=new _({signal:p,timeout:R}).onAbort(l=>this.publish({name:b.ABORTED,event:l,global:d})).onTimeout(l=>this.publish({name:b.TIMEOUT,event:l,global:d}));return u.signal=c.signal,this.publish({name:b.CONFIGURED,data:u,global:d}),{signalController:c,requestOptions:u,global:d}}static getBaseUrl(e){if(e instanceof URL)return e;if(!J(e))throw new TypeError("Invalid URL");return new URL(e,e.startsWith("/")?globalThis.location.origin:void 0)}static getOrParseMediaType(e){if(e===null)return;let t=s.mediaTypeCache.get(e);return t!==void 0||(t=T.parse(e)??void 0,t!==void 0&&(s.mediaTypeCache.size>=100&&s.mediaTypeCache.delete(s.mediaTypeCache.keys().next().value),s.mediaTypeCache.set(e,t))),t}static createUrl(e,t,n){let r=t?new URL(`${e.pathname.replace(de,"")}${t}`,e.origin):new URL(e);return n&&s.mergeSearchParams(r.searchParams,n),r}static generateResponseStatusFromError(e,{status:t,statusText:n}=new Response){switch(e){case H.ABORT:return me;case H.TIMEOUT:return ye;default:return t>=400?new w(t,n):ge}}async handleError(e,t,{cause:n,entity:r,url:o,method:i,timing:a}={},u){let p=i&&o?`${i} ${o.href} failed${t?` with status ${t.status}`:""}`:`An error has occurred with your request to: '${e}'`,R=new B(s.generateResponseStatusFromError(n?.name,t),{message:p,cause:n,entity:r,url:o,method:i,timing:a});for(let d of[s.globalHooks.beforeError,this.hooks.beforeError,u?.hooks?.beforeError])if(d)for(let h of d){let c=await h(R);c instanceof B&&(R=c)}return this.publish({name:b.ERROR,data:R}),R}publish({name:e,event:t=new CustomEvent(e),data:n,global:r=!0}){r&&s.globalSubscribr.publish(e,t,n),this.subscribr.publish(e,t,n)}getResponseHandler(e){if(!e)return;let t=s.getOrParseMediaType(e);if(t){for(let[n,r]of s.contentTypeHandlers)if(t.matches(n))return r}}get[Symbol.toStringTag](){return"Transportr"}};export{xe as Transportr};
|
|
8
8
|
//# sourceMappingURL=transportr.js.map
|