@zap-studio/retry 0.2.0 → 0.3.1

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.
Files changed (42) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +23 -12
  3. package/dist/abort.d.mts +29 -0
  4. package/dist/abort.d.mts.map +1 -0
  5. package/dist/abort.mjs +61 -0
  6. package/dist/abort.mjs.map +1 -0
  7. package/dist/errors-BVZjP1Q5.d.mts +76 -0
  8. package/dist/errors-BVZjP1Q5.d.mts.map +1 -0
  9. package/dist/errors.d.mts +2 -0
  10. package/dist/{error.mjs → errors.mjs} +21 -3
  11. package/dist/errors.mjs.map +1 -0
  12. package/dist/exponential-backoff.d.mts +33 -16
  13. package/dist/exponential-backoff.d.mts.map +1 -1
  14. package/dist/exponential-backoff.mjs +13 -4
  15. package/dist/exponential-backoff.mjs.map +1 -1
  16. package/dist/fixed-delay.d.mts +26 -15
  17. package/dist/fixed-delay.d.mts.map +1 -1
  18. package/dist/fixed-delay.mjs +10 -4
  19. package/dist/fixed-delay.mjs.map +1 -1
  20. package/dist/index.d.mts +40 -70
  21. package/dist/index.d.mts.map +1 -1
  22. package/dist/index.mjs +14 -177
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/result-mode.d.mts +19 -0
  25. package/dist/result-mode.d.mts.map +1 -0
  26. package/dist/result-mode.mjs +145 -0
  27. package/dist/result-mode.mjs.map +1 -0
  28. package/dist/sleep.d.mts +17 -0
  29. package/dist/sleep.d.mts.map +1 -0
  30. package/dist/sleep.mjs +23 -0
  31. package/dist/sleep.mjs.map +1 -0
  32. package/dist/throw-mode.d.mts +21 -0
  33. package/dist/throw-mode.d.mts.map +1 -0
  34. package/dist/throw-mode.mjs +49 -0
  35. package/dist/throw-mode.mjs.map +1 -0
  36. package/dist/types.d.mts +99 -46
  37. package/dist/types.d.mts.map +1 -1
  38. package/package.json +10 -7
  39. package/dist/error-CVW4I654.d.mts +0 -44
  40. package/dist/error-CVW4I654.d.mts.map +0 -1
  41. package/dist/error.d.mts +0 -2
  42. package/dist/error.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"throw-mode.d.mts","names":[],"sources":["../src/throw-mode.ts"],"mappings":";;;;;;;;;;;;;;;;;cAyBa,eAAsB,GAAG,QAAQ,OAC5C,QAAQ,YAAY,QAAQ,QAC5B,UAAU,oBAAoB,QAAQ,IACtC,QAAQ,oBAAoB,eAC5B,SAAS,gBACR,QAAQ"}
@@ -0,0 +1,49 @@
1
+ import { sleepWithAbortSignal, throwIfAborted } from "./abort.mjs";
2
+ //#region src/throw-mode.ts
3
+ /**
4
+ * Throw-mode execution path for `BaseRetryPolicy.run` (default when
5
+ * `throwOnExhausted` is not `false`).
6
+ *
7
+ * @module @zap-studio/retry/throw-mode
8
+ */
9
+ /**
10
+ * Runs the throw-mode retry loop: throws `RetryError` on exhaustion and
11
+ * `AbortError` when `signal` aborts.
12
+ *
13
+ * @param policy - Object providing `next` and `onExhausted` (same contract as
14
+ * `BaseRetryPolicy`).
15
+ * @param execute - Async work callback per attempt.
16
+ * @param sleep - Delay function between retries.
17
+ * @param signal - Optional cancel signal.
18
+ * @returns Resolves to the first successful return value.
19
+ * @throws {RetryError} When retries are exhausted and `onExhausted` returns
20
+ * the terminal error.
21
+ * @throws {AbortError} When `signal` is already aborted or aborts while waiting.
22
+ * @throws {Error} Any error thrown by `next`, `onExhausted`, or `sleep`.
23
+ */
24
+ const runThrowMode = async (policy, execute, sleep, signal) => {
25
+ let attempt = 1;
26
+ while (true) {
27
+ throwIfAborted(signal);
28
+ try {
29
+ return await execute(attempt);
30
+ } catch (error) {
31
+ throwIfAborted(signal);
32
+ const typedError = error;
33
+ const decision = policy.next({
34
+ attempt,
35
+ error: typedError
36
+ });
37
+ if (!decision.shouldRetry) throw policy.onExhausted({
38
+ attempts: attempt,
39
+ error: typedError
40
+ });
41
+ if (decision.delayMs > 0) await (signal === void 0 ? sleep(decision.delayMs) : sleepWithAbortSignal(sleep, decision.delayMs, signal));
42
+ attempt += 1;
43
+ }
44
+ }
45
+ };
46
+ //#endregion
47
+ export { runThrowMode };
48
+
49
+ //# sourceMappingURL=throw-mode.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"throw-mode.mjs","names":[],"sources":["../src/throw-mode.ts"],"sourcesContent":["/**\n * Throw-mode execution path for `BaseRetryPolicy.run` (default when\n * `throwOnExhausted` is not `false`).\n *\n * @module @zap-studio/retry/throw-mode\n */\n\nimport { sleepWithAbortSignal, throwIfAborted } from \"./abort.js\";\nimport type { RetryPolicy } from \"./types.js\";\n\n/**\n * Runs the throw-mode retry loop: throws `RetryError` on exhaustion and\n * `AbortError` when `signal` aborts.\n *\n * @param policy - Object providing `next` and `onExhausted` (same contract as\n * `BaseRetryPolicy`).\n * @param execute - Async work callback per attempt.\n * @param sleep - Delay function between retries.\n * @param signal - Optional cancel signal.\n * @returns Resolves to the first successful return value.\n * @throws {RetryError} When retries are exhausted and `onExhausted` returns\n * the terminal error.\n * @throws {AbortError} When `signal` is already aborted or aborts while waiting.\n * @throws {Error} Any error thrown by `next`, `onExhausted`, or `sleep`.\n */\nexport const runThrowMode = async <T, TError, TData>(\n policy: RetryPolicy<TError, TData>,\n execute: (attempt: number) => Promise<T>,\n sleep: (delayMs: number) => Promise<void>,\n signal?: AbortSignal\n): Promise<T> => {\n let attempt = 1;\n\n while (true) {\n throwIfAborted(signal);\n\n try {\n // oxlint-disable-next-line no-await-in-loop -- Retry attempts must run sequentially.\n return await execute(attempt);\n } catch (error) {\n throwIfAborted(signal);\n\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Policy error generic represents the caller's thrown error domain.\n const typedError = error as TError;\n const decision = policy.next({\n attempt,\n error: typedError,\n });\n\n if (!decision.shouldRetry) {\n throw policy.onExhausted({\n attempts: attempt,\n error: typedError,\n });\n }\n\n if (decision.delayMs > 0) {\n // oxlint-disable-next-line no-await-in-loop -- Delay belongs between sequential retry attempts.\n await (signal === undefined\n ? sleep(decision.delayMs)\n : sleepWithAbortSignal(sleep, decision.delayMs, signal));\n }\n\n attempt += 1;\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,eAAe,OAC1B,QACA,SACA,OACA,WACe;CACf,IAAI,UAAU;CAEd,OAAO,MAAM;EACX,eAAe,MAAM;EAErB,IAAI;GAEF,OAAO,MAAM,QAAQ,OAAO;EAC9B,SAAS,OAAO;GACd,eAAe,MAAM;GAGrB,MAAM,aAAa;GACnB,MAAM,WAAW,OAAO,KAAK;IAC3B;IACA,OAAO;GACT,CAAC;GAED,IAAI,CAAC,SAAS,aACZ,MAAM,OAAO,YAAY;IACvB,UAAU;IACV,OAAO;GACT,CAAC;GAGH,IAAI,SAAS,UAAU,GAErB,OAAO,WAAW,KAAA,IACd,MAAM,SAAS,OAAO,IACtB,qBAAqB,OAAO,SAAS,SAAS,MAAM;GAG1D,WAAW;EACb;CACF;AACF"}
package/dist/types.d.mts CHANGED
@@ -1,88 +1,141 @@
1
- import { t as RetryError } from "./error-CVW4I654.mjs";
2
-
1
+ import { r as RetryError, t as AbortError } from "./errors-BVZjP1Q5.mjs";
3
2
  //#region src/types.d.ts
4
3
  /**
5
- * Retry policy contract used by `BaseRetryPolicy`.
6
- *
7
- * @example
8
- * const policy: RetryPolicy = {
9
- * next: ({ attempt }) => ({ shouldRetry: attempt < 3, delayMs: 100 }),
10
- * onExhausted: ({ attempts }) => new RetryError("done", { attempts }),
11
- * };
12
- */
4
+ * Retry policy contract used by `BaseRetryPolicy`.
5
+ *
6
+ * @example
7
+ * const policy: RetryPolicy = {
8
+ * next: ({ attempt }) => ({ shouldRetry: attempt < 3, delayMs: 100 }),
9
+ * onExhausted: ({ attempts }) => new RetryError("done", { attempts }),
10
+ * };
11
+ */
13
12
  interface RetryPolicy<TError = unknown, TData = unknown> {
14
13
  /**
15
- * Returns the retry decision for a failed attempt.
16
- *
17
- * @throws Any error thrown by the policy implementation.
18
- */
19
- next(input: RetryDecisionInput<TError, TData>): RetryDecision;
20
- /**
21
- * Builds the terminal error used when retries are exhausted.
22
- *
23
- * @throws Any error thrown by the policy implementation.
24
- */
25
- onExhausted(input: RetryExhaustedInput<TError, TData>): RetryError;
14
+ * Returns the retry decision for a failed attempt.
15
+ *
16
+ * @throws {Error} Any error thrown by the policy implementation.
17
+ */
18
+ next: (input: RetryDecisionInput<TError, TData>) => RetryDecision;
19
+ /**
20
+ * Builds the terminal error used when retries are exhausted.
21
+ *
22
+ * @throws {Error} Any error thrown by the policy implementation.
23
+ */
24
+ onExhausted: (input: RetryExhaustedInput<TError, TData>) => RetryError;
26
25
  }
27
26
  /**
28
- * Decision returned by a retry policy for a specific attempt.
29
- */
27
+ * Decision returned by a retry policy for a specific attempt.
28
+ */
30
29
  interface RetryDecision {
30
+ /**
31
+ * When `true`, the runner may schedule another attempt (subject to
32
+ * `delayMs` and the runner's abort rules).
33
+ */
31
34
  readonly shouldRetry: boolean;
35
+ /**
36
+ * Milliseconds to wait before the next attempt when `shouldRetry` is `true`.
37
+ */
32
38
  readonly delayMs: number;
39
+ /**
40
+ * Optional machine-readable reason for the decision.
41
+ */
33
42
  readonly reason?: "retry" | "max-attempts-reached" | "policy-declined";
34
43
  }
35
44
  /**
36
- * Input passed to `RetryPolicy.next(...)` for each failed attempt.
37
- */
45
+ * Input passed to `RetryPolicy.next(...)` for each failed attempt.
46
+ */
38
47
  interface RetryDecisionInput<TError = unknown, TData = unknown> {
48
+ /**
49
+ * One-based attempt number for the current failure.
50
+ */
39
51
  readonly attempt: number;
52
+ /**
53
+ * Optional policy-level maximum attempts, when a policy wants to pass it
54
+ * through to `next`.
55
+ */
40
56
  readonly maxAttempts?: number;
57
+ /**
58
+ * Error raised by the most recent `execute(attempt)` call, when a failure
59
+ * occurred.
60
+ */
41
61
  readonly error?: TError;
62
+ /**
63
+ * Optional data captured alongside the failure, when a policy populates
64
+ * it.
65
+ */
42
66
  readonly data?: TData;
43
67
  }
44
68
  /**
45
- * Input passed to `RetryPolicy.onExhausted(...)` when retries stop.
46
- */
69
+ * Input passed to `RetryPolicy.onExhausted(...)` when retries stop.
70
+ */
47
71
  interface RetryExhaustedInput<TError = unknown, TData = unknown> {
72
+ /**
73
+ * Count of completed attempts that led to stopping retries.
74
+ */
48
75
  readonly attempts: number;
76
+ /**
77
+ * Last execution error, when available.
78
+ */
49
79
  readonly error?: TError;
80
+ /**
81
+ * Last captured data, when a policy or runner supplies it.
82
+ */
50
83
  readonly data?: TData;
51
84
  }
52
85
  /**
53
- * Options for `BaseRetryPolicy.run(...)`.
54
- */
86
+ * Options for `BaseRetryPolicy.run(...)`.
87
+ */
55
88
  interface RetryRunOptions {
56
89
  /**
57
- * Delay function used between retry attempts.
58
- *
59
- * @throws Any error thrown or rejected by the custom delay implementation.
60
- */
90
+ * Delay function used between retry attempts.
91
+ *
92
+ * @throws {Error} Any error thrown or rejected by the custom delay implementation.
93
+ */
61
94
  readonly sleep?: (delayMs: number) => Promise<void>;
62
95
  /**
63
- * Abort signal used to cancel retry orchestration.
64
- *
65
- * When aborted, the runner stops retrying and terminates immediately.
66
- */
96
+ * Abort signal used to cancel retry orchestration.
97
+ *
98
+ * When aborted, the runner stops retrying and terminates immediately.
99
+ */
67
100
  readonly signal?: AbortSignal;
68
101
  /**
69
- * When `true`, the runner throws a `RetryError` when retries are exhausted.
70
- *
71
- * When `false`, the runner returns a `RetryRunResult` discriminated union.
72
- *
73
- * @default false
74
- */
102
+ * When `true`, the runner throws a `RetryError` when retries are exhausted.
103
+ *
104
+ * When `false`, the runner returns a `RetryRunResult` discriminated union.
105
+ *
106
+ * @default true
107
+ */
75
108
  readonly throwOnExhausted?: boolean;
76
109
  }
77
110
  /**
78
- * Result union returned by non-throw runner mode.
79
- */
111
+ * Result union returned by non-throw runner mode.
112
+ *
113
+ * - Success: `ok: true` with the resolved `value`.
114
+ * - Failure: `ok: false` with terminal `error` and completed `attempts` count
115
+ * (exhaustion or abort).
116
+ */
80
117
  type RetryRunResult<T> = {
118
+ /**
119
+ * Discriminator for a successful run.
120
+ */
81
121
  ok: true;
122
+ /**
123
+ * Successful return value from the final attempt.
124
+ */
82
125
  value: T;
83
126
  } | {
127
+ /**
128
+ * Discriminator for a failed or aborted run.
129
+ */
84
130
  ok: false;
85
- error: RetryError;
131
+ /**
132
+ * Terminal error: `RetryError` when retries are exhausted, or
133
+ * `AbortError` when the run is canceled.
134
+ */
135
+ error: RetryError | AbortError;
136
+ /**
137
+ * Number of attempts that completed before the terminal outcome.
138
+ */
86
139
  attempts: number;
87
140
  };
88
141
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;;;;;;;;UAiBiB,WAAA;;;;;;EAMf,IAAA,CAAK,KAAA,EAAO,kBAAA,CAAmB,MAAA,EAAQ,KAAA,IAAS,aAAA;;;;;;EAMhD,WAAA,CAAY,KAAA,EAAO,mBAAA,CAAoB,MAAA,EAAQ,KAAA,IAAS,UAAA;AAAA;AAM1D;;;AAAA,UAAiB,aAAA;EAAA,SACN,WAAA;EAAA,SACA,OAAA;EAAA,SACA,MAAA;AAAA;;AAMX;;UAAiB,kBAAA;EAAA,SACN,OAAA;EAAA,SACA,WAAA;EAAA,SACA,KAAA,GAAQ,MAAA;EAAA,SACR,IAAA,GAAO,KAAA;AAAA;;;;UAMD,mBAAA;EAAA,SACN,QAAA;EAAA,SACA,KAAA,GAAQ,MAAA;EAAA,SACR,IAAA,GAAO,KAAA;AAAA;;;;UAMD,eAAA;EANC;AAMlB;;;;EANkB,SAYP,KAAA,IAAS,OAAA,aAAoB,OAAA;;;;;;WAM7B,MAAA,GAAS,WAAA;EAQT;AAMX;;;;;;EANW,SAAA,gBAAA;AAAA;;;;KAMC,cAAA;EAEN,EAAA;EACA,KAAA,EAAO,CAAA;AAAA;EAGP,EAAA;EACA,KAAA,EAAO,UAAA;EACP,QAAA;AAAA"}
1
+ {"version":3,"file":"types.d.mts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;;;;;;;UAiBiB,YAAY,kBAAkB;;;;;;EAM7C,OAAO,OAAO,mBAAmB,QAAQ,WAAW;;;;;;EAMpD,cAAc,OAAO,oBAAoB,QAAQ,WAAW;;;;;UAM7C;;;;;WAKN;;;;WAIA;;;;WAIA;;;;;UAMM,mBAAmB,kBAAkB;;;;WAI3C;;;;;WAKA;;;;;WAKA,QAAQ;;;;;WAKR,OAAO;;;;;UAMD,oBAAoB,kBAAkB;;;;WAI5C;;;;WAIA,QAAQ;;;;WAIR,OAAO;;;;;UAMD;;;;;;WAMN,SAAS,oBAAoB;;;;;;WAM7B,SAAS;;;;;;;;WAQT;;;;;;;;;KAUC,eAAe;;;;EAKrB;;;;EAIA,OAAO;;;;;EAMP;;;;;EAKA,OAAO,aAAa;;;;EAIpB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zap-studio/retry",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "private": false,
5
5
  "description": "Composable retry policies for resilient async operations.",
6
6
  "keywords": [
@@ -30,9 +30,13 @@
30
30
  "types": "./dist/index.d.mts",
31
31
  "exports": {
32
32
  ".": "./dist/index.mjs",
33
- "./error": "./dist/error.mjs",
33
+ "./abort": "./dist/abort.mjs",
34
+ "./errors": "./dist/errors.mjs",
34
35
  "./exponential-backoff": "./dist/exponential-backoff.mjs",
35
36
  "./fixed-delay": "./dist/fixed-delay.mjs",
37
+ "./result-mode": "./dist/result-mode.mjs",
38
+ "./sleep": "./dist/sleep.mjs",
39
+ "./throw-mode": "./dist/throw-mode.mjs",
36
40
  "./types": "./dist/types.mjs",
37
41
  "./package.json": "./package.json"
38
42
  },
@@ -46,16 +50,15 @@
46
50
  "exponential-backoff": "^3.1.3",
47
51
  "p-retry": "^8.0.0",
48
52
  "promise-retry": "^2.0.1",
49
- "typescript": "^6.0.3",
50
- "vite-plus": "^0.1.19",
53
+ "tsdown": "^0.22.4",
54
+ "typescript": "^7.0.2",
55
+ "vitest": "^4.1.10",
51
56
  "@zap-studio/typescript": "0.0.0"
52
57
  },
53
58
  "engines": {
54
59
  "node": ">=18.0.0"
55
60
  },
56
61
  "scripts": {
57
- "build": "vp pack",
58
- "test": "vp test run",
59
- "test:watch": "vp test watch"
62
+ "build": "tsdown --config ./tsdown.config.ts"
60
63
  }
61
64
  }
@@ -1,44 +0,0 @@
1
- //#region src/error.d.ts
2
- /**
3
- * Terminal error types used by retry policies and runners.
4
- *
5
- * @module @zap-studio/retry/error
6
- */
7
- /**
8
- * Context payload attached to `RetryError`.
9
- */
10
- interface RetryErrorContext {
11
- readonly attempts: number;
12
- readonly lastError?: unknown;
13
- readonly lastData?: unknown;
14
- }
15
- /**
16
- * Error thrown when retries are exhausted.
17
- *
18
- * @example
19
- * throw new RetryError("Retry exhausted", {
20
- * attempts: 3,
21
- * lastError: new Error("network"),
22
- * });
23
- */
24
- declare class RetryError extends Error {
25
- /**
26
- * Total attempts performed before exhaustion.
27
- */
28
- readonly attempts: number;
29
- /**
30
- * Last captured error from execution.
31
- */
32
- readonly lastError?: unknown;
33
- /**
34
- * Last captured data value, when available.
35
- */
36
- readonly lastData?: unknown;
37
- /**
38
- * Creates a RetryError with structured terminal context.
39
- */
40
- constructor(message: string, context: RetryErrorContext);
41
- }
42
- //#endregion
43
- export { RetryErrorContext as n, RetryError as t };
44
- //# sourceMappingURL=error-CVW4I654.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"error-CVW4I654.d.mts","names":[],"sources":["../src/error.ts"],"mappings":";;AASA;;;;;;;UAAiB,iBAAA;EAAA,SACN,QAAA;EAAA,SACA,SAAA;EAAA,SACA,QAAA;AAAA;;;;;;;;;;cAYE,UAAA,SAAmB,KAAA;EAiBQ;;;EAAA,SAbtB,QAAA;;;;WAIA,SAAA;;;;WAIA,QAAA;;;;EAKhB,WAAA,CAAY,OAAA,UAAiB,OAAA,EAAS,iBAAA;AAAA"}
package/dist/error.d.mts DELETED
@@ -1,2 +0,0 @@
1
- import { n as RetryErrorContext, t as RetryError } from "./error-CVW4I654.mjs";
2
- export { RetryError, RetryErrorContext };
@@ -1 +0,0 @@
1
- {"version":3,"file":"error.mjs","names":[],"sources":["../src/error.ts"],"sourcesContent":["/**\n * Terminal error types used by retry policies and runners.\n *\n * @module @zap-studio/retry/error\n */\n\n/**\n * Context payload attached to `RetryError`.\n */\nexport interface RetryErrorContext {\n readonly attempts: number;\n readonly lastError?: unknown;\n readonly lastData?: unknown;\n}\n\n/**\n * Error thrown when retries are exhausted.\n *\n * @example\n * throw new RetryError(\"Retry exhausted\", {\n * attempts: 3,\n * lastError: new Error(\"network\"),\n * });\n */\nexport class RetryError extends Error {\n /**\n * Total attempts performed before exhaustion.\n */\n public readonly attempts: number;\n /**\n * Last captured error from execution.\n */\n public readonly lastError?: unknown;\n /**\n * Last captured data value, when available.\n */\n public readonly lastData?: unknown;\n\n /**\n * Creates a RetryError with structured terminal context.\n */\n constructor(message: string, context: RetryErrorContext) {\n super(message);\n this.name = \"RetryError\";\n this.attempts = context.attempts;\n this.lastError = context.lastError;\n this.lastData = context.lastData;\n }\n}\n"],"mappings":";;;;;;;;;;AAwBA,IAAa,aAAb,cAAgC,MAAM;;;;CAIpC;;;;CAIA;;;;CAIA;;;;CAKA,YAAY,SAAiB,SAA4B;AACvD,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,WAAW,QAAQ;AACxB,OAAK,YAAY,QAAQ;AACzB,OAAK,WAAW,QAAQ"}