aifsmjs 0.5.1 → 0.5.3
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.
- package/README.md +43 -9
- package/README_ZHTW.md +44 -10
- package/dist/effects/index.d.cts +1 -1
- package/dist/effects/index.d.ts +1 -1
- package/dist/guards/index.d.cts +1 -1
- package/dist/guards/index.d.ts +1 -1
- package/dist/index.cjs +29 -21
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +40 -14
- package/dist/index.d.ts +40 -14
- package/dist/index.js +28 -22
- package/dist/index.js.map +1 -1
- package/dist/inspect/index.d.cts +1 -1
- package/dist/inspect/index.d.ts +1 -1
- package/dist/pbt/index.cjs +17 -8
- package/dist/pbt/index.cjs.map +1 -1
- package/dist/pbt/index.d.cts +1 -1
- package/dist/pbt/index.d.ts +1 -1
- package/dist/pbt/index.js +17 -8
- package/dist/pbt/index.js.map +1 -1
- package/dist/replay/index.cjs +13 -2
- package/dist/replay/index.cjs.map +1 -1
- package/dist/replay/index.d.cts +1 -1
- package/dist/replay/index.d.ts +1 -1
- package/dist/replay/index.js +13 -2
- package/dist/replay/index.js.map +1 -1
- package/dist/{types-CGKk6Rur.d.cts → types-DIM7QTtf.d.cts} +32 -2
- package/dist/{types-CGKk6Rur.d.ts → types-DIM7QTtf.d.ts} +32 -2
- package/llms-full.txt +55 -9
- package/package.json +1 -1
package/dist/replay/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/effects/enqueuer.ts","../../src/fsm/evaluator.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,KA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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 { 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 { 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 candidates = state.on?.[event.type];\n const candidateList: readonly TransitionDef<Ctx, Evt, States>[] = candidates\n ? Array.isArray(candidates)\n ? candidates\n : [candidates as TransitionDef<Ctx, Evt, States>]\n : [];\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":["../../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,CAAC,CAAA;AAAA,MACnC,CAAA,MAAO;AACL,QAAA,IAAA,CAAK,KAAK,MAAA,CAAO,MAAA,CAAO,EAAE,IAAA,EAAM,OAAA,EAAS,CAAC,CAAA;AAAA,MAC5C;AAAA,IACF;AAAA,GACD,CAAA;AACH;;;AClBO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EAClC,SAAA;AAAA,EACT,YAAY,SAAA,EAAmB;AAC7B,IAAA,KAAA,CAAM,CAAA,gBAAA,EAAmB,SAAS,CAAA,qCAAA,CAAuC,CAAA;AACzE,IAAA,IAAA,CAAK,IAAA,GAAO,mBAAA;AACZ,IAAA,IAAA,CAAK,SAAA,GAAY,SAAA;AAAA,EACnB;AACF,CAAA;AAEO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EAChC,SAAA;AAAA,EACT,YAAY,SAAA,EAAmB;AAC7B,IAAA,KAAA;AAAA,MACE,mBAAmB,SAAS,CAAA,uGAAA;AAAA,KAC9B;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AACZ,IAAA,IAAA,CAAK,SAAA,GAAY,SAAA;AAAA,EACnB;AACF,CAAA;AAcO,SAAS,eAAe,EAAA,EAAsB;AACnD,EAAA,IAAI,OAAO,EAAA,KAAO,UAAA,EAAY,OAAO,KAA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} 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"]}
|
|
@@ -40,6 +40,15 @@ type TransitionDef<Ctx, Evt, States extends string> = Readonly<{
|
|
|
40
40
|
guard?: GuardRef<Ctx, Evt>;
|
|
41
41
|
actions?: readonly ActionRef<Ctx, Evt>[];
|
|
42
42
|
}>;
|
|
43
|
+
/**
|
|
44
|
+
* A single transition as written in a `StateDef.on` map. Either the full
|
|
45
|
+
* {@link TransitionDef} object form, or the string shorthand `"targetState"`
|
|
46
|
+
* (à la XState) which the resolver normalizes to `{ target: "targetState" }`
|
|
47
|
+
* before processing. The shorthand carries no guard or actions.
|
|
48
|
+
*
|
|
49
|
+
* @since 0.5.3
|
|
50
|
+
*/
|
|
51
|
+
type TransitionConfig<Ctx, Evt, States extends string> = States | TransitionDef<Ctx, Evt, States>;
|
|
43
52
|
/**
|
|
44
53
|
* @experimental v0.3.0
|
|
45
54
|
*
|
|
@@ -56,7 +65,7 @@ type SubMachineDef<SubCtx, SubEvt extends {
|
|
|
56
65
|
type: string;
|
|
57
66
|
}, SubStates extends string> = MachineDef<SubCtx, SubEvt, SubStates>;
|
|
58
67
|
type StateDef<Ctx, Evt, States extends string> = Readonly<{
|
|
59
|
-
on?: Readonly<Record<string,
|
|
68
|
+
on?: Readonly<Record<string, TransitionConfig<Ctx, Evt, States> | readonly TransitionConfig<Ctx, Evt, States>[]>>;
|
|
60
69
|
entry?: readonly ActionRef<Ctx, Evt>[];
|
|
61
70
|
exit?: readonly ActionRef<Ctx, Evt>[];
|
|
62
71
|
final?: boolean;
|
|
@@ -90,6 +99,27 @@ type MachineDef<Ctx, Evt extends {
|
|
|
90
99
|
context: Ctx;
|
|
91
100
|
states: Readonly<Record<States, StateDef<Ctx, Evt, States>>>;
|
|
92
101
|
}>;
|
|
102
|
+
/**
|
|
103
|
+
* Input shape accepted by `defineMachine` / `setup().defineMachine`. Identical
|
|
104
|
+
* to {@link MachineDef} except `context` is **optional** — when omitted it
|
|
105
|
+
* defaults to `{}` (paired with the `Ctx = Record<string, never>` default type
|
|
106
|
+
* parameter). The returned value is always a fully-normalized
|
|
107
|
+
* {@link MachineDef} with `context` present, so downstream consumers are
|
|
108
|
+
* unaffected.
|
|
109
|
+
*
|
|
110
|
+
* @since 0.5.3
|
|
111
|
+
*/
|
|
112
|
+
type MachineConfig<Ctx, Evt extends {
|
|
113
|
+
type: string;
|
|
114
|
+
}, States extends string> = Readonly<{
|
|
115
|
+
id: string;
|
|
116
|
+
initial: States;
|
|
117
|
+
states: Readonly<Record<States, StateDef<Ctx, Evt, States>>>;
|
|
118
|
+
}> & (Record<string, never> extends Ctx ? {
|
|
119
|
+
readonly context?: Ctx;
|
|
120
|
+
} : {
|
|
121
|
+
readonly context: Ctx;
|
|
122
|
+
});
|
|
93
123
|
type Snapshot<Ctx, States extends string> = Readonly<{
|
|
94
124
|
value: States;
|
|
95
125
|
context: Ctx;
|
|
@@ -244,4 +274,4 @@ type RuntimeOptions<Ctx, Evt, States extends string> = Readonly<{
|
|
|
244
274
|
dispatchEffects?: boolean;
|
|
245
275
|
}>;
|
|
246
276
|
|
|
247
|
-
export { type Action as A, type Effect as E, type Guard as G, type Implementations as I, type
|
|
277
|
+
export { type Action as A, type Effect as E, type Guard as G, type Implementations as I, type MachineConfig as M, RESET_EVENT_TYPE as R, type Snapshot as S, type TransitionConfig as T, type ActionRef as a, type EffectHandler as b, type Enqueuer as c, type GuardArgs as d, type GuardRef as e, type MachineDef as f, type Middleware as g, type MiddlewareContext as h, type ResetEvent as i, type Runtime as j, type RuntimeErrorEvent as k, type RuntimeEventMap as l, type RuntimeOptions as m, type RuntimeTransitionEvent as n, type StateDef as o, type StepResult as p, type SubMachineDef as q, type TransitionDef as r };
|
|
@@ -40,6 +40,15 @@ type TransitionDef<Ctx, Evt, States extends string> = Readonly<{
|
|
|
40
40
|
guard?: GuardRef<Ctx, Evt>;
|
|
41
41
|
actions?: readonly ActionRef<Ctx, Evt>[];
|
|
42
42
|
}>;
|
|
43
|
+
/**
|
|
44
|
+
* A single transition as written in a `StateDef.on` map. Either the full
|
|
45
|
+
* {@link TransitionDef} object form, or the string shorthand `"targetState"`
|
|
46
|
+
* (à la XState) which the resolver normalizes to `{ target: "targetState" }`
|
|
47
|
+
* before processing. The shorthand carries no guard or actions.
|
|
48
|
+
*
|
|
49
|
+
* @since 0.5.3
|
|
50
|
+
*/
|
|
51
|
+
type TransitionConfig<Ctx, Evt, States extends string> = States | TransitionDef<Ctx, Evt, States>;
|
|
43
52
|
/**
|
|
44
53
|
* @experimental v0.3.0
|
|
45
54
|
*
|
|
@@ -56,7 +65,7 @@ type SubMachineDef<SubCtx, SubEvt extends {
|
|
|
56
65
|
type: string;
|
|
57
66
|
}, SubStates extends string> = MachineDef<SubCtx, SubEvt, SubStates>;
|
|
58
67
|
type StateDef<Ctx, Evt, States extends string> = Readonly<{
|
|
59
|
-
on?: Readonly<Record<string,
|
|
68
|
+
on?: Readonly<Record<string, TransitionConfig<Ctx, Evt, States> | readonly TransitionConfig<Ctx, Evt, States>[]>>;
|
|
60
69
|
entry?: readonly ActionRef<Ctx, Evt>[];
|
|
61
70
|
exit?: readonly ActionRef<Ctx, Evt>[];
|
|
62
71
|
final?: boolean;
|
|
@@ -90,6 +99,27 @@ type MachineDef<Ctx, Evt extends {
|
|
|
90
99
|
context: Ctx;
|
|
91
100
|
states: Readonly<Record<States, StateDef<Ctx, Evt, States>>>;
|
|
92
101
|
}>;
|
|
102
|
+
/**
|
|
103
|
+
* Input shape accepted by `defineMachine` / `setup().defineMachine`. Identical
|
|
104
|
+
* to {@link MachineDef} except `context` is **optional** — when omitted it
|
|
105
|
+
* defaults to `{}` (paired with the `Ctx = Record<string, never>` default type
|
|
106
|
+
* parameter). The returned value is always a fully-normalized
|
|
107
|
+
* {@link MachineDef} with `context` present, so downstream consumers are
|
|
108
|
+
* unaffected.
|
|
109
|
+
*
|
|
110
|
+
* @since 0.5.3
|
|
111
|
+
*/
|
|
112
|
+
type MachineConfig<Ctx, Evt extends {
|
|
113
|
+
type: string;
|
|
114
|
+
}, States extends string> = Readonly<{
|
|
115
|
+
id: string;
|
|
116
|
+
initial: States;
|
|
117
|
+
states: Readonly<Record<States, StateDef<Ctx, Evt, States>>>;
|
|
118
|
+
}> & (Record<string, never> extends Ctx ? {
|
|
119
|
+
readonly context?: Ctx;
|
|
120
|
+
} : {
|
|
121
|
+
readonly context: Ctx;
|
|
122
|
+
});
|
|
93
123
|
type Snapshot<Ctx, States extends string> = Readonly<{
|
|
94
124
|
value: States;
|
|
95
125
|
context: Ctx;
|
|
@@ -244,4 +274,4 @@ type RuntimeOptions<Ctx, Evt, States extends string> = Readonly<{
|
|
|
244
274
|
dispatchEffects?: boolean;
|
|
245
275
|
}>;
|
|
246
276
|
|
|
247
|
-
export { type Action as A, type Effect as E, type Guard as G, type Implementations as I, type
|
|
277
|
+
export { type Action as A, type Effect as E, type Guard as G, type Implementations as I, type MachineConfig as M, RESET_EVENT_TYPE as R, type Snapshot as S, type TransitionConfig as T, type ActionRef as a, type EffectHandler as b, type Enqueuer as c, type GuardArgs as d, type GuardRef as e, type MachineDef as f, type Middleware as g, type MiddlewareContext as h, type ResetEvent as i, type Runtime as j, type RuntimeErrorEvent as k, type RuntimeEventMap as l, type RuntimeOptions as m, type RuntimeTransitionEvent as n, type StateDef as o, type StepResult as p, type SubMachineDef as q, type TransitionDef as r };
|
package/llms-full.txt
CHANGED
|
@@ -177,13 +177,34 @@ aifsmjs follows the XState v5 two-phase pattern (`setup().createMachine()`): the
|
|
|
177
177
|
|
|
178
178
|
```typescript
|
|
179
179
|
function defineMachine<
|
|
180
|
-
Ctx,
|
|
181
|
-
Evt extends { type: string },
|
|
182
|
-
States extends string,
|
|
183
|
-
>(def:
|
|
180
|
+
Ctx = Record<string, never>,
|
|
181
|
+
Evt extends { type: string } = { type: string },
|
|
182
|
+
States extends string = string,
|
|
183
|
+
>(def: MachineConfig<Ctx, Evt, States>): MachineDef<Ctx, Evt, States>;
|
|
184
184
|
```
|
|
185
185
|
|
|
186
|
-
Pure data builder.
|
|
186
|
+
Pure data builder. Validates that `initial` exists in the `states` map and returns the (normalized) definition.
|
|
187
|
+
|
|
188
|
+
`context` is **optional** — omit it for stateless machines and it defaults to `{}` (the type parameter defaults to `Record<string, never>`). Existing definitions that pass `context` are unaffected.
|
|
189
|
+
|
|
190
|
+
```typescript
|
|
191
|
+
// No context needed — defaults to {}
|
|
192
|
+
const toggle = defineMachine({
|
|
193
|
+
id: "toggle",
|
|
194
|
+
initial: "off",
|
|
195
|
+
states: {
|
|
196
|
+
off: { on: { TOGGLE: "on" } }, // string shorthand, see below
|
|
197
|
+
on: { on: { TOGGLE: "off" } },
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
**String-shorthand transitions.** A transition value may be either the full object form or a bare target-state string (à la XState). The string is normalized to `{ target }` before processing — it carries no guard or actions:
|
|
203
|
+
|
|
204
|
+
```typescript
|
|
205
|
+
on: { NEXT: "green" } // shorthand for { target: "green" }
|
|
206
|
+
on: { NEXT: [{ target: "a", guard: "g" }, "b"] } // mixes with the object form
|
|
207
|
+
```
|
|
187
208
|
|
|
188
209
|
### `createRuntime(def, impl, opts?)`
|
|
189
210
|
|
|
@@ -220,7 +241,7 @@ function step<C, E, S>(
|
|
|
220
241
|
): { snapshot: Snapshot<C, S>; effects: readonly Effect[] };
|
|
221
242
|
```
|
|
222
243
|
|
|
223
|
-
**Pure function**. The invariant keeper for the whole library. It never dispatches effects
|
|
244
|
+
**Pure function**. The invariant keeper for the whole library. It never dispatches effects and never mutates the snapshot. A failing guard or unmapped event simply returns the original snapshot unchanged. It does throw on misuse (`UnknownGuardError`, `UnknownActionError`, `AsyncGuardError`) so guard/action wiring errors surface at development time rather than silently passing.
|
|
224
245
|
|
|
225
246
|
### `assign(updater)`
|
|
226
247
|
|
|
@@ -279,7 +300,7 @@ const runtime = createRuntime(def, impl, {
|
|
|
279
300
|
});
|
|
280
301
|
```
|
|
281
302
|
|
|
282
|
-
Koa-style `(ctx, next) => void` pipeline. `ctx` is `{ prev, next, event, effects }`, all
|
|
303
|
+
Koa-style `(ctx, next) => void` pipeline. `ctx` is `{ prev, next, event, effects, changed }`, all deep-frozen. **Cannot cancel a transition** — `next()` must be called; the return value carries no meaning.
|
|
283
304
|
|
|
284
305
|
### `aifsmjs/replay` — Pure event log replay
|
|
285
306
|
|
|
@@ -298,14 +319,25 @@ Never dispatches effects. For PBT, time-travel debugging, and incident reproduct
|
|
|
298
319
|
|
|
299
320
|
```typescript
|
|
300
321
|
import fc from "fast-check";
|
|
301
|
-
import {
|
|
322
|
+
import { createRuntime } from "aifsmjs";
|
|
323
|
+
import { commandsFromMachine, initialModel, properties } from "aifsmjs/pbt";
|
|
324
|
+
|
|
325
|
+
// Use one of the six built-in generic properties, or assertAll for all at once:
|
|
326
|
+
properties.replayEqualsFold(def, impl, {
|
|
327
|
+
NEXT: fc.constant({ type: "NEXT" as const }),
|
|
328
|
+
});
|
|
302
329
|
|
|
330
|
+
// Or build a custom property using commandsFromMachine:
|
|
303
331
|
fc.assert(
|
|
304
332
|
fc.property(
|
|
305
333
|
commandsFromMachine(def, impl, {
|
|
306
334
|
NEXT: fc.constant({ type: "NEXT" as const }),
|
|
307
335
|
}),
|
|
308
|
-
(cmds) =>
|
|
336
|
+
(cmds) => {
|
|
337
|
+
const real = createRuntime(def, impl, { dispatchEffects: false });
|
|
338
|
+
fc.modelRun(() => ({ model: initialModel(def), real }), cmds);
|
|
339
|
+
return true;
|
|
340
|
+
},
|
|
309
341
|
),
|
|
310
342
|
);
|
|
311
343
|
```
|
|
@@ -419,6 +451,8 @@ aifsmjs ships a few opinionated calls that look different from the typical FSM l
|
|
|
419
451
|
- **Guards and reducers are sync.** A non-deterministic guard would break the PBT determinism property (#1 in the generic suite). Move async predicates into events: send `FETCH_REQUEST`, then later `FETCH_DONE` with the resolved value as payload.
|
|
420
452
|
- **Effects are descriptors, not inline callbacks.** Actions enqueue `{ type, payload }` via `enqueue.effect(...)`; the runtime collects them and the dispatcher invokes user handlers. This keeps machine definitions serializable (JSON round-trippable when no inline functions are used), enables `replay()` to fold an event log into the same snapshot, and lets `inspect/persist` middleware capture effects for audit logs.
|
|
421
453
|
- **Two factory paths coexist.** `setup<Ctx, Evt>().defineMachine(...)` is the type-friendly form (States inferred from `keyof states`). `createMachine(def, impl, opts?)` is the spec-style single-factory shortcut from the ai*js ecosystem review. Plain `defineMachine<Ctx, Evt, States>(def)` remains for explicit generic control. Pick whichever reads best at the call site.
|
|
454
|
+
- **Transitions accept a string shorthand.** `on: { EVENT: "targetState" }` is sugar for `on: { EVENT: { target: "targetState" } }`, normalized in the resolver before any guard/action processing. The shorthand has no guard or actions; reach for the object form when you need them. It composes inside the array form too, so guard-fallthrough lists can mix `{ target, guard }` objects with bare target strings. The full object form is unchanged — this is purely additive.
|
|
455
|
+
- **`context` is optional.** Omit it for stateless machines and it defaults to `{}` (`Ctx` defaults to `Record<string, never>`). Definitions that already pass `context` keep their inferred type and behave identically.
|
|
422
456
|
- **`subscribe(listener)` and `on(type, fn, { signal, once })` both exist.** The typed `on()` matches the platform `EventTarget` semantics (signal + once) and emits `'transition'`, `'error'`, `'dispose'`. The older `subscribe()` keeps the React `useSyncExternalStore` shape — pass it directly. They are not exclusive.
|
|
423
457
|
|
|
424
458
|
---
|
|
@@ -545,6 +579,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
545
579
|
|
|
546
580
|
## [Unreleased]
|
|
547
581
|
|
|
582
|
+
## [0.5.3] - 2026-06-05
|
|
583
|
+
|
|
584
|
+
### Added
|
|
585
|
+
|
|
586
|
+
- **String-shorthand transitions and optional `context` (both additive, non-breaking).** Transitions now accept a bare target string — `on: { EVENT: "target" }` is sugar for `{ target: "target" }`, normalized in the resolver and composable inside guard-fallthrough arrays; and `context` is now optional in `defineMachine` / `setup().defineMachine`, defaulting to `{}` (`Ctx` defaults to `Record<string, never>`). Existing object-form transitions and explicit-`context` definitions are unaffected. (`src/fsm/types.ts`, `src/fsm/resolver.ts`, `src/fsm/definition.ts`, `src/fsm/lifecycle.ts`, `src/fsm/runtime.ts`)
|
|
587
|
+
|
|
588
|
+
## [0.5.2] - 2026-06-05
|
|
589
|
+
|
|
590
|
+
### Docs
|
|
591
|
+
|
|
592
|
+
- Review-driven documentation fixes (`README.md`, `README_ZHTW.md`, `llms-full.txt`): clarity and accuracy from a cross-package code review. No runtime or API change; `dist` byte-identical to 0.5.1.
|
|
593
|
+
|
|
548
594
|
## [0.5.1] - 2026-06-02
|
|
549
595
|
|
|
550
596
|
### Fixed
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aifsmjs",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.3",
|
|
4
4
|
"description": "Small, strict FSM library for deterministic, replayable state machines in any TypeScript/JS app — multi-step forms, checkout funnels, auth flows, tutorials, scene flow. Pure step() lifecycle, opt-in effects, inspect, replay, and a fast-check property-based testing adapter. Browser / Node / Bun / Deno / WebView / Worker friendly.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"fsm",
|