aifsmjs 0.5.3 → 0.5.6

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 (58) hide show
  1. package/README.md +8 -4
  2. package/README_ZHTW.md +7 -5
  3. package/dist/chunk-2MME5V4F.cjs +384 -0
  4. package/dist/chunk-2MME5V4F.cjs.map +1 -0
  5. package/dist/chunk-3B2USJ3H.cjs +18 -0
  6. package/dist/chunk-3B2USJ3H.cjs.map +1 -0
  7. package/dist/chunk-A7U7QQL5.js +52 -0
  8. package/dist/chunk-A7U7QQL5.js.map +1 -0
  9. package/dist/chunk-CDK25FTD.cjs +59 -0
  10. package/dist/chunk-CDK25FTD.cjs.map +1 -0
  11. package/dist/chunk-FHTQ7LSQ.cjs +21 -0
  12. package/dist/chunk-FHTQ7LSQ.cjs.map +1 -0
  13. package/dist/chunk-I354FONA.cjs +153 -0
  14. package/dist/chunk-I354FONA.cjs.map +1 -0
  15. package/dist/chunk-JKZAOPQC.js +16 -0
  16. package/dist/chunk-JKZAOPQC.js.map +1 -0
  17. package/dist/chunk-NEJYZAKR.js +19 -0
  18. package/dist/chunk-NEJYZAKR.js.map +1 -0
  19. package/dist/chunk-PZ5AY32C.js +9 -0
  20. package/dist/chunk-PZ5AY32C.js.map +1 -0
  21. package/dist/chunk-Q7SFCCGT.cjs +11 -0
  22. package/dist/chunk-Q7SFCCGT.cjs.map +1 -0
  23. package/dist/chunk-VZCSHTOI.js +374 -0
  24. package/dist/chunk-VZCSHTOI.js.map +1 -0
  25. package/dist/chunk-ZLQ7HZCE.js +142 -0
  26. package/dist/chunk-ZLQ7HZCE.js.map +1 -0
  27. package/dist/effects/index.cjs +8 -14
  28. package/dist/effects/index.cjs.map +1 -1
  29. package/dist/effects/index.js +5 -14
  30. package/dist/effects/index.js.map +1 -1
  31. package/dist/guards/index.cjs +9 -13
  32. package/dist/guards/index.cjs.map +1 -1
  33. package/dist/guards/index.js +8 -12
  34. package/dist/guards/index.js.map +1 -1
  35. package/dist/index.cjs +101 -591
  36. package/dist/index.cjs.map +1 -1
  37. package/dist/index.js +5 -571
  38. package/dist/index.js.map +1 -1
  39. package/dist/inspect/index.cjs +2 -0
  40. package/dist/inspect/index.cjs.map +1 -1
  41. package/dist/inspect/index.js +2 -0
  42. package/dist/inspect/index.js.map +1 -1
  43. package/dist/pbt/index.cjs +26 -525
  44. package/dist/pbt/index.cjs.map +1 -1
  45. package/dist/pbt/index.d.cts +7 -3
  46. package/dist/pbt/index.d.ts +7 -3
  47. package/dist/pbt/index.js +12 -511
  48. package/dist/pbt/index.js.map +1 -1
  49. package/dist/replay/index.cjs +9 -195
  50. package/dist/replay/index.cjs.map +1 -1
  51. package/dist/replay/index.js +5 -198
  52. package/dist/replay/index.js.map +1 -1
  53. package/dist/timer/index.cjs +30 -9
  54. package/dist/timer/index.cjs.map +1 -1
  55. package/dist/timer/index.js +30 -9
  56. package/dist/timer/index.js.map +1 -1
  57. package/llms-full.txt +165 -8
  58. package/package.json +8 -6
@@ -1,200 +1,7 @@
1
- // src/effects/enqueuer.ts
2
- function createEnqueuer(sink) {
3
- return Object.freeze({
4
- effect(type, payload) {
5
- if (payload === void 0) {
6
- sink.push(Object.freeze({ type }));
7
- } else {
8
- sink.push(Object.freeze({ type, payload }));
9
- }
10
- }
11
- });
12
- }
13
-
14
- // src/fsm/evaluator.ts
15
- var UnknownGuardError = class extends Error {
16
- guardName;
17
- constructor(guardName) {
18
- super(`aifsmjs: guard "${guardName}" not found in implementations.guards`);
19
- this.name = "UnknownGuardError";
20
- this.guardName = guardName;
21
- }
22
- };
23
- var AsyncGuardError = class extends Error {
24
- guardName;
25
- constructor(guardName) {
26
- super(
27
- `aifsmjs: guard "${guardName}" must be sync; received a Promise. Async guards break determinism and replay. Move I/O into an effect.`
28
- );
29
- this.name = "AsyncGuardError";
30
- this.guardName = guardName;
31
- }
32
- };
33
- function isAsyncGuardFn(fn) {
34
- if (typeof fn !== "function") return false;
35
- return fn.constructor?.name === "AsyncFunction";
36
- }
37
- function isThenable(x) {
38
- return x !== null && (typeof x === "object" || typeof x === "function") && typeof x.then === "function";
39
- }
40
- function resolveGuard(ref, impl) {
41
- if (typeof ref === "function") return ref;
42
- const fn = impl.guards?.[ref];
43
- if (!fn) throw new UnknownGuardError(ref);
44
- return fn;
45
- }
46
- function evalGuard(ref, context, event, impl, value) {
47
- const fn = resolveGuard(ref, impl);
48
- const guardName = typeof ref === "string" ? ref : fn.name || "<inline>";
49
- if (isAsyncGuardFn(fn)) {
50
- throw new AsyncGuardError(guardName);
51
- }
52
- const args = { context, event };
53
- const guardsMap = impl.guards;
54
- if (guardsMap) args.guards = guardsMap;
55
- if (value !== void 0) args.value = value;
56
- const result = fn(args);
57
- if (isThenable(result)) {
58
- throw new AsyncGuardError(guardName);
59
- }
60
- return result;
61
- }
62
-
63
- // src/fsm/resolver.ts
64
- function normalizeTransition(entry) {
65
- return typeof entry === "string" ? { target: entry } : entry;
66
- }
67
- function normalizeTransitions(entry) {
68
- if (entry === void 0) return [];
69
- if (Array.isArray(entry)) {
70
- return entry.some((t) => typeof t === "string") ? entry.map((t) => normalizeTransition(t)) : entry;
71
- }
72
- return [normalizeTransition(entry)];
73
- }
74
-
75
- // src/fsm/snapshot.ts
76
- var IS_DEV = typeof process !== "undefined" && typeof process.env !== "undefined" && process.env.NODE_ENV !== "production";
77
- function isPlainObject(value) {
78
- if (value === null || typeof value !== "object") return false;
79
- const proto = Object.getPrototypeOf(value);
80
- return proto === Object.prototype || proto === null;
81
- }
82
- function deepFreeze(value) {
83
- if (value === null || typeof value !== "object") return value;
84
- if (Object.isFrozen(value)) return value;
85
- Object.freeze(value);
86
- if (Array.isArray(value)) {
87
- for (const item of value) deepFreeze(item);
88
- } else if (isPlainObject(value)) {
89
- for (const key of Object.keys(value)) {
90
- deepFreeze(value[key]);
91
- }
92
- }
93
- return value;
94
- }
95
- function freezeSnapshot(snap) {
96
- return IS_DEV ? deepFreeze(snap) : Object.freeze(snap);
97
- }
98
-
99
- // src/fsm/updater.ts
100
- function isPlainRecord(value) {
101
- if (value === null || typeof value !== "object") return false;
102
- const proto = Object.getPrototypeOf(value);
103
- return proto === Object.prototype || proto === null;
104
- }
105
- function mergeContext(current, patch) {
106
- if (patch === void 0 || patch === null) return current;
107
- if (isPlainRecord(current) && isPlainRecord(patch)) {
108
- return { ...current, ...patch };
109
- }
110
- return patch;
111
- }
112
-
113
- // src/fsm/lifecycle.ts
114
- var UnknownActionError = class extends Error {
115
- actionName;
116
- constructor(actionName) {
117
- super(`aifsmjs: action "${actionName}" not found in implementations.actions`);
118
- this.name = "UnknownActionError";
119
- this.actionName = actionName;
120
- }
121
- };
122
- function resolveAction(ref, impl) {
123
- if (typeof ref === "function") return ref;
124
- const fn = impl.actions?.[ref];
125
- if (!fn) throw new UnknownActionError(ref);
126
- return fn;
127
- }
128
- function runActions(refs, ctx, event, impl, effectSink) {
129
- if (!refs || refs.length === 0) return ctx;
130
- const enqueue = createEnqueuer(effectSink);
131
- let current = ctx;
132
- for (const ref of refs) {
133
- const fn = resolveAction(ref, impl);
134
- const patch = fn({ context: current, event, enqueue });
135
- current = mergeContext(current, patch);
136
- }
137
- return current;
138
- }
139
- function pickTransition(candidates, ctx, event, impl, value) {
140
- for (const t of candidates) {
141
- if (!t.guard) return t;
142
- if (evalGuard(t.guard, ctx, event, impl, value)) return t;
143
- }
144
- return void 0;
145
- }
146
- function step(def, snapshot, event, impl) {
147
- if (snapshot.status === "final") {
148
- return Object.freeze({ snapshot, effects: [], changed: false });
149
- }
150
- const state = def.states[snapshot.value];
151
- if (!state) {
152
- return Object.freeze({ snapshot, effects: [], changed: false });
153
- }
154
- const candidateList = normalizeTransitions(state.on?.[event.type]);
155
- const chosen = pickTransition(candidateList, snapshot.context, event, impl, snapshot.value);
156
- if (!chosen) {
157
- return Object.freeze({ snapshot, effects: [], changed: false });
158
- }
159
- const isExternal = chosen.target !== void 0;
160
- const nextStateValue = chosen.target ?? snapshot.value;
161
- const nextState = def.states[nextStateValue];
162
- const effectSink = [];
163
- let ctx = snapshot.context;
164
- if (isExternal) {
165
- ctx = runActions(state.exit, ctx, event, impl, effectSink);
166
- }
167
- ctx = runActions(chosen.actions, ctx, event, impl, effectSink);
168
- if (isExternal && nextState) {
169
- ctx = runActions(nextState.entry, ctx, event, impl, effectSink);
170
- }
171
- const status = nextState?.final === true ? "final" : "active";
172
- const nextSnapshot = freezeSnapshot({
173
- value: nextStateValue,
174
- context: ctx,
175
- status
176
- });
177
- return Object.freeze({
178
- snapshot: nextSnapshot,
179
- effects: Object.freeze(effectSink.slice()),
180
- changed: true
181
- });
182
- }
183
-
184
- // src/replay/index.ts
185
- function replay(initial, events, def, impl) {
186
- let snapshot = initial;
187
- const effects = [];
188
- for (const event of events) {
189
- const r = step(def, snapshot, event, impl);
190
- snapshot = r.snapshot;
191
- if (r.effects.length > 0) {
192
- for (const eff of r.effects) effects.push(eff);
193
- }
194
- }
195
- return Object.freeze({ snapshot, effects: Object.freeze(effects.slice()) });
196
- }
197
-
198
- export { replay };
1
+ export { replay } from '../chunk-NEJYZAKR.js';
2
+ import '../chunk-ZLQ7HZCE.js';
3
+ import '../chunk-JKZAOPQC.js';
4
+ import '../chunk-A7U7QQL5.js';
5
+ import '../chunk-PZ5AY32C.js';
199
6
  //# sourceMappingURL=index.js.map
200
7
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/effects/enqueuer.ts","../../src/fsm/evaluator.ts","../../src/fsm/resolver.ts","../../src/fsm/snapshot.ts","../../src/fsm/updater.ts","../../src/fsm/lifecycle.ts","../../src/replay/index.ts"],"names":[],"mappings":";AAUO,SAAS,eAAe,IAAA,EAAuD;AACpF,EAAA,OAAO,OAAO,MAAA,CAAO;AAAA,IACnB,MAAA,CAAO,MAAc,OAAA,EAAmB;AACtC,MAAA,IAAI,YAAY,MAAA,EAAW;AACzB,QAAA,IAAA,CAAK,KAAK,MAAA,CAAO,MAAA,CAAO,EAAE,IAAA,EAAM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AAO;AAAA,IACnB,QAAA,EAAU,YAAA;AAAA,IACV,OAAA,EAAS,MAAA,CAAO,MAAA,CAAO,UAAA,CAAW,OAAO,CAAA;AAAA,IACzC,OAAA,EAAS;AAAA,GACV,CAAA;AACH;;;AClHO,SAAS,MAAA,CACd,OAAA,EACA,MAAA,EACA,GAAA,EACA,IAAA,EAC2B;AAC3B,EAAA,IAAI,QAAA,GAAW,OAAA;AACf,EAAA,MAAM,UAAoB,EAAC;AAC3B,EAAA,KAAA,MAAW,SAAS,MAAA,EAAQ;AAC1B,IAAA,MAAM,CAAA,GAAI,IAAA,CAAK,GAAA,EAAK,QAAA,EAAU,OAAO,IAAI,CAAA;AACzC,IAAA,QAAA,GAAW,CAAA,CAAE,QAAA;AACb,IAAA,IAAI,CAAA,CAAE,OAAA,CAAQ,MAAA,GAAS,CAAA,EAAG;AACxB,MAAA,KAAA,MAAW,GAAA,IAAO,CAAA,CAAE,OAAA,EAAS,OAAA,CAAQ,KAAK,GAAG,CAAA;AAAA,IAC/C;AAAA,EACF;AACA,EAAA,OAAO,MAAA,CAAO,MAAA,CAAO,EAAE,QAAA,EAAU,OAAA,EAAS,MAAA,CAAO,MAAA,CAAO,OAAA,CAAQ,KAAA,EAAO,CAAA,EAAG,CAAA;AAC5E","file":"index.js","sourcesContent":["import type { Enqueuer } from \"../fsm/types.js\";\n\n/**\n * Build a closure-based Enqueuer that pushes effects into the supplied sink.\n * Each `step()` invocation creates one such enqueuer and discards it\n * afterwards; the sink is the effects array later returned to the caller.\n *\n * Lives in `effects/` because the Enqueuer concept is the effects-domain API\n * — `step()` imports it from here.\n */\nexport function createEnqueuer(sink: { type: string; payload?: unknown }[]): Enqueuer {\n return Object.freeze({\n effect(type: string, payload?: unknown) {\n if (payload === undefined) {\n sink.push(Object.freeze({ type }));\n } else {\n sink.push(Object.freeze({ type, payload }));\n }\n },\n });\n}\n","import type { Guard, GuardRef, Implementations } from \"./types.js\";\n\nexport class UnknownGuardError extends Error {\n readonly guardName: string;\n constructor(guardName: string) {\n super(`aifsmjs: guard \"${guardName}\" not found in implementations.guards`);\n this.name = \"UnknownGuardError\";\n this.guardName = guardName;\n }\n}\n\nexport class AsyncGuardError extends Error {\n readonly guardName: string;\n constructor(guardName: string) {\n super(\n `aifsmjs: guard \"${guardName}\" must be sync; received a Promise. Async guards break determinism and replay. Move I/O into an effect.`,\n );\n this.name = \"AsyncGuardError\";\n this.guardName = guardName;\n }\n}\n\n/**\n * Detect declared-async guards at definition time. Catches the common case of\n * `async (args) => ...` inline guards. Combinator builders or arrow returns of\n * a Promise still slip past — those are caught at `evalGuard` runtime via\n * the `isThenable` check.\n *\n * Caveat: this relies on `Function.prototype.constructor.name === \"AsyncFunction\"`,\n * which is reliable in ES2017+ runtimes. If your bundler transpiles `async`\n * to generator-based code (e.g. ES5 / very old TypeScript targets), this\n * check returns `false` for those forms — the runtime `evalGuard` thenable\n * check still catches them.\n */\nexport function isAsyncGuardFn(fn: unknown): boolean {\n if (typeof fn !== \"function\") return false;\n return fn.constructor?.name === \"AsyncFunction\";\n}\n\n/**\n * Detect a thenable (PromiseLike) — anything with a callable `then`. Used in\n * place of `instanceof Promise` so cross-realm Promises (iframe / worker /\n * vm context) and user-defined thenables are also rejected.\n */\nfunction isThenable(x: unknown): x is PromiseLike<unknown> {\n return (\n x !== null &&\n (typeof x === \"object\" || typeof x === \"function\") &&\n typeof (x as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Resolve a guard ref to a Guard function. String refs are looked up in the\n * implementations map; inline functions are returned as-is.\n */\nexport function resolveGuard<Ctx, Evt>(\n ref: GuardRef<Ctx, Evt>,\n impl: Implementations<Ctx, Evt>,\n): Guard<Ctx, Evt> {\n if (typeof ref === \"function\") return ref;\n const fn = impl.guards?.[ref];\n if (!fn) throw new UnknownGuardError(ref);\n return fn;\n}\n\n/**\n * Evaluate a guard ref against (context, event). Guards must be sync and pure;\n * TypeScript blocks declared-async signatures at compile time, but JS callers\n * or casts can still slip through. This function checks two ways:\n * 1. Inline AsyncFunction (declared `async`) → throw AsyncGuardError.\n * 2. Return value is a Promise → throw AsyncGuardError.\n * Both throws are user errors; they would otherwise silently pass the guard\n * (Promise is truthy) and break determinism.\n *\n * The optional `value` argument is the current state value, threaded so the\n * `stateIn` combinator and similar predicates can introspect it.\n */\nexport function evalGuard<Ctx, Evt>(\n ref: GuardRef<Ctx, Evt>,\n context: Ctx,\n event: Evt,\n impl: Implementations<Ctx, Evt>,\n value?: string,\n): boolean {\n const fn = resolveGuard(ref, impl);\n // Function.prototype.name is \"\" for anonymous arrows — use `||` not `??`\n // so the empty string falls back to \"<inline>\" for readable error messages.\n const guardName = typeof ref === \"string\" ? ref : fn.name || \"<inline>\";\n if (isAsyncGuardFn(fn)) {\n throw new AsyncGuardError(guardName);\n }\n // Build args while honouring exactOptionalPropertyTypes: omit fields that\n // would otherwise be assigned `undefined`.\n type Args = {\n context: Ctx;\n event: Evt;\n guards?: Readonly<Record<string, Guard<Ctx, Evt>>>;\n value?: string;\n };\n const args: Args = { context, event };\n const guardsMap = impl.guards;\n if (guardsMap) args.guards = guardsMap;\n if (value !== undefined) args.value = value;\n const result = fn(args);\n // TS narrows `result` to boolean from Guard's return type, but a JS caller\n // or a cast can slip a Promise / PromiseLike through. We accept anything\n // thenable (native Promise, cross-realm Promise, user-defined thenable),\n // not just same-realm `instanceof Promise`.\n if (isThenable(result)) {\n throw new AsyncGuardError(guardName);\n }\n return result;\n}\n","import type { MachineDef, TransitionConfig, TransitionDef } from \"./types.js\";\n\n/**\n * Normalize a single transition config into its object form. The string\n * shorthand `\"targetState\"` (à la XState) becomes `{ target: \"targetState\" }`;\n * the object form is returned unchanged. Centralised here so every consumer\n * (`step`, `resolveTransitions`, `can`, validation) sees the same shape.\n *\n * @since 0.5.3\n */\nexport function normalizeTransition<Ctx, Evt, States extends string>(\n entry: TransitionConfig<Ctx, Evt, States>,\n): TransitionDef<Ctx, Evt, States> {\n return typeof entry === \"string\" ? ({ target: entry } as TransitionDef<Ctx, Evt, States>) : entry;\n}\n\n/**\n * Normalize the raw `state.on[eventType]` value (object, string shorthand, or\n * an array mixing both) into an ordered list of {@link TransitionDef} objects.\n * Declaration order is preserved.\n *\n * @since 0.5.3\n */\nexport function normalizeTransitions<Ctx, Evt, States extends string>(\n entry:\n | TransitionConfig<Ctx, Evt, States>\n | readonly TransitionConfig<Ctx, Evt, States>[]\n | undefined,\n): readonly TransitionDef<Ctx, Evt, States>[] {\n if (entry === undefined) return [];\n if (Array.isArray(entry)) {\n // Hot path (send/step/can run this per event): when no string shorthand is\n // present, return the original array instead of allocating a normalized copy.\n return entry.some((t) => typeof t === \"string\")\n ? entry.map((t) => normalizeTransition(t))\n : (entry as readonly TransitionDef<Ctx, Evt, States>[]);\n }\n return [normalizeTransition(entry as TransitionConfig<Ctx, Evt, States>)];\n}\n\n/**\n * Return all transition candidates for (state, eventType). Order is preserved\n * from the declaration so that guard fallthrough behaves predictably. String\n * shorthands are normalized to `{ target }` objects.\n *\n * If the event has no entry under the given state, an empty array is returned.\n */\nexport function resolveTransitions<Ctx, Evt extends { type: string }, States extends string>(\n def: MachineDef<Ctx, Evt, States>,\n stateValue: States,\n eventType: string,\n): readonly TransitionDef<Ctx, Evt, States>[] {\n const state = def.states[stateValue];\n if (!state || !state.on) return [];\n return normalizeTransitions(state.on[eventType]);\n}\n","import type { Snapshot } from \"./types.js\";\n\nconst IS_DEV =\n typeof process !== \"undefined\" &&\n typeof process.env !== \"undefined\" &&\n process.env.NODE_ENV !== \"production\";\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\nexport function deepFreeze<T>(value: T): T {\n if (value === null || typeof value !== \"object\") return value;\n if (Object.isFrozen(value)) return value;\n Object.freeze(value);\n if (Array.isArray(value)) {\n for (const item of value) deepFreeze(item);\n } else if (isPlainObject(value)) {\n for (const key of Object.keys(value)) {\n deepFreeze((value as Record<string, unknown>)[key]);\n }\n }\n return value;\n}\n\n/**\n * Wrap a freshly built snapshot. In dev mode the whole tree is deep-frozen so\n * accidental mutation throws immediately. In production only the top object is\n * frozen, keeping the cost negligible.\n */\nexport function freezeSnapshot<C, S extends string>(snap: Snapshot<C, S>): Snapshot<C, S> {\n // IS_DEV is always true in vitest; the production branch (`Object.freeze`)\n // is exercised only when NODE_ENV === \"production\" and is intentionally\n // left out of the coverage threshold.\n return IS_DEV ? deepFreeze(snap) : Object.freeze(snap);\n}\n\nexport function createSnapshot<C, S extends string>(args: {\n value: S;\n context: C;\n status?: \"active\" | \"final\";\n}): Snapshot<C, S> {\n return freezeSnapshot({\n value: args.value,\n context: args.context,\n status: args.status ?? \"active\",\n });\n}\n","import type { Action } from \"./types.js\";\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Build an Action that returns a Partial<Ctx> from a pure updater.\n * The partial is merged into the current context by `step()`.\n */\nexport function assign<Ctx, Evt>(\n updater: (args: { context: Ctx; event: Evt }) => Partial<Ctx>,\n): Action<Ctx, Evt> {\n return ({ context, event }) => updater({ context, event });\n}\n\n/**\n * Merge a partial context update into the current context. Plain-object\n * contexts get a shallow merge; non-object contexts get replaced wholesale.\n *\n * The function never mutates either argument.\n */\nexport function mergeContext<Ctx>(current: Ctx, patch: Partial<Ctx> | void): Ctx {\n if (patch === undefined || patch === null) return current;\n if (isPlainRecord(current) && isPlainRecord(patch)) {\n return { ...current, ...patch } as Ctx;\n }\n return patch as Ctx;\n}\n","import { createEnqueuer } from \"../effects/enqueuer.js\";\nimport { evalGuard } from \"./evaluator.js\";\nimport { normalizeTransitions } from \"./resolver.js\";\nimport { freezeSnapshot } from \"./snapshot.js\";\nimport type {\n Action,\n ActionRef,\n Effect,\n Implementations,\n MachineDef,\n Snapshot,\n StepResult,\n TransitionDef,\n} from \"./types.js\";\nimport { mergeContext } from \"./updater.js\";\n\nexport class UnknownActionError extends Error {\n readonly actionName: string;\n constructor(actionName: string) {\n super(`aifsmjs: action \"${actionName}\" not found in implementations.actions`);\n this.name = \"UnknownActionError\";\n this.actionName = actionName;\n }\n}\n\nfunction resolveAction<Ctx, Evt>(\n ref: ActionRef<Ctx, Evt>,\n impl: Implementations<Ctx, Evt>,\n): Action<Ctx, Evt> {\n if (typeof ref === \"function\") return ref;\n const fn = impl.actions?.[ref];\n if (!fn) throw new UnknownActionError(ref);\n return fn;\n}\n\nfunction runActions<Ctx, Evt>(\n refs: readonly ActionRef<Ctx, Evt>[] | undefined,\n ctx: Ctx,\n event: Evt,\n impl: Implementations<Ctx, Evt>,\n effectSink: Effect[],\n): Ctx {\n if (!refs || refs.length === 0) return ctx;\n const enqueue = createEnqueuer(effectSink as { type: string; payload?: unknown }[]);\n let current = ctx;\n for (const ref of refs) {\n const fn = resolveAction(ref, impl);\n const patch = fn({ context: current, event, enqueue });\n current = mergeContext(current, patch);\n }\n return current;\n}\n\nfunction pickTransition<Ctx, Evt, States extends string>(\n candidates: readonly TransitionDef<Ctx, Evt, States>[],\n ctx: Ctx,\n event: Evt,\n impl: Implementations<Ctx, Evt>,\n value: States,\n): TransitionDef<Ctx, Evt, States> | undefined {\n for (const t of candidates) {\n if (!t.guard) return t;\n if (evalGuard(t.guard, ctx, event, impl, value)) return t;\n }\n return undefined;\n}\n\n/**\n * Compute the next snapshot and collected effects from a single event.\n *\n * Order is fixed and uninterruptible:\n * 1. resolve candidate transitions for (state, event.type)\n * 2. evaluate guards in declaration order; pick the first passing one\n * 3. if external (target defined), run exit actions of the old state\n * 4. run transition.actions in declaration order\n * 5. if external, run entry actions of the new state\n * 6. return { snapshot, effects, changed }\n *\n * The function is pure: it never dispatches effects and never mutates inputs.\n */\nexport function step<Ctx, Evt extends { type: string }, States extends string>(\n def: MachineDef<Ctx, Evt, States>,\n snapshot: Snapshot<Ctx, States>,\n event: Evt,\n impl: Implementations<Ctx, Evt>,\n): StepResult<Ctx, States> {\n // Final state is inert: it never reacts to events.\n if (snapshot.status === \"final\") {\n return Object.freeze({ snapshot, effects: [] as readonly Effect[], changed: false });\n }\n\n const state = def.states[snapshot.value];\n /* v8 ignore next 3 — defensive: snapshot.value is always validated against def.states by defineMachine + initialSnapshot. */\n if (!state) {\n return Object.freeze({ snapshot, effects: [] as readonly Effect[], changed: false });\n }\n\n const candidateList = normalizeTransitions(state.on?.[event.type]);\n\n const chosen = pickTransition(candidateList, snapshot.context, event, impl, snapshot.value);\n if (!chosen) {\n return Object.freeze({ snapshot, effects: [] as readonly Effect[], changed: false });\n }\n\n const isExternal = chosen.target !== undefined;\n const nextStateValue = (chosen.target ?? snapshot.value) as States;\n const nextState = def.states[nextStateValue];\n\n const effectSink: Effect[] = [];\n let ctx = snapshot.context;\n\n if (isExternal) {\n ctx = runActions(state.exit, ctx, event, impl, effectSink);\n }\n ctx = runActions(chosen.actions, ctx, event, impl, effectSink);\n if (isExternal && nextState) {\n ctx = runActions(nextState.entry, ctx, event, impl, effectSink);\n }\n\n const status: \"active\" | \"final\" = nextState?.final === true ? \"final\" : \"active\";\n const nextSnapshot = freezeSnapshot({\n value: nextStateValue,\n context: ctx,\n status,\n });\n\n return Object.freeze({\n snapshot: nextSnapshot,\n effects: Object.freeze(effectSink.slice()) as readonly Effect[],\n changed: true,\n });\n}\n","import { step } from \"../fsm/lifecycle.js\";\nimport type { Effect, Implementations, MachineDef, Snapshot } from \"../fsm/types.js\";\n\nexport type ReplayResult<Ctx, States extends string> = Readonly<{\n snapshot: Snapshot<Ctx, States>;\n effects: readonly Effect[];\n}>;\n\n/**\n * Fold an event log into a final snapshot via `step()`. Effects are collected\n * but never dispatched — this is a pure function, suitable for PBT, time\n * travel, and incident reproduction.\n *\n * Equivalent to:\n * events.reduce((s, e) => step(def, s, e, impl).snapshot, initial)\n * but also accumulates the effects across all events.\n */\nexport function replay<Ctx, Evt extends { type: string }, States extends string>(\n initial: Snapshot<Ctx, States>,\n events: readonly Evt[],\n def: MachineDef<Ctx, Evt, States>,\n impl: Implementations<Ctx, Evt>,\n): ReplayResult<Ctx, States> {\n let snapshot = initial;\n const effects: Effect[] = [];\n for (const event of events) {\n const r = step(def, snapshot, event, impl);\n snapshot = r.snapshot;\n if (r.effects.length > 0) {\n for (const eff of r.effects) effects.push(eff);\n }\n }\n return Object.freeze({ snapshot, effects: Object.freeze(effects.slice()) });\n}\n"]}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ require('../chunk-Q7SFCCGT.cjs');
4
+
3
5
  // src/timer/scheduler.ts
4
6
  var NOOP = Object.freeze({ cancel: () => {
5
7
  } });
@@ -37,20 +39,39 @@ function createScheduler(defaults) {
37
39
  const sched = {
38
40
  after(ms, fn, opts) {
39
41
  const merged = { ...defaults, ...opts };
42
+ const { signal, ...innerOpts } = merged;
43
+ if (signal?.aborted) return NOOP;
40
44
  const slot = {};
41
- const wrapped = () => {
45
+ let fired = false;
46
+ let settled = false;
47
+ const detachAbort = () => {
48
+ if (signal) signal.removeEventListener("abort", onAbort);
49
+ };
50
+ const settle = () => {
51
+ if (settled) return;
52
+ settled = true;
42
53
  if (slot.ref) pending.delete(slot.ref);
54
+ detachAbort();
55
+ };
56
+ const wrapped = () => {
57
+ fired = true;
58
+ settle();
43
59
  fn();
44
60
  };
45
- const inner = after(ms, wrapped, merged);
46
- const handle = Object.freeze({
47
- cancel() {
48
- inner.cancel();
49
- if (slot.ref) pending.delete(slot.ref);
50
- }
51
- });
61
+ const cancel = () => {
62
+ inner.cancel();
63
+ settle();
64
+ };
65
+ function onAbort() {
66
+ cancel();
67
+ }
68
+ const inner = after(ms, wrapped, innerOpts);
69
+ const handle = Object.freeze({ cancel });
52
70
  slot.ref = handle;
53
- pending.add(handle);
71
+ if (!fired) {
72
+ pending.add(handle);
73
+ if (signal) signal.addEventListener("abort", onAbort, { once: true });
74
+ }
54
75
  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AAW,CAAA,IAAK,OAAA,EAAS,CAAA,CAAE,MAAA,EAAO;AAClC,MAAA,OAAA,CAAQ,KAAA,EAAM;AAAA,IAChB,CAAA;AAAA,IACA,IAAI,IAAA,GAAO;AACT,MAAA,OAAO,OAAA,CAAQ,IAAA;AAAA,IACjB;AAAA,GACF;AACA,EAAA,OAAO,KAAA;AACT","file":"index.cjs","sourcesContent":["export type AfterHandle = Readonly<{\n cancel(): void;\n}>;\n\nexport type SetTimeoutFn = (fn: () => void, ms: number) => unknown;\nexport type ClearTimeoutFn = (handle: unknown) => void;\n\nexport type AfterOptions = Readonly<{\n /**\n * If supplied and aborted, the callback never runs and any pending timer is\n * cleared. Aborting after fire is a no-op.\n */\n signal?: AbortSignal;\n /**\n * Override `setTimeout` (testing, SSR, custom loops). Defaults to globalThis.\n */\n setTimeout?: SetTimeoutFn;\n /**\n * Override `clearTimeout`. Must match the `setTimeout` you injected.\n */\n clearTimeout?: ClearTimeoutFn;\n}>;\n\nconst NOOP: AfterHandle = Object.freeze({ cancel: () => {} });\n\nfunction resolveTimers(opts: AfterOptions | undefined): {\n st: SetTimeoutFn;\n ct: ClearTimeoutFn;\n} {\n return {\n st: opts?.setTimeout ?? ((fn, ms) => globalThis.setTimeout(fn, ms)),\n ct: opts?.clearTimeout ?? ((h) => globalThis.clearTimeout(h as number)),\n };\n}\n\n/**\n * Schedule `fn` to run after `ms` milliseconds. Returns a handle whose\n * `cancel()` clears the pending timer. Optional `signal` aborts the timer when\n * triggered. Aborting after the callback fires is a no-op.\n *\n * The abort listener is registered with `{ once: true }` as a baseline, but\n * `{ once: true }` alone does NOT prevent listener accumulation when the same\n * signal is reused across many timers: it only removes the listener when the\n * signal aborts, not when the timer fires normally or `cancel()` is called.\n * We therefore explicitly call `signal.removeEventListener(\"abort\", cancel)`\n * inside the fire callback and at the end of `cancel()` so that a shared,\n * long-lived signal never accumulates dead listeners across timer reuse.\n */\nexport function after(ms: number, fn: () => void, opts?: AfterOptions): AfterHandle {\n if (opts?.signal?.aborted) return NOOP;\n\n const { st, ct } = resolveTimers(opts);\n let fired = false;\n let cancelled = false;\n // `cancel` and the timer handle reference each other. A const cell holds the\n // handle so `cancel` can be defined BEFORE `st(...)` runs (letting a custom\n // `st` that fires its callback synchronously reference `cancel` without\n // hitting the temporal-dead-zone) while still being able to clear the handle\n // assigned afterwards. A synchronous fire sets `fired=true`, so cancel() never\n // reads the still-unset handle in that path.\n const timer: { handle?: ReturnType<typeof st> } = {};\n\n const cancel = () => {\n if (fired || cancelled) return;\n cancelled = true;\n if (timer.handle !== undefined) ct(timer.handle);\n // Detach the abort listener so a reused signal does not accumulate dead\n // closures after this timer is cancelled.\n if (opts?.signal) opts.signal.removeEventListener(\"abort\", cancel);\n };\n\n timer.handle = st(() => {\n fired = true;\n /* v8 ignore next — defensive race guard: cancel() sets cancelled=true and clears the timer, but if a custom setTimeout fires after clear, this short-circuits fn(). */\n if (cancelled) return;\n // Detach the abort listener now that the timer has fired — the listener\n // will never be invoked and must not accumulate on a reused signal.\n if (opts?.signal) opts.signal.removeEventListener(\"abort\", cancel);\n fn();\n }, ms);\n\n // Attach only if the timer has not already fired synchronously (a custom `st`\n // may fire inline); otherwise the listener would be registered AFTER the fire\n // path's removal ran and would then leak until the signal aborts.\n if (opts?.signal && !fired) {\n opts.signal.addEventListener(\"abort\", cancel, { once: true });\n }\n\n return Object.freeze({ cancel });\n}\n\nexport type Scheduler = Readonly<{\n after(ms: number, fn: () => void, opts?: AfterOptions): AfterHandle;\n cancelAll(): void;\n readonly size: number;\n}>;\n\n/**\n * Build a scheduler that tracks every pending `after()` so they can be\n * cancelled together (e.g. on machine destroy). Each `after` returns a handle\n * whose `cancel()` also removes it from the tracking set.\n *\n * `defaults` are merged into every call — typically you inject `setTimeout` /\n * `clearTimeout` once at construction.\n */\nexport function createScheduler(defaults?: AfterOptions): Scheduler {\n const pending = new Set<AfterHandle>();\n\n const sched: Scheduler = {\n after(ms, fn, opts) {\n const merged: AfterOptions = { ...defaults, ...opts };\n // Forward-reference slot so `wrapped` can find the tracked handle\n // before it is constructed below.\n const slot: { ref?: AfterHandle } = {};\n const wrapped = () => {\n if (slot.ref) pending.delete(slot.ref);\n fn();\n };\n const inner = after(ms, wrapped, merged);\n const handle: AfterHandle = Object.freeze({\n cancel() {\n inner.cancel();\n if (slot.ref) pending.delete(slot.ref);\n },\n });\n slot.ref = handle;\n pending.add(handle);\n return handle;\n },\n cancelAll() {\n for (const h of pending) h.cancel();\n pending.clear();\n },\n get size() {\n return pending.size;\n },\n };\n return sched;\n}\n"]}
1
+ {"version":3,"sources":["../../src/timer/scheduler.ts"],"names":[],"mappings":";;;;;AAuBA,IAAM,IAAA,GAAoB,MAAA,CAAO,MAAA,CAAO,EAAE,QAAQ,MAAM;AAAC,CAAA,EAAG,CAAA;AAE5D,SAAS,cAAc,IAAA,EAGrB;AACA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,MAAM,UAAA,KAAe,CAAC,IAAI,EAAA,KAAO,UAAA,CAAW,UAAA,CAAW,EAAA,EAAI,EAAE,CAAA,CAAA;AAAA,IACjE,IAAI,IAAA,EAAM,YAAA,KAAiB,CAAC,CAAA,KAAM,UAAA,CAAW,aAAa,CAAW,CAAA;AAAA,GACvE;AACF;AAeO,SAAS,KAAA,CAAM,EAAA,EAAY,EAAA,EAAgB,IAAA,EAAkC;AAClF,EAAA,IAAI,IAAA,EAAM,MAAA,EAAQ,OAAA,EAAS,OAAO,IAAA;AAElC,EAAA,MAAM,EAAE,EAAA,EAAI,EAAA,EAAG,GAAI,cAAc,IAAI,CAAA;AACrC,EAAA,IAAI,KAAA,GAAQ,KAAA;AACZ,EAAA,IAAI,SAAA,GAAY,KAAA;AAOhB,EAAA,MAAM,QAA4C,EAAC;AAEnD,EAAA,MAAM,SAAS,MAAM;AACnB,IAAA,IAAI,SAAS,SAAA,EAAW;AACxB,IAAA,SAAA,GAAY,IAAA;AACZ,IAAA,IAAI,KAAA,CAAM,MAAA,KAAW,MAAA,EAAW,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= Readonly<{\n cancel(): void;\n}>;\n\nexport type SetTimeoutFn = (fn: () => void, ms: number) => unknown;\nexport type ClearTimeoutFn = (handle: unknown) => void;\n\nexport type AfterOptions = Readonly<{\n /**\n * If supplied and aborted, the callback never runs and any pending timer is\n * cleared. Aborting after fire is a no-op.\n */\n signal?: AbortSignal;\n /**\n * Override `setTimeout` (testing, SSR, custom loops). Defaults to globalThis.\n */\n setTimeout?: SetTimeoutFn;\n /**\n * Override `clearTimeout`. Must match the `setTimeout` you injected.\n */\n clearTimeout?: ClearTimeoutFn;\n}>;\n\nconst NOOP: AfterHandle = Object.freeze({ cancel: () => {} });\n\nfunction resolveTimers(opts: AfterOptions | undefined): {\n st: SetTimeoutFn;\n ct: ClearTimeoutFn;\n} {\n return {\n st: opts?.setTimeout ?? ((fn, ms) => globalThis.setTimeout(fn, ms)),\n ct: opts?.clearTimeout ?? ((h) => globalThis.clearTimeout(h as number)),\n };\n}\n\n/**\n * Schedule `fn` to run after `ms` milliseconds. Returns a handle whose\n * `cancel()` clears the pending timer. Optional `signal` aborts the timer when\n * triggered. Aborting after the callback fires is a no-op.\n *\n * The abort listener is registered with `{ once: true }` as a baseline, but\n * `{ once: true }` alone does NOT prevent listener accumulation when the same\n * signal is reused across many timers: it only removes the listener when the\n * signal aborts, not when the timer fires normally or `cancel()` is called.\n * We therefore explicitly call `signal.removeEventListener(\"abort\", cancel)`\n * inside the fire callback and at the end of `cancel()` so that a shared,\n * long-lived signal never accumulates dead listeners across timer reuse.\n */\nexport function after(ms: number, fn: () => void, opts?: AfterOptions): AfterHandle {\n if (opts?.signal?.aborted) return NOOP;\n\n const { st, ct } = resolveTimers(opts);\n let fired = false;\n let cancelled = false;\n // `cancel` and the timer handle reference each other. A const cell holds the\n // handle so `cancel` can be defined BEFORE `st(...)` runs (letting a custom\n // `st` that fires its callback synchronously reference `cancel` without\n // hitting the temporal-dead-zone) while still being able to clear the handle\n // assigned afterwards. A synchronous fire sets `fired=true`, so cancel() never\n // reads the still-unset handle in that path.\n const timer: { handle?: ReturnType<typeof st> } = {};\n\n const cancel = () => {\n if (fired || cancelled) return;\n cancelled = true;\n if (timer.handle !== undefined) ct(timer.handle);\n // Detach the abort listener so a reused signal does not accumulate dead\n // closures after this timer is cancelled.\n if (opts?.signal) opts.signal.removeEventListener(\"abort\", cancel);\n };\n\n timer.handle = st(() => {\n fired = true;\n /* v8 ignore next — defensive race guard: cancel() sets cancelled=true and clears the timer, but if a custom setTimeout fires after clear, this short-circuits fn(). */\n if (cancelled) return;\n // Detach the abort listener now that the timer has fired — the listener\n // will never be invoked and must not accumulate on a reused signal.\n if (opts?.signal) opts.signal.removeEventListener(\"abort\", cancel);\n fn();\n }, ms);\n\n // Attach only if the timer has not already fired synchronously (a custom `st`\n // may fire inline); otherwise the listener would be registered AFTER the fire\n // path's removal ran and would then leak until the signal aborts.\n if (opts?.signal && !fired) {\n opts.signal.addEventListener(\"abort\", cancel, { once: true });\n }\n\n return Object.freeze({ cancel });\n}\n\nexport type Scheduler = Readonly<{\n after(ms: number, fn: () => void, opts?: AfterOptions): AfterHandle;\n cancelAll(): void;\n readonly size: number;\n}>;\n\n/**\n * Build a scheduler that tracks every pending `after()` so they can be\n * cancelled together (e.g. on machine destroy). Each `after` returns a handle\n * whose `cancel()` also removes it from the tracking set.\n *\n * `defaults` are merged into every call — typically you inject `setTimeout` /\n * `clearTimeout` once at construction.\n */\nexport function createScheduler(defaults?: AfterOptions): Scheduler {\n const pending = new Set<AfterHandle>();\n\n const sched: Scheduler = {\n after(ms, fn, opts) {\n const merged: AfterOptions = { ...defaults, ...opts };\n // Signal handling is lifted to the scheduler layer: we own one abort\n // listener per timer and route it through the scheduler-level cancel so\n // the abort path also removes the handle from `pending`. The inner\n // after() therefore must NOT see the signal — otherwise it would clear\n // its timer on abort without ever touching `pending`, leaking the entry\n // (FSM-R-01, path a).\n const { signal, ...innerOpts } = merged;\n\n // Path b: scheduling on an already-aborted signal must not grow the Set.\n // after() returns NOOP in that case; tracking it would be a permanent\n // dead entry. Return the same NOOP without adding.\n if (signal?.aborted) return NOOP;\n\n // Forward-reference slot so `wrapped`/`cancel` can find the tracked\n // handle before it is constructed below.\n const slot: { ref?: AfterHandle } = {};\n let fired = false;\n let settled = false; // true once removed from pending (fire or cancel)\n\n const detachAbort = () => {\n if (signal) signal.removeEventListener(\"abort\", onAbort);\n };\n\n // Single removal path shared by fire, explicit cancel, and abort.\n const settle = () => {\n if (settled) return;\n settled = true;\n if (slot.ref) pending.delete(slot.ref);\n detachAbort();\n };\n\n const wrapped = () => {\n fired = true;\n settle();\n fn();\n };\n\n // Scheduler-level cancel: cancel the inner timer AND drop from pending\n // AND detach the abort listener. Registered on the abort path too.\n const cancel = () => {\n inner.cancel();\n settle();\n };\n function onAbort() {\n cancel();\n }\n\n const inner = after(ms, wrapped, innerOpts);\n\n const handle: AfterHandle = Object.freeze({ cancel });\n slot.ref = handle;\n\n // Path c (sync-fire): a custom setTimeout may fire `wrapped` inline,\n // during the after() call above — before we reach here. In that case the\n // timer is already done; adding it now would leave a permanent dead\n // entry. Only track timers that are still live.\n if (!fired) {\n pending.add(handle);\n // Attach the abort listener only for a live timer on a real signal.\n // { once: true } removes it on abort; settle()/detachAbort() remove it\n // on fire/cancel so a long-lived shared signal never accumulates dead\n // listeners.\n if (signal) signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n return handle;\n },\n cancelAll() {\n for (const h of pending) h.cancel();\n pending.clear();\n },\n get size() {\n return pending.size;\n },\n };\n return sched;\n}\n"]}
@@ -1,3 +1,5 @@
1
+ import '../chunk-PZ5AY32C.js';
2
+
1
3
  // src/timer/scheduler.ts
2
4
  var NOOP = Object.freeze({ cancel: () => {
3
5
  } });
@@ -35,20 +37,39 @@ function createScheduler(defaults) {
35
37
  const sched = {
36
38
  after(ms, fn, opts) {
37
39
  const merged = { ...defaults, ...opts };
40
+ const { signal, ...innerOpts } = merged;
41
+ if (signal?.aborted) return NOOP;
38
42
  const slot = {};
39
- const wrapped = () => {
43
+ let fired = false;
44
+ let settled = false;
45
+ const detachAbort = () => {
46
+ if (signal) signal.removeEventListener("abort", onAbort);
47
+ };
48
+ const settle = () => {
49
+ if (settled) return;
50
+ settled = true;
40
51
  if (slot.ref) pending.delete(slot.ref);
52
+ detachAbort();
53
+ };
54
+ const wrapped = () => {
55
+ fired = true;
56
+ settle();
41
57
  fn();
42
58
  };
43
- const inner = after(ms, wrapped, merged);
44
- const handle = Object.freeze({
45
- cancel() {
46
- inner.cancel();
47
- if (slot.ref) pending.delete(slot.ref);
48
- }
49
- });
59
+ const cancel = () => {
60
+ inner.cancel();
61
+ settle();
62
+ };
63
+ function onAbort() {
64
+ cancel();
65
+ }
66
+ const inner = after(ms, wrapped, innerOpts);
67
+ const handle = Object.freeze({ cancel });
50
68
  slot.ref = handle;
51
- pending.add(handle);
69
+ if (!fired) {
70
+ pending.add(handle);
71
+ if (signal) signal.addEventListener("abort", onAbort, { once: true });
72
+ }
52
73
  return handle;
53
74
  },
54
75
  cancelAll() {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/timer/scheduler.ts"],"names":[],"mappings":";AAuBA,IAAM,IAAA,GAAoB,MAAA,CAAO,MAAA,CAAO,EAAE,QAAQ,MAAM;AAAC,CAAA,EAAG,CAAA;AAE5D,SAAS,cAAc,IAAA,EAGrB;AACA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,MAAM,UAAA,KAAe,CAAC,IAAI,EAAA,KAAO,UAAA,CAAW,UAAA,CAAW,EAAA,EAAI,EAAE,CAAA,CAAA;AAAA,IACjE,IAAI,IAAA,EAAM,YAAA,KAAiB,CAAC,CAAA,KAAM,UAAA,CAAW,aAAa,CAAW,CAAA;AAAA,GACvE;AACF;AAeO,SAAS,KAAA,CAAM,EAAA,EAAY,EAAA,EAAgB,IAAA,EAAkC;AAClF,EAAA,IAAI,IAAA,EAAM,MAAA,EAAQ,OAAA,EAAS,OAAO,IAAA;AAElC,EAAA,MAAM,EAAE,EAAA,EAAI,EAAA,EAA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ACpB,QAAA,IAAI,IAAA,CAAK,GAAA,EAAK,OAAA,CAAQ,MAAA,CAAO,KAAK,GAAG,CAAA;AACrC,QAAA,EAAA,EAAG;AAAA,MACL,CAAA;AACA,MAAA,MAAM,KAAA,GAAQ,KAAA,CAAM,EAAA,EAAI,OAAA,EAAS,MAAM,CAAA;AACvC,MAAA,MAAM,MAAA,GAAsB,OAAO,MAAA,CAAO;AAAA,QACxC,MAAA,GAAS;AACP,UAAA,KAAA,CAAM,MAAA,EAAO;AACb,UAAA,IAAI,IAAA,CAAK,GAAA,EAAK,OAAA,CAAQ,MAAA,CAAO,KAAK,GAAG,CAAA;AAAA,QACvC;AAAA,OACD,CAAA;AACD,MAAA,IAAA,CAAK,GAAA,GAAM,MAAA;AACX,MAAA,OAAA,CAAQ,IAAI,MAAM,CAAA;AAClB,MAAA,OAAO,MAAA;AAAA,IACT,CAAA;AAAA,IACA,SAAA,GAAY;AACV,MAAA,KAAA,MAAW,CAAA,IAAK,OAAA,EAAS,CAAA,CAAE,MAAA,EAAO;AAClC,MAAA,OAAA,CAAQ,KAAA,EAAM;AAAA,IAChB,CAAA;AAAA,IACA,IAAI,IAAA,GAAO;AACT,MAAA,OAAO,OAAA,CAAQ,IAAA;AAAA,IACjB;AAAA,GACF;AACA,EAAA,OAAO,KAAA;AACT","file":"index.js","sourcesContent":["export type AfterHandle = Readonly<{\n cancel(): void;\n}>;\n\nexport type SetTimeoutFn = (fn: () => void, ms: number) => unknown;\nexport type ClearTimeoutFn = (handle: unknown) => void;\n\nexport type AfterOptions = Readonly<{\n /**\n * If supplied and aborted, the callback never runs and any pending timer is\n * cleared. Aborting after fire is a no-op.\n */\n signal?: AbortSignal;\n /**\n * Override `setTimeout` (testing, SSR, custom loops). Defaults to globalThis.\n */\n setTimeout?: SetTimeoutFn;\n /**\n * Override `clearTimeout`. Must match the `setTimeout` you injected.\n */\n clearTimeout?: ClearTimeoutFn;\n}>;\n\nconst NOOP: AfterHandle = Object.freeze({ cancel: () => {} });\n\nfunction resolveTimers(opts: AfterOptions | undefined): {\n st: SetTimeoutFn;\n ct: ClearTimeoutFn;\n} {\n return {\n st: opts?.setTimeout ?? ((fn, ms) => globalThis.setTimeout(fn, ms)),\n ct: opts?.clearTimeout ?? ((h) => globalThis.clearTimeout(h as number)),\n };\n}\n\n/**\n * Schedule `fn` to run after `ms` milliseconds. Returns a handle whose\n * `cancel()` clears the pending timer. Optional `signal` aborts the timer when\n * triggered. Aborting after the callback fires is a no-op.\n *\n * The abort listener is registered with `{ once: true }` as a baseline, but\n * `{ once: true }` alone does NOT prevent listener accumulation when the same\n * signal is reused across many timers: it only removes the listener when the\n * signal aborts, not when the timer fires normally or `cancel()` is called.\n * We therefore explicitly call `signal.removeEventListener(\"abort\", cancel)`\n * inside the fire callback and at the end of `cancel()` so that a shared,\n * long-lived signal never accumulates dead listeners across timer reuse.\n */\nexport function after(ms: number, fn: () => void, opts?: AfterOptions): AfterHandle {\n if (opts?.signal?.aborted) return NOOP;\n\n const { st, ct } = resolveTimers(opts);\n let fired = false;\n let cancelled = false;\n // `cancel` and the timer handle reference each other. A const cell holds the\n // handle so `cancel` can be defined BEFORE `st(...)` runs (letting a custom\n // `st` that fires its callback synchronously reference `cancel` without\n // hitting the temporal-dead-zone) while still being able to clear the handle\n // assigned afterwards. A synchronous fire sets `fired=true`, so cancel() never\n // reads the still-unset handle in that path.\n const timer: { handle?: ReturnType<typeof st> } = {};\n\n const cancel = () => {\n if (fired || cancelled) return;\n cancelled = true;\n if (timer.handle !== undefined) ct(timer.handle);\n // Detach the abort listener so a reused signal does not accumulate dead\n // closures after this timer is cancelled.\n if (opts?.signal) opts.signal.removeEventListener(\"abort\", cancel);\n };\n\n timer.handle = st(() => {\n fired = true;\n /* v8 ignore next — defensive race guard: cancel() sets cancelled=true and clears the timer, but if a custom setTimeout fires after clear, this short-circuits fn(). */\n if (cancelled) return;\n // Detach the abort listener now that the timer has fired — the listener\n // will never be invoked and must not accumulate on a reused signal.\n if (opts?.signal) opts.signal.removeEventListener(\"abort\", cancel);\n fn();\n }, ms);\n\n // Attach only if the timer has not already fired synchronously (a custom `st`\n // may fire inline); otherwise the listener would be registered AFTER the fire\n // path's removal ran and would then leak until the signal aborts.\n if (opts?.signal && !fired) {\n opts.signal.addEventListener(\"abort\", cancel, { once: true });\n }\n\n return Object.freeze({ cancel });\n}\n\nexport type Scheduler = Readonly<{\n after(ms: number, fn: () => void, opts?: AfterOptions): AfterHandle;\n cancelAll(): void;\n readonly size: number;\n}>;\n\n/**\n * Build a scheduler that tracks every pending `after()` so they can be\n * cancelled together (e.g. on machine destroy). Each `after` returns a handle\n * whose `cancel()` also removes it from the tracking set.\n *\n * `defaults` are merged into every call — typically you inject `setTimeout` /\n * `clearTimeout` once at construction.\n */\nexport function createScheduler(defaults?: AfterOptions): Scheduler {\n const pending = new Set<AfterHandle>();\n\n const sched: Scheduler = {\n after(ms, fn, opts) {\n const merged: AfterOptions = { ...defaults, ...opts };\n // Forward-reference slot so `wrapped` can find the tracked handle\n // before it is constructed below.\n const slot: { ref?: AfterHandle } = {};\n const wrapped = () => {\n if (slot.ref) pending.delete(slot.ref);\n fn();\n };\n const inner = after(ms, wrapped, merged);\n const handle: AfterHandle = Object.freeze({\n cancel() {\n inner.cancel();\n if (slot.ref) pending.delete(slot.ref);\n },\n });\n slot.ref = handle;\n pending.add(handle);\n return handle;\n },\n cancelAll() {\n for (const h of pending) h.cancel();\n pending.clear();\n },\n get size() {\n return pending.size;\n },\n };\n return sched;\n}\n"]}
1
+ {"version":3,"sources":["../../src/timer/scheduler.ts"],"names":[],"mappings":";;;AAuBA,IAAM,IAAA,GAAoB,MAAA,CAAO,MAAA,CAAO,EAAE,QAAQ,MAAM;AAAC,CAAA,EAAG,CAAA;AAE5D,SAAS,cAAc,IAAA,EAGrB;AACA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,MAAM,UAAA,KAAe,CAAC,IAAI,EAAA,KAAO,UAAA,CAAW,UAAA,CAAW,EAAA,EAAI,E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AO,EAAE,QAAQ,CAAA;AACpD,MAAA,IAAA,CAAK,GAAA,GAAM,MAAA;AAMX,MAAA,IAAI,CAAC,KAAA,EAAO;AACV,QAAA,OAAA,CAAQ,IAAI,MAAM,CAAA;AAKlB,QAAA,IAAI,MAAA,SAAe,gBAAA,CAAiB,OAAA,EAAS,SAAS,EAAE,IAAA,EAAM,MAAM,CAAA;AAAA,MACtE;AAEA,MAAA,OAAO,MAAA;AAAA,IACT,CAAA;AAAA,IACA,SAAA,GAAY;AACV,MAAA,KAAA,MAAW,CAAA,IAAK,OAAA,EAAS,CAAA,CAAE,MAAA,EAAO;AAClC,MAAA,OAAA,CAAQ,KAAA,EAAM;AAAA,IAChB,CAAA;AAAA,IACA,IAAI,IAAA,GAAO;AACT,MAAA,OAAO,OAAA,CAAQ,IAAA;AAAA,IACjB;AAAA,GACF;AACA,EAAA,OAAO,KAAA;AACT","file":"index.js","sourcesContent":["export type AfterHandle = Readonly<{\n cancel(): void;\n}>;\n\nexport type SetTimeoutFn = (fn: () => void, ms: number) => unknown;\nexport type ClearTimeoutFn = (handle: unknown) => void;\n\nexport type AfterOptions = Readonly<{\n /**\n * If supplied and aborted, the callback never runs and any pending timer is\n * cleared. Aborting after fire is a no-op.\n */\n signal?: AbortSignal;\n /**\n * Override `setTimeout` (testing, SSR, custom loops). Defaults to globalThis.\n */\n setTimeout?: SetTimeoutFn;\n /**\n * Override `clearTimeout`. Must match the `setTimeout` you injected.\n */\n clearTimeout?: ClearTimeoutFn;\n}>;\n\nconst NOOP: AfterHandle = Object.freeze({ cancel: () => {} });\n\nfunction resolveTimers(opts: AfterOptions | undefined): {\n st: SetTimeoutFn;\n ct: ClearTimeoutFn;\n} {\n return {\n st: opts?.setTimeout ?? ((fn, ms) => globalThis.setTimeout(fn, ms)),\n ct: opts?.clearTimeout ?? ((h) => globalThis.clearTimeout(h as number)),\n };\n}\n\n/**\n * Schedule `fn` to run after `ms` milliseconds. Returns a handle whose\n * `cancel()` clears the pending timer. Optional `signal` aborts the timer when\n * triggered. Aborting after the callback fires is a no-op.\n *\n * The abort listener is registered with `{ once: true }` as a baseline, but\n * `{ once: true }` alone does NOT prevent listener accumulation when the same\n * signal is reused across many timers: it only removes the listener when the\n * signal aborts, not when the timer fires normally or `cancel()` is called.\n * We therefore explicitly call `signal.removeEventListener(\"abort\", cancel)`\n * inside the fire callback and at the end of `cancel()` so that a shared,\n * long-lived signal never accumulates dead listeners across timer reuse.\n */\nexport function after(ms: number, fn: () => void, opts?: AfterOptions): AfterHandle {\n if (opts?.signal?.aborted) return NOOP;\n\n const { st, ct } = resolveTimers(opts);\n let fired = false;\n let cancelled = false;\n // `cancel` and the timer handle reference each other. A const cell holds the\n // handle so `cancel` can be defined BEFORE `st(...)` runs (letting a custom\n // `st` that fires its callback synchronously reference `cancel` without\n // hitting the temporal-dead-zone) while still being able to clear the handle\n // assigned afterwards. A synchronous fire sets `fired=true`, so cancel() never\n // reads the still-unset handle in that path.\n const timer: { handle?: ReturnType<typeof st> } = {};\n\n const cancel = () => {\n if (fired || cancelled) return;\n cancelled = true;\n if (timer.handle !== undefined) ct(timer.handle);\n // Detach the abort listener so a reused signal does not accumulate dead\n // closures after this timer is cancelled.\n if (opts?.signal) opts.signal.removeEventListener(\"abort\", cancel);\n };\n\n timer.handle = st(() => {\n fired = true;\n /* v8 ignore next — defensive race guard: cancel() sets cancelled=true and clears the timer, but if a custom setTimeout fires after clear, this short-circuits fn(). */\n if (cancelled) return;\n // Detach the abort listener now that the timer has fired — the listener\n // will never be invoked and must not accumulate on a reused signal.\n if (opts?.signal) opts.signal.removeEventListener(\"abort\", cancel);\n fn();\n }, ms);\n\n // Attach only if the timer has not already fired synchronously (a custom `st`\n // may fire inline); otherwise the listener would be registered AFTER the fire\n // path's removal ran and would then leak until the signal aborts.\n if (opts?.signal && !fired) {\n opts.signal.addEventListener(\"abort\", cancel, { once: true });\n }\n\n return Object.freeze({ cancel });\n}\n\nexport type Scheduler = Readonly<{\n after(ms: number, fn: () => void, opts?: AfterOptions): AfterHandle;\n cancelAll(): void;\n readonly size: number;\n}>;\n\n/**\n * Build a scheduler that tracks every pending `after()` so they can be\n * cancelled together (e.g. on machine destroy). Each `after` returns a handle\n * whose `cancel()` also removes it from the tracking set.\n *\n * `defaults` are merged into every call — typically you inject `setTimeout` /\n * `clearTimeout` once at construction.\n */\nexport function createScheduler(defaults?: AfterOptions): Scheduler {\n const pending = new Set<AfterHandle>();\n\n const sched: Scheduler = {\n after(ms, fn, opts) {\n const merged: AfterOptions = { ...defaults, ...opts };\n // Signal handling is lifted to the scheduler layer: we own one abort\n // listener per timer and route it through the scheduler-level cancel so\n // the abort path also removes the handle from `pending`. The inner\n // after() therefore must NOT see the signal — otherwise it would clear\n // its timer on abort without ever touching `pending`, leaking the entry\n // (FSM-R-01, path a).\n const { signal, ...innerOpts } = merged;\n\n // Path b: scheduling on an already-aborted signal must not grow the Set.\n // after() returns NOOP in that case; tracking it would be a permanent\n // dead entry. Return the same NOOP without adding.\n if (signal?.aborted) return NOOP;\n\n // Forward-reference slot so `wrapped`/`cancel` can find the tracked\n // handle before it is constructed below.\n const slot: { ref?: AfterHandle } = {};\n let fired = false;\n let settled = false; // true once removed from pending (fire or cancel)\n\n const detachAbort = () => {\n if (signal) signal.removeEventListener(\"abort\", onAbort);\n };\n\n // Single removal path shared by fire, explicit cancel, and abort.\n const settle = () => {\n if (settled) return;\n settled = true;\n if (slot.ref) pending.delete(slot.ref);\n detachAbort();\n };\n\n const wrapped = () => {\n fired = true;\n settle();\n fn();\n };\n\n // Scheduler-level cancel: cancel the inner timer AND drop from pending\n // AND detach the abort listener. Registered on the abort path too.\n const cancel = () => {\n inner.cancel();\n settle();\n };\n function onAbort() {\n cancel();\n }\n\n const inner = after(ms, wrapped, innerOpts);\n\n const handle: AfterHandle = Object.freeze({ cancel });\n slot.ref = handle;\n\n // Path c (sync-fire): a custom setTimeout may fire `wrapped` inline,\n // during the after() call above — before we reach here. In that case the\n // timer is already done; adding it now would leave a permanent dead\n // entry. Only track timers that are still live.\n if (!fired) {\n pending.add(handle);\n // Attach the abort listener only for a live timer on a real signal.\n // { once: true } removes it on abort; settle()/detachAbort() remove it\n // on fire/cancel so a long-lived shared signal never accumulates dead\n // listeners.\n if (signal) signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n return handle;\n },\n cancelAll() {\n for (const h of pending) h.cancel();\n pending.clear();\n },\n get size() {\n return pending.size;\n },\n };\n return sched;\n}\n"]}