@demlik/tea 0.15.0 → 0.17.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 (115) hide show
  1. package/README.md +30 -7
  2. package/dist/agent/index.d.ts +49 -37
  3. package/dist/agent/index.js +12 -8
  4. package/dist/chunk-4LPY67E4.js +18 -0
  5. package/dist/chunk-4LPY67E4.js.map +1 -0
  6. package/dist/chunk-4NTCPTNQ.js +64 -0
  7. package/dist/chunk-4NTCPTNQ.js.map +1 -0
  8. package/dist/{chunk-3B5X7SBB.js → chunk-4PXNZ5UY.js} +11 -9
  9. package/dist/chunk-4PXNZ5UY.js.map +1 -0
  10. package/dist/{chunk-AYS5N6WY.js → chunk-6XBEYZME.js} +62 -172
  11. package/dist/chunk-6XBEYZME.js.map +1 -0
  12. package/dist/chunk-C4U5D5HP.js +380 -0
  13. package/dist/chunk-C4U5D5HP.js.map +1 -0
  14. package/dist/{chunk-QPEVCJ5Q.js → chunk-DFUEAA6L.js} +13 -6
  15. package/dist/chunk-DFUEAA6L.js.map +1 -0
  16. package/dist/{chunk-22POWGFA.js → chunk-GWWCCSDH.js} +46 -20
  17. package/dist/chunk-GWWCCSDH.js.map +1 -0
  18. package/dist/chunk-K4ETBNKS.js +733 -0
  19. package/dist/chunk-K4ETBNKS.js.map +1 -0
  20. package/dist/chunk-KWNCM6XM.js +539 -0
  21. package/dist/chunk-KWNCM6XM.js.map +1 -0
  22. package/dist/{chunk-V46HSVCK.js → chunk-LYVOGOBC.js} +3 -3
  23. package/dist/{chunk-V46HSVCK.js.map → chunk-LYVOGOBC.js.map} +1 -1
  24. package/dist/{chunk-VTQI2NHP.js → chunk-OPH6Y4UT.js} +9 -8
  25. package/dist/chunk-OPH6Y4UT.js.map +1 -0
  26. package/dist/{chunk-Q5CQTBFA.js → chunk-OYR7ENKU.js} +20 -30
  27. package/dist/chunk-OYR7ENKU.js.map +1 -0
  28. package/dist/{chunk-MYXFNWAJ.js → chunk-QNGYQMZB.js} +4 -4
  29. package/dist/chunk-QNGYQMZB.js.map +1 -0
  30. package/dist/chunk-QWIPH4YH.js +98 -0
  31. package/dist/chunk-QWIPH4YH.js.map +1 -0
  32. package/dist/{chunk-TCLBCERH.js → chunk-XBZQT2TD.js} +238 -212
  33. package/dist/chunk-XBZQT2TD.js.map +1 -0
  34. package/dist/{core-DnzqWy6u.d.ts → core-rDbOaJTN.d.ts} +236 -140
  35. package/dist/do/index.d.ts +37 -33
  36. package/dist/do/index.js +21 -14
  37. package/dist/do/index.js.map +1 -1
  38. package/dist/{durable-effects-CWzA-o2B.d.ts → durable-effects-CNaw97Be.d.ts} +1 -1
  39. package/dist/effect/index.d.ts +151 -0
  40. package/dist/effect/index.js +98 -0
  41. package/dist/effect/index.js.map +1 -0
  42. package/dist/extension/index.d.ts +6 -7
  43. package/dist/extension/index.js +3 -2
  44. package/dist/extension/index.js.map +1 -1
  45. package/dist/flow/index.d.ts +68 -59
  46. package/dist/flow/index.js +32 -27
  47. package/dist/flow/index.js.map +1 -1
  48. package/dist/idempotency/index.d.ts +6 -7
  49. package/dist/idempotency/index.js +4 -2
  50. package/dist/{index-KXqTRJyb.d.ts → index-BOrsbdAf.d.ts} +19 -96
  51. package/dist/{index-DrIRb_Ch.d.ts → index-B_BxplWi.d.ts} +1 -1
  52. package/dist/index-CWmsXNdX.d.ts +207 -0
  53. package/dist/{index-C2DwkjlP.d.ts → index-Cberb5Rr.d.ts} +57 -45
  54. package/dist/{index-CSyMYDAB.d.ts → index-CcrKLtse.d.ts} +1 -1
  55. package/dist/{index-CuNO9m8i.d.ts → index-Cx0F2M34.d.ts} +14 -16
  56. package/dist/{index-HSYgG2Yt.d.ts → index-DaX_P35Q.d.ts} +247 -211
  57. package/dist/{index-CA_7I5g9.d.ts → index-q1PoukOZ.d.ts} +137 -246
  58. package/dist/index.d.ts +121 -385
  59. package/dist/index.js +2 -1
  60. package/dist/jev/index.d.ts +133 -97
  61. package/dist/jev/index.js +205 -161
  62. package/dist/jev/index.js.map +1 -1
  63. package/dist/{machine-DGlPWCWI.d.ts → machine-BcfCFMYF.d.ts} +171 -288
  64. package/dist/machine-viz/index.d.ts +5 -5
  65. package/dist/machine-viz/index.js +8 -4
  66. package/dist/machine-viz/index.js.map +1 -1
  67. package/dist/mem/index.d.ts +3 -4
  68. package/dist/mem/index.js +2 -1
  69. package/dist/mem/index.js.map +1 -1
  70. package/dist/node/index.d.ts +119 -78
  71. package/dist/node/index.js +52 -38
  72. package/dist/node/index.js.map +1 -1
  73. package/dist/paginate/index.d.ts +27 -22
  74. package/dist/paginate/index.js +6 -4
  75. package/dist/parity/index.d.ts +4 -5
  76. package/dist/parity/index.js +3 -2
  77. package/dist/parity/index.js.map +1 -1
  78. package/dist/pbt/index.d.ts +2 -2
  79. package/dist/pbt/index.js +2 -1
  80. package/dist/pbt/index.js.map +1 -1
  81. package/dist/persistence/index.d.ts +10 -12
  82. package/dist/persistence/index.js +5 -3
  83. package/dist/promise/index.d.ts +186 -0
  84. package/dist/promise/index.js +5 -0
  85. package/dist/promise/index.js.map +1 -0
  86. package/dist/{protocol-D8VbH-VH.d.ts → protocol-ClRZBhHQ.d.ts} +7 -8
  87. package/dist/react/index.d.ts +36 -17
  88. package/dist/react/index.js +27 -4
  89. package/dist/react/index.js.map +1 -1
  90. package/dist/resilience/index.d.ts +63 -456
  91. package/dist/resilience/index.js +37 -483
  92. package/dist/resilience/index.js.map +1 -1
  93. package/dist/{runtime-types-CMF13BBh.d.ts → runtime-types-B62Ucnxr.d.ts} +132 -389
  94. package/dist/testing/index.d.ts +33 -113
  95. package/dist/testing/index.js +39 -181
  96. package/dist/testing/index.js.map +1 -1
  97. package/dist/timing/index.d.ts +25 -22
  98. package/dist/timing/index.js +4 -3
  99. package/dist/timing/index.js.map +1 -1
  100. package/dist/{types-BseNPIhr.d.ts → types-DPm5YCDQ.d.ts} +2 -2
  101. package/dist/work-queue/index.d.ts +5 -6
  102. package/package.json +20 -7
  103. package/dist/chunk-22POWGFA.js.map +0 -1
  104. package/dist/chunk-3B5X7SBB.js.map +0 -1
  105. package/dist/chunk-66PY5WYF.js +0 -1816
  106. package/dist/chunk-66PY5WYF.js.map +0 -1
  107. package/dist/chunk-AYS5N6WY.js.map +0 -1
  108. package/dist/chunk-L3TND7LA.js +0 -97
  109. package/dist/chunk-L3TND7LA.js.map +0 -1
  110. package/dist/chunk-MYXFNWAJ.js.map +0 -1
  111. package/dist/chunk-Q5CQTBFA.js.map +0 -1
  112. package/dist/chunk-QPEVCJ5Q.js.map +0 -1
  113. package/dist/chunk-TCLBCERH.js.map +0 -1
  114. package/dist/chunk-VTQI2NHP.js.map +0 -1
  115. package/dist/index-ZCMhnVKN.d.ts +0 -272
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/flow/batch-window/index.ts"],"names":[],"mappings":";;;AA0IO,SAAS,eAAA,GAAqC;AACnD,EAAA,OAAO,EAAE,MAAA,EAAQ,EAAC,EAAG,UAAU,IAAA,EAAK;AACtC;AAqBO,SAAS,kBAAA,CACd,IACA,IAAA,EACoB;AACpB,EAAA,OAAO,gBAAA,CAAiB,IAAI,IAAI,CAAA;AAClC;AAmEO,SAAS,OAAA,CACd,MAAA,EACA,KAAA,EACA,IAAA,EACA,EAAA,EACyC;AACzC,EAAA,MAAM,MAAA,GAAS,CAAC,GAAG,KAAA,CAAM,QAAQ,IAAI,CAAA;AAGrC,EAAA,MAAM,QAAA,GAAW,MAAM,QAAA,IAAY,EAAA;AAInC,EAAA,IAAI,OAAO,MAAA,IAAU,IAAA,CAAK,IAAI,CAAA,EAAG,MAAA,CAAO,QAAQ,CAAA,EAAG;AACjD,IAAA,OAAO,CAAC,iBAAmB,EAAG,CAAC,OAAO,KAAA,CAAM,MAAM,CAAC,CAAC,CAAA;AAAA,EACtD;AAEA,EAAA,OAAO,CAAC,EAAE,MAAA,EAAQ,QAAA,EAAS,EAAG,EAAE,CAAA;AAClC;AAuBO,SAAS,QAAA,CACd,MAAA,EACA,KAAA,E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D;AACF","file":"chunk-DFUEAA6L.js","sourcesContent":["/**\n * internal/flow/batch-window — coalesce a stream of items into size- or\n * time-bounded BATCHES, then flush each batch as a single Cmd.\n *\n * What this module actually DELEGATES to, vs. what it merely RE-EXPORTS:\n *\n * - `../deadline` — REAL delegation (the only one). The window timer's Msg\n * is `deadlineExceeded`, keyed on the window's identity. `timerFor` arms it\n * through the engine's built-in `timer` Sub: `maxMs` counted from the\n * transition that opened the window, so a machine needs no runner. The\n * absolute-instant form is still here too — `subsFor` lists the same\n * deadline for `deadlinesSub` + `subscribeDeadline`, which re-arms for the\n * REMAINING time after a `Store` rehydrate rather than a fresh `maxMs`.\n * - `../work-queue` — TYPE re-export only, NOT a sink this module calls. A\n * flush emits a Cmd; the CONSUMER's interpret handler is what enqueues onto a\n * `createQueue(store)`. This module never touches queue status — it has no\n * queue state and no status flip to delegate. It re-exports `EnqueueInput<I>`\n * purely so the consumer's flush Cmd and queue agree on the item shape; any\n * actual status flip belongs in the consumer and is delegated to\n * `../work-queue/ops` there, not here.\n * - `../debounce` — VALUE/TYPE re-export only, NOT wired into `update`. A\n * bursty source (keystrokes, scroll, websocket frames) can be `debounce`d at\n * the host BEFORE it ever becomes an `add` Msg, so the batch window only sees\n * settled items. `debounce` is a sink transformer OUTSIDE `update`;\n * batch-window is the durable, replayable half inside it. Re-exported for\n * one-import ergonomics — this module does not call it.\n *\n * Why this is a knob and not hand-wired logic: the managed state (the buffer +\n * the window-open instant) lives in the Model, so it survives DO eviction /\n * reload (durable) and every transition is still a Msg through `update`\n * (replayable). A closure holding a `setTimeout` and a mutable array would break\n * both — banned. `add` / `onWindow` are PURE: time arrives as an `at`\n * parameter, never `Date.now()`; they return NEW slice values, never mutate.\n *\n * Typical wiring (combinator form):\n *\n * const bw = createBatchWindow<LogLine, Msg>({\n * maxItems: 100,\n * maxMs: 5_000,\n * flush: (items) => ({ type: \"FlushBatch\", items }),\n * });\n *\n * // Model: { batch: BatchWindow<LogLine>, ... }\n * // init: (loaded) => [loaded ?? { batch: bw.init(), ... }, []]\n * // update cells:\n * // LogArrived: (s, m) => mapBatch(s, bw.add(s.batch, m.line, m.at))\n * // deadline_exceeded: (s, m) => mapBatch(s, bw.onWindow(s.batch, m.atMs))\n * // subs: [{ type: \"timer\", deps: (s: Model) => bw.timer(s.batch) }]\n * // at run: run(machine, { interpret }) // `timer` is built in\n *\n * where `mapBatch(s, [batch, cmds]) => [{ ...s, batch }, cmds]` lifts the slice\n * transition into the consumer's Model. The `FlushBatch` Cmd's interpret handler\n * is the consumer's — it is where the batch meets I/O (an `enqueue`, a network\n * POST, an R2 write).\n *\n * Internal since #48 — not published on any subpath; reached from inside the\n * package as `internal/flow/batch-window`. Same one-shape-per-package rule as `deadline`, `cache`, and\n * `work-queue`.\n */\n\nimport type { Cmd, Subscribe, TimerDeps } from \"../../../index\";\n\n// `../debounce` re-export (value + type) for one-import ergonomics — see file\n// header. This module does NOT call debounce; a consumer that wants to debounce\n// a bursty source BEFORE it becomes an `add` Msg reaches it from the same import\n// as the batch window.\nexport { type Debounced, debounce } from \"../../timing/debounce\";\n\nimport {\n type DeadlineExceeded,\n type DeadlineSub,\n type DeadlinesSub,\n deadlineExceeded,\n deadlineSub,\n subscribeDeadline,\n} from \"../../resilience/deadline\";\n\n// `../work-queue` TYPE re-export only (see file header). This module emits a\n// flush Cmd; the CONSUMER's interpret handler enqueues onto a\n// `createQueue(store)`. Re-export the caller-facing enqueue payload type so the\n// consumer's flush Cmd and queue agree on the item shape.\nexport type { EnqueueInput } from \"../../work-queue\";\n\n/**\n * Configuration for a batch window — the knob. Pure config, no mutable state\n * (the `BatchWindow<I>` slice carries that). One config object is shared across\n * every window of one logical stream (often a module-scope const).\n *\n * `flush` is a pure Cmd CONSTRUCTOR, not a closure-with-state: it maps the\n * buffered items to the single Cmd the runtime performs when a window closes.\n * Keeping it a `(items) => Cmd` (not a `(items) => void`) is what keeps the\n * trigger replayable — the flush is a Cmd in the transition's output, never a\n * side effect inside the verb.\n */\nexport interface BatchWindowConfig<I, C extends Cmd> {\n /**\n * Size trigger. A batch flushes the instant its buffer reaches `maxItems`,\n * WITHOUT waiting for the time window — the classic \"send as soon as the\n * page is full\" cutoff. Must be `>= 1`; a config of `maxItems: 0` would flush\n * an empty batch on every `add`, which is never useful, so callers treat `1`\n * as the floor (the verb still behaves: with `maxItems <= 1` every item\n * flushes on arrival, a degenerate but legal \"no batching\" window).\n */\n readonly maxItems: number;\n /**\n * Time trigger, in milliseconds. A batch flushes no later than `openedAt +\n * maxMs` — `openedAt` being the `at` of the item that opened the window. This\n * is the latency ceiling: an item never waits longer than `maxMs` to ship,\n * even if the buffer never reaches `maxItems`.\n */\n readonly maxMs: number;\n /**\n * Map a flushed batch to the single Cmd the runtime performs. Called with the\n * buffered items in arrival order; the returned Cmd is what `add` / `onWindow`\n * emit when a window closes. PURE constructor — no I/O, no clock; the I/O\n * happens later in the consumer's interpret handler for the returned Cmd.\n */\n readonly flush: (items: readonly I[]) => C;\n}\n\n/**\n * The Model slice a batch window owns. `buffer` is the items accumulated for the\n * current open window; `openedAt` is the `at` of the item that OPENED it (the\n * anchor the time trigger measures against), or `null` when the window is\n * closed (buffer empty). The pair is the single source of truth for \"is a\n * window open, and when must it flush by?\" — both plain data so the whole slice\n * is trivially JSON-serializable into a consumer's `Store<S>`.\n *\n * Invariant the verbs preserve: `buffer.length === 0` IFF `openedAt === null`.\n * A non-empty buffer always has an `openedAt`; an empty buffer never does. The\n * window timer Sub keys its arm/disarm off exactly this invariant.\n */\nexport interface BatchWindow<I> {\n readonly buffer: readonly I[];\n readonly openedAt: number | null;\n}\n\n/** The starting slice: closed window, empty buffer. */\nexport function initBatchWindow<I>(): BatchWindow<I> {\n return { buffer: [], openedAt: null };\n}\n\n/**\n * The deadline a batch window's open timer lists: it IS `../deadline`'s\n * `DeadlineSub`, not a re-tagged copy. `atMs` is the absolute flush-by instant\n * (`openedAt + maxMs`). Aliasing the deadline type (rather than redeclaring an\n * identical shape) is what lets `subsFor` return `deadlineSub(...)` with no\n * cast — the value's static type already satisfies this name. Consumers running\n * several windows route each one by the deadline's `id`, not by a distinct type.\n */\nexport type BatchWindowSub = DeadlineSub;\n\n/** The Msg a closed-by-time window dispatches. Alias of `deadline`'s Msg. */\nexport type BatchWindowExpired = DeadlineExceeded;\n\n/**\n * Construct the window-expired Msg for the window identified by `id`, flushing\n * by `atMs`. Re-exported alias of `deadlineExceeded` so the runner and\n * the consumer's reducer share one constructor rather than two literals that\n * can drift. The consumer handles it in a reducer cell by calling `onWindow`.\n */\nexport function batchWindowExpired(\n id: string,\n atMs: number,\n): BatchWindowExpired {\n return deadlineExceeded(id, atMs);\n}\n\n/**\n * The bound knob returned by `createBatchWindow`. `init` + the two pure verbs +\n * `timer` + `subs`, all closing over one `BatchWindowConfig`. The verbs\n * return `readonly [BatchWindow<I>, readonly C[]]`: the next slice and the Cmds\n * to emit (one `flush` Cmd when a window closes, none otherwise).\n */\nexport interface BatchWindowKnob<I, C extends Cmd> {\n /** The starting slice — `initBatchWindow()`. */\n init(): BatchWindow<I>;\n /**\n * Buffer `item` (arrival-stamped `at`), flushing immediately if that brings\n * the buffer to `maxItems`. See `addItem`.\n */\n add(\n state: BatchWindow<I>,\n item: I,\n at: number,\n ): readonly [BatchWindow<I>, readonly C[]];\n /**\n * Flush whatever is buffered because the time window closed. See `onWindow`.\n */\n onWindow(\n state: BatchWindow<I>,\n at: number,\n ): readonly [BatchWindow<I>, readonly C[]];\n /**\n * The built-in `timer` Sub's deps while a window is open, `null` while it is\n * closed. See `timerFor`. `id` keys the Msg so several windows on one\n * machine route distinctly.\n */\n timer(\n state: BatchWindow<I>,\n id?: string,\n ): TimerDeps<BatchWindowExpired> | null;\n /**\n * The window timer as an absolute deadline, listed only while a window is\n * open — for `deadlinesSub` + `subscribeBatchWindow`. See `subsFor`.\n */\n subs(state: BatchWindow<I>, id?: string): readonly BatchWindowSub[];\n}\n\n/**\n * Buffer `item` and decide whether the size trigger fires. PURE.\n *\n * - Empty (closed) window → `item` OPENS it: `openedAt` becomes `at`, buffer\n * becomes `[item]`. This is the anchor the time window measures against.\n * - Open window → `item` appends; `openedAt` is left untouched (the window's\n * latency clock keeps running from the FIRST item, not this one).\n *\n * After buffering, if the buffer has reached `maxItems` the window flushes\n * immediately: emit `config.flush(buffer)` and RESET to the closed slice. The\n * size trigger pre-empts the time trigger — a full page ships now, the window\n * Sub for the (now closed) window disarms on the next reconcile because `subs`\n * returns `[]` for an empty buffer.\n *\n * `maxItems <= 1` is the degenerate \"no batching\" case: every item flushes on\n * arrival (buffer reaches 1 immediately). Legal and useful as a feature flag to\n * disable batching without restructuring the wiring.\n *\n * @param config the knob (maxItems / flush constructor)\n * @param state the current slice\n * @param item the item to buffer\n * @param at the arrival instant (epoch ms) — the caller stamps it; the verb\n * never reads the clock\n */\nexport function addItem<I, C extends Cmd>(\n config: BatchWindowConfig<I, C>,\n state: BatchWindow<I>,\n item: I,\n at: number,\n): readonly [BatchWindow<I>, readonly C[]] {\n const buffer = [...state.buffer, item];\n // A closed window opens at THIS item's `at`; an already-open window keeps its\n // original `openedAt` (the latency clock runs from the first item).\n const openedAt = state.openedAt ?? at;\n\n // Size trigger: a full page ships now, regardless of the time window. The\n // floor of 1 means `maxItems <= 1` flushes every item on arrival.\n if (buffer.length >= Math.max(1, config.maxItems)) {\n return [initBatchWindow<I>(), [config.flush(buffer)]];\n }\n\n return [{ buffer, openedAt }, []];\n}\n\n/**\n * Flush the open window because its time bound was reached. PURE.\n *\n * - Open window (buffer non-empty) → emit `config.flush(buffer)` and RESET to\n * the closed slice.\n * - Closed window (buffer empty) → no-op: return the same slice and no Cmds.\n * This guards the race where the size trigger already flushed and reset the\n * window before the time Sub's Msg lands — a stale `onWindow` after a\n * size-flush must NOT emit an empty batch.\n *\n * `at` is accepted for symmetry with `add` and so the consumer's reducer cell\n * has a uniform `(state, at)` shape; the verb doesn't need it for the flush\n * decision (the buffer's emptiness is the whole signal), but taking it keeps a\n * future \"flush only if the window is genuinely past `openedAt + maxMs`\"\n * tightening a non-breaking change.\n *\n * @param config the knob (flush constructor)\n * @param state the current slice\n * @param at the firing instant (epoch ms) — the caller stamps it; the verb\n * never reads the clock\n */\nexport function onWindow<I, C extends Cmd>(\n config: BatchWindowConfig<I, C>,\n state: BatchWindow<I>,\n _at: number,\n): readonly [BatchWindow<I>, readonly C[]] {\n // Empty buffer = the size trigger already flushed (or nothing arrived). A\n // stale timer Msg must not ship an empty batch — return the slice untouched.\n if (state.buffer.length === 0) return [state, []];\n return [initBatchWindow<I>(), [config.flush(state.buffer)]];\n}\n\n/**\n * The window timer deadline, derived from the slice. PURE.\n *\n * Returns the single deadline targeting `openedAt + maxMs` while a window is\n * open (buffer non-empty), or `[]` while it is closed. Fed through\n * `deadlinesSub`, the engine arms the timer when the list gains the deadline\n * and disarms it (clearing the pending `setTimeout`) when the list loses it —\n * so a size-flush that empties the buffer auto-cancels the now-irrelevant time\n * trigger on the next transition.\n *\n * `id` defaults to `\"batch-window\"`; pass a distinct id per window when a\n * machine runs several so the dispatched `BatchWindowExpired` Msg routes to the\n * right one.\n *\n * @param config the knob (maxMs)\n * @param state the current slice\n * @param id stable identity for this window's timer (default\n * `\"batch-window\"`)\n */\nexport function subsFor<I, C extends Cmd>(\n config: BatchWindowConfig<I, C>,\n state: BatchWindow<I>,\n id = \"batch-window\",\n): readonly BatchWindowSub[] {\n // Closed window → no timer. The invariant (empty buffer IFF openedAt null)\n // means either check suffices; we read `openedAt` so the `atMs` arithmetic\n // below is non-null without a `!`. `deadlineSub` already returns a\n // `DeadlineSub`, which IS `BatchWindowSub` — no cast.\n if (state.openedAt === null) return [];\n return [deadlineSub(id, state.openedAt + config.maxMs)];\n}\n\n/**\n * The built-in `timer` Sub's deps for a batch window. PURE.\n *\n * While a window is open it counts `maxMs` down from the transition that\n * opened it — the deps are fixed for the window's life (`openedAt` never moves\n * while items append), so the engine starts the countdown exactly once — and\n * fires `batchWindowExpired(id, openedAt + maxMs)`. A closed window is `null`,\n * so a size-flush that empties the buffer cancels the countdown on the next\n * transition.\n *\n * Relative by construction: a process that rehydrates an open window counts a\n * fresh `maxMs`. Reach for `subsFor` + `subscribeBatchWindow` when the flush\n * must land at the original absolute instant.\n */\nexport function timerFor<I, C extends Cmd>(\n config: BatchWindowConfig<I, C>,\n state: BatchWindow<I>,\n id = \"batch-window\",\n): TimerDeps<BatchWindowExpired> | null {\n if (state.openedAt === null) return null;\n return {\n ms: config.maxMs,\n msg: batchWindowExpired(id, state.openedAt + config.maxMs),\n };\n}\n\n/**\n * The `deadline` runner for a batch window's absolute timer — the exact\n * `../deadline` runner. Arms a one-shot timer per listed deadline for\n * `max(0, atMs - now)` and dispatches `batchWindowExpired(...)`; returns a\n * cleanup that clears them. Hand it to `run` as `subscribe.deadline` when the\n * machine declares `deadlinesSub((s) => bw.subs(s.batch))`.\n */\nexport const subscribeBatchWindow: Subscribe<\n BatchWindowExpired,\n DeadlinesSub,\n unknown\n>[\"deadline\"] = subscribeDeadline;\n\n/**\n * Build a batch window knob from a config. Combinator form (the default L2\n * ergonomic): hand it the config, splice the ~4 returned hooks into your\n * machine. The pure verbs (`add` / `onWindow`) close over the config so the\n * consumer's reducer cells stay a uniform `(state, ...args)` shape; `timer`\n * arms the window timer.\n *\n * @typeParam I the item type buffered into each batch\n * @typeParam C the Cmd type `config.flush` returns\n */\nexport function createBatchWindow<I, C extends Cmd>(\n config: BatchWindowConfig<I, C>,\n): BatchWindowKnob<I, C> {\n return {\n init: () => initBatchWindow<I>(),\n add: (state, item, at) => addItem(config, state, item, at),\n onWindow: (state, at) => onWindow(config, state, at),\n timer: (state, id) => timerFor(config, state, id),\n subs: (state, id) => subsFor(config, state, id),\n };\n}\n"]}
@@ -1,21 +1,38 @@
1
- import { fromInterval, subId, fromTimeout } from './chunk-66PY5WYF.js';
1
+ import { fromInterval } from './chunk-C4U5D5HP.js';
2
+ import { subId } from './chunk-K4ETBNKS.js';
2
3
 
3
4
  // src/internal/resilience/deadline/index.ts
5
+ function deadlines(list) {
6
+ return list.length === 0 ? null : list;
7
+ }
8
+ function deadlinesSub(select) {
9
+ return { type: "deadline", deps: (state) => deadlines(select(state)) };
10
+ }
4
11
  function deadlineSub(id, atMs, opts) {
5
12
  return { ...opts, id: subId(id), type: "deadline", atMs };
6
13
  }
7
14
  function subscribeWith(armTimer) {
8
- return (sub, _ctx, dispatch) => armTimer(
9
- sub.id,
10
- sub.atMs,
11
- deadlineExceeded(sub.id, sub.atMs, sub.name),
12
- dispatch
13
- );
15
+ return (sub, _ctx, dispatch) => {
16
+ const cancels = sub.deps.map(
17
+ (deadline) => armTimer(
18
+ deadline.id,
19
+ deadline.atMs,
20
+ deadlineExceeded(deadline.id, deadline.atMs, deadline.name),
21
+ dispatch
22
+ )
23
+ );
24
+ return () => {
25
+ for (const cancel of cancels) cancel();
26
+ };
27
+ };
14
28
  }
15
29
  function setTimeoutArmTimer() {
16
- return (id, atMs, msg, dispatch) => {
17
- const delayMs = Math.max(0, atMs - Date.now());
18
- return fromTimeout(() => msg)({ id, type: "deadline", delayMs }, void 0, dispatch);
30
+ return (_id, atMs, msg, dispatch) => {
31
+ const handle = setTimeout(
32
+ () => dispatch(msg),
33
+ Math.max(0, atMs - Date.now())
34
+ );
35
+ return () => clearTimeout(handle);
19
36
  };
20
37
  }
21
38
  var subscribeDeadline = (sub, ctx, dispatch) => subscribeWith(setTimeoutArmTimer())(sub, ctx, dispatch);
@@ -25,6 +42,19 @@ function deadlineExceeded(id, atMs, name) {
25
42
  function deadlineMsgType(name) {
26
43
  return name === void 0 ? "deadline_exceeded" : `${name}_deadline`;
27
44
  }
45
+ function nextTimer(list, nowMs) {
46
+ let soonest;
47
+ for (const deadline of list) {
48
+ if (soonest === void 0 || deadline.atMs < soonest.atMs) {
49
+ soonest = deadline;
50
+ }
51
+ }
52
+ if (soonest === void 0) return null;
53
+ return {
54
+ ms: Math.max(0, soonest.atMs - nowMs),
55
+ msg: deadlineExceeded(soonest.id, soonest.atMs, soonest.name)
56
+ };
57
+ }
28
58
 
29
59
  // src/internal/resilience/cache/index.ts
30
60
  function initCache() {
@@ -64,15 +94,11 @@ function evictExpired(cache, nowMs) {
64
94
  function cacheEvictMsg(id) {
65
95
  return { type: "cache_evict", id };
66
96
  }
67
- function cacheEvictionSub(id, everyMs) {
68
- return {
69
- id,
70
- type: "cache",
71
- intervalMs: everyMs
72
- };
97
+ function cacheEvictionSub(name, everyMs) {
98
+ return { type: "cache", deps: () => ({ name, intervalMs: everyMs }) };
73
99
  }
74
- var cacheEvictionSubscribe = fromInterval((sub) => cacheEvictMsg(sub.id));
100
+ var cacheEvictionSubscribe = fromInterval((sub) => cacheEvictMsg(sub.deps.name));
75
101
 
76
- export { cacheEvictMsg, cacheEvictionSub, cacheEvictionSubscribe, deadlineExceeded, deadlineMsgType, deadlineSub, evictExpired, get, has, initCache, remove, set, setTimeoutArmTimer, subscribeDeadline, subscribeWith };
77
- //# sourceMappingURL=chunk-22POWGFA.js.map
78
- //# sourceMappingURL=chunk-22POWGFA.js.map
102
+ export { cacheEvictMsg, cacheEvictionSub, cacheEvictionSubscribe, deadlineExceeded, deadlineMsgType, deadlineSub, deadlines, deadlinesSub, evictExpired, get, has, initCache, nextTimer, remove, set, setTimeoutArmTimer, subscribeDeadline, subscribeWith };
103
+ //# sourceMappingURL=chunk-GWWCCSDH.js.map
104
+ //# sourceMappingURL=chunk-GWWCCSDH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/resilience/deadline/index.ts","../src/internal/resilience/cache/index.ts"],"names":[],"mappings":";;;;AA8FO,SAAS,UACd,IAAA,EACkC;AAClC,EAAA,OAAO,IAAA,CAAK,MAAA,KAAW,CAAA,GAAI,IAAA,GAAO,IAAA;AACpC;AAQO,SAAS,aACd,MAAA,EACiC;AACjC,EAAA,OAAO,EAAE,IAAA,EAAM,UAAA,EAAY,IAAA,EAAM,CAAC,UAAU,SAAA,CAAU,MAAA,CAAO,KAAK,CAAC,CAAA,EAAE;AACvE;AAiFO,SAAS,WAAA,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sBAAA,GAIT,aAAa,CAAC,GAAA,KAAQ,cAAc,GAAA,CAAI,IAAA,CAAK,IAAI,CAAC","file":"chunk-GWWCCSDH.js","sourcesContent":["/**\n * internal/resilience/deadline — a one-shot Sub that fires when an ABSOLUTE wall-clock\n * deadline is reached.\n *\n * Generalizes the recurring \"auto-fail a machine at T+N\" / \"15-minute stale\n * guard\" pattern: a deadline a battery lists only while it should be armed,\n * which dispatches a single `DeadlineExceeded` Msg when the wall clock crosses\n * `atMs`.\n *\n * A battery's `subs(slice)` returns its deadlines as a LIST (`DeadlineSub[]`,\n * one per retry timer, say). A machine declares that list as ONE Sub of type\n * `\"deadline\"` whose `deps` is the list (`deadlinesSub(select)`), and the\n * `deadline` runner arms every deadline in it. A change to the list restarts\n * the runner, which re-arms each deadline for its REMAINING time — `atMs` is\n * absolute, so a restart never moves a deadline.\n *\n * Difference from `fromTimeout` (relative — \"fire after N ms\"): a deadline is\n * an ABSOLUTE target. The delay is computed at subscribe time as\n * `max(0, atMs - Date.now())`. The consequence that matters: subscribing LATE —\n * e.g. after a `Store` rehydrate that resumes a machine whose deadline was set\n * before the page reloaded — still fires at the correct absolute moment,\n * because the remaining delay is recomputed from the current clock, not stored\n * in the Sub. A deadline already in the past at subscribe time yields delay `0`,\n * so `setTimeout(fn, 0)` fires on the NEXT tick (never synchronously inside the\n * reconcile pass — the substrate must finish wiring all subs before any Msg\n * lands).\n *\n * `deadlineSub` produces one deadline literal carrying `atMs`; the runner\n * (`subscribeDeadline`) translates each `atMs` → a relative delay and arms a\n * `setTimeout` / `clearTimeout` pair per deadline. The clock\n * read (`Date.now()`) lives only in the subscribe handler — never in a reducer\n * (invariant 2) — and is exercised in tests via vitest fake timers, matching\n * the no-injection convention of the `fromTimeout` / `fromInterval` exemplars.\n *\n * WHAT BACKS THE TIMER IS THE HOST'S CHOICE. `setTimeout` is the universal\n * default, but it is not universal: a Durable Object that hibernates has no\n * live `setTimeout` to wake it, so its deadline must be backed by a `do_alarm`\n * registered on the alarm registry; a test host wants a fake-timer schedule.\n * That backing is the `ArmTimer` seam — `subscribeWith(armTimer)` builds the\n * `subscribe.deadline` handler from a host-plugged timer, and `subscribeDeadline`\n * IS `subscribeWith(setTimeoutArmTimer())`. One deadline surface, three hosts;\n * there is no second Sub type and no second `atMs` anchor to keep in sync.\n *\n * The anchor is what makes the seam safe. `atMs` is ABSOLUTE, so whatever backs\n * it arms to a fixed wall-clock instant: the host computes the gap itself\n * (`atMs - Date.now()`), and on a host that just rehydrated after hibernation\n * that gap is the SHRUNKEN remainder — the deadline honours the original target\n * rather than resetting to a fresh full-length window.\n *\n * Strengthens invariant 4 (external time is a subscription — the deadline is a\n * `Sub` the runtime reconciles, never a `setTimeout` leaked into a reducer) and\n * invariant 7 (identity is explicit — the Sub carries a stable `SubId`, so the\n * reconcile pass leaves it running across transitions instead of churning it).\n */\n\nimport type {\n DepKeyedSub,\n Dispose,\n Sub,\n SubId,\n TimerDeps,\n} from \"../../../index\";\nimport { subId } from \"../../../index\";\n\n/**\n * One deadline, as a battery lists it. `atMs` is the absolute target — epoch\n * milliseconds (the `Date.now()` / `Date.parse(...)` scale), NOT a relative\n * delay. `id` names the deadline inside its list: it rides on the dispatched\n * Msg so a reducer can tell WHICH deadline fired, and a registry-backed timer\n * (a DO alarm slot) keys its entry on it.\n *\n * It is plain data — it becomes part of the `deadline` Sub's `deps`, which the\n * engine hashes — and is not itself a running Sub.\n */\nexport type DeadlineSub<N extends string | undefined = undefined> = {\n readonly id: SubId;\n readonly type: \"deadline\";\n readonly atMs: number;\n} & DeadlineOpts<N>;\n\n/**\n * The running `\"deadline\"` Sub: its `deps` is the non-empty list of deadlines\n * to arm. Name it in `types.sub` for a machine that arms deadlines.\n */\nexport type DeadlinesSub<N extends string | undefined = undefined> = Sub<\n \"deadline\",\n readonly DeadlineSub<N>[]\n>;\n\n/**\n * The `deps` of a `deadline` Sub: the list, or `null` when it is empty — an\n * empty list is a Sub with nothing to arm, and an off Sub is not a live one\n * (`driveToDone` reads live Subs to tell a waiting machine from a stalled one).\n */\nexport function deadlines<N extends string | undefined = undefined>(\n list: readonly DeadlineSub<N>[],\n): readonly DeadlineSub<N>[] | null {\n return list.length === 0 ? null : list;\n}\n\n/**\n * The `subs` entry that arms whatever deadlines `select` lists at a state:\n *\n * subs: [deadlinesSub((s: State) => rc.subs(s.resilience))],\n * // run(machine, { subscribe: { deadline: subscribeDeadline } })\n */\nexport function deadlinesSub<S, N extends string | undefined = undefined>(\n select: (state: S) => readonly DeadlineSub<N>[],\n): DepKeyedSub<S, DeadlinesSub<N>> {\n return { type: \"deadline\", deps: (state) => deadlines(select(state)) };\n}\n\n/**\n * Additive options the `deadlineSub` factory folds onto the Sub literal. This\n * is the extension seam (invariant 5 — composition by reduction): future fields\n * — `repeatMs` for a re-arming deadline, `jitterMs` for spread, etc. — land HERE\n * as optional members, and every existing call site keeps compiling because the\n * factory's third parameter is optional and the fields are `readonly` optionals\n * on `DeadlineSub`. Callers are insulated from the concrete `DeadlineSub` shape:\n * they ask for what they need by name, never positionally, so a shape extension\n * never rewrites the ~13 `deadlineSub(id, atMs)` call sites.\n *\n * The first field to land here is {@link DeadlineOpts.name} — the knob name the\n * dispatched Msg tag is derived from — and it landed exactly that way: one\n * optional member, zero rewritten call sites.\n */\nexport type DeadlineOpts<N extends string | undefined = undefined> = {\n /**\n * The knob this deadline belongs to. Present → the dispatched Msg's tag is\n * `` `${name}_deadline` ``; absent → the tag stays the bare\n * `\"deadline_exceeded\"` every machine wired before this field is already\n * handling. `N` is the name as a TYPE as well as a value, so a consumer's\n * cell key and the Msg type are derived from one place and cannot drift.\n *\n * Name a deadline when a machine arms more than one family of them. The Sub\n * *id* was already scoped (`` `${name}:deadline:${key}` ``); this scopes the\n * Msg the Sub dispatches, which is what a reducer cell keys off.\n */\n readonly name?: N;\n};\n\n/**\n * The Msg the deadline dispatches when the wall clock crosses `atMs`. Exported\n * as a tagged shape so consumers can union it into their machine's Msg type and\n * handle it in a reducer cell. `id` lets a reducer disambiguate WHICH deadline\n * fired when a machine arms several at once; `atMs` echoes the target the timer\n * was scheduled against (useful for assertions / observability).\n *\n * Snake-shaped `\"deadline_exceeded\"` matches the tagged-Msg style this module's\n * orchestrator requested; the actor-in-name PascalCase convention\n * (`TimerFiredDeadline`) is the consumer's to apply at their own boundary if\n * they prefer — `deadlineExceeded(...)` only fixes the wire shape, not the\n * consumer's local dialect.\n */\nexport type DeadlineExceeded<N extends string | undefined = undefined> = {\n readonly type: DeadlineMsgType<N>;\n readonly id: string;\n readonly atMs: number;\n};\n\n/**\n * The dispatched Msg's tag, derived from the deadline's optional name. A named\n * deadline speaks `` `${N}_deadline` ``; an unnamed one speaks the bare\n * `\"deadline_exceeded\"` literal, which is what `DeadlineExceeded` with no type\n * argument still means — so every machine wired before the name existed keeps\n * the exact type it had.\n */\nexport type DeadlineMsgType<N extends string | undefined> = N extends string\n ? `${N}_deadline`\n : \"deadline_exceeded\";\n\n/**\n * Build a deadline literal. Pure data — no clock read, no timer; the timer\n * is armed later by the `deadline` runner. `id` is branded via `subId(...)` so\n * accidental raw-string drift fails at the type level (invariant 7).\n *\n * List it from a battery's `subs(slice)` while the deadline should be armed;\n * drop it to disarm — the engine restarts the `deadline` Sub, whose cleanup\n * clears the pending timer before it fires. That is the \"cancel on state exit\"\n * lifecycle.\n *\n * @param id Identity for this deadline, echoed on the Msg it fires. Use\n * distinct ids for distinct deadlines on the same machine.\n * @param atMs Absolute target in epoch milliseconds (e.g. `Date.now() + 900_000`\n * for a 15-minute guard, or a persisted `expiresAt`).\n * @param opts Optional additive fields folded onto the Sub literal (see\n * {@link DeadlineOpts}). Omit it for the common case; pass it when a\n * future field (e.g. `repeatMs`) needs to ride on the deadline. The\n * optionality is the future-proofing seam — extending the shape\n * never breaks an existing `deadlineSub(id, atMs)` call site.\n */\nexport function deadlineSub<N extends string | undefined = undefined>(\n id: string,\n atMs: number,\n opts?: DeadlineOpts<N>,\n): DeadlineSub<N> {\n return { ...opts, id: subId(id), type: \"deadline\", atMs };\n}\n\n/**\n * The host-plugged timer backing. Given the deadline's stable `id`, its\n * absolute `atMs`, and the Msg to fire, arm the platform-appropriate timer\n * (DO alarm registry, `setTimeout`, fake timer) and return a cleanup that\n * cancels the pending fire.\n *\n * `id` is the deadline's own id — a registry-backed host (the DO alarm slot)\n * keys its entry on `id` so the cleanup deletes the EXACT entry it armed. A\n * `setTimeout`-backed host ignores `id` (the closure holds the handle).\n *\n * The host computes the gap itself: `atMs - Date.now()` is the REMAINING time.\n * On a host that just rehydrated after hibernation that gap is the shrunken\n * remainder — the deadline is NOT reset to its full length. That recomputation\n * is the reason `atMs` rides on the Sub as an absolute instant rather than a\n * delay: the anchor is what every backing agrees on.\n */\nexport type ArmTimer<M> = (\n id: SubId,\n atMs: number,\n msg: M,\n dispatch: (msg: M) => void,\n) => () => void;\n\n/**\n * Build the `deadline` runner from a host-plugged `armTimer`. This module owns\n * the deadline shape, the anchor, and the Msg; the HOST owns what backs the\n * timer. The runner arms every deadline in the Sub's `deps` list — reading\n * `id` + `atMs`, building the `deadlineExceeded(...)` Msg and handing all three\n * to `armTimer` — and its cleanup cancels them all.\n *\n * Use it when `setTimeout` is the wrong backing — most concretely a Durable\n * Object, which hibernates and must register a `do_alarm` instead:\n *\n * run(machine, {\n * subscribe: {\n * deadline: subscribeWith((id, atMs, msg, dispatch) =>\n * alarms.register(id, atMs, () => dispatch(msg)),\n * ),\n * },\n * })\n *\n * For the `setTimeout` default, use {@link subscribeDeadline} — it is exactly\n * `subscribeWith(setTimeoutArmTimer())`, so there is one deadline surface and\n * one anchor, not a second one per host.\n */\nexport function subscribeWith<N extends string | undefined = undefined>(\n armTimer: ArmTimer<DeadlineExceeded<N>>,\n): (\n sub: DeadlinesSub<N>,\n ctx: unknown,\n dispatch: (msg: DeadlineExceeded<N>) => void,\n) => Dispose {\n return (sub, _ctx, dispatch) => {\n const cancels = sub.deps.map((deadline) =>\n armTimer(\n deadline.id,\n deadline.atMs,\n deadlineExceeded(deadline.id, deadline.atMs, deadline.name),\n dispatch,\n ),\n );\n return () => {\n for (const cancel of cancels) cancel();\n };\n };\n}\n\n/**\n * The `setTimeout` timer backing — for node / browser / any host whose timer is\n * a plain `setTimeout`. Arms for the REMAINING time (`max(0, atMs - Date.now())`,\n * floored at 0 so an already-past deadline fires on the NEXT tick rather than\n * synchronously inside the reconcile pass), so a deadline re-derived after a\n * rehydrate — or re-armed by a restart — fires at the original instant, not a\n * fresh full window. A hibernating host does NOT use this — it plugs its own\n * `armTimer` (a `do_alarm` registration) into {@link subscribeWith}.\n */\nexport function setTimeoutArmTimer<\n N extends string | undefined = undefined,\n>(): ArmTimer<DeadlineExceeded<N>> {\n return (_id, atMs, msg, dispatch) => {\n // Recompute the remaining delay from the CURRENT clock so a late start\n // (post-rehydrate, or a restart) still targets the same absolute moment.\n const handle = setTimeout(\n () => dispatch(msg),\n Math.max(0, atMs - Date.now()),\n );\n return () => clearTimeout(handle);\n };\n}\n\n/**\n * The `deadline` runner for the DEFAULT `setTimeout` backing. Arms a one-shot\n * timer per listed deadline for its remaining delay `max(0, atMs - Date.now())`\n * and dispatches `deadlineExceeded(...)` when each fires; the cleanup clears\n * every pending timer.\n *\n * It is `subscribeWith(setTimeoutArmTimer())` — the default backing named, not\n * a separate implementation, so the host-plugged path and the default path can\n * never disagree about the anchor.\n *\n * run(machine, { subscribe: { deadline: subscribeDeadline } })\n *\n * Generic in the deadline's name so ONE runner serves every knob in a machine:\n * the tag it dispatches is read off each deadline's own `name`, so a machine\n * listing a named knob's deadlines beside an unnamed one's wires this once.\n */\nexport const subscribeDeadline: <N extends string | undefined = undefined>(\n sub: DeadlinesSub<N>,\n ctx: unknown,\n dispatch: (msg: DeadlineExceeded<N>) => void,\n) => Dispose = <N extends string | undefined>(\n sub: DeadlinesSub<N>,\n ctx: unknown,\n dispatch: (msg: DeadlineExceeded<N>) => void,\n) => subscribeWith<N>(setTimeoutArmTimer<N>())(sub, ctx, dispatch);\n\n/**\n * Construct the Msg the deadline dispatches. Exported so consumers can build /\n * assert the same shape (and so the runner and tests share one\n * constructor rather than two literals that can drift).\n */\nexport function deadlineExceeded<N extends string | undefined = undefined>(\n id: string,\n atMs: number,\n name?: N,\n): DeadlineExceeded<N> {\n return { type: deadlineMsgType(name), id, atMs };\n}\n\n/**\n * The one place the named tag is spelled. `undefined` → the bare\n * `\"deadline_exceeded\"` literal; a name → `` `${name}_deadline` ``. Exported so\n * a consumer keying a reducer cell off a named deadline derives the key from\n * the same function the Sub dispatches through, instead of re-spelling the\n * template and drifting.\n */\nexport function deadlineMsgType<N extends string | undefined>(\n name?: N,\n): DeadlineMsgType<N> {\n return (\n name === undefined ? \"deadline_exceeded\" : `${name}_deadline`\n ) as DeadlineMsgType<N>;\n}\n\n/**\n * The built-in `timer` Sub's deps for the SOONEST deadline in `list`, counted\n * from `nowMs`; `null` when the list is empty (no timer armed).\n *\n * This is how a battery arms a whole deadline list through the engine's\n * built-in `timer` instead of a `deadline` runner: a machine declares ONE\n * `{ type: \"timer\", deps: (s) => nextTimer(list(s), clock(s)) }` entry. The\n * timer fires the soonest deadline's `DeadlineExceeded` Msg; the transition it\n * causes drops that deadline from the list, and the next soonest is armed.\n *\n * `nowMs` is the instant the list was last computed against — the battery's\n * own record of its latest transition, never a clock read (invariant 2). The\n * countdown is `atMs - nowMs`, clamped at `0`, and because `ms` is part of the\n * deps, every new `nowMs` restarts the countdown from that instant. PURE.\n */\nexport function nextTimer<N extends string | undefined = undefined>(\n list: readonly DeadlineSub<N>[],\n nowMs: number,\n): TimerDeps<DeadlineExceeded<N>> | null {\n let soonest: DeadlineSub<N> | undefined;\n for (const deadline of list) {\n if (soonest === undefined || deadline.atMs < soonest.atMs) {\n soonest = deadline;\n }\n }\n if (soonest === undefined) return null;\n return {\n ms: Math.max(0, soonest.atMs - nowMs),\n msg: deadlineExceeded(soonest.id, soonest.atMs, soonest.name),\n };\n}\n","/**\n * internal/resilience/cache — a TTL cache as pure state, PLUS a periodic eviction Sub.\n *\n * Same pure-state-ops shape as `../../idempotency/` and\n * `../../work-queue/ops.ts`: a state type plus pure transition functions. Host-\n * agnostic by construction — no `Date.now()`, no timers, no I/O inside the ops.\n * The caller injects the clock (`nowMs`) and folds the result through its own\n * reducer, keeping the store inside TEA's invariant 2 (transitions are pure:\n * same inputs → same outputs) so a consumer can exercise it with `replay`\n * without a fake clock.\n *\n * Every op returns a NEW cache value and never mutates its input (invariant 1 —\n * state is a value, not a place). `get` / `has` are read-shaped; `set` /\n * `remove` / `evictExpired` return a new cache.\n *\n * **Distinct from `/idempotency`.** Both are TTL-bounded key maps, but they\n * answer different questions and so carry different shapes:\n *\n * - `/idempotency` is DEDUPE-focused — \"have I already processed this key?\"\n * TTL is a single store-level policy (`ttlMs`), each entry stores the\n * `atMs` it was remembered at, and expiry is derived (`now - atMs >=\n * ttlMs`). It carries an `order` ledger + `capacity` because the use case\n * (webhook receivers, retried messages) needs bounded LRU eviction.\n * - `/cache` is RETRIEVAL-focused — \"what is the value for this key right\n * now?\" TTL is set PER ENTRY at write time: `set(key, value, nowMs,\n * ttlMs)` bakes the absolute `expiresAtMs = nowMs + ttlMs` into the entry.\n * Different keys can carry different lifetimes (a hot key cached for 1s, a\n * cold one for 1h) — the dimension idempotency's single store-level\n * `ttlMs` cannot express. No `order`, no `capacity`: a cache bounds itself\n * by TTL + periodic eviction, not by LRU count.\n *\n * The eviction Sub is the \"eviction is a Msg\" half: a `setInterval`-shaped Sub\n * (composed directly on `fromInterval`, from `src/subs/`) that periodically\n * dispatches a `cache_evict` Msg the consumer's reducer handles by calling\n * `evictExpired`. Time still never enters the reducer — the Sub fires the Msg,\n * the reducer reads `nowMs` off the Msg (the consumer stamps it at the Sub\n * boundary), and `evictExpired` does the pure drop.\n *\n * Internal to the package (`src/internal/resilience/`), not a published\n * subpath (#46); same one-shape-per-module rule as `work-queue`, `idempotency`,\n * and `rate-limit`.\n */\n\nimport type { DepKeyedSub, Sub } from \"../../../index\";\nimport { fromInterval } from \"../../../subs\";\nimport type { SubscribeHandler } from \"../../../subs/types\";\n\n/**\n * A cached entry: the `value` and the absolute clock reading `expiresAtMs` it\n * expires at. Unlike `/idempotency`'s entry (which stores `atMs` and derives\n * expiry from a store-level `ttlMs`), the expiry instant is baked in at write\n * time — so per-entry TTLs are a first-class capability. Both fields are plain\n * data so the whole cache is trivially JSON-serializable into a consumer's\n * `Store<S>`.\n */\nexport interface CacheEntry<V> {\n readonly value: V;\n readonly expiresAtMs: number;\n}\n\n/**\n * The cache: a map of `key → entry`. No `order` ledger and no `capacity` (cf.\n * `/idempotency`) — a TTL cache bounds itself by expiry + periodic eviction,\n * not by LRU count. Each entry carries its own `expiresAtMs`, so the cache\n * needs no store-level TTL policy field.\n */\nexport interface TtlCache<V> {\n readonly entries: Readonly<Record<string, CacheEntry<V>>>;\n}\n\n/** Create an empty cache. */\nexport function initCache<V>(): TtlCache<V> {\n return { entries: {} };\n}\n\n/**\n * Whether `entry` is expired at `nowMs`. Half-open: an entry whose\n * `expiresAtMs` exactly equals `nowMs` is expired (`nowMs >= expiresAtMs`),\n * matching `/idempotency` and `/rate-limit`'s window-edge cutoff — a value\n * cached at `t` with a `ttlMs` lifetime is gone at exactly `t + ttlMs`.\n */\nfunction isExpired<V>(entry: CacheEntry<V>, nowMs: number): boolean {\n return nowMs >= entry.expiresAtMs;\n}\n\n/**\n * The cached `value` for `key` iff present AND unexpired at `nowMs`, else\n * `undefined`. An expired entry reads as absent even though it is physically\n * still in `entries` until the next `evictExpired` (or an overwriting `set`)\n * drops it. PURE — reads only, never mutates.\n */\nexport function get<V>(\n cache: TtlCache<V>,\n key: string,\n nowMs: number,\n): V | undefined {\n const entry = cache.entries[key];\n if (entry === undefined || isExpired(entry, nowMs)) return undefined;\n return entry.value;\n}\n\n/**\n * True iff `key` is present AND unexpired at `nowMs`. The boolean sibling of\n * `get` for callers that only need presence, not the value. PURE.\n */\nexport function has<V>(\n cache: TtlCache<V>,\n key: string,\n nowMs: number,\n): boolean {\n const entry = cache.entries[key];\n if (entry === undefined) return false;\n return !isExpired(entry, nowMs);\n}\n\n/**\n * Write `key → value` with an absolute expiry of `nowMs + ttlMs`. Re-`set`ting\n * an existing key overwrites both the value and the expiry — the TTL clock\n * restarts from the new `nowMs`. PURE — returns a new cache; the input is\n * untouched (a fresh shallow copy of `entries`).\n */\nexport function set<V>(\n cache: TtlCache<V>,\n key: string,\n value: V,\n nowMs: number,\n ttlMs: number,\n): TtlCache<V> {\n const nextEntries: Record<string, CacheEntry<V>> = { ...cache.entries };\n nextEntries[key] = { value, expiresAtMs: nowMs + ttlMs };\n return { ...cache, entries: nextEntries };\n}\n\n/**\n * Drop `key` regardless of expiry. PURE — returns a new cache; the input is\n * untouched. Removing an absent key returns an equivalent cache (the shallow\n * copy still happens, but no entry is dropped).\n */\nexport function remove<V>(cache: TtlCache<V>, key: string): TtlCache<V> {\n const nextEntries: Record<string, CacheEntry<V>> = { ...cache.entries };\n delete nextEntries[key];\n return { ...cache, entries: nextEntries };\n}\n\n/**\n * Physically drop every entry expired at `nowMs` (`nowMs >= expiresAtMs`).\n * Returns a NEW cache with the survivors. This is the pure work the eviction\n * Sub's `cache_evict` Msg triggers — `get` / `has` already treat expired\n * entries as absent, so eviction is purely a memory-reclaim pass, not a\n * correctness one. PURE — the input cache is never mutated.\n */\nexport function evictExpired<V>(\n cache: TtlCache<V>,\n nowMs: number,\n): TtlCache<V> {\n const nextEntries: Record<string, CacheEntry<V>> = {};\n for (const [key, entry] of Object.entries(cache.entries)) {\n if (isExpired(entry, nowMs)) continue;\n nextEntries[key] = entry;\n }\n return { ...cache, entries: nextEntries };\n}\n\n// ---------------------------------------------------------------------------\n// Eviction Sub — \"eviction is a Msg\".\n//\n// A periodic timer Sub that dispatches `cache_evict` so the consumer's reducer\n// can call `evictExpired`. It is `fromInterval` specialized to a fixed Msg\n// shape — the interval rides in the Sub's `deps` (which the engine keys the\n// Sub on) and the runner dispatches a `cache_evict` Msg tagged with the cache's\n// name, so a consumer running several caches can route each tick to the right\n// cache by `msg.id`.\n//\n// Mirrors `fromInterval` exactly (factory + SubscribeHandler cell + exported\n// Msg constructor); it does NOT reimplement the timer lifecycle — it composes\n// directly on `fromInterval`, which owns `setInterval` / `clearInterval`. That\n// keeps the timer-handle bookkeeping (and its cleanup) in one place and this\n// module purely declarative.\n//\n// Strengthens invariant 4 (external time is a Sub the engine reconciles) and\n// invariant 9 (named, small Sub surface composed on the shared factory).\n// ---------------------------------------------------------------------------\n\n/**\n * The Msg the eviction Sub dispatches each tick. `id` is the cache's name so a\n * consumer with multiple caches can route the tick to the matching cache. The\n * reducer reads `Date.now()`-free time by stamping `nowMs` itself at the Sub\n * boundary if needed; the canonical reducer cell is\n * `cache_evict: (s) => [{ ...s, cache: evictExpired(s.cache, nowMs) }, []]`.\n */\nexport interface CacheEvictMsg {\n readonly type: \"cache_evict\";\n readonly id: string;\n}\n\n/** Construct a `cache_evict` Msg for the cache identified by `id`. */\nexport function cacheEvictMsg(id: string): CacheEvictMsg {\n return { type: \"cache_evict\", id };\n}\n\n/**\n * The `deps` of an eviction Sub: which cache it ticks for (`name`, echoed as\n * the Msg's `id`) and the tick period (`intervalMs`, which `fromInterval`\n * reads).\n */\nexport type CacheEvictionDeps = {\n readonly name: string;\n readonly intervalMs: number;\n};\n\n/**\n * The running eviction Sub: a `setInterval`-shaped Sub whose `deps` carry the\n * cache's name and tick period. `type: \"cache\"` is the lowercase source-noun\n * Sub convention (canon §2.5 / naming-style).\n */\nexport type CacheEvictionSub = Sub<\"cache\", CacheEvictionDeps>;\n\n/**\n * The `subs` entry for an eviction tick on the cache named `name`, every\n * `everyMs`. It is on for the machine's life:\n *\n * subs: [cacheEvictionSub(\"session-cache\", 30_000)],\n * // run(machine, { subscribe: { cache: cacheEvictionSubscribe } })\n *\n * The engine keys the Sub on its `deps`, so a machine that declares the same\n * name and period keeps one running interval, and a changed period restarts\n * it at the new one.\n */\nexport function cacheEvictionSub(\n name: string,\n everyMs: number,\n): DepKeyedSub<unknown, CacheEvictionSub> {\n return { type: \"cache\", deps: () => ({ name, intervalMs: everyMs }) };\n}\n\n/**\n * The `cache` runner for the eviction Sub. Hand it to `run`:\n *\n * run(machine, { subscribe: { cache: cacheEvictionSubscribe } })\n *\n * Composed directly on `fromInterval` — it owns the `setInterval` /\n * `clearInterval` lifecycle; this runner only pins the Msg the tick dispatches\n * (`cacheEvictMsg(sub.deps.name)`). The cleanup `fromInterval` returns stops\n * the interval when the Sub stops.\n */\nexport const cacheEvictionSubscribe: SubscribeHandler<\n CacheEvictionSub,\n CacheEvictMsg,\n unknown\n> = fromInterval((sub) => cacheEvictMsg(sub.deps.name));\n"]}