@demlik/tea 0.1.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 (96) hide show
  1. package/dist/cache/index.d.ts +151 -0
  2. package/dist/cache/index.js +53 -0
  3. package/dist/cache/index.js.map +1 -0
  4. package/dist/chunk-2YFLOCWX.js +15 -0
  5. package/dist/chunk-2YFLOCWX.js.map +1 -0
  6. package/dist/chunk-CMG2KMWX.js +458 -0
  7. package/dist/chunk-CMG2KMWX.js.map +1 -0
  8. package/dist/chunk-PYBQREFU.js +95 -0
  9. package/dist/chunk-PYBQREFU.js.map +1 -0
  10. package/dist/chunk-PYOCUBQJ.js +196 -0
  11. package/dist/chunk-PYOCUBQJ.js.map +1 -0
  12. package/dist/chunk-Y5JM3UUH.js +126 -0
  13. package/dist/chunk-Y5JM3UUH.js.map +1 -0
  14. package/dist/chunk-ZRUST6BK.js +62 -0
  15. package/dist/chunk-ZRUST6BK.js.map +1 -0
  16. package/dist/circuit-breaker/index.d.ts +196 -0
  17. package/dist/circuit-breaker/index.js +53 -0
  18. package/dist/circuit-breaker/index.js.map +1 -0
  19. package/dist/deadline/index.d.ts +113 -0
  20. package/dist/deadline/index.js +20 -0
  21. package/dist/deadline/index.js.map +1 -0
  22. package/dist/debounce/index.d.ts +114 -0
  23. package/dist/debounce/index.js +56 -0
  24. package/dist/debounce/index.js.map +1 -0
  25. package/dist/devtools/index.d.ts +137 -0
  26. package/dist/devtools/index.js +217 -0
  27. package/dist/devtools/index.js.map +1 -0
  28. package/dist/devtools/styles.css +218 -0
  29. package/dist/do/index.d.ts +135 -0
  30. package/dist/do/index.js +54 -0
  31. package/dist/do/index.js.map +1 -0
  32. package/dist/extension/index.d.ts +207 -0
  33. package/dist/extension/index.js +26 -0
  34. package/dist/extension/index.js.map +1 -0
  35. package/dist/extension/react.d.ts +121 -0
  36. package/dist/extension/react.js +69 -0
  37. package/dist/extension/react.js.map +1 -0
  38. package/dist/extension/subs/index.d.ts +44 -0
  39. package/dist/extension/subs/index.js +83 -0
  40. package/dist/extension/subs/index.js.map +1 -0
  41. package/dist/extension/test-utils.d.ts +128 -0
  42. package/dist/extension/test-utils.js +269 -0
  43. package/dist/extension/test-utils.js.map +1 -0
  44. package/dist/idempotency/index.d.ts +131 -0
  45. package/dist/idempotency/index.js +58 -0
  46. package/dist/idempotency/index.js.map +1 -0
  47. package/dist/index.d.ts +364 -0
  48. package/dist/index.js +3 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/machine-viz/index.d.ts +78 -0
  51. package/dist/machine-viz/index.js +139 -0
  52. package/dist/machine-viz/index.js.map +1 -0
  53. package/dist/mem/index.d.ts +45 -0
  54. package/dist/mem/index.js +19 -0
  55. package/dist/mem/index.js.map +1 -0
  56. package/dist/node/index.d.ts +134 -0
  57. package/dist/node/index.js +89 -0
  58. package/dist/node/index.js.map +1 -0
  59. package/dist/pbt/arbitraries/index.d.ts +135 -0
  60. package/dist/pbt/arbitraries/index.js +3 -0
  61. package/dist/pbt/arbitraries/index.js.map +1 -0
  62. package/dist/pbt/index.d.ts +28 -0
  63. package/dist/pbt/index.js +18 -0
  64. package/dist/pbt/index.js.map +1 -0
  65. package/dist/pbt/runners/index.d.ts +117 -0
  66. package/dist/pbt/runners/index.js +4 -0
  67. package/dist/pbt/runners/index.js.map +1 -0
  68. package/dist/rate-limit/index.d.ts +115 -0
  69. package/dist/rate-limit/index.js +45 -0
  70. package/dist/rate-limit/index.js.map +1 -0
  71. package/dist/react/index.d.ts +72 -0
  72. package/dist/react/index.js +33 -0
  73. package/dist/react/index.js.map +1 -0
  74. package/dist/recorder/index.d.ts +287 -0
  75. package/dist/recorder/index.js +157 -0
  76. package/dist/recorder/index.js.map +1 -0
  77. package/dist/retry-backoff/index.d.ts +131 -0
  78. package/dist/retry-backoff/index.js +37 -0
  79. package/dist/retry-backoff/index.js.map +1 -0
  80. package/dist/subs/index.d.ts +57 -0
  81. package/dist/subs/index.js +4 -0
  82. package/dist/subs/index.js.map +1 -0
  83. package/dist/testing/index.d.ts +220 -0
  84. package/dist/testing/index.js +105 -0
  85. package/dist/testing/index.js.map +1 -0
  86. package/dist/throttle/index.d.ts +125 -0
  87. package/dist/throttle/index.js +54 -0
  88. package/dist/throttle/index.js.map +1 -0
  89. package/dist/trace-replay/index.d.ts +52 -0
  90. package/dist/trace-replay/index.js +57 -0
  91. package/dist/trace-replay/index.js.map +1 -0
  92. package/dist/types-CwBC5wMn.d.ts +5 -0
  93. package/dist/work-queue/index.d.ts +56 -0
  94. package/dist/work-queue/index.js +143 -0
  95. package/dist/work-queue/index.js.map +1 -0
  96. package/package.json +184 -0
@@ -0,0 +1,458 @@
1
+ import { Result } from 'better-result';
2
+
3
+ // src/index.ts
4
+ var __DEV__ = (() => {
5
+ try {
6
+ const meta = import.meta;
7
+ if (meta.env?.DEV !== void 0) {
8
+ return meta.env.DEV;
9
+ }
10
+ } catch {
11
+ }
12
+ try {
13
+ return typeof process !== "undefined" && process.env?.NODE_ENV !== "production";
14
+ } catch {
15
+ return false;
16
+ }
17
+ })();
18
+ function deepFreeze(obj, seen) {
19
+ if (obj === null || typeof obj !== "object") return obj;
20
+ const proto = Object.getPrototypeOf(obj);
21
+ if (proto !== Object.prototype && proto !== Array.prototype && proto !== null) return obj;
22
+ const visited = seen ?? /* @__PURE__ */ new WeakSet();
23
+ if (visited.has(obj)) return obj;
24
+ visited.add(obj);
25
+ Object.freeze(obj);
26
+ for (const v of Object.values(obj)) deepFreeze(v, visited);
27
+ return obj;
28
+ }
29
+ function hasFunctionValues(obj) {
30
+ if (obj === null || typeof obj !== "object") return null;
31
+ for (const [key, value] of Object.entries(obj)) {
32
+ if (typeof value === "function") return key;
33
+ }
34
+ return null;
35
+ }
36
+ function assertPureResult(result, msgType) {
37
+ if (result && typeof result.then === "function") {
38
+ throw new Error(
39
+ `@demlik/tea: update cell "${msgType}" returned a Promise. update must be synchronous. Move async work to interpret.`
40
+ );
41
+ }
42
+ if (!Array.isArray(result) || result.length < 2 || !Array.isArray(result[1])) {
43
+ throw new Error(
44
+ `@demlik/tea: update cell "${msgType}" returned a non-tuple. Expected [State, Cmd[]], got ${typeof result}.`
45
+ );
46
+ }
47
+ const cmds = result[1];
48
+ for (const cmd of cmds) {
49
+ const fnField = hasFunctionValues(cmd);
50
+ if (fnField !== null) {
51
+ throw new Error(
52
+ `@demlik/tea: Cmd "${cmd.type}" has function field "${fnField}". Cmds must be plain data, not closures.`
53
+ );
54
+ }
55
+ }
56
+ }
57
+ function absurd(x) {
58
+ throw new Error(`unreachable: ${JSON.stringify(x)}`);
59
+ }
60
+ var noop = (state, _msg) => [
61
+ state,
62
+ []
63
+ ];
64
+ var Cmd = {
65
+ /**
66
+ * The empty Cmd array. Typed `readonly never[]` so it's assignable to any
67
+ * `readonly C[]` for any `C extends Cmd`. Use in `init` returns and
68
+ * Transitions cells that emit zero effects:
69
+ *
70
+ * init: (loaded) => [loaded ?? initial, Cmd.none],
71
+ * tick: (state) => [state, Cmd.none],
72
+ *
73
+ * Elm's `Cmd.none` analogue. Cultural signal alongside the runtime help:
74
+ * `[state, Cmd.none]` reads as intent ("this transition emits nothing"),
75
+ * `[state, []]` reads as "empty array of what".
76
+ *
77
+ * Frozen at runtime so a downstream consumer can't `.push()` into the
78
+ * shared reference.
79
+ */
80
+ none: Object.freeze([]),
81
+ /**
82
+ * Flat concat of cmd arrays. Use when a cell composes effects from
83
+ * multiple conditional sources:
84
+ *
85
+ * return [next, Cmd.batch(
86
+ * Cmd.whenDefined(state.queueItemId, (id) => ({ type: "complete", id })),
87
+ * Cmd.when(state.windowId !== undefined, { type: "close_window", windowId }),
88
+ * [{ type: "detach_debugger", tabId: state.tabId }],
89
+ * )];
90
+ *
91
+ * `<const C>` keeps inline cmd literals' discriminants narrow (same
92
+ * rationale as `when` / `whenDefined` above).
93
+ */
94
+ batch: (...arrs) => {
95
+ const out = [];
96
+ for (const arr of arrs) out.push(...arr);
97
+ return out;
98
+ },
99
+ /**
100
+ * Emit `cmd` wrapped in a single-element array iff `cond` is true.
101
+ * Otherwise return the empty array. Spreads cleanly into the cmds array
102
+ * returned by a Transitions cell.
103
+ *
104
+ * `const C` (TypeScript 5.0+) keeps the inferred `type:` discriminator
105
+ * literal narrow when called with an object literal — so `Cmd.when(b,
106
+ * { type: "x", ... })` infers as `{ type: "x", ... }`, not `{ type:
107
+ * string, ... }`, and stays assignable to a discriminated-union arm
108
+ * without `as const` at the call site.
109
+ */
110
+ when: (cond, cmd) => cond ? [cmd] : [],
111
+ /**
112
+ * If `value` is defined, call `build(value)` and emit the resulting cmd
113
+ * wrapped in a single-element array. If `value` is `undefined`, return
114
+ * the empty array. `value` is narrowed to `T` inside `build`.
115
+ *
116
+ * `const C` on the return type keeps the callback's object-literal
117
+ * `type:` field narrow (see `when` above for the full rationale).
118
+ */
119
+ whenDefined: (value, build) => value !== void 0 ? [build(value)] : []
120
+ };
121
+ function subId(s) {
122
+ return s;
123
+ }
124
+ var definedPortNames = /* @__PURE__ */ new Set();
125
+ var PortNameCollisionError = class extends Error {
126
+ name = "PortNameCollisionError";
127
+ constructor(portName) {
128
+ super(
129
+ `definePort: a port named "${portName}" was already defined. Each definePort call must use a unique name. If two modules need the same port, export it from one module and import it.`
130
+ );
131
+ }
132
+ };
133
+ function __resetPortRegistry() {
134
+ definedPortNames.clear();
135
+ }
136
+ function definePort(name) {
137
+ let isHmr = false;
138
+ try {
139
+ const meta = import.meta;
140
+ isHmr = meta?.hot !== void 0 && meta?.hot !== null;
141
+ } catch {
142
+ isHmr = false;
143
+ }
144
+ if (!isHmr && definedPortNames.has(name)) {
145
+ throw new PortNameCollisionError(name);
146
+ }
147
+ definedPortNames.add(name);
148
+ return { __brand: "port", name };
149
+ }
150
+ function defineMachine(m) {
151
+ return m;
152
+ }
153
+ function run(machine, opts) {
154
+ const { ctx, store } = opts;
155
+ let state;
156
+ let bootError = null;
157
+ let stopped = false;
158
+ const subRegistry = /* @__PURE__ */ new Map();
159
+ const listeners = /* @__PURE__ */ new Set();
160
+ const observers = /* @__PURE__ */ new Set();
161
+ const portRegistry = /* @__PURE__ */ new Map();
162
+ function portEmit(port, value) {
163
+ const subscribers = portRegistry.get(port);
164
+ if (!subscribers || subscribers.size === 0) return;
165
+ for (const listener of subscribers) {
166
+ try {
167
+ listener(value);
168
+ } catch (err) {
169
+ console.error(err);
170
+ }
171
+ }
172
+ }
173
+ const augmentedCtx = { ...ctx, emit: portEmit };
174
+ const updateForm = machine.update;
175
+ const updateMode = (() => {
176
+ const firstKey = Object.keys(updateForm)[0];
177
+ if (firstKey === void 0) {
178
+ return "reducer";
179
+ }
180
+ const firstValue = updateForm[firstKey];
181
+ return typeof firstValue === "function" ? "reducer" : "transitions";
182
+ })();
183
+ function applyUpdate(state2, msg) {
184
+ if (__DEV__) deepFreeze(state2);
185
+ let result;
186
+ if (updateMode === "reducer") {
187
+ const record = updateForm;
188
+ const handler = record[msg.type];
189
+ result = handler(state2, msg);
190
+ } else {
191
+ const table = updateForm;
192
+ const stateKey = state2.type;
193
+ const handler = table[stateKey][msg.type];
194
+ result = handler(state2, msg);
195
+ }
196
+ if (__DEV__) assertPureResult(result, msg.type);
197
+ return result;
198
+ }
199
+ let tail = Promise.resolve();
200
+ function reconcileSubs() {
201
+ if (!machine.subscriptions) return;
202
+ const desired = machine.subscriptions(state);
203
+ const desiredIds = /* @__PURE__ */ new Set();
204
+ const desiredTypeById = /* @__PURE__ */ new Map();
205
+ for (const sub of desired) {
206
+ const existing = desiredTypeById.get(sub.id);
207
+ if (existing !== void 0 && existing !== sub.type) {
208
+ throw new Error(
209
+ `@demlik/tea: Sub.id collision: id="${sub.id}" declared as type="${existing}" and type="${sub.type}"`
210
+ );
211
+ }
212
+ desiredTypeById.set(sub.id, sub.type);
213
+ }
214
+ for (const sub of desired) desiredIds.add(sub.id);
215
+ for (const [id, cleanup] of subRegistry) {
216
+ if (!desiredIds.has(id)) {
217
+ try {
218
+ cleanup();
219
+ } catch (err) {
220
+ console.error(err);
221
+ }
222
+ subRegistry.delete(id);
223
+ }
224
+ }
225
+ let firstStartError = null;
226
+ for (const sub of desired) {
227
+ if (subRegistry.has(sub.id)) continue;
228
+ const handler = machine.subscribe?.[sub.type];
229
+ if (!handler) {
230
+ continue;
231
+ }
232
+ try {
233
+ const cleanup = handler(sub, ctx, enqueueDispatch);
234
+ subRegistry.set(sub.id, cleanup);
235
+ } catch (err) {
236
+ if (firstStartError === null) firstStartError = err;
237
+ }
238
+ }
239
+ if (firstStartError !== null) throw firstStartError;
240
+ }
241
+ const interpretMap = machine.interpret ?? {};
242
+ async function runInterpret(cmds) {
243
+ for (const cmd of cmds) {
244
+ const handler = interpretMap[cmd.type];
245
+ if (!handler) continue;
246
+ const follow = await handler(cmd, augmentedCtx);
247
+ if (follow !== void 0 && follow !== null) {
248
+ enqueueDispatch(follow).catch(() => {
249
+ });
250
+ }
251
+ }
252
+ }
253
+ function fireListeners() {
254
+ for (const listener of listeners) {
255
+ try {
256
+ listener();
257
+ } catch (err) {
258
+ console.error(err);
259
+ }
260
+ }
261
+ }
262
+ function fireObservers(msg) {
263
+ if (observers.size === 0 || state === void 0) return;
264
+ const snapshot = state;
265
+ for (const observer of observers) {
266
+ try {
267
+ observer(msg, snapshot);
268
+ } catch (err) {
269
+ console.error(err);
270
+ }
271
+ }
272
+ }
273
+ async function stepDispatch(msg) {
274
+ if (state === void 0) {
275
+ throw new Error("@demlik/tea: runtime not booted");
276
+ }
277
+ const [next, cmds] = applyUpdate(state, msg);
278
+ state = next;
279
+ if (store) await store.save(state);
280
+ reconcileSubs();
281
+ await runInterpret(cmds);
282
+ fireListeners();
283
+ fireObservers(msg);
284
+ }
285
+ let pendingInitCmds = [];
286
+ if (!store) {
287
+ const [initialState, initCmds] = machine.init(null, ctx);
288
+ state = initialState;
289
+ pendingInitCmds = initCmds;
290
+ }
291
+ async function stepBootEffects() {
292
+ if (store) {
293
+ const raw = await store.load();
294
+ const parsed = store.migrate(raw);
295
+ const [initialState, initCmds] = machine.init(parsed, ctx);
296
+ state = initialState;
297
+ pendingInitCmds = initCmds;
298
+ await store.save(state);
299
+ }
300
+ reconcileSubs();
301
+ await runInterpret(pendingInitCmds);
302
+ fireListeners();
303
+ fireObservers(null);
304
+ }
305
+ function enqueueDispatch(msg) {
306
+ if (stopped) return Promise.reject(new Error("@demlik/tea: runtime stopped"));
307
+ const next = tail.then(() => {
308
+ if (bootError !== null) throw bootError;
309
+ return stepDispatch(msg);
310
+ });
311
+ tail = next.catch(() => {
312
+ });
313
+ return next;
314
+ }
315
+ const bootPromise = stepBootEffects();
316
+ tail = bootPromise.catch((err) => {
317
+ bootError = err;
318
+ });
319
+ const runtime = {
320
+ dispatch: enqueueDispatch,
321
+ getState() {
322
+ if (bootError !== null) throw bootError;
323
+ if (state === void 0) {
324
+ throw new Error("@demlik/tea: getState() called before runtime booted");
325
+ }
326
+ return state;
327
+ },
328
+ subscribe(listener) {
329
+ listeners.add(listener);
330
+ return () => {
331
+ listeners.delete(listener);
332
+ };
333
+ },
334
+ observe(observer) {
335
+ observers.add(observer);
336
+ return () => {
337
+ observers.delete(observer);
338
+ };
339
+ },
340
+ subscribePort(port, listener) {
341
+ const key = port;
342
+ let bucket = portRegistry.get(key);
343
+ if (!bucket) {
344
+ bucket = /* @__PURE__ */ new Set();
345
+ portRegistry.set(key, bucket);
346
+ }
347
+ const erased = listener;
348
+ bucket.add(erased);
349
+ return () => {
350
+ const set = portRegistry.get(key);
351
+ if (!set) return;
352
+ set.delete(erased);
353
+ if (set.size === 0) portRegistry.delete(key);
354
+ };
355
+ },
356
+ emitPort(port, value) {
357
+ portEmit(port, value);
358
+ },
359
+ // `ready` is the original (un-swallowed) boot promise. Idempotency
360
+ // comes for free — promises settle exactly once; every read returns the
361
+ // same settled value. See the boot-promise note above for why this is
362
+ // distinct from `tail`.
363
+ ready: bootPromise,
364
+ async stop() {
365
+ stopped = true;
366
+ await tail;
367
+ for (const [id, cleanup] of subRegistry) {
368
+ try {
369
+ cleanup();
370
+ } catch (err) {
371
+ console.error(err);
372
+ }
373
+ subRegistry.delete(id);
374
+ }
375
+ if (store && state !== void 0 && bootError === null) {
376
+ try {
377
+ await store.save(state);
378
+ } catch (err) {
379
+ console.error(err);
380
+ }
381
+ }
382
+ }
383
+ };
384
+ return runtime;
385
+ }
386
+ function historyTracker(runtime, size) {
387
+ const buffer = [];
388
+ let stopped = false;
389
+ const unobserve = size <= 0 ? () => {
390
+ } : runtime.observe((msg, state) => {
391
+ buffer.push({ msg, state });
392
+ if (buffer.length > size) buffer.shift();
393
+ });
394
+ return {
395
+ snapshot() {
396
+ return buffer.slice();
397
+ },
398
+ stop() {
399
+ if (stopped) return;
400
+ stopped = true;
401
+ unobserve();
402
+ }
403
+ };
404
+ }
405
+ function replay(machine, opts) {
406
+ const loaded = opts.loaded ?? null;
407
+ const [initialState, initCmds] = machine.init(loaded, opts.ctx);
408
+ if (loaded !== null && initCmds.length > 0) {
409
+ throw new Error(
410
+ "TEA contract violation: machine.init must return [state, []] (no Cmds) when `loaded` is non-null. Init's rehydrate branch is a pure state passthrough \u2014 the migration/parse boundary, not the boot-effect hook.\n\nRoutes for boot effects:\n - Stateless infrastructure (e.g. chrome.alarms ensure) \u2192 host module top level, outside TEA.\n - State-conditional resume (e.g. re-attach a session) \u2192 a `boot` Msg dispatched once from the host after `run(...)` returns, handled in update.\n\nSee .patterns/tea/tea-invariants.md (Invariant 2)."
411
+ );
412
+ }
413
+ let state = initialState;
414
+ const cmds = [...initCmds];
415
+ const updateForm = machine.update;
416
+ const updateMode = (() => {
417
+ const firstKey = Object.keys(updateForm)[0];
418
+ if (firstKey === void 0) return "reducer";
419
+ const firstValue = updateForm[firstKey];
420
+ return typeof firstValue === "function" ? "reducer" : "transitions";
421
+ })();
422
+ for (const msg of opts.msgs) {
423
+ if (__DEV__) deepFreeze(state);
424
+ let result;
425
+ if (updateMode === "reducer") {
426
+ result = updateForm[msg.type](
427
+ state,
428
+ msg
429
+ );
430
+ } else {
431
+ const table = updateForm;
432
+ const stateKey = state.type;
433
+ result = table[stateKey][msg.type](state, msg);
434
+ }
435
+ if (__DEV__) assertPureResult(result, msg.type);
436
+ const [next, emitted] = result;
437
+ state = next;
438
+ cmds.push(...emitted);
439
+ }
440
+ const subs = machine.subscriptions ? [...machine.subscriptions(state)] : [];
441
+ return { state, cmds, subs };
442
+ }
443
+ function tryInterpret(work, onOk, onErr) {
444
+ return async (cmd, ctx) => {
445
+ const result = await Result.tryPromise({
446
+ try: () => work(cmd, ctx),
447
+ catch: (error) => error
448
+ });
449
+ return result.match({
450
+ ok: (value) => onOk(value, cmd),
451
+ err: (error) => onErr(error, cmd)
452
+ });
453
+ };
454
+ }
455
+
456
+ export { Cmd, PortNameCollisionError, __resetPortRegistry, absurd, defineMachine, definePort, historyTracker, noop, replay, run, subId, tryInterpret };
457
+ //# sourceMappingURL=chunk-CMG2KMWX.js.map
458
+ //# sourceMappingURL=chunk-CMG2KMWX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"names":["state"],"mappings":";;;AA2BA,IAAM,WAAoB,MAAM;AAC9B,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,GAAO,MAAA,CAAA,IAAA;AACb,IAAA,IAAI,IAAA,CAAK,GAAA,EAAK,GAAA,KAAQ,KAAA,CAAA,EAAW;AAC/B,MAAA,OAAO,KAAK,GAAA,CAAI,GAAA;AAAA,IAClB;AAAA,EACF,CAAA,CAAA,MAAQ;AAAA,EAER;AACA,EAAA,IAAI;AACF,IAAA,OAAO,OAAO,OAAA,KAAY,WAAA,IAAe,OAAA,CAAQ,KAAK,QAAA,KAAa,YAAA;AAAA,EACrE,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF,CAAA,GAAG;AAEH,SAAS,UAAA,CAAc,KAAQ,IAAA,EAA2B;AACxD,EAAA,IAAI,GAAA,KAAQ,IAAA,IAAQ,OAAO,GAAA,KAAQ,UAAU,OAAO,GAAA;AACpD,EAAA,MAAM,KAAA,GAAQ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,GAAA,EAAK,MAAM,IAAA,CAAK,GAAA,EAAK,GAAG,CAAA;AAAA,MACxB,KAAA,EAAO,CAAC,KAAA,KAA4B;AAAA,KACrC,CAAA;AACD,IAAA,OAAO,OAAO,KAAA,CAAM;AAAA,MAClB,EAAA,EAAI,CAAC,KAAA,KAAU,IAAA,CAAK,OAAO,GAAG,CAAA;AAAA,MAC9B,GAAA,EAAK,CAAC,KAAA,KAAU,KAAA,CAAM,OAAO,GAAG;AAAA,KACjC,CAAA;AAAA,EACH,CAAA;AACF","file":"chunk-CMG2KMWX.js","sourcesContent":["/**\n * @demlik/tea — TEA-faithful state machine substrate.\n *\n * This module exposes the full Locked API Surface from the PRD as types and\n * implements `defineMachine` (identity, task 1), `run` (task 2), and\n * `replay` + `tryInterpret` (task 3).\n *\n * `replay` is the pure unit-test tool: it composes `init` + `update` only,\n * never touches `Store`, never calls `interpret`, never starts subscriptions.\n *\n * `tryInterpret` is Railway sugar — wraps a fallible async function and routes\n * Ok/Err to two Msg constructors via better-result.\n */\n\nimport { Result } from \"better-result\";\n\n// === Dev-mode invariant enforcement ===\n//\n// Three runtime guards that catch TEA invariant violations during development.\n// Dead-code-eliminated in production by any bundler that replaces\n// `import.meta.env.DEV` (Vite) or `process.env.NODE_ENV` (webpack/esbuild).\n//\n// 1. deepFreeze(state) before passing to update — catches mutation\n// 2. Thenable check on return value — catches async update\n// 3. Walk cmd fields for function types — catches closures-as-data\n//\n// These enforce invariants 1 and 2 at runtime where the type system cannot.\nconst __DEV__: boolean = (() => {\n try {\n const meta = import.meta as unknown as { env?: { DEV?: boolean } };\n if (meta.env?.DEV !== undefined) {\n return meta.env.DEV;\n }\n } catch {\n // import.meta not available (Node CJS, service workers)\n }\n try {\n return typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\";\n } catch {\n return false;\n }\n})();\n\nfunction deepFreeze<T>(obj: T, seen?: WeakSet<object>): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n const proto = Object.getPrototypeOf(obj);\n if (proto !== Object.prototype && proto !== Array.prototype && proto !== null) return obj;\n const visited = seen ?? new WeakSet();\n if (visited.has(obj as object)) return obj;\n visited.add(obj as object);\n Object.freeze(obj);\n for (const v of Object.values(obj as Record<string, unknown>)) deepFreeze(v, visited);\n return obj;\n}\n\nfunction hasFunctionValues(obj: unknown): string | null {\n if (obj === null || typeof obj !== \"object\") return null;\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n if (typeof value === \"function\") return key;\n }\n return null;\n}\n\nfunction assertPureResult(result: unknown, msgType: string): void {\n if (result && typeof (result as { then?: unknown }).then === \"function\") {\n throw new Error(\n `@demlik/tea: update cell \"${msgType}\" returned a Promise. ` +\n `update must be synchronous. Move async work to interpret.`,\n );\n }\n if (!Array.isArray(result) || result.length < 2 || !Array.isArray(result[1])) {\n throw new Error(\n `@demlik/tea: update cell \"${msgType}\" returned a non-tuple. ` +\n `Expected [State, Cmd[]], got ${typeof result}.`,\n );\n }\n const cmds = result[1] as readonly { type: string }[];\n for (const cmd of cmds) {\n const fnField = hasFunctionValues(cmd);\n if (fnField !== null) {\n throw new Error(\n `@demlik/tea: Cmd \"${cmd.type}\" has function field \"${fnField}\". ` +\n `Cmds must be plain data, not closures.`,\n );\n }\n }\n}\n\n// === Cmd: tagged-union, one-shot effect ===\nexport type Cmd<T extends string = string> = { type: T };\n\n// === Reducer<S, M, C>: record-of-handlers form of `update` ===\n//\n// Flat dispatch table keyed by `Msg.type`. Each cell is a pure transition for\n// a single Msg variant, narrowed via `Extract<M, { type: K }>`. The mapped type\n// is *load-bearing*: adding a Msg variant without a matching key in the\n// Reducer record is a compile error — no `absurd()` helper at call sites, no\n// silent fall-through, no default branch hiding impurity.\n//\n// Strengthens invariant 2 (pure transitions — the record form has no\n// fall-through default to hide impurity behind) and invariant 7 (identity is\n// explicit — the Msg variant set is load-bearing at the type level).\n//\n// `defineMachine` accepts the Reducer record form via overload. The runtime\n// dispatches via `update[msg.type](state, msg)`.\nexport type Reducer<S, M extends { type: string }, C extends Cmd> = {\n [K in M[\"type\"]]: (state: S, msg: Extract<M, { type: K }>) => readonly [S, readonly C[]];\n};\n\n// === Transitions<S, M, C>: table form of `update` for state-machine-shaped machines ===\n//\n// When `State` is itself a discriminated union (`State.type` is the active\n// phase), the table form makes every (state.type × msg.type) cell explicit at\n// the type level. Missing a cell — e.g. forgetting how `phase: \"settling\"`\n// handles `msg.type: \"tab_stepped\"` — fails to compile. No nested switch, no\n// fall-through, no `_ -> (state, [])` default branch hiding regressions.\n//\n// Each cell receives the narrowed `State` for its phase and the narrowed\n// `Msg` for its variant via two `Extract` lookups. Phantom-narrow at the\n// type level; pure data at runtime.\n//\n// `defineMachine` accepts a third `update` form for `Transitions<S, M, C>` —\n// the runtime dispatches via `update[state.type][msg.type](state, msg)`.\n//\n// Strengthens invariant 2 (table form has no fall-through default),\n// invariant 6 (runtime walks the table predictably, no hidden dispatch\n// fallback), and invariant 7 (both state.type and msg.type are load-bearing\n// at the type level).\nexport type Transitions<S extends { type: string }, M extends { type: string }, C extends Cmd> = {\n [P in S[\"type\"]]: {\n [K in M[\"type\"]]: (\n state: Extract<S, { type: P }>,\n msg: Extract<M, { type: K }>,\n ) => readonly [S, readonly C[]];\n };\n};\n\n// === absurd: compile-time exhaustiveness assertion ===\n//\n// Use in default branches of switches over discriminated unions where every\n// case should be handled explicitly. TS narrows the operand to `never` only\n// if every variant has been covered upstream; adding a new variant produces\n// a compile error at the `absurd(x)` site.\n//\n// The substrate's `Reducer<S, M, C>` and `Transitions<S, M, C>` forms cover\n// the reducer-side exhaustiveness with mapped types — no `absurd` needed\n// there. This helper exists for the OTHER boundaries where a discriminated\n// union is narrowed by hand: Sub handlers mapping a wire-protocol\n// discriminant to flat Msg variants, message-bridge dispatchers, port\n// fanouts, etc. Without it, consumers redeclare the same 3-line helper\n// across files; with it, the substrate owns the one canonical version.\n//\n// Strengthens invariant 7 (identity is explicit).\n/**\n * Compile-time exhaustiveness assertion. Use in default branches of\n * switches over discriminated unions where every case should be handled\n * explicitly — TS narrows the type to `never` only if every variant has\n * been covered. Strengthens invariant 7 (identity is explicit).\n *\n * @example\n * switch (msg.type) {\n * case \"a\": return ...;\n * case \"b\": return ...;\n * default: return absurd(msg); // compile error if a \"c\" is added\n * }\n */\nexport function absurd(x: never): never {\n throw new Error(`unreachable: ${JSON.stringify(x)}`);\n}\n\n// === noop: the explicit \"this cell ignores this msg\" helper ===\n//\n// Elm's fallback for unhandled (state × msg) pairs is implicit:\n// `_ -> (model, Cmd.none)` in a case expression. We make it explicit because\n// implicit no-ops are silent regressions waiting to happen — a future Msg\n// variant that *should* be handled gets swallowed by the wildcard.\n//\n// Naming the no-op forces the author to *decide*: \"this cell does nothing\"\n// is a real decision, distinct from \"I forgot to write this cell.\" The\n// mapped type rejects the second case; `noop` names the first.\n//\n// Assignable to any Transitions cell regardless of S/M/C concrete types\n// (the type parameters are free) — drop it into any cell without per-type\n// casts.\nexport const noop = <S, M, C extends Cmd>(state: S, _msg: M): readonly [S, readonly C[]] => [\n state,\n [],\n];\n\n// === Cmd: namespace for conditional Cmd emission ===\n//\n// Two recurring frictions in reducer cells:\n//\n// 1. \"Emit cmd X only when condition Y holds.\"\n// Hand-rolled: `cond ? [{ type: \"x\", ... }] : []`\n// With Cmd: `Cmd.when(cond, { type: \"x\", ... })`\n//\n// 2. \"Emit cmd X carrying a value that may be undefined; if undefined,\n// emit nothing.\"\n// Hand-rolled: `value !== undefined ? [{ type: \"x\", value }] : []`\n// With Cmd: `Cmd.whenDefined(value, (v) => ({ type: \"x\", value: v }))`\n//\n// Both forms return `readonly C[]` so they spread cleanly into the cmds\n// array returned by a Transitions cell:\n//\n// return [next, [\n// ...Cmd.when(state.tabId !== undefined, { type: \"detach_debugger\", tabId: state.tabId }),\n// ...Cmd.whenDefined(state.queueItemId, (id) => ({\n// type: \"queue:complete\", queueItemId: id, status: \"done\",\n// })),\n// ]];\n//\n// `Cmd` as a value namespace coexists with `Cmd<T>` as a type — TypeScript's\n// declaration merging puts them in different name spaces (type vs. value).\n// The reader sees `Cmd<...>` in type position and `Cmd.when(...)` in\n// expression position; no ambiguity at use sites.\n//\n// Why a namespace and not top-level `when` / `whenDefined`: `when` at module\n// scope reads as a generic conditional, but these helpers are specifically\n// for *Cmd emission* (return `readonly C[]`, the cmds-array contract of\n// every Transitions cell). The namespace pins that intent at the call site.\nexport const Cmd = {\n /**\n * The empty Cmd array. Typed `readonly never[]` so it's assignable to any\n * `readonly C[]` for any `C extends Cmd`. Use in `init` returns and\n * Transitions cells that emit zero effects:\n *\n * init: (loaded) => [loaded ?? initial, Cmd.none],\n * tick: (state) => [state, Cmd.none],\n *\n * Elm's `Cmd.none` analogue. Cultural signal alongside the runtime help:\n * `[state, Cmd.none]` reads as intent (\"this transition emits nothing\"),\n * `[state, []]` reads as \"empty array of what\".\n *\n * Frozen at runtime so a downstream consumer can't `.push()` into the\n * shared reference.\n */\n none: Object.freeze([]) as readonly never[],\n\n /**\n * Flat concat of cmd arrays. Use when a cell composes effects from\n * multiple conditional sources:\n *\n * return [next, Cmd.batch(\n * Cmd.whenDefined(state.queueItemId, (id) => ({ type: \"complete\", id })),\n * Cmd.when(state.windowId !== undefined, { type: \"close_window\", windowId }),\n * [{ type: \"detach_debugger\", tabId: state.tabId }],\n * )];\n *\n * `<const C>` keeps inline cmd literals' discriminants narrow (same\n * rationale as `when` / `whenDefined` above).\n */\n batch: <const C extends Cmd>(...arrs: readonly (readonly C[])[]): readonly C[] => {\n const out: C[] = [];\n for (const arr of arrs) out.push(...arr);\n return out;\n },\n\n /**\n * Emit `cmd` wrapped in a single-element array iff `cond` is true.\n * Otherwise return the empty array. Spreads cleanly into the cmds array\n * returned by a Transitions cell.\n *\n * `const C` (TypeScript 5.0+) keeps the inferred `type:` discriminator\n * literal narrow when called with an object literal — so `Cmd.when(b,\n * { type: \"x\", ... })` infers as `{ type: \"x\", ... }`, not `{ type:\n * string, ... }`, and stays assignable to a discriminated-union arm\n * without `as const` at the call site.\n */\n when: <const C extends Cmd>(cond: boolean, cmd: C): readonly C[] => (cond ? [cmd] : []),\n\n /**\n * If `value` is defined, call `build(value)` and emit the resulting cmd\n * wrapped in a single-element array. If `value` is `undefined`, return\n * the empty array. `value` is narrowed to `T` inside `build`.\n *\n * `const C` on the return type keeps the callback's object-literal\n * `type:` field narrow (see `when` above for the full rationale).\n */\n whenDefined: <T, const C extends Cmd>(\n value: T | undefined,\n build: (value: T) => C,\n ): readonly C[] => (value !== undefined ? [build(value)] : []),\n} as const;\n\n// === SubId: branded string for Sub identity ===\n//\n// Subs are reconciled by id on every transition (canon §2.5, invariant 7).\n// Before branding, `Sub.id` was a raw `string` — a typo at one call site and a\n// different typo at another would silently produce two distinct subs that\n// looked identical to a human reader. The brand makes id construction explicit\n// (`subId(\"...\")`) and catches accidental string-where-SubId at the type\n// level.\n//\n// The brand is structural: `string & { __brand: \"SubId\" }`. The `subId(s)`\n// constructor is the ONE permitted cast in the substrate — every other call\n// site must go through it.\nexport type SubId = string & { readonly __brand: \"SubId\" };\n\n/**\n * Construct a `SubId` from a string. Use this everywhere a Sub literal is\n * built — including ids derived from runtime data (`subId(\\`ws:${auditId}\\`)`).\n * The brand is structural, not nominal, so dynamic ids are permitted; the\n * constructor's job is to make the identity decision explicit at every call\n * site so the type system can catch accidental raw-string drift.\n *\n * Strengthens invariant 7 (identity is explicit).\n */\nexport function subId(s: string): SubId {\n return s as SubId;\n}\n\n// === Sub: tagged-union, continuous source of msgs; stable id used for diff/reconcile ===\nexport type Sub<T extends string = string> = { id: SubId; type: T };\n\n// === Port<T>: typed escape hatch for \"data leaving the runtime\" ===\n//\n// A Port is a named, typed channel that Cmd handlers can `emit` to via the\n// augmented `ctx.emit(port, value)`. Subscribers attach via\n// `runtime.subscribePort(port, listener)` and receive every emitted value\n// synchronously (same fanout discipline as `runtime.observe`).\n//\n// Why Ports are a substrate primitive, distinct from State and Observe:\n// - **State** is \"the world as the program sees it.\" Folding outgoing\n// announcements into State turns ephemeral signals into persisted facts —\n// the classic anti-pattern that motivated this primitive.\n// - **Observe** sees every transition `(msg, state)`. That's the right channel\n// for devtools and logging, but it forces every consumer to filter the\n// entire firehose for a single signal.\n// - **Ports** are typed and selective: one channel per concept, subscribers\n// only see what the handler chose to emit. Mirrors Elm's outgoing-port\n// semantics — a typed declaration with `port` keyword whose values flow\n// out of the program to the host.\n//\n// Port identity is **by reference** — the returned object IS the identity.\n// Name is metadata for debugging. To prevent the \"two modules definePort the\n// same name expecting to share a channel, silently get distinct ports\" class\n// of bug, `definePort` asserts the name has not been seen in this process —\n// the symmetric runtime check to `SubId` (canon §2.12, invariant 7). Each\n// definePort call must use a unique name; if two modules need the same port,\n// one module exports it and the other imports it.\nexport interface Port<T> {\n readonly __brand: \"port\";\n readonly name: string;\n // Phantom field — never assigned, never read at runtime. Carries `T` for\n // inference at `ctx.emit` and `subscribePort` call sites. Using `?` so\n // `definePort` can produce a Port without constructing a value of `T`.\n readonly __t?: T;\n}\n\n// Module-level registry — process-scope, identity-by-name. The set is the\n// runtime witness that every port name in this process is unique. Cleared\n// only by the test-only `__resetPortRegistry()` helper.\nconst definedPortNames = new Set<string>();\n\n/**\n * Thrown by `definePort` when a name has already been registered in the\n * current process. Symmetric with the `Sub.id` collision assert in\n * `reconcileSubs` — both mechanize invariant 7 (identity is explicit) at the\n * runtime layer the type system cannot reach (string names compared at\n * runtime, not at compile time).\n */\nexport class PortNameCollisionError extends Error {\n override readonly name = \"PortNameCollisionError\";\n constructor(portName: string) {\n super(\n `definePort: a port named \"${portName}\" was already defined. ` +\n `Each definePort call must use a unique name. ` +\n `If two modules need the same port, export it from one module and import it.`,\n );\n }\n}\n\n/**\n * Test-only escape hatch — clears the module-level port-name registry so the\n * collision assert in `definePort` doesn't false-positive across vitest's\n * non-isolated runs. Production code MUST NOT call this; the registry is the\n * invariant-7 witness for the process lifetime.\n *\n * @internal test-only\n */\nexport function __resetPortRegistry(): void {\n definedPortNames.clear();\n}\n\n/**\n * Define a typed port. `name` is metadata (shown in devtools / debug logs);\n * port identity is by reference. Each definePort call must use a unique\n * `name` — a second call with the same name throws\n * `PortNameCollisionError`. If two modules need the same port, export it\n * from one module and import it from the other.\n *\n * Use ports for \"data leaving the runtime selectively\" — e.g. cursor\n * announcements, DOM-mutation broadcasts, telemetry events that should NOT be\n * folded into State and should NOT be observed by every transition listener.\n *\n * Strengthens invariant 7 (identity is explicit) — the runtime assert is the\n * Port-side counterpart of `SubId`'s id collision check in `reconcileSubs`.\n */\nexport function definePort<T>(name: string): Port<T> {\n // HMR skip — Vite / dev servers re-import the module on hot reload, which\n // would otherwise false-positive on every definePort across reloads. The\n // try/catch is load-bearing for service-worker bundles: Vite polyfills\n // `import.meta.url` via `document.baseURI`, which throws ReferenceError in\n // an MV3 service worker. A throw here would abort SW install (Chrome\n // surfaces it as \"registration failed status 15\"). Catching it = \"no HMR\n // detected\" = the collision check applies, which is the correct SW\n // behavior (SWs reload via chrome.runtime.reload, not module HMR).\n let isHmr = false;\n try {\n const meta = import.meta as { hot?: unknown };\n isHmr = meta?.hot !== undefined && meta?.hot !== null;\n } catch {\n isHmr = false;\n }\n if (!isHmr && definedPortNames.has(name)) {\n throw new PortNameCollisionError(name);\n }\n definedPortNames.add(name);\n return { __brand: \"port\", name } as Port<T>;\n}\n\n/**\n * Augmentation injected onto `ctx` inside Cmd handlers. Handlers receive\n * `ctx & PortEmitter` so they can call `ctx.emit(port, value)` synchronously.\n * Subscribers registered via `runtime.subscribePort(port, listener)` receive\n * the value immediately.\n *\n * Emitting to a port with no subscribers is a no-op (does not throw).\n */\nexport interface PortEmitter {\n emit<T>(port: Port<T>, value: T): void;\n}\n\n// === Interpret<M, C, Ctx>: record-of-handlers form of `interpret` ===\n//\n// Flat dispatch table keyed by `Cmd.type`. Each cell receives the narrowed Cmd\n// and the runtime-augmented Ctx (`Ctx & PortEmitter`) and resolves to a\n// follow-up Msg or `void` (fire-and-forget). The mapped type makes a missing\n// handler a compile error — `defineMachine` cannot accept the dictionary until\n// every Cmd variant has one.\n//\n// Hoisted out of `Machine.interpret` so consumers can type a free-standing\n// handler dictionary with `Interpret<MyMsg, MyCmd, MyCtx>` instead of\n// re-declaring the mapped type at every effects module.\n//\n// Strengthens invariant 2 (the record form has no fall-through default to\n// hide impurity behind) and invariant 7 (identity is explicit — the Cmd\n// variant set is load-bearing at the type level).\nexport type Interpret<M extends { type: string }, C extends Cmd, Ctx> = {\n [K in C[\"type\"]]: (cmd: Extract<C, { type: K }>, ctx: Ctx & PortEmitter) => Promise<M | void>;\n};\n\n// === Subscribe<M, U, Ctx>: record-of-handlers form of `subscribe` ===\n//\n// Flat dispatch table keyed by `Sub.type`. Each cell receives the narrowed\n// Sub, the Ctx, and a `dispatch` to fire follow-up Msgs. Returns a cleanup\n// function the substrate calls when the Sub is reconciled out (state\n// transitioned away). The mapped type guarantees every Sub variant has a\n// handler at the type level; runtime dispatch is a single property lookup.\n//\n// Hoisted out of `Machine.subscribe` so consumers can type a free-standing\n// handler dictionary with `Subscribe<MyMsg, MySub, MyCtx>` instead of\n// re-declaring the mapped type at every subs module.\n//\n// Strengthens invariant 7 (identity is explicit — the Sub variant set is\n// load-bearing at the type level).\nexport type Subscribe<M extends { type: string }, U extends Sub, Ctx> = {\n [K in U[\"type\"]]: (\n sub: Extract<U, { type: K }>,\n ctx: Ctx,\n dispatch: (msg: M) => void,\n ) => () => void;\n};\n\n// === Machine: pure data, host-agnostic ===\n//\n// `update` is stored as a union of the two record forms — the runtime branches\n// on shape at dispatch time. The public `defineMachine` overloads enforce one\n// shape per call so consumers never see the union themselves.\n//\n// - Reducer form: `Reducer<S, M, C>` — flat record keyed by Msg.type;\n// exhaustiveness enforced by the mapped type.\n// - Transitions form: `Transitions<S, M, C>` — 2D table keyed by\n// `state.type` then `msg.type`; only available when `S extends { type:\n// string }`. Conditional in the union so machines without a discriminated\n// State don't widen to include this branch.\n//\n// `M` is constrained to `{ type: string }` because both record forms require\n// a string discriminant.\n//\n// `interpret` is conditionally optional: when `C` is `Cmd<never>` the\n// interpret map is keyed by `never`, so the only valid value is `{}`. Forcing\n// every cmdless machine to write `interpret: {} as never` is ceremony for a\n// shape the type already pins. The tuple-wrap (`[C] extends [Cmd<never>]`)\n// disables distributive conditional so a real cmd union (e.g.\n// `Cmd<\"a\"> | Cmd<\"b\">`) doesn't degrade to optional just because one arm\n// happens to be `Cmd<never>`. Same trick the `update` field uses.\nexport type Machine<S, M extends { type: string }, C extends Cmd, U extends Sub, Ctx> = {\n /**\n * Boot the runtime. Called once by `run(...)` with whatever `Store.load()`\n * returned: `null` on fresh boot, the persisted state on rehydrate.\n *\n * **Contract:** when `loaded !== null`, init MUST return `[loaded, []]` —\n * no Cmds. Init's rehydrate branch is the migration / parse boundary, not\n * the boot-effect hook. See Invariant 2 in `.patterns/tea/tea-invariants.md`.\n *\n * Boot effects routes:\n * - Stateless infrastructure → host module top, outside TEA.\n * - State-conditional resume → a `boot` Msg the host dispatches once\n * after `run(...)` returns.\n *\n * Violations are caught at runtime by `replay` (which throws with a\n * pointer to the alternatives).\n */\n init: (loaded: S | null, ctx: Ctx) => readonly [S, readonly C[]];\n update:\n | Reducer<S, M, C>\n // Wrap in tuple to disable distributive conditional behavior. Without\n // `[S]`, TS distributes the conditional across `S`'s union members,\n // producing `Transitions<A,...> | Transitions<B,...>` instead of the\n // desired `Transitions<A|B,...>` — the table form needs a single\n // mapping over the full union of state types, not separate tables per\n // member.\n | ([S] extends [{ type: string }] ? Transitions<S, M, C> : never);\n subscriptions?: (state: S) => readonly U[];\n subscribe?: Subscribe<M, U, Ctx>;\n} & ([C] extends [Cmd<never>]\n ? { interpret?: Interpret<M, C, Ctx> }\n : { interpret: Interpret<M, C, Ctx> });\n\n// === Store: pluggable persistence adapter ===\n//\n// `load()` returns `unknown` because storage genuinely doesn't know `S` —\n// chrome.storage returns whatever JSON lives at the key, DurableObjectStorage\n// returns whatever bytes were serialized. Casting raw storage to `S` at the\n// adapter boundary is the exact `as S` move forbidden by invariant 8\n// everywhere else in the substrate. `load()` returning `unknown` makes the\n// substrate stop pretending.\n//\n// `migrate(raw)` is the boundary parse. Returns `S` on a recognized shape —\n// the substrate passes it to `init` as `loaded`. Returns `null` on any\n// unrecognized shape — the substrate passes `null` to `init`, fresh-boot\n// path. Must NOT throw: if a future shape is unrecognizable, returning\n// `null` boots clean from a known-good path. Throwing here would\n// indistinguishably collapse \"storage corruption\" and \"schema migration not\n// yet written\" — both are runtime decisions, not panics.\n//\n// Strengthens invariant 8 (the boundary parses; the core trusts) — the\n// substrate now enforces the parse instead of relying on every adapter\n// remembering to.\nexport interface Store<S> {\n load(): Promise<unknown>;\n save(state: S): Promise<void>;\n migrate(raw: unknown): S | null;\n}\n\n// === RuntimeRef<M>: typed sibling-runtime handle ===\n//\n// A `RuntimeRef<M>` exposes only the inbox of a Runtime — `dispatch(msg)`.\n// Use it as the field type when one runtime holds a reference to a *sibling*\n// runtime (composition by reduction across orthogonal lifecycles — invariant\n// 5). The holder learns the Msg shape it can send, nothing about the\n// referenced runtime's State, Cmd, Sub, Ctx, observers, listeners, or Port\n// fanout. That asymmetry is the point: cross-runtime coupling collapses to\n// \"I can put a Msg in your inbox\", which is the smallest coordination\n// surface that preserves typed cross-runtime calls.\n//\n// `Runtime<S, M>` extends `RuntimeRef<M>` structurally — every Runtime is\n// trivially a RuntimeRef. The narrowing happens at the *consumer's* Ctx\n// type, not via a runtime cast.\n//\n// Strengthens invariant 5 (composition by reduction — sibling runtimes\n// coordinate through the narrowest typed surface) and invariant 6 (runtime\n// is small and inspectable — what a holder *can* do to a sibling runtime is\n// exactly one method, not the full surface).\nexport interface RuntimeRef<M extends { type: string }> {\n dispatch(msg: M): Promise<void>;\n}\n\n// === Runtime: handle returned from run() ===\n//\n// `subscribe(listener)` is the React-shaped change notifier (zero-arg, paired\n// with `getState()` via `useSyncExternalStore`). `observe(observer)` is the\n// devtools-shaped trace hook: it receives `(msg, state)` for every completed\n// transition, including the boot transition where `msg` is `null`. Both fire\n// from the same point in the dispatch loop (after save → reconcile →\n// interpret), so what an observer sees is consistent with what a subscriber\n// sees via `getState()`.\n//\n// Observe is separate from subscribe because the contracts differ: React\n// consumers want \"something changed, re-read state\"; devtools consumers want\n// \"here is the exact (msg, state) pair, append it to a log\". Folding them\n// would force every React subscriber to type-check a `msg | null` arg they\n// will never use, and would couple `useSyncExternalStore` to a particular Msg\n// type at the substrate.\nexport interface Runtime<S, M extends { type: string }> extends RuntimeRef<M> {\n dispatch(msg: M): Promise<void>;\n getState(): S;\n subscribe(listener: () => void): () => void;\n observe(observer: (msg: M | null, state: S) => void): () => void;\n /**\n * Subscribe to a typed Port. Returns a cleanup function that removes the\n * listener. Multiple listeners per port are supported; fanout is synchronous\n * (same shape as `observe`) and isolated — one listener throw does not strand\n * the others.\n *\n * Ports are for \"data leaving the runtime selectively\" — see `definePort`.\n * Distinct from `observe` (every transition) and from State (the world).\n */\n subscribePort<T>(port: Port<T>, listener: (value: T) => void): () => void;\n /**\n * Emit a value on a Port from OUTSIDE an interpret handler. Same synchronous\n * fanout discipline as `ctx.emit` inside interpret — every subscriber\n * receives the value immediately; emitting to a port with no subscribers is\n * a no-op; listener throws are isolated.\n *\n * Use this for `observe`-driven Port emission: the canonical case is one\n * runtime publishing a state-derived signal (e.g. \"am I idle?\") that\n * another runtime subscribes to via `subscribePort`. Without\n * `runtime.emitPort`, the only way to emit a Port is from inside an\n * `interpret` handler — which forces the reducer to spawn a \"tell the\n * outside world\" Cmd on every transition that should signal. With it,\n * `runtime.observe((msg, state) => runtime.emitPort(port, derive(state)))`\n * keeps the reducer free of Port-plumbing Cmds and matches the \"every\n * transition is observable\" contract this invariant set already commits to.\n *\n * Strengthens invariant 6 (runtime is small and inspectable — Port emission\n * is no longer privileged to interpret handlers; `observe`-driven emission\n * is structurally supported).\n */\n emitPort<T>(port: Port<T>, value: T): void;\n /**\n * Resolves after boot completes — i.e. after `store.load()` (if any), `init`,\n * `store.save()` of the initial state, `reconcileSubs`, `interpret` of any\n * init-emitted cmds, and the initial listener / observer fanout. Rejects with\n * the boot error if boot fails (the same error every subsequent `dispatch`\n * call rejects with).\n *\n * Idempotent — subsequent reads return the same settled promise. The runtime\n * holds exactly one `ready` promise per `run()` call.\n *\n * Closes the v1 boot-await gap previously documented in `stepBootEffects`:\n * components that need synchronous initial state under a store (e.g.,\n * `useSyncExternalStore` consumers) can `await runtime.ready` instead of\n * `runtime.dispatch(noopMsg)`.\n *\n * Expresses canon §2.3 (the `init` contract — boot is a named, awaitable\n * moment). Strengthens invariant 6 (runtime is small and inspectable).\n */\n ready: Promise<void>;\n stop(): Promise<void>;\n}\n\n// === defineMachine: identity-typed pass-through ===\n//\n// Overloads enforce exactly one `update` shape per call so consumers see a\n// concrete type for `update`, not the substrate-internal union. Implementation\n// is identity at runtime — the runtime (`run`) branches on the structural\n// shape of `update` (Reducer vs Transitions) when dispatching.\n//\n// - Reducer-form overload: `update: Reducer<S, M, C>` — flat record keyed by\n// Msg.type. Exhaustiveness is enforced by the mapped type; adding a Msg\n// variant without a matching key is a compile error.\n// - Transitions-form overload: `update: Transitions<S, M, C>` — 2D table\n// keyed by State.type then Msg.type. Only available when `S extends {\n// type: string }`.\n//\n// Distinguishing the two: TS overload resolution checks the literal shape of\n// the argument. Reducer values are functions; Transitions values are records\n// (of functions). Structurally distinct, so overload resolution picks the\n// right branch.\n//\n// Strengthens invariant 2 (record forms have no fall-through default) and\n// invariant 7 (the Msg variant set — and, for Transitions, the State variant\n// set — is load-bearing at the type level).\n\n// Transitions-form overload — `update` is a 2D table keyed by State.type\n// then Msg.type. Declared FIRST (most specific): the value shape (record of\n// records of functions) is structurally distinct from Reducer (record of\n// functions), so TS overload resolution picks this branch only when the\n// literal matches the table shape.\n//\n// The S constraint is expressed via a conditional `S extends { type: string\n// } ? Transitions<S, M, C> : never` instead of a generic-parameter\n// constraint. The conditional approach keeps `S` unconstrained at the\n// overload signature, so `Parameters<typeof defineMachine<NonDiscriminatedS,\n// ...>>` (the public `satisfies` pattern) doesn't fail at the first\n// overload — it just skips to the next one because `update` becomes\n// `never`.\nexport function defineMachine<S, M extends { type: string }, C extends Cmd, U extends Sub, Ctx>(\n m: Omit<Machine<S, M, C, U, Ctx>, \"update\"> & {\n // `[S]` tuple-wrap disables distributive conditional behavior — see\n // the comment on `Machine.update` for why distribution is wrong here.\n update: [S] extends [{ type: string }] ? Transitions<S, M, C> : never;\n },\n): Machine<S, M, C, U, Ctx>;\n// Reducer-form overload — `update` is a flat record keyed by Msg.type.\n// Object literals where every property is a function match this shape.\nexport function defineMachine<S, M extends { type: string }, C extends Cmd, U extends Sub, Ctx>(\n m: Omit<Machine<S, M, C, U, Ctx>, \"update\"> & {\n update: Reducer<S, M, C>;\n },\n): Machine<S, M, C, U, Ctx>;\n// Implementation signature — accepts both via the union on `Machine.update`.\nexport function defineMachine<S, M extends { type: string }, C extends Cmd, U extends Sub, Ctx>(\n m: Machine<S, M, C, U, Ctx>,\n): Machine<S, M, C, U, Ctx> {\n return m;\n}\n\n// === run: implemented in task 2 ===\n//\n// Returns a `Runtime<S, M>` synchronously. Boot (`store?.load()` + `init`) runs\n// asynchronously as the FIRST entry on the serial dispatch tail; every public\n// runtime method (`dispatch`, `stop`, `getState`) awaits the boot phase\n// implicitly through the queue. Failures inside `store.load` propagate via the\n// boot promise — subsequent calls reject/throw with that error. There is no\n// \"synchronous load\" branch because `Store#load` is async by contract.\n//\n// Save-then-effects ordering is structural: every transition mutates state,\n// awaits `store.save(newState)`, then reconciles subscriptions, then runs\n// `interpret` for emitted cmds, then fires external listeners. A throw in any\n// effect phase leaves the persisted state ahead of the host's belief about\n// what executed — the Railway discipline (`tryInterpret` in handlers) makes\n// that safe in practice.\nexport function run<S, M extends { type: string }, C extends Cmd, U extends Sub, Ctx>(\n machine: Machine<S, M, C, U, Ctx>,\n opts: { ctx: Ctx; store?: Store<S> },\n): Runtime<S, M> {\n const { ctx, store } = opts;\n\n // Holders are intentionally late-initialized: `state` is set inside the boot\n // step, which runs as the head of the tail. `getState()` before boot throws.\n let state: S | undefined;\n let bootError: unknown = null;\n let stopped = false;\n\n const subRegistry = new Map<string, () => void>();\n const listeners = new Set<() => void>();\n // Observers receive (msg, state) for every completed transition. Boot fires\n // once with msg = null. Same throw-isolation contract as listeners.\n const observers = new Set<(msg: M | null, state: S) => void>();\n\n // Port subscriber registry. Keyed by Port reference (NOT name) — port\n // identity is nominal/by-reference per Elm semantics. Each port can have\n // many listeners; emissions fan out synchronously to all of them.\n // `Set<(value: unknown) => void>` is the storage shape; per-port type\n // safety is enforced at the `subscribePort` / `emit` call sites via the\n // phantom `__t` field on `Port<T>`.\n const portRegistry = new Map<Port<unknown>, Set<(value: unknown) => void>>();\n\n // The `emit` function injected onto ctx. Synchronous fanout — same shape as\n // `observe`. No-op when the port has no subscribers. Listener throws are\n // isolated + logged so one bad subscriber does not strand the others.\n function portEmit<T>(port: Port<T>, value: T): void {\n const subscribers = portRegistry.get(port as Port<unknown>);\n if (!subscribers || subscribers.size === 0) return;\n for (const listener of subscribers) {\n try {\n listener(value);\n } catch (err) {\n console.error(err);\n }\n }\n }\n\n // Augmented ctx passed to every Cmd handler. `ctx` is intentionally spread\n // into a fresh object so handlers receive a Ctx & PortEmitter without\n // mutating the caller's ctx (which may be shared across runtimes / tests).\n const augmentedCtx: Ctx & PortEmitter = { ...ctx, emit: portEmit };\n\n // === update dispatch ===\n //\n // The substrate accepts two `update` shapes (see `defineMachine` overloads):\n //\n // 1. Reducer: `{ [msg.type]: (state, msg) => [S, C[]] }`\n // 2. Transitions: `{ [state.type]: { [msg.type]: (state, msg) => [S, C[]] } }`\n //\n // Branch is structural: an object's first inspected handler tells us\n // flat-vs-nested — if `update[msg.type]` is itself a function it's a\n // Reducer; if it's an object whose value is a function it's a Transitions\n // table. No runtime tag added to the Machine — the form is detectable from\n // the value shape, and the type system guarantees `update` matches one of\n // the two shapes at the `defineMachine` boundary.\n //\n // The form is detected ONCE per `run()` call (here, at runtime setup) and\n // cached as `updateMode`. The per-dispatch path is then a single branch +\n // 1-or-2 property lookups — no per-call shape inspection.\n type CellFn = (state: S, msg: M) => readonly [S, readonly C[]];\n type ReducerRecord = Reducer<S, M, C>;\n type TransitionsTable = {\n [stateType: string]: { [msgType: string]: CellFn };\n };\n const updateForm = machine.update;\n type UpdateMode = \"reducer\" | \"transitions\";\n const updateMode: UpdateMode = (() => {\n // Inspect a single value to disambiguate. Both Reducer and Transitions\n // are non-null objects; their values differ: Reducer's values are\n // functions, Transitions's values are objects (of functions). Pick the\n // first own key — order doesn't matter because the record forms are\n // uniform (every cell has the same value shape).\n const firstKey = Object.keys(updateForm as object)[0];\n if (firstKey === undefined) {\n // Empty object literal: M is `never`. No msg can ever be dispatched,\n // so the mode is irrelevant — pick \"reducer\" arbitrarily. Pre-boot\n // this never executes because the runtime never dispatches `never`.\n return \"reducer\";\n }\n const firstValue = (updateForm as Record<string, unknown>)[firstKey];\n return typeof firstValue === \"function\" ? \"reducer\" : \"transitions\";\n })();\n function applyUpdate(state: S, msg: M): readonly [S, readonly C[]] {\n if (__DEV__) deepFreeze(state);\n\n let result: readonly [S, readonly C[]];\n if (updateMode === \"reducer\") {\n // Flat record dispatch. Mapped type (`Reducer<S, M, C>`) guarantees\n // every Msg variant has a handler at the type level; runtime is a\n // single property lookup with no fallback default branch.\n const record = updateForm as ReducerRecord;\n const handler = record[msg.type as M[\"type\"]];\n result = handler(state, msg as Extract<M, { type: M[\"type\"] }>);\n } else {\n // Transitions table dispatch. `state` is constrained to\n // `{ type: string }` by the `defineMachine` Transitions overload; the\n // table guarantees every (state.type × msg.type) cell exists at the\n // type level. Runtime is two property lookups + the call.\n const table = updateForm as unknown as TransitionsTable;\n const stateKey = (state as unknown as { type: string }).type;\n // The Transitions overload guarantees every (state.type × msg.type) cell\n // exists at the type level; the runtime lookup cannot miss.\n const handler = table[stateKey]![msg.type]!;\n result = handler(state, msg);\n }\n\n if (__DEV__) assertPureResult(result, msg.type);\n return result;\n }\n\n // The serial dispatch queue: every step is chained onto `tail`. New dispatch\n // calls (and re-entrant ones from interpret follow-ups) wait for the\n // previous step to fully resolve before running their reducer. This is the\n // single concurrency gate.\n let tail: Promise<void> = Promise.resolve();\n\n /**\n * Reconcile subscriptions against `state`. Called after every save.\n *\n * - Same id present in old + new → leave running.\n * - Removed id → call cleanup. Swallow cleanup throws + `console.error`.\n * - New id → call subscribe[type]; on success store cleanup. On throw, the\n * sub is NOT registered; throw is remembered and re-thrown after the loop\n * so all other new subs still register.\n */\n function reconcileSubs(): void {\n if (!machine.subscriptions) return;\n const desired = machine.subscriptions(state as S);\n const desiredIds = new Set<string>();\n\n // Collision assert: within a single desired set, two subs sharing an id\n // but declaring different types is the silent class of bug that Elm's\n // sub diffing relies on the user to avoid — we catch it explicitly here.\n // (Same id + same type within the desired set is a redundant declaration\n // — harmless, and the `subRegistry.has` check below dedupes it on the\n // start path. Same id across transitions is the no-churn case the\n // reconcile pass is designed for and MUST NOT throw.)\n const desiredTypeById = new Map<string, string>();\n for (const sub of desired) {\n const existing = desiredTypeById.get(sub.id);\n if (existing !== undefined && existing !== sub.type) {\n throw new Error(\n `@demlik/tea: Sub.id collision: id=\"${sub.id}\" declared as type=\"${existing}\" and type=\"${sub.type}\"`,\n );\n }\n desiredTypeById.set(sub.id, sub.type);\n }\n\n // Removals first — anything in the registry not in `desired` should stop.\n for (const sub of desired) desiredIds.add(sub.id);\n for (const [id, cleanup] of subRegistry) {\n if (!desiredIds.has(id)) {\n try {\n cleanup();\n } catch (err) {\n console.error(err);\n }\n subRegistry.delete(id);\n }\n }\n\n // Additions — anything in `desired` not in the registry should start.\n let firstStartError: unknown = null;\n for (const sub of desired) {\n if (subRegistry.has(sub.id)) continue;\n const handler = machine.subscribe?.[sub.type as U[\"type\"]];\n if (!handler) {\n // No handler for this sub type — programmer error; skip. (TS would\n // normally forbid this at compile time when `subscribe` is provided\n // and U has variants, but a runtime guard is cheap.)\n continue;\n }\n try {\n const cleanup = handler(sub as Extract<U, { type: U[\"type\"] }>, ctx, enqueueDispatch);\n subRegistry.set(sub.id, cleanup);\n } catch (err) {\n if (firstStartError === null) firstStartError = err;\n // Do NOT register; continue to next sub so other starts still run.\n }\n }\n if (firstStartError !== null) throw firstStartError;\n }\n\n // `interpret` is optional at the type level when `C extends Cmd<never>`\n // (see `Machine<...>`). The runtime safely defaults a missing map to `{}`\n // because such a machine never emits cmds — the cmd loop below never\n // dereferences a handler. The defensive default also guards against a\n // miswired non-Cmd<never> consumer reaching this code path; the per-cmd\n // `if (!handler) continue` then preserves invariant-6 forward progress\n // instead of throwing on `undefined.foo`.\n type InterpretMap = {\n [K in C[\"type\"]]: (cmd: Extract<C, { type: K }>, ctx: Ctx & PortEmitter) => Promise<M | void>;\n };\n const interpretMap: InterpretMap =\n (machine as { interpret?: InterpretMap }).interpret ?? ({} as InterpretMap);\n\n /**\n * Run `interpret` for each emitted cmd. Each handler may return a follow-up\n * Msg — that Msg is enqueued onto the tail (NOT dispatched re-entrantly\n * inside the current transition).\n *\n * Throws propagate to the caller of `step`. The first error stops further\n * handlers in this transition.\n */\n async function runInterpret(cmds: readonly C[]): Promise<void> {\n for (const cmd of cmds) {\n const handler = interpretMap[cmd.type as C[\"type\"]];\n if (!handler) continue;\n const follow = await handler(cmd as Extract<C, { type: C[\"type\"] }>, augmentedCtx);\n if (follow !== undefined && follow !== null) {\n // Schedule follow-up Msg on the tail. The current step resolves\n // first; the follow-up runs after, as a fresh transition. Swallow the\n // returned rejection — fire-and-forget at this site; the runtime\n // never re-throws follow-up errors at the dispatcher of the original\n // cmd. If you need observable error handling, name a failure Msg via\n // `tryInterpret` (Railway).\n enqueueDispatch(follow as M).catch(() => {});\n }\n }\n }\n\n /**\n * Fire every external listener. Listener throws are isolated — one bad\n * listener does not strand the others. This is the dual of cleanup\n * semantics: the runtime guarantees forward progress for unrelated\n * observers.\n */\n function fireListeners(): void {\n for (const listener of listeners) {\n try {\n listener();\n } catch (err) {\n console.error(err);\n }\n }\n }\n\n /**\n * Fire every observer with the just-applied msg + post-transition state.\n * Same throw-isolation contract as `fireListeners`. Called immediately\n * after `fireListeners` so observers see exactly what subscribers see.\n */\n function fireObservers(msg: M | null): void {\n if (observers.size === 0 || state === undefined) return;\n const snapshot = state;\n for (const observer of observers) {\n try {\n observer(msg, snapshot);\n } catch (err) {\n console.error(err);\n }\n }\n }\n\n /**\n * One full transition: update → save → reconcile subs → interpret → fire\n * listeners. Save-before-effects is the hard ordering; tests pin it.\n *\n * Throws from `update` propagate immediately (state unchanged). Throws from\n * `save` propagate after the in-memory `state` is advanced (PRD row: \"state\n * advanced; persisted state did not\"). Throws from reconcile or interpret\n * propagate after `save` has succeeded (PRD row: \"state already saved\").\n */\n async function stepDispatch(msg: M): Promise<void> {\n if (state === undefined) {\n // This should never happen — boot always runs before any dispatch.\n throw new Error(\"@demlik/tea: runtime not booted\");\n }\n const [next, cmds] = applyUpdate(state, msg);\n state = next;\n if (store) await store.save(state);\n // Subscriptions reconcile against the new state; throws propagate AFTER\n // the entire diff pass completes (so other subs still register / clean\n // up correctly). Cleanup throws are swallowed inside reconcileSubs.\n reconcileSubs();\n await runInterpret(cmds);\n fireListeners();\n fireObservers(msg);\n }\n\n /**\n * Boot is split into two phases.\n *\n * - **Synchronous (`run()` call):** when `store` is absent, we know `loaded\n * = null` without an await — run `init(null, ctx)` IMMEDIATELY so that\n * `getState()` is observable synchronously. This is what\n * `useSyncExternalStore` consumers (e.g. `@demlik/tea/react`) need to render\n * on the first commit without an undefined-state flicker.\n * - **Asynchronous (`stepBootEffects` on the tail):** save + sub reconcile\n * + interpret-of-init-cmds + listener fire. These run as the first tail\n * entry; subsequent dispatches queue behind them.\n *\n * When `store` IS present we cannot do `init` synchronously (we'd be\n * inventing a loaded value), so we keep the full async path. Components\n * that want synchronous initial state in that case should omit the store\n * for the React mount and persist via a different mechanism (or accept the\n * default-snapshot story in a future v2).\n *\n * `store.load` throws propagate via the boot promise; subsequent calls\n * reject with the load error. (The PRD row \"run() throws synchronously\" is\n * imprecise relative to Store#load being async — we honor the intent: no\n * usable runtime is ever observable on load failure.)\n */\n // Synchronous init when there is NO store: `getState()` is observable\n // synchronously by `useSyncExternalStore` consumers. When a store IS\n // present, `init` must run AFTER `store.load()` (the contract: `init`\n // receives the loaded snapshot), and callers must await boot before\n // calling `getState()` — they do so implicitly via the first `dispatch()`\n // (which queues behind the boot step).\n //\n // The asymmetry is the substrate being honest about a real constraint: a\n // store is, by definition, an async boundary. Components that need\n // synchronous initial state under a store should await the runtime's boot\n // before mounting — `await runtime.ready` (not provided in v1; use `await\n // runtime.dispatch(noopMsg)` if needed, or a parent-level loading state).\n let pendingInitCmds: readonly C[] = [];\n if (!store) {\n const [initialState, initCmds] = machine.init(null, ctx);\n state = initialState;\n pendingInitCmds = initCmds;\n }\n\n async function stepBootEffects(): Promise<void> {\n if (store) {\n // Boundary parse (invariant 8). `store.load()` returns `unknown`\n // because storage doesn't know `S`; `store.migrate(raw)` is the\n // substrate's required parse — `S` on recognized shape, `null` on\n // unrecognized (which boots fresh, a known-good path). `migrate` MUST\n // NOT throw per its contract; if it does we surface the error via the\n // boot promise (same as a `load` throw — `runtime.ready` rejects and\n // every subsequent `dispatch` surfaces `bootError`).\n const raw = await store.load();\n const parsed = store.migrate(raw);\n const [initialState, initCmds] = machine.init(parsed, ctx);\n state = initialState;\n pendingInitCmds = initCmds;\n await store.save(state);\n }\n reconcileSubs();\n await runInterpret(pendingInitCmds);\n fireListeners();\n fireObservers(null);\n }\n\n /**\n * Enqueue a dispatch on the tail. Re-entrant calls from interpret or\n * subscribe handlers go through this same gate — guaranteeing serial\n * execution across the entire system.\n *\n * `dispatch` rejects when:\n * - the runtime is stopped (next dispatch always rejects after stop);\n * - boot failed (every dispatch surfaces the boot error);\n * - the reducer, save, sub start, or interpret throws.\n */\n function enqueueDispatch(msg: M): Promise<void> {\n if (stopped) return Promise.reject(new Error(\"@demlik/tea: runtime stopped\"));\n const next = tail.then(() => {\n if (bootError !== null) throw bootError;\n return stepDispatch(msg);\n });\n // Swallow the rejection on the tail so a single failing dispatch does NOT\n // poison every subsequent one. The original `next` promise still rejects\n // for the dispatch caller.\n tail = next.catch(() => {});\n return next;\n }\n\n // Kick off boot-effects immediately. Boot rejections are remembered on\n // `bootError`; they surface on every subsequent dispatch call. Note: when\n // `store` is absent the synchronous-init step above already set `state` —\n // `stepBootEffects` only runs save/sub/interpret/listener-fire. When\n // `store` is present, the full async path runs here.\n //\n // `bootPromise` is the original (un-swallowed) promise — it is what\n // `runtime.ready` exposes so callers see the boot error directly. `tail`\n // gets the swallowed branch so a boot failure does NOT poison every\n // subsequent dispatch's `.then` chain (each dispatch surfaces `bootError`\n // explicitly inside `enqueueDispatch`).\n const bootPromise = stepBootEffects();\n tail = bootPromise.catch((err) => {\n bootError = err;\n });\n\n const runtime: Runtime<S, M> = {\n dispatch: enqueueDispatch,\n getState(): S {\n if (bootError !== null) throw bootError;\n // Synchronous-init path (no store): `state` is set inside `run()`\n // before this getter can ever be called → returns immediately. Resumed\n // path (store present): `state` becomes defined after\n // `stepBootEffects` awaits `store.load()`; calls before that throw.\n // The `booted` flag is no longer a precondition — `state !==\n // undefined` is the single source of truth that init information is\n // available.\n if (state === undefined) {\n throw new Error(\"@demlik/tea: getState() called before runtime booted\");\n }\n return state;\n },\n subscribe(listener: () => void): () => void {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n observe(observer: (msg: M | null, state: S) => void): () => void {\n observers.add(observer);\n return () => {\n observers.delete(observer);\n };\n },\n subscribePort<T>(port: Port<T>, listener: (value: T) => void): () => void {\n const key = port as Port<unknown>;\n let bucket = portRegistry.get(key);\n if (!bucket) {\n bucket = new Set<(value: unknown) => void>();\n portRegistry.set(key, bucket);\n }\n // The bucket stores `(value: unknown) => void` to keep the registry\n // monomorphic; per-port type safety lives at this call site (the\n // listener's `T` is bound to the port's phantom `__t`).\n const erased = listener as (value: unknown) => void;\n bucket.add(erased);\n return () => {\n const set = portRegistry.get(key);\n if (!set) return;\n set.delete(erased);\n if (set.size === 0) portRegistry.delete(key);\n };\n },\n emitPort<T>(port: Port<T>, value: T): void {\n // Same closure as `ctx.emit` inside interpret — synchronous fanout,\n // no-op on no subscribers, listener-throw isolation. Exposing it on\n // the Runtime interface lets `observe`-driven Port emission work\n // without spawning a \"tell the outside world\" Cmd per transition.\n portEmit(port, value);\n },\n // `ready` is the original (un-swallowed) boot promise. Idempotency\n // comes for free — promises settle exactly once; every read returns the\n // same settled value. See the boot-promise note above for why this is\n // distinct from `tail`.\n ready: bootPromise,\n async stop(): Promise<void> {\n stopped = true;\n // Drain whatever is in flight before tearing down. Any rejections in\n // the tail were already swallowed at enqueue time, so this await\n // always resolves.\n await tail;\n // Run every active sub cleanup. Throws are swallowed + logged so one\n // bad cleanup does not strand the others.\n for (const [id, cleanup] of subRegistry) {\n try {\n cleanup();\n } catch (err) {\n console.error(err);\n }\n subRegistry.delete(id);\n }\n // Flush final state. A save throw here is logged but does not reject\n // `stop()` — the contract is \"returns a resolved Promise\".\n if (store && state !== undefined && bootError === null) {\n try {\n await store.save(state);\n } catch (err) {\n console.error(err);\n }\n }\n },\n };\n\n return runtime;\n}\n\n// === historyTracker: composable observability helper ===\n//\n// A bounded ring buffer of recent `(msg, state)` transitions, built on the\n// Runtime's public `observe` API. The substrate itself stays minimal — it\n// has no notion of history, no opt to enable one, no method on the Runtime\n// interface to read one. Anything that wants \"recent transitions\" composes\n// via this helper. The substrate provides the primitive (`observe`); this\n// is the bookkeeping that builds on it.\n//\n// Use cases:\n// - Bridge backlog replay for late subscribers (see `@demlik/tea/extension`).\n// - Debug inspectors showing recent traffic on attach.\n// - Sentry breadcrumb collection.\n// - Property/contract tests that want to assert \"these N transitions\n// happened in this order.\"\n//\n// Discipline:\n// - One-line creation: `const tr = historyTracker(runtime, 100);`\n// - Snapshot at any time: `tr.snapshot()` — shallow copy, oldest first.\n// - Detach when done: `tr.stop()` — unsubscribes the observer; the buffer\n// freezes at its current contents (snapshot() still works, useful for\n// post-hoc inspection in tests).\n//\n// Why not put this on the Runtime interface as `runtime.history()`?\n// Because history is derivable. Putting it on the Runtime privileges one\n// use case (debug inspectors) at the substrate level and grows the\n// interface for everyone. The composition shape stays out of the dispatch\n// loop entirely — the substrate's hot path doesn't pay any cost for a\n// feature it doesn't need to provide.\n// =============================================================================\n\nexport interface HistoryTracker<S, M extends { type: string }> {\n /**\n * Snapshot of recorded transitions, oldest first. Each entry is\n * `{ msg, state }` exactly as the underlying `observe` callback received\n * it — `msg` is `null` for the boot transition, a Msg for every other.\n *\n * Returns a shallow copy: the array is fresh on every call (callers may\n * iterate, slice, or replay without affecting the tracker's buffer).\n * Entry values are references to the originals (TEA states/msgs are\n * conventionally immutable; do not mutate them if your S/M is not).\n */\n snapshot(): readonly { readonly msg: M | null; readonly state: S }[];\n /**\n * Detach the underlying observer. After `stop()`:\n * - No new transitions are recorded.\n * - `snapshot()` continues to work and returns the buffer's contents\n * at the moment of stop (useful for post-hoc inspection in tests).\n * - The tracker holds no references that would prevent GC of the\n * `runtime` argument other than the entries already buffered.\n *\n * Idempotent — subsequent calls are no-ops.\n */\n stop(): void;\n}\n\n/**\n * Create a bounded history tracker over a Runtime. The tracker subscribes\n * to the runtime via `observe(...)` and retains the last `size` `(msg,\n * state)` transitions in a FIFO ring buffer.\n *\n * @param runtime Any `Runtime<S, M>`. The tracker uses only `observe`.\n * @param size Buffer cap. `size <= 0` produces a tracker whose\n * snapshot is always `[]` (the observer is still attached\n * but pushes a no-op; cheaper to skip the tracker entirely\n * in that case).\n *\n * Memory cost: O(size × avg(msg + state size)). For audit-extension's\n * inspector use case (size 100, audit state ~5KB), ~500KB max — held\n * in-memory only, no persistence.\n */\nexport function historyTracker<S, M extends { type: string }>(\n runtime: Runtime<S, M>,\n size: number,\n): HistoryTracker<S, M> {\n const buffer: { msg: M | null; state: S }[] = [];\n let stopped = false;\n\n const unobserve =\n size <= 0\n ? (): void => {}\n : runtime.observe((msg, state) => {\n buffer.push({ msg, state });\n if (buffer.length > size) buffer.shift();\n });\n\n return {\n snapshot() {\n // Shallow copy — callers may freely iterate or mutate the returned\n // array. Entry values are references; see HistoryTracker docs.\n return buffer.slice();\n },\n stop() {\n if (stopped) return;\n stopped = true;\n unobserve();\n },\n };\n}\n\n// === replay: pure unit-test helper ===\n//\n// Composes `init(loaded ?? null, ctx)` then `update(state, msg)` for each msg.\n// Returns the final state plus the cmds that *would* have been emitted and the\n// subs that *would* have been desired at the final state.\n//\n// Crucially:\n// - does NOT call any `interpret[type]` handler\n// - does NOT touch `Store`\n// - does NOT start any subscription via `machine.subscribe?.[type]`\n//\n// `subscriptions` (the description function) IS called to derive the returned\n// `subs` array. That's intentional — it lets tests assert what would be wired\n// up without actually wiring it.\nexport function replay<S, M extends { type: string }, C extends Cmd, U extends Sub, Ctx>(\n machine: Machine<S, M, C, U, Ctx>,\n opts: { msgs: readonly M[]; ctx: Ctx; loaded?: S | null },\n): { state: S; cmds: C[]; subs: U[] } {\n // `init` is `(loaded: S | null, ctx) => ...`; coerce undefined → null so the\n // AC \"`replay` with `loaded: undefined` calls `init(null, ctx)`\" holds.\n const loaded = opts.loaded ?? null;\n const [initialState, initCmds] = machine.init(loaded, opts.ctx);\n\n if (loaded !== null && initCmds.length > 0) {\n throw new Error(\n \"TEA contract violation: machine.init must return [state, []] (no Cmds) \" +\n \"when `loaded` is non-null. Init's rehydrate branch is a pure state \" +\n \"passthrough — the migration/parse boundary, not the boot-effect hook.\\n\\n\" +\n \"Routes for boot effects:\\n\" +\n \" - Stateless infrastructure (e.g. chrome.alarms ensure) → host module \" +\n \"top level, outside TEA.\\n\" +\n \" - State-conditional resume (e.g. re-attach a session) → a `boot` Msg \" +\n \"dispatched once from the host after `run(...)` returns, handled in update.\\n\\n\" +\n \"See .patterns/tea/tea-invariants.md (Invariant 2).\",\n );\n }\n\n let state: S = initialState;\n const cmds: C[] = [...initCmds];\n\n // Mirror the same form-branching the runtime does (see `applyUpdate` in\n // `run`). Detected once; reused per-msg. Keeping it inline (not factored\n // into a shared helper) so `replay` stays standalone — it is the pure\n // unit-test tool and must not depend on `run`'s internal closures.\n type CellFn = (state: S, msg: M) => readonly [S, readonly C[]];\n type ReducerRecord = Reducer<S, M, C>;\n type TransitionsTable = { [stateType: string]: { [msgType: string]: CellFn } };\n const updateForm = machine.update;\n type UpdateMode = \"reducer\" | \"transitions\";\n const updateMode: UpdateMode = (() => {\n const firstKey = Object.keys(updateForm as object)[0];\n if (firstKey === undefined) return \"reducer\";\n const firstValue = (updateForm as Record<string, unknown>)[firstKey];\n return typeof firstValue === \"function\" ? \"reducer\" : \"transitions\";\n })();\n\n for (const msg of opts.msgs) {\n if (__DEV__) deepFreeze(state);\n\n let result: readonly [S, readonly C[]];\n if (updateMode === \"reducer\") {\n result = (updateForm as ReducerRecord)[msg.type as M[\"type\"]](\n state,\n msg as Extract<M, { type: M[\"type\"] }>,\n );\n } else {\n const table = updateForm as unknown as TransitionsTable;\n const stateKey = (state as unknown as { type: string }).type;\n result = table[stateKey]![msg.type]!(state, msg);\n }\n\n if (__DEV__) assertPureResult(result, msg.type);\n\n const [next, emitted] = result;\n state = next;\n cmds.push(...emitted);\n }\n\n const subs: U[] = machine.subscriptions ? [...machine.subscriptions(state)] : [];\n\n return { state, cmds, subs };\n}\n\n// === tryInterpret: Railway sugar over `Result.tryPromise` ===\n//\n// Wraps a fallible `(cmd, ctx) => Promise<Ok>` and returns a handler suitable\n// for `interpret[type]`. On success the returned function resolves with\n// `onOk(value, cmd)`; on rejection it resolves with `onErr(error, cmd)`. It\n// NEVER rejects (assuming `onOk`/`onErr` are total — that's the caller's\n// contract).\n//\n// Implementation note: we use the `{try, catch: (e) => e}` form of\n// `Result.tryPromise` rather than the one-arg `(thunk)` form so the original\n// error passes through untouched. The one-arg form wraps errors in\n// `UnhandledException`, which would prevent callers from `instanceof`-checking\n// their own error types inside `onErr`.\n//\n// M is a Msg type (not a Cmd) — the helper routes Ok/Err to two Msg constructors.\nexport function tryInterpret<C extends Cmd, Ok, M, Ctx>(\n work: (cmd: C, ctx: Ctx) => Promise<Ok>,\n onOk: (value: Ok, cmd: C) => M,\n onErr: (error: unknown, cmd: C) => M,\n): (cmd: C, ctx: Ctx) => Promise<M> {\n return async (cmd, ctx) => {\n const result = await Result.tryPromise({\n try: () => work(cmd, ctx),\n catch: (error: unknown): unknown => error,\n });\n return result.match({\n ok: (value) => onOk(value, cmd),\n err: (error) => onErr(error, cmd),\n });\n };\n}\n"]}