@demlik/tea 0.1.2 → 0.3.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 (212) hide show
  1. package/README.md +49 -0
  2. package/dist/agent/index.d.ts +16 -770
  3. package/dist/agent/index.js +18 -16
  4. package/dist/authed-call/index.d.ts +3 -3
  5. package/dist/authed-call/index.js +22 -36
  6. package/dist/authed-call/index.js.map +1 -1
  7. package/dist/await-terminal/index.d.ts +2 -2
  8. package/dist/await-terminal/index.js +2 -2
  9. package/dist/batch-window/index.d.ts +3 -3
  10. package/dist/batch-window/index.js +3 -3
  11. package/dist/cache/index.d.ts +2 -2
  12. package/dist/cache/index.js +5 -2
  13. package/dist/{chunk-3545BOYL.js → chunk-25LBDCBC.js} +6 -5
  14. package/dist/chunk-25LBDCBC.js.map +1 -0
  15. package/dist/{chunk-IN33Q4VJ.js → chunk-2KNLKQVN.js} +3 -3
  16. package/dist/{chunk-IN33Q4VJ.js.map → chunk-2KNLKQVN.js.map} +1 -1
  17. package/dist/{chunk-MMH7CW5K.js → chunk-BP2R7TPP.js} +216 -157
  18. package/dist/chunk-BP2R7TPP.js.map +1 -0
  19. package/dist/chunk-C6QC273X.js +71 -0
  20. package/dist/chunk-C6QC273X.js.map +1 -0
  21. package/dist/{chunk-7W4LMPUW.js → chunk-CAXMQJJ3.js} +17 -24
  22. package/dist/chunk-CAXMQJJ3.js.map +1 -0
  23. package/dist/{chunk-UV6UWGEO.js → chunk-D736QUGF.js} +6 -5
  24. package/dist/chunk-D736QUGF.js.map +1 -0
  25. package/dist/chunk-EWJP3YYP.js +21 -0
  26. package/dist/chunk-EWJP3YYP.js.map +1 -0
  27. package/dist/{chunk-TGG26XMK.js → chunk-FV3Z5MBE.js} +10 -5
  28. package/dist/chunk-FV3Z5MBE.js.map +1 -0
  29. package/dist/chunk-G5E74IJB.js +8 -0
  30. package/dist/chunk-G5E74IJB.js.map +1 -0
  31. package/dist/{chunk-27N2SPTN.js → chunk-IXBKFQH5.js} +12 -11
  32. package/dist/chunk-IXBKFQH5.js.map +1 -0
  33. package/dist/{chunk-SQTCS44W.js → chunk-JFFVBEDI.js} +3 -3
  34. package/dist/{chunk-SQTCS44W.js.map → chunk-JFFVBEDI.js.map} +1 -1
  35. package/dist/chunk-LYLDCIPH.js +365 -0
  36. package/dist/chunk-LYLDCIPH.js.map +1 -0
  37. package/dist/{chunk-HJO6VNQI.js → chunk-MU6MCIAC.js} +3 -3
  38. package/dist/{chunk-HJO6VNQI.js.map → chunk-MU6MCIAC.js.map} +1 -1
  39. package/dist/{chunk-UYWUVEP6.js → chunk-MUUROGIH.js} +2 -2
  40. package/dist/chunk-MUUROGIH.js.map +1 -0
  41. package/dist/{chunk-EHIX7NYZ.js → chunk-MVY5DAMF.js} +4 -4
  42. package/dist/{chunk-EHIX7NYZ.js.map → chunk-MVY5DAMF.js.map} +1 -1
  43. package/dist/{chunk-LP7VQBRG.js → chunk-NPERUUUE.js} +76 -95
  44. package/dist/chunk-NPERUUUE.js.map +1 -0
  45. package/dist/{chunk-QLA76GIT.js → chunk-PBDYW2TU.js} +68 -9
  46. package/dist/chunk-PBDYW2TU.js.map +1 -0
  47. package/dist/{chunk-5VNWZADP.js → chunk-Q2UM7BXU.js} +18 -7
  48. package/dist/chunk-Q2UM7BXU.js.map +1 -0
  49. package/dist/chunk-RMX4EOQK.js +26 -0
  50. package/dist/chunk-RMX4EOQK.js.map +1 -0
  51. package/dist/{chunk-2YOE5PIS.js → chunk-S2EGRPCM.js} +8 -6
  52. package/dist/chunk-S2EGRPCM.js.map +1 -0
  53. package/dist/{chunk-ON24RKSE.js → chunk-S4O26D7B.js} +7 -14
  54. package/dist/chunk-S4O26D7B.js.map +1 -0
  55. package/dist/{chunk-3XJWC7VW.js → chunk-SK5JGUY7.js} +3 -3
  56. package/dist/{chunk-3XJWC7VW.js.map → chunk-SK5JGUY7.js.map} +1 -1
  57. package/dist/{chunk-5DEQ5I3U.js → chunk-TPGASTFF.js} +8 -10
  58. package/dist/chunk-TPGASTFF.js.map +1 -0
  59. package/dist/{chunk-SC3FAFZN.js → chunk-UF4MZSLT.js} +2 -2
  60. package/dist/chunk-UF4MZSLT.js.map +1 -0
  61. package/dist/{chunk-PS23H6KQ.js → chunk-VBUCHVCV.js} +6 -5
  62. package/dist/chunk-VBUCHVCV.js.map +1 -0
  63. package/dist/{chunk-S3FQN4SL.js → chunk-WGGAMW7Y.js} +191 -178
  64. package/dist/chunk-WGGAMW7Y.js.map +1 -0
  65. package/dist/chunk-ZJ5AOYBH.js +8 -0
  66. package/dist/chunk-ZJ5AOYBH.js.map +1 -0
  67. package/dist/{chunk-LEC4U6CX.js → chunk-ZVJZ72HY.js} +3 -3
  68. package/dist/{chunk-LEC4U6CX.js.map → chunk-ZVJZ72HY.js.map} +1 -1
  69. package/dist/circuit-breaker/index.d.ts +1 -0
  70. package/dist/circuit-breaker/index.js +1 -1
  71. package/dist/{core-BoB6t7dB.d.ts → core-42kapW0n.d.ts} +105 -6
  72. package/dist/deadline/index.d.ts +77 -11
  73. package/dist/deadline/index.js +3 -3
  74. package/dist/devtools/index.js +8 -28
  75. package/dist/devtools/index.js.map +1 -1
  76. package/dist/do/index.d.ts +483 -339
  77. package/dist/do/index.js +244 -214
  78. package/dist/do/index.js.map +1 -1
  79. package/dist/{durable-effects-CO9Uh971.d.ts → durable-effects-CFRngTNA.d.ts} +3 -3
  80. package/dist/extension/index.d.ts +25 -7
  81. package/dist/extension/index.js +4 -3
  82. package/dist/extension/index.js.map +1 -1
  83. package/dist/extension/react.js +4 -3
  84. package/dist/extension/react.js.map +1 -1
  85. package/dist/extension/subs/index.d.ts +2 -2
  86. package/dist/extension/subs/index.js +7 -10
  87. package/dist/extension/subs/index.js.map +1 -1
  88. package/dist/fan-out/index.d.ts +10 -10
  89. package/dist/fan-out/index.js +3 -3
  90. package/dist/idempotent-intake/index.d.ts +2 -2
  91. package/dist/idempotent-intake/index.js +3 -3
  92. package/dist/index.d.ts +50 -472
  93. package/dist/index.js +2 -2
  94. package/dist/llm-call/index.d.ts +3 -2
  95. package/dist/llm-call/index.js +12 -10
  96. package/dist/machine-B_BF4jij.d.ts +804 -0
  97. package/dist/machine-viz/index.d.ts +1 -1
  98. package/dist/machine-viz/index.js +2 -2
  99. package/dist/mem/index.d.ts +3 -2
  100. package/dist/mem/index.js.map +1 -1
  101. package/dist/monitored-run/index.d.ts +54 -30
  102. package/dist/monitored-run/index.js +7 -7
  103. package/dist/node/index.d.ts +3 -2
  104. package/dist/node/index.js +2 -3
  105. package/dist/node/index.js.map +1 -1
  106. package/dist/paginated-walk/index.d.ts +2 -2
  107. package/dist/paginated-walk/index.js +11 -10
  108. package/dist/parity/index.d.ts +6 -5
  109. package/dist/parity/index.js +5 -4
  110. package/dist/parity/index.js.map +1 -1
  111. package/dist/pbt/arbitraries/index.d.ts +1 -1
  112. package/dist/pbt/index.d.ts +1 -1
  113. package/dist/pbt/index.js +3 -3
  114. package/dist/pbt/index.js.map +1 -1
  115. package/dist/pbt/runners/index.d.ts +1 -1
  116. package/dist/pbt/runners/index.js +3 -3
  117. package/dist/poller/index.d.ts +59 -17
  118. package/dist/poller/index.js +56 -20
  119. package/dist/poller/index.js.map +1 -1
  120. package/dist/prediction/index.d.ts +1 -1
  121. package/dist/prediction/index.js +2 -2
  122. package/dist/pure/index.d.ts +1 -1
  123. package/dist/pure/index.js +2 -2
  124. package/dist/rate-limit/index.d.ts +2 -2
  125. package/dist/rate-limit/index.js +1 -1
  126. package/dist/react/index.d.ts +3 -2
  127. package/dist/react/index.js +2 -2
  128. package/dist/react/index.js.map +1 -1
  129. package/dist/reconciler/index.d.ts +2 -2
  130. package/dist/reconciler/index.js +13 -15
  131. package/dist/reconciler/index.js.map +1 -1
  132. package/dist/recorder/index.d.ts +20 -20
  133. package/dist/recorder/index.js +1 -1
  134. package/dist/resilient-call/index.d.ts +31 -6
  135. package/dist/resilient-call/index.js +10 -9
  136. package/dist/retry-backoff/index.d.ts +191 -14
  137. package/dist/retry-backoff/index.js +1 -1
  138. package/dist/retry-to-success/index.js +1 -1
  139. package/dist/runtime-types-gsog27b6.d.ts +337 -0
  140. package/dist/saga/index.d.ts +3 -2
  141. package/dist/saga/index.js +2 -2
  142. package/dist/saga/index.js.map +1 -1
  143. package/dist/snapshot/index.d.ts +1 -1
  144. package/dist/snapshot/index.js +3 -3
  145. package/dist/subs/index.d.ts +372 -4
  146. package/dist/subs/index.js +4 -1
  147. package/dist/testing/index.d.ts +2 -2
  148. package/dist/testing/index.js +2 -2
  149. package/dist/throttled-input/index.d.ts +2 -2
  150. package/dist/throttled-input/index.js +14 -13
  151. package/dist/throttled-input/index.js.map +1 -1
  152. package/dist/token-refresh/index.d.ts +1 -1
  153. package/dist/token-refresh/index.js +3 -3
  154. package/dist/trace-replay/index.d.ts +12 -7
  155. package/dist/trace-replay/index.js +4 -3
  156. package/dist/{types-B-8bcAp8.d.ts → types-KbL3W1mj.d.ts} +1 -1
  157. package/dist/with-deadline/index.d.ts +1 -1
  158. package/dist/with-deadline/index.js +2 -2
  159. package/dist/with-resilience/index.d.ts +21 -2
  160. package/dist/with-resilience/index.js +12 -23
  161. package/dist/with-resilience/index.js.map +1 -1
  162. package/dist/with-telemetry/index.d.ts +1 -1
  163. package/dist/with-telemetry/index.js +2 -2
  164. package/dist/work-queue/adapter.d.ts +2 -2
  165. package/dist/work-queue/adapter.js +2 -2
  166. package/dist/work-queue/index.d.ts +3 -2
  167. package/dist/work-queue/index.js +1 -1
  168. package/dist/work-queue/index.js.map +1 -1
  169. package/dist/work-queue/ops.d.ts +2 -2
  170. package/dist/work-queue/ops.js +1 -1
  171. package/dist/workflow/index.d.ts +51 -19
  172. package/dist/workflow/index.js +71 -52
  173. package/dist/workflow/index.js.map +1 -1
  174. package/package.json +4 -19
  175. package/dist/chunk-27N2SPTN.js.map +0 -1
  176. package/dist/chunk-2YOE5PIS.js.map +0 -1
  177. package/dist/chunk-3545BOYL.js.map +0 -1
  178. package/dist/chunk-5DEQ5I3U.js.map +0 -1
  179. package/dist/chunk-5VNWZADP.js.map +0 -1
  180. package/dist/chunk-6RGBKODV.js +0 -268
  181. package/dist/chunk-6RGBKODV.js.map +0 -1
  182. package/dist/chunk-7W4LMPUW.js.map +0 -1
  183. package/dist/chunk-DILMKOZ7.js +0 -91
  184. package/dist/chunk-DILMKOZ7.js.map +0 -1
  185. package/dist/chunk-K7Q23EQ4.js +0 -20
  186. package/dist/chunk-K7Q23EQ4.js.map +0 -1
  187. package/dist/chunk-LP7VQBRG.js.map +0 -1
  188. package/dist/chunk-MMH7CW5K.js.map +0 -1
  189. package/dist/chunk-NSDFA6M6.js +0 -198
  190. package/dist/chunk-NSDFA6M6.js.map +0 -1
  191. package/dist/chunk-ON24RKSE.js.map +0 -1
  192. package/dist/chunk-PS23H6KQ.js.map +0 -1
  193. package/dist/chunk-QLA76GIT.js.map +0 -1
  194. package/dist/chunk-S3FQN4SL.js.map +0 -1
  195. package/dist/chunk-SC3FAFZN.js.map +0 -1
  196. package/dist/chunk-TGG26XMK.js.map +0 -1
  197. package/dist/chunk-UV6UWGEO.js.map +0 -1
  198. package/dist/chunk-UYWUVEP6.js.map +0 -1
  199. package/dist/chunk-VLGARN6H.js +0 -202
  200. package/dist/chunk-VLGARN6H.js.map +0 -1
  201. package/dist/raft/demo.d.ts +0 -105
  202. package/dist/raft/demo.js +0 -172
  203. package/dist/raft/demo.js.map +0 -1
  204. package/dist/raft/index.d.ts +0 -548
  205. package/dist/raft/index.js +0 -7
  206. package/dist/raft/index.js.map +0 -1
  207. package/dist/raft/sim.d.ts +0 -222
  208. package/dist/raft/sim.js +0 -8
  209. package/dist/raft/sim.js.map +0 -1
  210. package/dist/raft/timeline.d.ts +0 -46
  211. package/dist/raft/timeline.js +0 -62
  212. package/dist/raft/timeline.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/throttled-input/index.ts"],"names":[],"mappings":";;;;;;;;;;;AAkQA,IAAM,cAAA,GAAiB,wBAAA;AAO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AA,GAChD;AACF","file":"index.js","sourcesContent":["/**\n * @demlik/tea/throttled-input — gate a high-frequency input stream into a\n * SETTLED, RATE-CAPPED, optionally DEDUPED sequence of emits, as a TEA knob: one\n * config object + a few pre-wired hooks you spread into your machine.\n *\n * Layering (the throttle-family map): `../throttle` and `../debounce` are the\n * two host-boundary PRIMITIVES — two distinct algorithms\n * (at-most-once-per-window vs collapse-a-burst) behind one signature shape.\n * THIS module is the third name but NOT a third primitive: a TEA machine\n * composed OVER them that re-exports both. Three exports, one layering — not\n * duplication. The reuse list below spells out composition vs reimplemented\n * semantic per sibling.\n *\n * What it reuses, and HOW (composition vs. reimplemented semantic — the two are\n * not the same, so this list keeps them apart):\n *\n * - `../cache` — COMPOSED directly. The DEDUPE / memoize layer is `../cache`'s\n * `TtlCache` plus its `get` / `set` / `initCache` ops, called at runtime —\n * not reinvented. While `cacheTtlMs` is set, an input whose `cacheKey` is\n * already cached and unexpired is served from the cache and emits NOTHING\n * (the downstream effect ran once for that key within its TTL); a fresh emit\n * writes the value into the cache so the next identical input within\n * `cacheTtlMs` is suppressed. The optional eviction Sub is the consumer's to\n * wire if they want memory reclaim (this knob's correctness needs only TTL\n * reads).\n * - `../deadline` — COMPOSED directly. The settle timer IS a `../deadline`\n * Sub: `subsFor` builds it via `deadlineSub`, and the subscribe cell +\n * Msg constructor are RE-EXPORTS of `../deadline`'s own (`subscribeDeadline`\n * → `subscribeThrottledInput`, `deadlineExceeded` → `throttledInputSettled`).\n * The timer lifecycle stays owned by `../deadline`; this knob redraws none\n * of it.\n * - `../throttle` / `../debounce` — TYPE + SEMANTIC reuse only, NOT composed.\n * Those siblings are host-boundary SINK transformers that hold a live\n * `setTimeout`; a `setTimeout` in a closure is exactly what a durable,\n * replayable knob must NOT hold. So their CODE is never called here. Instead\n * the RATE-cap semantic (\"at most once per `ms`\", leading-edge) and the\n * SETTLE semantic (\"wait until quiet\", trailing-edge) are REIMPLEMENTED as\n * pure Model state: `lastAt` is the durable rate cursor (half-open cutoff\n * `at - lastAt >= throttleMs`), and `pending` + the `../deadline` Sub realize\n * the debounce window inside `update`. The `throttle` / `debounce`\n * transformers themselves are RE-EXPORTED (the only reuse of their actual\n * code) so a consumer can pre-throttle / pre-coalesce a genuinely bursty\n * HOST event at the boundary BEFORE it ever becomes an `input` Msg — a\n * separate, optional escape hatch, not part of this knob's gates.\n *\n * \"Omit a brick, omit its gate\" (the resilient-call config rule): every gate\n * field is optional. Omit `throttleMs` → no rate cap (every input passes the\n * rate gate). Omit `debounceMs` → no settle wait (an input that clears the rate\n * gate emits IMMEDIATELY rather than being held). Omit `cacheTtlMs` → no cache\n * slice at all (the `cache` field is absent; no dedupe). A config with all three\n * omitted is a pass-through: `input` always emits.\n *\n * Why this is a knob and not hand-wired logic: the managed state (`lastAt`,\n * `pending`, `cache`) lives in the Model, so it survives DO eviction / reload\n * (durable) and every transition is still a Msg through `update` (replayable). A\n * closure holding a `setTimeout` and a mutable \"last value\" would break both —\n * banned. `input` / `onFlush` are PURE: time arrives as an `at` parameter, never\n * `Date.now()`; they return NEW slice values, never mutate.\n *\n * Typical wiring (combinator form):\n *\n * const search = createThrottledInput<string, Msg>({\n * debounceMs: 200, // wait for the user to stop typing\n * throttleMs: 1_000, // but never fire more than 1/s during a long burst\n * cacheTtlMs: 30_000, // skip a query repeated within 30s\n * cacheKey: (q) => q,\n * emit: (q) => ({ type: \"RunSearch\", query: q }),\n * });\n *\n * // Model: { search: ThrottledInput<string>, ... }\n * // init: (loaded) => [loaded ?? { search: search.init(), ... }, []]\n * // update cells:\n * // QueryTyped: (s, m) => mapInput(s, search.input(s.search, m.value, m.at))\n * // SettleFired: (s, m) => mapInput(s, search.onFlush(s.search, m.atMs))\n * // subscriptions: (s) => search.subs(s.search)\n * // subscribe: { ...search.handlers() }\n *\n * where `mapInput(s, [slice, cmds]) => [{ ...s, search: slice }, cmds]` lifts the\n * slice transition into the consumer's Model. The `RunSearch` Cmd's interpret\n * handler is the consumer's — it is where the settled input meets I/O.\n *\n * NOT a substrate primitive: it depends only on sibling subpaths (`../throttle`,\n * `../debounce`, `../cache`, `../deadline`) and the core `Cmd` / `Sub` types.\n * Consumers reach it via the `@demlik/tea/throttled-input` subpath; the L1\n * escape hatch is those sibling subpaths threaded by hand. NOT exported from the\n * package root — same one-shape-per-package rule as `batch-window` and `poller`.\n */\n\nimport {\n get as cacheGet,\n set as cacheSet,\n initCache,\n type TtlCache,\n} from \"../cache\";\nimport { type DeadlineSub, deadlineSub } from \"../deadline\";\nimport type { Cmd, Sub } from \"../index\";\n\n// `../throttle` + `../debounce` — host-boundary pre-transformers (see file\n// header). Re-exported so a consumer that wants to throttle/debounce a bursty\n// HOST source BEFORE it becomes an `input` Msg reaches them from the same\n// import as the durable gate.\nexport { type Debounced, debounce } from \"../debounce\";\nexport { type Throttled, throttle } from \"../throttle\";\n\n/**\n * The gate fields every throttled-input config shares, regardless of whether\n * dedupe is on. The two dedupe variants below extend this with mutually\n * exclusive cache fields.\n *\n * `emit` is a pure Cmd CONSTRUCTOR, not a closure-with-state: it maps a settled\n * value to the single Cmd the runtime performs when the gates let a value\n * through. Keeping it `(value) => Cmd` (not `(value) => void`) is what keeps the\n * trigger replayable — the emit is a Cmd in the transition's output, never a\n * side effect inside the verb (mirrors `batch-window`'s `flush`).\n */\ninterface ThrottledInputGates<V, C extends Cmd> {\n /**\n * Rate cap, in milliseconds. An input that lands within `throttleMs` of the\n * last EMIT (`at - lastAt < throttleMs`) is dropped from immediate firing —\n * the leading-edge \"at most once per `throttleMs`\" rate-cap rule, applied to\n * emits. The half-open cutoff (`>=` passes) matches `../throttle` and\n * `../cache`'s window-edge convention. Omit for no rate cap.\n *\n * Interacts with `debounceMs`: when both are set, a rate-blocked input is\n * still HELD as `pending` (so the settle timer eventually trails it out at a\n * legal moment) rather than silently dropped — the trailing-edge guarantee\n * that the FINAL sample of a window is never lost.\n */\n readonly throttleMs?: number;\n /**\n * Settle wait, in milliseconds. An input that clears the rate gate is not\n * emitted immediately; it is held as `pending` and a debounce deadline is\n * armed at `pendingAt + debounceMs`. A fresh input re-arms (slides) the\n * window. `onFlush` emits the pending value when the window finally expires.\n * Omit for no settle wait — a passing input emits on arrival.\n */\n readonly debounceMs?: number;\n /**\n * Map a settled value to the single Cmd the runtime performs. Called with the\n * value the gates let through; the returned Cmd is what `input` / `onFlush`\n * emit. PURE constructor — no I/O, no clock; the I/O happens later in the\n * consumer's interpret handler for the returned Cmd.\n */\n readonly emit: (value: V) => C;\n}\n\n/**\n * Configuration for a throttled input — the knob. Pure config, no mutable state\n * (the `ThrottledInput<V>` slice carries that). One config object is shared\n * across every input of one logical stream (often a module-scope const).\n *\n * A DISCRIMINATED UNION on the presence of dedupe, so the type system makes a\n * cache-key collision UNREPRESENTABLE (\"omit a brick, omit its gate\"):\n *\n * - **No dedupe** (`ThrottledInputNoCache`): `cacheTtlMs` absent ⇒ no cache\n * slice, no dedupe. `cacheKey` is statically forbidden here (`never`) — a\n * key with no cache to feed is dead config, so the type rejects it rather\n * than silently ignoring it.\n * - **Dedupe** (`ThrottledInputWithCache`): `cacheTtlMs` set ⇒ `cacheKey` is\n * REQUIRED. There is no `String(value)` default to fall back to, so a\n * structured value can NEVER collapse two distinct values to one slot (the\n * `\"[object Object]\"` collision). The consumer must state the identity that\n * keys the cache; a primitive stream still trivially passes `(v) => v` /\n * `String`, but it does so EXPLICITLY.\n */\nexport type ThrottledInputConfig<V, C extends Cmd> =\n | ThrottledInputNoCache<V, C>\n | ThrottledInputWithCache<V, C>;\n\n/**\n * The no-dedupe config variant: gates only, no cache. `cacheTtlMs` is absent\n * and `cacheKey` is statically `never` so a stray key (which would feed no\n * cache) is a type error, not a silently-ignored field.\n */\nexport interface ThrottledInputNoCache<V, C extends Cmd>\n extends ThrottledInputGates<V, C> {\n readonly cacheTtlMs?: undefined;\n readonly cacheKey?: never;\n}\n\n/**\n * The dedupe config variant: a per-entry TTL plus a REQUIRED `cacheKey`. An\n * input whose `cacheKey` is already cached and unexpired emits NOTHING (the\n * downstream effect ran once for that key within its TTL); a fresh emit writes\n * the value into the cache.\n *\n * `cacheKey` is required (no `String(value)` default) precisely so a structured\n * value cannot silently collide — the consumer names the identity, the cache\n * keys on exactly that.\n */\nexport interface ThrottledInputWithCache<V, C extends Cmd>\n extends ThrottledInputGates<V, C> {\n /**\n * Dedupe / memoize TTL, in milliseconds. An input whose `cacheKey` is already\n * cached and unexpired emits NOTHING; a fresh emit writes the value into the\n * cache so the next identical input within `cacheTtlMs` is suppressed.\n */\n readonly cacheTtlMs: number;\n /**\n * Key a value for the dedupe cache. REQUIRED whenever `cacheTtlMs` is set:\n * there is no `String(value)` fallback, so a structured value's identity is\n * always the consumer's explicit choice and two distinct values can never\n * collapse to one slot. A primitive stream passes `(v) => v` / `String`.\n */\n readonly cacheKey: (value: V) => string;\n}\n\n/**\n * The Model slice a throttled input owns — its visible slice (the knob\n * principle: managed state lives in the Model, never a closure, so it is durable\n * and replayable).\n *\n * - `lastAt` — the `at` of the most recent EMIT, or `null` before the first\n * emit. The `../throttle` rate cap measures against it: an input\n * within `throttleMs` of `lastAt` is rate-blocked. Persisted so a\n * resumed gate keeps its rate cursor.\n * - `pending` — the value HELD for the settle (debounce) window, paired with the\n * `at` it was held (the anchor the deadline targets), or `null`\n * when nothing is waiting. The single source of truth for \"is a\n * settle window open?\" — the debounce timer Sub arms iff this is\n * non-null.\n * - `cache` — the `../cache` TTL store backing dedupe, present IFF\n * `cacheTtlMs` is configured. Absent (the field omitted) for a\n * gate with no dedupe — no per-op cost, nothing to serialize.\n */\nexport interface ThrottledInput<V> {\n readonly lastAt: number | null;\n readonly pending: PendingInput<V> | null;\n readonly cache?: TtlCache<V>;\n}\n\n/**\n * A value held for the settle window: the `value` itself and the `at` it was\n * held (the anchor the debounce deadline targets, `at + debounceMs`). A distinct\n * type (not a bare `V`) because `V` may itself be `null` — a present-but-null\n * value is still a real pending input, distinct from \"nothing pending\", exactly\n * the `null`-sentinel discipline `../throttle` / `../debounce` use for their\n * `pendingArgs`.\n */\nexport interface PendingInput<V> {\n readonly value: V;\n readonly at: number;\n}\n\n/**\n * The Sub variant a throttled input's settle timer produces — a `../deadline`\n * Sub (so the window fires at the correct ABSOLUTE moment even after a late\n * subscribe / rehydrate, and so a consumer running several gates routes each by\n * `id`). `atMs` is the absolute settle-by instant (`pendingAt + debounceMs`).\n */\nexport type ThrottledInputSub = DeadlineSub;\n\n/**\n * The stable Sub id the gate arms its settle deadline under. A single gate arms\n * exactly one settle timer at a time, so one id suffices; a consumer running\n * several gates on one machine namespaces them by composing the knob under\n * distinct slices with distinct ids (the `subs(state, id)` parameter).\n */\nconst DEFAULT_SUB_ID = \"throttled-input:settle\";\n\n/**\n * The starting slice: no prior emit, nothing pending. The `cache` field is\n * seeded only when `cacheTtlMs` is configured (see `createThrottledInput`); the\n * free `initThrottledInput` leaves it absent (the no-dedupe shape).\n */\nexport function initThrottledInput<V>(): ThrottledInput<V> {\n return { lastAt: null, pending: null };\n}\n\n/**\n * Resolve a value's cache key under a DEDUPE config. PURE. Takes the narrowed\n * `ThrottledInputWithCache` (not the union) because `cacheKey` is only present —\n * and only meaningful — when dedupe is on; there is no `String(value)` default\n * to fall back to, so a structured value's identity is always the consumer's\n * explicit choice and two distinct values can never collapse to one slot.\n */\nfunction keyOf<V, C extends Cmd>(\n config: ThrottledInputWithCache<V, C>,\n value: V,\n): string {\n return config.cacheKey(value);\n}\n\n/**\n * Narrow `config` to its dedupe variant iff a cache slice is actually wired —\n * `cacheTtlMs` set AND a `cache` store present. Returns the narrowed config\n * (carrying the required `cacheKey`) or `null` when no dedupe is configured.\n * The single place the union is discriminated, so `isCacheHit` / `commitEmit`\n * share one narrowing rather than re-deriving the predicate.\n */\nfunction cacheConfig<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n): ThrottledInputWithCache<V, C> | null {\n return config.cacheTtlMs !== undefined && state.cache !== undefined\n ? config\n : null;\n}\n\n/**\n * Whether `value` is a cache HIT under `config` at `at` — present and unexpired.\n * PURE — reads only. Always `false` when `cacheTtlMs` is unset or no `cache`\n * slice exists (no dedupe configured), so the dedupe gate is a no-op for an\n * unconfigured gate.\n */\nfunction isCacheHit<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n value: V,\n at: number,\n): boolean {\n const cached = cacheConfig(config, state);\n if (cached === null || state.cache === undefined) return false;\n return cacheGet(state.cache, keyOf(cached, value), at) !== undefined;\n}\n\n/**\n * Emit `value` at clock `at`: bump the rate cursor, refresh the dedupe cache,\n * and clear any pending hold. PURE. The single place an emit's bookkeeping\n * lives, shared by `input` (immediate emit) and `onFlush` (trailing emit) so the\n * two paths can never drift on what an emit updates.\n *\n * - `lastAt` advances to `at` — the next input is rate-measured against this\n * emit, the `../throttle` window cursor.\n * - `cache` (when configured) records `value` under its key with `cacheTtlMs`\n * from `at` — so the next identical input within the TTL is suppressed.\n * - `pending` clears — the value just went out; nothing is waiting.\n */\nfunction commitEmit<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n value: V,\n at: number,\n): readonly [ThrottledInput<V>, readonly C[]] {\n const cached = cacheConfig(config, state);\n const cache =\n cached !== null && state.cache !== undefined\n ? cacheSet(\n state.cache,\n keyOf(cached, value),\n value,\n at,\n cached.cacheTtlMs,\n )\n : state.cache;\n const next: ThrottledInput<V> = {\n ...state,\n lastAt: at,\n pending: null,\n ...(cache !== undefined ? { cache } : {}),\n };\n return [next, [config.emit(value)]];\n}\n\n/**\n * Feed a new input `value` arriving at clock `at` through the gates. PURE.\n *\n * The gate order is DEDUPE → RATE → SETTLE (each skipped when its config field\n * is omitted), the same cache-first-then-gate order `resilient-call` uses (a hit\n * short-circuits before the expensive path):\n *\n * 1. **Dedupe** (`cacheTtlMs` set): if `value`'s key is cached and unexpired,\n * suppress — return the slice UNCHANGED (no emit, no pending, no re-arm).\n * The downstream effect already ran for this key within its TTL.\n * 2. **Rate** (`throttleMs` set): if `at` is within `throttleMs` of the last\n * emit (`at - lastAt < throttleMs`), this input is rate-blocked.\n * - With `debounceMs` set → HOLD it as `pending` (the trailing edge: the\n * settle timer will emit it at a legal moment, so the final sample is\n * never lost). The deadline `subs` arms targets `at + debounceMs`.\n * - Without `debounceMs` → DROP it (pure rate cap, no catch-up).\n * 3. **Settle** (`debounceMs` set): the input cleared the rate gate. HOLD it\n * as `pending` and let the debounce window slide; `onFlush` emits it once\n * the window expires. A fresh input before expiry overwrites `pending` (the\n * trailing edge fires with the LAST value, the `../debounce` default).\n * 4. **Pass-through**: no `debounceMs`, cleared the rate gate → EMIT now.\n *\n * @param config the knob (the three optional gates + `emit`)\n * @param state the current slice\n * @param value the input value\n * @param at the arrival instant (epoch ms) — the caller stamps it; the verb\n * never reads the clock\n */\nexport function input<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n value: V,\n at: number,\n): readonly [ThrottledInput<V>, readonly C[]] {\n // 1. Dedupe gate — a cached, unexpired key short-circuits everything.\n if (isCacheHit(config, state, value, at)) {\n return [state, []];\n }\n\n // 2. Rate gate — half-open cutoff (`>=` passes). `lastAt === null` (no prior\n // emit) always passes: the first input is never rate-blocked. Shared with\n // `onFlush` via `rateBlockedAt` so the arrival and trailing-edge paths agree\n // on the window.\n if (rateBlockedAt(config, state, at)) {\n // With a settle window, a rate-blocked input is HELD (trailing edge) so it\n // emits at the next legal moment; without one, it is a pure drop.\n if (config.debounceMs !== undefined) {\n return [{ ...state, pending: { value, at } }, []];\n }\n return [state, []];\n }\n\n // 3. Settle gate — passed the rate gate; if a debounce window is configured,\n // hold the value and (re)arm the settle deadline rather than emit now.\n if (config.debounceMs !== undefined) {\n return [{ ...state, pending: { value, at } }, []];\n }\n\n // 4. Pass-through — no settle wait, cleared the rate gate: emit immediately.\n return commitEmit(config, state, value, at);\n}\n\n/**\n * Whether emitting at clock `at` would breach the rate cap — `at` lands within\n * `throttleMs` of the last emit (`at - lastAt < throttleMs`). PURE — reads only.\n * Always `false` when `throttleMs` is unset (no rate cap) or before the first\n * emit (`lastAt === null`), so an unconfigured / never-fired gate never holds on\n * the rate gate. The single rate-gate predicate, shared by `input` (drop / hold\n * on arrival) and `onFlush` (re-hold a still-early trailing edge) so the two\n * paths can never drift on what \"within the rate window\" means.\n */\nfunction rateBlockedAt<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n at: number,\n): boolean {\n return (\n config.throttleMs !== undefined &&\n state.lastAt !== null &&\n at - state.lastAt < config.throttleMs\n );\n}\n\n/**\n * Emit the pending value because the settle (debounce) window closed. PURE.\n *\n * - Pending present, rate gate CLEAR → emit `config.emit(pending.value)`,\n * advance the rate cursor (`lastAt = at`), refresh the dedupe cache, and clear\n * `pending`. The trailing edge of `../debounce` realized as a Model transition.\n * - Pending present, rate gate STILL BLOCKED → re-HOLD: return the slice with\n * `pending` intact and NO Cmds. A settle Msg can fire at `pending.at +\n * debounceMs`, which may still be inside the rate window (`lastAt +\n * throttleMs`) — emitting then would breach the headline \"at most once per\n * `throttleMs`\" cap. Re-holding keeps the value waiting; `subs` re-arms the\n * deadline at `max(pending.at + debounceMs, lastAt + throttleMs)` so the next\n * timer fires at a LEGAL moment and the trailing edge is deferred, never lost.\n * - Pending absent → no-op: return the same slice and no Cmds. Guards the race\n * where an `input` already emitted (or a dedupe hit cleared interest) before\n * the settle timer's Msg lands — a stale `onFlush` must NOT emit. Symmetric\n * with `batch-window`'s closed-window guard.\n *\n * `at` is the firing instant the settle Msg carried (the caller stamps it; the\n * verb never reads the clock). It becomes the new rate cursor and the cache\n * write's `nowMs`, so a settled emit rate-blocks subsequent inputs from its\n * actual fire moment, not the moment the value was first held.\n *\n * @param config the knob (`throttleMs`, `emit`, cache config)\n * @param state the current slice\n * @param at the settle-timer firing instant (epoch ms)\n */\nexport function onFlush<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n at: number,\n): readonly [ThrottledInput<V>, readonly C[]] {\n // No pending value = an immediate emit already fired, or a dedupe hit cleared\n // interest. A stale timer Msg must not emit — return the slice untouched.\n if (state.pending === null) return [state, []];\n // Rate gate re-check: a settle Msg can land before the rate window opens (its\n // naive deadline is pending.at + debounceMs, which `subs` lifts to a legal\n // target — but a stale / early timer can still arrive). Emitting now would\n // breach \"at most once per throttleMs\", so re-hold and let `subs` re-arm at\n // the legal moment. The value stays pending; nothing is dropped.\n if (rateBlockedAt(config, state, at)) return [state, []];\n return commitEmit(config, state, state.pending.value, at);\n}\n\n/**\n * The settle timer Sub, derived from the slice. PURE.\n *\n * Returns the single `../deadline` Sub while a value is held AND a settle window\n * is configured, or `[]` otherwise. The deadline target is the LATER of two\n * constraints (so the timer never fires before BOTH are satisfied):\n *\n * - `pending.at + debounceMs` — the settle (debounce) deadline: the value has\n * stopped sliding, the burst has gone quiet.\n * - `lastAt + throttleMs` — the rate cap: emitting earlier would breach \"at\n * most once per `throttleMs`\". Only applies once a prior emit exists\n * (`lastAt !== null`) and a rate cap is configured (`throttleMs` set).\n *\n * `max(settleAt, rateAt)` is the earliest LEGAL trailing-edge moment. Anchoring\n * the timer here — rather than the naive `pending.at + debounceMs` — is what\n * keeps the rate cap intact across the trailing edge: a value held while still\n * inside the rate window arms its timer at `lastAt + throttleMs`, so `onFlush`\n * fires at a moment the rate gate already permits. (`onFlush` re-checks the gate\n * anyway and re-holds if an early/stale timer slips through, so the cap holds\n * even if a timer fires ahead of this target.)\n *\n * The substrate's reconcile pass arms the timer when the array gains the Sub and\n * disarms it (clearing the pending `setTimeout`) when the array loses it — so an\n * `onFlush` (or a dedupe hit) that clears `pending` auto-cancels the now-stale\n * settle timer on the next transition, and a sliding input that re-stamps\n * `pending.at` re-arms a fresh absolute target.\n *\n * `debounceMs` undefined ⇒ no settle window ⇒ `[]` even with a `pending` value\n * (an unconfigured settle never holds, but the guard keeps `subs` total).\n *\n * @param config the knob (`debounceMs`, `throttleMs`)\n * @param state the current slice\n * @param id stable identity for this gate's settle timer (default\n * `\"throttled-input:settle\"`); pass a distinct id per gate when a\n * machine runs several so the dispatched Msg routes distinctly.\n */\nexport function subsFor<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n id = DEFAULT_SUB_ID,\n): readonly ThrottledInputSub[] {\n if (config.debounceMs === undefined || state.pending === null) return [];\n const settleAt = state.pending.at + config.debounceMs;\n // The rate floor: the earliest moment the rate cap permits an emit. Absent\n // when no rate cap is configured or no prior emit set a cursor — then the\n // settle deadline alone governs.\n const rateAt =\n config.throttleMs !== undefined && state.lastAt !== null\n ? state.lastAt + config.throttleMs\n : settleAt;\n return [deadlineSub(id, Math.max(settleAt, rateAt))];\n}\n\n/**\n * The bound knob returned by `createThrottledInput`. `init` + the two pure verbs\n * + `subs`, all closing over one `ThrottledInputConfig`. The verbs return\n * `readonly [ThrottledInput<V>, readonly C[]]`: the next slice and the Cmds to\n * emit (one `emit` Cmd when a value passes, none while held / dropped / deduped).\n *\n * Pure-ops + subs module: there is no `handlers(ports)` cell. The settle timer's\n * subscribe cell IS `../deadline`'s `subscribeDeadline` (re-exported below) —\n * the consumer wires it into `subscribe` directly; the knob redraws no timer\n * lifecycle of its own. (Compare `poller`, identical: it too reuses\n * `../deadline`'s cell and ships no `handlers`.)\n */\nexport interface ThrottledInputKnob<V, C extends Cmd> {\n /** Seed the Model slice (with a cache iff `cacheTtlMs` is configured). */\n init(): ThrottledInput<V>;\n /**\n * Feed a new input through the dedupe → rate → settle gates. See `input`.\n */\n input(\n state: ThrottledInput<V>,\n value: V,\n at: number,\n ): readonly [ThrottledInput<V>, readonly C[]];\n /**\n * Emit the held value because the settle window closed. See `onFlush`.\n */\n onFlush(\n state: ThrottledInput<V>,\n at: number,\n ): readonly [ThrottledInput<V>, readonly C[]];\n /**\n * The settle timer Sub, armed only while a value is held. See `subsFor`.\n * `id` keys the deadline so several gates on one machine route distinctly.\n */\n subs(state: ThrottledInput<V>, id?: string): readonly Sub[];\n}\n\n/**\n * Build a throttled-input knob from `config`. Combinator form (the default L2\n * ergonomic): hand it the config, splice the returned hooks into your machine.\n * The pure verbs (`input` / `onFlush`) close over the config so the consumer's\n * reducer cells stay a uniform `(state, ...args)` shape; `subs` pre-wires the\n * settle timer.\n *\n * `init()` seeds a `cache` slice IFF `cacheTtlMs` is configured — an unconfigured\n * gate carries no cache field (nothing to serialize, no dedupe). Pure factory —\n * no clock read, no timer; everything happens when the consumer calls the\n * returned verbs / `subs` with an injected `at`.\n *\n * @typeParam V the input value type\n * @typeParam C the Cmd type `config.emit` returns\n */\nexport function createThrottledInput<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n): ThrottledInputKnob<V, C> {\n function init(): ThrottledInput<V> {\n const base = initThrottledInput<V>();\n // Seed the cache only when dedupe is configured — an unconfigured gate\n // carries no cache field at all (the no-dedupe shape).\n return config.cacheTtlMs !== undefined\n ? { ...base, cache: initCache<V>() }\n : base;\n }\n\n return {\n init,\n input: (state, value, at) => input(config, state, value, at),\n onFlush: (state, at) => onFlush(config, state, at),\n subs: (state, id) => subsFor(config, state, id),\n };\n}\n\n/**\n * The settle-timer wiring, RE-EXPORTED from `../deadline` (not redrawn) so the\n * timer lifecycle stays owned there. Consolidated into one `export ... from`:\n *\n * - `subscribeThrottledInput` (= `../deadline`'s `subscribeDeadline`) — the\n * `subscribe[\"deadline\"]` cell. Arms a one-shot timer for `max(0, atMs -\n * now)`, dispatches the deadline Msg, returns a cleanup that clears it. The\n * consumer assigns it: `subscribe: { deadline: subscribeThrottledInput }`.\n * - `throttledInputSettled` (= `../deadline`'s `deadlineExceeded`) +\n * `ThrottledInputSettled` (= `DeadlineExceeded`) — the settle-timer Msg\n * constructor and type the consumer handles via `onFlush`. Sharing one\n * constructor with the subscribe cell keeps the two from drifting; the\n * reducer reads `msg.atMs` as the `at` it threads into `onFlush`.\n */\nexport {\n type DeadlineExceeded as ThrottledInputSettled,\n deadlineExceeded as throttledInputSettled,\n subscribeDeadline as subscribeThrottledInput,\n} from \"../de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EAAO,OAAO,OAAA,CAAQ,MAAA,EAAQ,OAAO,EAAE,CAAA;AAAA,IACjD,MAAM,CAAC,KAAA,EAAO,OAAO,OAAA,CAAQ,MAAA,EAAQ,OAAO,EAAE;AAAA,GAChD;AACF","file":"index.js","sourcesContent":["/**\n * @demlik/tea/throttled-input — gate a high-frequency input stream into a\n * SETTLED, RATE-CAPPED, optionally DEDUPED sequence of emits, as a TEA knob: one\n * config object + a few pre-wired hooks you spread into your machine.\n *\n * Layering (the throttle-family map): `../throttle` and `../debounce` are the\n * two host-boundary PRIMITIVES — two distinct algorithms\n * (at-most-once-per-window vs collapse-a-burst) behind one signature shape.\n * THIS module is the third name but NOT a third primitive: a TEA machine\n * composed OVER them that re-exports both. Three exports, one layering — not\n * duplication. The reuse list below spells out composition vs reimplemented\n * semantic per sibling.\n *\n * What it reuses, and HOW (composition vs. reimplemented semantic — the two are\n * not the same, so this list keeps them apart):\n *\n * - `../cache` — COMPOSED directly. The DEDUPE / memoize layer is `../cache`'s\n * `TtlCache` plus its `get` / `set` / `initCache` ops, called at runtime —\n * not reinvented. While `cacheTtlMs` is set, an input whose `cacheKey` is\n * already cached and unexpired is served from the cache and emits NOTHING\n * (the downstream effect ran once for that key within its TTL); a fresh emit\n * writes the value into the cache so the next identical input within\n * `cacheTtlMs` is suppressed. The optional eviction Sub is the consumer's to\n * wire if they want memory reclaim (this knob's correctness needs only TTL\n * reads).\n * - `../deadline` — COMPOSED directly. The settle timer IS a `../deadline`\n * Sub: `subsFor` builds it via `deadlineSub`, and the subscribe cell +\n * Msg constructor are RE-EXPORTS of `../deadline`'s own (`subscribeDeadline`\n * → `subscribeThrottledInput`, `deadlineExceeded` → `throttledInputSettled`).\n * The timer lifecycle stays owned by `../deadline`; this knob redraws none\n * of it.\n * - `../throttle` / `../debounce` — TYPE + SEMANTIC reuse only, NOT composed.\n * Those siblings are host-boundary SINK transformers that hold a live\n * `setTimeout`; a `setTimeout` in a closure is exactly what a durable,\n * replayable knob must NOT hold. So their CODE is never called here. Instead\n * the RATE-cap semantic (\"at most once per `ms`\", leading-edge) and the\n * SETTLE semantic (\"wait until quiet\", trailing-edge) are REIMPLEMENTED as\n * pure Model state: `lastAt` is the durable rate cursor (half-open cutoff\n * `at - lastAt >= throttleMs`), and `pending` + the `../deadline` Sub realize\n * the debounce window inside `update`. The `throttle` / `debounce`\n * transformers themselves are RE-EXPORTED (the only reuse of their actual\n * code) so a consumer can pre-throttle / pre-coalesce a genuinely bursty\n * HOST event at the boundary BEFORE it ever becomes an `input` Msg — a\n * separate, optional escape hatch, not part of this knob's gates.\n *\n * \"Omit a brick, omit its gate\" (the resilient-call config rule): every gate\n * field is optional. Omit `throttleMs` → no rate cap (every input passes the\n * rate gate). Omit `debounceMs` → no settle wait (an input that clears the rate\n * gate emits IMMEDIATELY rather than being held). Omit `cacheTtlMs` → no cache\n * slice at all (the `cache` field is absent; no dedupe). A config with all three\n * omitted is a pass-through: `input` always emits.\n *\n * Why this is a knob and not hand-wired logic: the managed state (`lastAt`,\n * `pending`, `cache`) lives in the Model, so it survives DO eviction / reload\n * (durable) and every transition is still a Msg through `update` (replayable). A\n * closure holding a `setTimeout` and a mutable \"last value\" would break both —\n * banned. `input` / `onFlush` are PURE: time arrives as an `at` parameter, never\n * `Date.now()`; they return NEW slice values, never mutate.\n *\n * Typical wiring (combinator form):\n *\n * const search = createThrottledInput<string, Msg>({\n * debounceMs: 200, // wait for the user to stop typing\n * throttleMs: 1_000, // but never fire more than 1/s during a long burst\n * cacheTtlMs: 30_000, // skip a query repeated within 30s\n * cacheKey: (q) => q,\n * emit: (q) => ({ type: \"RunSearch\", query: q }),\n * });\n *\n * // Model: { search: ThrottledInput<string>, ... }\n * // init: (loaded) => [loaded ?? { search: search.init(), ... }, []]\n * // update cells:\n * // QueryTyped: (s, m) => mapInput(s, search.input(s.search, m.value, m.at))\n * // SettleFired: (s, m) => mapInput(s, search.onFlush(s.search, m.atMs))\n * // subscriptions: (s) => search.subs(s.search)\n * // subscribe: { ...search.handlers() }\n *\n * where `mapInput(s, [slice, cmds]) => [{ ...s, search: slice }, cmds]` lifts the\n * slice transition into the consumer's Model. The `RunSearch` Cmd's interpret\n * handler is the consumer's — it is where the settled input meets I/O.\n *\n * NOT a substrate primitive: it depends only on sibling subpaths (`../throttle`,\n * `../debounce`, `../cache`, `../deadline`) and the core `Cmd` / `Sub` types.\n * Consumers reach it via the `@demlik/tea/throttled-input` subpath; the L1\n * escape hatch is those sibling subpaths threaded by hand. NOT exported from the\n * package root — same one-shape-per-package rule as `batch-window` and `poller`.\n */\n\nimport {\n get as cacheGet,\n set as cacheSet,\n initCache,\n type TtlCache,\n} from \"../cache\";\nimport { type DeadlineSub, deadlineSub } from \"../deadline\";\nimport type { Cmd, Sub } from \"../index\";\n\n// `../throttle` + `../debounce` — host-boundary pre-transformers (see file\n// header). Re-exported so a consumer that wants to throttle/debounce a bursty\n// HOST source BEFORE it becomes an `input` Msg reaches them from the same\n// import as the durable gate.\nexport { type Debounced, debounce } from \"../debounce\";\nexport { type Throttled, throttle } from \"../throttle\";\n\n/**\n * The gate fields every throttled-input config shares, regardless of whether\n * dedupe is on. The two dedupe variants below extend this with mutually\n * exclusive cache fields.\n *\n * `emit` is a pure Cmd CONSTRUCTOR, not a closure-with-state: it maps a settled\n * value to the single Cmd the runtime performs when the gates let a value\n * through. Keeping it `(value) => Cmd` (not `(value) => void`) is what keeps the\n * trigger replayable — the emit is a Cmd in the transition's output, never a\n * side effect inside the verb (mirrors `batch-window`'s `flush`).\n */\ninterface ThrottledInputGates<V, C extends Cmd> {\n /**\n * Rate cap, in milliseconds. An input that lands within `throttleMs` of the\n * last EMIT (`at - lastAt < throttleMs`) is dropped from immediate firing —\n * the leading-edge \"at most once per `throttleMs`\" rate-cap rule, applied to\n * emits. The half-open cutoff (`>=` passes) matches `../throttle` and\n * `../cache`'s window-edge convention. Omit for no rate cap.\n *\n * Interacts with `debounceMs`: when both are set, a rate-blocked input is\n * still HELD as `pending` (so the settle timer eventually trails it out at a\n * legal moment) rather than silently dropped — the trailing-edge guarantee\n * that the FINAL sample of a window is never lost.\n */\n readonly throttleMs?: number;\n /**\n * Settle wait, in milliseconds. An input that clears the rate gate is not\n * emitted immediately; it is held as `pending` and a debounce deadline is\n * armed at `pendingAt + debounceMs`. A fresh input re-arms (slides) the\n * window. `onFlush` emits the pending value when the window finally expires.\n * Omit for no settle wait — a passing input emits on arrival.\n */\n readonly debounceMs?: number;\n /**\n * Map a settled value to the single Cmd the runtime performs. Called with the\n * value the gates let through; the returned Cmd is what `input` / `onFlush`\n * emit. PURE constructor — no I/O, no clock; the I/O happens later in the\n * consumer's interpret handler for the returned Cmd.\n */\n readonly emit: (value: V) => C;\n}\n\n/**\n * Configuration for a throttled input — the knob. Pure config, no mutable state\n * (the `ThrottledInput<V>` slice carries that). One config object is shared\n * across every input of one logical stream (often a module-scope const).\n *\n * A DISCRIMINATED UNION on the presence of dedupe, so the type system makes a\n * cache-key collision UNREPRESENTABLE (\"omit a brick, omit its gate\"):\n *\n * - **No dedupe** (`ThrottledInputNoCache`): `cacheTtlMs` absent ⇒ no cache\n * slice, no dedupe. `cacheKey` is statically forbidden here (`never`) — a\n * key with no cache to feed is dead config, so the type rejects it rather\n * than silently ignoring it.\n * - **Dedupe** (`ThrottledInputWithCache`): `cacheTtlMs` set ⇒ `cacheKey` is\n * REQUIRED. There is no `String(value)` default to fall back to, so a\n * structured value can NEVER collapse two distinct values to one slot (the\n * `\"[object Object]\"` collision). The consumer must state the identity that\n * keys the cache; a primitive stream still trivially passes `(v) => v` /\n * `String`, but it does so EXPLICITLY.\n */\nexport type ThrottledInputConfig<V, C extends Cmd> =\n | ThrottledInputNoCache<V, C>\n | ThrottledInputWithCache<V, C>;\n\n/**\n * The no-dedupe config variant: gates only, no cache. `cacheTtlMs` is absent\n * and `cacheKey` is statically `never` so a stray key (which would feed no\n * cache) is a type error, not a silently-ignored field.\n */\nexport interface ThrottledInputNoCache<V, C extends Cmd>\n extends ThrottledInputGates<V, C> {\n readonly cacheTtlMs?: undefined;\n readonly cacheKey?: never;\n}\n\n/**\n * The dedupe config variant: a per-entry TTL plus a REQUIRED `cacheKey`. An\n * input whose `cacheKey` is already cached and unexpired emits NOTHING (the\n * downstream effect ran once for that key within its TTL); a fresh emit writes\n * the value into the cache.\n *\n * `cacheKey` is required (no `String(value)` default) precisely so a structured\n * value cannot silently collide — the consumer names the identity, the cache\n * keys on exactly that.\n */\nexport interface ThrottledInputWithCache<V, C extends Cmd>\n extends ThrottledInputGates<V, C> {\n /**\n * Dedupe / memoize TTL, in milliseconds. An input whose `cacheKey` is already\n * cached and unexpired emits NOTHING; a fresh emit writes the value into the\n * cache so the next identical input within `cacheTtlMs` is suppressed.\n */\n readonly cacheTtlMs: number;\n /**\n * Key a value for the dedupe cache. REQUIRED whenever `cacheTtlMs` is set:\n * there is no `String(value)` fallback, so a structured value's identity is\n * always the consumer's explicit choice and two distinct values can never\n * collapse to one slot. A primitive stream passes `(v) => v` / `String`.\n */\n readonly cacheKey: (value: V) => string;\n}\n\n/**\n * The Model slice a throttled input owns — its visible slice (the knob\n * principle: managed state lives in the Model, never a closure, so it is durable\n * and replayable).\n *\n * - `lastAt` — the `at` of the most recent EMIT, or `null` before the first\n * emit. The `../throttle` rate cap measures against it: an input\n * within `throttleMs` of `lastAt` is rate-blocked. Persisted so a\n * resumed gate keeps its rate cursor.\n * - `pending` — the value HELD for the settle (debounce) window, paired with the\n * `at` it was held (the anchor the deadline targets), or `null`\n * when nothing is waiting. The single source of truth for \"is a\n * settle window open?\" — the debounce timer Sub arms iff this is\n * non-null.\n * - `cache` — the `../cache` TTL store backing dedupe, present IFF\n * `cacheTtlMs` is configured. Absent (the field omitted) for a\n * gate with no dedupe — no per-op cost, nothing to serialize.\n */\nexport interface ThrottledInput<V> {\n readonly lastAt: number | null;\n readonly pending: PendingInput<V> | null;\n readonly cache?: TtlCache<V>;\n}\n\n/**\n * A value held for the settle window: the `value` itself and the `at` it was\n * held (the anchor the debounce deadline targets, `at + debounceMs`). A distinct\n * type (not a bare `V`) because `V` may itself be `null` — a present-but-null\n * value is still a real pending input, distinct from \"nothing pending\", exactly\n * the `null`-sentinel discipline `../throttle` / `../debounce` use for their\n * `pendingArgs`.\n */\nexport interface PendingInput<V> {\n readonly value: V;\n readonly at: number;\n}\n\n/**\n * The Sub variant a throttled input's settle timer produces — a `../deadline`\n * Sub (so the window fires at the correct ABSOLUTE moment even after a late\n * subscribe / rehydrate, and so a consumer running several gates routes each by\n * `id`). `atMs` is the absolute settle-by instant (`pendingAt + debounceMs`).\n */\nexport type ThrottledInputSub = DeadlineSub;\n\n/**\n * The stable Sub id the gate arms its settle deadline under. A single gate arms\n * exactly one settle timer at a time, so one id suffices; a consumer running\n * several gates on one machine namespaces them by composing the knob under\n * distinct slices with distinct ids (the `subs(state, id)` parameter).\n */\nconst DEFAULT_SUB_ID = \"throttled-input:settle\";\n\n/**\n * The starting slice: no prior emit, nothing pending. The `cache` field is\n * seeded only when `cacheTtlMs` is configured (see `createThrottledInput`); the\n * free `initThrottledInput` leaves it absent (the no-dedupe shape).\n */\nexport function initThrottledInput<V>(): ThrottledInput<V> {\n return { lastAt: null, pending: null };\n}\n\n/**\n * Resolve a value's cache key under a DEDUPE config. PURE. Takes the narrowed\n * `ThrottledInputWithCache` (not the union) because `cacheKey` is only present —\n * and only meaningful — when dedupe is on; there is no `String(value)` default\n * to fall back to, so a structured value's identity is always the consumer's\n * explicit choice and two distinct values can never collapse to one slot.\n */\nfunction keyOf<V, C extends Cmd>(\n config: ThrottledInputWithCache<V, C>,\n value: V,\n): string {\n return config.cacheKey(value);\n}\n\n/**\n * Narrow `config` to its dedupe variant iff a cache slice is actually wired —\n * `cacheTtlMs` set AND a `cache` store present. Returns the narrowed config\n * (carrying the required `cacheKey`) paired with the resolved `cache` store, or\n * `null` when no dedupe is configured. The single place the union is\n * discriminated, so `isCacheHit` / `commitEmit` share one narrowing — and reuse\n * the resolved `cache` — rather than re-deriving the predicate and re-narrowing\n * `state.cache`.\n */\nfunction cacheConfig<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n): {\n readonly config: ThrottledInputWithCache<V, C>;\n readonly cache: TtlCache<V>;\n} | null {\n return config.cacheTtlMs !== undefined && state.cache !== undefined\n ? { config, cache: state.cache }\n : null;\n}\n\n/**\n * Whether `value` is a cache HIT under `config` at `at` — present and unexpired.\n * PURE — reads only. Always `false` when `cacheTtlMs` is unset or no `cache`\n * slice exists (no dedupe configured), so the dedupe gate is a no-op for an\n * unconfigured gate.\n */\nfunction isCacheHit<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n value: V,\n at: number,\n): boolean {\n const cached = cacheConfig(config, state);\n if (cached === null) return false;\n return cacheGet(cached.cache, keyOf(cached.config, value), at) !== undefined;\n}\n\n/**\n * Emit `value` at clock `at`: bump the rate cursor, refresh the dedupe cache,\n * and clear any pending hold. PURE. The single place an emit's bookkeeping\n * lives, shared by `input` (immediate emit) and `onFlush` (trailing emit) so the\n * two paths can never drift on what an emit updates.\n *\n * - `lastAt` advances to `at` — the next input is rate-measured against this\n * emit, the `../throttle` window cursor.\n * - `cache` (when configured) records `value` under its key with `cacheTtlMs`\n * from `at` — so the next identical input within the TTL is suppressed.\n * - `pending` clears — the value just went out; nothing is waiting.\n */\nfunction commitEmit<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n value: V,\n at: number,\n): readonly [ThrottledInput<V>, readonly C[]] {\n const cached = cacheConfig(config, state);\n const cache =\n cached !== null\n ? cacheSet(\n cached.cache,\n keyOf(cached.config, value),\n value,\n at,\n cached.config.cacheTtlMs,\n )\n : state.cache;\n const next: ThrottledInput<V> = {\n ...state,\n lastAt: at,\n pending: null,\n ...(cache !== undefined ? { cache } : {}),\n };\n return [next, [config.emit(value)]];\n}\n\n/**\n * Feed a new input `value` arriving at clock `at` through the gates. PURE.\n *\n * The gate order is DEDUPE → RATE → SETTLE (each skipped when its config field\n * is omitted), the same cache-first-then-gate order `resilient-call` uses (a hit\n * short-circuits before the expensive path):\n *\n * 1. **Dedupe** (`cacheTtlMs` set): if `value`'s key is cached and unexpired,\n * suppress — return the slice UNCHANGED (no emit, no pending, no re-arm).\n * The downstream effect already ran for this key within its TTL.\n * 2. **Rate** (`throttleMs` set): if `at` is within `throttleMs` of the last\n * emit (`at - lastAt < throttleMs`), this input is rate-blocked.\n * - With `debounceMs` set → HOLD it as `pending` (the trailing edge: the\n * settle timer will emit it at a legal moment, so the final sample is\n * never lost). The deadline `subs` arms targets `at + debounceMs`.\n * - Without `debounceMs` → DROP it (pure rate cap, no catch-up).\n * 3. **Settle** (`debounceMs` set): the input cleared the rate gate. HOLD it\n * as `pending` and let the debounce window slide; `onFlush` emits it once\n * the window expires. A fresh input before expiry overwrites `pending` (the\n * trailing edge fires with the LAST value, the `../debounce` default).\n * 4. **Pass-through**: no `debounceMs`, cleared the rate gate → EMIT now.\n *\n * @param config the knob (the three optional gates + `emit`)\n * @param state the current slice\n * @param value the input value\n * @param at the arrival instant (epoch ms) — the caller stamps it; the verb\n * never reads the clock\n */\nexport function input<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n value: V,\n at: number,\n): readonly [ThrottledInput<V>, readonly C[]] {\n // 1. Dedupe gate — a cached, unexpired key short-circuits everything.\n if (isCacheHit(config, state, value, at)) {\n return [state, []];\n }\n\n // 2. Rate gate — half-open cutoff (`>=` passes). `lastAt === null` (no prior\n // emit) always passes: the first input is never rate-blocked. Shared with\n // `onFlush` via `rateBlockedAt` so the arrival and trailing-edge paths agree\n // on the window.\n if (rateBlockedAt(config, state, at)) {\n // With a settle window, a rate-blocked input is HELD (trailing edge) so it\n // emits at the next legal moment; without one, it is a pure drop.\n if (config.debounceMs !== undefined) {\n return [{ ...state, pending: { value, at } }, []];\n }\n return [state, []];\n }\n\n // 3. Settle gate — passed the rate gate; if a debounce window is configured,\n // hold the value and (re)arm the settle deadline rather than emit now.\n if (config.debounceMs !== undefined) {\n return [{ ...state, pending: { value, at } }, []];\n }\n\n // 4. Pass-through — no settle wait, cleared the rate gate: emit immediately.\n return commitEmit(config, state, value, at);\n}\n\n/**\n * Whether emitting at clock `at` would breach the rate cap — `at` lands within\n * `throttleMs` of the last emit (`at - lastAt < throttleMs`). PURE — reads only.\n * Always `false` when `throttleMs` is unset (no rate cap) or before the first\n * emit (`lastAt === null`), so an unconfigured / never-fired gate never holds on\n * the rate gate. The single rate-gate predicate, shared by `input` (drop / hold\n * on arrival) and `onFlush` (re-hold a still-early trailing edge) so the two\n * paths can never drift on what \"within the rate window\" means.\n */\nfunction rateBlockedAt<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n at: number,\n): boolean {\n return (\n config.throttleMs !== undefined &&\n state.lastAt !== null &&\n at - state.lastAt < config.throttleMs\n );\n}\n\n/**\n * Emit the pending value because the settle (debounce) window closed. PURE.\n *\n * - Pending present, rate gate CLEAR → emit `config.emit(pending.value)`,\n * advance the rate cursor (`lastAt = at`), refresh the dedupe cache, and clear\n * `pending`. The trailing edge of `../debounce` realized as a Model transition.\n * - Pending present, rate gate STILL BLOCKED → re-HOLD: return the slice with\n * `pending` intact and NO Cmds. A settle Msg can fire at `pending.at +\n * debounceMs`, which may still be inside the rate window (`lastAt +\n * throttleMs`) — emitting then would breach the headline \"at most once per\n * `throttleMs`\" cap. Re-holding keeps the value waiting; `subs` re-arms the\n * deadline at `max(pending.at + debounceMs, lastAt + throttleMs)` so the next\n * timer fires at a LEGAL moment and the trailing edge is deferred, never lost.\n * - Pending absent → no-op: return the same slice and no Cmds. Guards the race\n * where an `input` already emitted (or a dedupe hit cleared interest) before\n * the settle timer's Msg lands — a stale `onFlush` must NOT emit. Symmetric\n * with `batch-window`'s closed-window guard.\n *\n * `at` is the firing instant the settle Msg carried (the caller stamps it; the\n * verb never reads the clock). It becomes the new rate cursor and the cache\n * write's `nowMs`, so a settled emit rate-blocks subsequent inputs from its\n * actual fire moment, not the moment the value was first held.\n *\n * @param config the knob (`throttleMs`, `emit`, cache config)\n * @param state the current slice\n * @param at the settle-timer firing instant (epoch ms)\n */\nexport function onFlush<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n at: number,\n): readonly [ThrottledInput<V>, readonly C[]] {\n // No pending value = an immediate emit already fired, or a dedupe hit cleared\n // interest. A stale timer Msg must not emit — return the slice untouched.\n if (state.pending === null) return [state, []];\n // Rate gate re-check: a settle Msg can land before the rate window opens (its\n // naive deadline is pending.at + debounceMs, which `subs` lifts to a legal\n // target — but a stale / early timer can still arrive). Emitting now would\n // breach \"at most once per throttleMs\", so re-hold and let `subs` re-arm at\n // the legal moment. The value stays pending; nothing is dropped.\n if (rateBlockedAt(config, state, at)) return [state, []];\n return commitEmit(config, state, state.pending.value, at);\n}\n\n/**\n * The settle timer Sub, derived from the slice. PURE.\n *\n * Returns the single `../deadline` Sub while a value is held AND a settle window\n * is configured, or `[]` otherwise. The deadline target is the LATER of two\n * constraints (so the timer never fires before BOTH are satisfied):\n *\n * - `pending.at + debounceMs` — the settle (debounce) deadline: the value has\n * stopped sliding, the burst has gone quiet.\n * - `lastAt + throttleMs` — the rate cap: emitting earlier would breach \"at\n * most once per `throttleMs`\". Only applies once a prior emit exists\n * (`lastAt !== null`) and a rate cap is configured (`throttleMs` set).\n *\n * `max(settleAt, rateAt)` is the earliest LEGAL trailing-edge moment. Anchoring\n * the timer here — rather than the naive `pending.at + debounceMs` — is what\n * keeps the rate cap intact across the trailing edge: a value held while still\n * inside the rate window arms its timer at `lastAt + throttleMs`, so `onFlush`\n * fires at a moment the rate gate already permits. (`onFlush` re-checks the gate\n * anyway and re-holds if an early/stale timer slips through, so the cap holds\n * even if a timer fires ahead of this target.)\n *\n * The substrate's reconcile pass arms the timer when the array gains the Sub and\n * disarms it (clearing the pending `setTimeout`) when the array loses it — so an\n * `onFlush` (or a dedupe hit) that clears `pending` auto-cancels the now-stale\n * settle timer on the next transition, and a sliding input that re-stamps\n * `pending.at` re-arms a fresh absolute target.\n *\n * `debounceMs` undefined ⇒ no settle window ⇒ `[]` even with a `pending` value\n * (an unconfigured settle never holds, but the guard keeps `subs` total).\n *\n * @param config the knob (`debounceMs`, `throttleMs`)\n * @param state the current slice\n * @param id stable identity for this gate's settle timer (default\n * `\"throttled-input:settle\"`); pass a distinct id per gate when a\n * machine runs several so the dispatched Msg routes distinctly.\n */\nexport function subsFor<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n state: ThrottledInput<V>,\n id = DEFAULT_SUB_ID,\n): readonly ThrottledInputSub[] {\n if (config.debounceMs === undefined || state.pending === null) return [];\n const settleAt = state.pending.at + config.debounceMs;\n // The rate floor: the earliest moment the rate cap permits an emit. Absent\n // when no rate cap is configured or no prior emit set a cursor — then the\n // settle deadline alone governs.\n const rateAt =\n config.throttleMs !== undefined && state.lastAt !== null\n ? state.lastAt + config.throttleMs\n : settleAt;\n return [deadlineSub(id, Math.max(settleAt, rateAt))];\n}\n\n/**\n * The bound knob returned by `createThrottledInput`. `init` + the two pure verbs\n * + `subs`, all closing over one `ThrottledInputConfig`. The verbs return\n * `readonly [ThrottledInput<V>, readonly C[]]`: the next slice and the Cmds to\n * emit (one `emit` Cmd when a value passes, none while held / dropped / deduped).\n *\n * Pure-ops + subs module: there is no `handlers(ports)` cell. The settle timer's\n * subscribe cell IS `../deadline`'s `subscribeDeadline` (re-exported below) —\n * the consumer wires it into `subscribe` directly; the knob redraws no timer\n * lifecycle of its own. (Compare `poller`, identical: it too reuses\n * `../deadline`'s cell and ships no `handlers`.)\n */\nexport interface ThrottledInputKnob<V, C extends Cmd> {\n /** Seed the Model slice (with a cache iff `cacheTtlMs` is configured). */\n init(): ThrottledInput<V>;\n /**\n * Feed a new input through the dedupe → rate → settle gates. See `input`.\n */\n input(\n state: ThrottledInput<V>,\n value: V,\n at: number,\n ): readonly [ThrottledInput<V>, readonly C[]];\n /**\n * Emit the held value because the settle window closed. See `onFlush`.\n */\n onFlush(\n state: ThrottledInput<V>,\n at: number,\n ): readonly [ThrottledInput<V>, readonly C[]];\n /**\n * The settle timer Sub, armed only while a value is held. See `subsFor`.\n * `id` keys the deadline so several gates on one machine route distinctly.\n */\n subs(state: ThrottledInput<V>, id?: string): readonly Sub[];\n}\n\n/**\n * Build a throttled-input knob from `config`. Combinator form (the default L2\n * ergonomic): hand it the config, splice the returned hooks into your machine.\n * The pure verbs (`input` / `onFlush`) close over the config so the consumer's\n * reducer cells stay a uniform `(state, ...args)` shape; `subs` pre-wires the\n * settle timer.\n *\n * `init()` seeds a `cache` slice IFF `cacheTtlMs` is configured — an unconfigured\n * gate carries no cache field (nothing to serialize, no dedupe). Pure factory —\n * no clock read, no timer; everything happens when the consumer calls the\n * returned verbs / `subs` with an injected `at`.\n *\n * @typeParam V the input value type\n * @typeParam C the Cmd type `config.emit` returns\n */\nexport function createThrottledInput<V, C extends Cmd>(\n config: ThrottledInputConfig<V, C>,\n): ThrottledInputKnob<V, C> {\n function init(): ThrottledInput<V> {\n const base = initThrottledInput<V>();\n // Seed the cache only when dedupe is configured — an unconfigured gate\n // carries no cache field at all (the no-dedupe shape).\n return config.cacheTtlMs !== undefined\n ? { ...base, cache: initCache<V>() }\n : base;\n }\n\n return {\n init,\n input: (state, value, at) => input(config, state, value, at),\n onFlush: (state, at) => onFlush(config, state, at),\n subs: (state, id) => subsFor(config, state, id),\n };\n}\n\n/**\n * The settle-timer wiring, RE-EXPORTED from `../deadline` (not redrawn) so the\n * timer lifecycle stays owned there. Consolidated into one `export ... from`:\n *\n * - `subscribeThrottledInput` (= `../deadline`'s `subscribeDeadline`) — the\n * `subscribe[\"deadline\"]` cell. Arms a one-shot timer for `max(0, atMs -\n * now)`, dispatches the deadline Msg, returns a cleanup that clears it. The\n * consumer assigns it: `subscribe: { deadline: subscribeThrottledInput }`.\n * - `throttledInputSettled` (= `../deadline`'s `deadlineExceeded`) +\n * `ThrottledInputSettled` (= `DeadlineExceeded`) — the settle-timer Msg\n * constructor and type the consumer handles via `onFlush`. Sharing one\n * constructor with the subscribe cell keeps the two from drifting; the\n * reducer reads `msg.atMs` as the `at` it threads into `onFlush`.\n */\nexport {\n type DeadlineExceeded as ThrottledInputSettled,\n deadlineExceeded as throttledInputSettled,\n subscribeDeadline as subscribeThrottledInput,\n} from \"../deadline\";\n"]}
@@ -1,4 +1,4 @@
1
- import { C as Cmd, I as Interpret } from '../core-BoB6t7dB.js';
1
+ import { C as Cmd, c as Interpret } from '../core-42kapW0n.js';
2
2
  import { M as MsgType } from '../protocol-B5YmJr0d.js';
3
3
 
4
4
  /**
@@ -1,6 +1,6 @@
1
- export { createTokenRefresh, initTokenRefresh, refreshTokenCmd, tokenRefreshFailedMsg, tokenRefreshedMsg } from '../chunk-3XJWC7VW.js';
1
+ export { createTokenRefresh, initTokenRefresh, refreshTokenCmd, tokenRefreshFailedMsg, tokenRefreshedMsg } from '../chunk-SK5JGUY7.js';
2
2
  import '../chunk-JELSZN25.js';
3
- import '../chunk-MMH7CW5K.js';
4
- import '../chunk-QLA76GIT.js';
3
+ import '../chunk-BP2R7TPP.js';
4
+ import '../chunk-PBDYW2TU.js';
5
5
  //# sourceMappingURL=index.js.map
6
6
  //# sourceMappingURL=index.js.map
@@ -1,6 +1,6 @@
1
- import { C as Cmd, S as Sub, M as Machine } from '../core-BoB6t7dB.js';
1
+ import { C as Cmd, S as Sub, M as Machine } from '../core-42kapW0n.js';
2
2
  import { Trace } from '../recorder/index.js';
3
- import '../index.js';
3
+ import '../runtime-types-gsog27b6.js';
4
4
 
5
5
  /**
6
6
  * The outcome of {@link replayTrace}.
@@ -50,11 +50,16 @@ declare function replayTrace<S, M extends {
50
50
  type: string;
51
51
  }, C extends Cmd, U extends Sub, Ctx>(machine: Machine<S, M, C, U, Ctx>, trace: Trace<S, M>, ctx: Ctx): ReplayResult<S>;
52
52
  /**
53
- * Order-insensitive structural deep-equality — the single comparator this
54
- * package owns, exposed so consumers (e.g. `@demlik/tea/parity`'s `diff`)
55
- * reuse it rather than adding a second deep-compare. `true` iff `a` and `b`
56
- * are structurally equal under {@link firstDivergence}'s walk (object keys
57
- * compared order-insensitively, arrays index-by-index).
53
+ * Order-insensitive structural deep-equality — the comparator the
54
+ * record/replay lane owns, exposed so consumers (e.g. `@demlik/tea/parity`'s
55
+ * `parityEqual`) reuse it rather than adding a fourth deep-compare. It is one
56
+ * of three structural walkers in the package, divergent on purpose:
57
+ * this `deepEqual` returns a boolean verdict (order-insensitive, for
58
+ * replay/parity equality), `devtools`'s `diffState` returns a change list (for
59
+ * a human-readable diff view), and `testing`'s `__deepEqual` is the assertion
60
+ * helpers' internal compare — same shape, three jobs, not one to collapse.
61
+ * `true` iff `a` and `b` are structurally equal under {@link firstDivergence}'s
62
+ * walk (object keys compared order-insensitively, arrays index-by-index).
58
63
  */
59
64
  declare function deepEqual(a: unknown, b: unknown): boolean;
60
65
 
@@ -1,5 +1,6 @@
1
- export { deepEqual, replayTrace } from '../chunk-ON24RKSE.js';
2
- import '../chunk-MMH7CW5K.js';
3
- import '../chunk-QLA76GIT.js';
1
+ export { deepEqual, replayTrace } from '../chunk-S4O26D7B.js';
2
+ import '../chunk-EWJP3YYP.js';
3
+ import '../chunk-BP2R7TPP.js';
4
+ import '../chunk-PBDYW2TU.js';
4
5
  //# sourceMappingURL=index.js.map
5
6
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import { S as Sub } from './core-BoB6t7dB.js';
1
+ import { S as Sub } from './core-42kapW0n.js';
2
2
 
3
3
  type SubscribeHandler<S extends Sub, M, Ctx> = (sub: S, ctx: Ctx, dispatch: (msg: M) => void) => () => void;
4
4
 
@@ -1,4 +1,4 @@
1
- import { S as Sub, C as Cmd, M as Machine } from '../core-BoB6t7dB.js';
1
+ import { S as Sub, C as Cmd, M as Machine } from '../core-42kapW0n.js';
2
2
 
3
3
  /**
4
4
  * @demlik/tea/with-deadline — auto-fail a wrapped machine at T+N, re-arm on
@@ -1,6 +1,6 @@
1
1
  import { fromTimeout } from '../chunk-2YFLOCWX.js';
2
- import '../chunk-MMH7CW5K.js';
3
- import { msgKeysOf, applyCell, subId } from '../chunk-QLA76GIT.js';
2
+ import '../chunk-BP2R7TPP.js';
3
+ import { msgKeysOf, applyCell, subId } from '../chunk-PBDYW2TU.js';
4
4
 
5
5
  // src/with-deadline/index.ts
6
6
  function deadlineExceededMsg(seq) {
@@ -1,7 +1,7 @@
1
- import { C as Cmd, S as Sub, M as Machine } from '../core-BoB6t7dB.js';
1
+ import { C as Cmd, S as Sub, M as Machine } from '../core-42kapW0n.js';
2
2
  import { ResilientConfig, ResilientState } from '../resilient-call/index.js';
3
3
  import '../cache/index.js';
4
- import '../types-B-8bcAp8.js';
4
+ import '../types-KbL3W1mj.js';
5
5
  import '../circuit-breaker/index.js';
6
6
  import '../deadline/index.js';
7
7
  import '../protocol-B5YmJr0d.js';
@@ -9,6 +9,8 @@ import '../rate-limit/index.js';
9
9
  import '../retry-backoff/index.js';
10
10
 
11
11
  /**
12
+ * @packageDocumentation
13
+ *
12
14
  * @demlik/tea/with-resilience — the INTERCEPTING wrapper of the wrapper tier.
13
15
  *
14
16
  * `withResilience(base, config)` is a **pure function over machine data**: it
@@ -70,6 +72,23 @@ import '../retry-backoff/index.js';
70
72
  * the only clock read is `Date.now()` at the interpret boundary (the
71
73
  * `$resilience:run` handler stamps the ok/err Msg `at`) and in the timer
72
74
  * Sub. The merged `update` is PURE — `at` arrives as Msg data.
75
+ *
76
+ * ## The retry bound may be a DURATION, not only a count
77
+ *
78
+ * `config.retry` is resilient-call's `AnyRetryPolicy`: a count (`RetryPolicy`),
79
+ * a wall-clock outage budget (`DurationRetryPolicy`, `maxElapsedMs`), or an
80
+ * explicit `unbounded: true`. Nothing extra is wired for the duration bound and
81
+ * nothing extra is required of the base machine — rule 5 already made the clock
82
+ * arrive as DATA on exactly the Msgs the streak is measured from:
83
+ * `$resilience:err.at` (stamped by the wrapper's own `$resilience:run` handler
84
+ * at the interpret boundary) and `$resilience:timer.atMs` (the Sub's fire
85
+ * instant). Those are the two instants `recordFailure` / `shouldRetry` are fed,
86
+ * so an outage budget is measured against true wall time even when
87
+ * `config.at` is absent — the cold gate's `at` never records a failure.
88
+ *
89
+ * `config.at` therefore stays REQUIRED-when-time-sensitive-brick and OPTIONAL
90
+ * otherwise, unchanged: a duration-bounded retry does NOT make it required,
91
+ * because the cold attempt is not a failure observation.
73
92
  */
74
93
 
75
94
  /**
@@ -1,14 +1,15 @@
1
- import { createResilientCall } from '../chunk-27N2SPTN.js';
1
+ import { createResilientCall } from '../chunk-IXBKFQH5.js';
2
2
  import { MsgType } from '../chunk-JELSZN25.js';
3
- import { subscribeDeadline } from '../chunk-K7Q23EQ4.js';
4
- import '../chunk-5VNWZADP.js';
5
- import '../chunk-2YOE5PIS.js';
6
- import '../chunk-SC3FAFZN.js';
7
- import '../chunk-IN33Q4VJ.js';
8
- import '../chunk-NSDFA6M6.js';
3
+ import { subscribeDeadline } from '../chunk-RMX4EOQK.js';
4
+ import '../chunk-Q2UM7BXU.js';
5
+ import '../chunk-S2EGRPCM.js';
6
+ import '../chunk-UF4MZSLT.js';
7
+ import '../chunk-2KNLKQVN.js';
8
+ import '../chunk-LYLDCIPH.js';
9
9
  import '../chunk-2YFLOCWX.js';
10
- import { tryInterpret } from '../chunk-MMH7CW5K.js';
11
- import { msgKeysOf, applyCell, subId, formOf } from '../chunk-QLA76GIT.js';
10
+ import '../chunk-ZJ5AOYBH.js';
11
+ import { tryInterpret } from '../chunk-BP2R7TPP.js';
12
+ import { msgKeysOf, applyCell, subId, formOf } from '../chunk-PBDYW2TU.js';
12
13
 
13
14
  // src/with-resilience/index.ts
14
15
  var RC_RETRY_PREFIX = "resilient:retry:";
@@ -70,13 +71,7 @@ function withResilience(base, config, rng = Math.random) {
70
71
  const callKey = keyOf(cmd);
71
72
  const [nextSlice, runCmds] = rc.attempt(resilience, callKey, cmd, at);
72
73
  resilience = nextSlice;
73
- for (const rcRun of runCmds) {
74
- outCmds.push({
75
- type: "$resilience:run",
76
- key: rcRun.key,
77
- input: rcRun.input
78
- });
79
- }
74
+ outCmds.push(...renameRunCmds(runCmds));
80
75
  }
81
76
  const next = { base: nextBase, $resilience: resilience };
82
77
  return [next, outCmds];
@@ -228,13 +223,7 @@ function withResilience(base, config, rng = Math.random) {
228
223
  const callKey = keyOf(cmd);
229
224
  const [nextSlice, runCmds] = rc.attempt(resilience, callKey, cmd, 0);
230
225
  resilience = nextSlice;
231
- for (const rcRun of runCmds) {
232
- initCmds.push({
233
- type: "$resilience:run",
234
- key: rcRun.key,
235
- input: rcRun.input
236
- });
237
- }
226
+ initCmds.push(...renameRunCmds(runCmds));
238
227
  }
239
228
  const model = { base: base0, $resilience: resilience };
240
229
  return [model, initCmds];
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/with-resilience/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAgOA,IAAM,eAAA,GAAkB,kBAAA;AACxB,IAAM,kBAAA,GAAqB,qBAAA;AAC3B,IAAM,eAAA,GAAkB,oBAAA;AACxB,IAAM,kBAAA,GAAqB,uBAAA;AAG3B,SAAS,iBAAiB,IAAA,EAAsB;AAC9C,EAAA,IAAI,IAAA,CAAK,WAAW,eAAe,CAAA;AACjC,IAAA,OAAO,eAAA,GAAkB,IAAA,CAAK,KAAA,CAAM,eAAA,CAAgB,MAAM,CAAA;AAC5D,EAAA,IAAI,IAAA,CAAK,WAAW,kBAAkB,CAAA;AACpC,IAAA,OAAO,kBAAA,GAAqB,IAAA,CAAK,KAAA,CAAM,kBAAA,CAAmB,MAAM,CAAA;AAClE,EAAA,OAAO,IAAA;AACT;AAGA,SAAS,YAAY,IAAA,EAAsB;AACzC,EAAA,IAAI,IAAA,CAAK,WAAW,eAAe,CAAA;AACjC,IAAA,OAAO,eAAA,GAAkB,IAAA,CAAK,KAAA,CAAM,eAAA,CAAgB,MAAM,CAAA;AAC5D,EAAA,IAAI,IAAA,CAAK,WAAW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AAA,EAAK;AACzB,MAAA,MAAM,WAAmB,EAAC;AAC1B,MAAA,KAAA,MAAW,OAAO,QAAA,EAAU;AAC1B,QAAA,IAAI,GAAA,CAAI,SAAS,MAAA,EAAQ;AACvB,UAAA,QAAA,CAAS,KAAK,GAAG,CAAA;AACjB,UAAA;AAAA,QACF;AAiBA,QAAA,IAAI,MAAA,CAAO,aAAa,MAAA,EAAW;AACjC,UAAA,MAAM,IAAI,KAAA;AAAA,YACR,CAAA,gDAAA,EAAmD,MAAM,CAAA,iJAAA,EAGhD,MAAA,CAAO,SAAS,EAAE,CAAA,mWAAA;AAAA,WAM7B;AAAA,QACF;AACA,QAAA,MAAM,OAAA,GAAU,MAAM,GAAG,CAAA;AACzB,QAAA,MAAM,CAAC,WAAW,OAAO,CAAA,GAAI,GAAG,OAAA,CAAQ,UAAA,EAAY,OAAA,EAAS,GAAA,EAAK,CAAC,CAAA;AACnE,QAAA,UAAA,GAAa,SAAA;AACb,QAAA,KAAA,MAAW,SAAS,OAAA,EAAS;AAC3B,UAAA,QAAA,CAAS,IAAA,CAAK;AAAA,YACZ,IAAA,EAAM,iBAAA;AAAA,YACN,KAAK,KAAA,CAAM,GAAA;AAAA,YACX,OAAO,KAAA,CAAM;AAAA,WACd,CAAA;AAAA,QACH;AAAA,MACF;AACA,MAAA,MAAM,KAAA,GAAY,EAAE,IAAA,EAAM,KAAA,EAAO,aAAa,UAAA,EAAW;AACzD,MAAA,OAAO,CAAC,OAAO,QAAQ,CAAA;AAAA,IACzB,CAAA;AAAA,IACA,MAAA;AAAA,IACA,aAAA;AAAA,IACA,SAAA,EAAW,YAAA;AAAA,IAOX;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\n * @demlik/tea/with-resilience — the INTERCEPTING wrapper of the wrapper tier.\n *\n * `withResilience(base, config)` is a **pure function over machine data**: it\n * takes any `Machine<S, M, C, U, Ctx>`, a chosen TARGET base Cmd type, and a\n * resilience knob, and returns a NEW `Machine` over the composed Model\n * `{ base, $resilience }`. You `run()` / `replay()` the result exactly like any\n * other machine — there is no new runtime, no privileged interception path.\n *\n * This is the HARDEST wrapper. `withTelemetry` only OBSERVES; this one\n * INTERCEPTS. It bolts the resilient-call concern (cache → circuit-breaker →\n * rate-limit → exponential-backoff retry, with a deadline cap) onto a chosen\n * base Cmd WITHOUT the base authoring any of it. The base keeps emitting its\n * plain effect Cmd; the wrapper diverts each one through the resilience gate.\n *\n * ## Retag, never swallow (rule 2 — the whole danger)\n *\n * The merged `update` delegates to `base.update`, then PARTITIONS the base Cmds\n * by type:\n *\n * - A NON-target base Cmd passes through UNCHANGED — byte-identical, in the\n * same slot. The wrapper does not touch effects it was not asked to harden.\n * - A TARGET base Cmd is RETAGGED: it becomes the `input` payload of a\n * `$resilience:run` carrier Cmd (when the gate admits it), OR its gating is\n * RECORDED as a `$resilience:*` decision in the SAME transition (cache hit,\n * circuit-open fast-fail, rate-limited backoff). It is NEVER emitted raw,\n * and it NEVER vanishes without a `$resilience:*` Cmd recording where it\n * went. That recorded divergence is exactly what the conformance gate's\n * `intercepting` option verifies.\n *\n * The resilient-call result Msgs route back through the merged `update`:\n * `$resilience:ok` → `succeed` (close the breaker, fill the cache, reset the\n * retry run), `$resilience:err` → `fail` (trip the breaker, then back off or\n * settle), `$resilience:timer` → `onTimer` (a retry timer re-runs the gate; a\n * deadline timer settles the call failed). Every decision is a Msg/Cmd through\n * the reducer + log — \"why did this fire\" is answerable from the log alone.\n *\n * ## The slice + verbs are REUSED, not reinvented\n *\n * The `$resilience` slice IS resilient-call's `ResilientState<I, R>` (per-key\n * call / retry / circuit / bucket / cache), and the gate / backoff / breaker\n * logic IS its `attempt` / `succeed` / `fail` / `onTimer` verbs + `subs`. The\n * wrapper only ADAPTS the boundary: the verb's `input` is the ORIGINAL base\n * Cmd, the verb's `resilient_run` carrier is renamed to `$resilience:run`, and\n * the sub / timer ids are re-keyed into the `$resilience:` namespace (rule 4).\n *\n * ## The 5 rules it satisfies\n *\n * 1. **Named, serializable slice.** `model.$resilience` is resilient-call's\n * plain-data `ResilientState` — JSON-serializable (the deadline error is a\n * `{_tag,...}` sentinel, never a `new Error`), never a closure.\n * 2. **Retag-and-re-emit, never swallow.** See above — a target base Cmd is\n * always inside a `$resilience:run` inner payload or recorded by a\n * `$resilience:*` divergence Cmd in the same transition.\n * 3. **Every decision is a Msg/Cmd.** Gate / retry-schedule / fast-fail /\n * settle are all `$resilience:*` Cmds and Msgs through the merged `update`.\n * 4. **Subs merge by id.** Base subs ⧺ resilient-call retry/deadline timers,\n * re-keyed `$resilience:retry:{key}` / `$resilience:deadline:{key}`.\n * 5. **Clock out of update.** Backoff jitter RNG is injected at construction;\n * the only clock read is `Date.now()` at the interpret boundary (the\n * `$resilience:run` handler stamps the ok/err Msg `at`) and in the timer\n * Sub. The merged `update` is PURE — `at` arrives as Msg data.\n */\n\nimport { type DeadlineSub, subscribeDeadline } from \"../deadline\";\nimport type {\n Cmd,\n Interpret,\n Machine,\n Reducer,\n Sub,\n UpdateForm,\n} from \"../index\";\nimport { applyCell, formOf, msgKeysOf, subId, tryInterpret } from \"../index\";\nimport { MsgType } from \"../protocol\";\nimport {\n createResilientCall,\n type ResilientConfig,\n type ResilientState,\n} from \"../resilient-call\";\n\n// ===========================================================================\n// Config — the target + the resilience knob + an optional key deriver.\n// ===========================================================================\n\n/**\n * The `withResilience` knob. Extends resilient-call's `ResilientConfig` (every\n * brick optional — omit a brick, omit its gate) with the two fields the wrapper\n * needs that the bare knob does not:\n *\n * - `target` — the `Cmd.type` discriminant of the ONE base Cmd this wrapper\n * hardens. Every other base Cmd passes through untouched.\n * - `keyOf` — OPTIONAL. Derives the per-call resilience `key` from the target\n * base Cmd, so distinct logical calls (distinct urls, distinct ids) get\n * independent retry / cache state. Pure — it runs inside the merged\n * `update`, so it must NOT read the clock / RNG. Defaults to a single\n * shared key (`target`), i.e. one logical call at a time.\n */\nexport interface ResilienceConfig<TC extends Cmd, TM extends { type: string }>\n extends ResilientConfig {\n /** The base `Cmd.type` to make resilient. */\n readonly target: TC[\"type\"];\n /** Optional per-call key deriver. Pure. Defaults to the target type itself. */\n readonly keyOf?: (cmd: TC) => string;\n /**\n * Extracts the real wall-clock time (ms) the TRIGGERING base Msg carries as\n * data — the time-as-data convention `resilient-call` expects on `attempt`.\n *\n * The merged `update` is PURE: it cannot read `Date.now()` (rule 5). The COLD\n * attempt's gate (the very first `attempt` for a target Cmd in a transition)\n * still needs a real instant — the breaker compares `at` against its recorded\n * `openedAtMs`, the cache against its write `at`, the bucket against its last\n * refill `at`, and the deadline cap anchors at `at + deadline.ms`. Fabricating\n * `at = 0` is the betrayal: a cold attempt after a real-time breaker trip then\n * computes cooldown = `0 - realTripTime < 0` forever, so the breaker NEVER\n * recovers, and a `0`-anchored deadline brick fires immediately.\n *\n * So the base Msg that drove this transition MUST carry its own wall time as\n * data, and `at` reads it off that Msg. The merged update passes\n * `at(currentBaseMsg)` into `rc.attempt` for every target Cmd that transition\n * emitted — real time enters the cold gate as Msg data, never `0`.\n *\n * REQUIRED whenever any time-sensitive brick (`circuit`, `rateLimit`, `cache`,\n * `deadline`) is configured — `withResilience` THROWS at construction if such\n * a brick is set and `at` is absent (errors are data: the cold gate needs real\n * time, refuse to build a breaker that can never recover). OPTIONAL when only\n * `retry` is configured: retry backoff reads its time off the result / timer\n * Msgs (`$resilience:err.at`, `$resilience:timer.atMs`), never the cold attempt\n * — so a `0` cold `at` is harmless there. Pure: it runs inside the merged\n * `update`, so it must NOT read the clock / RNG.\n */\n readonly at?: (msg: TM) => number;\n}\n\n// ===========================================================================\n// The slice + the wrapper Cmds/Msgs/Subs/Ports vocabulary.\n// ===========================================================================\n\n/**\n * The composed Model. The base machine's state nests under `base`; the wrapper\n * owns the NAMED `$resilience` slice — resilient-call's `ResilientState` keyed\n * by the per-call `key`, with `I = TC` (the original target base Cmd is the\n * port input) and `R = unknown` (the base interpret handler's result is opaque\n * to the wrapper — it only routes Ok/Err). Plain data → round-trips through\n * `JSON.parse(JSON.stringify(...))` iff the base state does.\n */\nexport interface ResilienceModel<S, TC extends Cmd> {\n readonly base: S;\n readonly $resilience: ResilientState<TC, unknown>;\n}\n\n/**\n * The carrier Cmd the wrapper emits when the gate ADMITS a target base Cmd. It\n * RETAGS the original base Cmd into `input` — the base Cmd is plain data, so no\n * closure (invariant 3). The interpret handler unwraps `input` and runs it\n * through the BASE interpret for that Cmd type. `key` indexes the resilient\n * call this run belongs to.\n */\nexport type ResilienceRunCmd<TC extends Cmd> = Cmd<\"$resilience:run\"> & {\n readonly key: string;\n /** The ORIGINAL base Cmd, retagged — never swallowed. */\n readonly input: TC;\n};\n\n/**\n * The success Msg the `$resilience:run` handler dispatches back when the base\n * interpret resolved OK. Routes to `succeed`. `at` is stamped at the interpret\n * boundary (the one permitted clock read).\n */\nexport type ResilienceOkMsg = {\n readonly type: \"$resilience:ok\";\n readonly key: string;\n readonly result: unknown;\n readonly at: number;\n};\n\n/**\n * The error Msg the `$resilience:run` handler dispatches back when the base\n * interpret threw / rejected. Routes to `fail` (trip the breaker, then back off\n * or settle). `at` is stamped at the interpret boundary.\n */\nexport type ResilienceErrMsg = {\n readonly type: \"$resilience:err\";\n readonly key: string;\n readonly error: unknown;\n readonly at: number;\n};\n\n/**\n * The retry / deadline timer Msg the `$resilience:timer` Sub dispatches when\n * the wall clock crosses the armed instant. Routes to `onTimer`. `id` is the\n * `$resilience:`-namespaced timer id; `atMs` is the fire instant (Msg data, the\n * clock that drove it lives in the Sub).\n */\nexport type ResilienceTimerMsg = {\n readonly type: \"$resilience:timer\";\n readonly id: string;\n readonly atMs: number;\n};\n\n/** Every Msg the wrapper adds to the base's Msg union. */\nexport type ResilienceMsg =\n | ResilienceOkMsg\n | ResilienceErrMsg\n | ResilienceTimerMsg;\n\n/** Every Cmd the wrapper adds to the base's Cmd union. */\nexport type ResilienceCmd<TC extends Cmd> = ResilienceRunCmd<TC>;\n\n/** The Sub the wrapper adds — a deadline-style timer in the `$resilience` family. */\nexport type ResilienceTimerSub = Sub<\"$resilience:timer\"> & {\n readonly atMs: number;\n};\n\n// ===========================================================================\n// Boundary re-keying — the resilient-call namespace ↔ the `$resilience` one.\n// ===========================================================================\n\n// resilient-call emits its carrier as `resilient_run` and keys its timer Subs\n// `resilient:retry:{key}` / `resilient:deadline:{key}`. The wrapper presents the\n// `$resilience:` namespace to the outside world (rule 4) while REUSING the\n// unmodified verbs underneath. These two pure string maps are the only seam:\n// rename the carrier on the way OUT, re-key the timer id on the way IN.\n\nconst RC_RETRY_PREFIX = \"resilient:retry:\";\nconst RC_DEADLINE_PREFIX = \"resilient:deadline:\";\nconst WX_RETRY_PREFIX = \"$resilience:retry:\";\nconst WX_DEADLINE_PREFIX = \"$resilience:deadline:\";\n\n/** resilient-call internal sub id → the `$resilience:`-namespaced public id. */\nfunction toWrapperTimerId(rcId: string): string {\n if (rcId.startsWith(RC_RETRY_PREFIX))\n return WX_RETRY_PREFIX + rcId.slice(RC_RETRY_PREFIX.length);\n if (rcId.startsWith(RC_DEADLINE_PREFIX))\n return WX_DEADLINE_PREFIX + rcId.slice(RC_DEADLINE_PREFIX.length);\n return rcId;\n}\n\n/** The `$resilience:`-namespaced timer id → the resilient-call internal id. */\nfunction toRcTimerId(wxId: string): string {\n if (wxId.startsWith(WX_RETRY_PREFIX))\n return RC_RETRY_PREFIX + wxId.slice(WX_RETRY_PREFIX.length);\n if (wxId.startsWith(WX_DEADLINE_PREFIX))\n return RC_DEADLINE_PREFIX + wxId.slice(WX_DEADLINE_PREFIX.length);\n return wxId;\n}\n\n/**\n * Does the base machine declare `key` as a Msg.type cell, in EITHER update\n * form? The reserved-namespace guard checks the correct level per form (keyed\n * on `formOf`, the same classification `applyCell` / `msgKeysOf` use):\n *\n * - Reducer form (`{ [msgType]: cell }`, values are functions) — the\n * msg-type keys live at the TOP level, so `Object.hasOwn(update, key)`.\n * - Transitions form (`{ [stateType]: { [msgType]: cell } }`, values are\n * records) — the msg-type keys live in the INNER tables, one per state.\n * A reserved msg-type can hide in ANY inner table, so scan EVERY inner\n * table; a collision in even one inner cell would let a transitions-form\n * base squat on e.g. an inner `$resilience:ok` cell that the wrapper's\n * merged update would silently clobber. Top-level `Object.hasOwn` (the\n * old check) only sees state-type keys here and would MISS it entirely.\n */\nfunction updateDeclaresMsgKey(\n machine: { update: object; __form?: UpdateForm },\n key: string,\n): boolean {\n if (formOf(machine) === \"reducer\") {\n // Reducer form — msg-type keys at the top level.\n return Object.hasOwn(machine.update, key);\n }\n // Transitions form — msg-type keys live in each inner state-type table. An\n // inner table can be a callable object (the shape `__form` disambiguates),\n // so accept \"function\" alongside \"object\" here.\n for (const innerTable of Object.values(machine.update)) {\n if (\n innerTable !== null &&\n (typeof innerTable === \"object\" || typeof innerTable === \"function\") &&\n Object.hasOwn(innerTable, key)\n ) {\n return true;\n }\n }\n return false;\n}\n\n// ===========================================================================\n// withResilience — the wrapper.\n// ===========================================================================\n\n/**\n * Wrap `base` so its `config.target` Cmd is run through the resilient-call\n * concern (cache → circuit → rate-limit → retry, deadline-capped). Returns a\n * NEW `Machine` over the composed Model `{ base, $resilience }`, with the\n * base's Msgs/Cmds/Subs/Ctx extended by the wrapper's own.\n *\n * @param base any `Machine<S, M, C, U, Ctx>`.\n * @param config the resilience knob: `target`, the optional bricks, `keyOf`.\n * @param rng injected backoff jitter source. Pass a fixed `() => 0.5` in\n * tests to pin retry delays; defaults to `Math.random` (read only\n * at the verb boundary, never inside the merged `update`).\n */\nexport function withResilience<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n base: Machine<S, M, C, U, Ctx>,\n config: ResilienceConfig<C, M>,\n rng: () => number = Math.random,\n): Machine<\n ResilienceModel<S, C>,\n M | ResilienceMsg,\n C | ResilienceCmd<C>,\n U | ResilienceTimerSub,\n Ctx\n> {\n type WM = ResilienceModel<S, C>;\n type WMsg = M | ResilienceMsg;\n type WCmd = C | ResilienceCmd<C>;\n\n const { target } = config;\n const keyOf = config.keyOf ?? (() => target);\n\n // A time-sensitive brick gates the COLD attempt against real wall time read\n // off the triggering base Msg (`config.at`). Without `at` the cold gate would\n // have to fabricate `0` — and a cold attempt after a real-time breaker trip\n // then computes cooldown = `0 - realTripTime < 0` forever (the breaker NEVER\n // recovers), while a `0`-anchored deadline fires immediately. Refuse to build\n // such a machine: errors are data, surfaced at construction, never a silent\n // breaker that can't recover. Retry alone reads time off the result/timer\n // Msgs, not the cold attempt, so `at` stays optional there.\n const timeSensitiveBrick =\n config.circuit !== undefined ||\n config.rateLimit !== undefined ||\n config.cache !== undefined ||\n config.deadline !== undefined;\n if (timeSensitiveBrick && config.at === undefined) {\n throw new Error(\n \"withResilience: a time-sensitive brick (circuit / rateLimit / cache / \" +\n \"deadline) is configured but `config.at` is missing. The cold-attempt \" +\n \"gate needs the REAL wall time the triggering base Msg carries as data \" +\n \"(time-as-data) — without it the gate would fabricate `at = 0`, so a \" +\n \"cold attempt after a real-time breaker trip computes a negative \" +\n \"cooldown and the breaker NEVER recovers (and a deadline brick fires \" +\n \"immediately). Provide `at: (msg) => msg.<wallTimeField>`.\",\n );\n }\n // Read the triggering base Msg's wall time as data for the cold gate. When no\n // time-sensitive brick is configured `at` may be omitted; the cold attempt\n // then gates at `0`, which is harmless because retry backoff reads its time\n // off the result / timer Msgs, never the cold attempt.\n const atOf = config.at ?? (() => 0);\n\n // The REUSED knob: I = the original target base Cmd, R = the opaque base\n // interpret result. Its verbs / subs / gate are used unmodified; the wrapper\n // only adapts the boundary (carrier rename + timer-id re-keying).\n const rc = createResilientCall<C, unknown>(config, rng);\n\n // -------------------------------------------------------------------------\n // The merged update — a flat Reducer over the composed (non-discriminated)\n // Model. Cells: every base Msg.type (delegating to base.update + partition),\n // plus the three `$resilience:*` Msgs (delegating to the reused verbs).\n // -------------------------------------------------------------------------\n\n type Cell = (state: WM, msg: WMsg) => readonly [WM, readonly WCmd[]];\n const update: Record<string, Cell> = {};\n\n // --- Base-Msg cells: delegate, then PARTITION + retag the target Cmd. ----\n // Base Msg keys enumerated via `msgKeysOf(base)` — keyed on the\n // authoritative `__form` tag, no structural re-derivation here (#275).\n for (const key of msgKeysOf(base)) {\n update[key] = (state, msg) => {\n // 1) Run the base reducer. Its NON-target Cmds pass through unchanged.\n const [nextBase, baseCmds] = applyCell<S, M, C>(\n base,\n state.base,\n msg as M,\n );\n\n // 2) Partition base Cmds: non-target pass straight through; each target\n // Cmd is routed through the resilient-call `attempt` gate, which either\n // emits a `resilient_run` carrier (→ renamed `$resilience:run`,\n // retagging the ORIGINAL base Cmd into `input`), or records the gate\n // decision in the slice with NO carrier (cache hit / circuit-open /\n // rate-limited backoff). Either way the target Cmd never escapes raw\n // and never vanishes off-ledger.\n let resilience = state.$resilience;\n const outCmds: WCmd[] = [];\n // The COLD attempt's gate time — the REAL wall time the triggering base\n // Msg carries as data (rule 5: the merged `update` stays pure; the clock\n // does not enter here, the Msg's own `at` data does). With this real\n // instant the breaker compares `at - openedAtMs` against its cooldown\n // (set by a prior real-time `$resilience:err`), so a cold attempt during\n // cooldown fast-fails and one AFTER cooldown is admitted — the breaker\n // RECOVERS. The cache compares `at` against its stored write `at`, the\n // bucket refills from `at`, and the deadline cap anchors at\n // `at + deadline.ms` — all against true wall time, never a fabricated\n // `0`. Every SUBSEQUENT gate run (`fail` → backoff, retry-timer\n // `onTimer` → re-gate) reads time off the result / timer Msgs the same\n // way. `atOf` defaults to `0` ONLY when no time-sensitive brick is\n // configured (construction throws otherwise), where retry backoff reads\n // its time off the result/timer Msgs and the cold `at` is never compared.\n const at = atOf(msg as M);\n for (const cmd of baseCmds) {\n if (cmd.type !== target) {\n outCmds.push(cmd);\n continue;\n }\n const callKey = keyOf(cmd);\n const [nextSlice, runCmds] = rc.attempt(resilience, callKey, cmd, at);\n resilience = nextSlice;\n // rc.attempt emits 0 or 1 `resilient_run` carriers. Rename each to the\n // `$resilience:run` namespace, preserving the retagged `input` (the\n // ORIGINAL base Cmd). Zero carriers = the gate recorded a divergence in\n // `nextSlice` (cache/circuit/backoff) — visible in the slice + log.\n for (const rcRun of runCmds) {\n outCmds.push({\n type: \"$resilience:run\",\n key: rcRun.key,\n input: rcRun.input,\n });\n }\n }\n\n const next: WM = { base: nextBase, $resilience: resilience };\n return [next, outCmds];\n };\n }\n\n // --- `$resilience:ok` → succeed ------------------------------------------\n update[\"$resilience:ok\"] = (state, msg) => {\n const m = msg as ResilienceOkMsg;\n const [slice, runCmds] = rc.succeed(state.$resilience, m.key, {\n type: MsgType.ResilientOk,\n key: m.key,\n result: m.result,\n at: m.at,\n });\n return [{ ...state, $resilience: slice }, renameRunCmds(runCmds)];\n };\n\n // --- `$resilience:err` → fail --------------------------------------------\n update[\"$resilience:err\"] = (state, msg) => {\n const m = msg as ResilienceErrMsg;\n const [slice, runCmds] = rc.fail(state.$resilience, m.key, {\n type: MsgType.ResilientErr,\n key: m.key,\n error: m.error,\n at: m.at,\n });\n return [{ ...state, $resilience: slice }, renameRunCmds(runCmds)];\n };\n\n // --- `$resilience:timer` → onTimer (retry re-runs gate / deadline settles) -\n update[\"$resilience:timer\"] = (state, msg) => {\n const m = msg as ResilienceTimerMsg;\n // Re-key the public `$resilience:`-id back to the resilient-call internal\n // id the `onTimer` verb matches against, then run the unmodified verb.\n const [slice, runCmds] = rc.onTimer(state.$resilience, {\n type: \"deadline_exceeded\",\n id: toRcTimerId(m.id),\n atMs: m.atMs,\n });\n return [{ ...state, $resilience: slice }, renameRunCmds(runCmds)];\n };\n\n // Rename any `resilient_run` carriers a verb produced (the retry re-attempt\n // path) into the `$resilience:run` namespace, preserving the retagged input.\n function renameRunCmds(\n runCmds: readonly { type: string; key: string; input: C }[],\n ): readonly WCmd[] {\n return runCmds.map((r) => ({\n type: \"$resilience:run\" as const,\n key: r.key,\n input: r.input,\n }));\n }\n\n // -------------------------------------------------------------------------\n // Subs — base subs ⧺ resilient-call timers, re-keyed into `$resilience:`.\n // -------------------------------------------------------------------------\n\n const baseSubscriptions = base.subscriptions;\n const baseSubscribe = (base as { subscribe?: unknown }).subscribe;\n\n function subscriptions(state: WM): readonly (U | ResilienceTimerSub)[] {\n const baseSubs = baseSubscriptions\n ? baseSubscriptions(state.base)\n : ([] as readonly U[]);\n // rc.subs returns DeadlineSubs keyed `resilient:retry:{k}` /\n // `resilient:deadline:{k}`. Re-key each into the `$resilience:` namespace\n // and re-type to the wrapper's `$resilience:timer` Sub family (rule 4).\n const rcSubs: readonly DeadlineSub[] = rc.subs(state.$resilience);\n const timerSubs: ResilienceTimerSub[] = rcSubs.map((s) => ({\n id: subId(toWrapperTimerId(s.id)),\n type: \"$resilience:timer\",\n atMs: s.atMs,\n }));\n return [...baseSubs, ...timerSubs];\n }\n\n // -------------------------------------------------------------------------\n // Interpret — base.interpret for non-target + the `$resilience:run` handler\n // that COMPOSES base.interpret for the retagged inner Cmd.\n // -------------------------------------------------------------------------\n\n const baseInterpret =\n (base as { interpret?: Interpret<M, C, Ctx> }).interpret ??\n ({} as Interpret<M, C, Ctx>);\n\n // Reserved-namespace guard (mirrors withTelemetry + the substrate's\n // definePort / SubId collision asserts). The wrapper OWNS four reserved keys:\n // the `$resilience:run` carrier Cmd, the `$resilience:ok` / `$resilience:err`\n // result Msgs, and the `$resilience:timer` Sub Msg. The merges below spread\n // the wrapper's cells over the base's update / interpret / subscribe maps; if\n // the base already declares ANY reserved key on ANY of those three surfaces,\n // the spread would SILENTLY clobber it (or the base's own key would shadow the\n // wrapper's). The `$resilience:` namespace is the wrapper's — refuse to wrap a\n // base that squats on any of the four across any surface.\n //\n // Ordered BEFORE the target-handler guard below: squatting a reserved key is a\n // target-INDEPENDENT structural defect of the base, so it is the more\n // fundamental rejection and must report first. Otherwise a base that BOTH\n // squats `$resilience:*` AND omits the target handler would surface the\n // narrower missing-target error and mask the namespace collision — exactly the\n // regression #111's construction-time hoist introduced (the hoisted target\n // check shadowed this guard for such a base), fixed by #112.\n //\n // `update` is checked PER FORM (the same `formOf` classification the wrapper\n // already uses via `msgKeysOf` / `applyCell`): a Reducer-form\n // base keys its msg-types at the TOP level, but a Transitions-form base keys\n // them in the INNER `{ [stateType]: { [msgType]: cell } }` tables — so a flat\n // top-level `Object.hasOwn` would MISS a reserved msg-type squatting inside an\n // inner table (e.g. an inner `$resilience:ok` cell) and let the merged update\n // silently clobber it. `interpret` and `subscribe` are always flat keyed-by\n // -type maps, so the direct `Object.hasOwn` is correct there.\n const RESERVED = [\n \"$resilience:run\",\n \"$resilience:ok\",\n \"$resilience:err\",\n \"$resilience:timer\",\n ] as const;\n const surfaces: readonly {\n readonly name: string;\n readonly declares: (reserved: string) => boolean;\n }[] = [\n {\n name: \"update\",\n declares: (reserved) => updateDeclaresMsgKey(base, reserved),\n },\n {\n name: \"interpret\",\n declares: (reserved) => Object.hasOwn(baseInterpret as object, reserved),\n },\n {\n name: \"subscribe\",\n declares: (reserved) =>\n Object.hasOwn((baseSubscribe as object | undefined) ?? {}, reserved),\n },\n ];\n for (const reserved of RESERVED) {\n for (const surface of surfaces) {\n if (surface.declares(reserved)) {\n throw new Error(\n `withResilience: the base machine declares a reserved \"${reserved}\" ` +\n `${surface.name} key — the wrapper owns the \"$resilience:\" ` +\n `namespace ($resilience:run / :ok / :err / :timer across update, ` +\n `interpret, and subscribe). Rename the base key.`,\n );\n }\n }\n }\n\n // Construction guard — the target Cmd MUST have a base interpret handler. This\n // is a property of the (base, config) pair, fully known here at construction:\n // the `$resilience:run` carrier delegates to `baseInterpret[target]`, so a\n // missing handler means the resilient effect has nothing to perform. Surface\n // it now — refuse to build a machine whose target can never run — rather than\n // lazily on the first effect (errors are data, surfaced at construction, like\n // the time-sensitive-`at` and reserved-namespace guards above). Ordered AFTER\n // the reserved-namespace guard so a base that squats `$resilience:*` is\n // rejected for the namespace collision first, not masked by this narrower\n // missing-target error (#112).\n if (!Object.hasOwn(baseInterpret as object, target)) {\n throw new Error(\n `withResilience: no base interpret handler for target Cmd \"${target}\" ` +\n `— the resilient effect has nothing to perform. The base machine must ` +\n `declare an interpret handler for its target Cmd type.`,\n );\n }\n\n // The `$resilience:run` handler delegates to the BASE interpret handler for\n // the retagged inner Cmd's type, wrapped via tryInterpret so Ok routes to\n // `$resilience:ok` and Err to `$resilience:err`. `Date.now()` is stamped here\n // — the ONE permitted clock read (interpret is impure; update is pure).\n const runHandler = tryInterpret<\n ResilienceRunCmd<C>,\n // The carried result is the base interpret handler's resolution, whose\n // contract is `Promise<M | void>` (a follow-up base Msg or nothing — see\n // `Interpret<M, C, Ctx>`). Carrying `M | void` here (not bare `unknown`)\n // keeps the base's follow-up Msg type at the seam; `ResilienceOkMsg.result`\n // then narrows from genuine looseness to \"a base Msg or void\".\n // biome-ignore lint/suspicious/noConfusingVoidType: mirrors `Interpret`'s own `Promise<M | void>` — the base handler resolves to a follow-up Msg OR nothing; `M | undefined` would reject no-return bodies\n M | void,\n ResilienceOkMsg | ResilienceErrMsg,\n unknown\n >(\n async (cmd, ctx) => {\n // Compose the base interpret: run the ORIGINAL base Cmd through the base's\n // own handler for its type. The base handler may itself return a follow-up\n // Msg or void; the resilience layer treats its RESOLUTION (resolve vs\n // throw) as the success/failure signal, and carries whatever it returned\n // as `result`. A throw → tryInterpret routes to `$resilience:err`.\n const inner = cmd.input;\n // The base handler's own type is `Interpret<M, C, Ctx>[type]`, i.e.\n // `(cmd, ctx & PortEmitter) => Promise<M | void>`. We read it off the\n // erased `Record` and re-narrow to that contract — the result type is\n // KNOWN (the base Msg union or void), so it is not widened to `unknown`.\n // biome-ignore lint/suspicious/noConfusingVoidType: the base handler contract is `Promise<M | void>` (follow-up Msg or no-return); narrowing to `undefined` would reject void-returning base handlers\n type BaseHandler = (c: C, ctx: Ctx) => Promise<M | void>;\n const handler = (baseInterpret as Record<string, unknown>)[inner.type] as\n | BaseHandler\n | undefined;\n if (handler === undefined) {\n // Unreachable in practice: the construction guard above already refused\n // to build this machine if `baseInterpret[target]` was missing, and the\n // retagged inner Cmd's type is always the target. Kept as defense in\n // depth on the erased-Record read — if it ever fires it routes to\n // `$resilience:err` (errors are data, never swallowed).\n throw new Error(\n `withResilience: no base interpret handler for target Cmd ` +\n `\"${inner.type}\" — the resilient effect has nothing to perform.`,\n );\n }\n return await handler(inner, ctx as unknown as Ctx);\n },\n (result, cmd): ResilienceOkMsg => ({\n type: \"$resilience:ok\",\n key: cmd.key,\n result,\n at: Date.now(),\n }),\n (error, cmd): ResilienceErrMsg => ({\n type: \"$resilience:err\",\n key: cmd.key,\n error,\n at: Date.now(),\n }),\n );\n\n const interpret = {\n ...(baseInterpret as Record<string, unknown>),\n \"$resilience:run\": runHandler,\n } as Interpret<WMsg, WCmd, Ctx>;\n\n // -------------------------------------------------------------------------\n // The `subscribe` map — base cells ⧺ the `$resilience:timer` cell, which\n // delegates the timer lifecycle to the deadline Sub primitive (re-keying the\n // dispatched Msg into the `$resilience:timer` shape). Clock lives here.\n // -------------------------------------------------------------------------\n\n const subscribeMap = {\n ...((baseSubscribe as Record<string, unknown> | undefined) ?? {}),\n \"$resilience:timer\": (\n sub: ResilienceTimerSub,\n ctx: Ctx,\n dispatch: (msg: WMsg) => void,\n ): (() => void) =>\n // Reuse the deadline subscribe cell wholesale: it arms a one-shot timer\n // for `max(0, atMs - Date.now())` and fires when the wall clock crosses\n // `atMs`. We hand it a `DeadlineSub` shape and translate its\n // `deadline_exceeded` Msg into the wrapper's `$resilience:timer` Msg.\n subscribeDeadline(\n { id: sub.id as DeadlineSub[\"id\"], type: \"deadline\", atMs: sub.atMs },\n ctx,\n (dl) =>\n dispatch({ type: \"$resilience:timer\", id: dl.id, atMs: dl.atMs }),\n ),\n };\n\n return {\n init: (loaded, ctx) => {\n // Rehydrate: `loaded !== null` MUST return `[loaded, []]` (no Cmds) — the\n // substrate's replay enforces it. Split the composed loaded Model into its\n // base slice and feed the base its own snapshot so the base rehydrate\n // contract is honored transitively.\n if (loaded !== null) {\n return [loaded, []];\n }\n const [base0, baseCmds] = base.init(null, ctx);\n // The base's OWN init Cmds: NON-target Cmds pass straight through; a\n // TARGET Cmd is RETAGGED (admitted) so it is observed, never raw — the\n // same retag-not-swallow contract the merged update enforces (rule 2). A\n // target Cmd that escaped init raw would bypass the gate AND the carrier,\n // so the resilience layer would never see the effect resolve. At a fresh\n // boot the breaker is closed and the bucket full, so the gate decision is\n // unambiguously ADMIT — but the Cmd must still travel inside a\n // `$resilience:run` carrier (the slice records its `running` phase). Boot\n // is the resilience epoch: the cold gate runs at `at = 0`, harmless here\n // because the breaker is closed (nothing to compare), the cache empty, and\n // the bucket full. Wall time enters once the effect resolves (the\n // `$resilience:ok` / `:err` Msgs carry `at`), exactly as in a transition.\n let resilience = rc.init();\n const initCmds: WCmd[] = [];\n for (const cmd of baseCmds) {\n if (cmd.type !== target) {\n initCmds.push(cmd);\n continue;\n }\n // The boot cold attempt gates at `at = 0` (boot is the resilience epoch:\n // no real Msg drove it, so there is no time-as-data to read). For the\n // circuit / rateLimit / cache bricks that is harmless at a fresh boot —\n // the breaker is closed (nothing to compare), the bucket full, the cache\n // empty, so the gate ADMITS unambiguously and the `0` is never compared\n // against a real instant. The DEADLINE brick is the exception: it anchors\n // the cap at `at + deadline.ms = 0 + ms`, so its `$resilience:deadline`\n // Sub arms at `atMs = ms` and `subscribeDeadline` fires after\n // `max(0, atMs - Date.now()) === 0` ms — i.e. IMMEDIATELY at boot,\n // settling the boot call failed before it can run. A `0`-anchored boot\n // deadline is never the author's intent; it is the same trap the\n // construction guard refuses for transitions (a fabricated `at` the\n // deadline cannot honor). Fail loud: a boot effect that needs a real\n // deadline belongs behind a post-run boot Msg (where a real `at` exists),\n // not an init Cmd. Mirrors the substrate guidance \"boot effects belong in\n // a boot Msg, not init Cmds.\"\n if (config.deadline !== undefined) {\n throw new Error(\n `withResilience: base.init emits the target Cmd \"${target}\" while a ` +\n `deadline brick is configured. The boot cold attempt has no real ` +\n `wall time (boot is gated at at=0), so the deadline would anchor at ` +\n `0 + ${config.deadline.ms}ms and its $resilience:deadline Sub would ` +\n `fire IMMEDIATELY (max(0, atMs - now) === 0), failing the boot call ` +\n `instantly. Move the boot effect out of base.init and into a boot ` +\n `Msg dispatched after run() (where the triggering Msg carries a real ` +\n `at via config.at), so the deadline anchors at a real instant. (Boot ` +\n `effects belong in a boot Msg, not init Cmds.)`,\n );\n }\n const callKey = keyOf(cmd);\n const [nextSlice, runCmds] = rc.attempt(resilience, callKey, cmd, 0);\n resilience = nextSlice;\n for (const rcRun of runCmds) {\n initCmds.push({\n type: \"$resilience:run\",\n key: rcRun.key,\n input: rcRun.input,\n });\n }\n }\n const model: WM = { base: base0, $resilience: resilience };\n return [model, initCmds];\n },\n update: update as unknown as Reducer<WM, WMsg, WCmd>,\n subscriptions,\n subscribe: subscribeMap as unknown as Machine<\n WM,\n WMsg,\n WCmd,\n U | ResilienceTimerSub,\n Ctx\n >[\"subscribe\"],\n interpret,\n } as Machine<WM, WMsg, WCmd, U | ResilienceTimerSub, Ctx>;\n}\n"]}
1
+ {"version":3,"sources":["../../src/with-resilience/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAmPA,IAAM,eAAA,GAAkB,kBAAA;AACxB,IAAM,kBAAA,GAAqB,qBAAA;AAC3B,IAAM,eAAA,GAAkB,oBAAA;AACxB,IAAM,kBAAA,GAAqB,uBAAA;AAG3B,SAAS,iBAAiB,IAAA,EAAsB;AAC9C,EAAA,IAAI,IAAA,CAAK,WAAW,eAAe,CAAA;AACjC,IAAA,OAAO,eAAA,GAAkB,IAAA,CAAK,KAAA,CAAM,eAAA,CAAgB,MAAM,CAAA;AAC5D,EAAA,IAAI,IAAA,CAAK,WAAW,kBAAkB,CAAA;AACpC,IAAA,OAAO,kBAAA,GAAqB,IAAA,CAAK,KAAA,CAAM,kBAAA,CAAmB,MAAM,CAAA;AAClE,EAAA,OAAO,IAAA;AACT;AAGA,SAAS,YAAY,IAAA,EAAsB;AACzC,EAAA,IAAI,IAAA,CAAK,WAAW,eAAe,CAAA;AACjC,IAAA,OAAO,eAAA,GAAkB,IAAA,CAAK,KAAA,CAAM,eAAA,CAAgB,MAAM,CAAA;AAC5D,EAAA,IAAI,IAAA,CAAK,WAAW,kB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AQ;AACvB,UAAA,QAAA,CAAS,KAAK,GAAG,CAAA;AACjB,UAAA;AAAA,QACF;AAiBA,QAAA,IAAI,MAAA,CAAO,aAAa,MAAA,EAAW;AACjC,UAAA,MAAM,IAAI,KAAA;AAAA,YACR,CAAA,gDAAA,EAAmD,MAAM,CAAA,iJAAA,EAGhD,MAAA,CAAO,SAAS,EAAE,CAAA,mWAAA;AAAA,WAM7B;AAAA,QACF;AACA,QAAA,MAAM,OAAA,GAAU,MAAM,GAAG,CAAA;AACzB,QAAA,MAAM,CAAC,WAAW,OAAO,CAAA,GAAI,GAAG,OAAA,CAAQ,UAAA,EAAY,OAAA,EAAS,GAAA,EAAK,CAAC,CAAA;AACnE,QAAA,UAAA,GAAa,SAAA;AAEb,QAAA,QAAA,CAAS,IAAA,CAAK,GAAG,aAAA,CAAc,OAAO,CAAC,CAAA;AAAA,MACzC;AACA,MAAA,MAAM,KAAA,GAAY,EAAE,IAAA,EAAM,KAAA,EAAO,aAAa,UAAA,EAAW;AACzD,MAAA,OAAO,CAAC,OAAO,QAAQ,CAAA;AAAA,IACzB,CAAA;AAAA,IACA,MAAA;AAAA,IACA,aAAA;AAAA,IACA,SAAA,EAAW,YAAA;AAAA,IAOX;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\n * @packageDocumentation\n *\n * @demlik/tea/with-resilience — the INTERCEPTING wrapper of the wrapper tier.\n *\n * `withResilience(base, config)` is a **pure function over machine data**: it\n * takes any `Machine<S, M, C, U, Ctx>`, a chosen TARGET base Cmd type, and a\n * resilience knob, and returns a NEW `Machine` over the composed Model\n * `{ base, $resilience }`. You `run()` / `replay()` the result exactly like any\n * other machine — there is no new runtime, no privileged interception path.\n *\n * This is the HARDEST wrapper. `withTelemetry` only OBSERVES; this one\n * INTERCEPTS. It bolts the resilient-call concern (cache → circuit-breaker →\n * rate-limit → exponential-backoff retry, with a deadline cap) onto a chosen\n * base Cmd WITHOUT the base authoring any of it. The base keeps emitting its\n * plain effect Cmd; the wrapper diverts each one through the resilience gate.\n *\n * ## Retag, never swallow (rule 2 — the whole danger)\n *\n * The merged `update` delegates to `base.update`, then PARTITIONS the base Cmds\n * by type:\n *\n * - A NON-target base Cmd passes through UNCHANGED — byte-identical, in the\n * same slot. The wrapper does not touch effects it was not asked to harden.\n * - A TARGET base Cmd is RETAGGED: it becomes the `input` payload of a\n * `$resilience:run` carrier Cmd (when the gate admits it), OR its gating is\n * RECORDED as a `$resilience:*` decision in the SAME transition (cache hit,\n * circuit-open fast-fail, rate-limited backoff). It is NEVER emitted raw,\n * and it NEVER vanishes without a `$resilience:*` Cmd recording where it\n * went. That recorded divergence is exactly what the conformance gate's\n * `intercepting` option verifies.\n *\n * The resilient-call result Msgs route back through the merged `update`:\n * `$resilience:ok` → `succeed` (close the breaker, fill the cache, reset the\n * retry run), `$resilience:err` → `fail` (trip the breaker, then back off or\n * settle), `$resilience:timer` → `onTimer` (a retry timer re-runs the gate; a\n * deadline timer settles the call failed). Every decision is a Msg/Cmd through\n * the reducer + log — \"why did this fire\" is answerable from the log alone.\n *\n * ## The slice + verbs are REUSED, not reinvented\n *\n * The `$resilience` slice IS resilient-call's `ResilientState<I, R>` (per-key\n * call / retry / circuit / bucket / cache), and the gate / backoff / breaker\n * logic IS its `attempt` / `succeed` / `fail` / `onTimer` verbs + `subs`. The\n * wrapper only ADAPTS the boundary: the verb's `input` is the ORIGINAL base\n * Cmd, the verb's `resilient_run` carrier is renamed to `$resilience:run`, and\n * the sub / timer ids are re-keyed into the `$resilience:` namespace (rule 4).\n *\n * ## The 5 rules it satisfies\n *\n * 1. **Named, serializable slice.** `model.$resilience` is resilient-call's\n * plain-data `ResilientState` — JSON-serializable (the deadline error is a\n * `{_tag,...}` sentinel, never a `new Error`), never a closure.\n * 2. **Retag-and-re-emit, never swallow.** See above — a target base Cmd is\n * always inside a `$resilience:run` inner payload or recorded by a\n * `$resilience:*` divergence Cmd in the same transition.\n * 3. **Every decision is a Msg/Cmd.** Gate / retry-schedule / fast-fail /\n * settle are all `$resilience:*` Cmds and Msgs through the merged `update`.\n * 4. **Subs merge by id.** Base subs ⧺ resilient-call retry/deadline timers,\n * re-keyed `$resilience:retry:{key}` / `$resilience:deadline:{key}`.\n * 5. **Clock out of update.** Backoff jitter RNG is injected at construction;\n * the only clock read is `Date.now()` at the interpret boundary (the\n * `$resilience:run` handler stamps the ok/err Msg `at`) and in the timer\n * Sub. The merged `update` is PURE — `at` arrives as Msg data.\n *\n * ## The retry bound may be a DURATION, not only a count\n *\n * `config.retry` is resilient-call's `AnyRetryPolicy`: a count (`RetryPolicy`),\n * a wall-clock outage budget (`DurationRetryPolicy`, `maxElapsedMs`), or an\n * explicit `unbounded: true`. Nothing extra is wired for the duration bound and\n * nothing extra is required of the base machine — rule 5 already made the clock\n * arrive as DATA on exactly the Msgs the streak is measured from:\n * `$resilience:err.at` (stamped by the wrapper's own `$resilience:run` handler\n * at the interpret boundary) and `$resilience:timer.atMs` (the Sub's fire\n * instant). Those are the two instants `recordFailure` / `shouldRetry` are fed,\n * so an outage budget is measured against true wall time even when\n * `config.at` is absent — the cold gate's `at` never records a failure.\n *\n * `config.at` therefore stays REQUIRED-when-time-sensitive-brick and OPTIONAL\n * otherwise, unchanged: a duration-bounded retry does NOT make it required,\n * because the cold attempt is not a failure observation.\n */\n\nimport { type DeadlineSub, subscribeDeadline } from \"../deadline\";\nimport type {\n Cmd,\n Interpret,\n Machine,\n Reducer,\n Sub,\n UpdateForm,\n} from \"../index\";\nimport { applyCell, formOf, msgKeysOf, subId, tryInterpret } from \"../index\";\nimport { MsgType } from \"../protocol\";\nimport {\n createResilientCall,\n type ResilientConfig,\n type ResilientState,\n} from \"../resilient-call\";\n\n// ===========================================================================\n// Config — the target + the resilience knob + an optional key deriver.\n// ===========================================================================\n\n/**\n * The `withResilience` knob. Extends resilient-call's `ResilientConfig` (every\n * brick optional — omit a brick, omit its gate) with the two fields the wrapper\n * needs that the bare knob does not:\n *\n * - `target` — the `Cmd.type` discriminant of the ONE base Cmd this wrapper\n * hardens. Every other base Cmd passes through untouched.\n * - `keyOf` — OPTIONAL. Derives the per-call resilience `key` from the target\n * base Cmd, so distinct logical calls (distinct urls, distinct ids) get\n * independent retry / cache state. Pure — it runs inside the merged\n * `update`, so it must NOT read the clock / RNG. Defaults to a single\n * shared key (`target`), i.e. one logical call at a time.\n */\nexport interface ResilienceConfig<TC extends Cmd, TM extends { type: string }>\n extends ResilientConfig {\n /** The base `Cmd.type` to make resilient. */\n readonly target: TC[\"type\"];\n /** Optional per-call key deriver. Pure. Defaults to the target type itself. */\n readonly keyOf?: (cmd: TC) => string;\n /**\n * Extracts the real wall-clock time (ms) the TRIGGERING base Msg carries as\n * data — the time-as-data convention `resilient-call` expects on `attempt`.\n *\n * The merged `update` is PURE: it cannot read `Date.now()` (rule 5). The COLD\n * attempt's gate (the very first `attempt` for a target Cmd in a transition)\n * still needs a real instant — the breaker compares `at` against its recorded\n * `openedAtMs`, the cache against its write `at`, the bucket against its last\n * refill `at`, and the deadline cap anchors at `at + deadline.ms`. Fabricating\n * `at = 0` is the betrayal: a cold attempt after a real-time breaker trip then\n * computes cooldown = `0 - realTripTime < 0` forever, so the breaker NEVER\n * recovers, and a `0`-anchored deadline brick fires immediately.\n *\n * So the base Msg that drove this transition MUST carry its own wall time as\n * data, and `at` reads it off that Msg. The merged update passes\n * `at(currentBaseMsg)` into `rc.attempt` for every target Cmd that transition\n * emitted — real time enters the cold gate as Msg data, never `0`.\n *\n * REQUIRED whenever any time-sensitive brick (`circuit`, `rateLimit`, `cache`,\n * `deadline`) is configured — `withResilience` THROWS at construction if such\n * a brick is set and `at` is absent (errors are data: the cold gate needs real\n * time, refuse to build a breaker that can never recover). OPTIONAL when only\n * `retry` is configured: retry backoff reads its time off the result / timer\n * Msgs (`$resilience:err.at`, `$resilience:timer.atMs`), never the cold attempt\n * — so a `0` cold `at` is harmless there. Pure: it runs inside the merged\n * `update`, so it must NOT read the clock / RNG.\n */\n readonly at?: (msg: TM) => number;\n}\n\n// ===========================================================================\n// The slice + the wrapper Cmds/Msgs/Subs/Ports vocabulary.\n// ===========================================================================\n\n/**\n * The composed Model. The base machine's state nests under `base`; the wrapper\n * owns the NAMED `$resilience` slice — resilient-call's `ResilientState` keyed\n * by the per-call `key`, with `I = TC` (the original target base Cmd is the\n * port input) and `R = unknown` (the base interpret handler's result is opaque\n * to the wrapper — it only routes Ok/Err). Plain data → round-trips through\n * `JSON.parse(JSON.stringify(...))` iff the base state does.\n */\nexport interface ResilienceModel<S, TC extends Cmd> {\n readonly base: S;\n readonly $resilience: ResilientState<TC, unknown>;\n}\n\n/**\n * The carrier Cmd the wrapper emits when the gate ADMITS a target base Cmd. It\n * RETAGS the original base Cmd into `input` — the base Cmd is plain data, so no\n * closure (invariant 3). The interpret handler unwraps `input` and runs it\n * through the BASE interpret for that Cmd type. `key` indexes the resilient\n * call this run belongs to.\n */\nexport type ResilienceRunCmd<TC extends Cmd> = Cmd<\"$resilience:run\"> & {\n readonly key: string;\n /** The ORIGINAL base Cmd, retagged — never swallowed. */\n readonly input: TC;\n};\n\n/**\n * The success Msg the `$resilience:run` handler dispatches back when the base\n * interpret resolved OK. Routes to `succeed`. `at` is stamped at the interpret\n * boundary (the one permitted clock read).\n */\nexport type ResilienceOkMsg = {\n readonly type: \"$resilience:ok\";\n readonly key: string;\n readonly result: unknown;\n readonly at: number;\n};\n\n/**\n * The error Msg the `$resilience:run` handler dispatches back when the base\n * interpret threw / rejected. Routes to `fail` (trip the breaker, then back off\n * or settle). `at` is stamped at the interpret boundary.\n */\nexport type ResilienceErrMsg = {\n readonly type: \"$resilience:err\";\n readonly key: string;\n readonly error: unknown;\n readonly at: number;\n};\n\n/**\n * The retry / deadline timer Msg the `$resilience:timer` Sub dispatches when\n * the wall clock crosses the armed instant. Routes to `onTimer`. `id` is the\n * `$resilience:`-namespaced timer id; `atMs` is the fire instant (Msg data, the\n * clock that drove it lives in the Sub).\n */\nexport type ResilienceTimerMsg = {\n readonly type: \"$resilience:timer\";\n readonly id: string;\n readonly atMs: number;\n};\n\n/** Every Msg the wrapper adds to the base's Msg union. */\nexport type ResilienceMsg =\n | ResilienceOkMsg\n | ResilienceErrMsg\n | ResilienceTimerMsg;\n\n/** Every Cmd the wrapper adds to the base's Cmd union. */\nexport type ResilienceCmd<TC extends Cmd> = ResilienceRunCmd<TC>;\n\n/** The Sub the wrapper adds — a deadline-style timer in the `$resilience` family. */\nexport type ResilienceTimerSub = Sub<\"$resilience:timer\"> & {\n readonly atMs: number;\n};\n\n// ===========================================================================\n// Boundary re-keying — the resilient-call namespace ↔ the `$resilience` one.\n// ===========================================================================\n\n// resilient-call emits its carrier as `resilient_run` and keys its timer Subs\n// `resilient:retry:{key}` / `resilient:deadline:{key}`. The wrapper presents the\n// `$resilience:` namespace to the outside world (rule 4) while REUSING the\n// unmodified verbs underneath. These two pure string maps are the only seam:\n// rename the carrier on the way OUT, re-key the timer id on the way IN.\n\nconst RC_RETRY_PREFIX = \"resilient:retry:\";\nconst RC_DEADLINE_PREFIX = \"resilient:deadline:\";\nconst WX_RETRY_PREFIX = \"$resilience:retry:\";\nconst WX_DEADLINE_PREFIX = \"$resilience:deadline:\";\n\n/** resilient-call internal sub id → the `$resilience:`-namespaced public id. */\nfunction toWrapperTimerId(rcId: string): string {\n if (rcId.startsWith(RC_RETRY_PREFIX))\n return WX_RETRY_PREFIX + rcId.slice(RC_RETRY_PREFIX.length);\n if (rcId.startsWith(RC_DEADLINE_PREFIX))\n return WX_DEADLINE_PREFIX + rcId.slice(RC_DEADLINE_PREFIX.length);\n return rcId;\n}\n\n/** The `$resilience:`-namespaced timer id → the resilient-call internal id. */\nfunction toRcTimerId(wxId: string): string {\n if (wxId.startsWith(WX_RETRY_PREFIX))\n return RC_RETRY_PREFIX + wxId.slice(WX_RETRY_PREFIX.length);\n if (wxId.startsWith(WX_DEADLINE_PREFIX))\n return RC_DEADLINE_PREFIX + wxId.slice(WX_DEADLINE_PREFIX.length);\n return wxId;\n}\n\n/**\n * Does the base machine declare `key` as a Msg.type cell, in EITHER update\n * form? The reserved-namespace guard checks the correct level per form (keyed\n * on `formOf`, the same classification `applyCell` / `msgKeysOf` use):\n *\n * - Reducer form (`{ [msgType]: cell }`, values are functions) — the\n * msg-type keys live at the TOP level, so `Object.hasOwn(update, key)`.\n * - Transitions form (`{ [stateType]: { [msgType]: cell } }`, values are\n * records) — the msg-type keys live in the INNER tables, one per state.\n * A reserved msg-type can hide in ANY inner table, so scan EVERY inner\n * table; a collision in even one inner cell would let a transitions-form\n * base squat on e.g. an inner `$resilience:ok` cell that the wrapper's\n * merged update would silently clobber. Top-level `Object.hasOwn` (the\n * old check) only sees state-type keys here and would MISS it entirely.\n */\nfunction updateDeclaresMsgKey(\n machine: { update: object; __form?: UpdateForm },\n key: string,\n): boolean {\n if (formOf(machine) === \"reducer\") {\n // Reducer form — msg-type keys at the top level.\n return Object.hasOwn(machine.update, key);\n }\n // Transitions form — msg-type keys live in each inner state-type table. An\n // inner table can be a callable object (the shape `__form` disambiguates),\n // so accept \"function\" alongside \"object\" here.\n for (const innerTable of Object.values(machine.update)) {\n if (\n innerTable !== null &&\n (typeof innerTable === \"object\" || typeof innerTable === \"function\") &&\n Object.hasOwn(innerTable, key)\n ) {\n return true;\n }\n }\n return false;\n}\n\n// ===========================================================================\n// withResilience — the wrapper.\n// ===========================================================================\n\n/**\n * Wrap `base` so its `config.target` Cmd is run through the resilient-call\n * concern (cache → circuit → rate-limit → retry, deadline-capped). Returns a\n * NEW `Machine` over the composed Model `{ base, $resilience }`, with the\n * base's Msgs/Cmds/Subs/Ctx extended by the wrapper's own.\n *\n * @param base any `Machine<S, M, C, U, Ctx>`.\n * @param config the resilience knob: `target`, the optional bricks, `keyOf`.\n * @param rng injected backoff jitter source. Pass a fixed `() => 0.5` in\n * tests to pin retry delays; defaults to `Math.random` (read only\n * at the verb boundary, never inside the merged `update`).\n */\nexport function withResilience<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n base: Machine<S, M, C, U, Ctx>,\n config: ResilienceConfig<C, M>,\n rng: () => number = Math.random,\n): Machine<\n ResilienceModel<S, C>,\n M | ResilienceMsg,\n C | ResilienceCmd<C>,\n U | ResilienceTimerSub,\n Ctx\n> {\n type WM = ResilienceModel<S, C>;\n type WMsg = M | ResilienceMsg;\n type WCmd = C | ResilienceCmd<C>;\n\n const { target } = config;\n const keyOf = config.keyOf ?? (() => target);\n\n // A time-sensitive brick gates the COLD attempt against real wall time read\n // off the triggering base Msg (`config.at`). Without `at` the cold gate would\n // have to fabricate `0` — and a cold attempt after a real-time breaker trip\n // then computes cooldown = `0 - realTripTime < 0` forever (the breaker NEVER\n // recovers), while a `0`-anchored deadline fires immediately. Refuse to build\n // such a machine: errors are data, surfaced at construction, never a silent\n // breaker that can't recover. Retry alone reads time off the result/timer\n // Msgs, not the cold attempt, so `at` stays optional there.\n const timeSensitiveBrick =\n config.circuit !== undefined ||\n config.rateLimit !== undefined ||\n config.cache !== undefined ||\n config.deadline !== undefined;\n if (timeSensitiveBrick && config.at === undefined) {\n throw new Error(\n \"withResilience: a time-sensitive brick (circuit / rateLimit / cache / \" +\n \"deadline) is configured but `config.at` is missing. The cold-attempt \" +\n \"gate needs the REAL wall time the triggering base Msg carries as data \" +\n \"(time-as-data) — without it the gate would fabricate `at = 0`, so a \" +\n \"cold attempt after a real-time breaker trip computes a negative \" +\n \"cooldown and the breaker NEVER recovers (and a deadline brick fires \" +\n \"immediately). Provide `at: (msg) => msg.<wallTimeField>`.\",\n );\n }\n // Read the triggering base Msg's wall time as data for the cold gate. When no\n // time-sensitive brick is configured `at` may be omitted; the cold attempt\n // then gates at `0`, which is harmless because retry backoff reads its time\n // off the result / timer Msgs, never the cold attempt.\n const atOf = config.at ?? (() => 0);\n\n // The REUSED knob: I = the original target base Cmd, R = the opaque base\n // interpret result. Its verbs / subs / gate are used unmodified; the wrapper\n // only adapts the boundary (carrier rename + timer-id re-keying).\n const rc = createResilientCall<C, unknown>(config, rng);\n\n // -------------------------------------------------------------------------\n // The merged update — a flat Reducer over the composed (non-discriminated)\n // Model. Cells: every base Msg.type (delegating to base.update + partition),\n // plus the three `$resilience:*` Msgs (delegating to the reused verbs).\n // -------------------------------------------------------------------------\n\n type Cell = (state: WM, msg: WMsg) => readonly [WM, readonly WCmd[]];\n const update: Record<string, Cell> = {};\n\n // --- Base-Msg cells: delegate, then PARTITION + retag the target Cmd. ----\n // Base Msg keys enumerated via `msgKeysOf(base)` — keyed on the\n // authoritative `__form` tag, no structural re-derivation here (#275).\n for (const key of msgKeysOf(base)) {\n update[key] = (state, msg) => {\n // 1) Run the base reducer. Its NON-target Cmds pass through unchanged.\n const [nextBase, baseCmds] = applyCell<S, M, C>(\n base,\n state.base,\n msg as M,\n );\n\n // 2) Partition base Cmds: non-target pass straight through; each target\n // Cmd is routed through the resilient-call `attempt` gate, which either\n // emits a `resilient_run` carrier (→ renamed `$resilience:run`,\n // retagging the ORIGINAL base Cmd into `input`), or records the gate\n // decision in the slice with NO carrier (cache hit / circuit-open /\n // rate-limited backoff). Either way the target Cmd never escapes raw\n // and never vanishes off-ledger.\n let resilience = state.$resilience;\n const outCmds: WCmd[] = [];\n // The COLD attempt's gate time — the REAL wall time the triggering base\n // Msg carries as data (rule 5: the merged `update` stays pure; the clock\n // does not enter here, the Msg's own `at` data does). With this real\n // instant the breaker compares `at - openedAtMs` against its cooldown\n // (set by a prior real-time `$resilience:err`), so a cold attempt during\n // cooldown fast-fails and one AFTER cooldown is admitted — the breaker\n // RECOVERS. The cache compares `at` against its stored write `at`, the\n // bucket refills from `at`, and the deadline cap anchors at\n // `at + deadline.ms` — all against true wall time, never a fabricated\n // `0`. Every SUBSEQUENT gate run (`fail` → backoff, retry-timer\n // `onTimer` → re-gate) reads time off the result / timer Msgs the same\n // way. `atOf` defaults to `0` ONLY when no time-sensitive brick is\n // configured (construction throws otherwise), where retry backoff reads\n // its time off the result/timer Msgs and the cold `at` is never compared.\n const at = atOf(msg as M);\n for (const cmd of baseCmds) {\n if (cmd.type !== target) {\n outCmds.push(cmd);\n continue;\n }\n const callKey = keyOf(cmd);\n const [nextSlice, runCmds] = rc.attempt(resilience, callKey, cmd, at);\n resilience = nextSlice;\n // rc.attempt emits 0 or 1 `resilient_run` carriers. `renameRunCmds`\n // renames each into the `$resilience:run` namespace, preserving the\n // retagged `input` (the ORIGINAL base Cmd). Zero carriers = the gate\n // recorded a divergence in `nextSlice` (cache/circuit/backoff) —\n // visible in the slice + log.\n outCmds.push(...renameRunCmds(runCmds));\n }\n\n const next: WM = { base: nextBase, $resilience: resilience };\n return [next, outCmds];\n };\n }\n\n // --- `$resilience:ok` → succeed ------------------------------------------\n update[\"$resilience:ok\"] = (state, msg) => {\n const m = msg as ResilienceOkMsg;\n const [slice, runCmds] = rc.succeed(state.$resilience, m.key, {\n type: MsgType.ResilientOk,\n key: m.key,\n result: m.result,\n at: m.at,\n });\n return [{ ...state, $resilience: slice }, renameRunCmds(runCmds)];\n };\n\n // --- `$resilience:err` → fail --------------------------------------------\n update[\"$resilience:err\"] = (state, msg) => {\n const m = msg as ResilienceErrMsg;\n const [slice, runCmds] = rc.fail(state.$resilience, m.key, {\n type: MsgType.ResilientErr,\n key: m.key,\n error: m.error,\n at: m.at,\n });\n return [{ ...state, $resilience: slice }, renameRunCmds(runCmds)];\n };\n\n // --- `$resilience:timer` → onTimer (retry re-runs gate / deadline settles) -\n update[\"$resilience:timer\"] = (state, msg) => {\n const m = msg as ResilienceTimerMsg;\n // Re-key the public `$resilience:`-id back to the resilient-call internal\n // id the `onTimer` verb matches against, then run the unmodified verb.\n const [slice, runCmds] = rc.onTimer(state.$resilience, {\n type: \"deadline_exceeded\",\n id: toRcTimerId(m.id),\n atMs: m.atMs,\n });\n return [{ ...state, $resilience: slice }, renameRunCmds(runCmds)];\n };\n\n // Rename any `resilient_run` carriers a verb produced (the retry re-attempt\n // path) into the `$resilience:run` namespace, preserving the retagged input.\n function renameRunCmds(\n runCmds: readonly { type: string; key: string; input: C }[],\n ): readonly WCmd[] {\n return runCmds.map((r) => ({\n type: \"$resilience:run\" as const,\n key: r.key,\n input: r.input,\n }));\n }\n\n // -------------------------------------------------------------------------\n // Subs — base subs ⧺ resilient-call timers, re-keyed into `$resilience:`.\n // -------------------------------------------------------------------------\n\n const baseSubscriptions = base.subscriptions;\n const baseSubscribe = (base as { subscribe?: unknown }).subscribe;\n\n function subscriptions(state: WM): readonly (U | ResilienceTimerSub)[] {\n const baseSubs = baseSubscriptions\n ? baseSubscriptions(state.base)\n : ([] as readonly U[]);\n // rc.subs returns DeadlineSubs keyed `resilient:retry:{k}` /\n // `resilient:deadline:{k}`. Re-key each into the `$resilience:` namespace\n // and re-type to the wrapper's `$resilience:timer` Sub family (rule 4).\n const rcSubs: readonly DeadlineSub[] = rc.subs(state.$resilience);\n const timerSubs: ResilienceTimerSub[] = rcSubs.map((s) => ({\n id: subId(toWrapperTimerId(s.id)),\n type: \"$resilience:timer\",\n atMs: s.atMs,\n }));\n return [...baseSubs, ...timerSubs];\n }\n\n // -------------------------------------------------------------------------\n // Interpret — base.interpret for non-target + the `$resilience:run` handler\n // that COMPOSES base.interpret for the retagged inner Cmd.\n // -------------------------------------------------------------------------\n\n const baseInterpret =\n (base as { interpret?: Interpret<M, C, Ctx> }).interpret ??\n ({} as Interpret<M, C, Ctx>);\n\n // Reserved-namespace guard (mirrors withTelemetry + the substrate's\n // definePort / SubId collision asserts). The wrapper OWNS four reserved keys:\n // the `$resilience:run` carrier Cmd, the `$resilience:ok` / `$resilience:err`\n // result Msgs, and the `$resilience:timer` Sub Msg. The merges below spread\n // the wrapper's cells over the base's update / interpret / subscribe maps; if\n // the base already declares ANY reserved key on ANY of those three surfaces,\n // the spread would SILENTLY clobber it (or the base's own key would shadow the\n // wrapper's). The `$resilience:` namespace is the wrapper's — refuse to wrap a\n // base that squats on any of the four across any surface.\n //\n // Ordered BEFORE the target-handler guard below: squatting a reserved key is a\n // target-INDEPENDENT structural defect of the base, so it is the more\n // fundamental rejection and must report first. Otherwise a base that BOTH\n // squats `$resilience:*` AND omits the target handler would surface the\n // narrower missing-target error and mask the namespace collision — exactly the\n // regression #111's construction-time hoist introduced (the hoisted target\n // check shadowed this guard for such a base), fixed by #112.\n //\n // `update` is checked PER FORM (the same `formOf` classification the wrapper\n // already uses via `msgKeysOf` / `applyCell`): a Reducer-form\n // base keys its msg-types at the TOP level, but a Transitions-form base keys\n // them in the INNER `{ [stateType]: { [msgType]: cell } }` tables — so a flat\n // top-level `Object.hasOwn` would MISS a reserved msg-type squatting inside an\n // inner table (e.g. an inner `$resilience:ok` cell) and let the merged update\n // silently clobber it. `interpret` and `subscribe` are always flat keyed-by\n // -type maps, so the direct `Object.hasOwn` is correct there.\n const RESERVED = [\n \"$resilience:run\",\n \"$resilience:ok\",\n \"$resilience:err\",\n \"$resilience:timer\",\n ] as const;\n const surfaces: readonly {\n readonly name: string;\n readonly declares: (reserved: string) => boolean;\n }[] = [\n {\n name: \"update\",\n declares: (reserved) => updateDeclaresMsgKey(base, reserved),\n },\n {\n name: \"interpret\",\n declares: (reserved) => Object.hasOwn(baseInterpret as object, reserved),\n },\n {\n name: \"subscribe\",\n declares: (reserved) =>\n Object.hasOwn((baseSubscribe as object | undefined) ?? {}, reserved),\n },\n ];\n for (const reserved of RESERVED) {\n for (const surface of surfaces) {\n if (surface.declares(reserved)) {\n throw new Error(\n `withResilience: the base machine declares a reserved \"${reserved}\" ` +\n `${surface.name} key — the wrapper owns the \"$resilience:\" ` +\n `namespace ($resilience:run / :ok / :err / :timer across update, ` +\n `interpret, and subscribe). Rename the base key.`,\n );\n }\n }\n }\n\n // Construction guard — the target Cmd MUST have a base interpret handler. This\n // is a property of the (base, config) pair, fully known here at construction:\n // the `$resilience:run` carrier delegates to `baseInterpret[target]`, so a\n // missing handler means the resilient effect has nothing to perform. Surface\n // it now — refuse to build a machine whose target can never run — rather than\n // lazily on the first effect (errors are data, surfaced at construction, like\n // the time-sensitive-`at` and reserved-namespace guards above). Ordered AFTER\n // the reserved-namespace guard so a base that squats `$resilience:*` is\n // rejected for the namespace collision first, not masked by this narrower\n // missing-target error (#112).\n if (!Object.hasOwn(baseInterpret as object, target)) {\n throw new Error(\n `withResilience: no base interpret handler for target Cmd \"${target}\" ` +\n `— the resilient effect has nothing to perform. The base machine must ` +\n `declare an interpret handler for its target Cmd type.`,\n );\n }\n\n // The `$resilience:run` handler delegates to the BASE interpret handler for\n // the retagged inner Cmd's type, wrapped via tryInterpret so Ok routes to\n // `$resilience:ok` and Err to `$resilience:err`. `Date.now()` is stamped here\n // — the ONE permitted clock read (interpret is impure; update is pure).\n const runHandler = tryInterpret<\n ResilienceRunCmd<C>,\n // The carried result is the base interpret handler's resolution, whose\n // contract is `Promise<M | void>` (a follow-up base Msg or nothing — see\n // `Interpret<M, C, Ctx>`). Carrying `M | void` here (not bare `unknown`)\n // keeps the base's follow-up Msg type at the seam; `ResilienceOkMsg.result`\n // then narrows from genuine looseness to \"a base Msg or void\".\n // biome-ignore lint/suspicious/noConfusingVoidType: mirrors `Interpret`'s own `Promise<M | void>` — the base handler resolves to a follow-up Msg OR nothing; `M | undefined` would reject no-return bodies\n M | void,\n ResilienceOkMsg | ResilienceErrMsg,\n unknown\n >(\n async (cmd, ctx) => {\n // Compose the base interpret: run the ORIGINAL base Cmd through the base's\n // own handler for its type. The base handler may itself return a follow-up\n // Msg or void; the resilience layer treats its RESOLUTION (resolve vs\n // throw) as the success/failure signal, and carries whatever it returned\n // as `result`. A throw → tryInterpret routes to `$resilience:err`.\n const inner = cmd.input;\n // The base handler's own type is `Interpret<M, C, Ctx>[type]`, i.e.\n // `(cmd, ctx & PortEmitter) => Promise<M | void>`. We read it off the\n // erased `Record` and re-narrow to that contract — the result type is\n // KNOWN (the base Msg union or void), so it is not widened to `unknown`.\n // biome-ignore lint/suspicious/noConfusingVoidType: the base handler contract is `Promise<M | void>` (follow-up Msg or no-return); narrowing to `undefined` would reject void-returning base handlers\n type BaseHandler = (c: C, ctx: Ctx) => Promise<M | void>;\n const handler = (baseInterpret as Record<string, unknown>)[inner.type] as\n | BaseHandler\n | undefined;\n if (handler === undefined) {\n // Unreachable in practice: the construction guard above already refused\n // to build this machine if `baseInterpret[target]` was missing, and the\n // retagged inner Cmd's type is always the target. Kept as defense in\n // depth on the erased-Record read — if it ever fires it routes to\n // `$resilience:err` (errors are data, never swallowed).\n throw new Error(\n `withResilience: no base interpret handler for target Cmd ` +\n `\"${inner.type}\" — the resilient effect has nothing to perform.`,\n );\n }\n return await handler(inner, ctx as unknown as Ctx);\n },\n (result, cmd): ResilienceOkMsg => ({\n type: \"$resilience:ok\",\n key: cmd.key,\n result,\n at: Date.now(),\n }),\n (error, cmd): ResilienceErrMsg => ({\n type: \"$resilience:err\",\n key: cmd.key,\n error,\n at: Date.now(),\n }),\n );\n\n const interpret = {\n ...(baseInterpret as Record<string, unknown>),\n \"$resilience:run\": runHandler,\n } as Interpret<WMsg, WCmd, Ctx>;\n\n // -------------------------------------------------------------------------\n // The `subscribe` map — base cells ⧺ the `$resilience:timer` cell, which\n // delegates the timer lifecycle to the deadline Sub primitive (re-keying the\n // dispatched Msg into the `$resilience:timer` shape). Clock lives here.\n // -------------------------------------------------------------------------\n\n const subscribeMap = {\n ...((baseSubscribe as Record<string, unknown> | undefined) ?? {}),\n \"$resilience:timer\": (\n sub: ResilienceTimerSub,\n ctx: Ctx,\n dispatch: (msg: WMsg) => void,\n ): (() => void) =>\n // Reuse the deadline subscribe cell wholesale: it arms a one-shot timer\n // for `max(0, atMs - Date.now())` and fires when the wall clock crosses\n // `atMs`. We hand it a `DeadlineSub` shape and translate its\n // `deadline_exceeded` Msg into the wrapper's `$resilience:timer` Msg.\n subscribeDeadline(\n { id: sub.id as DeadlineSub[\"id\"], type: \"deadline\", atMs: sub.atMs },\n ctx,\n (dl) =>\n dispatch({ type: \"$resilience:timer\", id: dl.id, atMs: dl.atMs }),\n ),\n };\n\n return {\n init: (loaded, ctx) => {\n // Rehydrate: `loaded !== null` MUST return `[loaded, []]` (no Cmds) — the\n // substrate's replay enforces it. Split the composed loaded Model into its\n // base slice and feed the base its own snapshot so the base rehydrate\n // contract is honored transitively.\n if (loaded !== null) {\n return [loaded, []];\n }\n const [base0, baseCmds] = base.init(null, ctx);\n // The base's OWN init Cmds: NON-target Cmds pass straight through; a\n // TARGET Cmd is RETAGGED (admitted) so it is observed, never raw — the\n // same retag-not-swallow contract the merged update enforces (rule 2). A\n // target Cmd that escaped init raw would bypass the gate AND the carrier,\n // so the resilience layer would never see the effect resolve. At a fresh\n // boot the breaker is closed and the bucket full, so the gate decision is\n // unambiguously ADMIT — but the Cmd must still travel inside a\n // `$resilience:run` carrier (the slice records its `running` phase). Boot\n // is the resilience epoch: the cold gate runs at `at = 0`, harmless here\n // because the breaker is closed (nothing to compare), the cache empty, and\n // the bucket full. Wall time enters once the effect resolves (the\n // `$resilience:ok` / `:err` Msgs carry `at`), exactly as in a transition.\n let resilience = rc.init();\n const initCmds: WCmd[] = [];\n for (const cmd of baseCmds) {\n if (cmd.type !== target) {\n initCmds.push(cmd);\n continue;\n }\n // The boot cold attempt gates at `at = 0` (boot is the resilience epoch:\n // no real Msg drove it, so there is no time-as-data to read). For the\n // circuit / rateLimit / cache bricks that is harmless at a fresh boot —\n // the breaker is closed (nothing to compare), the bucket full, the cache\n // empty, so the gate ADMITS unambiguously and the `0` is never compared\n // against a real instant. The DEADLINE brick is the exception: it anchors\n // the cap at `at + deadline.ms = 0 + ms`, so its `$resilience:deadline`\n // Sub arms at `atMs = ms` and `subscribeDeadline` fires after\n // `max(0, atMs - Date.now()) === 0` ms — i.e. IMMEDIATELY at boot,\n // settling the boot call failed before it can run. A `0`-anchored boot\n // deadline is never the author's intent; it is the same trap the\n // construction guard refuses for transitions (a fabricated `at` the\n // deadline cannot honor). Fail loud: a boot effect that needs a real\n // deadline belongs behind a post-run boot Msg (where a real `at` exists),\n // not an init Cmd. Mirrors the substrate guidance \"boot effects belong in\n // a boot Msg, not init Cmds.\"\n if (config.deadline !== undefined) {\n throw new Error(\n `withResilience: base.init emits the target Cmd \"${target}\" while a ` +\n `deadline brick is configured. The boot cold attempt has no real ` +\n `wall time (boot is gated at at=0), so the deadline would anchor at ` +\n `0 + ${config.deadline.ms}ms and its $resilience:deadline Sub would ` +\n `fire IMMEDIATELY (max(0, atMs - now) === 0), failing the boot call ` +\n `instantly. Move the boot effect out of base.init and into a boot ` +\n `Msg dispatched after run() (where the triggering Msg carries a real ` +\n `at via config.at), so the deadline anchors at a real instant. (Boot ` +\n `effects belong in a boot Msg, not init Cmds.)`,\n );\n }\n const callKey = keyOf(cmd);\n const [nextSlice, runCmds] = rc.attempt(resilience, callKey, cmd, 0);\n resilience = nextSlice;\n // Same `$resilience:run` retag as the update loop — one helper.\n initCmds.push(...renameRunCmds(runCmds));\n }\n const model: WM = { base: base0, $resilience: resilience };\n return [model, initCmds];\n },\n update: update as unknown as Reducer<WM, WMsg, WCmd>,\n subscriptions,\n subscribe: subscribeMap as unknown as Machine<\n WM,\n WMsg,\n WCmd,\n U | ResilienceTimerSub,\n Ctx\n >[\"subscribe\"],\n interpret,\n } as Machine<WM, WMsg, WCmd, U | ResilienceTimerSub, Ctx>;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { C as Cmd, S as Sub, M as Machine } from '../core-BoB6t7dB.js';
1
+ import { C as Cmd, S as Sub, M as Machine } from '../core-42kapW0n.js';
2
2
 
3
3
  /**
4
4
  * @demlik/tea/with-telemetry — the pattern-setting wrapper of the wrapper tier.
@@ -1,5 +1,5 @@
1
- import '../chunk-MMH7CW5K.js';
2
- import { msgKeysOf, applyCell } from '../chunk-QLA76GIT.js';
1
+ import '../chunk-BP2R7TPP.js';
2
+ import { msgKeysOf, applyCell } from '../chunk-PBDYW2TU.js';
3
3
 
4
4
  // src/with-telemetry/index.ts
5
5
  function withTelemetry(base, config = {}) {
@@ -1,6 +1,6 @@
1
1
  import { QueueItem } from './index.js';
2
- import '../index.js';
3
- import '../core-BoB6t7dB.js';
2
+ import '../runtime-types-gsog27b6.js';
3
+ import '../core-42kapW0n.js';
4
4
 
5
5
  /**
6
6
  * @demlik/tea/work-queue/adapter — the verb seam over the pure queue ops.