vigor-fetch 5.4.0 → 6.0.0

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/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";function createBrand(e,r){return`@vigor-fetch:::${e} <- ${r}`}Object.defineProperty(exports,"__esModule",{value:!0});var VigorDefault=Symbol("VigorDefault"),isVigorDefault=e=>e===VigorDefault,VigorEmpty=Symbol("VigorEmpty"),isVigorEmpty=e=>e===VigorEmpty,VigorCastPlaceholder=Symbol("VigorCastPlaceholder"),VigorStatus=class{_base;_config;constructor(e,r){this._base=e,this._config=this._merge(e,r,void 0,"replace")}_next(e,r){const t=this._merge(this._config,e,r);return this._create(t)}_merge(e,r,t,o="concat"){const i=e=>null!==e&&"object"==typeof e&&Object.getPrototypeOf(e)===Object.prototype,s=e=>{if(Array.isArray(e))return e.map(s);if(i(e)){const r={};for(const t of Object.keys(e))r[t]=s(e[t]);return r}return e},a=(e,r,t)=>{if(void 0===r)return s(e);if("replace"===t)return r;if(Array.isArray(e)&&Array.isArray(r))return"replace"===o?s(r):[...e,...r];if(i(e)&&i(r)){const o={},s=i(t)?t:void 0,n=new Set([...Object.keys(e),...Object.keys(r)]);for(const t of n)o[t]=a(e[t],r[t],s?.[t]);return o}return r};return a(e,r,t)}_snapshot(e){const{timeline:r,...t}=e;return this._merge(t,{})}get base(){return this._base}get config(){return this._config}},VigorAllPolicySettingsBase={__brand:createBrand("All","Policy<Settings<Schema"),debug:!1,concurrency:5,onlySuccess:!1,timeout:VigorEmpty,failFast:!1},VigorAllPolicySettings=class _VigorAllPolicySettings extends VigorStatus{constructor(e=VigorAllBase){super(VigorAllBase,e)}_create(e){return new _VigorAllPolicySettings(e)}concurrency(e){return this._next({policy:{settings:{concurrency:e}}})}onlySuccess(e){return this._next({policy:{settings:{onlySuccess:e}}})}timeout(e){return this._next({policy:{settings:{timeout:e}}})}failFast(e){return this._next({policy:{settings:{failFast:e}}})}debug(e){return this._next({policy:{settings:{debug:e}}})}},VigorAllPolicyMiddlewaresBase={__brand:createBrand("All","Policy<Middlewares<Schema"),before:[],after:[],onResult:[],beforeEach:[],afterEach:[],onErrorEach:[]},VigorAllPolicyMiddlewares=class _VigorAllPolicyMiddlewares extends VigorStatus{constructor(e=VigorAllBase){super(VigorAllBase,e)}_create(e){return new _VigorAllPolicyMiddlewares(e)}before(e,r){return this._next({policy:{middlewares:{before:[{_mode:e,func:r}]}}})}after(e,r){return this._next({policy:{middlewares:{after:[{_mode:e,func:r}]}}})}onResult(e,r){return this._next({policy:{middlewares:{onResult:[{_mode:e,func:r}]}}})}beforeEach(e){return this._next({policy:{middlewares:{beforeEach:[e]}}})}afterEach(e){return this._next({policy:{middlewares:{afterEach:[e]}}})}onErrorEach(e){return this._next({policy:{middlewares:{onErrorEach:[e]}}})}},VigorAllPolicyBase={__brand:createBrand("All","Policy<Schema"),target:[],abortSignals:[],settings:VigorAllPolicySettingsBase,middlewares:VigorAllPolicyMiddlewaresBase},VigorAllContextBase={__brand:createBrand("All","Context<Schema"),result:VigorDefault,policy:VigorAllPolicyBase,record:{},timeline:[]},VigorAllEachContextBase={__brand:createBrand("All","EachContext<Schema"),index:0,result:VigorDefault,error:VigorDefault,flags:{overridden:!1},record:{}},VigorError=class extends Error{timestamp=new Date;cause;code;data;method;context;constructor(e,r,t){super(`[${e}] ${r}`),this.name=new.target.name,this.code=e,this.cause=t.cause,this.data=t.data,this.method=t.method,this.context=t.context,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace?.(this,new.target)}};function findInVigorErrorChain(e,r){const t=new Set,o=e=>{if(null==e||t.has(e))return;if(t.add(e),r(e))return e;if("object"!=typeof e)return;const i=e.data;if(e instanceof VigorError&&null!==i&&"object"==typeof i&&"error"in i){const e=o(i.error);if(void 0!==e)return e}return o(e.cause)};return o(e)}function runVigorGuard(e,r,t){const o=r[r.length-1];if("function"!=typeof o)return t(e,r);const i=Array.isArray(r[0])?r[0]:[r[0]],s=findInVigorErrorChain(e,e=>t(e,i));return void 0===s?void 0:o(s)}var VigorAllErrorMessageFuncs={EMPTY_TARGET:e=>"Empty target list",TIMED_OUT:({limit:e,index:r})=>`Task #${r} timeout: exceeded ${e}ms`},VigorAllError=class extends VigorError{constructor(e,r){super(e,(0,VigorAllErrorMessageFuncs[e])(r.data),r)}};function isVigorAllError(e,...r){return runVigorGuard(e,r,(e,r)=>e instanceof VigorAllError&&(0===r.length||r.includes(e.code)))}var internalMiddlewares=new WeakSet;function markVigorInternal(e){return internalMiddlewares.add(e),e}function isVigorInternalMiddleware(e){const r="function"==typeof e?e:e?.func;return"function"==typeof r&&internalMiddlewares.has(r)}function createVigorTimelineRecorder(e,r,t){const o=(o,i)=>{t&&e.push({action:o,content:i,now:Date.now(),ctx:r()})},i=o;return{add:o,stage:async(e,r,o)=>{if(0===r.length)return;if(!t){for(const e of r)await o(e,e=>e);return}i("MIDDLEWARE_LOOP_STARTED",{stage:e,middlewares:r});const s=performance.now();try{for(const[t,s]of r.entries()){const r=isVigorInternalMiddleware(s),a=performance.now();try{await o(s,o=>{const a={};for(const[n,l]of Object.entries(o))a[n]=(...o)=>(i("MIDDLEWARE_API_CALLED",{stage:e,index:t,middleware:s,internal:r,method:n,args:o}),l(...o));return a})}catch(o){throw i("MIDDLEWARE_RAN",{stage:e,index:t,middleware:s,internal:r,took:performance.now()-a,threw:!0,error:o}),o}i("MIDDLEWARE_RAN",{stage:e,index:t,middleware:s,internal:r,took:performance.now()-a,threw:!1,error:null})}}finally{i("MIDDLEWARE_LOOP_ENDED",{stage:e,middlewares:r,took:performance.now()-s})}}}}var MAX_TIMEOUT=2**31-1,VigorAllBase={__brand:createBrand("All","Schema"),policy:VigorAllPolicyBase,cast:VigorEmpty},VigorAll=class _VigorAll extends VigorStatus{constructor(e=VigorAllBase){super(VigorAllBase,e)}_create(e){return new _VigorAll(e)}target(...e){return this._next({policy:{target:e}})}abortSignals(...e){return this._next({policy:{abortSignals:e}})}settings(e){if("function"==typeof e||e instanceof VigorAllPolicySettings){const r="function"==typeof e?e(new VigorAllPolicySettings(this.config)):e;return this._next({policy:{settings:r.config.policy.settings}})}return this._next({policy:{settings:e}})}middlewares(e){if("function"==typeof e||e instanceof VigorAllPolicyMiddlewares){const r="function"==typeof e?e(new VigorAllPolicyMiddlewares):e;return this._next({policy:{middlewares:r.config.policy.middlewares}})}return this._next({policy:{middlewares:e}})}async _runTask(e,r,t,o,i,s){let a=this._merge(VigorAllEachContextBase,{index:r});const{add:n,stage:l}=createVigorTimelineRecorder(i,()=>this._merge(a,{}),s),c=new AbortController,g=AbortSignal.any([o,c.signal]);let u,y;n("TASK_STARTED",{index:r});const d=performance.now(),p=e=>(n("TASK_ENDED",{index:r,success:e.success,took:performance.now()-d}),e);try{await l("beforeEach",t.middlewares.beforeEach,e=>e(a)),g.throwIfAborted();const o=t.settings.timeout;return!isVigorEmpty(o)&&Number.isFinite(o)&&o>0&&(u=setTimeout(()=>c.abort(new VigorAllError("TIMED_OUT",{method:"request",data:{limit:o,index:r}})),Math.min(o,MAX_TIMEOUT))),a.result=await Promise.race([e(g),new Promise((e,r)=>{y=()=>r(g.reason),g.addEventListener("abort",y)})]),await l("afterEach",t.middlewares.afterEach,e=>e(a)),p({success:!0,value:a.result})}catch(e){a.error=e,n("TASK_ERROR",{index:r,error:e});const o=e=>{a.flags.overridden=!0,a.result=e};return await l("onErrorEach",t.middlewares.onErrorEach,(e,r)=>e(a,r({setResult:o}))),a.flags.overridden?p({success:!0,value:a.result}):p({success:!1,value:e})}finally{clearTimeout(u),y&&g.removeEventListener("abort",y)}}cast(){return this._next({cast:VigorCastPlaceholder},{cast:"replace"})}async request(){const e=await this.requestVerbose();if(e.success)return e.data;throw e.error}async requestVerbose(){return await this.requestRuntime()}async requestRuntime(e=[]){const r=this._merge(this.config,{}),t=r.policy;let o=this._merge(VigorAllContextBase,{policy:t},void 0,"replace");o.timeline=e;const i=performance.now(),{add:s,stage:a}=createVigorTimelineRecorder(e,()=>this._snapshot(o),r.policy.settings.debug),n=(e,r)=>s("REQUEST_END",{success:e,outcome:e?"result":"failed",error:r,took:performance.now()-i,restarts:0}),l=e=>{o.result=e},c=e=>{throw e},g=Number.isNaN(t.settings.concurrency)?1:Math.max(1,Math.floor(t.settings.concurrency));s("PROCESS_HANDLING",{type:"REQUEST_START",data:{tasks:t.target.length,concurrency:g}});try{if(0===t.target.length)throw new VigorAllError("EMPTY_TARGET",{method:"request",data:{},context:o});await a("before",t.middlewares.before,async(e,r)=>{"fluent"===e._mode?await e.func(o):o=await e.func(o,r({throwError:c}))??o});const r=new Array(t.target.length),i=new AbortController,s=AbortSignal.any([...t.abortSignals,i.signal]);let u=0;const y=async()=>{for(;!s.aborted;){const o=u++;if(o>=t.target.length)return;try{r[o]=await this._runTask(t.target[o],o,t,s,e,t.settings.debug)}catch(e){return void i.abort(e)}!r[o].success&&t.settings.failFast&&i.abort(r[o].value)}};return await Promise.all(Array.from({length:Math.min(g,t.target.length)},()=>y())),s.throwIfAborted(),o.result=t.settings.onlySuccess?r.filter(e=>e.success).map(e=>e.value):r.map(e=>e.success?{success:!0,data:e.value,error:null}:{success:!1,data:null,error:e.value}),await a("after",t.middlewares.after,async(e,r)=>{"fluent"===e._mode?await e.func(o):o=await e.func(o,r({setResult:l,throwError:c}))??o}),await a("onResult",t.middlewares.onResult,async(e,r)=>{"fluent"===e._mode?o.result=await e.func(o.result):o=await e.func(o,r({setResult:l,throwError:c}))??o}),n(!0,null),{success:!0,data:o.result,error:null,timeline:e}}catch(r){return s("PROCESS_HANDLING",{type:"REQUEST_ERROR",data:{error:r}}),n(!1,r),{success:!1,data:null,error:r,timeline:e}}}},VigorFetchPolicySettingsBase={__brand:createBrand("Fetch","Policy<Settings<Schema"),debug:!1,retryHeaders:["retry-after","ratelimit-reset","x-ratelimit-reset","x-retry-after","x-amz-retry-after"],unretryStatus:[400,401,402,403,404,405,406,407,409,410,411,412,413,414,415,416,417,422,424,426,428,431,451,501,505,506,508,510,511],maxRetryAfter:3e5,redirect:!1,confinePath:!0,maxRestarts:3,default:VigorEmpty},VigorFetchPolicySettings=class _VigorFetchPolicySettings extends VigorStatus{constructor(e=VigorFetchBase){super(VigorFetchBase,e)}_create(e){return new _VigorFetchPolicySettings(e)}retryHeaders(...e){return this._next({policy:{settings:{retryHeaders:e}}},{policy:{settings:{retryHeaders:"replace"}}})}unretryStatus(...e){return this._next({policy:{settings:{unretryStatus:e}}},{policy:{settings:{unretryStatus:"replace"}}})}maxRetryAfter(e){return this._next({policy:{settings:{maxRetryAfter:e}}})}confinePath(e){return this._next({policy:{settings:{confinePath:e}}})}redirect(e){return this._next({policy:{settings:{redirect:e}}})}maxRestarts(e){return this._next({policy:{settings:{maxRestarts:e}}})}default(e){return this._next({policy:{settings:{default:e}}})}debug(e){return this._next({policy:{settings:{debug:e}}})}},VigorFetchPolicyMiddlewaresBase={__brand:createBrand("Fetch","Policy<Middlewares<Schema"),before:[],after:[],onResult:[],onError:[]},VigorFetchPolicyMiddlewares=class _VigorFetchPolicyMiddlewares extends VigorStatus{constructor(e=VigorFetchBase){super(VigorFetchBase,e)}_create(e){return new _VigorFetchPolicyMiddlewares(e)}before(e,r){return this._next({policy:{middlewares:{before:[{_mode:e,func:r}]}}})}after(e,r){return this._next({policy:{middlewares:{after:[{_mode:e,func:r}]}}})}onResult(e,r){return this._next({policy:{middlewares:{onResult:[{_mode:e,func:r}]}}})}onError(e,r){return this._next({policy:{middlewares:{onError:[{_mode:e,func:r}]}}})}},VigorRetryPolicySettingsBase={__brand:createBrand("Retry","Policy<Settings<Schema"),debug:!1,default:VigorEmpty,maxAttempts:5,maxRestarts:3,timeout:2e4},VigorRetryPolicySettings=class _VigorRetryPolicySettings extends VigorStatus{constructor(e=VigorRetryBase){super(VigorRetryBase,e)}_create(e){return new _VigorRetryPolicySettings(e)}default(e){return this._next({policy:{settings:{default:e}}})}maxAttempts(e){return this._next({policy:{settings:{maxAttempts:e}}})}maxRestarts(e){return this._next({policy:{settings:{maxRestarts:e}}})}timeout(e){return this._next({policy:{settings:{timeout:e}}})}debug(e){return this._next({policy:{settings:{debug:e}}})}},VigorRetryPolicyMiddlewaresBase={__brand:createBrand("Retry","Policy<Middlewares<Schema"),before:[],after:[],onResult:[],retryIf:[],onRetry:[],onError:[]},VigorRetryPolicyMiddlewares=class _VigorRetryPolicyMiddlewares extends VigorStatus{constructor(e=VigorRetryBase){super(VigorRetryBase,e)}_create(e){return new _VigorRetryPolicyMiddlewares(e)}before(e,r){return this._next({policy:{middlewares:{before:[{_mode:e,func:r}]}}})}after(e,r){return this._next({policy:{middlewares:{after:[{_mode:e,func:r}]}}})}onResult(e,r){return this._next({policy:{middlewares:{onResult:[{_mode:e,func:r}]}}})}retryIf(e,r){return this._next({policy:{middlewares:{retryIf:[{_mode:e,func:r}]}}})}onRetry(e,r){return this._next({policy:{middlewares:{onRetry:[{_mode:e,func:r}]}}})}onError(e,r){return this._next({policy:{middlewares:{onError:[{_mode:e,func:r}]}}})}},VigorRetryErrorMessageFuncs={VALUE_REQUIRED:({key:e})=>`Value Required (missing ${e})`,RETRY_EXHAUSTED:({maxAttempts:e})=>`Retry exhausted, (max ${e})`,RESTART_EXHAUSTED:({maxAttempts:e})=>`Restart exhausted, (max ${e})`,TIMED_OUT:({limit:e})=>`Timeout: exceeded ${e}ms`},VigorRetryError=class extends VigorError{constructor(e,r){super(e,(0,VigorRetryErrorMessageFuncs[e])(r.data),r)}};function isVigorRetryError(e,...r){return runVigorGuard(e,r,(e,r)=>e instanceof VigorRetryError&&(0===r.length||r.includes(e.code)))}function VigorJitter(e){return(2*Math.random()-1)*e}var VigorRetryPolicyAlgorithmsConstantBase={__brand:createBrand("Retry","Policy<Algorithms<Constant<Schema"),_tag:"constant",jitter:1e3,interval:2e3,_calculateDelay:(e,r)=>{const{interval:t,jitter:o}=r,i=o;let s=Math.max(i,t);return s+=VigorJitter(o),s}},VigorRetryPolicyAlgorithmsConstant=class _VigorRetryPolicyAlgorithmsConstant extends VigorStatus{constructor(e=VigorRetryPolicyAlgorithmsConstantBase){super(VigorRetryPolicyAlgorithmsConstantBase,e)}_create(e){return new _VigorRetryPolicyAlgorithmsConstant(e)}jitter(e){return this._next({jitter:e})}interval(e){return this._next({interval:e})}},VigorRetryPolicyAlgorithmsLinearBase={__brand:createBrand("Retry","Policy<Algorithms<Linear<Schema"),_tag:"linear",jitter:1e3,initial:500,increment:1e3,minDelay:0,maxDelay:1e4,_calculateDelay:(e,r)=>{const{initial:t,jitter:o,increment:i,minDelay:s,maxDelay:a}=r,n=a-s,l=Math.min(o,n/2),c=s+l,g=a-l;let u=t+i*e;return u=Math.max(c,Math.min(g,u)),u+=VigorJitter(l),u}},VigorRetryPolicyAlgorithmsLinear=class _VigorRetryPolicyAlgorithmsLinear extends VigorStatus{constructor(e=VigorRetryPolicyAlgorithmsLinearBase){super(VigorRetryPolicyAlgorithmsLinearBase,e)}_create(e){return new _VigorRetryPolicyAlgorithmsLinear(e)}jitter(e){return this._next({jitter:e})}initial(e){return this._next({initial:e})}increment(e){return this._next({increment:e})}minDelay(e){return this._next({minDelay:e})}maxDelay(e){return this._next({maxDelay:e})}},VigorRetryPolicyAlgorithmsBackoffBase={__brand:createBrand("Retry","Policy<Algorithms<Backoff<Schema"),_tag:"backoff",jitter:800,initial:0,multiplier:1.7,unit:1e3,minDelay:500,maxDelay:1e4,_calculateDelay:(e,r)=>{const{jitter:t,initial:o,multiplier:i,unit:s,minDelay:a,maxDelay:n}=r,l=n-a,c=Math.min(t,l/2),g=a+c,u=n-c;let y=o+s*Math.pow(i,e);return y=Math.max(g,Math.min(u,y)),y+=VigorJitter(c),y}},VigorRetryPolicyAlgorithmsBackoff=class _VigorRetryPolicyAlgorithmsBackoff extends VigorStatus{constructor(e=VigorRetryPolicyAlgorithmsBackoffBase){super(VigorRetryPolicyAlgorithmsBackoffBase,e)}_create(e){return new _VigorRetryPolicyAlgorithmsBackoff(e)}jitter(e){return this._next({jitter:e})}initial(e){return this._next({initial:e})}multiplier(e){return this._next({multiplier:e})}unit(e){return this._next({unit:e})}minDelay(e){return this._next({minDelay:e})}maxDelay(e){return this._next({maxDelay:e})}},VigorRetryPolicyAlgorithmsCustomBase={__brand:createBrand("Retry","Policy<Algorithms<Custom<Schema"),_tag:"custom",jitter:800,minDelay:500,maxDelay:1e4,target:VigorEmpty,_calculateDelay:(e,r)=>{const{jitter:t,minDelay:o,maxDelay:i,target:s}=r;if(isVigorEmpty(s))throw new VigorRetryError("VALUE_REQUIRED",{method:"_calculateDelay",data:{key:"target"}});const a=i-o,n=Math.min(t,a/2),l=o+n,c=i-n;let g=s(e);return g=Math.max(l,Math.min(c,g)),g+=VigorJitter(n),g}},VigorRetryPolicyAlgorithmsCustom=class _VigorRetryPolicyAlgorithmsCustom extends VigorStatus{constructor(e=VigorRetryPolicyAlgorithmsCustomBase){super(VigorRetryPolicyAlgorithmsCustomBase,e)}_create(e){return new _VigorRetryPolicyAlgorithmsCustom(e)}jitter(e){return this._next({jitter:e})}minDelay(e){return this._next({minDelay:e})}maxDelay(e){return this._next({maxDelay:e})}target(e){return this._next({target:e})}},VigorRetryPolicyAlgorithmsBase=VigorRetryPolicyAlgorithmsConstantBase,VigorRetryPolicyAlgorithms=class _VigorRetryPolicyAlgorithms extends VigorStatus{constructor(e=VigorRetryBase){super(VigorRetryBase,e)}_create(e){return new _VigorRetryPolicyAlgorithms(e)}constant(e){const r=this._merge(VigorRetryPolicyAlgorithmsConstantBase,e??{});return this._next({policy:{algorithms:r}},{policy:{algorithms:"replace"}})}linear(e){const r=this._merge(VigorRetryPolicyAlgorithmsLinearBase,e??{});return this._next({policy:{algorithms:r}},{policy:{algorithms:"replace"}})}backoff(e){const r=this._merge(VigorRetryPolicyAlgorithmsBackoffBase,e??{});return this._next({policy:{algorithms:r}},{policy:{algorithms:"replace"}})}custom(e){const r=this._merge(VigorRetryPolicyAlgorithmsCustomBase,e??{});return this._next({policy:{algorithms:r}},{policy:{algorithms:"replace"}})}},VigorRetryPolicyBase={__brand:createBrand("Retry","Policy<Schema"),target:VigorEmpty,abortSignals:[],settings:VigorRetryPolicySettingsBase,middlewares:VigorRetryPolicyMiddlewaresBase,algorithms:VigorRetryPolicyAlgorithmsBase},VigorRetryContextBase={__brand:createBrand("Retry","Context<Schema"),result:VigorDefault,error:VigorDefault,system:{delay:VigorDefault,attempt:0},flags:{doRetry:!0,doRestart:!1,brokeRetry:!1,aborted:!1,timedOut:!1,overridden:!1},record:{},timeline:[],policy:VigorRetryPolicyBase},MAX_TIMEOUT2=2**31-1,VigorRetryBase={__brand:createBrand("Retry","Schema"),policy:VigorRetryPolicyBase,cast:VigorEmpty},VigorRetry=class _VigorRetry extends VigorStatus{constructor(e=VigorRetryBase){super(VigorRetryBase,e)}_create(e){return new _VigorRetry(e)}target(e){return this._next({policy:{target:e}})}abortSignals(...e){return this._next({policy:{abortSignals:e}})}settings(e){if("function"==typeof e||e instanceof VigorRetryPolicySettings){const r="function"==typeof e?e(new VigorRetryPolicySettings(this.config)):e;return this._next({policy:{settings:r.config.policy.settings}})}return this._next({policy:{settings:e}})}middlewares(e){if("function"==typeof e||e instanceof VigorRetryPolicyMiddlewares){const r="function"==typeof e?e(new VigorRetryPolicyMiddlewares):e;return this._next({policy:{middlewares:r.config.policy.middlewares}})}return this._next({policy:{middlewares:e}})}algorithms(e){if("function"==typeof e){const r=e(new VigorRetryPolicyAlgorithms).config.policy.algorithms;return this._next({policy:{algorithms:r}},{policy:{algorithms:"replace"}})}return this._next({policy:{algorithms:e}},{policy:{algorithms:"replace"}})}cast(){return this._next({cast:VigorCastPlaceholder},{cast:"replace"})}async request(){const e=await this.requestVerbose();if(e.success)return e.data;throw e.error}async requestVerbose(){return await this.requestRuntime()}async requestRuntime(e=1,r=[],t=performance.now()){const o=this._merge(this.config,{});let i=this._merge(VigorRetryContextBase,{policy:o.policy},void 0,"replace");i.timeline=r;const{add:s,stage:a}=createVigorTimelineRecorder(r,()=>this._snapshot(i),o.policy.settings.debug);s("PROCESS_HANDLING",{type:"REQUEST_START",data:{restartAttempt:e}});const n=(r,o,i)=>s("REQUEST_END",{success:r,outcome:o,error:i,took:performance.now()-t,restarts:e-1}),l=(e,t)=>(n(!0,t,null),{success:!0,data:e,error:null,timeline:r}),c=e=>(n(!1,"failed",e),{success:!1,data:null,error:e,timeline:r}),g=(e,r)=>s("RETRY_DECISION",{attempt:i.system.attempt,retry:e,reason:r});if(isVigorEmpty(i.policy.target))return c(new VigorRetryError("VALUE_REQUIRED",{method:"request",data:{key:"target"},context:i}));const u=i.policy.target,y=e=>{throw e},d=AbortSignal.any(i.policy.abortSignals);try{for(;i.system.attempt<i.policy.settings.maxAttempts;){i.system.attempt++,s("ATTEMPT_INCREASED",{attempt:i.system.attempt}),s("PROCESS_HANDLING",{type:"RETRY_START",data:{attempt:i.system.attempt}}),i.flags.timedOut=!1;try{const e=e=>{throw i.flags.brokeRetry=!0,e},r=new AbortController,t=new AbortController,o=AbortSignal.any([r.signal,t.signal]),n=AbortSignal.any([o,d]);let c,g;try{await a("before",i.policy.middlewares.before,async(t,o)=>{"fluent"===t._mode?await t.func(i):i=await t.func(i,o({abort:e=>r.abort(e),throwError:y,breakRetry:e}))??i}),n.throwIfAborted();const o=i.policy.settings.timeout;Number.isFinite(o)&&o>0&&(g=setTimeout(()=>{i.flags.timedOut=!0,t.abort(new VigorRetryError("TIMED_OUT",{method:"request",data:{limit:o},context:i}))},Math.min(o,MAX_TIMEOUT2)));const d=i.system.attempt;s("TARGET_REQUEST_STARTED",{attempt:d});const p=performance.now();i.result=await Promise.race([u(n),new Promise((e,r)=>{c=()=>r(n.reason),n.addEventListener("abort",c)})]),s("TARGET_REQUEST_ENDED",{attempt:d,took:performance.now()-p}),await a("after",i.policy.middlewares.after,async(e,r)=>{"fluent"===e._mode?await e.func(i):i=await e.func(i,r({throwError:y}))??i});const h=e=>{i.result=e};return await a("onResult",i.policy.middlewares.onResult,async(e,r)=>{"fluent"===e._mode?i.result=await e.func(i.result):i=await e.func(i,r({setResult:h,throwError:y}))??i}),l(i.result,"result")}finally{clearTimeout(g),c&&n.removeEventListener("abort",c)}}catch(e){if(i.error=e,d.aborted&&(i.flags.aborted=!0),s("PROCESS_HANDLING",{type:"RETRY_ERROR",data:{attempt:i.system.attempt,error:e,timedOut:i.flags.timedOut,aborted:i.flags.aborted}}),i.flags.aborted)throw g(!1,"aborted"),i.error;if(i.flags.brokeRetry)throw g(!1,"breakRetry"),i.error;i.flags.doRetry=!0;const r=()=>i.flags.doRetry=!0,t=()=>i.flags.doRetry=!1;if(await a("retryIf",i.policy.middlewares.retryIf,async(e,o)=>{"fluent"===e._mode?i.flags.doRetry=await e.func(i.error):i=await e.func(i,o({proceedRetry:r,cancelRetry:t}))??i}),!i.flags.doRetry)throw g(!1,"cancelled"),i.error;if(i.system.attempt>=i.policy.settings.maxAttempts){g(!1,"exhausted");break}g(!0,"retry"),i.system.delay=i.policy.algorithms._calculateDelay(i.system.attempt,i.policy.algorithms);const o=e=>{i.system.delay=e};await a("onRetry",i.policy.middlewares.onRetry,async(e,r)=>{"fluent"===e._mode?await e.func(i.error):i=await e.func(i,r({throwError:y,setDelay:o}))??i});const n=Math.min(Math.max(0,Number(i.system.delay)||0),MAX_TIMEOUT2);s("RETRY_DELAY",{attempt:i.system.attempt,delay:n}),await new Promise((e,r)=>{if(d.aborted)return i.flags.aborted=!0,r(d.reason);const t=()=>{clearTimeout(o),i.flags.aborted=!0,r(d.reason)},o=setTimeout(()=>{d.removeEventListener("abort",t),e()},n);d.addEventListener("abort",t,{once:!0})})}}throw new VigorRetryError("RETRY_EXHAUSTED",{method:"request",cause:i.error,data:{maxAttempts:i.policy.settings.maxAttempts,error:i.error},context:i})}catch(o){i.error=o,s("PROCESS_HANDLING",{type:"REQUEST_ERROR",data:{error:o}}),i.flags.doRestart=!1,i.flags.overridden=!1;const n=e=>{i.flags.overridden=!0,i.result=e},g=()=>i.flags.doRestart=!0,u=()=>i.flags.doRestart=!1;try{await a("onError",i.policy.middlewares.onError,async(e,r)=>{"fluent"===e._mode?await e.func(i.error):i=await e.func(i,r({setResult:n,throwError:y,proceedRestart:g,cancelRestart:u}))??i})}catch(e){return c(e)}if(i.flags.doRestart)return e>i.policy.settings.maxRestarts?c(new VigorRetryError("RESTART_EXHAUSTED",{method:"request",cause:i.error,data:{maxAttempts:i.policy.settings.maxRestarts,error:i.error},context:i})):(s("PROCESS_HANDLING",{type:"REQUEST_RESTART",data:{restartAttempt:e+1}}),await this.requestRuntime(e+1,r,t));if(i.flags.overridden)return l(i.result,"overridden");if(!isVigorEmpty(i.policy.settings.default))try{return l(await i.policy.settings.default(i),"default")}catch(e){return c(e)}return c(i.error)}}},VigorParsePolicySettingsBase={__brand:createBrand("Parse","Policy<Settings<Schema"),debug:!1,raw:!1,default:VigorEmpty,maxRestarts:3},VigorParsePolicySettings=class _VigorParsePolicySettings extends VigorStatus{constructor(e=VigorParseBase){super(VigorParseBase,e)}_create(e){return new _VigorParsePolicySettings(e)}raw(e){return this._next({policy:{settings:{raw:e}}})}default(e){return this._next({policy:{settings:{default:e}}})}maxRestarts(e){return this._next({policy:{settings:{maxRestarts:e}}})}debug(e){return this._next({policy:{settings:{debug:e}}})}},VigorParsePolicyMiddlewaresBase={__brand:createBrand("Parse","Policy<Middlewares<Schema"),before:[],after:[],onResult:[],onError:[]},VigorParsePolicyMiddlewares=class _VigorParsePolicyMiddlewares extends VigorStatus{constructor(e=VigorParseBase){super(VigorParseBase,e)}_create(e){return new _VigorParsePolicyMiddlewares(e)}before(e,r){return this._next({policy:{middlewares:{before:[{_mode:e,func:r}]}}})}after(e,r){return this._next({policy:{middlewares:{after:[{_mode:e,func:r}]}}})}onResult(e,r){return this._next({policy:{middlewares:{onResult:[{_mode:e,func:r}]}}})}onError(e,r){return this._next({policy:{middlewares:{onError:[{_mode:e,func:r}]}}})}},describeVigorParseFailure=e=>e instanceof Error?`${e.name}: ${e.message}`:String(e),VigorParseErrorMessageFuncs={VALUE_REQUIRED:({key:e})=>`Value Required (missing ${e})`,INVALID_CONTENT_TYPE:({received:e})=>`Invalid Content-Type header: ${String(e)}`,PARSER_NOT_FOUND:({received:e,expected:r})=>`Parser not found for Content-Type "${String(e)}" (known: ${r.join(", ")})`,PARSER_ALL_FAILED:({tried:e,errors:r})=>`All parsers failed: ${e.map((e,t)=>`${e} (${describeVigorParseFailure(r[t])})`).join(", ")}`,RESTART_EXHAUSTED:({maxAttempts:e})=>`Restart exhausted, (max ${e})`},VigorParseError=class extends VigorError{constructor(e,r){super(e,(0,VigorParseErrorMessageFuncs[e])(r.data),r)}};function isVigorParseError(e,...r){return runVigorGuard(e,r,(e,r)=>e instanceof VigorParseError&&(0===r.length||r.includes(e.code)))}var VigorParsePolicyStrategiesBase={__brand:createBrand("Parse","Policy<Strategies<Schema"),funcs:[]},bodyCache=new WeakMap;async function readVigorParseBody(e){let r=bodyCache.get(e);return r||(r=null===e.body?Promise.resolve(new Uint8Array(0)):e.arrayBuffer().then(e=>new Uint8Array(e)),bodyCache.set(e,r)),{bytes:await r,contentType:e.headers.get("content-type"),status:e instanceof Response?e.status:null,headers:e.headers,source:e}}var utf8=new TextDecoder("utf-8"),getCharset=e=>/;\s*charset\s*=\s*"?([^";\s]+)"?/i.exec(e??"")?.[1]??"utf-8",getMimeType=e=>(e??"").split(";")[0].trim().toLowerCase(),decodeText=(e,r=!1)=>{let t;try{t=new TextDecoder(getCharset(e.contentType),{fatal:r})}catch{t=new TextDecoder("utf-8",{fatal:r})}return t.decode(e.bytes)},parseJson=e=>JSON.parse(utf8.decode(e.bytes)),parseJsonOrNull=e=>{const r=utf8.decode(e.bytes);return""===r.trim()?null:JSON.parse(r)},hexValue=e=>e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1,decodeFormComponent=e=>{const r=new Uint8Array(e.length);let t=0;for(let o=0;o<e.length;o++){const i=e[o];if(43!==i){if(37===i&&o+2<e.length){const i=hexValue(e[o+1]),s=hexValue(e[o+2]);if(i>=0&&s>=0){r[t++]=16*i+s,o+=2;continue}}r[t++]=i}else r[t++]=32}return utf8.decode(r.subarray(0,t))},parseUrlEncoded=e=>{const r=new FormData,{bytes:t}=e;let o=0;for(let e=0;e<=t.length;e++){if(e<t.length&&38!==t[e])continue;const i=t.subarray(o,e);if(o=e+1,0===i.length)continue;const s=i.indexOf(61),a=-1===s?i:i.subarray(0,s),n=-1===s?new Uint8Array(0):i.subarray(s+1);r.append(decodeFormComponent(a),decodeFormComponent(n))}return r},parseMultipart=e=>new Response(e.bytes,{headers:{"content-type":e.contentType??""}}).formData(),parseFormData=e=>{const r=getMimeType(e.contentType);if("application/x-www-form-urlencoded"===r)return parseUrlEncoded(e);if("multipart/form-data"===r)return parseMultipart(e);throw new VigorParseError("INVALID_CONTENT_TYPE",{method:"parseFormData",data:{received:e.contentType}})},toArrayBuffer=e=>e.bytes.slice().buffer,toBlob=e=>new Blob([e.bytes],{type:e.contentType??""}),NoBodyStatus=[204,205,304],ContentTypeParsers=[{header:"application/json",regExp:/application\/(.+\+)?json(.+\+)?/i,method:parseJsonOrNull},{header:"application/xml",regExp:/application\/(.+\+)?xml(.+\+)?/i,method:e=>decodeText(e)},{header:"application/x-www-form-urlencoded",regExp:/application\/(.+\+)?x-www-form-urlencoded(.+\+)?/i,method:parseUrlEncoded},{header:"application/octet-stream",regExp:/application\/(.+\+)?octet-stream(.+\+)?/i,method:toArrayBuffer},{header:"image/*",regExp:/^image\/.+/i,method:toBlob},{header:"audio/*",regExp:/^audio\/.+/i,method:toBlob},{header:"video/*",regExp:/^video\/.+/i,method:toBlob},{header:"multipart/form-data",regExp:/multipart\/(.+\+)?form-data(.+\+)?/i,method:parseMultipart},{header:"text/*",regExp:/^text\/.+/i,method:e=>decodeText(e)}],SniffMethods=[{title:"json",method:parseJson},{title:"formData",method:parseFormData},{title:"text",method:e=>decodeText(e,!0)},{title:"blob",method:toBlob}],VigorParseContentTypeStrategy=async e=>{if(0===e.bytes.length||null!==e.status&&NoBodyStatus.includes(e.status))return null;if(!e.contentType)return decodeText(e);const r=ContentTypeParsers.find(r=>r.regExp.test(e.contentType));return r?await r.method(e):toBlob(e)},VigorParseSniffStrategy=async e=>{const r=[];for(const t of SniffMethods)try{return await t.method(e)}catch(e){r.push(e)}throw new VigorParseError("PARSER_ALL_FAILED",{method:"VigorParseSniffStrategy",cause:r.at(-1),data:{tried:SniffMethods.map(e=>e.title),errors:r}})},VigorParsePolicyStrategies=class _VigorParsePolicyStrategies extends VigorStatus{constructor(e=VigorParseBase){super(VigorParseBase,e)}_create(e){return new _VigorParsePolicyStrategies(e)}_set(e,r){return this._next({policy:{strategies:{funcs:e}}},r?{policy:{strategies:{funcs:"replace"}}}:void 0)}contentType(e){return this._set([VigorParseContentTypeStrategy],e)}sniff(e){return this._set([VigorParseSniffStrategy],e)}json(e){return this._set([parseJson],e)}text(e){return this._set([e=>decodeText(e)],e)}arrayBuffer(e){return this._set([toArrayBuffer],e)}blob(e){return this._set([toBlob],e)}bytes(e){return this._set([e=>e.bytes.slice()],e)}formData(e){return this._set([parseFormData],e)}custom(e,r){return this._set([e],r)}},VigorParsePolicyBase={__brand:createBrand("Parse","Policy<Schema"),target:VigorDefault,settings:VigorParsePolicySettingsBase,middlewares:VigorParsePolicyMiddlewaresBase,strategies:VigorParsePolicyStrategiesBase},VigorParseContextBase={__brand:createBrand("Parse","Context<Schema"),result:VigorDefault,error:VigorDefault,response:VigorDefault,flags:{overridden:!1,restarted:!1},record:{},timeline:[],policy:VigorParsePolicyBase},VigorParseBase={__brand:createBrand("Parse","Schema"),policy:VigorParsePolicyBase,cast:VigorEmpty},VigorParse=class _VigorParse extends VigorStatus{constructor(e=VigorParseBase){super(VigorParseBase,e)}_create(e){return new _VigorParse(e)}target(e){return this._next({policy:{target:e}})}settings(e){if("function"==typeof e||e instanceof VigorParsePolicySettings){const r="function"==typeof e?e(new VigorParsePolicySettings(this.config)):e;return this._next({policy:{settings:r.config.policy.settings}})}return this._next({policy:{settings:e}})}middlewares(e){if("function"==typeof e||e instanceof VigorParsePolicyMiddlewares){const r="function"==typeof e?e(new VigorParsePolicyMiddlewares):e;return this._next({policy:{middlewares:r.config.policy.middlewares}})}return this._next({policy:{middlewares:e}})}strategies(e){if("function"==typeof e||e instanceof VigorParsePolicyStrategies){const r="function"==typeof e?e(new VigorParsePolicyStrategies):e;return this._next({policy:{strategies:r.config.policy.strategies}})}return this._next({policy:{strategies:e}})}cast(){return this._next({cast:VigorCastPlaceholder},{cast:"replace"})}async request(){const e=await this.requestVerbose();if(e.success)return e.data;throw e.error}async requestVerbose(){return await this.requestRuntime()}async requestRuntime(e=1,r=[],t=performance.now()){const o=this._merge(this.config,{});let i=this._merge(VigorParseContextBase,{policy:o.policy},void 0,"replace");i.timeline=r;const{add:s,stage:a}=createVigorTimelineRecorder(r,()=>this._snapshot(i),o.policy.settings.debug);s("PROCESS_HANDLING",{type:"REQUEST_START",data:{restartAttempt:e}});const n=(r,o,i)=>s("REQUEST_END",{success:r,outcome:o,error:i,took:performance.now()-t,restarts:e-1}),l=(e,t)=>(n(!0,t,null),{success:!0,data:e,error:null,timeline:r}),c=e=>(n(!1,"failed",e),{success:!1,data:null,error:e,timeline:r});if(isVigorDefault(i.policy.target))return c(new VigorParseError("VALUE_REQUIRED",{method:"request",data:{key:"target"},context:i}));i.response=i.policy.target;const g=e=>{throw e};try{if(await a("before",i.policy.middlewares.before,async(e,r)=>{"fluent"===e._mode?await e.func(i):i=await e.func(i,r({throwError:g}))??i}),i.policy.settings.raw)i.result=i.response;else{const e=performance.now(),r=await readVigorParseBody(i.response);s("BODY_READ",{size:r.bytes.byteLength,took:performance.now()-e});const t=i.policy.strategies.funcs.length>0?i.policy.strategies.funcs:[VigorParseContentTypeStrategy];let o=!1;const a=[];for(const[e,n]of t.entries()){s("STRATEGY_STARTED",{index:e});const t=performance.now();try{i.result=await n(r),s("STRATEGY_SUCCEEDED",{index:e,took:performance.now()-t}),o=!0;break}catch(r){a.push(r),s("STRATEGY_FAILED",{index:e,error:r,took:performance.now()-t})}}if(!o)throw new VigorParseError("PARSER_ALL_FAILED",{method:"request",cause:a.at(-1),data:{tried:t.map((e,r)=>`strategy#${r}`),errors:a},context:i})}const e=e=>{i.result=e};return await a("after",i.policy.middlewares.after,async(r,t)=>{"fluent"===r._mode?await r.func(i):i=await r.func(i,t({setResult:e,throwError:g}))??i}),await a("onResult",i.policy.middlewares.onResult,async(r,t)=>{"fluent"===r._mode?i.result=await r.func(i.result):i=await r.func(i,t({setResult:e,throwError:g}))??i}),l(i.result,"result")}catch(o){i.error=o,s("PROCESS_HANDLING",{type:"REQUEST_ERROR",data:{error:o}}),i.flags.overridden=!1,i.flags.restarted=!1;const n=e=>{i.flags.overridden=!0,i.result=e},u=()=>i.flags.restarted=!0,y=()=>i.flags.restarted=!1;try{await a("onError",i.policy.middlewares.onError,async(e,r)=>{"fluent"===e._mode?await e.func(i.error):i=await e.func(i,r({setResult:n,throwError:g,proceedRestart:u,cancelRestart:y}))??i})}catch(e){return c(e)}if(i.flags.restarted)return e>i.policy.settings.maxRestarts?c(new VigorParseError("RESTART_EXHAUSTED",{method:"request",cause:i.error,data:{maxAttempts:i.policy.settings.maxRestarts,error:i.error},context:i})):(s("PROCESS_HANDLING",{type:"REQUEST_RESTART",data:{restartAttempt:e+1}}),await this.requestRuntime(e+1,r,t));if(i.flags.overridden)return l(i.result,"overridden");if(!isVigorEmpty(i.policy.settings.default))try{return l(await i.policy.settings.default(i),"default")}catch(e){return c(e)}return c(i.error)}}},VigorFetchPolicyBase={__brand:createBrand("Fetch","Policy<Schema"),method:VigorEmpty,origin:VigorEmpty,path:[],query:[],hash:"",headers:{},body:VigorEmpty,extra:{},settings:VigorFetchPolicySettingsBase,middlewares:VigorFetchPolicyMiddlewaresBase,retry:VigorRetryBase,parse:VigorParseBase},VigorFetchContextBase={__brand:createBrand("Fetch","Context<Schema"),href:"",response:VigorDefault,result:VigorDefault,error:VigorDefault,options:VigorDefault,flags:{overridden:!1,restarted:!1},record:{},timeline:[],policy:VigorFetchPolicyBase},VigorFetchErrorMessageFuncs={...VigorRetryErrorMessageFuncs,...VigorParseErrorMessageFuncs,VALUE_REQUIRED:({key:e})=>`Value Required (missing ${e})`,INVALID_BODY:({received:e})=>"Invalid Body type: "+typeof e,BODY_NOT_ALLOWED:({method:e})=>`A ${e} request cannot have a body`,INVALID_PROTOCOL:({origin:e,base:r})=>r?`Invalid URL: could not resolve "${e}" against base "${r}"`:`Invalid URL: "${e}" is not an absolute URL, and no base (window.location) is available to resolve it against — pass an absolute origin (e.g. "https://api.example.com") when running outside a browser`,FETCH_FAILED:({status:e,statusText:r})=>`Fetch Failed: ${e} ${r}`,RESTART_EXHAUSTED:({maxAttempts:e})=>`Restart exhausted, (max ${e})`,PATH_ESCAPED:({url:e,base:r})=>`Path escapes "${r}": the request would go to "${e}" (settings.confinePath)`,REDIRECTED:({url:e,status:r})=>`Redirected (${r}) to "${e}" — navigating away`},VigorFetchError=class extends VigorError{constructor(e,r){super(e,(0,VigorFetchErrorMessageFuncs[e])(r.data),r)}};function isVigorFetchError(e,...r){return runVigorGuard(e,r,(e,r)=>e instanceof VigorFetchError&&(0===r.length||r.includes(e.code)))}function adoptVigorFetchError(e,r){if(!(e instanceof VigorRetryError||e instanceof VigorParseError))return e;const t=e.data,o=null!==t&&"object"==typeof t&&"error"in t?{...t,error:adoptVigorFetchError(t.error,r)}:t;return new VigorFetchError(e.code,{method:e.method,cause:e,data:o,context:r})}var VigorFetchBase={__brand:createBrand("Fetch","Schema"),policy:VigorFetchPolicyBase,cast:VigorEmpty,apiMap:VigorEmpty},VigorFetch=class _VigorFetch extends VigorStatus{constructor(e=VigorFetchBase){super(VigorFetchBase,e)}_create(e){return new _VigorFetch(e)}method(e){return this._next({policy:{method:e}})}origin(e){return this._next({policy:{origin:e}})}path(...e){return this._next({policy:{path:this._stringifyList(e)}})}query(...e){return this._next({policy:{query:e}})}hash(e){return this._next({policy:{hash:e}},{policy:{hash:"replace"}})}headers(e,r){return"overwrite"===e?this._next({policy:{headers:r}},{policy:{headers:"replace"}}):this._next({policy:{headers:r}})}body(e,r){const t=this.config.policy.body,o="merge"===e&&this._isPlainObject(t)&&this._isPlainObject(r)?{...t,...r}:r;return this._next({policy:{body:o}},{policy:{body:"replace"}})}options(e,r){const t="merge"===e?{...this.config.policy.extra,...r}:r;return this._next({policy:{extra:t}},{policy:{extra:"replace"}})}settings(e){const r={policy:{settings:{retryHeaders:"replace",unretryStatus:"replace"}}};if("function"==typeof e||e instanceof VigorFetchPolicySettings){const t="function"==typeof e?e(new VigorFetchPolicySettings(this.config)):e;return this._next({policy:{settings:t.config.policy.settings}},r)}return this._next({policy:{settings:e}},r)}middlewares(e){if("function"==typeof e||e instanceof VigorFetchPolicyMiddlewares){const r="function"==typeof e?e(new VigorFetchPolicyMiddlewares):e;return this._next({policy:{middlewares:r.config.policy.middlewares}})}return this._next({policy:{middlewares:e}})}retry(e){if("function"==typeof e||e instanceof VigorRetry){const r="function"==typeof e?e(new VigorRetry):e;return this._next({policy:{retry:r.config}},{policy:{retry:"replace"}})}return this._next({policy:{retry:this._merge(VigorRetryBase,e)}},{policy:{retry:"replace"}})}parse(e){if("function"==typeof e||e instanceof VigorParse){const r="function"==typeof e?e(new VigorParse):e;return this._next({policy:{parse:r.config}},{policy:{parse:"replace"}})}return this._next({policy:{parse:this._merge(VigorParseBase,e)}},{policy:{parse:"replace"}})}_isPlainObject(e){return null!==e&&"object"==typeof e&&Object.getPrototypeOf(e)===Object.prototype}_stringifyList(e){return e.filter(e=>null!=e).map(e=>e instanceof Date?e.toISOString():String(e))}_resolveBase(){if("undefined"!=typeof globalThis&&globalThis.location?.href)return globalThis.location.href}_buildUrl(e,r,t,o,i){const s=this._resolveBase();let a;try{a=new URL(e,s)}catch{throw new VigorFetchError("INVALID_PROTOCOL",{method:"_buildUrl",data:{origin:e,base:s},context:i})}const n=a.origin,l=[a.pathname.replace(/^\/+|\/+$/g,"")];for(const e of r)for(const r of e.split("/"))l.push(encodeURIComponent(r));const c=l.filter(Boolean).join("/"),g=new URL(c,n),u=e=>e instanceof Date?e.toISOString():String(e),y=[...a.searchParams.entries(),...t.flatMap(e=>Object.entries(e))];for(const[e,r]of y)if(null!=r)if(Array.isArray(r))for(const t of r)g.searchParams.append(e,u(t));else g.searchParams.append(e,u(r));if(g.hash=o||a.hash,i.policy.settings.confinePath){const e="/"+a.pathname.replace(/^\/+|\/+$/g,""),r="/"===e||g.pathname===e||g.pathname.startsWith(e+"/");if(g.origin!==a.origin||!r)throw new VigorFetchError("PATH_ESCAPED",{method:"_buildUrl",data:{url:g.href,base:a.origin+("/"===e?"":e)},context:i})}return g.href}_normalizeBody(e,r){if(null==e)return{headers:{},body:e};if("string"==typeof e)return{headers:{"Content-Type":"text/plain;charset=UTF-8"},body:e};if(e instanceof Blob)return{headers:e.type?{"Content-Type":e.type}:{},body:e};if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return{headers:{"Content-Type":"application/octet-stream"},body:e};if("undefined"!=typeof ReadableStream&&e instanceof ReadableStream)return{headers:{"Content-Type":"application/octet-stream"},body:e};if(e instanceof URLSearchParams)return{headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},body:e};if(e instanceof FormData)return{headers:{},body:e};if("object"==typeof e)return{headers:{"Content-Type":"application/json"},body:JSON.stringify(e)};throw new VigorFetchError("INVALID_BODY",{method:"_normalizeBody",data:{received:e},context:r})}_resolveRedirect(e,r){if(e.redirected&&e.url)return e.url;if(e.status<300||e.status>=400)return null;const t=e.headers.get("location");if(!t)return null;try{return new URL(t,e.url||r).href}catch{return null}}_browserLocation(){const e=globalThis.window;return void 0!==e?.location?.href?e.location:null}_assignHeaders(e,r){for(const[t,o]of Object.entries(r)){const r=t.toLowerCase();for(const t of Object.keys(e))t.toLowerCase()===r&&delete e[t];e[t]=o}}_parseRetryHeader(e){if(!e)return null;const r=Number(e);let t;if(""===e.trim()||isNaN(r)){const r=new Date(e).getTime();if(isNaN(r))return null;t=r-Date.now()}else t=r>=1e12?r-Date.now():r>=1e9?1e3*r-Date.now():1e3*r;return t>0?t:null}apiMap(){return this._next({apiMap:VigorCastPlaceholder},{apiMap:"replace"})}route(e,...r){const t=e,o=t.indexOf(" "),i=t.slice(0,o),s=r[0]??{},a=t.slice(o+1).split("/").filter(Boolean).map(e=>{if(!e.startsWith(":"))return e;const r=e.slice(1),t=s[r];if(null==t)throw new VigorFetchError("VALUE_REQUIRED",{method:"route",data:{key:`params.${r}`}});return t});return this.method(i).path(...a)}cast(){return this._next({cast:VigorCastPlaceholder},{cast:"replace"})}async request(){const e=await this.requestRuntime();if(e.success)return e.data;throw e.error}async requestVerbose(){return await this.requestRuntime()}async requestRuntime(e=1,r=[],t=performance.now()){const o=this._merge(this.config,{});let i=this._merge(VigorFetchContextBase,{policy:o.policy},void 0,"replace");i.timeline=r;const{add:s,stage:a}=createVigorTimelineRecorder(r,()=>this._snapshot(i),o.policy.settings.debug);s("PROCESS_HANDLING",{type:"REQUEST_START",data:{restartAttempt:e}});const n=(r,o,i)=>s("REQUEST_END",{success:r,outcome:o,error:i,took:performance.now()-t,restarts:e-1}),l=(e,t,o=null)=>(n(!0,t,null),{success:!0,data:e,error:null,status:o?.status??null,response:o,timeline:r}),c=e=>(n(!1,"failed",e),{success:!1,data:null,error:e,status:null,response:null,timeline:r});let g=0;const u=async(e,r,t)=>{s("PARSE_STARTED",{engine:t,source:e,attempt:r});const o=performance.now(),i=await t.requestVerbose();return s("PARSE_ENDED",{engine:t,source:e,attempt:r,timeline:i.timeline,took:performance.now()-o,result:i.success?i.data:VigorDefault}),i},y=e=>{throw e};try{if(isVigorEmpty(i.policy.origin))throw new VigorFetchError("VALUE_REQUIRED",{method:"request",data:{key:"origin"},context:i});i.href=this._buildUrl(i.policy.origin,i.policy.path,i.policy.query,i.policy.hash,i),s("BUILT_URL",{url:i.href});const e=!isVigorEmpty(i.policy.body)&&null!=i.policy.body,r=isVigorEmpty(i.policy.method)?e?"POST":"GET":i.policy.method,t={...i.policy.extra,method:r,headers:{}};if(e){const e=this._normalizeBody(i.policy.body,i);void 0!==e.body&&(t.body=e.body),Object.assign(t.headers,e.headers)}this._assignHeaders(t.headers,i.policy.headers),i.options=t,await a("before",i.policy.middlewares.before,async(e,r)=>{"fluent"===e._mode?await e.func(i):i=await e.func(i,r({throwError:y,setOptions:e=>{i.options=e},setHeaders:e=>{i.options.headers=e},setBody:e=>{i.options.body=e}}))??i});const n=isVigorDefault(i.options)?t:i.options;i.options=n,s("SET_OPTIONS",{options:n});const c=(n.method??"GET").toUpperCase();if(null!=n.body&&("GET"===c||"HEAD"===c))throw new VigorFetchError("BODY_NOT_ALLOWED",{method:"request",data:{method:c},context:i});const d="undefined"!=typeof ReadableStream&&n.body instanceof ReadableStream;d&&(n.duplex??="half");const p={policy:{settings:{debug:!0}}},h=new VigorParse(o.policy.settings.debug?this._merge(i.policy.parse,p):i.policy.parse),m=new VigorRetry(o.policy.settings.debug?this._merge(i.policy.retry,p):i.policy.retry).target(async e=>await fetch(i.href,{...n,signal:e})).middlewares(e=>e.after("intercept",async(e,r)=>{const t=e.result;if(g=e.system.attempt,s("RESPONSE_RECEIVED",{attempt:e.system.attempt,status:t.status,statusText:t.statusText,ok:t.ok,redirected:t.redirected,url:t.url}),i.policy.settings.redirect){const e=this._resolveRedirect(t,i.href),o=this._browserLocation();e&&o&&(o.href=e,r.throwError(new VigorFetchError("REDIRECTED",{method:"request",data:{url:e,status:t.status,response:t},context:i})))}if(!t.ok&&304!==t.status){const o=await u("failedResponse",e.system.attempt,h.target(t.clone())),s=o.success?o.data:void 0;r.throwError(new VigorFetchError("FETCH_FAILED",{method:"request",data:{status:t.status,statusText:t.statusText,response:t,url:t.url,parsed:s},context:i}))}return i.policy.parse.policy.settings.raw||await readVigorParseBody(t),e}).retryIf("intercept",async(e,r)=>{const t=e.error instanceof VigorFetchError?e.error.data?.response:void 0;return(e.error instanceof VigorFetchError&&"REDIRECTED"===e.error.code||d||t&&("opaqueredirect"===t.type||t.status>=300&&t.status<400)||t&&i.policy.settings.unretryStatus.includes(t.status))&&r.cancelRetry(),e}).onRetry("intercept",async(e,r)=>{const t=e.error instanceof VigorFetchError?e.error.data?.response:void 0;if(429===t?.status||503===t?.status)for(const e of i.policy.settings.retryHeaders){const o=this._parseRetryHeader(t.headers.get(e));if(null!==o){r.setDelay(Math.min(o,i.policy.settings.maxRetryAfter));break}}return e}));for(const e of["after","retryIf","onRetry"]){const r=m.config.policy.middlewares[e];markVigorInternal(r[r.length-1].func)}s("ENGINE_CREATED",{retryEngine:m,parseEngine:h});const f=await(async e=>{s("RETRY_STARTED",{engine:e});const r=performance.now(),t=await e.requestVerbose();return s("RETRY_ENDED",{engine:e,timeline:t.timeline,took:performance.now()-r,response:t.success?t.data:VigorDefault}),t})(m);if(!f.success)throw adoptVigorFetchError(f.error,i);i.response=f.data;const V=await u("response",g,h.target(i.response));if(!V.success)throw adoptVigorFetchError(V.error,i);i.result=V.data,await a("after",i.policy.middlewares.after,async(e,r)=>{"fluent"===e._mode?await e.func(i):i=await e.func(i,r({throwError:y,setResult:e=>{i.result=e}}))??i});const _=e=>{i.result=e};return await a("onResult",i.policy.middlewares.onResult,async(e,r)=>{"fluent"===e._mode?i.result=await e.func(i.result):i=await e.func(i,r({setResult:_,throwError:y}))??i}),l(i.result,"result",i.response)}catch(o){i.error=o,s("PROCESS_HANDLING",{type:"REQUEST_ERROR",data:{error:o}}),i.flags.overridden=!1,i.flags.restarted=!1;const n=e=>{i.flags.overridden=!0,i.result=e},g=()=>i.flags.restarted=!0,u=()=>i.flags.restarted=!1;try{await a("onError",i.policy.middlewares.onError,async(e,r)=>{"fluent"===e._mode?await e.func(i.error):i=await e.func(i,r({setResult:n,throwError:y,proceedRestart:g,cancelRestart:u}))??i})}catch(e){return c(e)}if(i.flags.restarted)return e>i.policy.settings.maxRestarts?c(new VigorFetchError("RESTART_EXHAUSTED",{method:"request",cause:i.error,data:{maxAttempts:i.policy.settings.maxRestarts,error:i.error},context:i})):(s("PROCESS_HANDLING",{type:"REQUEST_RESTART",data:{restartAttempt:e+1}}),await this.requestRuntime(e+1,r,t));if(i.flags.overridden)return l(i.result,"overridden");if(!isVigorEmpty(i.policy.settings.default))try{return l(await i.policy.settings.default(i),"default")}catch(e){return c(e)}return c(o)}}};function retryWithTarget(e){return(new VigorRetry).target(e)}function parseWithTarget(e){return(new VigorParse).target(e)}function fetchWithOrigin(e){return(new VigorFetch).origin(e)}function allWithTargets(e){return(new VigorAll).target(...e)}var vigorBase={retry:e=>void 0!==e?retryWithTarget(e):new VigorRetry,parse:e=>void 0!==e?parseWithTarget(e):new VigorParse,fetch:e=>void 0!==e?fetchWithOrigin(e):new VigorFetch,all:(...e)=>e.length>0?allWithTargets(e):new VigorAll,builders:{fetch:{settings:()=>new VigorFetchPolicySettings,middlewares:()=>new VigorFetchPolicyMiddlewares},retry:{settings:()=>new VigorRetryPolicySettings,middlewares:()=>new VigorRetryPolicyMiddlewares,algorithms:()=>new VigorRetryPolicyAlgorithms,algorithm:{constant:()=>new VigorRetryPolicyAlgorithmsConstant,linear:()=>new VigorRetryPolicyAlgorithmsLinear,backoff:()=>new VigorRetryPolicyAlgorithmsBackoff,custom:()=>new VigorRetryPolicyAlgorithmsCustom}},parse:{settings:()=>new VigorParsePolicySettings,middlewares:()=>new VigorParsePolicyMiddlewares,strategies:()=>new VigorParsePolicyStrategies},all:{settings:()=>new VigorAllPolicySettings,middlewares:()=>new VigorAllPolicyMiddlewares}},guards:{retry:isVigorRetryError,parse:isVigorParseError,fetch:isVigorFetchError,all:isVigorAllError}},cloneVigor=e=>({...e,builders:{fetch:{...e.builders.fetch},retry:{...e.builders.retry,algorithm:{...e.builders.retry.algorithm}},parse:{...e.builders.parse},all:{...e.builders.all}},guards:{...e.guards}}),createVigor=e=>{const r={...e,use:(e,t)=>{const o=e.func(r,{...e.options,...t}),{use:i,...s}={...cloneVigor(r),...o};return createVigor(s)}};return r},vigor=createVigor(vigorBase),index_default=vigor;exports.VigorAll=VigorAll,exports.VigorAllBase=VigorAllBase,exports.VigorAllContextBase=VigorAllContextBase,exports.VigorAllEachContextBase=VigorAllEachContextBase,exports.VigorAllError=VigorAllError,exports.VigorAllErrorMessageFuncs=VigorAllErrorMessageFuncs,exports.VigorAllPolicyBase=VigorAllPolicyBase,exports.VigorAllPolicyMiddlewares=VigorAllPolicyMiddlewares,exports.VigorAllPolicyMiddlewaresBase=VigorAllPolicyMiddlewaresBase,exports.VigorAllPolicySettings=VigorAllPolicySettings,exports.VigorAllPolicySettingsBase=VigorAllPolicySettingsBase,exports.VigorCastPlaceholder=VigorCastPlaceholder,exports.VigorDefault=VigorDefault,exports.VigorEmpty=VigorEmpty,exports.VigorError=VigorError,exports.VigorFetch=VigorFetch,exports.VigorFetchBase=VigorFetchBase,exports.VigorFetchContextBase=VigorFetchContextBase,exports.VigorFetchError=VigorFetchError,exports.VigorFetchErrorMessageFuncs=VigorFetchErrorMessageFuncs,exports.VigorFetchPolicyBase=VigorFetchPolicyBase,exports.VigorFetchPolicyMiddlewares=VigorFetchPolicyMiddlewares,exports.VigorFetchPolicyMiddlewaresBase=VigorFetchPolicyMiddlewaresBase,exports.VigorFetchPolicySettings=VigorFetchPolicySettings,exports.VigorFetchPolicySettingsBase=VigorFetchPolicySettingsBase,exports.VigorJitter=VigorJitter,exports.VigorParse=VigorParse,exports.VigorParseBase=VigorParseBase,exports.VigorParseContentTypeStrategy=VigorParseContentTypeStrategy,exports.VigorParseContextBase=VigorParseContextBase,exports.VigorParseError=VigorParseError,exports.VigorParseErrorMessageFuncs=VigorParseErrorMessageFuncs,exports.VigorParsePolicyBase=VigorParsePolicyBase,exports.VigorParsePolicyMiddlewares=VigorParsePolicyMiddlewares,exports.VigorParsePolicyMiddlewaresBase=VigorParsePolicyMiddlewaresBase,exports.VigorParsePolicySettings=VigorParsePolicySettings,exports.VigorParsePolicySettingsBase=VigorParsePolicySettingsBase,exports.VigorParsePolicyStrategies=VigorParsePolicyStrategies,exports.VigorParsePolicyStrategiesBase=VigorParsePolicyStrategiesBase,exports.VigorParseSniffStrategy=VigorParseSniffStrategy,exports.VigorRetry=VigorRetry,exports.VigorRetryBase=VigorRetryBase,exports.VigorRetryContextBase=VigorRetryContextBase,exports.VigorRetryError=VigorRetryError,exports.VigorRetryErrorMessageFuncs=VigorRetryErrorMessageFuncs,exports.VigorRetryPolicyAlgorithms=VigorRetryPolicyAlgorithms,exports.VigorRetryPolicyAlgorithmsBackoff=VigorRetryPolicyAlgorithmsBackoff,exports.VigorRetryPolicyAlgorithmsBackoffBase=VigorRetryPolicyAlgorithmsBackoffBase,exports.VigorRetryPolicyAlgorithmsBase=VigorRetryPolicyAlgorithmsBase,exports.VigorRetryPolicyAlgorithmsConstant=VigorRetryPolicyAlgorithmsConstant,exports.VigorRetryPolicyAlgorithmsConstantBase=VigorRetryPolicyAlgorithmsConstantBase,exports.VigorRetryPolicyAlgorithmsCustom=VigorRetryPolicyAlgorithmsCustom,exports.VigorRetryPolicyAlgorithmsCustomBase=VigorRetryPolicyAlgorithmsCustomBase,exports.VigorRetryPolicyAlgorithmsLinear=VigorRetryPolicyAlgorithmsLinear,exports.VigorRetryPolicyAlgorithmsLinearBase=VigorRetryPolicyAlgorithmsLinearBase,exports.VigorRetryPolicyBase=VigorRetryPolicyBase,exports.VigorRetryPolicyMiddlewares=VigorRetryPolicyMiddlewares,exports.VigorRetryPolicyMiddlewaresBase=VigorRetryPolicyMiddlewaresBase,exports.VigorRetryPolicySettings=VigorRetryPolicySettings,exports.VigorRetryPolicySettingsBase=VigorRetryPolicySettingsBase,exports.VigorStatus=VigorStatus,exports.adoptVigorFetchError=adoptVigorFetchError,exports.createBrand=createBrand,exports.createVigorTimelineRecorder=createVigorTimelineRecorder,exports.default=index_default,exports.findInVigorErrorChain=findInVigorErrorChain,exports.isVigorAllError=isVigorAllError,exports.isVigorDefault=isVigorDefault,exports.isVigorEmpty=isVigorEmpty,exports.isVigorFetchError=isVigorFetchError,exports.isVigorInternalMiddleware=isVigorInternalMiddleware,exports.isVigorParseError=isVigorParseError,exports.isVigorRetryError=isVigorRetryError,exports.markVigorInternal=markVigorInternal,exports.readVigorParseBody=readVigorParseBody,exports.runVigorGuard=runVigorGuard,exports.vigor=vigor;
1
+ "use strict";function createBrand(e,r){return`@vigor-fetch:::${e} <- ${r}`}Object.defineProperty(exports,"__esModule",{value:!0});var VigorDefault=Symbol("VigorDefault"),isVigorDefault=e=>e===VigorDefault,VigorEmpty=Symbol("VigorEmpty"),isVigorEmpty=e=>e===VigorEmpty,VigorCastPlaceholder=Symbol("VigorCastPlaceholder"),VigorStatus=class{_base;_config;constructor(e,r){this._base=e,this._config=this._merge(e,r,void 0,"replace")}_next(e,r){const t=this._merge(this._config,e,r);return this._create(t)}_merge(e,r,t,i="concat"){const o=e=>null!==e&&"object"==typeof e&&Object.getPrototypeOf(e)===Object.prototype,s=e=>{if(Array.isArray(e))return e.map(s);if(o(e)){const r={};for(const t of Object.keys(e))r[t]=s(e[t]);return r}return e},a=(e,r,t)=>{if(void 0===r)return s(e);if("replace"===t)return r;if(Array.isArray(e)&&Array.isArray(r))return"replace"===i?s(r):[...e,...r];if(o(e)&&o(r)){const i={},s=o(t)?t:void 0,n=new Set([...Object.keys(e),...Object.keys(r)]);for(const t of n)i[t]=a(e[t],r[t],s?.[t]);return i}return r};return a(e,r,t)}_snapshot(e){const{timeline:r,...t}=e;return this._merge(t,{})}get base(){return this._base}get config(){return this._config}},VigorAllPolicySettingsBase={__brand:createBrand("All","Policy<Settings<Schema"),debug:!1,concurrency:5,onlySuccess:!1,timeout:VigorEmpty,failFast:!1},VigorAllPolicySettings=class _VigorAllPolicySettings extends VigorStatus{constructor(e=VigorAllBase){super(VigorAllBase,e)}_create(e){return new _VigorAllPolicySettings(e)}concurrency(e){return this._next({policy:{settings:{concurrency:e}}})}onlySuccess(e){return this._next({policy:{settings:{onlySuccess:e}}})}timeout(e){return this._next({policy:{settings:{timeout:e}}})}failFast(e){return this._next({policy:{settings:{failFast:e}}})}debug(e){return this._next({policy:{settings:{debug:e}}})}},VigorAllPolicyMiddlewaresBase={__brand:createBrand("All","Policy<Middlewares<Schema"),before:[],after:[],onResult:[],beforeEach:[],afterEach:[],onErrorEach:[]},VigorAllPolicyMiddlewares=class _VigorAllPolicyMiddlewares extends VigorStatus{constructor(e=VigorAllBase){super(VigorAllBase,e)}_create(e){return new _VigorAllPolicyMiddlewares(e)}before(e,r){return this._next({policy:{middlewares:{before:[{_mode:e,func:r}]}}})}after(e,r){return this._next({policy:{middlewares:{after:[{_mode:e,func:r}]}}})}onResult(e,r){return this._next({policy:{middlewares:{onResult:[{_mode:e,func:r}]}}})}beforeEach(e){return this._next({policy:{middlewares:{beforeEach:[e]}}})}afterEach(e){return this._next({policy:{middlewares:{afterEach:[e]}}})}onErrorEach(e){return this._next({policy:{middlewares:{onErrorEach:[e]}}})}},VigorAllPolicyBase={__brand:createBrand("All","Policy<Schema"),target:[],abortSignals:[],settings:VigorAllPolicySettingsBase,middlewares:VigorAllPolicyMiddlewaresBase},VigorAllContextBase={__brand:createBrand("All","Context<Schema"),result:VigorDefault,policy:VigorAllPolicyBase,record:{},timeline:[]},VigorAllEachContextBase={__brand:createBrand("All","EachContext<Schema"),index:0,result:VigorDefault,error:VigorDefault,flags:{overridden:!1},record:{}},VigorError=class extends Error{timestamp=new Date;cause;code;data;method;context;constructor(e,r,t){super(`[${e}] ${r}`),this.name=new.target.name,this.code=e,this.cause=t.cause,this.data=t.data,this.method=t.method,this.context=t.context,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace?.(this,new.target)}};function findInVigorErrorChain(e,r){const t=new Set,i=e=>{if(null==e||t.has(e))return;if(t.add(e),r(e))return e;if("object"!=typeof e)return;const o=e.data;if(e instanceof VigorError&&null!==o&&"object"==typeof o&&"error"in o){const e=i(o.error);if(void 0!==e)return e}return i(e.cause)};return i(e)}function runVigorGuard(e,r,t){const i=r[r.length-1];if("function"!=typeof i)return t(e,r);const o=Array.isArray(r[0])?r[0]:[r[0]],s=findInVigorErrorChain(e,e=>t(e,o));return void 0===s?void 0:i(s)}var VigorAllErrorMessageFuncs={EMPTY_TARGET:e=>"Empty target list",TIMED_OUT:({limit:e,index:r})=>`Task #${r} timeout: exceeded ${e}ms`},VigorAllError=class extends VigorError{constructor(e,r){super(e,(0,VigorAllErrorMessageFuncs[e])(r.data),r)}};function isVigorAllError(e,...r){return runVigorGuard(e,r,(e,r)=>e instanceof VigorAllError&&(0===r.length||r.includes(e.code)))}var internalMiddlewares=new WeakSet;function markVigorInternal(e){return internalMiddlewares.add(e),e}function isVigorInternalMiddleware(e){const r="function"==typeof e?e:e?.func;return"function"==typeof r&&internalMiddlewares.has(r)}function createVigorTimelineRecorder(e,r,t){const i=(i,o)=>{t&&e.push({action:i,content:o,now:Date.now(),ctx:r()})},o=i;return{add:i,stage:async(e,r,i)=>{if(0===r.length)return;if(!t){for(const e of r)await i(e,e=>e);return}o("MIDDLEWARE_LOOP_STARTED",{stage:e,middlewares:r});const s=performance.now();try{for(const[t,s]of r.entries()){const r=isVigorInternalMiddleware(s),a=performance.now();try{await i(s,i=>{const a={};for(const[n,l]of Object.entries(i))a[n]=(...i)=>(o("MIDDLEWARE_API_CALLED",{stage:e,index:t,middleware:s,internal:r,method:n,args:i}),l(...i));return a})}catch(i){throw o("MIDDLEWARE_RAN",{stage:e,index:t,middleware:s,internal:r,took:performance.now()-a,threw:!0,error:i}),i}o("MIDDLEWARE_RAN",{stage:e,index:t,middleware:s,internal:r,took:performance.now()-a,threw:!1,error:null})}}finally{o("MIDDLEWARE_LOOP_ENDED",{stage:e,middlewares:r,took:performance.now()-s})}}}}var MAX_TIMEOUT=2**31-1,VigorAllBase={__brand:createBrand("All","Schema"),policy:VigorAllPolicyBase,cast:VigorEmpty},VigorAll=class _VigorAll extends VigorStatus{constructor(e=VigorAllBase){super(VigorAllBase,e)}_create(e){return new _VigorAll(e)}target(...e){return this._next({policy:{target:e}})}abortSignals(...e){return this._next({policy:{abortSignals:e}})}settings(e){if("function"==typeof e||e instanceof VigorAllPolicySettings){const r="function"==typeof e?e(new VigorAllPolicySettings(this.config)):e;return this._next({policy:{settings:r.config.policy.settings}})}return this._next({policy:{settings:e}})}middlewares(e){if("function"==typeof e||e instanceof VigorAllPolicyMiddlewares){const r="function"==typeof e?e(new VigorAllPolicyMiddlewares):e;return this._next({policy:{middlewares:r.config.policy.middlewares}})}return this._next({policy:{middlewares:e}})}async _runTask(e,r,t,i,o,s){let a=this._merge(VigorAllEachContextBase,{index:r});const{add:n,stage:l}=createVigorTimelineRecorder(o,()=>this._merge(a,{}),s),c=new AbortController,g=AbortSignal.any([i,c.signal]);let y,u;n("TASK_STARTED",{index:r});const d=performance.now(),p=e=>(n("TASK_ENDED",{index:r,success:e.success,took:performance.now()-d}),e);try{await l("beforeEach",t.middlewares.beforeEach,e=>e(a)),g.throwIfAborted();const i=t.settings.timeout;return!isVigorEmpty(i)&&Number.isFinite(i)&&i>0&&(y=setTimeout(()=>c.abort(new VigorAllError("TIMED_OUT",{method:"request",data:{limit:i,index:r}})),Math.min(i,MAX_TIMEOUT))),a.result=await Promise.race([e(g),new Promise((e,r)=>{u=()=>r(g.reason),g.addEventListener("abort",u)})]),await l("afterEach",t.middlewares.afterEach,e=>e(a)),p({success:!0,value:a.result})}catch(e){a.error=e,n("TASK_ERROR",{index:r,error:e});const i=e=>{a.flags.overridden=!0,a.result=e};return await l("onErrorEach",t.middlewares.onErrorEach,(e,r)=>e(a,r({setResult:i}))),a.flags.overridden?p({success:!0,value:a.result}):p({success:!1,value:e})}finally{clearTimeout(y),u&&g.removeEventListener("abort",u)}}cast(){return this._next({cast:VigorCastPlaceholder},{cast:"replace"})}async request(){const e=await this.requestVerbose();if(e.success)return e.data;throw e.error}async requestVerbose(){return await this.requestRuntime()}async requestRuntime(e=[]){const r=this._merge(this.config,{}),t=r.policy;let i=this._merge(VigorAllContextBase,{policy:t},void 0,"replace");i.timeline=e;const o=performance.now(),{add:s,stage:a}=createVigorTimelineRecorder(e,()=>this._snapshot(i),r.policy.settings.debug),n=(e,r)=>s("REQUEST_END",{success:e,outcome:e?"result":"failed",error:r,took:performance.now()-o,restarts:0}),l=e=>{i.result=e},c=e=>{throw e},g=Number.isNaN(t.settings.concurrency)?1:Math.max(1,Math.floor(t.settings.concurrency));s("PROCESS_HANDLING",{type:"REQUEST_START",data:{tasks:t.target.length,concurrency:g}});try{if(0===t.target.length)throw new VigorAllError("EMPTY_TARGET",{method:"request",data:{},context:i});await a("before",t.middlewares.before,async(e,r)=>{"fluent"===e._mode?await e.func(i):i=await e.func(i,r({throwError:c}))??i});const r=new Array(t.target.length),o=new AbortController,s=AbortSignal.any([...t.abortSignals,o.signal]);let y=0;const u=async()=>{for(;!s.aborted;){const i=y++;if(i>=t.target.length)return;try{r[i]=await this._runTask(t.target[i],i,t,s,e,t.settings.debug)}catch(e){return void o.abort(e)}!r[i].success&&t.settings.failFast&&o.abort(r[i].value)}};return await Promise.all(Array.from({length:Math.min(g,t.target.length)},()=>u())),s.throwIfAborted(),i.result=t.settings.onlySuccess?r.filter(e=>e.success).map(e=>e.value):r.map(e=>e.success?{success:!0,data:e.value,error:null}:{success:!1,data:null,error:e.value}),await a("after",t.middlewares.after,async(e,r)=>{"fluent"===e._mode?await e.func(i):i=await e.func(i,r({setResult:l,throwError:c}))??i}),await a("onResult",t.middlewares.onResult,async(e,r)=>{"fluent"===e._mode?i.result=await e.func(i.result):i=await e.func(i,r({setResult:l,throwError:c}))??i}),n(!0,null),{success:!0,data:i.result,error:null,timeline:e}}catch(r){return s("PROCESS_HANDLING",{type:"REQUEST_ERROR",data:{error:r}}),n(!1,r),{success:!1,data:null,error:r,timeline:e}}}},VigorFetchPolicySettingsBase={__brand:createBrand("Fetch","Policy<Settings<Schema"),debug:!1,retryHeaders:["retry-after","ratelimit-reset","x-ratelimit-reset","x-retry-after","x-amz-retry-after"],unretryStatus:[400,401,402,403,404,405,406,407,409,410,411,412,413,414,415,416,417,422,424,426,428,431,451,501,505,506,508,510,511],maxRetryAfter:3e5,redirect:!1,maxRestarts:3,fetcher:VigorEmpty,default:VigorEmpty},VigorFetchPolicySettings=class _VigorFetchPolicySettings extends VigorStatus{constructor(e=VigorFetchBase){super(VigorFetchBase,e)}_create(e){return new _VigorFetchPolicySettings(e)}retryHeaders(...e){return this._next({policy:{settings:{retryHeaders:e}}},{policy:{settings:{retryHeaders:"replace"}}})}unretryStatus(...e){return this._next({policy:{settings:{unretryStatus:e}}},{policy:{settings:{unretryStatus:"replace"}}})}maxRetryAfter(e){return this._next({policy:{settings:{maxRetryAfter:e}}})}redirect(e){return this._next({policy:{settings:{redirect:e}}})}maxRestarts(e){return this._next({policy:{settings:{maxRestarts:e}}})}fetcher(e){return this._next({policy:{settings:{fetcher:e}}})}default(e){return this._next({policy:{settings:{default:e}}})}debug(e){return this._next({policy:{settings:{debug:e}}})}},VigorFetchPolicyMiddlewaresBase={__brand:createBrand("Fetch","Policy<Middlewares<Schema"),before:[],after:[],onResult:[],onError:[]},VigorFetchPolicyMiddlewares=class _VigorFetchPolicyMiddlewares extends VigorStatus{constructor(e=VigorFetchBase){super(VigorFetchBase,e)}_create(e){return new _VigorFetchPolicyMiddlewares(e)}before(e,r){return this._next({policy:{middlewares:{before:[{_mode:e,func:r}]}}})}after(e,r){return this._next({policy:{middlewares:{after:[{_mode:e,func:r}]}}})}onResult(e,r){return this._next({policy:{middlewares:{onResult:[{_mode:e,func:r}]}}})}onError(e,r){return this._next({policy:{middlewares:{onError:[{_mode:e,func:r}]}}})}},VigorRetryPolicySettingsBase={__brand:createBrand("Retry","Policy<Settings<Schema"),debug:!1,default:VigorEmpty,maxAttempts:5,maxRestarts:3,timeout:2e4},VigorRetryPolicySettings=class _VigorRetryPolicySettings extends VigorStatus{constructor(e=VigorRetryBase){super(VigorRetryBase,e)}_create(e){return new _VigorRetryPolicySettings(e)}default(e){return this._next({policy:{settings:{default:e}}})}maxAttempts(e){return this._next({policy:{settings:{maxAttempts:e}}})}maxRestarts(e){return this._next({policy:{settings:{maxRestarts:e}}})}timeout(e){return this._next({policy:{settings:{timeout:e}}})}debug(e){return this._next({policy:{settings:{debug:e}}})}},VigorRetryPolicyMiddlewaresBase={__brand:createBrand("Retry","Policy<Middlewares<Schema"),before:[],after:[],onResult:[],retryIf:[],onRetry:[],onError:[]},VigorRetryPolicyMiddlewares=class _VigorRetryPolicyMiddlewares extends VigorStatus{constructor(e=VigorRetryBase){super(VigorRetryBase,e)}_create(e){return new _VigorRetryPolicyMiddlewares(e)}before(e,r){return this._next({policy:{middlewares:{before:[{_mode:e,func:r}]}}})}after(e,r){return this._next({policy:{middlewares:{after:[{_mode:e,func:r}]}}})}onResult(e,r){return this._next({policy:{middlewares:{onResult:[{_mode:e,func:r}]}}})}retryIf(e,r){return this._next({policy:{middlewares:{retryIf:[{_mode:e,func:r}]}}})}onRetry(e,r){return this._next({policy:{middlewares:{onRetry:[{_mode:e,func:r}]}}})}onError(e,r){return this._next({policy:{middlewares:{onError:[{_mode:e,func:r}]}}})}},VigorRetryErrorMessageFuncs={VALUE_REQUIRED:({key:e})=>`Value Required (missing ${e})`,RETRY_EXHAUSTED:({maxAttempts:e})=>`Retry exhausted, (max ${e})`,RESTART_EXHAUSTED:({maxAttempts:e})=>`Restart exhausted, (max ${e})`,TIMED_OUT:({limit:e})=>`Timeout: exceeded ${e}ms`},VigorRetryError=class extends VigorError{constructor(e,r){super(e,(0,VigorRetryErrorMessageFuncs[e])(r.data),r)}};function isVigorRetryError(e,...r){return runVigorGuard(e,r,(e,r)=>e instanceof VigorRetryError&&(0===r.length||r.includes(e.code)))}function VigorJitter(e){return(2*Math.random()-1)*e}var VigorRetryPolicyAlgorithmsConstantBase={__brand:createBrand("Retry","Policy<Algorithms<Constant<Schema"),_tag:"constant",jitter:1e3,interval:2e3,_calculateDelay:(e,r)=>{const{interval:t,jitter:i}=r,o=i;let s=Math.max(o,t);return s+=VigorJitter(i),s}},VigorRetryPolicyAlgorithmsConstant=class _VigorRetryPolicyAlgorithmsConstant extends VigorStatus{constructor(e=VigorRetryPolicyAlgorithmsConstantBase){super(VigorRetryPolicyAlgorithmsConstantBase,e)}_create(e){return new _VigorRetryPolicyAlgorithmsConstant(e)}jitter(e){return this._next({jitter:e})}interval(e){return this._next({interval:e})}},VigorRetryPolicyAlgorithmsLinearBase={__brand:createBrand("Retry","Policy<Algorithms<Linear<Schema"),_tag:"linear",jitter:1e3,initial:500,increment:1e3,minDelay:0,maxDelay:1e4,_calculateDelay:(e,r)=>{const{initial:t,jitter:i,increment:o,minDelay:s,maxDelay:a}=r,n=a-s,l=Math.min(i,n/2),c=s+l,g=a-l;let y=t+o*e;return y=Math.max(c,Math.min(g,y)),y+=VigorJitter(l),y}},VigorRetryPolicyAlgorithmsLinear=class _VigorRetryPolicyAlgorithmsLinear extends VigorStatus{constructor(e=VigorRetryPolicyAlgorithmsLinearBase){super(VigorRetryPolicyAlgorithmsLinearBase,e)}_create(e){return new _VigorRetryPolicyAlgorithmsLinear(e)}jitter(e){return this._next({jitter:e})}initial(e){return this._next({initial:e})}increment(e){return this._next({increment:e})}minDelay(e){return this._next({minDelay:e})}maxDelay(e){return this._next({maxDelay:e})}},VigorRetryPolicyAlgorithmsBackoffBase={__brand:createBrand("Retry","Policy<Algorithms<Backoff<Schema"),_tag:"backoff",jitter:800,initial:0,multiplier:1.7,unit:1e3,minDelay:500,maxDelay:1e4,_calculateDelay:(e,r)=>{const{jitter:t,initial:i,multiplier:o,unit:s,minDelay:a,maxDelay:n}=r,l=n-a,c=Math.min(t,l/2),g=a+c,y=n-c;let u=i+s*Math.pow(o,e);return u=Math.max(g,Math.min(y,u)),u+=VigorJitter(c),u}},VigorRetryPolicyAlgorithmsBackoff=class _VigorRetryPolicyAlgorithmsBackoff extends VigorStatus{constructor(e=VigorRetryPolicyAlgorithmsBackoffBase){super(VigorRetryPolicyAlgorithmsBackoffBase,e)}_create(e){return new _VigorRetryPolicyAlgorithmsBackoff(e)}jitter(e){return this._next({jitter:e})}initial(e){return this._next({initial:e})}multiplier(e){return this._next({multiplier:e})}unit(e){return this._next({unit:e})}minDelay(e){return this._next({minDelay:e})}maxDelay(e){return this._next({maxDelay:e})}},VigorRetryPolicyAlgorithmsCustomBase={__brand:createBrand("Retry","Policy<Algorithms<Custom<Schema"),_tag:"custom",jitter:800,minDelay:500,maxDelay:1e4,target:VigorEmpty,_calculateDelay:(e,r)=>{const{jitter:t,minDelay:i,maxDelay:o,target:s}=r;if(isVigorEmpty(s))throw new VigorRetryError("VALUE_REQUIRED",{method:"_calculateDelay",data:{key:"target"}});const a=o-i,n=Math.min(t,a/2),l=i+n,c=o-n;let g=s(e);return g=Math.max(l,Math.min(c,g)),g+=VigorJitter(n),g}},VigorRetryPolicyAlgorithmsCustom=class _VigorRetryPolicyAlgorithmsCustom extends VigorStatus{constructor(e=VigorRetryPolicyAlgorithmsCustomBase){super(VigorRetryPolicyAlgorithmsCustomBase,e)}_create(e){return new _VigorRetryPolicyAlgorithmsCustom(e)}jitter(e){return this._next({jitter:e})}minDelay(e){return this._next({minDelay:e})}maxDelay(e){return this._next({maxDelay:e})}target(e){return this._next({target:e})}},VigorRetryPolicyAlgorithmsBase=VigorRetryPolicyAlgorithmsConstantBase,VigorRetryPolicyAlgorithms=class _VigorRetryPolicyAlgorithms extends VigorStatus{constructor(e=VigorRetryBase){super(VigorRetryBase,e)}_create(e){return new _VigorRetryPolicyAlgorithms(e)}constant(e){const r=this._merge(VigorRetryPolicyAlgorithmsConstantBase,e??{});return this._next({policy:{algorithms:r}},{policy:{algorithms:"replace"}})}linear(e){const r=this._merge(VigorRetryPolicyAlgorithmsLinearBase,e??{});return this._next({policy:{algorithms:r}},{policy:{algorithms:"replace"}})}backoff(e){const r=this._merge(VigorRetryPolicyAlgorithmsBackoffBase,e??{});return this._next({policy:{algorithms:r}},{policy:{algorithms:"replace"}})}custom(e){const r=this._merge(VigorRetryPolicyAlgorithmsCustomBase,e??{});return this._next({policy:{algorithms:r}},{policy:{algorithms:"replace"}})}},VigorRetryPolicyBase={__brand:createBrand("Retry","Policy<Schema"),target:VigorEmpty,abortSignals:[],settings:VigorRetryPolicySettingsBase,middlewares:VigorRetryPolicyMiddlewaresBase,algorithms:VigorRetryPolicyAlgorithmsBase},VigorRetryContextBase={__brand:createBrand("Retry","Context<Schema"),result:VigorDefault,error:VigorDefault,system:{delay:VigorDefault,attempt:0},flags:{doRetry:!0,doRestart:!1,brokeRetry:!1,aborted:!1,timedOut:!1,overridden:!1},record:{},timeline:[],policy:VigorRetryPolicyBase},MAX_TIMEOUT2=2**31-1,VigorRetryBase={__brand:createBrand("Retry","Schema"),policy:VigorRetryPolicyBase,cast:VigorEmpty},VigorRetry=class _VigorRetry extends VigorStatus{constructor(e=VigorRetryBase){super(VigorRetryBase,e)}_create(e){return new _VigorRetry(e)}target(e){return this._next({policy:{target:e}})}abortSignals(...e){return this._next({policy:{abortSignals:e}})}settings(e){if("function"==typeof e||e instanceof VigorRetryPolicySettings){const r="function"==typeof e?e(new VigorRetryPolicySettings(this.config)):e;return this._next({policy:{settings:r.config.policy.settings}})}return this._next({policy:{settings:e}})}middlewares(e){if("function"==typeof e||e instanceof VigorRetryPolicyMiddlewares){const r="function"==typeof e?e(new VigorRetryPolicyMiddlewares):e;return this._next({policy:{middlewares:r.config.policy.middlewares}})}return this._next({policy:{middlewares:e}})}algorithms(e){if("function"==typeof e){const r=e(new VigorRetryPolicyAlgorithms).config.policy.algorithms;return this._next({policy:{algorithms:r}},{policy:{algorithms:"replace"}})}return this._next({policy:{algorithms:e}},{policy:{algorithms:"replace"}})}cast(){return this._next({cast:VigorCastPlaceholder},{cast:"replace"})}async request(){const e=await this.requestVerbose();if(e.success)return e.data;throw e.error}async requestVerbose(){return await this.requestRuntime()}async requestRuntime(e=1,r=[],t=performance.now()){const i=this._merge(this.config,{});let o=this._merge(VigorRetryContextBase,{policy:i.policy},void 0,"replace");o.timeline=r;const{add:s,stage:a}=createVigorTimelineRecorder(r,()=>this._snapshot(o),i.policy.settings.debug);s("PROCESS_HANDLING",{type:"REQUEST_START",data:{restartAttempt:e}});const n=(r,i,o)=>s("REQUEST_END",{success:r,outcome:i,error:o,took:performance.now()-t,restarts:e-1}),l=(e,t)=>(n(!0,t,null),{success:!0,data:e,error:null,timeline:r}),c=e=>(n(!1,"failed",e),{success:!1,data:null,error:e,timeline:r}),g=(e,r)=>s("RETRY_DECISION",{attempt:o.system.attempt,retry:e,reason:r});if(isVigorEmpty(o.policy.target))return c(new VigorRetryError("VALUE_REQUIRED",{method:"request",data:{key:"target"},context:o}));const y=o.policy.target,u=e=>{throw e},d=AbortSignal.any(o.policy.abortSignals);try{for(;o.system.attempt<o.policy.settings.maxAttempts;){o.system.attempt++,s("ATTEMPT_INCREASED",{attempt:o.system.attempt}),s("PROCESS_HANDLING",{type:"RETRY_START",data:{attempt:o.system.attempt}}),o.flags.timedOut=!1;try{const e=e=>{throw o.flags.brokeRetry=!0,e},r=new AbortController,t=new AbortController,i=AbortSignal.any([r.signal,t.signal]),n=AbortSignal.any([i,d]);let c,g;try{await a("before",o.policy.middlewares.before,async(t,i)=>{"fluent"===t._mode?await t.func(o):o=await t.func(o,i({abort:e=>r.abort(e),throwError:u,breakRetry:e}))??o}),n.throwIfAborted();const i=o.policy.settings.timeout;Number.isFinite(i)&&i>0&&(g=setTimeout(()=>{o.flags.timedOut=!0,t.abort(new VigorRetryError("TIMED_OUT",{method:"request",data:{limit:i},context:o}))},Math.min(i,MAX_TIMEOUT2)));const d=o.system.attempt;s("TARGET_REQUEST_STARTED",{attempt:d});const p=performance.now();o.result=await Promise.race([y(n),new Promise((e,r)=>{c=()=>r(n.reason),n.addEventListener("abort",c)})]),s("TARGET_REQUEST_ENDED",{attempt:d,took:performance.now()-p}),await a("after",o.policy.middlewares.after,async(e,r)=>{"fluent"===e._mode?await e.func(o):o=await e.func(o,r({throwError:u}))??o});const h=e=>{o.result=e};return await a("onResult",o.policy.middlewares.onResult,async(e,r)=>{"fluent"===e._mode?o.result=await e.func(o.result):o=await e.func(o,r({setResult:h,throwError:u}))??o}),l(o.result,"result")}finally{clearTimeout(g),c&&n.removeEventListener("abort",c)}}catch(e){if(o.error=e,d.aborted&&(o.flags.aborted=!0),s("PROCESS_HANDLING",{type:"RETRY_ERROR",data:{attempt:o.system.attempt,error:e,timedOut:o.flags.timedOut,aborted:o.flags.aborted}}),o.flags.aborted)throw g(!1,"aborted"),o.error;if(o.flags.brokeRetry)throw g(!1,"breakRetry"),o.error;o.flags.doRetry=!0;const r=()=>o.flags.doRetry=!0,t=()=>o.flags.doRetry=!1;if(await a("retryIf",o.policy.middlewares.retryIf,async(e,i)=>{"fluent"===e._mode?o.flags.doRetry=await e.func(o.error):o=await e.func(o,i({proceedRetry:r,cancelRetry:t}))??o}),!o.flags.doRetry)throw g(!1,"cancelled"),o.error;if(o.system.attempt>=o.policy.settings.maxAttempts){g(!1,"exhausted");break}g(!0,"retry"),o.system.delay=o.policy.algorithms._calculateDelay(o.system.attempt,o.policy.algorithms);const i=e=>{o.system.delay=e};await a("onRetry",o.policy.middlewares.onRetry,async(e,r)=>{"fluent"===e._mode?await e.func(o.error):o=await e.func(o,r({throwError:u,setDelay:i}))??o});const n=Math.min(Math.max(0,Number(o.system.delay)||0),MAX_TIMEOUT2);s("RETRY_DELAY",{attempt:o.system.attempt,delay:n}),await new Promise((e,r)=>{if(d.aborted)return o.flags.aborted=!0,r(d.reason);const t=()=>{clearTimeout(i),o.flags.aborted=!0,r(d.reason)},i=setTimeout(()=>{d.removeEventListener("abort",t),e()},n);d.addEventListener("abort",t,{once:!0})})}}throw new VigorRetryError("RETRY_EXHAUSTED",{method:"request",cause:o.error,data:{maxAttempts:o.policy.settings.maxAttempts,error:o.error},context:o})}catch(i){o.error=i,s("PROCESS_HANDLING",{type:"REQUEST_ERROR",data:{error:i}}),o.flags.doRestart=!1,o.flags.overridden=!1;const n=e=>{o.flags.overridden=!0,o.result=e},g=()=>o.flags.doRestart=!0,y=()=>o.flags.doRestart=!1;try{await a("onError",o.policy.middlewares.onError,async(e,r)=>{"fluent"===e._mode?await e.func(o.error):o=await e.func(o,r({setResult:n,throwError:u,proceedRestart:g,cancelRestart:y}))??o})}catch(e){return c(e)}if(o.flags.doRestart)return e>o.policy.settings.maxRestarts?c(new VigorRetryError("RESTART_EXHAUSTED",{method:"request",cause:o.error,data:{maxAttempts:o.policy.settings.maxRestarts,error:o.error},context:o})):(s("PROCESS_HANDLING",{type:"REQUEST_RESTART",data:{restartAttempt:e+1}}),await this.requestRuntime(e+1,r,t));if(o.flags.overridden)return l(o.result,"overridden");if(!isVigorEmpty(o.policy.settings.default))try{return l(await o.policy.settings.default(o),"default")}catch(e){return c(e)}return c(o.error)}}},VigorParsePolicySettingsBase={__brand:createBrand("Parse","Policy<Settings<Schema"),debug:!1,raw:!1,default:VigorEmpty,maxRestarts:3},VigorParsePolicySettings=class _VigorParsePolicySettings extends VigorStatus{constructor(e=VigorParseBase){super(VigorParseBase,e)}_create(e){return new _VigorParsePolicySettings(e)}raw(e){return this._next({policy:{settings:{raw:e}}})}default(e){return this._next({policy:{settings:{default:e}}})}maxRestarts(e){return this._next({policy:{settings:{maxRestarts:e}}})}debug(e){return this._next({policy:{settings:{debug:e}}})}},VigorParsePolicyMiddlewaresBase={__brand:createBrand("Parse","Policy<Middlewares<Schema"),before:[],after:[],onResult:[],onError:[]},VigorParsePolicyMiddlewares=class _VigorParsePolicyMiddlewares extends VigorStatus{constructor(e=VigorParseBase){super(VigorParseBase,e)}_create(e){return new _VigorParsePolicyMiddlewares(e)}before(e,r){return this._next({policy:{middlewares:{before:[{_mode:e,func:r}]}}})}after(e,r){return this._next({policy:{middlewares:{after:[{_mode:e,func:r}]}}})}onResult(e,r){return this._next({policy:{middlewares:{onResult:[{_mode:e,func:r}]}}})}onError(e,r){return this._next({policy:{middlewares:{onError:[{_mode:e,func:r}]}}})}},describeVigorParseFailure=e=>e instanceof Error?`${e.name}: ${e.message}`:String(e),VigorParseErrorMessageFuncs={VALUE_REQUIRED:({key:e})=>`Value Required (missing ${e})`,INVALID_CONTENT_TYPE:({received:e})=>`Invalid Content-Type header: ${String(e)}`,PARSER_NOT_FOUND:({received:e,expected:r})=>`Parser not found for Content-Type "${String(e)}" (known: ${r.join(", ")})`,PARSER_ALL_FAILED:({tried:e,errors:r})=>`All parsers failed: ${e.map((e,t)=>`${e} (${describeVigorParseFailure(r[t])})`).join(", ")}`,RESTART_EXHAUSTED:({maxAttempts:e})=>`Restart exhausted, (max ${e})`},VigorParseError=class extends VigorError{constructor(e,r){super(e,(0,VigorParseErrorMessageFuncs[e])(r.data),r)}};function isVigorParseError(e,...r){return runVigorGuard(e,r,(e,r)=>e instanceof VigorParseError&&(0===r.length||r.includes(e.code)))}var VigorParsePolicyStrategiesBase={__brand:createBrand("Parse","Policy<Strategies<Schema"),funcs:[]},bodyCache=new WeakMap;async function readVigorParseBody(e){let r=bodyCache.get(e);return r||(r=null===e.body?Promise.resolve(new Uint8Array(0)):e.arrayBuffer().then(e=>new Uint8Array(e)),bodyCache.set(e,r)),{bytes:await r,contentType:e.headers.get("content-type"),status:e instanceof Response?e.status:null,headers:e.headers,source:e}}var utf8=new TextDecoder("utf-8"),getCharset=e=>/;\s*charset\s*=\s*"?([^";\s]+)"?/i.exec(e??"")?.[1]??"utf-8",getMimeType=e=>(e??"").split(";")[0].trim().toLowerCase(),decodeText=(e,r=!1)=>{let t;try{t=new TextDecoder(getCharset(e.contentType),{fatal:r})}catch{t=new TextDecoder("utf-8",{fatal:r})}return t.decode(e.bytes)},parseJson=e=>JSON.parse(utf8.decode(e.bytes)),parseJsonOrNull=e=>{const r=utf8.decode(e.bytes);return""===r.trim()?null:JSON.parse(r)},hexValue=e=>e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1,decodeFormComponent=e=>{const r=new Uint8Array(e.length);let t=0;for(let i=0;i<e.length;i++){const o=e[i];if(43!==o){if(37===o&&i+2<e.length){const o=hexValue(e[i+1]),s=hexValue(e[i+2]);if(o>=0&&s>=0){r[t++]=16*o+s,i+=2;continue}}r[t++]=o}else r[t++]=32}return utf8.decode(r.subarray(0,t))},parseUrlEncoded=e=>{const r=new FormData,{bytes:t}=e;let i=0;for(let e=0;e<=t.length;e++){if(e<t.length&&38!==t[e])continue;const o=t.subarray(i,e);if(i=e+1,0===o.length)continue;const s=o.indexOf(61),a=-1===s?o:o.subarray(0,s),n=-1===s?new Uint8Array(0):o.subarray(s+1);r.append(decodeFormComponent(a),decodeFormComponent(n))}return r},parseMultipart=e=>new Response(e.bytes,{headers:{"content-type":e.contentType??""}}).formData(),parseFormData=e=>{const r=getMimeType(e.contentType);if("application/x-www-form-urlencoded"===r)return parseUrlEncoded(e);if("multipart/form-data"===r)return parseMultipart(e);throw new VigorParseError("INVALID_CONTENT_TYPE",{method:"parseFormData",data:{received:e.contentType}})},toArrayBuffer=e=>e.bytes.slice().buffer,toBlob=e=>new Blob([e.bytes],{type:e.contentType??""}),NoBodyStatus=[204,205,304],ContentTypeParsers=[{header:"application/json",regExp:/application\/(.+\+)?json(.+\+)?/i,method:parseJsonOrNull},{header:"application/xml",regExp:/application\/(.+\+)?xml(.+\+)?/i,method:e=>decodeText(e)},{header:"application/x-www-form-urlencoded",regExp:/application\/(.+\+)?x-www-form-urlencoded(.+\+)?/i,method:parseUrlEncoded},{header:"application/octet-stream",regExp:/application\/(.+\+)?octet-stream(.+\+)?/i,method:toArrayBuffer},{header:"image/*",regExp:/^image\/.+/i,method:toBlob},{header:"audio/*",regExp:/^audio\/.+/i,method:toBlob},{header:"video/*",regExp:/^video\/.+/i,method:toBlob},{header:"multipart/form-data",regExp:/multipart\/(.+\+)?form-data(.+\+)?/i,method:parseMultipart},{header:"text/*",regExp:/^text\/.+/i,method:e=>decodeText(e)}],SniffMethods=[{title:"json",method:parseJson},{title:"formData",method:parseFormData},{title:"text",method:e=>decodeText(e,!0)},{title:"blob",method:toBlob}],VigorParseContentTypeStrategy=async e=>{if(0===e.bytes.length||null!==e.status&&NoBodyStatus.includes(e.status))return null;if(!e.contentType)return decodeText(e);const r=ContentTypeParsers.find(r=>r.regExp.test(e.contentType));return r?await r.method(e):toBlob(e)},VigorParseSniffStrategy=async e=>{const r=[];for(const t of SniffMethods)try{return await t.method(e)}catch(e){r.push(e)}throw new VigorParseError("PARSER_ALL_FAILED",{method:"VigorParseSniffStrategy",cause:r.at(-1),data:{tried:SniffMethods.map(e=>e.title),errors:r}})},VigorParsePolicyStrategies=class _VigorParsePolicyStrategies extends VigorStatus{constructor(e=VigorParseBase){super(VigorParseBase,e)}_create(e){return new _VigorParsePolicyStrategies(e)}_set(e,r){return this._next({policy:{strategies:{funcs:e}}},r?{policy:{strategies:{funcs:"replace"}}}:void 0)}contentType(e){return this._set([VigorParseContentTypeStrategy],e)}sniff(e){return this._set([VigorParseSniffStrategy],e)}json(e){return this._set([parseJson],e)}text(e){return this._set([e=>decodeText(e)],e)}arrayBuffer(e){return this._set([toArrayBuffer],e)}blob(e){return this._set([toBlob],e)}bytes(e){return this._set([e=>e.bytes.slice()],e)}formData(e){return this._set([parseFormData],e)}custom(e,r){return this._set([e],r)}},VigorParsePolicyBase={__brand:createBrand("Parse","Policy<Schema"),target:VigorDefault,settings:VigorParsePolicySettingsBase,middlewares:VigorParsePolicyMiddlewaresBase,strategies:VigorParsePolicyStrategiesBase},VigorParseContextBase={__brand:createBrand("Parse","Context<Schema"),result:VigorDefault,error:VigorDefault,response:VigorDefault,flags:{overridden:!1,restarted:!1},record:{},timeline:[],policy:VigorParsePolicyBase},VigorParseBase={__brand:createBrand("Parse","Schema"),policy:VigorParsePolicyBase,cast:VigorEmpty},VigorParse=class _VigorParse extends VigorStatus{constructor(e=VigorParseBase){super(VigorParseBase,e)}_create(e){return new _VigorParse(e)}target(e){return this._next({policy:{target:e}})}settings(e){if("function"==typeof e||e instanceof VigorParsePolicySettings){const r="function"==typeof e?e(new VigorParsePolicySettings(this.config)):e;return this._next({policy:{settings:r.config.policy.settings}})}return this._next({policy:{settings:e}})}middlewares(e){if("function"==typeof e||e instanceof VigorParsePolicyMiddlewares){const r="function"==typeof e?e(new VigorParsePolicyMiddlewares):e;return this._next({policy:{middlewares:r.config.policy.middlewares}})}return this._next({policy:{middlewares:e}})}strategies(e){if("function"==typeof e||e instanceof VigorParsePolicyStrategies){const r="function"==typeof e?e(new VigorParsePolicyStrategies):e;return this._next({policy:{strategies:r.config.policy.strategies}})}return this._next({policy:{strategies:e}})}cast(){return this._next({cast:VigorCastPlaceholder},{cast:"replace"})}async request(){const e=await this.requestVerbose();if(e.success)return e.data;throw e.error}async requestVerbose(){return await this.requestRuntime()}async requestRuntime(e=1,r=[],t=performance.now()){const i=this._merge(this.config,{});let o=this._merge(VigorParseContextBase,{policy:i.policy},void 0,"replace");o.timeline=r;const{add:s,stage:a}=createVigorTimelineRecorder(r,()=>this._snapshot(o),i.policy.settings.debug);s("PROCESS_HANDLING",{type:"REQUEST_START",data:{restartAttempt:e}});const n=(r,i,o)=>s("REQUEST_END",{success:r,outcome:i,error:o,took:performance.now()-t,restarts:e-1}),l=(e,t)=>(n(!0,t,null),{success:!0,data:e,error:null,timeline:r}),c=e=>(n(!1,"failed",e),{success:!1,data:null,error:e,timeline:r});if(isVigorDefault(o.policy.target))return c(new VigorParseError("VALUE_REQUIRED",{method:"request",data:{key:"target"},context:o}));o.response=o.policy.target;const g=e=>{throw e};try{if(await a("before",o.policy.middlewares.before,async(e,r)=>{"fluent"===e._mode?await e.func(o):o=await e.func(o,r({throwError:g}))??o}),o.policy.settings.raw)o.result=o.response;else{const e=performance.now(),r=await readVigorParseBody(o.response);s("BODY_READ",{size:r.bytes.byteLength,took:performance.now()-e});const t=o.policy.strategies.funcs.length>0?o.policy.strategies.funcs:[VigorParseContentTypeStrategy];let i=!1;const a=[];for(const[e,n]of t.entries()){s("STRATEGY_STARTED",{index:e});const t=performance.now();try{o.result=await n(r),s("STRATEGY_SUCCEEDED",{index:e,took:performance.now()-t}),i=!0;break}catch(r){a.push(r),s("STRATEGY_FAILED",{index:e,error:r,took:performance.now()-t})}}if(!i)throw new VigorParseError("PARSER_ALL_FAILED",{method:"request",cause:a.at(-1),data:{tried:t.map((e,r)=>`strategy#${r}`),errors:a},context:o})}const e=e=>{o.result=e};return await a("after",o.policy.middlewares.after,async(r,t)=>{"fluent"===r._mode?await r.func(o):o=await r.func(o,t({setResult:e,throwError:g}))??o}),await a("onResult",o.policy.middlewares.onResult,async(r,t)=>{"fluent"===r._mode?o.result=await r.func(o.result):o=await r.func(o,t({setResult:e,throwError:g}))??o}),l(o.result,"result")}catch(i){o.error=i,s("PROCESS_HANDLING",{type:"REQUEST_ERROR",data:{error:i}}),o.flags.overridden=!1,o.flags.restarted=!1;const n=e=>{o.flags.overridden=!0,o.result=e},y=()=>o.flags.restarted=!0,u=()=>o.flags.restarted=!1;try{await a("onError",o.policy.middlewares.onError,async(e,r)=>{"fluent"===e._mode?await e.func(o.error):o=await e.func(o,r({setResult:n,throwError:g,proceedRestart:y,cancelRestart:u}))??o})}catch(e){return c(e)}if(o.flags.restarted)return e>o.policy.settings.maxRestarts?c(new VigorParseError("RESTART_EXHAUSTED",{method:"request",cause:o.error,data:{maxAttempts:o.policy.settings.maxRestarts,error:o.error},context:o})):(s("PROCESS_HANDLING",{type:"REQUEST_RESTART",data:{restartAttempt:e+1}}),await this.requestRuntime(e+1,r,t));if(o.flags.overridden)return l(o.result,"overridden");if(!isVigorEmpty(o.policy.settings.default))try{return l(await o.policy.settings.default(o),"default")}catch(e){return c(e)}return c(o.error)}}},VigorFetchErrorMessageFuncs={...VigorRetryErrorMessageFuncs,...VigorParseErrorMessageFuncs,VALUE_REQUIRED:({key:e})=>`Value Required (missing ${e})`,SERIALIZE_FAILED:({stage:e,received:r})=>`The "${e}" serializer left a non-string value (${typeof r}): its last step must produce strings`,INVALID_BODY:({received:e})=>"Invalid Body type: "+typeof e,BODY_NOT_ALLOWED:({method:e})=>`A ${e} request cannot have a body`,INVALID_PROTOCOL:({origin:e,base:r})=>r?`Invalid URL: could not resolve "${e}" against base "${r}"`:`Invalid URL: "${e}" is not an absolute URL, and no base (window.location) is available to resolve it against — pass an absolute origin (e.g. "https://api.example.com") when running outside a browser`,FETCH_FAILED:({status:e,statusText:r})=>`Fetch Failed: ${e} ${r}`,RESTART_EXHAUSTED:({maxAttempts:e})=>`Restart exhausted, (max ${e})`,PATH_ESCAPED:({url:e,base:r})=>`Path escapes "${r}": the request would go to "${e}" (serializers.url confine)`,REDIRECTED:({url:e,status:r})=>`Redirected (${r}) to "${e}" — navigating away`},VigorFetchError=class extends VigorError{constructor(e,r){super(e,(0,VigorFetchErrorMessageFuncs[e])(r.data),r)}};function isVigorFetchError(e,...r){return runVigorGuard(e,r,(e,r)=>e instanceof VigorFetchError&&(0===r.length||r.includes(e.code)))}function adoptVigorFetchError(e,r){if(!(e instanceof VigorRetryError||e instanceof VigorParseError))return e;const t=e.data,i=null!==t&&"object"==typeof t&&"error"in t?{...t,error:adoptVigorFetchError(t.error,r)}:t;return new VigorFetchError(e.code,{method:e.method,cause:e,data:i,context:r})}var step=(e,r)=>({name:e,func:r}),vigorStringifyValue=e=>e instanceof Date?e.toISOString():String(e),isNullish=e=>null==e,VigorPathSteps={dropNullish:()=>step("dropNullish",e=>e.filter(e=>!isNullish(e))),stringify:()=>step("stringify",e=>e.map(vigorStringifyValue)),split:(e="/")=>step(`split(${JSON.stringify(e)})`,r=>r.flatMap(r=>"string"==typeof r?r.split(e).filter(Boolean):[r])),encode:()=>step("encode",e=>e.map(e=>"string"==typeof e?encodeURIComponent(e):e)),prefixOrigin:()=>step("prefixOrigin",(e,{origin:r})=>[...r.pathname.split("/").filter(Boolean),...e])},VigorQuerySteps={fromOrigin:()=>step("fromOrigin",(e,{origin:r})=>[...r.searchParams.entries(),...e]),dropNullish:()=>step("dropNullish",e=>e.filter(([,e])=>!isNullish(e))),arrays:(e="repeat")=>step(`arrays(${JSON.stringify(e)})`,r=>r.flatMap(([r,t])=>{if(!Array.isArray(t))return[[r,t]];if("comma"===e)return[[r,t.map(vigorStringifyValue).join(",")]];const i="brackets"===e?`${r}[]`:r;return t.map(e=>[i,vigorStringifyValue(e)])})),stringify:()=>step("stringify",e=>e.map(([e,r])=>[e,vigorStringifyValue(r)]))},VigorUrlSteps={hashFromOrigin:()=>step("hashFromOrigin",(e,{origin:r})=>{e.hash||(e.hash=r.hash)}),confine:()=>step("confine",(e,{origin:r,context:t})=>{const i="/"+r.pathname.replace(/^\/+|\/+$/g,""),o="/"===i||e.pathname===i||e.pathname.startsWith(i+"/");if(e.origin!==r.origin||!o)throw new VigorFetchError("PATH_ESCAPED",{method:"serialize",data:{url:e.href,base:r.origin+("/"===i?"":i)},context:t})})},VigorBodySteps={text:()=>step("text",e=>"string"==typeof e?{body:e,contentType:"text/plain;charset=UTF-8"}:void 0),blob:()=>step("blob",e=>e instanceof Blob?{body:e,contentType:e.type||null}:void 0),binary:()=>step("binary",e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{body:e,contentType:"application/octet-stream"}:void 0),stream:()=>step("stream",e=>"undefined"!=typeof ReadableStream&&e instanceof ReadableStream?{body:e,contentType:"application/octet-stream"}:void 0),urlencoded:()=>step("urlencoded",e=>e instanceof URLSearchParams?{body:e,contentType:"application/x-www-form-urlencoded;charset=UTF-8"}:void 0),formData:()=>step("formData",e=>e instanceof FormData?{body:e,contentType:null}:void 0),json:()=>step("json",e=>"object"==typeof e&&null!==e?{body:JSON.stringify(e),contentType:"application/json"}:void 0)},VigorHeadersSteps={caseInsensitive:()=>step("caseInsensitive",e=>{const r={};for(const[t,i]of Object.entries(e)){for(const e of Object.keys(r))e.toLowerCase()===t.toLowerCase()&&delete r[e];r[t]=i}return r}),contentType:()=>step("contentType",(e,{contentType:r})=>!r||Object.keys(e).some(e=>"content-type"===e.toLowerCase())?e:{...e,"Content-Type":r})},VigorSerializerChain=class{constructor(e=[]){this.steps=e}steps;_add(e){return this._create([...this.steps,e])}custom(e,r){return this._add(step(e,r))}},VigorPathSerializer=class _VigorPathSerializer extends VigorSerializerChain{_create(e){return new _VigorPathSerializer(e)}dropNullish(){return this._add(VigorPathSteps.dropNullish())}stringify(){return this._add(VigorPathSteps.stringify())}split(e){return this._add(VigorPathSteps.split(e))}encode(){return this._add(VigorPathSteps.encode())}prefixOrigin(){return this._add(VigorPathSteps.prefixOrigin())}},VigorQuerySerializer=class _VigorQuerySerializer extends VigorSerializerChain{_create(e){return new _VigorQuerySerializer(e)}fromOrigin(){return this._add(VigorQuerySteps.fromOrigin())}dropNullish(){return this._add(VigorQuerySteps.dropNullish())}arrays(e){return this._add(VigorQuerySteps.arrays(e))}stringify(){return this._add(VigorQuerySteps.stringify())}},VigorUrlSerializer=class _VigorUrlSerializer extends VigorSerializerChain{_create(e){return new _VigorUrlSerializer(e)}hashFromOrigin(){return this._add(VigorUrlSteps.hashFromOrigin())}confine(){return this._add(VigorUrlSteps.confine())}},VigorBodySerializer=class _VigorBodySerializer extends VigorSerializerChain{_create(e){return new _VigorBodySerializer(e)}text(){return this._add(VigorBodySteps.text())}blob(){return this._add(VigorBodySteps.blob())}binary(){return this._add(VigorBodySteps.binary())}stream(){return this._add(VigorBodySteps.stream())}urlencoded(){return this._add(VigorBodySteps.urlencoded())}formData(){return this._add(VigorBodySteps.formData())}json(){return this._add(VigorBodySteps.json())}},VigorHeadersSerializer=class _VigorHeadersSerializer extends VigorSerializerChain{_create(e){return new _VigorHeadersSerializer(e)}caseInsensitive(){return this._add(VigorHeadersSteps.caseInsensitive())}contentType(){return this._add(VigorHeadersSteps.contentType())}},VigorFetchSerializersBase={path:[...(new VigorPathSerializer).dropNullish().stringify().split("/").encode().prefixOrigin().steps],query:[...(new VigorQuerySerializer).fromOrigin().dropNullish().arrays("repeat").stringify().steps],url:[...(new VigorUrlSerializer).hashFromOrigin().confine().steps],body:[...(new VigorBodySerializer).text().blob().binary().stream().urlencoded().formData().json().steps],headers:[...(new VigorHeadersSerializer).caseInsensitive().contentType().steps]},VigorFetchPolicySerializers=class _VigorFetchPolicySerializers{constructor(e={}){this.stages=e}stages;_set(e,r){return new _VigorFetchPolicySerializers({...this.stages,[e]:[...r]})}path(e){return this._set("path",e(new VigorPathSerializer).steps)}query(e){return this._set("query",e(new VigorQuerySerializer).steps)}url(e){return this._set("url",e(new VigorUrlSerializer).steps)}body(e){return this._set("body",e(new VigorBodySerializer).steps)}headers(e){return this._set("headers",e(new VigorHeadersSerializer).steps)}},VigorFetchPolicyBase={__brand:createBrand("Fetch","Policy<Schema"),method:VigorEmpty,origin:VigorEmpty,path:[],query:[],hash:"",headers:{},body:VigorEmpty,extra:{},serializers:VigorFetchSerializersBase,settings:VigorFetchPolicySettingsBase,middlewares:VigorFetchPolicyMiddlewaresBase,retry:VigorRetryBase,parse:VigorParseBase},VigorFetchContextBase={__brand:createBrand("Fetch","Context<Schema"),href:"",response:VigorDefault,result:VigorDefault,error:VigorDefault,options:VigorDefault,flags:{overridden:!1,restarted:!1},record:{},timeline:[],policy:VigorFetchPolicyBase},VigorFetchRetryMergeStrategy={policy:{algorithms:"replace"}},VigorFetchBase={__brand:createBrand("Fetch","Schema"),policy:VigorFetchPolicyBase,cast:VigorEmpty,apiMap:VigorEmpty},VigorFetch=class _VigorFetch extends VigorStatus{constructor(e=VigorFetchBase){super(VigorFetchBase,e)}_create(e){return new _VigorFetch(e)}method(e){return this._next({policy:{method:e}})}origin(e){return this._next({policy:{origin:e}})}path(e,...r){return this._next({policy:{path:r}},"replace"===e?{policy:{path:"replace"}}:void 0)}query(e,...r){return this._next({policy:{query:r}},"replace"===e?{policy:{query:"replace"}}:void 0)}hash(e){return this._next({policy:{hash:e}},{policy:{hash:"replace"}})}headers(e,r){return"replace"===e?this._next({policy:{headers:r}},{policy:{headers:"replace"}}):this._next({policy:{headers:r}})}body(e,r){const t=this.config.policy.body,i="merge"===e&&this._isPlainObject(t)&&this._isPlainObject(r)?{...t,...r}:r;return this._next({policy:{body:i}},{policy:{body:"replace"}})}options(e,r){const t="merge"===e?{...this.config.policy.extra,...r}:r;return this._next({policy:{extra:t}},{policy:{extra:"replace"}})}serializers(e){const r="function"==typeof e?e(new VigorFetchPolicySerializers).stages:e instanceof VigorFetchPolicySerializers?e.stages:e;return this._next({policy:{serializers:r}},{policy:{serializers:{path:"replace",query:"replace",url:"replace",body:"replace",headers:"replace"}}})}settings(e){const r={policy:{settings:{retryHeaders:"replace",unretryStatus:"replace"}}};if("function"==typeof e||e instanceof VigorFetchPolicySettings){const t="function"==typeof e?e(new VigorFetchPolicySettings(this.config)):e;return this._next({policy:{settings:t.config.policy.settings}},r)}return this._next({policy:{settings:e}},r)}middlewares(e){if("function"==typeof e||e instanceof VigorFetchPolicyMiddlewares){const r="function"==typeof e?e(new VigorFetchPolicyMiddlewares):e;return this._next({policy:{middlewares:r.config.policy.middlewares}})}return this._next({policy:{middlewares:e}})}retry(e){if(e instanceof VigorRetry)return this._next({policy:{retry:e.config}},{policy:{retry:"replace"}});if("function"==typeof e){const r=e(new VigorRetry(this.config.policy.retry));return this._next({policy:{retry:r.config}},{policy:{retry:"replace"}})}return this._next({policy:{retry:e}},{policy:{retry:VigorFetchRetryMergeStrategy}})}parse(e){if(e instanceof VigorParse)return this._next({policy:{parse:e.config}},{policy:{parse:"replace"}});if("function"==typeof e){const r=e(new VigorParse(this.config.policy.parse));return this._next({policy:{parse:r.config}},{policy:{parse:"replace"}})}return this._next({policy:{parse:e}})}_isPlainObject(e){return null!==e&&"object"==typeof e&&Object.getPrototypeOf(e)===Object.prototype}_resolveBase(){if("undefined"!=typeof globalThis&&globalThis.location?.href)return globalThis.location.href}_resolveOrigin(e,r){const t=this._resolveBase();try{return new URL(e,t)}catch{throw new VigorFetchError("INVALID_PROTOCOL",{method:"_resolveOrigin",data:{origin:e,base:t},context:r})}}_runStage(e,r,t,i,o){for(const e of r)t=e.func(t,i)??t;return o(e,r.map(e=>e.name),t),t}_requireStrings(e,r,t){const i=r.findIndex(e=>"string"!=typeof e);if(-1!==i)throw new VigorFetchError("SERIALIZE_FAILED",{method:"_serializeUrl",data:{stage:e,received:r[i]},context:t})}_serializeUrl(e,r){const{context:t}=e,i=t.policy.serializers,o=this._runStage("path",i.path,[...t.policy.path],e,r);this._requireStrings("path",o,t);const s=this._runStage("query",i.query,t.policy.query.flatMap(e=>Object.entries(e)),e,r);this._requireStrings("query",s.flat(),t);let a=new URL("/"+o.join("/"),e.origin.origin);for(const[e,r]of s)a.searchParams.append(e,r);return a.hash=t.policy.hash,a=this._runStage("url",i.url,a,e,r),a.href}_serializeBody(e,r,t){const{context:i}=e,o=i.policy.serializers;let s;if(r){const r=[];for(const t of o.body)if(r.push(t.name),s=t.func(i.policy.body,e),s)break;if(t("body",r,s),!s)throw new VigorFetchError("INVALID_BODY",{method:"_serializeBody",data:{received:i.policy.body},context:i})}const a=this._runStage("headers",o.headers,{...i.policy.headers},{...e,contentType:s?.contentType??null},t);return{body:s?.body,headers:a}}_resolveRedirect(e,r){if(e.redirected&&e.url)return e.url;if(e.status<300||e.status>=400)return null;const t=e.headers.get("location");if(!t)return null;try{return new URL(t,e.url||r).href}catch{return null}}_browserLocation(){const e=globalThis.window;return void 0!==e?.location?.href?e.location:null}_parseRetryHeader(e){if(!e)return null;const r=Number(e);let t;if(""===e.trim()||isNaN(r)){const r=new Date(e).getTime();if(isNaN(r))return null;t=r-Date.now()}else t=r>=1e12?r-Date.now():r>=1e9?1e3*r-Date.now():1e3*r;return t>0?t:null}apiMap(){return this._next({apiMap:VigorCastPlaceholder},{apiMap:"replace"})}route(e,...r){const t=e,i=t.indexOf(" "),o=t.slice(0,i),s=r[0]??{},a=t.slice(i+1).split("/").filter(Boolean).map(e=>{if(!e.startsWith(":"))return e;const r=e.slice(1),t=s[r];if(null==t)throw new VigorFetchError("VALUE_REQUIRED",{method:"route",data:{key:`params.${r}`}});return t});return this.method(o).path("append",...a)}cast(){return this._next({cast:VigorCastPlaceholder},{cast:"replace"})}async request(){const e=await this.requestRuntime();if(e.success)return e.data;throw e.error}async requestVerbose(){return await this.requestRuntime()}async requestRuntime(e=1,r=[],t=performance.now()){const i=this._merge(this.config,{});let o=this._merge(VigorFetchContextBase,{policy:i.policy},void 0,"replace");o.timeline=r;const{add:s,stage:a}=createVigorTimelineRecorder(r,()=>this._snapshot(o),i.policy.settings.debug);s("PROCESS_HANDLING",{type:"REQUEST_START",data:{restartAttempt:e}});const n=(r,i,o)=>s("REQUEST_END",{success:r,outcome:i,error:o,took:performance.now()-t,restarts:e-1}),l=(e,t,i=null)=>(n(!0,t,null),{success:!0,data:e,error:null,status:i?.status??null,response:i,timeline:r}),c=e=>(n(!1,"failed",e),{success:!1,data:null,error:e,status:null,response:null,timeline:r});let g=0;const y=async(e,r,t)=>{s("PARSE_STARTED",{engine:t,source:e,attempt:r});const i=performance.now(),o=await t.requestVerbose();return s("PARSE_ENDED",{engine:t,source:e,attempt:r,timeline:o.timeline,took:performance.now()-i,result:o.success?o.data:VigorDefault}),o},u=e=>{throw e};try{if(isVigorEmpty(o.policy.origin))throw new VigorFetchError("VALUE_REQUIRED",{method:"request",data:{key:"origin"},context:o});const e={origin:this._resolveOrigin(o.policy.origin,o),context:o},r=(e,r,t)=>s("SERIALIZED",{stage:e,steps:r,output:t});o.href=this._serializeUrl(e,r),s("BUILT_URL",{url:o.href});const t=!isVigorEmpty(o.policy.body)&&null!=o.policy.body,n=isVigorEmpty(o.policy.method)?t?"POST":"GET":o.policy.method,{body:c,headers:d}=this._serializeBody(e,t,r),p={...o.policy.extra,method:n,headers:d};void 0!==c&&(p.body=c),o.options=p,await a("before",o.policy.middlewares.before,async(e,r)=>{"fluent"===e._mode?await e.func(o):o=await e.func(o,r({throwError:u,setOptions:e=>{o.options=e},setHeaders:e=>{o.options.headers=e},setBody:e=>{o.options.body=e}}))??o});const h=isVigorDefault(o.options)?p:o.options;o.options=h,s("SET_OPTIONS",{options:h});const f=(h.method??"GET").toUpperCase();if(null!=h.body&&("GET"===f||"HEAD"===f))throw new VigorFetchError("BODY_NOT_ALLOWED",{method:"request",data:{method:f},context:o});const m="undefined"!=typeof ReadableStream&&h.body instanceof ReadableStream;m&&(h.duplex??="half");const V={policy:{settings:{debug:!0}}},_=new VigorParse(i.policy.settings.debug?this._merge(o.policy.parse,V):o.policy.parse),w=isVigorEmpty(o.policy.settings.fetcher)?globalThis.fetch:o.policy.settings.fetcher,E=new VigorRetry(i.policy.settings.debug?this._merge(o.policy.retry,V):o.policy.retry).target(async e=>await w(o.href,{...h,signal:e})).middlewares(e=>e.after("intercept",async(e,r)=>{const t=e.result;if(g=e.system.attempt,s("RESPONSE_RECEIVED",{attempt:e.system.attempt,status:t.status,statusText:t.statusText,ok:t.ok,redirected:t.redirected,url:t.url}),o.policy.settings.redirect){const e=this._resolveRedirect(t,o.href),i=this._browserLocation();e&&i&&(i.href=e,r.throwError(new VigorFetchError("REDIRECTED",{method:"request",data:{url:e,status:t.status,response:t},context:o})))}if(!t.ok&&304!==t.status){const i=await y("failedResponse",e.system.attempt,_.target(t.clone())),s=i.success?i.data:void 0;r.throwError(new VigorFetchError("FETCH_FAILED",{method:"request",data:{status:t.status,statusText:t.statusText,response:t,url:t.url,parsed:s},context:o}))}return o.policy.parse.policy.settings.raw||await readVigorParseBody(t),e}).retryIf("intercept",async(e,r)=>{const t=e.error instanceof VigorFetchError?e.error.data?.response:void 0;return(e.error instanceof VigorFetchError&&"REDIRECTED"===e.error.code||m||t&&("opaqueredirect"===t.type||t.status>=300&&t.status<400)||t&&o.policy.settings.unretryStatus.includes(t.status))&&r.cancelRetry(),e}).onRetry("intercept",async(e,r)=>{const t=e.error instanceof VigorFetchError?e.error.data?.response:void 0;if(429===t?.status||503===t?.status)for(const e of o.policy.settings.retryHeaders){const i=this._parseRetryHeader(t.headers.get(e));if(null!==i){r.setDelay(Math.min(i,o.policy.settings.maxRetryAfter));break}}return e}));for(const e of["after","retryIf","onRetry"]){const r=E.config.policy.middlewares[e];markVigorInternal(r[r.length-1].func)}s("ENGINE_CREATED",{retryEngine:E,parseEngine:_});const R=await(async e=>{s("RETRY_STARTED",{engine:e});const r=performance.now(),t=await e.requestVerbose();return s("RETRY_ENDED",{engine:e,timeline:t.timeline,took:performance.now()-r,response:t.success?t.data:VigorDefault}),t})(E);if(!R.success)throw adoptVigorFetchError(R.error,o);o.response=R.data;const x=await y("response",g,_.target(o.response));if(!x.success)throw adoptVigorFetchError(x.error,o);o.result=x.data,await a("after",o.policy.middlewares.after,async(e,r)=>{"fluent"===e._mode?await e.func(o):o=await e.func(o,r({throwError:u,setResult:e=>{o.result=e}}))??o});const P=e=>{o.result=e};return await a("onResult",o.policy.middlewares.onResult,async(e,r)=>{"fluent"===e._mode?o.result=await e.func(o.result):o=await e.func(o,r({setResult:P,throwError:u}))??o}),l(o.result,"result",o.response)}catch(i){o.error=i,s("PROCESS_HANDLING",{type:"REQUEST_ERROR",data:{error:i}}),o.flags.overridden=!1,o.flags.restarted=!1;const n=e=>{o.flags.overridden=!0,o.result=e},g=()=>o.flags.restarted=!0,y=()=>o.flags.restarted=!1;try{await a("onError",o.policy.middlewares.onError,async(e,r)=>{"fluent"===e._mode?await e.func(o.error):o=await e.func(o,r({setResult:n,throwError:u,proceedRestart:g,cancelRestart:y}))??o})}catch(e){return c(e)}if(o.flags.restarted)return e>o.policy.settings.maxRestarts?c(new VigorFetchError("RESTART_EXHAUSTED",{method:"request",cause:o.error,data:{maxAttempts:o.policy.settings.maxRestarts,error:o.error},context:o})):(s("PROCESS_HANDLING",{type:"REQUEST_RESTART",data:{restartAttempt:e+1}}),await this.requestRuntime(e+1,r,t));if(o.flags.overridden)return l(o.result,"overridden");if(!isVigorEmpty(o.policy.settings.default))try{return l(await o.policy.settings.default(o),"default")}catch(e){return c(e)}return c(i)}}};function retryWithTarget(e){return(new VigorRetry).target(e)}function parseWithTarget(e){return(new VigorParse).target(e)}function fetchWithOrigin(e){return(new VigorFetch).origin(e)}function allWithTargets(e){return(new VigorAll).target(...e)}var vigorBase={retry:e=>void 0!==e?retryWithTarget(e):new VigorRetry,parse:e=>void 0!==e?parseWithTarget(e):new VigorParse,fetch:e=>void 0!==e?fetchWithOrigin(e):new VigorFetch,all:(...e)=>e.length>0?allWithTargets(e):new VigorAll,builders:{fetch:{settings:()=>new VigorFetchPolicySettings,middlewares:()=>new VigorFetchPolicyMiddlewares,serializers:()=>new VigorFetchPolicySerializers},retry:{settings:()=>new VigorRetryPolicySettings,middlewares:()=>new VigorRetryPolicyMiddlewares,algorithms:()=>new VigorRetryPolicyAlgorithms,algorithm:{constant:()=>new VigorRetryPolicyAlgorithmsConstant,linear:()=>new VigorRetryPolicyAlgorithmsLinear,backoff:()=>new VigorRetryPolicyAlgorithmsBackoff,custom:()=>new VigorRetryPolicyAlgorithmsCustom}},parse:{settings:()=>new VigorParsePolicySettings,middlewares:()=>new VigorParsePolicyMiddlewares,strategies:()=>new VigorParsePolicyStrategies},all:{settings:()=>new VigorAllPolicySettings,middlewares:()=>new VigorAllPolicyMiddlewares}},guards:{retry:isVigorRetryError,parse:isVigorParseError,fetch:isVigorFetchError,all:isVigorAllError}},cloneVigor=e=>({...e,builders:{fetch:{...e.builders.fetch},retry:{...e.builders.retry,algorithm:{...e.builders.retry.algorithm}},parse:{...e.builders.parse},all:{...e.builders.all}},guards:{...e.guards}}),createVigor=e=>{const r={...e,use:(e,t)=>{const i=e.func(r,{...e.options,...t}),{use:o,...s}={...cloneVigor(r),...i};return createVigor(s)}};return r},vigor=createVigor(vigorBase),index_default=vigor;exports.VigorAll=VigorAll,exports.VigorAllBase=VigorAllBase,exports.VigorAllContextBase=VigorAllContextBase,exports.VigorAllEachContextBase=VigorAllEachContextBase,exports.VigorAllError=VigorAllError,exports.VigorAllErrorMessageFuncs=VigorAllErrorMessageFuncs,exports.VigorAllPolicyBase=VigorAllPolicyBase,exports.VigorAllPolicyMiddlewares=VigorAllPolicyMiddlewares,exports.VigorAllPolicyMiddlewaresBase=VigorAllPolicyMiddlewaresBase,exports.VigorAllPolicySettings=VigorAllPolicySettings,exports.VigorAllPolicySettingsBase=VigorAllPolicySettingsBase,exports.VigorBodySerializer=VigorBodySerializer,exports.VigorBodySteps=VigorBodySteps,exports.VigorCastPlaceholder=VigorCastPlaceholder,exports.VigorDefault=VigorDefault,exports.VigorEmpty=VigorEmpty,exports.VigorError=VigorError,exports.VigorFetch=VigorFetch,exports.VigorFetchBase=VigorFetchBase,exports.VigorFetchContextBase=VigorFetchContextBase,exports.VigorFetchError=VigorFetchError,exports.VigorFetchErrorMessageFuncs=VigorFetchErrorMessageFuncs,exports.VigorFetchPolicyBase=VigorFetchPolicyBase,exports.VigorFetchPolicyMiddlewares=VigorFetchPolicyMiddlewares,exports.VigorFetchPolicyMiddlewaresBase=VigorFetchPolicyMiddlewaresBase,exports.VigorFetchPolicySerializers=VigorFetchPolicySerializers,exports.VigorFetchPolicySettings=VigorFetchPolicySettings,exports.VigorFetchPolicySettingsBase=VigorFetchPolicySettingsBase,exports.VigorFetchSerializersBase=VigorFetchSerializersBase,exports.VigorHeadersSerializer=VigorHeadersSerializer,exports.VigorHeadersSteps=VigorHeadersSteps,exports.VigorJitter=VigorJitter,exports.VigorParse=VigorParse,exports.VigorParseBase=VigorParseBase,exports.VigorParseContentTypeStrategy=VigorParseContentTypeStrategy,exports.VigorParseContextBase=VigorParseContextBase,exports.VigorParseError=VigorParseError,exports.VigorParseErrorMessageFuncs=VigorParseErrorMessageFuncs,exports.VigorParsePolicyBase=VigorParsePolicyBase,exports.VigorParsePolicyMiddlewares=VigorParsePolicyMiddlewares,exports.VigorParsePolicyMiddlewaresBase=VigorParsePolicyMiddlewaresBase,exports.VigorParsePolicySettings=VigorParsePolicySettings,exports.VigorParsePolicySettingsBase=VigorParsePolicySettingsBase,exports.VigorParsePolicyStrategies=VigorParsePolicyStrategies,exports.VigorParsePolicyStrategiesBase=VigorParsePolicyStrategiesBase,exports.VigorParseSniffStrategy=VigorParseSniffStrategy,exports.VigorPathSerializer=VigorPathSerializer,exports.VigorPathSteps=VigorPathSteps,exports.VigorQuerySerializer=VigorQuerySerializer,exports.VigorQuerySteps=VigorQuerySteps,exports.VigorRetry=VigorRetry,exports.VigorRetryBase=VigorRetryBase,exports.VigorRetryContextBase=VigorRetryContextBase,exports.VigorRetryError=VigorRetryError,exports.VigorRetryErrorMessageFuncs=VigorRetryErrorMessageFuncs,exports.VigorRetryPolicyAlgorithms=VigorRetryPolicyAlgorithms,exports.VigorRetryPolicyAlgorithmsBackoff=VigorRetryPolicyAlgorithmsBackoff,exports.VigorRetryPolicyAlgorithmsBackoffBase=VigorRetryPolicyAlgorithmsBackoffBase,exports.VigorRetryPolicyAlgorithmsBase=VigorRetryPolicyAlgorithmsBase,exports.VigorRetryPolicyAlgorithmsConstant=VigorRetryPolicyAlgorithmsConstant,exports.VigorRetryPolicyAlgorithmsConstantBase=VigorRetryPolicyAlgorithmsConstantBase,exports.VigorRetryPolicyAlgorithmsCustom=VigorRetryPolicyAlgorithmsCustom,exports.VigorRetryPolicyAlgorithmsCustomBase=VigorRetryPolicyAlgorithmsCustomBase,exports.VigorRetryPolicyAlgorithmsLinear=VigorRetryPolicyAlgorithmsLinear,exports.VigorRetryPolicyAlgorithmsLinearBase=VigorRetryPolicyAlgorithmsLinearBase,exports.VigorRetryPolicyBase=VigorRetryPolicyBase,exports.VigorRetryPolicyMiddlewares=VigorRetryPolicyMiddlewares,exports.VigorRetryPolicyMiddlewaresBase=VigorRetryPolicyMiddlewaresBase,exports.VigorRetryPolicySettings=VigorRetryPolicySettings,exports.VigorRetryPolicySettingsBase=VigorRetryPolicySettingsBase,exports.VigorStatus=VigorStatus,exports.VigorUrlSerializer=VigorUrlSerializer,exports.VigorUrlSteps=VigorUrlSteps,exports.adoptVigorFetchError=adoptVigorFetchError,exports.createBrand=createBrand,exports.createVigorTimelineRecorder=createVigorTimelineRecorder,exports.default=index_default,exports.findInVigorErrorChain=findInVigorErrorChain,exports.isVigorAllError=isVigorAllError,exports.isVigorDefault=isVigorDefault,exports.isVigorEmpty=isVigorEmpty,exports.isVigorFetchError=isVigorFetchError,exports.isVigorInternalMiddleware=isVigorInternalMiddleware,exports.isVigorParseError=isVigorParseError,exports.isVigorRetryError=isVigorRetryError,exports.markVigorInternal=markVigorInternal,exports.readVigorParseBody=readVigorParseBody,exports.runVigorGuard=runVigorGuard,exports.vigor=vigor,exports.vigorStringifyValue=vigorStringifyValue;