@demlik/tea 0.16.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 (84) hide show
  1. package/dist/agent/index.d.ts +13 -13
  2. package/dist/agent/index.js +9 -9
  3. package/dist/{chunk-CIHSHLQX.js → chunk-4NTCPTNQ.js} +3 -3
  4. package/dist/{chunk-CIHSHLQX.js.map → chunk-4NTCPTNQ.js.map} +1 -1
  5. package/dist/{chunk-7MGXQZPW.js → chunk-4PXNZ5UY.js} +4 -4
  6. package/dist/{chunk-7MGXQZPW.js.map → chunk-4PXNZ5UY.js.map} +1 -1
  7. package/dist/{chunk-6NG4V5SB.js → chunk-6XBEYZME.js} +5 -5
  8. package/dist/{chunk-6NG4V5SB.js.map → chunk-6XBEYZME.js.map} +1 -1
  9. package/dist/{chunk-GOX2CYIM.js → chunk-C4U5D5HP.js} +3 -3
  10. package/dist/{chunk-GOX2CYIM.js.map → chunk-C4U5D5HP.js.map} +1 -1
  11. package/dist/{chunk-MVZS5FDM.js → chunk-DFUEAA6L.js} +3 -3
  12. package/dist/{chunk-MVZS5FDM.js.map → chunk-DFUEAA6L.js.map} +1 -1
  13. package/dist/{chunk-IVJP3GKJ.js → chunk-GWWCCSDH.js} +4 -4
  14. package/dist/{chunk-IVJP3GKJ.js.map → chunk-GWWCCSDH.js.map} +1 -1
  15. package/dist/{chunk-CH5KTOEZ.js → chunk-K4ETBNKS.js} +32 -9
  16. package/dist/chunk-K4ETBNKS.js.map +1 -0
  17. package/dist/{chunk-5XU6ZJO2.js → chunk-KWNCM6XM.js} +19 -13
  18. package/dist/chunk-KWNCM6XM.js.map +1 -0
  19. package/dist/{chunk-BCTEOVOU.js → chunk-LYVOGOBC.js} +3 -3
  20. package/dist/{chunk-BCTEOVOU.js.map → chunk-LYVOGOBC.js.map} +1 -1
  21. package/dist/{chunk-MYNLY3HP.js → chunk-OPH6Y4UT.js} +3 -3
  22. package/dist/{chunk-MYNLY3HP.js.map → chunk-OPH6Y4UT.js.map} +1 -1
  23. package/dist/{chunk-NSIAORRY.js → chunk-OYR7ENKU.js} +3 -3
  24. package/dist/{chunk-NSIAORRY.js.map → chunk-OYR7ENKU.js.map} +1 -1
  25. package/dist/{chunk-WT5PBPLB.js → chunk-QWIPH4YH.js} +4 -4
  26. package/dist/{chunk-WT5PBPLB.js.map → chunk-QWIPH4YH.js.map} +1 -1
  27. package/dist/{chunk-EHUDXAKC.js → chunk-XBZQT2TD.js} +7 -7
  28. package/dist/chunk-XBZQT2TD.js.map +1 -0
  29. package/dist/{core-BbgtiXdg.d.ts → core-rDbOaJTN.d.ts} +7 -3
  30. package/dist/do/index.d.ts +12 -12
  31. package/dist/do/index.js +10 -10
  32. package/dist/{durable-effects-7MTK_jnj.d.ts → durable-effects-CNaw97Be.d.ts} +1 -1
  33. package/dist/effect/index.d.ts +2 -2
  34. package/dist/effect/index.js +2 -2
  35. package/dist/extension/index.d.ts +3 -3
  36. package/dist/extension/index.js +2 -2
  37. package/dist/flow/index.d.ts +13 -13
  38. package/dist/flow/index.js +10 -10
  39. package/dist/idempotency/index.d.ts +3 -3
  40. package/dist/idempotency/index.js +3 -3
  41. package/dist/{index-Bz5Rh9Ga.d.ts → index-BOrsbdAf.d.ts} +4 -4
  42. package/dist/{index-DU6JpQ8G.d.ts → index-B_BxplWi.d.ts} +1 -1
  43. package/dist/{index-CjFDUBeq.d.ts → index-CWmsXNdX.d.ts} +1 -1
  44. package/dist/{index-_dOR3xqA.d.ts → index-Cberb5Rr.d.ts} +2 -2
  45. package/dist/{index-7vV8xmsD.d.ts → index-CcrKLtse.d.ts} +1 -1
  46. package/dist/{index-CkFYA9Y6.d.ts → index-Cx0F2M34.d.ts} +2 -2
  47. package/dist/{index-Xufl55W8.d.ts → index-DaX_P35Q.d.ts} +2 -2
  48. package/dist/{index-Cou86-GX.d.ts → index-q1PoukOZ.d.ts} +2 -2
  49. package/dist/index.d.ts +5 -5
  50. package/dist/index.js +2 -2
  51. package/dist/jev/index.d.ts +8 -8
  52. package/dist/jev/index.js +5 -5
  53. package/dist/{machine-BQzTV8On.d.ts → machine-BcfCFMYF.d.ts} +7 -7
  54. package/dist/machine-viz/index.d.ts +1 -1
  55. package/dist/machine-viz/index.js +2 -2
  56. package/dist/mem/index.d.ts +2 -2
  57. package/dist/mem/index.js +2 -2
  58. package/dist/node/index.d.ts +2 -2
  59. package/dist/node/index.js +2 -2
  60. package/dist/paginate/index.d.ts +4 -4
  61. package/dist/paginate/index.js +5 -5
  62. package/dist/parity/index.d.ts +3 -3
  63. package/dist/parity/index.js +3 -3
  64. package/dist/pbt/index.d.ts +1 -1
  65. package/dist/pbt/index.js +2 -2
  66. package/dist/persistence/index.d.ts +9 -10
  67. package/dist/persistence/index.js +4 -4
  68. package/dist/promise/index.d.ts +2 -2
  69. package/dist/promise/index.js +3 -3
  70. package/dist/react/index.d.ts +2 -2
  71. package/dist/resilience/index.d.ts +6 -6
  72. package/dist/resilience/index.js +5 -5
  73. package/dist/{runtime-types-CiVpC0HN.d.ts → runtime-types-B62Ucnxr.d.ts} +2 -2
  74. package/dist/testing/index.d.ts +22 -108
  75. package/dist/testing/index.js +27 -177
  76. package/dist/testing/index.js.map +1 -1
  77. package/dist/timing/index.d.ts +4 -4
  78. package/dist/timing/index.js +4 -4
  79. package/dist/{types-LxZxGYda.d.ts → types-DPm5YCDQ.d.ts} +1 -1
  80. package/dist/work-queue/index.d.ts +4 -4
  81. package/package.json +3 -3
  82. package/dist/chunk-5XU6ZJO2.js.map +0 -1
  83. package/dist/chunk-CH5KTOEZ.js.map +0 -1
  84. package/dist/chunk-EHUDXAKC.js.map +0 -1
@@ -1 +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;AAQ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O,SAAS,gBAAA,CACd,MACA,OAAA,EACwC;AACxC,EAAA,OAAO,EAAE,MAAM,OAAA,EAAS,IAAA,EAAM,OAAO,EAAE,IAAA,EAAM,UAAA,EAAY,OAAA,EAAQ,CAAA,EAAG;AACtE;AAYO,IAAM,sBAAA,GAIT,aAAa,CAAC,GAAA,KAAQ,cAAc,GAAA,CAAI,IAAA,CAAK,IAAI,CAAC","file":"chunk-IVJP3GKJ.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"]}
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,CACd,EAAA,EACA,IAAA,EACA,IAAA,EACgB;AAChB,EAAA,OAAO,EAAE,GAAG,IAAA,EAAM,EAAA,EAAI,MAAM,EAAE,CAAA,EAAG,IAAA,EAAM,UAAA,EAAY,IAAA,EAAK;AAC1D;AA+CO,SAAS,cACd,QAAA,EAKW;AACX,EAAA,OAAO,CAAC,GAAA,EAAK,IAAA,EAAM,QAAA,KAAa;AAC9B,IAAA,MAAM,OAAA,GAAU,IAAI,IAAA,CAAK,GAAA;AAAA,MA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O,EAAE,GAAG,KAAA,EAAO,OAAA,EAAS,WAAA,EAAY;AAC1C;AAOO,SAAS,MAAA,CAAU,OAAoB,GAAA,EAA0B;AACtE,EAAA,MAAM,WAAA,GAA6C,EAAE,GAAG,KAAA,CAAM,OAAA,EAAQ;AACtE,EAAA,OAAO,YAAY,GAAG,CAAA;AACtB,EAAA,OAAO,EAAE,GAAG,KAAA,EAAO,OAAA,EAAS,WAAA,EAAY;AAC1C;AASO,SAAS,YAAA,CACd,OACA,KAAA,EACa;AACb,EAAA,MAAM,cAA6C,EAAC;AACpD,EAAA,KAAA,MAAW,CAAC,KAAK,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,KAAA,CAAM,OAAO,CAAA,EAAG;AACxD,IAAA,IAAI,SAAA,CAAU,KAAA,EAAO,KAAK,CAAA,EAAG;AAC7B,IAAA,WAAA,CAAY,GAAG,CAAA,GAAI,KAAA;AAAA,EACrB;AACA,EAAA,OAAO,EAAE,GAAG,KAAA,EAAO,OAAA,EAAS,WAAA,EAAY;AAC1C;AAmCO,SAAS,cAAc,EAAA,EAA2B;AACvD,EAAA,OAAO,EAAE,IAAA,EAAM,aAAA,EAAe,EAAA,EAAG;AACnC;AA8BO,SAAS,gBAAA,CACd,MACA,OAAA,EACwC;AACxC,EAAA,OAAO,EAAE,MAAM,OAAA,EAAS,IAAA,EAAM,OAAO,EAAE,IAAA,EAAM,UAAA,EAAY,OAAA,EAAQ,CAAA,EAAG;AACtE;AAYO,IAAM,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"]}
@@ -130,14 +130,37 @@ var OutcomeContractError = class extends Error {
130
130
  };
131
131
  var cmdEdge = /* @__PURE__ */ Symbol("tea.cmdEdge");
132
132
  function cmdEdgeOver(defs, clock) {
133
+ return cmdContractOver(defs, clock).settle;
134
+ }
135
+ function cmdContractOver(defs, clock) {
133
136
  const byType = /* @__PURE__ */ new Map();
134
137
  for (const def of defs) byType.set(def.cmdType, def);
135
- return (cmd, returned) => {
136
- const def = byType.get(cmd.type);
137
- if (def === void 0) return returned;
138
- if (returned === void 0 || returned === null) return void 0;
139
- if (isOutcome(returned)) return mint(def, cmd, returned, clock());
140
- throw new OutcomeContractError(def.cmdType, describeReturn(def, returned));
138
+ const minted = /* @__PURE__ */ new WeakSet();
139
+ return {
140
+ settle: (cmd, returned) => {
141
+ const def = byType.get(cmd.type);
142
+ if (def === void 0) return returned;
143
+ if (returned === void 0 || returned === null) return void 0;
144
+ if (!isOutcome(returned)) {
145
+ throw new OutcomeContractError(
146
+ def.cmdType,
147
+ describeReturn(def, returned)
148
+ );
149
+ }
150
+ const msg = mint(def, cmd, returned, clock());
151
+ minted.add(msg);
152
+ return msg;
153
+ },
154
+ checkDispatch: (cmd, msg) => {
155
+ const def = byType.get(cmd.type);
156
+ if (def === void 0) return;
157
+ if (msg.type !== def.okType && msg.type !== def.errType) return;
158
+ if (minted.has(msg)) return;
159
+ throw new OutcomeContractError(
160
+ def.cmdType,
161
+ `dispatched its own "${msg.type}" Msg`
162
+ );
163
+ }
141
164
  };
142
165
  }
143
166
  function describeReturn(def, returned) {
@@ -705,6 +728,6 @@ function tryInterpret(work, onOk, onErr) {
705
728
  };
706
729
  }
707
730
 
708
- export { AsyncSchemaError, Cmd, DispatchDiscardedError, DisposeTimeoutNotice, DriveFailedError, DriveStalledError, IdentityDropNotice, NoCellError, Outcome, OutcomeContractError, PortNameCollisionError, QuiescenceTimeoutError, RuntimeDiscardNotice, RuntimeDiscardedError, StoreConflictError, UndeclaredFailureError, __resetPortRegistry, absurd, acceptedTypes, acceptsOf, applyCell, applyCellChecked, asReducer, checkedStep, cmdEdge, cmdEdgeOf, cmdEdgeOver, defineMachine, definePort, describeMachine, desiredSub, detachWork, detachWorkOf, detectUpdateForm, foldMsgs, foldUpdates, formOf, isFencedStore, malformedResult, msgKeysOf, noop, replay, schemaMigrate, structuralHash, subEntriesOf, subId, subIdOf, tryApplyCell, tryFoldMsgs, tryInterpret, validateSync, without, wrapDetached };
709
- //# sourceMappingURL=chunk-CH5KTOEZ.js.map
710
- //# sourceMappingURL=chunk-CH5KTOEZ.js.map
731
+ export { AsyncSchemaError, Cmd, DispatchDiscardedError, DisposeTimeoutNotice, DriveFailedError, DriveStalledError, IdentityDropNotice, NoCellError, Outcome, OutcomeContractError, PortNameCollisionError, QuiescenceTimeoutError, RuntimeDiscardNotice, RuntimeDiscardedError, StoreConflictError, UndeclaredFailureError, __resetPortRegistry, absurd, acceptedTypes, acceptsOf, applyCell, applyCellChecked, asReducer, checkedStep, cmdContractOver, cmdEdge, cmdEdgeOf, cmdEdgeOver, defineMachine, definePort, describeMachine, desiredSub, detachWork, detachWorkOf, detectUpdateForm, foldMsgs, foldUpdates, formOf, isFencedStore, malformedResult, msgKeysOf, noop, replay, schemaMigrate, structuralHash, subEntriesOf, subId, subIdOf, tryApplyCell, tryFoldMsgs, tryInterpret, validateSync, without, wrapDetached };
732
+ //# sourceMappingURL=chunk-K4ETBNKS.js.map
733
+ //# sourceMappingURL=chunk-K4ETBNKS.js.map