@noego/trust 0.5.1-dev.4 → 0.5.1-dev.5

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.d.ts CHANGED
@@ -9,6 +9,7 @@
9
9
  * Result.ok / Result.err — make a result
10
10
  * Trust.try / Trust.tryAsync — the only boundary that may catch a throw
11
11
  * Trust.decide / Trust.translate — the only places a failure may stop or change
12
+ * Trust.retry — kind-selective retry preserving failure context
12
13
  * Trust.using / Trust.usingAsync — acquire, use and always release a Result resource
13
14
  *
14
15
  * The underlying functions are exported as well because the `@noego/trust/eslint`
@@ -186,7 +187,126 @@ type MatchCheck<H> = [Extract<H[keyof H], {
186
187
  readonly __trust: 'match cannot mix stated and bare returns';
187
188
  }];
188
189
  declare function match<R extends Result<unknown, unknown>, H extends MatchBase<R, H>>(result: R & MatchGuard<R>, handlers: MatchFns<R, H>, ...check: MatchCheck<H>): Matched<H>;
190
+ type RetryDelay = number | false | null | undefined;
191
+ type HasWideKind<E> = E extends {
192
+ readonly kind: infer K extends string;
193
+ } ? string extends K ? true : never : never;
194
+ type MatchingFailure<E, K> = E extends {
195
+ readonly kind: infer EK extends string;
196
+ } ? EK extends K ? E : K extends EK ? E & {
197
+ readonly kind: K;
198
+ } : [EK & K] extends [never] ? never : E & {
199
+ readonly kind: EK & K;
200
+ } : never;
201
+ type RetryGuard<R> = [RawErrorOf<R>] extends [never] ? {
202
+ readonly __trust: 'retry needs a result that can fail (it has no Err member)';
203
+ } : [RawErrorOf<R>] extends [{
204
+ readonly kind: string;
205
+ }] ? [HasWideKind<RawErrorOf<R>>] extends [never] ? StateGuard<R> : {
206
+ readonly __trust: 'every failure needs a literal string `kind` (`kind: string` is too wide)';
207
+ } : {
208
+ readonly __trust: 'every failure needs a string `kind` (string and Error are not failures)';
209
+ };
210
+ type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
211
+ type ToDigits<S extends string, Acc extends Digit[] = []> = S extends `${infer C}${infer Rest}` ? C extends Digit ? ToDigits<Rest, [...Acc, C]> : never : Acc;
212
+ type MaxSafeDigits = ['9', '0', '0', '7', '1', '9', '9', '2', '5', '4', '7', '4', '0', '9', '9', '1'];
213
+ type DigitsLeq<A extends Digit[], B extends Digit[]> = A extends [infer AH extends Digit, ...infer AT extends Digit[]] ? B extends [infer BH extends Digit, ...infer BT extends Digit[]] ? AH extends BH ? DigitsLeq<AT, BT> : '0123456789' extends `${string}${AH}${string}${BH}${string}` ? true : false : false : true;
214
+ type IsValidRetryTimesMember<N extends number> = 0 extends N ? false : [ToDigits<`${N}`>] extends [never] ? false : ToDigits<`${N}`> extends infer DS extends Digit[] ? DS['length'] extends 0 ? false : '0123456789abcdef' extends `${string}${DS['length'] extends 10 ? 'a' : DS['length'] extends 11 ? 'b' : DS['length'] extends 12 ? 'c' : DS['length'] extends 13 ? 'd' : DS['length'] extends 14 ? 'e' : DS['length'] extends 15 ? 'f' : DS['length']}${string}` ? true : DS['length'] extends 16 ? DigitsLeq<DS, MaxSafeDigits> : false : false;
215
+ type CheckRetryTimesMember<N extends number> = N extends unknown ? IsValidRetryTimesMember<N> : never;
216
+ type RetryTimes<N extends number> = number extends N ? number : [Extract<CheckRetryTimesMember<N>, false>] extends [never] ? number : {
217
+ readonly __trust: 'retry `times` must be a safe integer >= 1';
218
+ };
219
+ declare const hostAbortSignalBrand: unique symbol;
220
+ type AmbientAbortSignal = typeof globalThis extends {
221
+ readonly AbortSignal: {
222
+ readonly prototype: infer S;
223
+ };
224
+ } ? S : {
225
+ readonly [hostAbortSignalBrand]: true;
226
+ readonly aborted: boolean;
227
+ readonly reason: unknown;
228
+ throwIfAborted(): void;
229
+ addEventListener(type: 'abort', listener: () => void, options?: boolean | {
230
+ readonly once?: boolean;
231
+ }): void;
232
+ removeEventListener(type: 'abort', listener: () => void, options?: boolean | {
233
+ readonly capture?: boolean;
234
+ }): void;
235
+ };
236
+ type RetryShape<H, N extends number> = {
237
+ readonly times: N & RetryTimes<N>;
238
+ readonly on: {
239
+ readonly [K in keyof H]-?: (...args: never[]) => H[K];
240
+ };
241
+ readonly signal?: AmbientAbortSignal;
242
+ readonly timeoutMs?: number;
243
+ };
244
+ type HandlerKeyToKind<K> = K extends string ? K : K extends number ? `${K}` : never;
245
+ type RetryContext<E, H> = {
246
+ readonly on: ([HasWideKind<E>] extends [never] ? {
247
+ readonly [K in Exclude<KindsOf<E>, keyof Object>]?: (failure: MatchingFailure<E, K>, attempt: number) => RetryDelay;
248
+ } : unknown) & {
249
+ readonly [K in keyof H]-?: [E] extends [never] ? (failure: never, attempt: number) => RetryDelay : [HasWideKind<E>] extends [never] ? [HandlerKeyToKind<K>] extends [never] ? ((failure: never, attempt: number) => RetryDelay) & {
250
+ readonly __trust: 'retry `on` handler names an unknown failure `kind`';
251
+ } : HandlerKeyToKind<K> extends KindsOf<E> ? (failure: MatchingFailure<E, HandlerKeyToKind<K>>, attempt: number) => RetryDelay : ((failure: never, attempt: number) => RetryDelay) & {
252
+ readonly __trust: 'retry `on` handler names an unknown failure `kind`';
253
+ } : (failure: never, attempt: number) => RetryDelay;
254
+ };
255
+ };
256
+ declare const retryPending: unique symbol;
257
+ type RetryPending = {
258
+ readonly [retryPending]: true;
259
+ };
260
+ type RetryResultOf<T> = Awaited<Exclude<T, RetryPending>>;
261
+ type RetryDeferred<T, H> = [Extract<T, RetryPending>] extends [never] ? RetryContext<ErrorOf<RetryResultOf<T>>, H> & RetryGuard<RetryResultOf<T>> : unknown;
262
+ /**
263
+ * Retries a `Result`-returning operation up to `options.times` total attempts,
264
+ * sleeping only for failure `kind`s explicitly listed in `options.on` and returning
265
+ * the exact `Result` of the last attempt untouched when stopping.
266
+ *
267
+ * Cancellation (`options.signal`) and per-attempt `options.timeoutMs` are cooperative:
268
+ * they abort the `signal` passed to `fn`, and `retry` still awaits `fn`'s returned
269
+ * `Result` (or rejection) before inspecting the outcome or starting another attempt.
270
+ * If `fn` ignores an aborted `signal` and never settles, `retry` will remain pending.
271
+ */
272
+ declare function retry<T extends Result<unknown, unknown> | PromiseLike<Result<unknown, unknown>> | RetryPending, H extends Record<keyof H, RetryDelay>, N extends number = number>(fn: (attempt: number, signal: AmbientAbortSignal) => T, options: RetryShape<H, N> & RetryDeferred<T, H>): Promise<RetryResultOf<T>>;
273
+ interface AllOptions {
274
+ readonly signal?: AmbientAbortSignal | undefined;
275
+ }
276
+ interface MapOptions {
277
+ readonly concurrency: number;
278
+ readonly signal?: AmbientAbortSignal | undefined;
279
+ }
189
280
  type MaybePromise<T> = T | PromiseLike<T>;
281
+ type ResultTask = MaybePromise<Result<unknown, unknown>>;
282
+ type AllList = readonly ResultTask[] | [];
283
+ type PositionalValues<T extends readonly unknown[]> = {
284
+ -readonly [K in keyof T]: OkOf<Awaited<T[K]>>;
285
+ };
286
+ type AllValues<T extends readonly unknown[]> = number extends T['length'] ? Exclude<keyof T, keyof any[] | `${number}`> extends never ? PositionalValues<T> : OkOf<Awaited<T[number]>>[] : PositionalValues<[...T]>;
287
+ type AllErrors<T extends readonly unknown[]> = RawErrorOf<Awaited<T[number]>>;
288
+ type AllResult<T extends readonly unknown[]> = [AllErrors<T>] extends [never] ? Ok<AllValues<T>> : Result<AllValues<T>, AllErrors<T>>;
289
+ type HasStatedMember<R> = 0 extends (1 & R) ? false : [StatedMembersOf<R>] extends [never] ? false : true;
290
+ type AllCheck<T extends readonly unknown[]> = HasStatedMember<Awaited<T[number]>> extends true ? [problem: {
291
+ readonly __trust: 'Trust.all cannot unwrap stated results; match states first';
292
+ }] : [];
293
+ type MappedResult<R> = [RawErrorOf<R>] extends [never] ? Ok<OkOf<R>[]> : Result<OkOf<R>[], RawErrorOf<R>>;
294
+ type MapCheck<R> = HasStatedMember<R> extends true ? [problem: {
295
+ readonly __trust: 'Trust.map cannot unwrap stated results; match states first';
296
+ }] : [];
297
+ /**
298
+ * Runs a tuple or array of `Result` tasks in parallel and short-circuits on the first `Err`,
299
+ * aborting the internal `AbortSignal` (and chaining an optional parent `options.signal`).
300
+ */
301
+ declare function all<T extends AllList>(tasks: (signal: AmbientAbortSignal) => T, ...check: AllCheck<T>): Promise<AllResult<T>>;
302
+ declare function all<T extends AllList>(tasks: (signal: AmbientAbortSignal) => T, options: AllOptions | undefined, ...check: AllCheck<T>): Promise<AllResult<T>>;
303
+ declare function all<T extends AllList>(tasks: T, ...check: AllCheck<T>): Promise<AllResult<T>>;
304
+ declare function all<T extends AllList>(tasks: T, options: AllOptions | undefined, ...check: AllCheck<T>): Promise<AllResult<T>>;
305
+ /**
306
+ * Maps `items` with at most `options.concurrency` active callbacks at once (`concurrency` must be a finite integer >= 1).
307
+ * On the first `Err`, stops scheduling remaining items, aborts `signal`, and resolves to that `Err`.
308
+ */
309
+ declare function map<T, Out extends ResultTask>(items: Iterable<T>, options: MapOptions, fn: (item: T, signal: AmbientAbortSignal, index: number) => Out, ...check: MapCheck<Awaited<Out>>): Promise<MappedResult<Awaited<Out>>>;
190
310
  type ResourceOf<A> = OkOf<Awaited<A>>;
191
311
  type SyncOf<T> = Exclude<T, PromiseLike<unknown>>;
192
312
  type AsyncOf<T> = Extract<T, PromiseLike<unknown>>;
@@ -238,6 +358,7 @@ declare const Result: {
238
358
  * Apply the discipline:
239
359
  * `Trust.try` / `Trust.tryAsync` are the only boundary that may catch a throw;
240
360
  * `Trust.decide` is the only place a failure may stop; `Trust.translate` the only place it may change kind;
361
+ * `Trust.retry` retries only named failure kinds and preserves the final failure intact.
241
362
  * `Trust.using` / `Trust.usingAsync` acquire, use and always release a Result resource.
242
363
  */
243
364
  declare const Trust: {
@@ -246,8 +367,11 @@ declare const Trust: {
246
367
  readonly decide: typeof decide;
247
368
  readonly translate: typeof translate;
248
369
  readonly match: typeof match;
370
+ readonly retry: typeof retry;
371
+ readonly all: typeof all;
372
+ readonly map: typeof map;
249
373
  readonly using: typeof using;
250
374
  readonly usingAsync: typeof usingAsync;
251
375
  };
252
376
 
253
- export { type Err, type Failure, type Ok, Result, type StatedOk, type StatedResult, Trust, decide, err, match, ok, state, translate, tryResult, tryResultAsync, using, usingAsync };
377
+ export { type AllOptions, type Err, type Failure, type MapOptions, type Ok, Result, type StatedOk, type StatedResult, Trust, all, decide, err, map, match, ok, retry, state, translate, tryResult, tryResultAsync, using, usingAsync };