trybox 0.10.0 → 0.11.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 +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +301 -295
- package/dist/index.d.ts +301 -295
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/metafile-cjs.json +1 -1
- package/dist/metafile-esm.json +1 -1
- package/package.json +47 -43
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';Object.defineProperty(
|
|
1
|
+
'use strict';var K=Object.defineProperty;var W=(e,r,o)=>r in e?K(e,r,{enumerable:true,configurable:true,writable:true,value:o}):e[r]=o;var i=(e,r,o)=>W(e,typeof r!="symbol"?r+"":r,o);var E=class extends Error{constructor(o,t){super(o);i(this,"cause");i(this,"meta");i(this,"status");i(this,"timestamp");this.timestamp=new Date,this.name=this.constructor.name,this.cause=t?.cause,this.meta=t?.meta,this.status=t?.status,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor);}is(o){return this.code===o}withMeta(o){return Object.assign(this,{meta:o})}withStatus(o){return Object.assign(this,{status:o})}withCause(o){return Object.assign(this,{cause:o})}toJSON(){return {name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),cause:this.cause,stack:this.stack}}},M=class extends E{constructor(o,t){super(`Operation timed out after ${o}ms`,{cause:t});i(this,"code","TIMEOUT");}};var h=class extends E{constructor(o,t){super(`Circuit breaker is open, reset after ${o}ms`,{cause:t});i(this,"code","CIRCUIT_OPEN");}},A=class extends E{constructor(o,t,n){super(o,{cause:n,meta:{validationErrors:t}});this.validationErrors=t;i(this,"code","VALIDATION");}};var S=class extends E{constructor(o,t){super(o,{cause:t});i(this,"code","UNKNOWN");}};var D=class{constructor(r){i(this,"state");i(this,"config");this.config=r,this.state={state:"closed",failureCount:0,halfOpenCount:0};}async canExecute(){return this.updateStateIfNeeded(),this.state.state!=="open"}async recordSuccess(){switch(this.state.state){case "closed":this.state={...this.state,failureCount:0};break;case "half-open":this.state={state:"closed",failureCount:0,halfOpenCount:0};break;}}async recordFailure(r){if(!(this.config.shouldCountAsFailure?.(r)??true))return;let t=new Date;switch(this.state.state){case "closed":{let n=this.state.failureCount+1;n>=this.config.failureThreshold?this.state={state:"open",failureCount:n,halfOpenCount:0,lastFailureTime:t,nextAttemptTime:new Date(t.getTime()+this.config.resetTimeout)}:this.state={...this.state,failureCount:n,lastFailureTime:t};break}case "half-open":this.state={state:"open",failureCount:this.state.failureCount+1,halfOpenCount:0,lastFailureTime:t,nextAttemptTime:new Date(t.getTime()+this.config.resetTimeout)};break;case "open":this.state={...this.state,lastFailureTime:t,nextAttemptTime:new Date(t.getTime()+this.config.resetTimeout)};break}}getState(){return this.updateStateIfNeeded(),{...this.state,canExecute:this.state.state!=="open"}}createOpenError(){let r=this.state.nextAttemptTime?this.state.nextAttemptTime.getTime()-Date.now():this.config.resetTimeout;return new h(r)}forceState(r){this.state={state:r,failureCount:0,halfOpenCount:0};}reset(){this.state={state:"closed",failureCount:0,halfOpenCount:0};}updateStateIfNeeded(){this.state.state==="open"&&this.state.nextAttemptTime&&new Date>=this.state.nextAttemptTime&&(this.state={...this.state,state:"half-open",halfOpenCount:0});}};var H=(e,r)=>o=>{for(let t of e){let n=t(o);if(n!==null)return n}return r(o)},U=e=>r=>r instanceof E?r:r instanceof Error?new e(r.message,r):typeof r=="string"?new e(r):new e("Unknown error occurred",r);var z=e=>{if(typeof e!="object"||e===null)return false;let r=e;return typeof r.status=="number"||typeof r.statusCode=="number"},P=class{constructor(r){this.predicate=r;}toCode(r){return new N(this.predicate,r)}toError(r){return o=>{if(!this.predicate(o))return null;let t=r(o),n=t.code;class s extends E{constructor(){super(t.message,{cause:t.cause??o,meta:t.meta,status:t.status});i(this,"code",n);}}return new s}}},N=class{constructor(r,o){this.predicate=r;this.errorCode=o;}with(r){return o=>{if(!this.predicate(o))return null;let t=r(o),n=this.errorCode;class s extends E{constructor(){super(t.message,{cause:t.cause,meta:t.meta,status:t.status});i(this,"code",n);}}return new s}}},p={when:e=>new P(e),instance:e=>new P(r=>r instanceof e),code:e=>({for:r=>new N(r,e)}),string:(e,r)=>({when:o=>p.when(o).toCode(r).with(t=>({message:t===e?e:`${r}: ${t}`,cause:t}))}),httpStatus:(e,r)=>({for:o=>p.when(o).toCode(r??`HTTP_${e}`).with(t=>({message:`HTTP ${e} error`,cause:t}))})};var y={abort:p.when(e=>e instanceof DOMException&&e.name==="AbortError").toCode("ABORTED").with(e=>({message:e.message||"Operation was aborted",cause:e})),timeout:p.when(e=>e instanceof Error&&e.name==="TimeoutError").toCode("TIMEOUT").with(e=>({message:e.message||"Operation timed out",cause:e})),network:p.when(e=>z(e)).toCode("NETWORK").with(e=>{let r=e.status??e.statusCode;return {message:e.message||`Network error with status ${r??"unknown"}`,cause:e}}),http:p.when(e=>{if(!z(e))return false;let r=e,o=r.status??r.statusCode;return typeof o=="number"&&o>=400}).toCode("HTTP").with(e=>{let r=e.status??e.statusCode;return {message:e.message||`HTTP ${r??"error"} error`,cause:e}}),unknown:p.when(e=>e instanceof Error).toCode("UNKNOWN").with(e=>({message:e.message||"Unknown error occurred",cause:e}))};var j=[y.abort,y.timeout,y.network,y.http,y.unknown];var L={when:e=>p.when(e),instance:e=>p.instance(e)},$=j;p.when(e=>e instanceof h).toCode("CIRCUIT_OPEN").with(e=>({message:e.message,cause:e}));p.when(e=>e instanceof A).toCode("VALIDATION").with(e=>({message:e.message,cause:e}));var _=(e,r,o)=>{switch(e.type){case "fixed":return e.delay;case "exponential":{let t=e.base*e.factor**(Number(r)-1);return e.maxDelay?Math.min(t,e.maxDelay):t}case "fibonacci":{let t=e.base*J(Number(r));return e.maxDelay?Math.min(t,e.maxDelay):t}case "custom":return e.calculate(r,o);default:return e}},J=e=>{if(e<=1)return 1;let r=1,o=1;for(let t=2;t<=e;t++){let n=r+o;r=o,o=n;}return o};var v=(e,r)=>new Promise((o,t)=>{if(r?.aborted){t(new DOMException("Aborted","AbortError"));return}let n=setTimeout(()=>{o();},e),s=()=>{clearTimeout(n),t(new DOMException("Aborted","AbortError"));};r?.addEventListener("abort",s,{once:true});});var q=e=>{if(e.toError)return e.toError;let r=e.rulesMode??"extend",o=e.rules??[],t=$,n=e.fallback??(u=>U(S)(u)),s=r==="replace"?o:[...o,...t];return H(s,n)},C=class e{constructor(r={}){i(this,"circuitBreaker");i(this,"config");let{rules:o,rulesMode:t,fallback:n,toError:s,mapError:u,...l}=r,x=q(r),m={...l,errorHandling:{normalizer:x,mapError:u}};this.config=m,m.circuitBreaker&&(this.circuitBreaker=new D(m.circuitBreaker));}async execute(r,o={}){let t={...this.config,...o};if(this.circuitBreaker&&!await this.circuitBreaker.canExecute())return {type:"failure",ok:false,data:null,error:this.circuitBreaker.createOpenError(),metrics:{totalAttempts:0,totalRetries:0,totalDuration:0,retryHistory:[]}};let n=await Y(r,t);return this.circuitBreaker&&(n.ok?await this.circuitBreaker.recordSuccess():await this.circuitBreaker.recordFailure(n.error)),n}async executeOrThrow(r,o={}){let t=await this.execute(r,o);if(t.ok)return t.data;throw t.error}async executeAll(r,o={}){let t={...this.config,...o},n=t.concurrency??Number.POSITIVE_INFINITY,s=new Array(r.length),u=0,l=async()=>{for(;;){let m=u;if(u++,m>=r.length)return;let f=r[m];if(!f)return;s[m]=await this.execute(f,t);}},x=Array.from({length:Math.min(n,r.length)},()=>l());return await Promise.all(x),s}async executeAllOrThrow(r,o={}){let t=await this.executeAll(r,o);for(let n of t)if(!n.ok)throw n.error;return t.map(n=>{if(!n.ok)throw n.error;return n.data})}getCircuitBreakerState(){return this.circuitBreaker?.getState()}resetCircuitBreaker(){this.circuitBreaker?.reset();}getConfig(){return {...this.config}}withConfig(r){let{errorHandling:o,...t}=this.config,{errorHandling:n,...s}=r;return new e({...t,...s})}withErrorType(r={}){return new e(r)}};async function Y(e,r){let{signal:o,ignoreAbort:t=true,timeout:n,retry:s,errorHandling:u,hooks:l,logger:x}=r,m,f=0,b=0,T=[],g=Date.now(),R=G(o);if(R.aborted){let a=u.normalizer(new DOMException("Aborted","AbortError")),c=u.mapError?u.mapError(a):a;return {type:"aborted",ok:false,data:null,error:c,metrics:{totalAttempts:f,totalRetries:b,totalDuration:Date.now()-g,lastError:c,retryHistory:T}}}let B=async a=>{f=a;try{let c=e({signal:R}),w=n?await Q(c,n,R):await c;return l?.onSuccess?.(w),x?.info?.(`Task succeeded on attempt ${a}`),w}catch(c){let w=u.normalizer(c),d=u.mapError?u.mapError(w):w;if(m=d,t&&d.code==="ABORTED"||(l?.onError?.(d),x?.error?.(`Task failed on attempt ${a}`,d)),a<=(s?.maxRetries??0)){let F=s?.shouldRetry,V={totalAttempts:f,elapsedTime:Date.now()-g,startTime:new Date(g),lastDelay:T[T.length-1]?.delay};if(!F||F(a,d,V)){let O=s?_(s.strategy,a,d):0;return T.push({attempt:a,error:d,delay:O,timestamp:new Date}),b=a-1,l?.onRetry?.(a,d,O),x?.info?.(`Retrying in ${O}ms (attempt ${a+1})`),await v(O,R),B(a+1)}}throw d}};try{let a=await B(1),c={totalAttempts:f,totalRetries:b,totalDuration:Date.now()-g,retryHistory:T};return l?.onFinally?.(c),{type:"success",ok:!0,data:a,error:null,metrics:c}}catch(a){let c=m??u.normalizer(a),w=c.code==="TIMEOUT"?"timeout":c.code==="ABORTED"?"aborted":"failure",d={totalAttempts:f,totalRetries:b,totalDuration:Date.now()-g,lastError:c,retryHistory:T};return l?.onFinally?.(d),{type:w,ok:false,data:null,error:c,metrics:d}}}function G(e){let r=new AbortController;if(!e)return r.signal;let o=()=>r.abort();return e.aborted?(o(),r.signal):(e.addEventListener("abort",o,{once:true}),r.signal)}async function Q(e,r,o){let t=v(r,o).then(()=>{throw new M(r)});return Promise.race([e,t])}var I,k=e=>e?new C(e):(I||(I=new C),I);async function X(e,r){return k().execute(e,r)}async function Z(e,r){return k().executeOrThrow(e,r)}async function ee(e,r){return k().executeAll(e,r)}async function re(e,r){return k().executeAllOrThrow(e,r)}exports.Executor=C;exports.errorRule=L;exports.execute=X;exports.executeAll=ee;exports.executeAllOrThrow=re;exports.executeOrThrow=Z;exports.getExecutor=k;//# sourceMappingURL=index.cjs.map
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/error/normalize.ts","../src/types.ts","../src/utils.ts","../src/runner/run.ts","../src/runner/runAll.ts","../src/runner/runAllOrThrow.ts","../src/error/core.ts","../src/error/builder.ts","../src/runner/runner.ts","../src/index.ts"],"names":["createNormalizer","rules","fallback","err","r","out","defaultFallback","toResultError","validateOptions","options","sleep","ms","resolve","clamp","n","min","max","resolveRetryDelay","retryDelay","attempt","defaultBaseDelay","backoffStrategy","maxDelay","base","backoff","computeBackoffDelay","applyJitter","delay","jitter","rng","ratio","strategy","v","b","a","prev","curr","i","next","run","fn","toError","mapError","onError","onSuccess","onFinally","ignoreAbort","retries","shouldRetry","timeout","signal","onRetry","logger","onAbort","mapped","startedAt","lastError","lastDelay","controller","timeoutId","abortPromise","_","reject","data","e","totalDuration","metrics","nextAttempt","context","decision","isSuccess","runAll","tasks","concurrency","mode","runOptions","limit","results","nextIndex","aborted","setResult","markSkipped","t","worker","task","runAllOrThrow","firstError","CircuitOpenError","circuitOpen","abort","httpStatus","obj","status","aggregate","string","message","getDefaultRules","ErrorRuleBuilder","matcher","mapper","errorRule","ctor","predicate","composeMapError","local","createRunner","opts","rulesMode","customToError","defaultMapError","defaultCircuitBreaker","effectiveRules","defaultRulesList","failureCount","openUntil","halfOpenRequired","cb","now","fns","trybox"],"mappings":"sEAEO,SAASA,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACA,CACA,OAAQC,CAAAA,EAAoB,CAC1B,IAAA,IAAWC,CAAAA,IAAKH,CAAAA,CAAO,CACrB,IAAMI,CAAAA,CAAMD,EAAED,CAAG,CAAA,CACjB,GAAIE,CAAAA,CAAK,OAAOA,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AAAA,CAAG,gBAAA,GACrBF,EAAY,IAAA,CAAK,GAAA,EAAI,CAAIE,CAAAA,CAAG,YAAA,CAC5BD,CAAAA,CAAmBC,CAAAA,CAAG,gBAAA,EAAoB,CAAA,CAAA,CAAA,CAAA,CAqBzChH,CAAAA,CACR,CACH,CAAA,CACA,GAAA,CACEkH,CAAAA,CACA7G,EAA+B,EAAC,CACG,CACnC,OAAO8D,CAAAA,CAAW+C,CAAAA,CAAK,CACrB,OAAA,CAAA7E,CAAAA,CACA,WAAA,CAAAK,CAAAA,CACA,GAAGrC,CAAAA,CACH,QAAA,CAAU8F,EAAgBM,CAAAA,CAAiBpG,CAAAA,CAAQ,QAAQ,CAC7D,CAAC,CACH,CAAA,CACA,UAAA,CACE6G,CAAAA,CACA7G,CAAAA,CAAsC,EAAC,CACzB,CACd,OAAO4E,EAAkBiC,CAAAA,CAAK,CAC5B,OAAA,CAAA7E,CAAAA,CACA,WAAA,CAAAK,CAAAA,CACA,GAAGrC,CAAAA,CACH,QAAA,CAAU8F,CAAAA,CAAgBM,CAAAA,CAAiBpG,CAAAA,CAAQ,QAAQ,CAC7D,CAAC,CACH,CACF,CACF,CC7Le,SAAR8G,EAAAA,CAAwB9G,CAAAA,CAAe,EAAC,CAAQ,CACrD,OAAOgG,EAAAA,CAAahG,CAAO,CAC7B","file":"index.cjs","sourcesContent":["import type { ResultError, Rule } from \"./types\";\n\nexport function createNormalizer<E extends ResultError>(\n rules: Rule<E>[],\n fallback: (err: unknown) => E\n) {\n return (err: unknown): E => {\n for (const r of rules) {\n const out = r(err);\n if (out) return out;\n }\n return fallback(err);\n };\n}\n\n// General fallback (without depending on fetch / http)\nexport function defaultFallback(err: unknown): ResultError {\n if (err instanceof Error) {\n // In browsers, network errors sometimes fall as TypeError (fetch),\n // but this is not 100% universal; we treat it as best-effort.\n const code = err.name === \"TypeError\" ? \"NETWORK\" : \"UNKNOWN\";\n return { code, message: err.message || \"Something went wrong\", cause: err };\n }\n return { code: \"UNKNOWN\", message: \"Something went wrong\", cause: err };\n}\n\n// \"default\" normalizer that includes abort rule (very useful in UI)\nexport function toResultError(err: unknown): ResultError {\n // AbortError (browser / fetch / AbortController)\n if (err instanceof DOMException && err.name === \"AbortError\") {\n return { code: \"ABORTED\", message: \"Request cancelled\", cause: err };\n }\n if (err instanceof DOMException && err.name === \"TimeoutError\") {\n return { code: \"TIMEOUT\", message: \"Request timed out\", cause: err };\n }\n return defaultFallback(err);\n}\n","import type { ResultError } from \"./error/types\";\n\nexport type RetryDelayFn<E> = (attempt: number, err: E) => number;\n\nexport type MaybePromise<T> = T | Promise<T>;\n\nexport type Jitter =\n | boolean\n | number // ratio 0..1\n | { ratio?: number; mode?: \"full\" | \"equal\"; rng?: () => number };\n\n/**\n * Backoff strategy to calculate the delay between retries.\n * - \"linear\": uses the base delay as is in each attempt.\n * - \"exponential\": multiplies the delay by 2^(attempt-1).\n * - \"fibonacci\": multiplies by F(attempt) (classic Fibonacci sequence).\n * - function: custom function based on the attempt number.\n */\nexport type BackoffStrategy =\n | \"linear\"\n | \"exponential\"\n | \"fibonacci\"\n | ((attempt: number) => number);\n\n/**\n * Retry options for `run`, `runAll` and `runAllOrThrow`.\n */\nexport type RetryOptions<E extends ResultError = ResultError> = {\n /**\n * Number of retries to perform (does not include the initial attempt).\n * @default 0\n */\n retries?: number;\n /**\n * Delay between attempts:\n * - number: fixed delay (ms)\n * - () => number: lazy delay (evaluated per attempt)\n * - (attempt, err) => number: delay based on attempt and last error\n * @default 0 or a default baseDelay if retries are present\n */\n retryDelay?: number | (() => number) | RetryDelayFn<E>;\n /**\n * Decides whether to retry given a specific error.\n * Can be synchronous or asynchronous.\n * Receives the next attempt number and a context with accumulated metrics.\n * @default () => true\n */\n shouldRetry?: (\n attempt: number,\n error: E,\n context: RetryContext\n ) => boolean | Promise<boolean>;\n /**\n * Random jitter to avoid thundering herd:\n * - true: default ratio 0.5\n * - false: no jitter\n * - number: ratio 0..1\n * - object: full control (ratio, mode, rng)\n * @default 0.5\n */\n jitter?: Jitter;\n /**\n * Backoff strategy to apply on the calculated delay.\n * @default \"linear\"\n */\n backoffStrategy?: BackoffStrategy;\n /**\n * Upper limit of the delay after backoff and before jitter.\n * @default undefined (no limit)\n */\n maxDelay?: number;\n};\n\n/**\n * Context for `shouldRetry` with accumulated metrics of the current attempt.\n */\nexport type RetryContext = {\n /** Total attempts (including the next retry). */\n totalAttempts: number;\n /** Elapsed time in ms since the start of `run`. */\n elapsedTime: number;\n /** Timestamp (ms) when the execution started. */\n startTime: number;\n /** The delay (ms) applied before the last attempt, if any. */\n lastDelay?: number;\n};\n\n/**\n * Main options for `run` and extended to `runAll`/`runAllOrThrow`.\n */\nexport type RunOptions<\n T,\n E extends ResultError = ResultError\n> = RetryOptions<E> & {\n /**\n * Normalizes an unknown error value to your type `E`.\n * If not provided, a default normalizer is used.\n */\n toError?: (err: unknown) => E;\n /**\n * Optional transformation applied after `toError`.\n * Useful for adjusting messages, codes, or adding metadata.\n */\n mapError?: (error: E) => E;\n /**\n * Callback on failure (not called if `ignoreAbort` and error is ABORTED).\n */\n onError?: (error: E) => void;\n /**\n * Callback on success.\n */\n onSuccess?: (data: T) => void;\n /**\n * Callback that always executes at the end (success or error).\n */\n onFinally?: () => void;\n /**\n * If true, aborts (ABORTED) are not considered fatal errors:\n * `onError` is not called and `{ ok: false, error }` is returned.\n * @default true\n */\n ignoreAbort?: boolean;\n /**\n * Signal for native work cancellation.\n * If aborted, it cuts with `AbortError`.\n */\n signal?: AbortSignal;\n /**\n * Maximum timeout in ms for the work; expires with `TimeoutError`.\n */\n timeout?: number;\n /**\n * Retry observability: receives attempt, error, and next delay.\n */\n onRetry?: (attempt: number, error: E, nextDelay: number) => void;\n /**\n * Optional structured logger for debug and errors.\n */\n logger?: {\n debug?: (msg: string, meta?: unknown) => void;\n error?: (msg: string, error: E) => void;\n };\n /**\n * Callback on abort, useful for reacting to `AbortSignal`.\n */\n onAbort?: (signal: AbortSignal) => void;\n};\n\n/**\n * Circuit breaker configuration options:\n * - failureThreshold: number of consecutive failures to open the circuit\n * - resetTimeout: time in ms it remains open before attempting half-open\n * - halfOpenRequests: allowed quantity in half-open state\n */\nexport type CircuitBreakerOptions = {\n failureThreshold: number;\n resetTimeout: number;\n halfOpenRequests?: number;\n};\n\n/**\n * Execution metrics optionally returned in `RunResult`.\n */\nexport type Metrics<E extends ResultError = ResultError> = {\n totalAttempts: number;\n totalRetries: number;\n totalDuration: number;\n lastError?: E;\n};\n\nexport type RunResult<T, E extends ResultError = ResultError> =\n | { ok: true; data: T; error: null; metrics?: Metrics<E> }\n | { ok: false; data: null; error: E; metrics?: Metrics<E> };\n\n/**\n * Validates common execution/retry options.\n */\nexport function validateOptions<T, E extends ResultError = ResultError>(\n options: RunOptions<T, E>\n): void {\n if (options.retries != null && options.retries < 0) {\n throw new Error(\"retries must be >= 0\");\n }\n if (options.timeout != null && options.timeout <= 0) {\n throw new Error(\"timeout must be > 0\");\n }\n if (options.maxDelay != null && options.maxDelay < 0) {\n throw new Error(\"maxDelay must be >= 0\");\n }\n // const cb = options.circuitBreaker;\n // if (cb) {\n // if (cb.failureThreshold < 1) {\n // throw new Error(\"failureThreshold must be >= 1\");\n // }\n // if (cb.resetTimeout <= 0) {\n // throw new Error(\"resetTimeout must be > 0\");\n // }\n // if (cb.halfOpenRequests != null && cb.halfOpenRequests < 1) {\n // throw new Error(\"halfOpenRequests must be >= 1\");\n // }\n // }\n}\n","import type { Jitter, RetryDelayFn, BackoffStrategy } from \"./types\";\n\nexport const sleep = (ms: number) =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\nexport function clamp(n: number, min: number, max: number) {\n return Math.max(min, Math.min(max, n));\n}\n\nexport function resolveRetryDelay<E>(\n retryDelay: number | RetryDelayFn<E> | undefined,\n attempt: number,\n err: E,\n defaultBaseDelay: number,\n backoffStrategy?: BackoffStrategy,\n maxDelay?: number\n): number {\n let base =\n typeof retryDelay === \"function\"\n ? (retryDelay as RetryDelayFn<E>)(attempt, err)\n : typeof retryDelay === \"number\"\n ? (retryDelay as number)\n : typeof retryDelay === \"undefined\"\n ? defaultBaseDelay\n : defaultBaseDelay;\n\n const backoff = computeBackoffDelay(\n backoffStrategy ?? \"linear\",\n base,\n attempt\n );\n\n const out = maxDelay != null ? clamp(backoff, 0, maxDelay) : backoff;\n return Number.isFinite(out) ? out : 0;\n}\n\nexport function applyJitter(delay: number, jitter: Jitter | undefined): number {\n if (delay <= 0 || !jitter) return delay;\n\n const rng =\n typeof jitter === \"object\" && jitter.rng ? jitter.rng : Math.random;\n\n // reasonable defaults\n const ratio =\n typeof jitter === \"number\"\n ? jitter\n : jitter === true\n ? 0.5\n : typeof jitter === \"object\" && jitter.ratio != null\n ? jitter.ratio\n : 0.5;\n\n const r = clamp(ratio, 0, 1);\n\n const mode = typeof jitter === \"object\" && jitter.mode ? jitter.mode : \"full\";\n\n // \"full\": 0..delay*r extra (recommended to avoid thundering herd)\n // \"equal\": delay*(1-r) + random(0..delay*r)\n if (mode === \"equal\") {\n return delay * (1 - r) + rng() * delay * r;\n }\n\n // full jitter: add random extra up to delay*r\n return delay + rng() * delay * r;\n}\n\nexport function computeBackoffDelay(\n strategy: BackoffStrategy,\n base: number,\n attempt: number\n): number {\n if (typeof strategy === \"function\") {\n const v = strategy(attempt);\n return v >= 0 ? v : 0;\n }\n const b = base >= 0 ? base : 0;\n const a = attempt >= 1 ? attempt : 1;\n if (strategy === \"linear\") return b;\n if (strategy === \"exponential\") return b * Math.pow(2, a - 1);\n if (strategy === \"fibonacci\") {\n if (a <= 2) return b;\n let prev = 1;\n let curr = 1;\n for (let i = 3; i <= a; i++) {\n const next = prev + curr;\n prev = curr;\n curr = next;\n }\n return b * curr;\n }\n return b;\n}\n","import type { ResultError } from \"../error/types\";\nimport { toResultError as defaultToResultError } from \"../error/normalize\";\nimport type { MaybePromise, RunOptions, RunResult } from \"../types\";\nimport { validateOptions } from \"../types\";\nimport { applyJitter, resolveRetryDelay, sleep } from \"../utils\";\n\n/**\n * Executes an async operation and returns a Result instead of throwing.\n *\n * Errors are normalized into an `ResultError` (or a custom error type `E`)\n * using the provided `toError` function.\n *\n * This utility is framework-agnostic and works in browsers, Node.js,\n * React effects, and any async context.\n */\nexport async function run<T, E extends ResultError = ResultError>(\n fn: (ctx?: { signal: AbortSignal }) => MaybePromise<T>,\n options: RunOptions<T, E> = {}\n): Promise<RunResult<T, E>> {\n const {\n toError = defaultToResultError as unknown as (err: unknown) => E,\n mapError,\n onError,\n onSuccess,\n onFinally,\n ignoreAbort = true,\n retries = 0,\n retryDelay,\n shouldRetry = () => true,\n jitter = { ratio: 0.5, mode: \"full\" },\n backoffStrategy,\n maxDelay,\n timeout,\n signal,\n onRetry,\n logger,\n onAbort,\n } = options;\n\n const defaultBaseDelay = retries > 0 ? 300 : 0;\n\n validateOptions(options);\n\n if (signal?.aborted) {\n try {\n onAbort?.(signal);\n } finally {\n const err = toError(new DOMException(\"Aborted\", \"AbortError\"));\n const mapped = mapError ? mapError(err) : err;\n if (!ignoreAbort) {\n onError?.(mapped);\n }\n onFinally?.();\n return {\n ok: false,\n data: null,\n error: mapped,\n metrics: {\n totalAttempts: 0,\n totalRetries: 0,\n totalDuration: 0,\n lastError: mapped,\n },\n };\n }\n }\n\n const startedAt = Date.now();\n let attempt = 0;\n let lastError: E | undefined;\n let lastDelay = 0;\n\n while (true) {\n const controller = new AbortController();\n if (signal) {\n if (signal.aborted) {\n controller.abort(signal.reason);\n } else {\n signal.addEventListener(\n \"abort\",\n () => controller.abort(signal.reason),\n {\n once: true,\n }\n );\n }\n }\n\n let timeoutId: any = null;\n if (timeout && timeout > 0) {\n timeoutId = setTimeout(() => {\n controller.abort(new DOMException(\"Timeout\", \"TimeoutError\"));\n }, timeout);\n }\n\n try {\n const abortPromise = new Promise<never>((_, reject) => {\n if (controller.signal.aborted) {\n reject(controller.signal.reason);\n } else {\n controller.signal.addEventListener(\n \"abort\",\n () => reject(controller.signal.reason),\n { once: true }\n );\n }\n });\n\n const data = await Promise.race([\n fn({ signal: controller.signal }),\n abortPromise,\n ]);\n\n if (timeoutId) clearTimeout(timeoutId);\n try {\n onSuccess?.(data);\n } catch (e) {\n logger?.error?.(\"run:onSuccess failed\", toError(e));\n }\n try {\n onFinally?.();\n } catch (e) {\n logger?.error?.(\"run:onFinally failed\", toError(e));\n }\n const totalDuration = Date.now() - startedAt;\n const metrics = {\n totalAttempts: attempt + 1,\n totalRetries: attempt,\n totalDuration,\n lastError,\n };\n logger?.debug?.(\"run:success\", {\n attempts: metrics.totalAttempts,\n duration: metrics.totalDuration,\n });\n return { ok: true, data, error: null, metrics };\n } catch (e) {\n let err = toError(e);\n if (mapError) err = mapError(err);\n\n const isAborted =\n (err as any)?.code === \"ABORTED\" ||\n (e instanceof DOMException && e.name === \"AbortError\") ||\n signal?.aborted;\n\n if (isAborted) {\n try {\n if (signal) {\n try {\n onAbort?.(signal);\n } catch (e) {\n logger?.error?.(\"run:onAbort failed\", toError(e));\n }\n }\n } finally {\n if (!ignoreAbort) {\n try {\n onError?.(err);\n } catch (e) {\n logger?.error?.(\"run:onError failed\", toError(e));\n }\n }\n try {\n onFinally?.();\n } catch (e) {\n logger?.error?.(\"run:onFinally failed\", toError(e));\n }\n const totalDuration = Date.now() - startedAt;\n const metrics = {\n totalAttempts: attempt + 1,\n totalRetries: attempt,\n totalDuration,\n lastError: err,\n };\n logger?.debug?.(\"run:aborted\", {\n attempt,\n duration: metrics.totalDuration,\n });\n return { ok: false, data: null, error: err, metrics };\n }\n }\n\n lastError = err;\n const nextAttempt = attempt + 1;\n const context = {\n totalAttempts: nextAttempt,\n elapsedTime: Date.now() - startedAt,\n startTime: startedAt,\n lastDelay: lastDelay > 0 ? lastDelay : undefined,\n };\n const decision = await Promise.resolve(\n shouldRetry(nextAttempt, err, context)\n );\n const canRetry = attempt < retries && decision;\n\n if (canRetry) {\n attempt = nextAttempt;\n\n let delay = resolveRetryDelay(\n retryDelay,\n attempt,\n err,\n defaultBaseDelay,\n backoffStrategy,\n maxDelay\n );\n\n if (!Number.isFinite(delay) || delay < 0) delay = 0;\n\n delay = applyJitter(delay, jitter);\n lastDelay = delay;\n\n onRetry?.(attempt, err, delay);\n logger?.debug?.(\"run:retry\", { attempt, delay });\n if (delay > 0) await sleep(delay);\n continue;\n }\n\n // Final failure or aborted\n try {\n onError?.(err);\n } catch (e) {\n logger?.error?.(\"run:onError failed\", toError(e));\n }\n try {\n onFinally?.();\n } catch (e) {\n logger?.error?.(\"run:onFinally failed\", toError(e));\n }\n const totalDuration = Date.now() - startedAt;\n const metrics = {\n totalAttempts: attempt + 1,\n totalRetries: attempt,\n totalDuration,\n lastError: err,\n };\n logger?.error?.(\"run:error\", err);\n return { ok: false, data: null, error: err, metrics };\n }\n }\n}\n","import { run } from \"./run\";\nimport type { ResultError } from \"../error/types\";\nimport type { MaybePromise, RunOptions, RunResult } from \"../types\";\nimport { validateOptions } from \"../types\";\n\n/**\n * Discriminated result per item in `runAll`:\n * - \"ok\": successful task with `data`\n * - \"error\": failed task with `error`\n * - \"skipped\": task not executed due to cancellation/fail-fast/concurrency\n */\nexport type RunAllItemResult<T, E extends ResultError = ResultError> =\n | { status: \"ok\"; ok: true; data: T; error: null }\n | { status: \"error\"; ok: false; data: null; error: E }\n | { status: \"skipped\"; ok: false; data: null; error: null };\n\n/** Helper to discriminate successful results. */\nexport type SuccessResult<T> = Extract<\n RunAllItemResult<T, any>,\n { status: \"ok\" }\n>;\n/** Helper to discriminate error results. */\nexport type ErrorResult<E> = Extract<\n RunAllItemResult<any, E extends ResultError ? E : ResultError>,\n { status: \"error\" }\n>;\n\n/** Type guard that detects `status: \"ok\"` with `data` typing. */\nexport const isSuccess = <T, E extends ResultError = ResultError>(\n r: RunAllItemResult<T, E>\n): r is SuccessResult<T> => r.status === \"ok\";\n\nexport type RunAllOptions<T, E extends ResultError = ResultError> = RunOptions<\n T,\n E\n> & {\n /**\n * Maximum number of concurrent tasks to run.\n * @default Infinity\n */\n concurrency?: number;\n\n /**\n * Execution mode regarding errors.\n * - \"settle\": Run all tasks (default).\n * - \"fail-fast\": Stop starting new tasks if one fails.\n * @default \"settle\"\n */\n mode?: \"settle\" | \"fail-fast\";\n};\n\nexport async function runAll<T, E extends ResultError = ResultError>(\n tasks: Array<() => MaybePromise<T>>,\n options: RunAllOptions<T, E> = {}\n): Promise<RunAllItemResult<T, E>[]> {\n const { concurrency = Infinity, mode = \"settle\", ...runOptions } = options;\n validateOptions(runOptions);\n\n if (tasks.length === 0) return [];\n\n const limit = Number.isFinite(concurrency)\n ? Math.max(1, Math.floor(concurrency))\n : Infinity;\n\n const results: RunAllItemResult<T, E>[] = new Array(tasks.length);\n\n let nextIndex = 0;\n let aborted = false;\n\n const setResult = (i: number, r: RunResult<T, E>) => {\n results[i] = r.ok\n ? { status: \"ok\", ok: true, data: r.data, error: null }\n : { status: \"error\", ok: false, data: null, error: r.error };\n };\n\n const markSkipped = () => {\n for (let i = 0; i < tasks.length; i++) {\n if (results[i]) continue;\n results[i] = {\n status: \"skipped\",\n ok: false,\n data: null,\n error: null,\n };\n }\n };\n\n // Run all in parallel if unlimited or limit >= count\n if (limit >= tasks.length) {\n const rs = await Promise.all(tasks.map((t) => run<T, E>(t, runOptions)));\n rs.forEach((r, i) => {\n setResult(i, r);\n });\n return results;\n }\n\n const worker = async () => {\n while (true) {\n if (aborted) return;\n\n const i = nextIndex++;\n if (i >= tasks.length) return;\n\n const task = tasks[i];\n if (!task) continue; // skip if task is undefined\n\n const r = await run<T, E>(task, runOptions);\n setResult(i, r);\n\n if (!r.ok) {\n if (mode === \"fail-fast\") {\n aborted = true;\n return;\n }\n }\n }\n };\n\n await Promise.all(\n Array.from({ length: Math.min(limit, tasks.length) }, () => worker())\n );\n\n markSkipped();\n return results;\n}\n","import { run } from \"./run\";\nimport type { ResultError } from \"../error/types\";\nimport type { RunOptions } from \"../types\";\nimport { validateOptions } from \"../types\";\nimport type { MaybePromise } from \"../types\";\n\n/**\n * Options for `runAllOrThrow`:\n * - Inherits all options from `RunOptions`\n * - `concurrency`: limit of simultaneous tasks; if one fails, it throws\n */\nexport type RunAllOrThrowOptions<\n T,\n E extends ResultError = ResultError\n> = RunOptions<T, E> & {\n /**\n * Maximum number of concurrent tasks to run.\n * @default Infinity\n */\n concurrency?: number;\n};\n\nexport async function runAllOrThrow<T, E extends ResultError = ResultError>(\n tasks: Array<() => MaybePromise<T>>,\n options: RunAllOrThrowOptions<T, E> = {}\n): Promise<T[]> {\n const { concurrency = Infinity, ...runOptions } = options;\n validateOptions(runOptions);\n\n if (tasks.length === 0) return [];\n\n const limit = Number.isFinite(concurrency)\n ? Math.max(1, Math.floor(concurrency))\n : Infinity;\n\n const data: T[] = new Array(tasks.length);\n\n // Run all in parallel if unlimited or limit >= count\n if (limit >= tasks.length) {\n await Promise.all(\n tasks.map(async (t, i) => {\n const r = await run<T, E>(t, runOptions);\n if (!r.ok) throw r.error;\n data[i] = r.data;\n })\n );\n return data;\n }\n\n let nextIndex = 0;\n let aborted = false;\n let firstError: E | null = null;\n\n const worker = async () => {\n while (true) {\n if (aborted) return;\n\n const i = nextIndex++;\n if (i >= tasks.length) return;\n\n const task = tasks[i];\n if (!task) continue; // skip if task is undefined\n\n const r = await run<T, E>(task, runOptions);\n\n if (!r.ok) {\n firstError ??= r.error;\n aborted = true;\n return;\n }\n\n data[i] = r.data;\n }\n };\n\n await Promise.all(\n Array.from({ length: Math.min(limit, tasks.length) }, () => worker())\n );\n\n if (firstError) throw firstError;\n\n // Safety fill\n return data;\n}\n","import type { ResultError, Rule } from \"./types\";\n\nexport class CircuitOpenError extends Error {\n constructor() {\n super(\"Circuit open\");\n this.name = \"CircuitOpenError\";\n }\n}\n\nexport const circuitOpen: Rule<ResultError<\"CIRCUIT_OPEN\">> = (err) => {\n // console.log(\"Checking CircuitOpenError\", err, err instanceof CircuitOpenError);\n if (\n err instanceof CircuitOpenError ||\n (err instanceof Error && err.name === \"CircuitOpenError\")\n ) {\n return {\n code: \"CIRCUIT_OPEN\",\n message: \"Circuit open\",\n cause: err,\n };\n }\n return null;\n};\n\nexport const abort: Rule<ResultError<\"ABORTED\">> = (err) => {\n if (err instanceof DOMException && err.name === \"AbortError\") {\n return { code: \"ABORTED\", message: \"Request cancelled\", cause: err };\n }\n if (err instanceof Error && err.name === \"AbortError\") {\n return {\n code: \"ABORTED\",\n message: err.message || \"Request cancelled\",\n cause: err,\n };\n }\n return null;\n};\n\nexport const timeout: Rule<ResultError<\"TIMEOUT\">> = (err) => {\n if (err instanceof DOMException && err.name === \"TimeoutError\") {\n return { code: \"TIMEOUT\", message: \"Request timed out\", cause: err };\n }\n if (err instanceof Error && err.name === \"TimeoutError\") {\n return {\n code: \"TIMEOUT\",\n message: err.message || \"Request timed out\",\n cause: err,\n };\n }\n return null;\n};\n\nexport const httpStatus: Rule<ResultError<\"HTTP\">> = (err) => {\n if (typeof err === \"object\" && err !== null) {\n const obj = err as Record<string, unknown>;\n const status = obj.status ?? obj.statusCode;\n if (typeof status === \"number\") {\n return {\n code: \"HTTP\",\n message:\n typeof obj.message === \"string\"\n ? obj.message\n : `HTTP Error ${status}`,\n status,\n cause: err,\n };\n }\n }\n return null;\n};\n\nexport const aggregate: Rule<ResultError<\"UNKNOWN\", { errors: unknown[] }>> = (\n err\n) => {\n if (typeof AggregateError !== \"undefined\" && err instanceof AggregateError) {\n return {\n code: \"UNKNOWN\",\n message: err.message || \"Multiple errors occurred\",\n cause: err,\n meta: { errors: err.errors as unknown[] },\n };\n }\n return null;\n};\n\nexport const string: Rule<ResultError<\"UNKNOWN\">> = (err) => {\n if (typeof err === \"string\") {\n return { code: \"UNKNOWN\", message: err, cause: err };\n }\n return null;\n};\n\nexport const message: Rule<ResultError<\"UNKNOWN\">> = (err) => {\n if (\n typeof err === \"object\" &&\n err !== null &&\n \"message\" in err &&\n typeof (err as { message: unknown }).message === \"string\"\n ) {\n return {\n code: \"UNKNOWN\",\n message: (err as { message: string }).message,\n cause: err,\n };\n }\n return null;\n};\n\nexport const rules = {\n circuitOpen,\n abort,\n timeout,\n httpStatus,\n aggregate,\n string,\n message,\n} satisfies Record<string, Rule<ResultError>>;\n\nexport function getDefaultRules() {\n return [\n circuitOpen,\n abort,\n timeout,\n httpStatus,\n aggregate,\n string,\n message,\n ] as const;\n}\n\nexport const defaultRules = getDefaultRules();\n","import type { ResultError, Rule } from \"./types\";\n\nclass ErrorRuleBuilder<E> {\n constructor(private readonly matcher: (err: unknown) => err is E) {}\n\n toError<const Out extends ResultError>(mapper: (err: E) => Out): Rule<Out> {\n return (err: unknown) => {\n if (!this.matcher(err)) return null;\n return mapper(err);\n };\n }\n}\n\nexport const errorRule = {\n instance<E extends new (...args: any[]) => unknown>(ctor: E) {\n return new ErrorRuleBuilder<InstanceType<E>>(\n (err): err is InstanceType<E> => err instanceof ctor\n );\n },\n\n when<E = unknown>(predicate: (err: unknown) => err is E) {\n return new ErrorRuleBuilder<E>(predicate);\n },\n};\n","import type { ResultError, Rule, InferErrorFromRules } from \"../error/types\";\nimport { getDefaultRules, CircuitOpenError } from \"../error/core\";\nimport {\n createNormalizer,\n defaultFallback,\n toResultError,\n} from \"../error/normalize\";\nimport { run as baseRun } from \"./run\";\nimport type { MaybePromise, RunOptions, RunResult } from \"../types\";\nimport type { CircuitBreakerOptions } from \"../types\";\nimport {\n runAllOrThrow as baseRunAllOrThrow,\n type RunAllOrThrowOptions,\n} from \"./runAllOrThrow\";\nimport {\n runAll as baseRunAll,\n type RunAllItemResult,\n type RunAllOptions,\n} from \"./runAll\";\n\nexport type RulesMode = \"extend\" | \"replace\";\n\nexport type CreateRunnerOptions<E extends ResultError = ResultError> = {\n /**\n * Custom matchers to use for normalizing errors.\n * If not provided, the default matchers are used.\n */\n rules?: Rule<E>[];\n\n /**\n * How to treat provided rules in relation to default rules.\n * - \"extend\": Use default rules after custom rules (default).\n * - \"replace\": Use only custom rules (and fallback).\n */\n rulesMode?: RulesMode;\n\n /**\n * Custom fallback function to use for normalizing errors.\n * If not provided, the default fallback is used.\n */\n fallback?: (err: unknown) => E;\n\n /**\n * If you want a completely custom normalizer, you can provide it directly.\n * If set, `matchers` and `fallback` are ignored.\n */\n toError?: (err: unknown) => E;\n\n /** Default for run options */\n ignoreAbort?: boolean;\n\n /** Optional default mapper for all runs */\n mapError?: (error: E) => E;\n /**\n * Circuit breaker configuration (applies to all executions of the Runner).\n */\n circuitBreaker?: CircuitBreakerOptions;\n};\n\nconst composeMapError =\n <E>(base?: (e: E) => E, local?: (e: E) => E) =>\n (e: E) =>\n local ? local(base ? base(e) : e) : base ? base(e) : e;\n\nexport interface Runner<E extends ResultError> {\n run<T>(\n fn: () => Promise<T>,\n options?: RunOptions<T, E>\n ): Promise<RunResult<T, E>>;\n all<T>(\n fns: Array<() => MaybePromise<T>>,\n options?: RunAllOptions<T, E>\n ): Promise<RunAllItemResult<T, E>[]>;\n allOrThrow<T>(\n fns: Array<() => MaybePromise<T>>,\n options?: RunAllOrThrowOptions<T, E>\n ): Promise<T[]>;\n}\n\nexport function createRunner(\n opts?: Omit<CreateRunnerOptions<ResultError>, \"rules\">\n): Runner<ResultError>;\n\nexport function createRunner<const TRules extends readonly Rule<any>[]>(\n opts: { rules: TRules } & Omit<\n CreateRunnerOptions<InferErrorFromRules<TRules>>,\n \"rules\"\n >\n): Runner<InferErrorFromRules<TRules>>;\n\nexport function createRunner<const TRules extends readonly Rule<any>[] = []>(\n opts: any = {}\n): any {\n type E = InferErrorFromRules<TRules>;\n\n const {\n rules = [],\n rulesMode = \"extend\",\n fallback = (e: unknown) => defaultFallback(e) as unknown as E,\n toError: customToError,\n ignoreAbort = true,\n mapError: defaultMapError,\n circuitBreaker: defaultCircuitBreaker,\n } = opts as CreateRunnerOptions<E>;\n\n let effectiveRules: Rule<E>[] = [];\n const defaultRulesList = (getDefaultRules() || []) as unknown as Rule<E>[];\n\n if (rules.length > 0) {\n if (rulesMode === \"extend\") {\n effectiveRules = [...rules, ...defaultRulesList];\n } else {\n effectiveRules = [...rules];\n }\n } else {\n // If no custom rules, and extend -> use default rules\n if (rulesMode === \"extend\") {\n effectiveRules = defaultRulesList;\n } else {\n effectiveRules = [];\n }\n }\n\n const toError =\n customToError ??\n (effectiveRules.length > 0\n ? createNormalizer<E>(effectiveRules, fallback)\n : (toResultError as unknown as (e: unknown) => E));\n\n let failureCount = 0;\n let openUntil: number | null = null;\n let halfOpenRequired: number | null = null;\n\n return {\n run<T>(\n fn: () => Promise<T>,\n options: RunOptions<T, E> = {}\n ): Promise<RunResult<T, E>> {\n const cb = defaultCircuitBreaker;\n const now = Date.now();\n\n if (cb) {\n if (openUntil && now < openUntil) {\n const err = toError(new CircuitOpenError());\n const mapped = composeMapError(\n defaultMapError,\n options.mapError\n )(err);\n options.onError?.(mapped);\n options.onFinally?.();\n return Promise.resolve({\n ok: false,\n data: null,\n error: mapped,\n metrics: {\n totalAttempts: 0,\n totalRetries: 0,\n totalDuration: 0,\n lastError: mapped,\n },\n });\n }\n }\n\n return baseRun(fn, {\n toError,\n ignoreAbort,\n ...options,\n mapError: composeMapError(defaultMapError, options.mapError),\n }).then((r) => {\n if (!cb) return r;\n\n if (!r.ok) {\n // Failure\n if (openUntil && Date.now() >= openUntil) {\n // Half-open failure -> Open immediately\n openUntil = Date.now() + cb.resetTimeout;\n halfOpenRequired = cb.halfOpenRequests ?? 1;\n failureCount = 0;\n } else if (!openUntil) {\n // Closed failure -> Count threshold\n failureCount++;\n if (failureCount >= cb.failureThreshold) {\n openUntil = Date.now() + cb.resetTimeout;\n halfOpenRequired = cb.halfOpenRequests ?? 1;\n }\n }\n } else {\n // Success\n if (openUntil && Date.now() >= openUntil) {\n // Half-open success\n if (halfOpenRequired && halfOpenRequired > 0) {\n halfOpenRequired--;\n }\n if (!halfOpenRequired || halfOpenRequired <= 0) {\n // Closed\n openUntil = null;\n failureCount = 0;\n halfOpenRequired = null;\n }\n } else {\n // Closed success -> Reset failure count\n failureCount = 0;\n }\n }\n return r;\n });\n },\n all<T>(\n fns: Array<() => MaybePromise<T>>,\n options: RunAllOptions<T, E> = {}\n ): Promise<RunAllItemResult<T, E>[]> {\n return baseRunAll(fns, {\n toError,\n ignoreAbort,\n ...options,\n mapError: composeMapError(defaultMapError, options.mapError),\n });\n },\n allOrThrow<T>(\n fns: Array<() => MaybePromise<T>>,\n options: RunAllOrThrowOptions<T, E> = {}\n ): Promise<T[]> {\n return baseRunAllOrThrow(fns, {\n toError,\n ignoreAbort,\n ...options,\n mapError: composeMapError(defaultMapError, options.mapError),\n });\n },\n };\n}\n","export { run } from \"./runner/run\";\nexport { runAll, type RunAllItemResult } from \"./runner/runAll\";\nexport type {\n RunAllOptions,\n SuccessResult,\n ErrorResult,\n} from \"./runner/runAll\";\nexport { isSuccess } from \"./runner/runAll\";\nexport { runAllOrThrow } from \"./runner/runAllOrThrow\";\nexport type { RunOptions, RunResult, RetryOptions } from \"./types\";\nexport type {\n BackoffStrategy,\n CircuitBreakerOptions,\n Metrics,\n RetryContext,\n} from \"./types\";\n\nexport type { ResultError, ResultErrorCode } from \"./error/types\";\nexport {\n toResultError,\n defaultFallback,\n createNormalizer,\n} from \"./error/normalize\";\nexport { rules } from \"./error/core\";\n\nexport { errorRule } from \"./error/builder\";\n\nimport type { ResultError, Rule, InferErrorFromRules } from \"./error/types\";\nimport { createRunner } from \"./runner/runner\";\nimport type { CreateRunnerOptions, Runner } from \"./runner/runner\";\n\nexport default function trybox(\n options?: Omit<CreateRunnerOptions<ResultError>, \"rules\">\n): Runner<ResultError>;\n\nexport default function trybox<const TRules extends readonly Rule<any>[]>(\n options: { rules: TRules } & Omit<\n CreateRunnerOptions<InferErrorFromRules<TRules>>,\n \"rules\"\n >\n): Runner<InferErrorFromRules<TRules>>;\n\nexport default function trybox(options: any = {}): any {\n return createRunner(options);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/error/typed-error.ts","../src/circuit-breaker/breaker.ts","../src/error/error-normalizer.ts","../src/error/error-builder.ts","../src/error/error-rules.ts","../src/retry/retry-strategies.ts","../src/utils/timing.ts","../src/core/executor.ts","../src/core/execution.ts"],"names":["TypedError","message","opts","__publicField","code","meta","status","cause","TimeoutError","timeout","CircuitOpenError","resetAfter","ValidationError","validationErrors","UnknownError","CircuitBreaker","config","error","now","newFailureCount","state","createErrorNormalizer","rules","fallback","rule","result","createFallbackNormalizer","ErrorClass","hasNumericStatus","err","candidate","ErrorRuleBuilder","predicate","ErrorMapper","mapper","out","CustomError","errorCode","mapped","CustomTypedError","createErrorRule","BuiltinRules","builtInRules","errorRule","defaultRules","calculateDelay","strategy","attempt","expDelay","fibDelay","fibonacci","n","prev","curr","i","next","sleep","ms","signal","resolve","reject","timeoutId","onAbort","buildNormalizer","rulesMode","userRules","builtins","Executor","_Executor","options","_rules","_rulesMode","_fallback","_toError","mapError","executionConfig","normalizer","baseConfig","task","mergedConfig","executeInternal","r","tasks","concurrency","idx","worker","current","workers","results","additionalConfig","_currentHandling","_newHandling","extraConfig","outerSignal","ignoreAbort","retry","errorHandling","hooks","logger","lastError","totalAttempts","totalRetries","retryHistory","startTime","compositeSignal","createCompositeSignal","e","runAttempt","p","data","withTimeout","norm","shouldRetry","ctx","delay","metrics","finalError","kind","controller","abort","promise","timeoutPromise","singleton","getExecutor","execute","executeOrThrow","executeAll","executeAllOrThrow"],"mappings":"aAQO,IAAA,CAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,UAAA,CAAA,IAAA,CAAA,YAAA,CAAA,IAAA,CAAA,QAAA,CAAA,IAAA,CAAA,KAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,OAAA,CAAA,EAAA,QAAA,CAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAA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AAAA,CACC,CACD,OAAOsD,GAAe,CAAE,UAAA,CAAWzC,CAAAA,CAAOb,CAAO,CAClD,CAEA,eAAsB0D,EAAAA,CACrB7C,CAAAA,CACAb,CAAAA,CACC,CACD,OAAOsD,CAAAA,EAAe,CAAE,iBAAA,CAAkBzC,CAAAA,CAAOb,CAAO,CACzD","file":"index.cjs","sourcesContent":["/**\n * Modern typed error hierarchy with enhanced capabilities\n * Provides type-safe error handling with fluent API and metadata support\n */\n\nimport type { Milliseconds } from '../types/branded-types';\n\n// Base typed error class with enhanced capabilities\nexport abstract class TypedError<\n\tCode extends string = string,\n\tMeta = unknown,\n> extends Error {\n\tabstract readonly code: Code;\n\treadonly cause?: unknown;\n\treadonly meta?: Meta;\n\treadonly status?: number;\n\treadonly timestamp: Date;\n\n\tconstructor(\n\t\tmessage: string,\n\t\topts?: { cause?: unknown; meta?: Meta; status?: number },\n\t) {\n\t\tsuper(message);\n\t\tthis.timestamp = new Date();\n\t\tthis.name = this.constructor.name;\n\t\t(this as { cause?: unknown }).cause = opts?.cause;\n\t\t(this as { meta?: Meta }).meta = opts?.meta;\n\t\t(this as { status?: number }).status = opts?.status;\n\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, this.constructor);\n\t\t}\n\t}\n\n\t// Type-safe error code checking\n\tis<C extends string>(code: C): this is TypedError<C> & { code: C } {\n\t\treturn (this.code as string) === code;\n\t}\n\n\t// Chainable metadata attachment\n\twithMeta<const M>(meta: M): this & { meta: M } {\n\t\treturn Object.assign(this, { meta });\n\t}\n\n\t// Chainable status code attachment\n\twithStatus(status: number): this & { status: number } {\n\t\treturn Object.assign(this, { status });\n\t}\n\n\t// Chainable cause attachment\n\twithCause(cause: unknown): this & { cause: unknown } {\n\t\treturn Object.assign(this, { cause });\n\t}\n\n\t// Convert to JSON representation\n\ttoJSON(): Record<string, unknown> {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tcode: this.code,\n\t\t\tmessage: this.message,\n\t\t\ttimestamp: this.timestamp.toISOString(),\n\t\t\tcause: this.cause,\n\t\t\tstack: this.stack,\n\t\t};\n\t}\n}\n\n// Built-in error types with enhanced capabilities\nexport class TimeoutError extends TypedError<'TIMEOUT'> {\n\treadonly code = 'TIMEOUT' as const;\n\n\tconstructor(timeout: Milliseconds, cause?: unknown) {\n\t\tsuper(`Operation timed out after ${timeout}ms`, { cause });\n\t}\n}\n\nexport class AbortedError extends TypedError<'ABORTED'> {\n\treadonly code = 'ABORTED' as const;\n\n\tconstructor(reason?: string, cause?: unknown) {\n\t\tsuper(reason || 'Operation was aborted', { cause });\n\t}\n}\n\nexport class CircuitOpenError extends TypedError<'CIRCUIT_OPEN'> {\n\treadonly code = 'CIRCUIT_OPEN' as const;\n\n\tconstructor(resetAfter: Milliseconds, cause?: unknown) {\n\t\tsuper(`Circuit breaker is open, reset after ${resetAfter}ms`, { cause });\n\t}\n}\n\ntype ValidationMeta = { validationErrors: unknown[] };\n\nexport class ValidationError extends TypedError<'VALIDATION', ValidationMeta> {\n\treadonly code = 'VALIDATION' as const;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly validationErrors: unknown[],\n\t\tcause?: unknown,\n\t) {\n\t\tsuper(message, { cause, meta: { validationErrors } });\n\t}\n}\n\nexport class NetworkError extends TypedError<'NETWORK'> {\n\treadonly code = 'NETWORK' as const;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly statusCode?: number,\n\t\tcause?: unknown,\n\t) {\n\t\tsuper(message, { cause, status: statusCode });\n\t}\n}\n\ntype HttpMeta = { response?: unknown };\n\nexport class HttpError extends TypedError<'HTTP', HttpMeta> {\n\treadonly code = 'HTTP' as const;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly status: number,\n\t\tpublic readonly response?: unknown,\n\t\tcause?: unknown,\n\t) {\n\t\tsuper(message, { cause, status, meta: { response } });\n\t}\n}\n\nexport class UnknownError extends TypedError<'UNKNOWN'> {\n\treadonly code = 'UNKNOWN' as const;\n\n\tconstructor(message: string, cause?: unknown) {\n\t\tsuper(message, { cause });\n\t}\n}\n\n// Error code union for built-in errors\nexport type BuiltInErrorCode =\n\t| 'TIMEOUT'\n\t| 'ABORTED'\n\t| 'CIRCUIT_OPEN'\n\t| 'VALIDATION'\n\t| 'NETWORK'\n\t| 'HTTP'\n\t| 'UNKNOWN';\n\n// Error factory functions for convenience\nexport const createTimeoutError = (\n\ttimeout: Milliseconds,\n\tcause?: unknown,\n): TimeoutError => new TimeoutError(timeout, cause);\n\nexport const createAbortedError = (\n\treason?: string,\n\tcause?: unknown,\n): AbortedError => new AbortedError(reason, cause);\n\nexport const createCircuitOpenError = (\n\tresetAfter: Milliseconds,\n\tcause?: unknown,\n): CircuitOpenError => new CircuitOpenError(resetAfter, cause);\n\nexport const createValidationError = (\n\tmessage: string,\n\terrors: unknown[],\n\tcause?: unknown,\n): ValidationError => new ValidationError(message, errors, cause);\n\nexport const createNetworkError = (\n\tmessage: string,\n\tstatusCode?: number,\n\tcause?: unknown,\n): NetworkError => new NetworkError(message, statusCode, cause);\n\nexport const createHttpError = (\n\tmessage: string,\n\tstatus: number,\n\tresponse?: unknown,\n\tcause?: unknown,\n): HttpError => new HttpError(message, status, response, cause);\n\nexport const createUnknownError = (cause?: unknown): UnknownError =>\n\tnew UnknownError('Unknown error occurred', cause);\n","/**\n * Modern circuit breaker implementation with enhanced state management\n * Provides circuit breaker pattern with type safety and observability\n */\n\nimport { CircuitOpenError, type TypedError } from '../error/typed-error';\nimport type { Milliseconds, RetryCount } from '../types/branded-types';\n\n// Circuit breaker configuration\nexport interface CircuitBreakerConfig<E extends TypedError = TypedError> {\n\t/** Number of consecutive failures before opening circuit */\n\treadonly failureThreshold: RetryCount;\n\n\t/** How long to wait before attempting to close circuit */\n\treadonly resetTimeout: Milliseconds;\n\n\t/** Number of requests allowed in half-open state */\n\treadonly halfOpenRequests: RetryCount;\n\n\t/** Optional function to determine if error should count as failure */\n\treadonly shouldCountAsFailure?: (error: E) => boolean;\n}\n\n// Circuit breaker state\nexport type CircuitState = 'closed' | 'open' | 'half-open';\n\n// Internal state tracking\ninterface CircuitBreakerInternalState {\n\treadonly state: CircuitState;\n\treadonly failureCount: RetryCount;\n\treadonly halfOpenCount: RetryCount;\n\treadonly lastFailureTime?: Date;\n\treadonly nextAttemptTime?: Date;\n}\n\n// Modern circuit breaker implementation\nexport class CircuitBreaker<E extends TypedError = TypedError> {\n\tprivate state: CircuitBreakerInternalState;\n\tprivate readonly config: CircuitBreakerConfig<E>;\n\n\tconstructor(config: CircuitBreakerConfig<E>) {\n\t\tthis.config = config;\n\t\tthis.state = {\n\t\t\tstate: 'closed',\n\t\t\tfailureCount: 0 as RetryCount,\n\t\t\thalfOpenCount: 0 as RetryCount,\n\t\t};\n\t}\n\n\t// Check if execution is allowed\n\tasync canExecute(): Promise<boolean> {\n\t\tthis.updateStateIfNeeded();\n\t\treturn this.state.state !== 'open';\n\t}\n\n\t// Record successful execution\n\tasync recordSuccess(): Promise<void> {\n\t\tswitch (this.state.state) {\n\t\t\tcase 'closed':\n\t\t\t\t// Reset failure count on success\n\t\t\t\tthis.state = {\n\t\t\t\t\t...this.state,\n\t\t\t\t\tfailureCount: 0 as RetryCount,\n\t\t\t\t};\n\t\t\t\tbreak;\n\n\t\t\tcase 'half-open':\n\t\t\t\t// Close circuit on first success in half-open\n\t\t\t\tthis.state = {\n\t\t\t\t\tstate: 'closed',\n\t\t\t\t\tfailureCount: 0 as RetryCount,\n\t\t\t\t\thalfOpenCount: 0 as RetryCount,\n\t\t\t\t};\n\t\t\t\tbreak;\n\n\t\t\tcase 'open':\n\t\t\t\t// Should not happen, but handle gracefully\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Record failed execution\n\tasync recordFailure(error: E): Promise<void> {\n\t\tconst shouldCount = this.config.shouldCountAsFailure?.(error) ?? true;\n\n\t\tif (!shouldCount) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst now = new Date();\n\n\t\tswitch (this.state.state) {\n\t\t\tcase 'closed': {\n\t\t\t\tconst newFailureCount = (this.state.failureCount + 1) as RetryCount;\n\n\t\t\t\tif (newFailureCount >= this.config.failureThreshold) {\n\t\t\t\t\t// Open circuit\n\t\t\t\t\tthis.state = {\n\t\t\t\t\t\tstate: 'open',\n\t\t\t\t\t\tfailureCount: newFailureCount,\n\t\t\t\t\t\thalfOpenCount: 0 as RetryCount,\n\t\t\t\t\t\tlastFailureTime: now,\n\t\t\t\t\t\tnextAttemptTime: new Date(now.getTime() + this.config.resetTimeout),\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\t// Increment failure count\n\t\t\t\t\tthis.state = {\n\t\t\t\t\t\t...this.state,\n\t\t\t\t\t\tfailureCount: newFailureCount,\n\t\t\t\t\t\tlastFailureTime: now,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'half-open':\n\t\t\t\t// Open circuit immediately on failure in half-open\n\t\t\t\tthis.state = {\n\t\t\t\t\tstate: 'open',\n\t\t\t\t\tfailureCount: (this.state.failureCount + 1) as RetryCount,\n\t\t\t\t\thalfOpenCount: 0 as RetryCount,\n\t\t\t\t\tlastFailureTime: now,\n\t\t\t\t\tnextAttemptTime: new Date(now.getTime() + this.config.resetTimeout),\n\t\t\t\t};\n\t\t\t\tbreak;\n\n\t\t\tcase 'open':\n\t\t\t\t// Already open, just update failure time\n\t\t\t\tthis.state = {\n\t\t\t\t\t...this.state,\n\t\t\t\t\tlastFailureTime: now,\n\t\t\t\t\tnextAttemptTime: new Date(now.getTime() + this.config.resetTimeout),\n\t\t\t\t};\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Get current circuit state\n\tgetState(): CircuitBreakerState {\n\t\tthis.updateStateIfNeeded();\n\t\treturn {\n\t\t\t...this.state,\n\t\t\tcanExecute: this.state.state !== 'open',\n\t\t};\n\t}\n\n\t// Create error for when circuit is open\n\tcreateOpenError(): CircuitOpenError {\n\t\tconst resetAfter = this.state.nextAttemptTime\n\t\t\t? ((this.state.nextAttemptTime.getTime() - Date.now()) as Milliseconds)\n\t\t\t: this.config.resetTimeout;\n\n\t\treturn new CircuitOpenError(resetAfter);\n\t}\n\n\t// Force circuit to specific state (for testing/maintenance)\n\tforceState(state: CircuitState): void {\n\t\tthis.state = {\n\t\t\tstate,\n\t\t\tfailureCount: 0 as RetryCount,\n\t\t\thalfOpenCount: 0 as RetryCount,\n\t\t};\n\t}\n\n\t// Reset circuit to closed state\n\treset(): void {\n\t\tthis.state = {\n\t\t\tstate: 'closed',\n\t\t\tfailureCount: 0 as RetryCount,\n\t\t\thalfOpenCount: 0 as RetryCount,\n\t\t};\n\t}\n\n\t// Update state based on time\n\tprivate updateStateIfNeeded(): void {\n\t\tif (this.state.state === 'open' && this.state.nextAttemptTime) {\n\t\t\tconst now = new Date();\n\t\t\tif (now >= this.state.nextAttemptTime) {\n\t\t\t\t// Move to half-open state\n\t\t\t\tthis.state = {\n\t\t\t\t\t...this.state,\n\t\t\t\t\tstate: 'half-open',\n\t\t\t\t\thalfOpenCount: 0 as RetryCount,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Circuit breaker state information\nexport interface CircuitBreakerState {\n\treadonly state: CircuitState;\n\treadonly failureCount: RetryCount;\n\treadonly halfOpenCount: RetryCount;\n\treadonly lastFailureTime?: Date;\n\treadonly nextAttemptTime?: Date;\n\treadonly canExecute: boolean;\n}\n","/**\n * Modern error normalization system\n * Provides type-safe error transformation and normalization\n */\n\nimport { TypedError } from './typed-error';\n\n// Error normalizer function type\nexport type ErrorNormalizer<E extends TypedError = TypedError> = (\n\terror: unknown,\n) => E;\n\n// Built-in error normalizer rules\nexport type ErrorRule<E extends TypedError = TypedError> = (\n\terror: unknown,\n) => E | null;\n\n// Error normalization result\nexport type NormalizationResult<E extends TypedError> =\n\t| { success: true; error: E }\n\t| { success: false; originalError: unknown };\n\n// Create error normalizer from rules\nexport const createErrorNormalizer = <E extends TypedError>(\n\trules: ErrorRule<E>[],\n\tfallback: ErrorNormalizer<E>,\n): ErrorNormalizer<E> => {\n\treturn (error: unknown): E => {\n\t\tfor (const rule of rules) {\n\t\t\tconst result = rule(error);\n\t\t\tif (result !== null) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\treturn fallback(error);\n\t};\n};\n\n// Create default fallback normalizer\nexport const createFallbackNormalizer = <E extends TypedError>(\n\tErrorClass: new (message: string, cause?: unknown) => E,\n): ErrorNormalizer<E> => {\n\treturn (error: unknown): E => {\n\t\tif (error instanceof TypedError) {\n\t\t\treturn error as unknown as E;\n\t\t}\n\n\t\tif (error instanceof Error) {\n\t\t\treturn new ErrorClass(error.message, error);\n\t\t}\n\t\tif (typeof error === 'string') {\n\t\t\treturn new ErrorClass(error);\n\t\t}\n\t\treturn new ErrorClass('Unknown error occurred', error);\n\t};\n};\n","/**\n * Modern fluent error rule builder\n * Provides type-safe error rule creation with enhanced ergonomics\n */\n\nimport type { ErrorRule } from './error-normalizer';\nimport { TypedError } from './typed-error';\n\ntype StatusCarrier = {\n\tstatus?: number;\n\tstatusCode?: number;\n\tmessage?: string;\n};\n\nconst hasNumericStatus = (err: unknown): err is StatusCarrier => {\n\tif (typeof err !== 'object' || err === null) return false;\n\tconst candidate = err as StatusCarrier;\n\treturn (\n\t\ttypeof candidate.status === 'number' ||\n\t\ttypeof candidate.statusCode === 'number'\n\t);\n};\n\n// Modern error rule builder with enhanced ergonomics\nexport class ErrorRuleBuilder<T> {\n\tconstructor(private readonly predicate: (err: unknown) => err is T) {}\n\n\ttoCode<const C extends string>(code: C) {\n\t\treturn new ErrorMapper<T, C>(this.predicate, code);\n\t}\n\n\t// Map to a typed error instance (compatible with existing tests)\n\t// The returned rule is usable in createErrorNormalizer/trybox({ rules }).\n\ttoError<\n\t\tconst Out extends {\n\t\t\tcode: string;\n\t\t\tmessage: string;\n\t\t\tmeta?: unknown;\n\t\t\tstatus?: number;\n\t\t\tcause?: unknown;\n\t\t},\n\t>(mapper: (err: T) => Out): ErrorRule<TypedError<Out['code'], Out['meta']>> {\n\t\treturn (err: unknown) => {\n\t\t\tif (!this.predicate(err)) return null;\n\t\t\tconst out = mapper(err as T);\n\t\t\tconst code = out.code as Out['code'];\n\n\t\t\tclass CustomError extends TypedError<Out['code'], Out['meta']> {\n\t\t\t\treadonly code = code;\n\t\t\t\tconstructor() {\n\t\t\t\t\tsuper(out.message, {\n\t\t\t\t\t\tcause: out.cause ?? err,\n\t\t\t\t\t\tmeta: out.meta,\n\t\t\t\t\t\tstatus: out.status,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn new CustomError();\n\t\t};\n\t}\n}\n\n// Error mapper for code-based mapping\nexport class ErrorMapper<T, C extends string> {\n\tconstructor(\n\t\tprivate readonly predicate: (err: unknown) => err is T,\n\t\tprivate readonly errorCode: C,\n\t) {}\n\n\twith<const M = unknown>(\n\t\tmapper: (err: T) => {\n\t\t\tmessage: string;\n\t\t\tcause?: unknown;\n\t\t\tmeta?: M;\n\t\t\tstatus?: number;\n\t\t},\n\t) {\n\t\treturn (err: unknown): TypedError<C, M> | null => {\n\t\t\tif (!this.predicate(err)) return null;\n\t\t\tconst mapped = mapper(err);\n\n\t\t\tconst errorCode = this.errorCode;\n\t\t\tclass CustomTypedError extends TypedError<C, M> {\n\t\t\t\treadonly code = errorCode;\n\t\t\t\tconstructor() {\n\t\t\t\t\tsuper(mapped.message, {\n\t\t\t\t\t\tcause: mapped.cause,\n\t\t\t\t\t\tmeta: mapped.meta,\n\t\t\t\t\t\tstatus: mapped.status,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn new CustomTypedError();\n\t\t};\n\t}\n}\n\n// Enhanced error rule factory with modern patterns\nexport const createErrorRule = {\n\twhen: <T>(predicate: (err: unknown) => err is T) =>\n\t\tnew ErrorRuleBuilder(predicate),\n\n\tinstance: <T extends new (...args: unknown[]) => unknown>(ErrorClass: T) =>\n\t\tnew ErrorRuleBuilder(\n\t\t\t(err): err is InstanceType<T> => err instanceof ErrorClass,\n\t\t),\n\n\tcode: <C extends string>(code: C) => ({\n\t\tfor: <T>(predicate: (err: unknown) => err is T) =>\n\t\t\tnew ErrorMapper(predicate, code),\n\t}),\n\n\t// Built-in error rules for common cases\n\tstring: <C extends string>(message: string, code: C) => ({\n\t\twhen: <T>(predicate: (err: unknown) => err is T) =>\n\t\t\tcreateErrorRule\n\t\t\t\t.when(predicate)\n\t\t\t\t.toCode(code)\n\t\t\t\t.with((err) => ({\n\t\t\t\t\tmessage: err === message ? message : `${code}: ${err}`,\n\t\t\t\t\tcause: err,\n\t\t\t\t})),\n\t}),\n\n\t// HTTP status error rule\n\thttpStatus: <C extends string>(status: number, code?: C) => ({\n\t\tfor: <T>(predicate: (err: unknown) => err is T) =>\n\t\t\tcreateErrorRule\n\t\t\t\t.when(predicate)\n\t\t\t\t.toCode(code ?? `HTTP_${status}`)\n\t\t\t\t.with((err) => ({\n\t\t\t\t\tmessage: `HTTP ${status} error`,\n\t\t\t\t\tcause: err,\n\t\t\t\t})),\n\t}),\n\n\t// NOTE: advanced helpers removed for simplicity\n} as const;\n\n// Legacy compatibility exports\nexport { ErrorRuleBuilder as errorRuleBuilder, ErrorMapper as errorMapper };\n\n// Utility functions for rule composition\nexport const combineRules = <E extends TypedError>(\n\t...rules: ErrorRule<E>[]\n): ErrorRule<E> => {\n\treturn (error: unknown): E | null => {\n\t\tfor (const rule of rules) {\n\t\t\tconst result = rule(error);\n\t\t\tif (result !== null) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t};\n};\n\nexport const chainRules = (\n\t...rules: Array<ErrorRule<TypedError> | ((err: unknown) => TypedError | null)>\n): ErrorRule<TypedError> => {\n\treturn (error: unknown): TypedError | null => {\n\t\tconst currentError = error;\n\n\t\tfor (const rule of rules) {\n\t\t\tconst result = rule(currentError);\n\t\t\tif (result !== null) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t};\n};\n\n// Built-in error rule presets\nexport const BuiltinRules = {\n\t// Abort errors\n\tabort: createErrorRule\n\t\t.when(\n\t\t\t(err): err is DOMException =>\n\t\t\t\terr instanceof DOMException && err.name === 'AbortError',\n\t\t)\n\t\t.toCode('ABORTED')\n\t\t.with((err) => ({\n\t\t\tmessage: err.message || 'Operation was aborted',\n\t\t\tcause: err,\n\t\t})),\n\n\t// Timeout errors\n\ttimeout: createErrorRule\n\t\t.when(\n\t\t\t(err): err is Error =>\n\t\t\t\terr instanceof Error && err.name === 'TimeoutError',\n\t\t)\n\t\t.toCode('TIMEOUT')\n\t\t.with((err) => ({\n\t\t\tmessage: err.message || 'Operation timed out',\n\t\t\tcause: err,\n\t\t})),\n\n\t// Network errors\n\tnetwork: createErrorRule\n\t\t.when((err): err is StatusCarrier => hasNumericStatus(err))\n\t\t.toCode('NETWORK')\n\t\t.with((err) => {\n\t\t\tconst status = err.status ?? err.statusCode;\n\t\t\treturn {\n\t\t\t\tmessage:\n\t\t\t\t\terr.message || `Network error with status ${status ?? 'unknown'}`,\n\t\t\t\tcause: err,\n\t\t\t};\n\t\t}),\n\n\t// HTTP errors (4xx, 5xx)\n\thttp: createErrorRule\n\t\t.when((err): err is StatusCarrier => {\n\t\t\tif (!hasNumericStatus(err)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconst candidate = err as StatusCarrier;\n\t\t\tconst status = candidate.status ?? candidate.statusCode;\n\t\t\treturn typeof status === 'number' && status >= 400;\n\t\t})\n\t\t.toCode('HTTP')\n\t\t.with((err) => {\n\t\t\tconst status = err.status ?? err.statusCode;\n\t\t\treturn {\n\t\t\t\tmessage: err.message || `HTTP ${status ?? 'error'} error`,\n\t\t\t\tcause: err,\n\t\t\t};\n\t\t}),\n\n\t// Generic error fallback\n\tunknown: createErrorRule\n\t\t.when((err): err is Error => err instanceof Error)\n\t\t.toCode('UNKNOWN')\n\t\t.with((err) => ({\n\t\t\tmessage: err.message || 'Unknown error occurred',\n\t\t\tcause: err,\n\t\t})),\n} as const;\n","/**\n * Built-in error rules for common error patterns\n * Provides ready-to-use error normalization rules\n */\n\nimport { BuiltinRules, createErrorRule } from './error-builder';\nimport type { ErrorRule } from './error-normalizer';\nimport { CircuitOpenError, ValidationError } from './typed-error';\n\n// Built-in error rules export\nexport { BuiltinRules };\n\n// Combined built-in rules array\nexport const builtInRules: ErrorRule[] = [\n\tBuiltinRules.abort,\n\tBuiltinRules.timeout,\n\tBuiltinRules.network,\n\tBuiltinRules.http,\n\tBuiltinRules.unknown,\n];\n\n// Export createErrorRule for convenience\nexport { createErrorRule };\n\n// Error rule factory for creating custom rules\nexport const errorRule = {\n\twhen: <T>(predicate: (err: unknown) => err is T) =>\n\t\tcreateErrorRule.when(predicate),\n\n\tinstance: <T extends new (...args: unknown[]) => unknown>(ErrorClass: T) =>\n\t\tcreateErrorRule.instance(ErrorClass),\n} as const;\n\n// Default error rule set\nexport const defaultRules = builtInRules;\n\n// Timeout error rule\nexport const timeoutErrorRule: ErrorRule = BuiltinRules.timeout;\n\n// Aborted error rule\nexport const abortedErrorRule: ErrorRule = BuiltinRules.abort;\n\n// Network error rule\nexport const networkErrorRule: ErrorRule = BuiltinRules.network;\n\n// HTTP error rule\nexport const httpErrorRule: ErrorRule = BuiltinRules.http;\n\n// Circuit breaker error rule\nexport const circuitOpenErrorRule: ErrorRule = createErrorRule\n\t.when((err): err is CircuitOpenError => err instanceof CircuitOpenError)\n\t.toCode('CIRCUIT_OPEN')\n\t.with((err) => ({\n\t\tmessage: err.message,\n\t\tcause: err,\n\t}));\n\n// Validation error rule\nexport const validationErrorRule: ErrorRule = createErrorRule\n\t.when((err): err is ValidationError => err instanceof ValidationError)\n\t.toCode('VALIDATION')\n\t.with((err) => ({\n\t\tmessage: err.message,\n\t\tcause: err,\n\t}));\n","/**\n * Modern retry strategies with enhanced capabilities\n * Provides various retry patterns with type safety\n */\n\nimport type { Milliseconds, RetryCount } from '../types/branded-types';\n\n// Modern retry strategy types\nexport type RetryStrategy =\n\t| FixedDelayStrategy\n\t| ExponentialBackoffStrategy\n\t| FibonacciBackoffStrategy\n\t| CustomDelayStrategy;\n\nexport interface FixedDelayStrategy {\n\treadonly type: 'fixed';\n\treadonly delay: Milliseconds;\n}\n\nexport interface ExponentialBackoffStrategy {\n\treadonly type: 'exponential';\n\treadonly base: Milliseconds;\n\treadonly factor: number;\n\treadonly maxDelay?: Milliseconds;\n}\n\nexport interface FibonacciBackoffStrategy {\n\treadonly type: 'fibonacci';\n\treadonly base: Milliseconds;\n\treadonly maxDelay?: Milliseconds;\n}\n\nexport interface CustomDelayStrategy {\n\treadonly type: 'custom';\n\treadonly calculate: (attempt: RetryCount, error: unknown) => Milliseconds;\n}\n\n// Strategy factory functions\nexport const RetryStrategies = {\n\tfixed: (delay: Milliseconds): FixedDelayStrategy => ({\n\t\ttype: 'fixed',\n\t\tdelay,\n\t}),\n\n\texponential: (\n\t\tbase: Milliseconds,\n\t\tfactor: number = 2,\n\t\tmaxDelay?: Milliseconds,\n\t): ExponentialBackoffStrategy => ({\n\t\ttype: 'exponential',\n\t\tbase,\n\t\tfactor,\n\t\tmaxDelay,\n\t}),\n\n\tfibonacci: (\n\t\tbase: Milliseconds,\n\t\tmaxDelay?: Milliseconds,\n\t): FibonacciBackoffStrategy => ({\n\t\ttype: 'fibonacci',\n\t\tbase,\n\t\tmaxDelay,\n\t}),\n\n\tcustom: (\n\t\tcalculate: (attempt: RetryCount, error: unknown) => Milliseconds,\n\t): CustomDelayStrategy => ({\n\t\ttype: 'custom',\n\t\tcalculate,\n\t}),\n} as const;\n\n// Delay calculation functions\nexport const calculateDelay = (\n\tstrategy: RetryStrategy,\n\tattempt: RetryCount,\n\terror: unknown,\n): Milliseconds => {\n\tswitch (strategy.type) {\n\t\tcase 'fixed': {\n\t\t\treturn strategy.delay;\n\t\t}\n\t\tcase 'exponential': {\n\t\t\tconst expDelay = strategy.base * strategy.factor ** (Number(attempt) - 1);\n\t\t\treturn (\n\t\t\t\tstrategy.maxDelay ? Math.min(expDelay, strategy.maxDelay) : expDelay\n\t\t\t) as Milliseconds;\n\t\t}\n\n\t\tcase 'fibonacci': {\n\t\t\tconst fibDelay = strategy.base * fibonacci(Number(attempt));\n\t\t\treturn (\n\t\t\t\tstrategy.maxDelay ? Math.min(fibDelay, strategy.maxDelay) : fibDelay\n\t\t\t) as Milliseconds;\n\t\t}\n\n\t\tcase 'custom': {\n\t\t\treturn strategy.calculate(attempt, error);\n\t\t}\n\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = strategy;\n\t\t\treturn _exhaustive;\n\t\t}\n\t}\n};\n\n// Fibonacci sequence calculator\nconst fibonacci = (n: number): number => {\n\tif (n <= 1) return 1;\n\tlet prev = 1;\n\tlet curr = 1;\n\tfor (let i = 2; i <= n; i++) {\n\t\tconst next = prev + curr;\n\t\tprev = curr;\n\t\tcurr = next;\n\t}\n\treturn curr;\n};\n\n// Utility functions for strategy validation\nexport const validateStrategy = (strategy: RetryStrategy): void => {\n\tswitch (strategy.type) {\n\t\tcase 'fixed': {\n\t\t\tif (strategy.delay <= 0) {\n\t\t\t\tthrow new Error('Fixed delay must be positive');\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tcase 'exponential':\n\t\t\tif (strategy.base <= 0) {\n\t\t\t\tthrow new Error('Exponential base delay must be positive');\n\t\t\t}\n\t\t\tif (strategy.factor <= 1) {\n\t\t\t\tthrow new Error('Exponential factor must be greater than 1');\n\t\t\t}\n\t\t\tif (strategy.maxDelay && strategy.maxDelay <= 0) {\n\t\t\t\tthrow new Error('Exponential max delay must be positive');\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 'fibonacci':\n\t\t\tif (strategy.base <= 0) {\n\t\t\t\tthrow new Error('Fibonacci base delay must be positive');\n\t\t\t}\n\t\t\tif (strategy.maxDelay && strategy.maxDelay <= 0) {\n\t\t\t\tthrow new Error('Fibonacci max delay must be positive');\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 'custom':\n\t\t\t// Cannot validate custom function at runtime\n\t\t\tbreak;\n\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = strategy;\n\t\t\tthrow new Error(`Unknown strategy type: ${_exhaustive}`);\n\t\t}\n\t}\n};\n","/**\n * Modern utility functions for timing and common operations\n * Provides enhanced utilities with type safety\n */\n\nimport type { Milliseconds } from '../types/branded-types';\n\n// Enhanced sleep function with cancellation support\nexport const sleep = (\n\tms: number | Milliseconds,\n\tsignal?: AbortSignal,\n): Promise<void> => {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t\treturn;\n\t\t}\n\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\tresolve();\n\t\t}, ms as number);\n\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timeoutId);\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t};\n\n\t\tsignal?.addEventListener('abort', onAbort, { once: true });\n\t});\n};\n\n// Enhanced timeout with promise race\nexport const withTimeout = <T>(\n\tpromise: Promise<T>,\n\ttimeoutMs: Milliseconds,\n\tsignal?: AbortSignal,\n): Promise<T> => {\n\tconst timeoutPromise = sleep(timeoutMs, signal).then(() => {\n\t\tthrow new Error(`Operation timed out after ${timeoutMs}ms`);\n\t});\n\n\treturn Promise.race([promise, timeoutPromise]);\n};\n\n// Debounce function with type safety\nexport const debounce = <T extends (...args: unknown[]) => unknown>(\n\tfunc: T,\n\tdelay: Milliseconds,\n): T => {\n\tlet timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n\treturn ((...args: Parameters<T>) => {\n\t\tif (timeoutId !== null) {\n\t\t\tclearTimeout(timeoutId);\n\t\t}\n\n\t\ttimeoutId = setTimeout(() => {\n\t\t\tfunc(...args);\n\t\t\ttimeoutId = null;\n\t\t}, delay);\n\t}) as T;\n};\n\n// Throttle function with type safety\nexport const throttle = <T extends (...args: unknown[]) => unknown>(\n\tfunc: T,\n\tdelay: Milliseconds,\n): T => {\n\tlet lastCallTime = 0;\n\tlet timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n\treturn ((...args: Parameters<T>) => {\n\t\tconst now = Date.now();\n\n\t\tif (now - lastCallTime >= delay) {\n\t\t\tlastCallTime = now;\n\t\t\tfunc(...args);\n\t\t} else if (timeoutId === null) {\n\t\t\ttimeoutId = setTimeout(\n\t\t\t\t() => {\n\t\t\t\t\tlastCallTime = Date.now();\n\t\t\t\t\tfunc(...args);\n\t\t\t\t\ttimeoutId = null;\n\t\t\t\t},\n\t\t\t\tdelay - (now - lastCallTime),\n\t\t\t);\n\t\t}\n\t}) as T;\n};\n\n// Retry with exponential backoff\nexport const retry = async <T>(\n\toperation: () => Promise<T>,\n\tmaxRetries: number,\n\tbaseDelay: Milliseconds,\n\tbackoffFactor: number = 2,\n): Promise<T> => {\n\tlet lastError: Error | undefined;\n\n\tfor (let attempt = 0; attempt <= maxRetries; attempt++) {\n\t\ttry {\n\t\t\treturn await operation();\n\t\t} catch (error) {\n\t\t\tlastError = error instanceof Error ? error : new Error(String(error));\n\n\t\t\tif (attempt === maxRetries) {\n\t\t\t\tthrow lastError;\n\t\t\t}\n\n\t\t\tconst delay = baseDelay * backoffFactor ** attempt;\n\t\t\tawait sleep(delay as Milliseconds);\n\t\t}\n\t}\n\n\tthrow lastError ?? new Error('Operation failed after retries');\n};\n\n// Measure execution time\nexport const measureTime = async <T>(\n\toperation: () => Promise<T>,\n): Promise<{ result: T; duration: Milliseconds }> => {\n\tconst start = Date.now();\n\tconst result = await operation();\n\tconst duration = (Date.now() - start) as Milliseconds;\n\n\treturn { result, duration };\n};\n\n// Create a promise with external resolve/reject\nexport const createDeferred = <T = void>(): {\n\tpromise: Promise<T>;\n\tresolve: (value: T) => void;\n\treject: (reason?: unknown) => void;\n} => {\n\tlet resolve: ((value: T) => void) | undefined;\n\tlet reject: ((reason?: unknown) => void) | undefined;\n\n\tconst promise = new Promise<T>((res, rej) => {\n\t\tresolve = res;\n\t\treject = rej;\n\t});\n\n\tif (!resolve || !reject) {\n\t\tthrow new Error('Promise executor did not initialize resolve/reject');\n\t}\n\n\treturn { promise, resolve, reject };\n};\n\n// Safe JSON parsing with error handling\nexport const safeJsonParse = <T = unknown>(\n\ttext: string,\n\tfallback?: T,\n): T | null => {\n\ttry {\n\t\treturn JSON.parse(text) as T;\n\t} catch {\n\t\treturn fallback ?? null;\n\t}\n};\n\n// Safe JSON stringify with error handling\nexport const safeJsonStringify = (\n\tvalue: unknown,\n\tfallback?: string,\n): string | null => {\n\ttry {\n\t\treturn JSON.stringify(value);\n\t} catch {\n\t\treturn fallback ?? null;\n\t}\n};\n","/**\n * Modern executor with enhanced capabilities\n * Provides comprehensive task execution with circuit breaker and retry logic\n */\n\nimport { CircuitBreaker } from '../circuit-breaker/breaker';\nimport type { ErrorNormalizer, ErrorRule } from '../error/error-normalizer';\nimport {\n\tcreateErrorNormalizer,\n\tcreateFallbackNormalizer,\n} from '../error/error-normalizer';\nimport { defaultRules } from '../error/error-rules';\nimport {\n\ttype AbortedError,\n\ttype CircuitOpenError,\n\ttype HttpError,\n\ttype NetworkError,\n\tTimeoutError,\n\ttype TypedError,\n\tUnknownError,\n\ttype ValidationError,\n} from '../error/typed-error';\nimport { calculateDelay } from '../retry/retry-strategies';\nimport type { Milliseconds, RetryCount } from '../types/branded-types';\nimport type { ExecutionConfig } from '../types/config-types';\nimport type { ExecutionMetrics, ExecutionResult } from '../types/result-types';\nimport { sleep } from '../utils/timing';\n\n// Modern executor with enhanced capabilities\nexport type RulesMode = 'extend' | 'replace';\n\nexport type DefaultError =\n\t| AbortedError\n\t| TimeoutError\n\t| NetworkError\n\t| HttpError\n\t| CircuitOpenError\n\t| ValidationError\n\t| UnknownError;\n\ntype NonNull<T> = T extends null ? never : T;\ntype RuleReturn<R> = R extends (err: unknown) => infer Out\n\t? NonNull<Out>\n\t: never;\n\nexport type InferErrorFromRules<\n\tTRules extends readonly ErrorRule<TypedError>[],\n> = TRules extends readonly []\n\t? TypedError\n\t: RuleReturn<TRules[number]> | UnknownError;\n\nexport type ExecutorOptions<E extends TypedError = TypedError> = Omit<\n\tPartial<ExecutionConfig<E>>,\n\t'errorHandling'\n> & {\n\trules?: Array<ErrorRule<E>>;\n\trulesMode?: RulesMode;\n\tfallback?: (err: unknown) => E;\n\ttoError?: (err: unknown) => E;\n\tmapError?: (error: E) => E;\n};\n\nconst buildNormalizer = <E extends TypedError>(\n\topts: ExecutorOptions<E>,\n): ErrorNormalizer<E> => {\n\tif (opts.toError) return opts.toError;\n\n\tconst rulesMode: RulesMode = opts.rulesMode ?? 'extend';\n\tconst userRules = (opts.rules ?? []) as Array<ErrorRule<E>>;\n\tconst builtins = defaultRules as unknown as Array<ErrorRule<E>>;\n\n\tconst fallback =\n\t\topts.fallback ??\n\t\t((err: unknown) =>\n\t\t\tcreateFallbackNormalizer(\n\t\t\t\tUnknownError as unknown as new (\n\t\t\t\t\tmessage: string,\n\t\t\t\t\tcause?: unknown,\n\t\t\t\t) => E,\n\t\t\t)(err));\n\n\tconst rules =\n\t\trulesMode === 'replace' ? userRules : [...userRules, ...builtins];\n\treturn createErrorNormalizer(rules, fallback);\n};\n\nexport class Executor<E extends TypedError = TypedError> {\n\tprivate readonly circuitBreaker?: CircuitBreaker<E>;\n\tprivate readonly config: ExecutionConfig<E>;\n\n\tconstructor(options: ExecutorOptions<E> = {}) {\n\t\tconst {\n\t\t\trules: _rules,\n\t\t\trulesMode: _rulesMode,\n\t\t\tfallback: _fallback,\n\t\t\ttoError: _toError,\n\t\t\tmapError,\n\t\t\t...executionConfig\n\t\t} = options;\n\t\tconst normalizer = buildNormalizer(options);\n\t\tconst baseConfig: ExecutionConfig<E> = {\n\t\t\t...executionConfig,\n\t\t\terrorHandling: {\n\t\t\t\tnormalizer,\n\t\t\t\tmapError,\n\t\t\t},\n\t\t};\n\n\t\tthis.config = baseConfig;\n\n\t\tif (baseConfig.circuitBreaker) {\n\t\t\tthis.circuitBreaker = new CircuitBreaker(baseConfig.circuitBreaker);\n\t\t}\n\t}\n\n\t// Execute a single task\n\tasync execute<T>(\n\t\ttask: (ctx: { signal: AbortSignal }) => Promise<T>,\n\t\toptions: Partial<ExecutionConfig<E>> = {},\n\t): Promise<ExecutionResult<T, E>> {\n\t\tconst mergedConfig = { ...this.config, ...options };\n\n\t\t// Circuit breaker check\n\t\tif (this.circuitBreaker) {\n\t\t\tconst canExecute = await this.circuitBreaker.canExecute();\n\t\t\tif (!canExecute) {\n\t\t\t\tconst error = this.circuitBreaker.createOpenError() as E;\n\n\t\t\t\tconst result: ExecutionResult<T, E> = {\n\t\t\t\t\ttype: 'failure',\n\t\t\t\t\tok: false,\n\t\t\t\t\tdata: null,\n\t\t\t\t\terror,\n\t\t\t\t\tmetrics: {\n\t\t\t\t\t\ttotalAttempts: 0 as RetryCount,\n\t\t\t\t\t\ttotalRetries: 0 as RetryCount,\n\t\t\t\t\t\ttotalDuration: 0 as Milliseconds,\n\t\t\t\t\t\tretryHistory: [],\n\t\t\t\t\t},\n\t\t\t\t};\n\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\n\t\tconst result = await executeInternal(task, mergedConfig);\n\n\t\t// Update circuit breaker state\n\t\tif (this.circuitBreaker) {\n\t\t\tif (result.ok) {\n\t\t\t\tawait this.circuitBreaker.recordSuccess();\n\t\t\t} else {\n\t\t\t\tawait this.circuitBreaker.recordFailure(result.error);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tasync executeOrThrow<T>(\n\t\ttask: (ctx: { signal: AbortSignal }) => Promise<T>,\n\t\toptions: Partial<ExecutionConfig<E>> = {},\n\t): Promise<T> {\n\t\tconst r = await this.execute(task, options);\n\t\tif (r.ok) return r.data;\n\t\tthrow r.error;\n\t}\n\n\t// Execute multiple tasks with concurrency control\n\tasync executeAll<T>(\n\t\ttasks: Array<(ctx: { signal: AbortSignal }) => Promise<T>>,\n\t\toptions: Partial<ExecutionConfig<E> & { concurrency?: number }> = {},\n\t): Promise<ExecutionResult<T, E>[]> {\n\t\tconst mergedConfig = { ...this.config, ...options };\n\t\tconst concurrency = mergedConfig.concurrency ?? Number.POSITIVE_INFINITY;\n\n\t\tconst out: ExecutionResult<T, E>[] = new Array(tasks.length);\n\t\tlet idx = 0;\n\n\t\tconst worker = async () => {\n\t\t\twhile (true) {\n\t\t\t\tconst current = idx;\n\t\t\t\tidx++;\n\t\t\t\tif (current >= tasks.length) return;\n\t\t\t\tconst task = tasks[current];\n\t\t\t\tif (!task) return;\n\t\t\t\tout[current] = await this.execute(task, mergedConfig);\n\t\t\t}\n\t\t};\n\n\t\tconst workers = Array.from(\n\t\t\t{ length: Math.min(concurrency, tasks.length) },\n\t\t\t() => worker(),\n\t\t);\n\t\tawait Promise.all(workers);\n\n\t\treturn out;\n\t}\n\n\tasync executeAllOrThrow<T>(\n\t\ttasks: Array<(ctx: { signal: AbortSignal }) => Promise<T>>,\n\t\toptions: Partial<ExecutionConfig<E> & { concurrency?: number }> = {},\n\t): Promise<T[]> {\n\t\tconst results = await this.executeAll(tasks, options);\n\t\tfor (const r of results) {\n\t\t\tif (!r.ok) throw r.error;\n\t\t}\n\t\treturn results.map((r) => {\n\t\t\tif (!r.ok) throw r.error;\n\t\t\treturn r.data;\n\t\t});\n\t}\n\n\t// (additional helpers removed; prefer compose outside)\n\n\t// Get current circuit breaker state\n\tgetCircuitBreakerState() {\n\t\treturn this.circuitBreaker?.getState();\n\t}\n\n\t// Reset circuit breaker\n\tresetCircuitBreaker(): void {\n\t\tthis.circuitBreaker?.reset();\n\t}\n\n\t// Get executor configuration\n\tgetConfig(): ExecutionConfig<E> {\n\t\treturn { ...this.config };\n\t}\n\n\t// Create a new executor with merged configuration\n\twithConfig(additionalConfig: Partial<ExecutionConfig<E>>): Executor<E> {\n\t\tconst { errorHandling: _currentHandling, ...baseConfig } = this.config;\n\t\tconst { errorHandling: _newHandling, ...extraConfig } = additionalConfig;\n\t\treturn new Executor<E>({\n\t\t\t...baseConfig,\n\t\t\t...extraConfig,\n\t\t});\n\t}\n\n\t// Create a new executor with different error type\n\twithErrorType<T extends TypedError>(\n\t\tconfig: Partial<ExecutionConfig<T>> = {},\n\t): Executor<T> {\n\t\treturn new Executor<T>(config as ExecutionConfig<T>);\n\t}\n}\n\nexport function createExecutor<E extends TypedError = DefaultError>(\n\toptions?: ExecutorOptions<E>,\n): Executor<E> {\n\treturn new Executor<E>(options);\n}\n\nasync function executeInternal<T, E extends TypedError>(\n\ttask: (ctx: { signal: AbortSignal }) => Promise<T>,\n\tconfig: ExecutionConfig<E>,\n): Promise<ExecutionResult<T, E>> {\n\tconst {\n\t\tsignal: outerSignal,\n\t\tignoreAbort = true,\n\t\ttimeout,\n\t\tretry,\n\t\terrorHandling,\n\t\thooks,\n\t\tlogger,\n\t} = config;\n\n\tlet lastError: E | undefined;\n\tlet totalAttempts = 0 as RetryCount;\n\tlet totalRetries = 0 as RetryCount;\n\tconst retryHistory: Array<{\n\t\tattempt: RetryCount;\n\t\terror: E;\n\t\tdelay: Milliseconds;\n\t\ttimestamp: Date;\n\t}> = [];\n\tconst startTime = Date.now();\n\n\tconst compositeSignal = createCompositeSignal(outerSignal);\n\tif (compositeSignal.aborted) {\n\t\t// normalize abort immediately\n\t\tconst e = errorHandling.normalizer(\n\t\t\tnew DOMException('Aborted', 'AbortError'),\n\t\t);\n\t\tconst mapped = errorHandling.mapError ? errorHandling.mapError(e) : e;\n\t\treturn {\n\t\t\ttype: 'aborted',\n\t\t\tok: false,\n\t\t\tdata: null,\n\t\t\terror: mapped,\n\t\t\tmetrics: {\n\t\t\t\ttotalAttempts,\n\t\t\t\ttotalRetries,\n\t\t\t\ttotalDuration: (Date.now() - startTime) as Milliseconds,\n\t\t\t\tlastError: mapped,\n\t\t\t\tretryHistory,\n\t\t\t},\n\t\t};\n\t}\n\n\tconst runAttempt = async (attempt: number): Promise<T> => {\n\t\ttotalAttempts = attempt as RetryCount;\n\t\ttry {\n\t\t\tconst p = task({ signal: compositeSignal });\n\t\t\tconst data = timeout\n\t\t\t\t? await withTimeout(p, timeout, compositeSignal)\n\t\t\t\t: await p;\n\t\t\thooks?.onSuccess?.(data);\n\t\t\tlogger?.info?.(`Task succeeded on attempt ${attempt}`);\n\t\t\treturn data;\n\t\t} catch (err) {\n\t\t\tconst norm = errorHandling.normalizer(err);\n\t\t\tconst mapped = errorHandling.mapError\n\t\t\t\t? errorHandling.mapError(norm)\n\t\t\t\t: norm;\n\t\t\tlastError = mapped;\n\n\t\t\tif (!(ignoreAbort && mapped.code === 'ABORTED')) {\n\t\t\t\thooks?.onError?.(mapped);\n\t\t\t\tlogger?.error?.(`Task failed on attempt ${attempt}`, mapped);\n\t\t\t}\n\n\t\t\tif (attempt <= (retry?.maxRetries ?? (0 as RetryCount))) {\n\t\t\t\tconst shouldRetry = retry?.shouldRetry;\n\t\t\t\tconst ctx = {\n\t\t\t\t\ttotalAttempts: totalAttempts,\n\t\t\t\t\telapsedTime: (Date.now() - startTime) as Milliseconds,\n\t\t\t\t\tstartTime: new Date(startTime),\n\t\t\t\t\tlastDelay: retryHistory[retryHistory.length - 1]?.delay,\n\t\t\t\t};\n\n\t\t\t\tif (!shouldRetry || shouldRetry(attempt as RetryCount, mapped, ctx)) {\n\t\t\t\t\tconst delay = retry\n\t\t\t\t\t\t? (calculateDelay(\n\t\t\t\t\t\t\t\tretry.strategy,\n\t\t\t\t\t\t\t\tattempt as RetryCount,\n\t\t\t\t\t\t\t\tmapped,\n\t\t\t\t\t\t\t) as Milliseconds)\n\t\t\t\t\t\t: (0 as Milliseconds);\n\n\t\t\t\t\tretryHistory.push({\n\t\t\t\t\t\tattempt: attempt as RetryCount,\n\t\t\t\t\t\terror: mapped,\n\t\t\t\t\t\tdelay,\n\t\t\t\t\t\ttimestamp: new Date(),\n\t\t\t\t\t});\n\n\t\t\t\t\ttotalRetries = (attempt - 1) as RetryCount;\n\t\t\t\t\thooks?.onRetry?.(attempt as RetryCount, mapped, delay);\n\t\t\t\t\tlogger?.info?.(`Retrying in ${delay}ms (attempt ${attempt + 1})`);\n\n\t\t\t\t\tawait sleep(delay as number, compositeSignal);\n\t\t\t\t\treturn runAttempt(attempt + 1);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthrow mapped;\n\t\t}\n\t};\n\n\ttry {\n\t\tconst data = await runAttempt(1);\n\t\tconst metrics: ExecutionMetrics<E> = {\n\t\t\ttotalAttempts,\n\t\t\ttotalRetries,\n\t\t\ttotalDuration: (Date.now() - startTime) as Milliseconds,\n\t\t\tretryHistory,\n\t\t};\n\t\thooks?.onFinally?.(metrics);\n\t\treturn { type: 'success', ok: true, data, error: null, metrics };\n\t} catch (err) {\n\t\tconst finalError = (lastError ?? (errorHandling.normalizer(err) as E)) as E;\n\t\tconst kind: 'failure' | 'timeout' | 'aborted' =\n\t\t\tfinalError.code === 'TIMEOUT'\n\t\t\t\t? 'timeout'\n\t\t\t\t: finalError.code === 'ABORTED'\n\t\t\t\t\t? 'aborted'\n\t\t\t\t\t: 'failure';\n\n\t\tconst metrics: ExecutionMetrics<E> = {\n\t\t\ttotalAttempts,\n\t\t\ttotalRetries,\n\t\t\ttotalDuration: (Date.now() - startTime) as Milliseconds,\n\t\t\tlastError: finalError,\n\t\t\tretryHistory,\n\t\t};\n\n\t\thooks?.onFinally?.(metrics);\n\t\treturn {\n\t\t\ttype: kind,\n\t\t\tok: false,\n\t\t\tdata: null,\n\t\t\terror: finalError,\n\t\t\tmetrics,\n\t\t};\n\t}\n}\n\nfunction createCompositeSignal(signal?: AbortSignal): AbortSignal {\n\tconst controller = new AbortController();\n\tif (!signal) return controller.signal;\n\tconst abort = () => controller.abort();\n\tif (signal.aborted) {\n\t\tabort();\n\t\treturn controller.signal;\n\t}\n\tsignal.addEventListener('abort', abort, { once: true });\n\treturn controller.signal;\n}\n\nasync function withTimeout<T>(\n\tpromise: Promise<T>,\n\ttimeout: Milliseconds,\n\tsignal?: AbortSignal,\n): Promise<T> {\n\tconst timeoutPromise = sleep(timeout as number, signal).then(() => {\n\t\tthrow new TimeoutError(timeout);\n\t});\n\treturn Promise.race([promise, timeoutPromise]);\n}\n","/**\n * Thin functional facade over a singleton Executor.\n * No business logic lives here; it forwards to `src/core/executor.ts`.\n */\n\nimport type { TypedError } from '../error/typed-error';\nimport type { ExecutionConfig } from '../types/config-types';\nimport { Executor, type ExecutorOptions } from './executor';\n\nlet singleton: Executor<TypedError> | undefined;\n\nexport const getExecutor = <E extends TypedError = TypedError>(\n\toptions?: ExecutorOptions<E>,\n): Executor<E> => {\n\tif (!options) {\n\t\tif (!singleton) singleton = new Executor();\n\t\treturn singleton as unknown as Executor<E>;\n\t}\n\treturn new Executor<E>(options);\n};\n\nexport async function execute<T, E extends TypedError = TypedError>(\n\ttask: (ctx: { signal: AbortSignal }) => Promise<T>,\n\toptions?: Partial<ExecutionConfig<E>>,\n) {\n\treturn getExecutor<E>().execute(task, options);\n}\n\nexport async function executeOrThrow<T, E extends TypedError = TypedError>(\n\ttask: (ctx: { signal: AbortSignal }) => Promise<T>,\n\toptions?: Partial<ExecutionConfig<E>>,\n) {\n\treturn getExecutor<E>().executeOrThrow(task, options);\n}\n\nexport async function executeAll<T, E extends TypedError = TypedError>(\n\ttasks: Array<(ctx: { signal: AbortSignal }) => Promise<T>>,\n\toptions?: Partial<ExecutionConfig<E> & { concurrency?: number }>,\n) {\n\treturn getExecutor<E>().executeAll(tasks, options);\n}\n\nexport async function executeAllOrThrow<T, E extends TypedError = TypedError>(\n\ttasks: Array<(ctx: { signal: AbortSignal }) => Promise<T>>,\n\toptions?: Partial<ExecutionConfig<E> & { concurrency?: number }>,\n) {\n\treturn getExecutor<E>().executeAllOrThrow(tasks, options);\n}\n"]}
|