@demlik/tea 0.14.0 → 0.16.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.
Files changed (116) hide show
  1. package/README.md +30 -7
  2. package/dist/agent/index.d.ts +49 -36
  3. package/dist/agent/index.js +12 -8
  4. package/dist/chunk-4LPY67E4.js +18 -0
  5. package/dist/chunk-4LPY67E4.js.map +1 -0
  6. package/dist/chunk-5XU6ZJO2.js +533 -0
  7. package/dist/chunk-5XU6ZJO2.js.map +1 -0
  8. package/dist/{chunk-AQ6ZIMEA.js → chunk-6NG4V5SB.js} +89 -115
  9. package/dist/chunk-6NG4V5SB.js.map +1 -0
  10. package/dist/{chunk-HYDWG35Q.js → chunk-7MGXQZPW.js} +11 -9
  11. package/dist/chunk-7MGXQZPW.js.map +1 -0
  12. package/dist/{chunk-BLJ2JQSH.js → chunk-BCTEOVOU.js} +3 -3
  13. package/dist/{chunk-BLJ2JQSH.js.map → chunk-BCTEOVOU.js.map} +1 -1
  14. package/dist/chunk-CH5KTOEZ.js +710 -0
  15. package/dist/chunk-CH5KTOEZ.js.map +1 -0
  16. package/dist/chunk-CIHSHLQX.js +64 -0
  17. package/dist/chunk-CIHSHLQX.js.map +1 -0
  18. package/dist/{chunk-Z2L3LSNV.js → chunk-EHUDXAKC.js} +246 -210
  19. package/dist/chunk-EHUDXAKC.js.map +1 -0
  20. package/dist/chunk-GOX2CYIM.js +380 -0
  21. package/dist/chunk-GOX2CYIM.js.map +1 -0
  22. package/dist/chunk-IVJP3GKJ.js +104 -0
  23. package/dist/chunk-IVJP3GKJ.js.map +1 -0
  24. package/dist/{chunk-F7FMAWLA.js → chunk-MVZS5FDM.js} +13 -6
  25. package/dist/chunk-MVZS5FDM.js.map +1 -0
  26. package/dist/{chunk-LYLTKJWM.js → chunk-MYNLY3HP.js} +9 -8
  27. package/dist/chunk-MYNLY3HP.js.map +1 -0
  28. package/dist/{chunk-I5MQMJDW.js → chunk-NSIAORRY.js} +20 -30
  29. package/dist/chunk-NSIAORRY.js.map +1 -0
  30. package/dist/{chunk-MYXFNWAJ.js → chunk-QNGYQMZB.js} +4 -4
  31. package/dist/chunk-QNGYQMZB.js.map +1 -0
  32. package/dist/chunk-WT5PBPLB.js +98 -0
  33. package/dist/chunk-WT5PBPLB.js.map +1 -0
  34. package/dist/{core-CTzMJ82M.d.ts → core-BbgtiXdg.d.ts} +231 -139
  35. package/dist/do/index.d.ts +37 -32
  36. package/dist/do/index.js +21 -14
  37. package/dist/do/index.js.map +1 -1
  38. package/dist/{durable-effects-B0-qGQDy.d.ts → durable-effects-7MTK_jnj.d.ts} +1 -1
  39. package/dist/effect/index.d.ts +151 -0
  40. package/dist/effect/index.js +98 -0
  41. package/dist/effect/index.js.map +1 -0
  42. package/dist/extension/index.d.ts +6 -7
  43. package/dist/extension/index.js +3 -2
  44. package/dist/extension/index.js.map +1 -1
  45. package/dist/flow/index.d.ts +68 -70
  46. package/dist/flow/index.js +32 -27
  47. package/dist/flow/index.js.map +1 -1
  48. package/dist/idempotency/index.d.ts +6 -7
  49. package/dist/idempotency/index.js +4 -2
  50. package/dist/{index-DJWIER_3.d.ts → index-7vV8xmsD.d.ts} +1 -1
  51. package/dist/{index-NjrT3fL2.d.ts → index-Bz5Rh9Ga.d.ts} +19 -96
  52. package/dist/index-CjFDUBeq.d.ts +207 -0
  53. package/dist/{index-6A7dB8f6.d.ts → index-CkFYA9Y6.d.ts} +14 -16
  54. package/dist/{index-B5BZ-_cT.d.ts → index-Cou86-GX.d.ts} +189 -108
  55. package/dist/{index-TvRb1KVf.d.ts → index-DU6JpQ8G.d.ts} +1 -1
  56. package/dist/{index-q0hXFeZ0.d.ts → index-Xufl55W8.d.ts} +286 -215
  57. package/dist/{index-4vZzljCD.d.ts → index-_dOR3xqA.d.ts} +57 -45
  58. package/dist/index.d.ts +181 -385
  59. package/dist/index.js +2 -1
  60. package/dist/jev/index.d.ts +147 -99
  61. package/dist/jev/index.js +329 -233
  62. package/dist/jev/index.js.map +1 -1
  63. package/dist/{machine-CdIcN2Xm.d.ts → machine-BQzTV8On.d.ts} +171 -280
  64. package/dist/machine-viz/index.d.ts +5 -5
  65. package/dist/machine-viz/index.js +8 -4
  66. package/dist/machine-viz/index.js.map +1 -1
  67. package/dist/mem/index.d.ts +3 -4
  68. package/dist/mem/index.js +2 -1
  69. package/dist/mem/index.js.map +1 -1
  70. package/dist/node/index.d.ts +119 -78
  71. package/dist/node/index.js +52 -38
  72. package/dist/node/index.js.map +1 -1
  73. package/dist/paginate/index.d.ts +27 -33
  74. package/dist/paginate/index.js +6 -4
  75. package/dist/parity/index.d.ts +4 -5
  76. package/dist/parity/index.js +3 -2
  77. package/dist/parity/index.js.map +1 -1
  78. package/dist/pbt/index.d.ts +2 -2
  79. package/dist/pbt/index.js +2 -1
  80. package/dist/pbt/index.js.map +1 -1
  81. package/dist/persistence/index.d.ts +6 -7
  82. package/dist/persistence/index.js +5 -3
  83. package/dist/promise/index.d.ts +186 -0
  84. package/dist/promise/index.js +5 -0
  85. package/dist/promise/index.js.map +1 -0
  86. package/dist/protocol-ClRZBhHQ.d.ts +53 -0
  87. package/dist/react/index.d.ts +36 -17
  88. package/dist/react/index.js +27 -4
  89. package/dist/react/index.js.map +1 -1
  90. package/dist/resilience/index.d.ts +63 -455
  91. package/dist/resilience/index.js +37 -483
  92. package/dist/resilience/index.js.map +1 -1
  93. package/dist/{runtime-types-LWDoi943.d.ts → runtime-types-CiVpC0HN.d.ts} +131 -388
  94. package/dist/testing/index.d.ts +165 -15
  95. package/dist/testing/index.js +104 -3
  96. package/dist/testing/index.js.map +1 -1
  97. package/dist/timing/index.d.ts +25 -22
  98. package/dist/timing/index.js +4 -3
  99. package/dist/timing/index.js.map +1 -1
  100. package/dist/{types-DP3f5NIl.d.ts → types-LxZxGYda.d.ts} +2 -2
  101. package/dist/work-queue/index.d.ts +5 -6
  102. package/package.json +18 -5
  103. package/dist/chunk-AQ6ZIMEA.js.map +0 -1
  104. package/dist/chunk-F2US5BW6.js +0 -72
  105. package/dist/chunk-F2US5BW6.js.map +0 -1
  106. package/dist/chunk-F7FMAWLA.js.map +0 -1
  107. package/dist/chunk-HUKZQX6U.js +0 -97
  108. package/dist/chunk-HUKZQX6U.js.map +0 -1
  109. package/dist/chunk-HYDWG35Q.js.map +0 -1
  110. package/dist/chunk-I5MQMJDW.js.map +0 -1
  111. package/dist/chunk-LYLTKJWM.js.map +0 -1
  112. package/dist/chunk-MYXFNWAJ.js.map +0 -1
  113. package/dist/chunk-RQULHGYH.js +0 -1804
  114. package/dist/chunk-RQULHGYH.js.map +0 -1
  115. package/dist/chunk-Z2L3LSNV.js.map +0 -1
  116. package/dist/index-DMCeMPMJ.d.ts +0 -272
@@ -1,11 +1,12 @@
1
- import { a as CmdOf, b as CmdDef, C as Cmd, I as Interpret, i as CmdValue, g as PortEmitter, S as Sub, M as Machine } from '../core-CTzMJ82M.js';
2
- import { M as MsgType, e as ResilientConfig, a as ResilientState, R as RunCmd, S as SucceedMsg, F as FailMsg, f as ResilientTimerMsg, d as ResilientPorts } from '../index-B5BZ-_cT.js';
3
- export { g as CacheConfig, h as CallBudget, i as CallPhase, C as CircuitConfig, j as CircuitPolicy, k as CircuitState, l as DeadlineExceededError, c as RateLimitConfig, D as ResilientCallDeadlineConfig, m as RunCmdDef, n as SlidingWindow, T as TokenBucket, o as canPass, p as createResilientCall, q as defaultCircuitPolicy, r as initBucket, s as initCircuit, t as initWindow, u as liftResilience, v as onFailure, w as onSuccess, x as record, y as refill, z as remaining, A as runCmdDef, B as tryConsume } from '../index-B5BZ-_cT.js';
4
- import { a as DeadlineSub } from '../index-q0hXFeZ0.js';
5
- export { A as ArmTimer, e as CacheEntry, c as CacheEvictMsg, C as CacheEvictionSub, D as DeadlineExceeded, f as DeadlineOpts, T as TtlCache, g as cacheEvictMsg, h as cacheEvictionSub, i as cacheEvictionSubscribe, d as deadlineExceeded, b as deadlineSub, j as evictExpired, k as get, l as has, m as initCache, r as remove, n as set, o as setTimeoutArmTimer, s as subscribeDeadline, p as subscribeWith } from '../index-q0hXFeZ0.js';
1
+ import { c as CmdOf, b as CmdDef, f as SettledErr, g as TaggedError, e as SettledOk, T as TimerDeps, C as Cmd } from '../core-BbgtiXdg.js';
2
+ import { M as MsgType } from '../protocol-ClRZBhHQ.js';
3
+ import { a as DeadlineSub } from '../index-Xufl55W8.js';
4
+ export { A as ArmTimer, g as CacheEntry, f as CacheEvictMsg, h as CacheEvictionDeps, C as CacheEvictionSub, D as DeadlineExceeded, i as DeadlineMsgType, j as DeadlineOpts, b as DeadlinesSub, T as TtlCache, k as cacheEvictMsg, l as cacheEvictionSub, m as cacheEvictionSubscribe, d as deadlineExceeded, n as deadlineMsgType, c as deadlineSub, o as deadlines, e as deadlinesSub, p as evictExpired, q as get, r as has, t as initCache, u as nextTimer, v as remove, w as set, x as setTimeoutArmTimer, s as subscribeDeadline, y as subscribeWith } from '../index-Xufl55W8.js';
5
+ import { c as ResilientConfig, a as ResilientState, R as RunCmd, S as SucceedMsg, F as FailMsg, b as ResilientTimerMsg } from '../index-Cou86-GX.js';
6
+ export { C as CacheConfig, d as CallBudget, e as CallPhase, f as CircuitConfig, g as CircuitPolicy, h as CircuitState, D as DEFAULT_RESILIENT_NAME, i as DeadlineExceededError, j as DeadlineNameOf, k as DefaultResilientName, l as RateLimitConfig, m as ResilientCallDeadlineConfig, n as ResilientDeadlineType, o as ResilientErrType, p as ResilientOkType, q as ResilientRunType, r as RunCmdDef, s as RunErr, t as SettleMsg, u as SettleOutcome, v as SettleResult, w as SlidingWindow, T as TokenBucket, x as canPass, y as createResilientCall, z as defaultCircuitPolicy, A as initBucket, B as initCircuit, E as initWindow, G as liftResilience, H as onFailure, I as onSuccess, J as record, K as refill, L as remaining, M as runCmdDef, N as tryConsume } from '../index-Cou86-GX.js';
6
7
  import { Rng, RetryPolicy } from '../retry-backoff/index.js';
7
- import 'zod';
8
- import '../types-DP3f5NIl.js';
8
+ import '@standard-schema/spec';
9
+ import '../types-LxZxGYda.js';
9
10
 
10
11
  /**
11
12
  * A minted credential: the opaque `value` to send on the wire, and the absolute
@@ -74,59 +75,38 @@ interface TokenState {
74
75
  declare function initTokenRefresh(): TokenState;
75
76
  /**
76
77
  * The Cmd this knob emits to ask the runtime to mint a fresh token. Plain data
77
- * (no closure — invariant 1) carrying nothing: the refresh port takes no input,
78
- * and the slice the result installs is read off the follow-up Msg, not this
79
- * Cmd. The consumer unions this into their machine's Cmd type and lets
80
- * `handlers` interpret it.
78
+ * (no closure — invariant 1) carrying nothing: the refresh takes no input, and
79
+ * the slice the result installs is read off the settled Msg, not this Cmd.
80
+ * List it in the machine's `cmds`; its handler returns `ok(token)` or
81
+ * `err({ _tag: "token_refresh_failed", … })`, and the engine mints
82
+ * `refresh_token_ok` / `refresh_token_err`.
81
83
  */
82
84
  declare const refreshToken: CmdDef<"refresh_token", Record<string, never>, Token, {
83
85
  readonly [detail: string]: unknown;
84
86
  readonly _tag: "token_refresh_failed";
85
- }, unknown>;
87
+ }>;
86
88
  type RefreshTokenCmd = CmdOf<typeof refreshToken>;
87
89
  /** Construct a `refresh_token` Cmd. */
88
90
  declare function refreshTokenCmd(): RefreshTokenCmd;
89
91
  /**
90
- * The Msg the refresh port dispatches on success — carries the freshly minted
91
- * `Token`. The consumer unions this into their Msg type and handles it by
92
- * folding `refreshed(state, msg.token)` into the slice.
92
+ * The Msg the engine mints when the `refresh_token` handler returns
93
+ * `ok(token)`: `value` is the freshly minted `Token`. Fold it with
94
+ * `refreshed(state, msg.value)`.
93
95
  */
94
- interface TokenRefreshedMsg {
95
- readonly type: typeof MsgType.TokenRefreshed;
96
- readonly token: Token;
97
- }
98
- /** Construct a `token_refreshed` Msg carrying the new token. */
99
- declare function tokenRefreshedMsg(token: Token): TokenRefreshedMsg;
96
+ type TokenRefreshedMsg = SettledOk<"refresh_token", RefreshTokenCmd, Token>;
100
97
  /**
101
- * The Msg the refresh port dispatches on failure — carries the rejection so the
102
- * consumer's reducer can decide whether to back off, surface an error, or give
103
- * up (errors are data: it is dispatched, never swallowed). The slice itself is
104
- * left untouched by a failed refresh — the held token (if any) stays held and
105
- * stale stays set, so the consumer can retry; clearing it is the consumer's
106
- * policy, expressed in their reducer.
98
+ * The Msg the engine mints when the handler returns
99
+ * `err({ _tag: "token_refresh_failed", … })` — errors are data, never
100
+ * swallowed. The slice is left untouched by a failed refresh: the held token
101
+ * (if any) stays held and stale stays set, so the consumer can retry; clearing
102
+ * it is the consumer's policy, expressed in their reducer.
107
103
  */
108
- interface TokenRefreshFailedMsg {
109
- readonly type: typeof MsgType.TokenRefreshFailed;
110
- readonly error: unknown;
111
- }
112
- /** Construct a `token_refresh_failed` Msg carrying the rejection. */
113
- declare function tokenRefreshFailedMsg(error: unknown): TokenRefreshFailedMsg;
114
- /** The two Msgs the refresh port can produce. Union for a consumer's Msg type. */
104
+ type TokenRefreshFailedMsg = SettledErr<"refresh_token", RefreshTokenCmd, TaggedError<"token_refresh_failed">>;
105
+ /** The two Msgs a refresh can settle with. Union for a consumer's Msg type. */
115
106
  type TokenRefreshMsg = TokenRefreshedMsg | TokenRefreshFailedMsg;
116
- /** The ports this knob's `handlers` splice needs — the single refresh DI seam. */
117
- interface TokenRefreshPorts {
118
- /**
119
- * Mint a fresh credential. Called ONLY from the `refresh_token` interpret
120
- * handler — never from a verb — so the network I/O and any clock the issuer
121
- * reads stay at the effect boundary. May reject; the rejection is routed to
122
- * `token_refresh_failed` (errors are data), never thrown into the runtime.
123
- */
124
- readonly refresh: () => Promise<Token>;
125
- }
126
107
  /**
127
- * The knob: hand it a config, get back the slice initializer, the pure verbs,
128
- * and the `handlers` splice. Mirrors every L2 composition's uniform contract so
129
- * the call sites read identically across bricks.
108
+ * The knob: hand it a config, get back the slice initializer and the pure
109
+ * verbs, plus the `refresh_token` Cmd def (`run`) to list in `cmds`.
130
110
  *
131
111
  * @example
132
112
  * const tr = createTokenRefresh({ skewMs: 30_000 });
@@ -134,13 +114,17 @@ interface TokenRefreshPorts {
134
114
  * const [s1, cmds] = tr.ensureFresh(s0, Date.now()); // cmds = [refreshTokenCmd()]
135
115
  */
136
116
  declare function createTokenRefresh(config?: TokenRefreshConfig): {
117
+ /** The `refresh_token` Cmd def — list it in the machine's `cmds`. */
118
+ run: CmdDef<"refresh_token", Record<string, never>, Token, {
119
+ readonly [detail: string]: unknown;
120
+ readonly _tag: "token_refresh_failed";
121
+ }>;
137
122
  /** The slice initializer — spread into the consumer's `init`. */
138
123
  init: typeof initTokenRefresh;
139
124
  needsRefresh: (state: TokenState, at: number) => boolean;
140
125
  on401: (state: TokenState) => TokenState;
141
126
  refreshed: (state: TokenState, token: Token) => TokenState;
142
- ensureFresh: (state: TokenState, at: number) => readonly [TokenState, readonly Cmd[]];
143
- handlers: (ports: TokenRefreshPorts) => Interpret<TokenRefreshMsg, RefreshTokenCmd, unknown>;
127
+ ensureFresh: (state: TokenState, at: number) => readonly [TokenState, readonly RefreshTokenCmd[]];
144
128
  };
145
129
  /** The shape `createTokenRefresh` returns — useful for typing a held knob. */
146
130
  type TokenRefresh = ReturnType<typeof createTokenRefresh>;
@@ -148,19 +132,15 @@ type TokenRefresh = ReturnType<typeof createTokenRefresh>;
148
132
  /**
149
133
  * The authed-call knob. It is `ResilientConfig` widened by the token dimension:
150
134
  *
151
- * - `refresh` — the ONLY required field: the port that mints a fresh `Token`.
152
- * Identical to token-refresh's `TokenRefreshPorts.refresh`; it is hoisted
153
- * onto the config (not the ports) so the consumer spells the credential
154
- * source once, the same way `rng` is curried onto the factory.
155
135
  * - `skewMs` — token-refresh's refresh-ahead skew (optional, defaults to 0).
156
136
  * - every `ResilientConfig` field (`retry` / `circuit` / `rateLimit` /
157
137
  * `cache` / `deadline`) — passed straight through to the resilient-call
158
138
  * knob, each still optional, each still "omit a brick → omit its gate".
139
+ *
140
+ * The token mint is not on the config: it is the `refresh_token` Cmd, and its
141
+ * handler is yours.
159
142
  */
160
- interface AuthedConfig extends ResilientConfig, TokenRefreshConfig {
161
- /** Mint a fresh credential. The single DI seam the auth dimension adds. */
162
- readonly refresh: () => Promise<Token>;
163
- }
143
+ type AuthedConfig = ResilientConfig & TokenRefreshConfig;
164
144
  /**
165
145
  * The composed slice. Three plain-data fields, no closures:
166
146
  *
@@ -208,11 +188,6 @@ type UnauthorizedError = {
208
188
  readonly _tag: "unauthorized";
209
189
  readonly key: string;
210
190
  };
211
- /** Ports `handlers` needs — resilient-call's run port AND token-refresh's refresh port. */
212
- interface AuthedPorts<I, R> extends ResilientPorts<I, R> {
213
- /** Mint a fresh credential. Mirrors `AuthedConfig.refresh` for symmetry at the splice site. */
214
- readonly refresh: () => Promise<Token>;
215
- }
216
191
  /**
217
192
  * Build an authed-call knob from `config`. `rng` is injected for retry jitter
218
193
  * and threaded straight into the underlying resilient-call knob — pass a fixed
@@ -222,34 +197,38 @@ interface AuthedPorts<I, R> extends ResilientPorts<I, R> {
222
197
  * Returns the uniform L2 knob contract, widened by the auth verbs (`on401`,
223
198
  * `onRefreshed`, `installToken`). `I` is the port input type, `R` the result.
224
199
  */
225
- declare function createAuthedCall<I, R>(config: AuthedConfig, rng?: () => number): {
200
+ declare function createAuthedCall<I, R>(config?: AuthedConfig, rng?: () => number): {
201
+ /** The call's `Cmd.define`d run Cmd — list it in `cmds`. */
202
+ run: CmdDef<"resilient_run", {
203
+ readonly key: string;
204
+ readonly input: I;
205
+ }, R, {
206
+ readonly [detail: string]: unknown;
207
+ readonly _tag: "deadline_exceeded";
208
+ } | {
209
+ readonly [detail: string]: unknown;
210
+ readonly _tag: "port_rejected";
211
+ }>;
212
+ /** token-refresh's `refresh_token` Cmd def — list it in `cmds`. */
213
+ refresh: CmdDef<"refresh_token", Record<string, never>, Token, {
214
+ readonly [detail: string]: unknown;
215
+ readonly _tag: "token_refresh_failed";
216
+ }>;
226
217
  init: () => AuthedState<I, R>;
227
218
  attempt: (s: AuthedState<I, R>, key: string, input: I, at: number) => readonly [AuthedState<I, R>, readonly AuthedCmd<I>[]];
228
- succeed: (s: AuthedState<I, R>, key: string, msg: SucceedMsg<R>) => readonly [AuthedState<I, R>, readonly AuthedCmd<I>[]];
229
- fail: (s: AuthedState<I, R>, key: string, msg: FailMsg) => readonly [AuthedState<I, R>, readonly AuthedCmd<I>[]];
219
+ succeed: (s: AuthedState<I, R>, msg: SucceedMsg<R>) => readonly [AuthedState<I, R>, readonly AuthedCmd<I>[]];
220
+ fail: (s: AuthedState<I, R>, msg: FailMsg) => readonly [AuthedState<I, R>, readonly AuthedCmd<I>[]];
230
221
  on401: (s: AuthedState<I, R>, key: string, at: number) => readonly [AuthedState<I, R>, readonly AuthedCmd<I>[]];
231
222
  installToken: (s: AuthedState<I, R>, token: Token) => AuthedState<I, R>;
232
223
  onRefreshed: (s: AuthedState<I, R>, at: number) => readonly [AuthedState<I, R>, readonly AuthedCmd<I>[]];
233
- onTimer: (s: AuthedState<I, R>, msg: ResilientTimerMsg) => readonly [AuthedState<I, R>, readonly AuthedCmd<I>[]];
224
+ onTimer: (s: AuthedState<I, R>, msg: ResilientTimerMsg | {
225
+ readonly id: string;
226
+ readonly atMs: number;
227
+ }) => readonly [AuthedState<I, R>, readonly AuthedCmd<I>[]];
234
228
  /** token-refresh's call-boundary verb, re-exposed for proactive expiry refresh. */
235
229
  needsRefresh: (s: AuthedState<I, R>, at: number) => boolean;
236
- subs: (s: AuthedState<I, R>) => readonly DeadlineSub[];
237
- handlers: (ports: AuthedPorts<I, R>) => {
238
- refresh_token: (cmd: CmdValue<"refresh_token", Record<string, never>, {
239
- readonly [detail: string]: unknown;
240
- readonly _tag: "token_refresh_failed";
241
- }, unknown>, ctx: PortEmitter, dispatch?: ((msg: TokenRefreshMsg) => void) | undefined) => Promise<void | TokenRefreshMsg>;
242
- resilient_run: (cmd: CmdValue<"resilient_run", {
243
- readonly key: string;
244
- readonly input: I;
245
- }, {
246
- readonly [detail: string]: unknown;
247
- readonly _tag: "deadline_exceeded";
248
- } | {
249
- readonly [detail: string]: unknown;
250
- readonly _tag: "port_rejected";
251
- }, unknown>, ctx: Readonly<Record<never, never>>) => Promise<FailMsg | SucceedMsg<R>>;
252
- };
230
+ deadlines: (s: AuthedState<I, R>) => readonly DeadlineSub[];
231
+ timer: (s: AuthedState<I, R>) => TimerDeps<ResilientTimerMsg<"resilient">> | null;
253
232
  };
254
233
  /** The shape `createAuthedCall` returns — useful for typing a held knob. */
255
234
  type AuthedCall<I, R> = ReturnType<typeof createAuthedCall<I, R>>;
@@ -369,375 +348,4 @@ interface RetryToSuccessOptions {
369
348
  */
370
349
  declare function retryToSuccess<R>(port: () => Promise<R>, policy: RetryPolicy, opts?: RetryToSuccessOptions): Promise<R>;
371
350
 
372
- /**
373
- * The wrapper's Model slice. `phase` is the lifecycle (`armed` while the
374
- * countdown runs, `exceeded` once the deadline fired); `seq` is the monotonic
375
- * re-arm counter that keys the timer Sub's id so each accepted progress Msg
376
- * retires the old timer and starts a fresh one.
377
- *
378
- * PURE and SERIALIZABLE: there is deliberately NO absolute timestamp here. A
379
- * deadline timestamp would force the merged `update` to read the wall clock to
380
- * compute it, which the conformance gate (property 2 — two replays under
381
- * distinct ambient clocks) is built to catch. Instead, the timer arms a fresh
382
- * full `ms` countdown per generation; no remaining-delay computation and no
383
- * clock read occur in the slice or `update` — the only clock is `setTimeout`
384
- * inside the Sub.
385
- */
386
- interface DeadlineSlice {
387
- /** `armed` while the countdown is live; `exceeded` once the deadline fired. */
388
- readonly phase: "armed" | "exceeded";
389
- /**
390
- * Monotonic re-arm counter. Starts at 0; each accepted progress Msg (while
391
- * armed) bumps it by one. Folds into the timer Sub's id, so a bump = a new id
392
- * = the substrate retires the old timer and arms a fresh `ms` countdown.
393
- */
394
- readonly seq: number;
395
- }
396
- /**
397
- * The composed Model. The base machine's state is nested under `base`; the
398
- * wrapper's state lives in the NAMED `$deadline` slice — never hidden in a
399
- * closure. Both fields are plain data, so the whole composed Model round-trips
400
- * through `JSON.parse(JSON.stringify(...))` iff the base state does.
401
- */
402
- interface DeadlineModel<S> {
403
- readonly base: S;
404
- readonly $deadline: DeadlineSlice;
405
- }
406
- /**
407
- * The relative-timeout Sub the wrapper arms while `phase === "armed"`. `delayMs`
408
- * is the window `config.ms`; the id is `$deadline:timeout:{seq}`, so each
409
- * progress bump produces a distinct id and the reconcile pass churns the timer.
410
- * Same `delayMs`-on-the-Sub shape `fromTimeout` consumes.
411
- */
412
- type DeadlineTimeoutSub = Sub<"$deadline:timeout"> & {
413
- readonly delayMs: number;
414
- };
415
- /**
416
- * The Msg the timeout Sub dispatches when `config.ms` elapses with no accepted
417
- * progress. `seq` echoes the re-arm generation the timer was armed against, so a
418
- * stale timer's Msg (one whose id was already retired) is identifiable; the
419
- * merged `update` only honors it when it matches the current slice `seq`.
420
- */
421
- interface DeadlineExceededMsg {
422
- readonly type: "$deadline:exceeded";
423
- /** The re-arm generation this timer was armed against. */
424
- readonly seq: number;
425
- }
426
- /**
427
- * Construct the deadline-exceeded Msg. Exported so the subscribe cell and tests
428
- * share one constructor rather than two literals that can drift.
429
- */
430
- declare function deadlineExceededMsg(seq: number): DeadlineExceededMsg;
431
- /**
432
- * The fire-and-forget decision Cmd the merged `update` appends on every
433
- * transition, so the wrapper's choice is visible in the replayed Cmd log
434
- * (rule 3) — `rearm` when an accepted progress Msg bumped `seq`, `expire` when
435
- * the deadline-exceeded Msg flipped the phase, `idle` otherwise (a non-progress
436
- * Msg, or a Msg after the machine already auto-failed). Plain data; its
437
- * interpret handler is a no-op (the decision is the Cmd's presence in the log,
438
- * not a side effect).
439
- */
440
- declare const deadlineDecision: CmdDef<"$deadline:decision", {
441
- decision: "idle" | "rearm" | "expire";
442
- seq: number;
443
- }, void, never, unknown>;
444
- type DeadlineDecisionCmd = CmdOf<typeof deadlineDecision>;
445
- /**
446
- * A predicate over a Msg that decides whether it re-arms the deadline.
447
- *
448
- * The argument is `Readonly<M>` and the result is `boolean`: this is the
449
- * STRONGEST purity TS can express here. `Readonly<M>` removes the most common
450
- * impurity at compile time — the predicate cannot reassign the Msg's own
451
- * fields — and `boolean` pins the return so a side-effecting `(msg) => { … }`
452
- * with an implicit `undefined`/`void` return is rejected.
453
- *
454
- * What the type system CANNOT encode (TS has no effect tracking): observational
455
- * purity. A body that reads `Date.now()`, calls `Math.random()`, performs IO,
456
- * or closes over and mutates external state still type-checks. Those remain a
457
- * CONVENTION enforced by review, not the compiler — the predicate runs inside
458
- * the pure merged `update` (invariant 2), so it must be a pure function of the
459
- * Msg alone: no clock, no RNG, no IO, no captured mutable state.
460
- */
461
- type ProgressPredicate<M extends {
462
- type: string;
463
- }> = (msg: Readonly<M>) => boolean;
464
- /**
465
- * The deadline knob. `ms` is the inactivity window; `progress` is an OPTIONAL
466
- * predicate picking which base Msgs count as activity (default: EVERY base Msg
467
- * re-arms). The predicate runs INSIDE the pure merged `update`, so it must be a
468
- * pure function of the Msg — see {@link ProgressPredicate} for what the type
469
- * enforces vs. what stays a convention.
470
- */
471
- interface DeadlineConfig<M extends {
472
- type: string;
473
- }> {
474
- /** The inactivity window in milliseconds. Auto-fail after `ms` with no progress. */
475
- readonly ms: number;
476
- /**
477
- * Predicate picking which base Msgs re-arm the timer. Default: every base Msg
478
- * counts as progress. Pure — a function of the Msg alone (see
479
- * {@link ProgressPredicate}).
480
- */
481
- readonly progress?: ProgressPredicate<M>;
482
- }
483
- /**
484
- * Wrap `base` with an inactivity deadline. Returns a NEW `Machine` over the
485
- * composed Model `{ base, $deadline }`, with the base's Msgs/Cmds/Subs extended
486
- * by the wrapper's own (`$deadline:exceeded` Msg, `$deadline:decision` Cmd,
487
- * `$deadline:timeout` Sub).
488
- *
489
- * The composed machine:
490
- * - `init` rehydrates the base (honoring the `[loaded, []]` contract) and
491
- * seeds `$deadline: { phase: "armed", seq: 0 }`. Base init Cmds pass
492
- * through unchanged.
493
- * - `update` (Reducer form) runs the base reducer for base Msgs — base Cmds
494
- * pass through UNCHANGED — and on an accepted progress Msg bumps `seq`
495
- * (re-arm). The `$deadline:exceeded` Msg cell flips `phase` to `exceeded`.
496
- * Every transition appends a `$deadline:decision` marker Cmd.
497
- * - `subscriptions` is the base's, plus a `$deadline:timeout` Sub keyed on
498
- * `seq` while `phase === "armed"`.
499
- * - `subscribe` is the base's, plus the `$deadline:timeout` cell.
500
- * - `interpret` is the base's, plus a no-op `$deadline:decision` handler.
501
- *
502
- * @param base any `Machine<S, M, C, U, Ctx>`.
503
- * @param config the deadline knob (`ms` window + optional `progress` predicate).
504
- */
505
- declare function withDeadline<S, M extends {
506
- type: string;
507
- }, C extends Cmd, U extends Sub, Ctx>(base: Machine<S, M, C, U, Ctx>, config: DeadlineConfig<M>): Machine<DeadlineModel<S>, M | DeadlineExceededMsg, C | DeadlineDecisionCmd, U | DeadlineTimeoutSub, Ctx>;
508
-
509
- /**
510
- * The `withResilience` knob. Extends resilient-call's `ResilientConfig` (every
511
- * brick optional — omit a brick, omit its gate) with the two fields the wrapper
512
- * needs that the bare knob does not:
513
- *
514
- * - `target` — the `Cmd.type` discriminant of the ONE base Cmd this wrapper
515
- * hardens. Every other base Cmd passes through untouched.
516
- * - `keyOf` — OPTIONAL. Derives the per-call resilience `key` from the target
517
- * base Cmd, so distinct logical calls (distinct urls, distinct ids) get
518
- * independent retry / cache state. Pure — it runs inside the merged
519
- * `update`, so it must NOT read the clock / RNG. Defaults to a single
520
- * shared key (`target`), i.e. one logical call at a time.
521
- */
522
- interface ResilienceConfig<TC extends Cmd, TM extends {
523
- type: string;
524
- }> extends ResilientConfig {
525
- /** The base `Cmd.type` to make resilient. */
526
- readonly target: TC["type"];
527
- /** Optional per-call key deriver. Pure. Defaults to the target type itself. */
528
- readonly keyOf?: (cmd: TC) => string;
529
- /**
530
- * Extracts the real wall-clock time (ms) the TRIGGERING base Msg carries as
531
- * data — the time-as-data convention `resilient-call` expects on `attempt`.
532
- *
533
- * The merged `update` is PURE: it cannot read `Date.now()` (rule 5). The COLD
534
- * attempt's gate (the very first `attempt` for a target Cmd in a transition)
535
- * still needs a real instant — the breaker compares `at` against its recorded
536
- * `openedAtMs`, the cache against its write `at`, the bucket against its last
537
- * refill `at`, and the deadline cap anchors at `at + deadline.ms`. Fabricating
538
- * `at = 0` is the betrayal: a cold attempt after a real-time breaker trip then
539
- * computes cooldown = `0 - realTripTime < 0` forever, so the breaker NEVER
540
- * recovers, and a `0`-anchored deadline brick fires immediately.
541
- *
542
- * So the base Msg that drove this transition MUST carry its own wall time as
543
- * data, and `at` reads it off that Msg. The merged update passes
544
- * `at(currentBaseMsg)` into `rc.attempt` for every target Cmd that transition
545
- * emitted — real time enters the cold gate as Msg data, never `0`.
546
- *
547
- * REQUIRED whenever any time-sensitive brick (`circuit`, `rateLimit`, `cache`,
548
- * `deadline`) is configured — `withResilience` THROWS at construction if such
549
- * a brick is set and `at` is absent (errors are data: the cold gate needs real
550
- * time, refuse to build a breaker that can never recover). OPTIONAL when only
551
- * `retry` is configured: retry backoff reads its time off the result / timer
552
- * Msgs (`$resilience:err.at`, `$resilience:timer.atMs`), never the cold attempt
553
- * — so a `0` cold `at` is harmless there. Pure: it runs inside the merged
554
- * `update`, so it must NOT read the clock / RNG.
555
- */
556
- readonly at?: (msg: TM) => number;
557
- }
558
- /**
559
- * The composed Model. The base machine's state nests under `base`; the wrapper
560
- * owns the NAMED `$resilience` slice — resilient-call's `ResilientState` keyed
561
- * by the per-call `key`, with `I = TC` (the original target base Cmd is the
562
- * port input) and `R = unknown` (the base interpret handler's resolution — the
563
- * wrapper never inspects it; it routes Ok/Err and delivers a Msg to the base).
564
- * Plain data → round-trips through `JSON.parse(JSON.stringify(...))` iff the
565
- * base state does.
566
- */
567
- interface ResilienceModel<S, TC extends Cmd> {
568
- readonly base: S;
569
- readonly $resilience: ResilientState<TC, unknown>;
570
- }
571
- /**
572
- * The carrier Cmd the wrapper emits when the gate ADMITS a target base Cmd. It
573
- * RETAGS the original base Cmd into `input` — the base Cmd is plain data, so no
574
- * closure (invariant 3). The interpret handler unwraps `input` and runs it
575
- * through the BASE interpret for that Cmd type. `key` indexes the resilient
576
- * call this run belongs to.
577
- */
578
- declare function resilienceRunCmdDef<TC extends Cmd, TM>(): CmdDef<"$resilience:run", {
579
- readonly key: string;
580
- /** The ORIGINAL base Cmd, retagged — never swallowed. */
581
- readonly input: TC;
582
- }, void | TM, {
583
- readonly [detail: string]: unknown;
584
- readonly _tag: "deadline_exceeded";
585
- } | {
586
- readonly [detail: string]: unknown;
587
- readonly _tag: "base_rejected";
588
- }, unknown>;
589
- type ResilienceRunCmd<TC extends Cmd> = CmdOf<ReturnType<typeof resilienceRunCmdDef<TC, unknown>>>;
590
- /**
591
- * The success Msg the `$resilience:run` handler dispatches back when the base
592
- * interpret resolved OK. Routes to `succeed`, then `result` — the base
593
- * handler's follow-up, when it is a Msg — is folded through the base reducer.
594
- * `at` is stamped at the interpret boundary (the one permitted clock read).
595
- */
596
- type ResilienceOkMsg = {
597
- readonly type: "$resilience:ok";
598
- readonly key: string;
599
- readonly result: unknown;
600
- readonly at: number;
601
- };
602
- /**
603
- * The error Msg the `$resilience:run` handler dispatches back when the base
604
- * interpret threw / rejected. Routes to `fail` (trip the breaker, then back off
605
- * or settle). `at` is stamped at the interpret boundary.
606
- */
607
- type ResilienceErrMsg = {
608
- readonly type: "$resilience:err";
609
- readonly key: string;
610
- readonly error: unknown;
611
- readonly at: number;
612
- };
613
- /**
614
- * The retry / deadline timer Msg the `$resilience:timer` Sub dispatches when
615
- * the wall clock crosses the armed instant. Routes to `onTimer`. `id` is the
616
- * `$resilience:`-namespaced timer id; `atMs` is the fire instant (Msg data, the
617
- * clock that drove it lives in the Sub).
618
- */
619
- type ResilienceTimerMsg = {
620
- readonly type: "$resilience:timer";
621
- readonly id: string;
622
- readonly atMs: number;
623
- };
624
- /** Every Msg the wrapper adds to the base's Msg union. */
625
- type ResilienceMsg = ResilienceOkMsg | ResilienceErrMsg | ResilienceTimerMsg;
626
- /** Every Cmd the wrapper adds to the base's Cmd union. */
627
- type ResilienceCmd<TC extends Cmd> = ResilienceRunCmd<TC>;
628
- /** The Sub the wrapper adds — a deadline-style timer in the `$resilience` family. */
629
- type ResilienceTimerSub = Sub<"$resilience:timer"> & {
630
- readonly atMs: number;
631
- };
632
- /**
633
- * Wrap `base` so its `config.target` Cmd is run through the resilient-call
634
- * concern (cache → circuit → rate-limit → retry, deadline-capped). Returns a
635
- * NEW `Machine` over the composed Model `{ base, $resilience }`, with the
636
- * base's Msgs/Cmds/Subs/Ctx extended by the wrapper's own.
637
- *
638
- * @param base any `Machine<S, M, C, U, Ctx>`.
639
- * @param config the resilience knob: `target`, the optional bricks, `keyOf`.
640
- * @param rng injected backoff jitter source. Pass a fixed `() => 0.5` in
641
- * tests to pin retry delays; defaults to `Math.random` (read only
642
- * at the verb boundary, never inside the merged `update`).
643
- */
644
- declare function withResilience<S, M extends {
645
- type: string;
646
- }, C extends Cmd, U extends Sub, Ctx>(base: Machine<S, M, C, U, Ctx>, config: ResilienceConfig<C, M>, rng?: () => number): Machine<ResilienceModel<S, C>, M | ResilienceMsg, C | ResilienceCmd<C>, U | ResilienceTimerSub, Ctx>;
647
-
648
- /**
649
- * The datum handed to the sink. The default projector emits `{ seq, msgType }`;
650
- * a custom `event` projector may return any extra fields. `at` is OPTIONAL and
651
- * plain data — it is stamped at the interpret boundary by the `clock` port, not
652
- * inside the (pure, clock-free) merged `update`. Every field is JSON-round-trip
653
- * serializable so a recorded telemetry stream stays durable.
654
- */
655
- interface TelemetryEvent {
656
- /** Monotonic event counter — equals `$telemetry.seq` after the transition. */
657
- readonly seq: number;
658
- /** The `Msg.type` discriminant that drove this transition. */
659
- readonly msgType: string;
660
- /**
661
- * Wall-clock instant the event was emitted, ms since epoch. Absent until the
662
- * interpret boundary stamps it (the `clock` port). Optional because the
663
- * merged `update` is clock-free — a verb must never read `Date.now()`.
664
- */
665
- readonly at?: number;
666
- }
667
- /**
668
- * The wrapper's Model slice. A monotonic event counter — minimal but real, so
669
- * the named-slice mechanism is exercised for the richer-slice wrappers that
670
- * follow. `seq` equals the number of base Msgs folded so far: after replaying
671
- * `N` msgs, `$telemetry.seq === N`. Plain data → serializes into a `Store<S>`.
672
- */
673
- interface TelemetrySlice {
674
- readonly seq: number;
675
- }
676
- /**
677
- * The composed Model. The base machine's state is nested under `base`; the
678
- * wrapper's state lives in the NAMED `$telemetry` slice — never hidden in a
679
- * closure. Both fields are plain data, so the whole composed Model round-trips
680
- * through `JSON.parse(JSON.stringify(...))` iff the base state does.
681
- */
682
- interface TelemetryModel<S> {
683
- readonly base: S;
684
- readonly $telemetry: TelemetrySlice;
685
- }
686
- /**
687
- * The fire-and-forget Cmd the merged `update` appends after every base
688
- * transition. It carries the projected `event` as plain data (invariant 3 —
689
- * no closure). The interpret handler hands `event` to the sink and dispatches
690
- * NOTHING back, so there is no feedback loop.
691
- */
692
- declare const telemetryEmit: CmdDef<"$telemetry:emit", {
693
- event: TelemetryEvent;
694
- }, void, never, TelemetryPorts>;
695
- type TelemetryEmitCmd = CmdOf<typeof telemetryEmit>;
696
- /**
697
- * The side-effecting ports the wrapper adds to `Ctx`. The sink (PostHog / Sentry
698
- * bridge) lives at the interpret boundary, never in a verb. `clock` is the
699
- * optional wall-clock source used to stamp `event.at` at that same boundary —
700
- * pass `Date.now` in production, a fixed `() => 1000` in tests; omit it to leave
701
- * `at` unset.
702
- */
703
- interface TelemetryPorts {
704
- /** The side-effecting sink. Fire-and-forget — its result is never awaited into a Msg. */
705
- readonly telemetrySink: (event: TelemetryEvent) => void | Promise<void>;
706
- /** Optional clock for stamping `event.at` at the interpret boundary. */
707
- readonly clock?: () => number;
708
- }
709
- /**
710
- * The telemetry knob. `event` is an OPTIONAL projector mapping
711
- * `(msg, prev, next)` to a `TelemetryEvent`; omit it and the default emits
712
- * `{ seq, msgType }` where `seq` is the post-transition counter. The projector
713
- * runs INSIDE the pure merged `update`, so it must not read the clock — stamp
714
- * `at` at the sink boundary via the `clock` port instead.
715
- */
716
- interface TelemetryConfig<S, M extends {
717
- type: string;
718
- }> {
719
- readonly event?: (msg: M, prev: TelemetryModel<S>, next: TelemetryModel<S>) => TelemetryEvent;
720
- }
721
- /**
722
- * Wrap `base` with observe-only telemetry. Returns a NEW `Machine` over the
723
- * composed Model `{ base, $telemetry }`, with the base's Msgs/Cmds/Subs/Ctx
724
- * extended by the wrapper's own.
725
- *
726
- * The composed machine:
727
- * - `init` rehydrates the base (honoring the `[loaded, []]` contract) and
728
- * seeds `$telemetry: { seq: 0 }`. Base init Cmds pass through unchanged.
729
- * - `update` (Reducer form, keyed by every base `Msg.type`) runs the base
730
- * reducer, increments `seq`, and appends a `$telemetry:emit` Cmd carrying
731
- * the projected event. Base Cmds pass through UNCHANGED — the observe-only
732
- * property.
733
- * - `subscriptions` / `subscribe` are the base's, verbatim (no timers).
734
- * - `interpret` is `{ ...base.interpret, "$telemetry:emit": sink-handler }`.
735
- *
736
- * @param base any `Machine<S, M, C, U, Ctx>`.
737
- * @param config the telemetry knob (optional `event` projector).
738
- */
739
- declare function withTelemetry<S, M extends {
740
- type: string;
741
- }, C extends Cmd, U extends Sub, Ctx>(base: Machine<S, M, C, U, Ctx>, config?: TelemetryConfig<S, M>): Machine<TelemetryModel<S>, M, C | TelemetryEmitCmd, U, Ctx & TelemetryPorts>;
742
-
743
- export { type AuthedCall, type AuthedCmd, type AuthedConfig, type AuthedPorts, type AuthedState, type DeadlineConfig, type DeadlineDecisionCmd, type DeadlineExceededMsg, type DeadlineModel, type DeadlineSlice, DeadlineSub, type DeadlineTimeoutSub, FailMsg, type ProgressPredicate, type RefreshTokenCmd, type ResilienceCmd, type ResilienceConfig, type ResilienceErrMsg, type ResilienceModel, type ResilienceMsg, type ResilienceOkMsg, type ResilienceRunCmd, type ResilienceTimerMsg, type ResilienceTimerSub, ResilientConfig, ResilientPorts, ResilientState, ResilientTimerMsg, RetryExhaustedError, type RetryToSuccessOptions, RunCmd, SucceedMsg, type TelemetryConfig, type TelemetryEmitCmd, type TelemetryEvent, type TelemetryModel, type TelemetryPorts, type TelemetrySlice, type Token, type TokenRefresh, type TokenRefreshConfig, type TokenRefreshFailedMsg, type TokenRefreshMsg, type TokenRefreshPorts, type TokenRefreshedMsg, type TokenState, type Unauthorized, type UnauthorizedError, createAuthedCall, createTokenRefresh, deadlineDecision, deadlineExceededMsg, initTokenRefresh, liftAuthed, refreshToken, refreshTokenCmd, resilienceRunCmdDef, retryToSuccess, telemetryEmit, tokenRefreshFailedMsg, tokenRefreshedMsg, withDeadline, withResilience, withTelemetry };
351
+ export { type AuthedCall, type AuthedCmd, type AuthedConfig, type AuthedState, DeadlineSub, FailMsg, type RefreshTokenCmd, ResilientConfig, ResilientState, ResilientTimerMsg, RetryExhaustedError, type RetryToSuccessOptions, RunCmd, SucceedMsg, type Token, type TokenRefresh, type TokenRefreshConfig, type TokenRefreshFailedMsg, type TokenRefreshMsg, type TokenRefreshedMsg, type TokenState, type Unauthorized, type UnauthorizedError, createAuthedCall, createTokenRefresh, initTokenRefresh, liftAuthed, refreshToken, refreshTokenCmd, retryToSuccess };