trybox 0.10.1 → 0.12.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/README.md +20 -15
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +385 -301
- package/dist/index.d.ts +385 -301
- 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 +48 -43
package/dist/index.d.ts
CHANGED
|
@@ -1,338 +1,422 @@
|
|
|
1
|
-
type ResultErrorCode = "ABORTED" | "NETWORK" | "TIMEOUT" | "VALIDATION" | "HTTP" | "CIRCUIT_OPEN" | "UNKNOWN";
|
|
2
1
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* - `code`: A stable identifier you can switch on (e.g. "HTTP", "VALIDATION").
|
|
6
|
-
* - `message`: User-facing or log-friendly message.
|
|
7
|
-
* - `status`: Optional numeric status (commonly HTTP status).
|
|
8
|
-
* - `meta`: Optional payload with extra context (response body, validation fields, etc.).
|
|
9
|
-
* - `cause`: The original thrown value for debugging.
|
|
2
|
+
* Branded types for enhanced type safety and runtime validation
|
|
3
|
+
* These provide compile-time guarantees while maintaining runtime checks
|
|
10
4
|
*/
|
|
11
|
-
type
|
|
12
|
-
|
|
13
|
-
message: string;
|
|
14
|
-
status?: number;
|
|
15
|
-
meta?: Meta;
|
|
16
|
-
cause?: unknown;
|
|
5
|
+
type Milliseconds = number & {
|
|
6
|
+
readonly __brand: 'Milliseconds';
|
|
17
7
|
};
|
|
18
|
-
type
|
|
19
|
-
|
|
20
|
-
type InferErrorFromRules<TRules extends readonly Rule<any>[]> = TRules extends readonly [] ? ResultError : RuleReturn<TRules[number]> | ResultError<"UNKNOWN">;
|
|
21
|
-
type Rule<E extends ResultError = ResultError> = (err: unknown) => E | null;
|
|
22
|
-
|
|
23
|
-
type RetryDelayFn<E> = (attempt: number, err: E) => number;
|
|
24
|
-
type MaybePromise<T> = T | Promise<T>;
|
|
25
|
-
type Jitter = boolean | number | {
|
|
26
|
-
ratio?: number;
|
|
27
|
-
mode?: "full" | "equal";
|
|
28
|
-
rng?: () => number;
|
|
8
|
+
type RetryCount = number & {
|
|
9
|
+
readonly __brand: 'RetryCount';
|
|
29
10
|
};
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
* - "linear": uses the base delay as is in each attempt.
|
|
33
|
-
* - "exponential": multiplies the delay by 2^(attempt-1).
|
|
34
|
-
* - "fibonacci": multiplies by F(attempt) (classic Fibonacci sequence).
|
|
35
|
-
* - function: custom function based on the attempt number.
|
|
36
|
-
*/
|
|
37
|
-
type BackoffStrategy = "linear" | "exponential" | "fibonacci" | ((attempt: number) => number);
|
|
38
|
-
/**
|
|
39
|
-
* Retry options for `run`, `runAll` and `runAllOrThrow`.
|
|
40
|
-
*/
|
|
41
|
-
type RetryOptions<E extends ResultError = ResultError> = {
|
|
42
|
-
/**
|
|
43
|
-
* Number of retries to perform (does not include the initial attempt).
|
|
44
|
-
* @default 0
|
|
45
|
-
*/
|
|
46
|
-
retries?: number;
|
|
47
|
-
/**
|
|
48
|
-
* Delay between attempts:
|
|
49
|
-
* - number: fixed delay (ms)
|
|
50
|
-
* - () => number: lazy delay (evaluated per attempt)
|
|
51
|
-
* - (attempt, err) => number: delay based on attempt and last error
|
|
52
|
-
* @default 0 or a default baseDelay if retries are present
|
|
53
|
-
*/
|
|
54
|
-
retryDelay?: number | (() => number) | RetryDelayFn<E>;
|
|
55
|
-
/**
|
|
56
|
-
* Decides whether to retry given a specific error.
|
|
57
|
-
* Can be synchronous or asynchronous.
|
|
58
|
-
* Receives the next attempt number and a context with accumulated metrics.
|
|
59
|
-
* @default () => true
|
|
60
|
-
*/
|
|
61
|
-
shouldRetry?: (attempt: number, error: E, context: RetryContext) => boolean | Promise<boolean>;
|
|
62
|
-
/**
|
|
63
|
-
* Random jitter to avoid thundering herd:
|
|
64
|
-
* - true: default ratio 0.5
|
|
65
|
-
* - false: no jitter
|
|
66
|
-
* - number: ratio 0..1
|
|
67
|
-
* - object: full control (ratio, mode, rng)
|
|
68
|
-
* @default 0.5
|
|
69
|
-
*/
|
|
70
|
-
jitter?: Jitter;
|
|
71
|
-
/**
|
|
72
|
-
* Backoff strategy to apply on the calculated delay.
|
|
73
|
-
* @default "linear"
|
|
74
|
-
*/
|
|
75
|
-
backoffStrategy?: BackoffStrategy;
|
|
76
|
-
/**
|
|
77
|
-
* Upper limit of the delay after backoff and before jitter.
|
|
78
|
-
* @default undefined (no limit)
|
|
79
|
-
*/
|
|
80
|
-
maxDelay?: number;
|
|
11
|
+
type ConcurrencyLimit = number & {
|
|
12
|
+
readonly __brand: 'ConcurrencyLimit';
|
|
81
13
|
};
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
*/
|
|
85
|
-
type RetryContext = {
|
|
86
|
-
/** Total attempts (including the next retry). */
|
|
87
|
-
totalAttempts: number;
|
|
88
|
-
/** Elapsed time in ms since the start of `run`. */
|
|
89
|
-
elapsedTime: number;
|
|
90
|
-
/** Timestamp (ms) when the execution started. */
|
|
91
|
-
startTime: number;
|
|
92
|
-
/** The delay (ms) applied before the last attempt, if any. */
|
|
93
|
-
lastDelay?: number;
|
|
14
|
+
type Percentage = number & {
|
|
15
|
+
readonly __brand: 'Percentage';
|
|
94
16
|
};
|
|
17
|
+
type StatusCode = number & {
|
|
18
|
+
readonly __brand: 'StatusCode';
|
|
19
|
+
};
|
|
20
|
+
declare const asMilliseconds: (n: number) => Milliseconds;
|
|
21
|
+
declare const asRetryCount: (n: number) => RetryCount;
|
|
22
|
+
declare const asConcurrencyLimit: (n: number) => ConcurrencyLimit;
|
|
23
|
+
declare const asPercentage: (n: number) => Percentage;
|
|
24
|
+
declare const asStatusCode: (n: number) => StatusCode;
|
|
25
|
+
|
|
95
26
|
/**
|
|
96
|
-
*
|
|
27
|
+
* Modern typed error hierarchy with enhanced capabilities
|
|
28
|
+
* Provides type-safe error handling with fluent API and metadata support
|
|
97
29
|
*/
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
*/
|
|
116
|
-
onSuccess?: (data: T) => void;
|
|
117
|
-
/**
|
|
118
|
-
* Callback that always executes at the end (success or error).
|
|
119
|
-
*/
|
|
120
|
-
onFinally?: () => void;
|
|
121
|
-
/**
|
|
122
|
-
* If true, aborts (ABORTED) are not considered fatal errors:
|
|
123
|
-
* `onError` is not called and `{ ok: false, error }` is returned.
|
|
124
|
-
* @default true
|
|
125
|
-
*/
|
|
126
|
-
ignoreAbort?: boolean;
|
|
127
|
-
/**
|
|
128
|
-
* Signal for native work cancellation.
|
|
129
|
-
* If aborted, it cuts with `AbortError`.
|
|
130
|
-
*/
|
|
131
|
-
signal?: AbortSignal;
|
|
132
|
-
/**
|
|
133
|
-
* Maximum timeout in ms for the work; expires with `TimeoutError`.
|
|
134
|
-
*/
|
|
135
|
-
timeout?: number;
|
|
136
|
-
/**
|
|
137
|
-
* Retry observability: receives attempt, error, and next delay.
|
|
138
|
-
*/
|
|
139
|
-
onRetry?: (attempt: number, error: E, nextDelay: number) => void;
|
|
140
|
-
/**
|
|
141
|
-
* Optional structured logger for debug and errors.
|
|
142
|
-
*/
|
|
143
|
-
logger?: {
|
|
144
|
-
debug?: (msg: string, meta?: unknown) => void;
|
|
145
|
-
error?: (msg: string, error: E) => void;
|
|
30
|
+
|
|
31
|
+
declare abstract class TypedError<Code extends string = string, Meta = unknown> extends Error {
|
|
32
|
+
abstract readonly code: Code;
|
|
33
|
+
readonly cause?: unknown;
|
|
34
|
+
readonly meta?: Meta;
|
|
35
|
+
readonly status?: number;
|
|
36
|
+
readonly timestamp: Date;
|
|
37
|
+
constructor(message: string, opts?: {
|
|
38
|
+
cause?: unknown;
|
|
39
|
+
meta?: Meta;
|
|
40
|
+
status?: number;
|
|
41
|
+
});
|
|
42
|
+
is<C extends string>(code: C): this is TypedError<C> & {
|
|
43
|
+
code: C;
|
|
44
|
+
};
|
|
45
|
+
withMeta<const M>(meta: M): this & {
|
|
46
|
+
meta: M;
|
|
146
47
|
};
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
48
|
+
withStatus(status: number): this & {
|
|
49
|
+
status: number;
|
|
50
|
+
};
|
|
51
|
+
withCause(cause: unknown): this & {
|
|
52
|
+
cause: unknown;
|
|
53
|
+
};
|
|
54
|
+
toJSON(): Record<string, unknown>;
|
|
55
|
+
}
|
|
56
|
+
declare class TimeoutError extends TypedError<'TIMEOUT'> {
|
|
57
|
+
readonly code: "TIMEOUT";
|
|
58
|
+
constructor(timeout: Milliseconds, cause?: unknown);
|
|
59
|
+
}
|
|
60
|
+
declare class AbortedError extends TypedError<'ABORTED'> {
|
|
61
|
+
readonly code: "ABORTED";
|
|
62
|
+
constructor(reason?: string, cause?: unknown);
|
|
63
|
+
}
|
|
64
|
+
declare class CircuitOpenError extends TypedError<'CIRCUIT_OPEN'> {
|
|
65
|
+
readonly code: "CIRCUIT_OPEN";
|
|
66
|
+
constructor(resetAfter: Milliseconds, cause?: unknown);
|
|
67
|
+
}
|
|
68
|
+
type ValidationMeta = {
|
|
69
|
+
validationErrors: unknown[];
|
|
151
70
|
};
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
71
|
+
declare class ValidationError extends TypedError<'VALIDATION', ValidationMeta> {
|
|
72
|
+
readonly validationErrors: unknown[];
|
|
73
|
+
readonly code: "VALIDATION";
|
|
74
|
+
constructor(message: string, validationErrors: unknown[], cause?: unknown);
|
|
75
|
+
}
|
|
76
|
+
declare class NetworkError extends TypedError<'NETWORK'> {
|
|
77
|
+
readonly statusCode?: number | undefined;
|
|
78
|
+
readonly code: "NETWORK";
|
|
79
|
+
constructor(message: string, statusCode?: number | undefined, cause?: unknown);
|
|
80
|
+
}
|
|
81
|
+
type HttpMeta = {
|
|
82
|
+
response?: unknown;
|
|
162
83
|
};
|
|
84
|
+
declare class HttpError extends TypedError<'HTTP', HttpMeta> {
|
|
85
|
+
readonly status: number;
|
|
86
|
+
readonly response?: unknown | undefined;
|
|
87
|
+
readonly code: "HTTP";
|
|
88
|
+
constructor(message: string, status: number, response?: unknown | undefined, cause?: unknown);
|
|
89
|
+
}
|
|
90
|
+
declare class UnknownError extends TypedError<'UNKNOWN'> {
|
|
91
|
+
readonly code: "UNKNOWN";
|
|
92
|
+
constructor(message: string, cause?: unknown);
|
|
93
|
+
}
|
|
94
|
+
|
|
163
95
|
/**
|
|
164
|
-
*
|
|
96
|
+
* Modern error normalization system
|
|
97
|
+
* Provides type-safe error transformation and normalization
|
|
165
98
|
*/
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
totalDuration: number;
|
|
170
|
-
lastError?: E;
|
|
171
|
-
};
|
|
172
|
-
type RunResult<T, E extends ResultError = ResultError> = {
|
|
173
|
-
ok: true;
|
|
174
|
-
data: T;
|
|
175
|
-
error: null;
|
|
176
|
-
metrics?: Metrics<E>;
|
|
177
|
-
} | {
|
|
178
|
-
ok: false;
|
|
179
|
-
data: null;
|
|
180
|
-
error: E;
|
|
181
|
-
metrics?: Metrics<E>;
|
|
182
|
-
};
|
|
99
|
+
|
|
100
|
+
type ErrorNormalizer<E extends TypedError = TypedError> = (error: unknown) => E;
|
|
101
|
+
type ErrorRule<E extends TypedError = TypedError> = (error: unknown) => E | null;
|
|
183
102
|
|
|
184
103
|
/**
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
* Errors are normalized into an `ResultError` (or a custom error type `E`)
|
|
188
|
-
* using the provided `toError` function.
|
|
189
|
-
*
|
|
190
|
-
* This utility is framework-agnostic and works in browsers, Node.js,
|
|
191
|
-
* React effects, and any async context.
|
|
104
|
+
* Modern result types with enhanced discriminated unions
|
|
105
|
+
* Provides better type safety and more granular result categorization
|
|
192
106
|
*/
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
107
|
+
|
|
108
|
+
type ExecutionResult<T, E extends TypedError = TypedError> = SuccessResult<T, E> | FailureResult<E> | AbortedResult<E> | TimeoutResult<E>;
|
|
109
|
+
interface SuccessResult<T, E extends TypedError> {
|
|
110
|
+
readonly type: 'success';
|
|
111
|
+
readonly ok: true;
|
|
112
|
+
readonly data: T;
|
|
113
|
+
readonly error: null;
|
|
114
|
+
readonly metrics?: ExecutionMetrics$1<E>;
|
|
115
|
+
}
|
|
116
|
+
interface FailureResult<E extends TypedError> {
|
|
117
|
+
readonly type: 'failure';
|
|
118
|
+
readonly ok: false;
|
|
119
|
+
readonly data: null;
|
|
120
|
+
readonly error: E;
|
|
121
|
+
readonly metrics?: ExecutionMetrics$1<E>;
|
|
122
|
+
}
|
|
123
|
+
interface AbortedResult<E extends TypedError> {
|
|
124
|
+
readonly type: 'aborted';
|
|
125
|
+
readonly ok: false;
|
|
126
|
+
readonly data: null;
|
|
127
|
+
readonly error: E;
|
|
128
|
+
readonly metrics?: ExecutionMetrics$1<E>;
|
|
129
|
+
}
|
|
130
|
+
interface TimeoutResult<E extends TypedError> {
|
|
131
|
+
readonly type: 'timeout';
|
|
132
|
+
readonly ok: false;
|
|
133
|
+
readonly data: null;
|
|
134
|
+
readonly error: E;
|
|
135
|
+
readonly metrics?: ExecutionMetrics$1<E>;
|
|
136
|
+
}
|
|
137
|
+
interface ExecutionMetrics$1<E extends TypedError> {
|
|
138
|
+
readonly totalAttempts: RetryCount;
|
|
139
|
+
readonly totalRetries: RetryCount;
|
|
140
|
+
readonly totalDuration: Milliseconds;
|
|
141
|
+
readonly lastError?: E;
|
|
142
|
+
readonly retryHistory: Array<{
|
|
143
|
+
readonly attempt: RetryCount;
|
|
144
|
+
readonly error: E;
|
|
145
|
+
readonly delay: Milliseconds;
|
|
146
|
+
readonly timestamp: Date;
|
|
147
|
+
}>;
|
|
148
|
+
}
|
|
196
149
|
|
|
197
150
|
/**
|
|
198
|
-
*
|
|
199
|
-
*
|
|
200
|
-
* - "error": failed task with `error`
|
|
201
|
-
* - "skipped": task not executed due to cancellation/fail-fast/concurrency
|
|
151
|
+
* Modern circuit breaker implementation with enhanced state management
|
|
152
|
+
* Provides circuit breaker pattern with type safety and observability
|
|
202
153
|
*/
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
error: E;
|
|
213
|
-
}
|
|
214
|
-
status: "skipped";
|
|
215
|
-
ok: false;
|
|
216
|
-
data: null;
|
|
217
|
-
error: null;
|
|
218
|
-
};
|
|
219
|
-
/** Helper to discriminate successful results. */
|
|
220
|
-
type SuccessResult<T> = Extract<RunAllItemResult<T, any>, {
|
|
221
|
-
status: "ok";
|
|
222
|
-
}>;
|
|
223
|
-
/** Helper to discriminate error results. */
|
|
224
|
-
type ErrorResult<E> = Extract<RunAllItemResult<any, E extends ResultError ? E : ResultError>, {
|
|
225
|
-
status: "error";
|
|
226
|
-
}>;
|
|
227
|
-
/** Type guard that detects `status: "ok"` with `data` typing. */
|
|
228
|
-
declare const isSuccess: <T, E extends ResultError = ResultError>(r: RunAllItemResult<T, E>) => r is SuccessResult<T>;
|
|
229
|
-
type RunAllOptions<T, E extends ResultError = ResultError> = RunOptions<T, E> & {
|
|
230
|
-
/**
|
|
231
|
-
* Maximum number of concurrent tasks to run.
|
|
232
|
-
* @default Infinity
|
|
233
|
-
*/
|
|
234
|
-
concurrency?: number;
|
|
235
|
-
/**
|
|
236
|
-
* Execution mode regarding errors.
|
|
237
|
-
* - "settle": Run all tasks (default).
|
|
238
|
-
* - "fail-fast": Stop starting new tasks if one fails.
|
|
239
|
-
* @default "settle"
|
|
240
|
-
*/
|
|
241
|
-
mode?: "settle" | "fail-fast";
|
|
242
|
-
};
|
|
243
|
-
declare function runAll<T, E extends ResultError = ResultError>(tasks: Array<() => MaybePromise<T>>, options?: RunAllOptions<T, E>): Promise<RunAllItemResult<T, E>[]>;
|
|
154
|
+
|
|
155
|
+
interface CircuitBreakerConfig<E extends TypedError = TypedError> {
|
|
156
|
+
/** Number of consecutive failures before opening circuit */
|
|
157
|
+
readonly failureThreshold: number;
|
|
158
|
+
/** How long to wait before attempting to close circuit */
|
|
159
|
+
readonly resetTimeout: number;
|
|
160
|
+
/** Number of requests allowed in half-open state */
|
|
161
|
+
readonly halfOpenRequests: number;
|
|
162
|
+
/** Optional function to determine if error should count as failure */
|
|
163
|
+
readonly shouldCountAsFailure?: (error: E) => boolean;
|
|
164
|
+
}
|
|
244
165
|
|
|
245
166
|
/**
|
|
246
|
-
*
|
|
247
|
-
*
|
|
248
|
-
* - `concurrency`: limit of simultaneous tasks; if one fails, it throws
|
|
167
|
+
* Modern retry strategies with enhanced capabilities
|
|
168
|
+
* Provides various retry patterns with type safety
|
|
249
169
|
*/
|
|
250
|
-
type RunAllOrThrowOptions<T, E extends ResultError = ResultError> = RunOptions<T, E> & {
|
|
251
|
-
/**
|
|
252
|
-
* Maximum number of concurrent tasks to run.
|
|
253
|
-
* @default Infinity
|
|
254
|
-
*/
|
|
255
|
-
concurrency?: number;
|
|
256
|
-
};
|
|
257
|
-
declare function runAllOrThrow<T, E extends ResultError = ResultError>(tasks: Array<() => MaybePromise<T>>, options?: RunAllOrThrowOptions<T, E>): Promise<T[]>;
|
|
258
|
-
|
|
259
|
-
declare function createNormalizer<E extends ResultError>(rules: Rule<E>[], fallback: (err: unknown) => E): (err: unknown) => E;
|
|
260
|
-
declare function defaultFallback(err: unknown): ResultError;
|
|
261
|
-
declare function toResultError(err: unknown): ResultError;
|
|
262
170
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
171
|
+
type RetryStrategy = FixedDelayStrategy | ExponentialBackoffStrategy | FibonacciBackoffStrategy | CustomDelayStrategy;
|
|
172
|
+
interface FixedDelayStrategy {
|
|
173
|
+
readonly type: 'fixed';
|
|
174
|
+
readonly delay: number;
|
|
175
|
+
}
|
|
176
|
+
interface ExponentialBackoffStrategy {
|
|
177
|
+
readonly type: 'exponential';
|
|
178
|
+
readonly base: number;
|
|
179
|
+
readonly factor: number;
|
|
180
|
+
readonly maxDelay?: number;
|
|
181
|
+
}
|
|
182
|
+
interface FibonacciBackoffStrategy {
|
|
183
|
+
readonly type: 'fibonacci';
|
|
184
|
+
readonly base: number;
|
|
185
|
+
readonly maxDelay?: number;
|
|
186
|
+
}
|
|
187
|
+
interface CustomDelayStrategy {
|
|
188
|
+
readonly type: 'custom';
|
|
189
|
+
readonly calculate: (attempt: RetryCount, error: unknown) => number;
|
|
190
|
+
}
|
|
191
|
+
declare const RetryStrategies: {
|
|
192
|
+
readonly fixed: (delay: number) => FixedDelayStrategy;
|
|
193
|
+
readonly exponential: (base: number, factor?: number, maxDelay?: number) => ExponentialBackoffStrategy;
|
|
194
|
+
readonly fibonacci: (base: number, maxDelay?: number) => FibonacciBackoffStrategy;
|
|
195
|
+
readonly custom: (calculate: (attempt: RetryCount, error: unknown) => number) => CustomDelayStrategy;
|
|
273
196
|
};
|
|
274
|
-
declare const defaultRules: readonly [Rule<ResultError<"CIRCUIT_OPEN">>, Rule<ResultError<"ABORTED">>, Rule<ResultError<"TIMEOUT">>, Rule<ResultError<"HTTP">>, Rule<ResultError<"UNKNOWN", {
|
|
275
|
-
errors: unknown[];
|
|
276
|
-
}>>, Rule<ResultError<"UNKNOWN">>, Rule<ResultError<"UNKNOWN">>];
|
|
277
|
-
type DefaultRules = typeof defaultRules;
|
|
278
|
-
type DefaultError = InferErrorFromRules<DefaultRules>;
|
|
279
197
|
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
198
|
+
interface ExecutionConfig<E extends TypedError = TypedError> {
|
|
199
|
+
/** Abort signal passed to tasks */
|
|
200
|
+
readonly signal?: AbortSignal;
|
|
201
|
+
/** If true, aborts are treated as non-throwing failures */
|
|
202
|
+
readonly ignoreAbort?: boolean;
|
|
203
|
+
/** Timeout configuration */
|
|
204
|
+
readonly timeout?: number;
|
|
205
|
+
/** Retry configuration */
|
|
206
|
+
readonly retry?: RetryConfig<E>;
|
|
207
|
+
/** Circuit breaker configuration */
|
|
208
|
+
readonly circuitBreaker?: CircuitBreakerConfig<E>;
|
|
209
|
+
/** Error handling configuration */
|
|
210
|
+
readonly errorHandling: ErrorHandlingConfig<E>;
|
|
211
|
+
/** Concurrency configuration for batch operations */
|
|
212
|
+
readonly concurrency?: number;
|
|
213
|
+
/** Logging configuration */
|
|
214
|
+
readonly logger?: LoggerConfig<E>;
|
|
215
|
+
/** Callback hooks */
|
|
216
|
+
readonly hooks?: HookConfig<E>;
|
|
284
217
|
}
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
218
|
+
interface RetryConfig<E extends TypedError> {
|
|
219
|
+
/** Maximum number of retry attempts */
|
|
220
|
+
readonly maxRetries: number;
|
|
221
|
+
/** Base delay strategy */
|
|
222
|
+
readonly strategy: RetryStrategy;
|
|
223
|
+
/** Jitter configuration to prevent thundering herd */
|
|
224
|
+
readonly jitter?: JitterConfig;
|
|
225
|
+
/** Function to determine if retry should be attempted */
|
|
226
|
+
readonly shouldRetry?: ShouldRetryPredicate<E>;
|
|
227
|
+
}
|
|
228
|
+
type ShouldRetryPredicate<E extends TypedError> = (attempt: number, error: E, context: RetryContext) => boolean;
|
|
229
|
+
interface RetryContext {
|
|
230
|
+
/** Total attempts made so far */
|
|
231
|
+
readonly totalAttempts: number;
|
|
232
|
+
/** Elapsed time since start */
|
|
233
|
+
readonly elapsedTime: number;
|
|
234
|
+
/** Start timestamp */
|
|
235
|
+
readonly startTime: Date;
|
|
236
|
+
/** Last delay applied */
|
|
237
|
+
readonly lastDelay?: number;
|
|
238
|
+
}
|
|
239
|
+
interface ErrorHandlingConfig<E extends TypedError> {
|
|
240
|
+
/** Error normalizer function */
|
|
241
|
+
readonly normalizer: ErrorNormalizer<E>;
|
|
242
|
+
/** Optional error mapping/transformation */
|
|
243
|
+
readonly mapError?: (error: E) => E;
|
|
244
|
+
}
|
|
245
|
+
interface LoggerConfig<E extends TypedError> {
|
|
246
|
+
/** Debug logging function */
|
|
247
|
+
readonly debug?: (message: string, meta?: unknown) => void;
|
|
248
|
+
/** Error logging function */
|
|
249
|
+
readonly error?: (message: string, error: E) => void;
|
|
250
|
+
/** Info logging function */
|
|
251
|
+
readonly info?: (message: string, meta?: unknown) => void;
|
|
252
|
+
/** Warning logging function */
|
|
253
|
+
readonly warn?: (message: string, meta?: unknown) => void;
|
|
254
|
+
}
|
|
255
|
+
interface HookConfig<E extends TypedError> {
|
|
256
|
+
/** Called on successful execution */
|
|
257
|
+
readonly onSuccess?: <T>(data: T, metrics?: ExecutionMetrics<E>) => void;
|
|
258
|
+
/** Called on failed execution */
|
|
259
|
+
readonly onError?: (error: E, metrics?: ExecutionMetrics<E>) => void;
|
|
260
|
+
/** Called always, success or failure */
|
|
261
|
+
readonly onFinally?: (metrics?: ExecutionMetrics<E>) => void;
|
|
262
|
+
/** Called on abort */
|
|
263
|
+
readonly onAbort?: (signal: AbortSignal) => void;
|
|
264
|
+
/** Called before retry attempt */
|
|
265
|
+
readonly onRetry?: (attempt: number, error: E, delay: number) => void;
|
|
266
|
+
/** Called when circuit breaker state changes */
|
|
267
|
+
readonly onCircuitStateChange?: (from: CircuitState, to: CircuitState) => void;
|
|
268
|
+
}
|
|
269
|
+
type CircuitState = 'closed' | 'open' | 'half-open';
|
|
270
|
+
type ExecutionMetrics<E extends TypedError> = ExecutionMetrics$1<E>;
|
|
271
|
+
type JitterConfig = {
|
|
272
|
+
type: 'none';
|
|
273
|
+
} | {
|
|
274
|
+
type: 'full';
|
|
275
|
+
ratio: number;
|
|
276
|
+
} | {
|
|
277
|
+
type: 'equal';
|
|
278
|
+
ratio: number;
|
|
279
|
+
} | {
|
|
280
|
+
type: 'custom';
|
|
281
|
+
calculate: (delay: number) => number;
|
|
282
|
+
};
|
|
283
|
+
declare const JitterConfig: {
|
|
284
|
+
readonly none: () => JitterConfig;
|
|
285
|
+
readonly full: (ratio?: number) => JitterConfig;
|
|
286
|
+
readonly equal: (ratio?: number) => JitterConfig;
|
|
287
|
+
readonly custom: (calculate: (delay: number) => number) => JitterConfig;
|
|
288
288
|
};
|
|
289
289
|
|
|
290
|
-
type RulesMode =
|
|
291
|
-
type
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
rules?:
|
|
297
|
-
/**
|
|
298
|
-
* How to treat provided rules in relation to default rules.
|
|
299
|
-
* - "extend": Use default rules after custom rules (default).
|
|
300
|
-
* - "replace": Use only custom rules (and fallback).
|
|
301
|
-
*/
|
|
290
|
+
type RulesMode = 'extend' | 'replace';
|
|
291
|
+
type DefaultError = AbortedError | TimeoutError | NetworkError | HttpError | CircuitOpenError | ValidationError | UnknownError;
|
|
292
|
+
type NonNull<T> = T extends null ? never : T;
|
|
293
|
+
type RuleReturn<R> = R extends (err: unknown) => infer Out ? NonNull<Out> : never;
|
|
294
|
+
type InferErrorFromRules<TRules extends readonly ErrorRule<TypedError>[]> = TRules extends readonly [] ? TypedError : RuleReturn<TRules[number]> | UnknownError;
|
|
295
|
+
type ExecutorOptions<E extends TypedError = TypedError> = Omit<Partial<ExecutionConfig<E>>, 'errorHandling'> & {
|
|
296
|
+
rules?: Array<ErrorRule<E>>;
|
|
302
297
|
rulesMode?: RulesMode;
|
|
303
|
-
/**
|
|
304
|
-
* Custom fallback function to use for normalizing errors.
|
|
305
|
-
* If not provided, the default fallback is used.
|
|
306
|
-
*/
|
|
307
298
|
fallback?: (err: unknown) => E;
|
|
308
|
-
/**
|
|
309
|
-
* If you want a completely custom normalizer, you can provide it directly.
|
|
310
|
-
* If set, `matchers` and `fallback` are ignored.
|
|
311
|
-
*/
|
|
312
299
|
toError?: (err: unknown) => E;
|
|
313
|
-
/** Default for run options */
|
|
314
|
-
ignoreAbort?: boolean;
|
|
315
|
-
/** Optional default mapper for all runs */
|
|
316
300
|
mapError?: (error: E) => E;
|
|
317
|
-
/**
|
|
318
|
-
* Circuit breaker configuration (applies to all executions of the Runner).
|
|
319
|
-
*/
|
|
320
|
-
circuitBreaker?: CircuitBreakerOptions;
|
|
321
301
|
};
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Modern fluent error rule builder
|
|
305
|
+
* Provides type-safe error rule creation with enhanced ergonomics
|
|
306
|
+
*/
|
|
307
|
+
|
|
308
|
+
declare class ErrorRuleBuilder<T> {
|
|
309
|
+
private readonly predicate;
|
|
310
|
+
constructor(predicate: (err: unknown) => err is T);
|
|
311
|
+
toCode<const C extends string>(code: C): ErrorMapper<T, C>;
|
|
312
|
+
toError<const Out extends {
|
|
313
|
+
code: string;
|
|
314
|
+
message: string;
|
|
315
|
+
meta?: unknown;
|
|
316
|
+
status?: number;
|
|
317
|
+
cause?: unknown;
|
|
318
|
+
}>(mapper: (err: T) => Out): ErrorRule<TypedError<Out['code'], Out['meta']>>;
|
|
319
|
+
}
|
|
320
|
+
declare class ErrorMapper<T, C extends string> {
|
|
321
|
+
private readonly predicate;
|
|
322
|
+
private readonly errorCode;
|
|
323
|
+
constructor(predicate: (err: unknown) => err is T, errorCode: C);
|
|
324
|
+
with<const M = unknown>(mapper: (err: T) => {
|
|
325
|
+
message: string;
|
|
326
|
+
cause?: unknown;
|
|
327
|
+
meta?: M;
|
|
328
|
+
status?: number;
|
|
329
|
+
}): (err: unknown) => TypedError<C, M> | null;
|
|
326
330
|
}
|
|
327
331
|
|
|
328
|
-
declare
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
332
|
+
declare const errorRule: {
|
|
333
|
+
readonly when: <T>(predicate: (err: unknown) => err is T) => ErrorRuleBuilder<T>;
|
|
334
|
+
readonly instance: <T extends new (...args: unknown[]) => unknown>(ErrorClass: T) => ErrorRuleBuilder<InstanceType<T>>;
|
|
335
|
+
};
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Public API: legacy runner-first.
|
|
339
|
+
*
|
|
340
|
+
* Default export is a factory that creates an internal Executor instance.
|
|
341
|
+
* The Executor class and the old functional facade are intentionally not
|
|
342
|
+
* exported from the package surface.
|
|
343
|
+
*/
|
|
344
|
+
|
|
345
|
+
type Runner<E extends TypedError = TypedError> = {
|
|
346
|
+
run: <T>(task: (ctx: {
|
|
347
|
+
signal: AbortSignal;
|
|
348
|
+
}) => Promise<T>, options?: Partial<ExecutionConfig<E>>) => Promise<ExecutionResult<T, E>>;
|
|
349
|
+
execute: <T>(task: (ctx: {
|
|
350
|
+
signal: AbortSignal;
|
|
351
|
+
}) => Promise<T>, options?: Partial<ExecutionConfig<E>>) => Promise<ExecutionResult<T, E>>;
|
|
352
|
+
runOrThrow: <T>(task: (ctx: {
|
|
353
|
+
signal: AbortSignal;
|
|
354
|
+
}) => Promise<T>, options?: Partial<ExecutionConfig<E>>) => Promise<T>;
|
|
355
|
+
executeOrThrow: <T>(task: (ctx: {
|
|
356
|
+
signal: AbortSignal;
|
|
357
|
+
}) => Promise<T>, options?: Partial<ExecutionConfig<E>>) => Promise<T>;
|
|
358
|
+
runAll: <T>(tasks: Array<(ctx: {
|
|
359
|
+
signal: AbortSignal;
|
|
360
|
+
}) => Promise<T>>, options?: Partial<ExecutionConfig<E> & {
|
|
361
|
+
concurrency?: number;
|
|
362
|
+
}>) => Promise<Array<ExecutionResult<T, E>>>;
|
|
363
|
+
executeAll: <T>(tasks: Array<(ctx: {
|
|
364
|
+
signal: AbortSignal;
|
|
365
|
+
}) => Promise<T>>, options?: Partial<ExecutionConfig<E> & {
|
|
366
|
+
concurrency?: number;
|
|
367
|
+
}>) => Promise<Array<ExecutionResult<T, E>>>;
|
|
368
|
+
runOrThrowAll: <T>(tasks: Array<(ctx: {
|
|
369
|
+
signal: AbortSignal;
|
|
370
|
+
}) => Promise<T>>, options?: Partial<ExecutionConfig<E> & {
|
|
371
|
+
concurrency?: number;
|
|
372
|
+
}>) => Promise<T[]>;
|
|
373
|
+
executeOrThrowAll: <T>(tasks: Array<(ctx: {
|
|
374
|
+
signal: AbortSignal;
|
|
375
|
+
}) => Promise<T>>, options?: Partial<ExecutionConfig<E> & {
|
|
376
|
+
concurrency?: number;
|
|
377
|
+
}>) => Promise<T[]>;
|
|
378
|
+
};
|
|
379
|
+
declare function trybox<const TRules extends readonly ErrorRule<TypedError>[]>(options: Omit<ExecutorOptions<InferErrorFromRules<TRules>>, 'rules'> & {
|
|
334
380
|
rules: TRules;
|
|
335
|
-
|
|
336
|
-
|
|
381
|
+
}): Runner<InferErrorFromRules<TRules>>;
|
|
382
|
+
declare function trybox<E extends TypedError = DefaultError>(options?: ExecutorOptions<E>): Runner<E>;
|
|
383
|
+
|
|
384
|
+
declare const execute: <T, E extends TypedError = DefaultError>(task: (ctx: {
|
|
385
|
+
signal: AbortSignal;
|
|
386
|
+
}) => Promise<T>, options?: Partial<ExecutionConfig<E>>) => Promise<ExecutionResult<T, TypedError<string, unknown>>>;
|
|
387
|
+
declare const executeOrThrow: <T, E extends TypedError = DefaultError>(task: (ctx: {
|
|
388
|
+
signal: AbortSignal;
|
|
389
|
+
}) => Promise<T>, options?: Partial<ExecutionConfig<E>>) => Promise<T>;
|
|
390
|
+
declare const executeAll: <T, E extends TypedError = DefaultError>(tasks: Array<(ctx: {
|
|
391
|
+
signal: AbortSignal;
|
|
392
|
+
}) => Promise<T>>, options?: Partial<ExecutionConfig<E> & {
|
|
393
|
+
concurrency?: number;
|
|
394
|
+
}>) => Promise<ExecutionResult<T, TypedError<string, unknown>>[]>;
|
|
395
|
+
declare const executeAllOrThrow: <T, E extends TypedError = DefaultError>(tasks: Array<(ctx: {
|
|
396
|
+
signal: AbortSignal;
|
|
397
|
+
}) => Promise<T>>, options?: Partial<ExecutionConfig<E> & {
|
|
398
|
+
concurrency?: number;
|
|
399
|
+
}>) => Promise<T[]>;
|
|
400
|
+
declare const executeOrThrowAll: <T, E extends TypedError = DefaultError>(tasks: Array<(ctx: {
|
|
401
|
+
signal: AbortSignal;
|
|
402
|
+
}) => Promise<T>>, options?: Partial<ExecutionConfig<E> & {
|
|
403
|
+
concurrency?: number;
|
|
404
|
+
}>) => Promise<T[]>;
|
|
405
|
+
declare const run: <T, E extends TypedError = DefaultError>(task: (ctx: {
|
|
406
|
+
signal: AbortSignal;
|
|
407
|
+
}) => Promise<T>, options?: Partial<ExecutionConfig<E>>) => Promise<ExecutionResult<T, TypedError<string, unknown>>>;
|
|
408
|
+
declare const runOrThrow: <T, E extends TypedError = DefaultError>(task: (ctx: {
|
|
409
|
+
signal: AbortSignal;
|
|
410
|
+
}) => Promise<T>, options?: Partial<ExecutionConfig<E>>) => Promise<T>;
|
|
411
|
+
declare const runAll: <T, E extends TypedError = DefaultError>(tasks: Array<(ctx: {
|
|
412
|
+
signal: AbortSignal;
|
|
413
|
+
}) => Promise<T>>, options?: Partial<ExecutionConfig<E> & {
|
|
414
|
+
concurrency?: number;
|
|
415
|
+
}>) => Promise<ExecutionResult<T, TypedError<string, unknown>>[]>;
|
|
416
|
+
declare const runOrThrowAll: <T, E extends TypedError = DefaultError>(tasks: Array<(ctx: {
|
|
417
|
+
signal: AbortSignal;
|
|
418
|
+
}) => Promise<T>>, options?: Partial<ExecutionConfig<E> & {
|
|
419
|
+
concurrency?: number;
|
|
420
|
+
}>) => Promise<T[]>;
|
|
337
421
|
|
|
338
|
-
export { type
|
|
422
|
+
export { type AbortedResult, type ConcurrencyLimit, type ExecutionConfig, type ExecutionMetrics$1 as ExecutionMetrics, type ExecutionResult, type ExecutorOptions, type FailureResult, type Milliseconds, type Percentage, type RetryCount, RetryStrategies, type RulesMode, type Runner, type StatusCode, type SuccessResult, type TimeoutResult, asConcurrencyLimit, asMilliseconds, asPercentage, asRetryCount, asStatusCode, trybox as default, errorRule, execute, executeAll, executeAllOrThrow, executeOrThrow, executeOrThrowAll, run, runAll, runOrThrow, runOrThrowAll, trybox };
|