@rxova/journey-core 1.0.0 → 1.0.1
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 +24 -24
- package/dist/connectors/immer/immer.cjs.map +1 -1
- package/dist/connectors/immer/immer.js.map +1 -1
- package/dist/core/helpers.d.cts +0 -6
- package/dist/core/helpers.d.ts +0 -6
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +4 -4
- package/dist/linear/linear.types.d.cts +1 -1
- package/dist/linear/linear.types.d.ts +1 -1
- package/dist/plugins/execution-paths/execution-paths.d.cts +1 -1
- package/dist/plugins/execution-paths/execution-paths.d.ts +1 -1
- package/dist/plugins/index.cjs +1 -1
- package/dist/plugins/index.cjs.map +3 -3
- package/dist/plugins/index.d.cts +6 -6
- package/dist/plugins/index.d.ts +6 -6
- package/dist/plugins/index.js +1 -1
- package/dist/plugins/index.js.map +3 -3
- package/dist/plugins/persistence/persistence.d.cts +1 -1
- package/dist/plugins/persistence/persistence.d.ts +1 -1
- package/package.json +6 -7
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/core/errors.ts", "../src/core/helpers.ts", "../src/core/machine.ts", "
|
|
4
|
-
"sourcesContent": ["/**\n * Machine-readable reasons a journey can refuse to build or operate.\n *\n * Closed on purpose: consumers should be able to `switch` over it exhaustively.\n * Adding a member is a minor change; removing or repurposing one is not done\n * within a major.\n */\nexport type JourneyErrorCode =\n /** A definition declared no steps. */\n | \"empty-definition\"\n /** The same step id was declared twice. */\n | \"duplicate-step-id\"\n /** A step id was referenced that the definition does not declare. */\n | \"unknown-step\"\n /** `initial` names a step the definition does not declare. */\n | \"unknown-initial-step\"\n /** A transition's `from` or `to` names a step that does not exist. */\n | \"dangling-transition\"\n /** Two plugins claimed the same `name`. */\n | \"duplicate-plugin-name\"\n /** Persistence was requested but no usable storage could be resolved. */\n | \"storage-unavailable\"\n /** Navigation work's `commit` returned a promise; it must be synchronous. */\n | \"async-commit\"\n /** A transition or work entry declared `label` as something other than a non-empty string. */\n | \"invalid-label\"\n /** A transition or work entry declared `timeoutMs` as something other than a positive finite number. */\n | \"invalid-timeout\";\n\nexport type JourneyErrorDetails = {\n /** The offending step id, where one caused the failure. */\n readonly stepId?: string;\n /** The offending event name, for transition failures. */\n readonly event?: string;\n /** The offending plugin name, for plugin failures. */\n readonly pluginName?: string;\n};\n\n/**\n * Every error core throws itself.\n *\n * Before this existed, distinguishing \"duplicate plugin name\" from \"unknown step\n * in transition\" meant matching on the message text \u2014 which quietly made every\n * message a compatibility promise. `code` is the stable contract; `message` is\n * for humans and may be reworded in any release.\n *\n * Errors surfaced through `NavigationResult.error` and the `error` subscription\n * event stay `unknown`: those carry whatever the caller's own work threw, which\n * core cannot constrain.\n */\nexport class JourneyError extends Error {\n readonly code: JourneyErrorCode;\n readonly stepId: string | undefined;\n readonly event: string | undefined;\n readonly pluginName: string | undefined;\n\n constructor(\n code: JourneyErrorCode,\n message: string,\n details: JourneyErrorDetails = {},\n cause?: unknown\n ) {\n super(`journey: ${message}`, cause === undefined ? undefined : { cause });\n this.name = \"JourneyError\";\n this.code = code;\n this.stepId = details.stepId;\n this.event = details.event;\n this.pluginName = details.pluginName;\n }\n}\n\n/** Narrowing helper, so consumers need not import the class to test for it. */\nexport const isJourneyError = (value: unknown): value is JourneyError =>\n value instanceof JourneyError;\n", "import type { RuntimeTransition } from \"./runtime.types\";\nimport type { StepAsyncState, TransitionInfo } from \"./types\";\n\n/** Hard cap on events processed from one raise cascade before it is dropped. */\nexport const MAX_RAISED_EVENTS = 25;\n\n/**\n * Key for definition-declared send work. Work belongs to an (origin step,\n * event) pair, not to an event alone \u2014 the same event name can be declared\n * from several steps with different work on each. Length-prefixing the step id\n * keeps the key injective without reserving a separator character.\n */\nexport const eventWorkKey = (from: string, event: string): string =>\n `${from.length}:${from}${event}`;\n\n/**\n * How one edge is named in errors and timeout messages.\n *\n * A declared label wins outright \u2014 that is the point of declaring one. Without\n * it the fallback still has to distinguish candidates that share an event and\n * a target and differ only by guard, so it carries the declaration index:\n * `submit[1] (login -> twofa)`.\n */\nexport const describeTransition = (transition: RuntimeTransition): string =>\n transition.label ??\n `${transition.event}[${transition.index}] (${transition.from} -> ${transition.to})`;\n\n/**\n * The public, generics-free view of an edge handed to step hooks. Built once\n * per navigation and shared by the three hooks it runs \u2014 and left unfrozen,\n * like the hook args it rides on, since it does not outlive them.\n */\nexport const transitionInfo = (transition: RuntimeTransition | null): TransitionInfo | null =>\n transition === null\n ? null\n : {\n event: transition.event,\n from: transition.from,\n to: transition.to,\n label: transition.label ?? null,\n index: transition.index\n };\n\nexport const SUCCESS_ASYNC: StepAsyncState = Object.freeze({\n isLoading: false,\n isSuccess: true,\n isError: false,\n error: null\n});\n\nexport const LOADING_ASYNC: StepAsyncState = Object.freeze({\n isLoading: true,\n isSuccess: false,\n isError: false,\n error: null\n});\n\n/**\n * Own-property membership, for every guard that asks \"is this a declared id?\".\n *\n * `in` walks the prototype chain, so `\"toString\" in steps` is true for any\n * object literal. Using it to validate step ids let `toString`, `constructor`,\n * `__proto__`, `hasOwnProperty` and friends pass as declared steps \u2014 including\n * ids arriving from a persisted record or a route parameter, which are not\n * developer-authored. Own-property checks are the only correct test here.\n */\nexport const hasOwn = (target: object, key: string): boolean => Object.hasOwn(target, key);\n\n/** Subscriber exceptions are isolated so one listener cannot break the pipeline. */\nexport function reportListenerError(error: unknown): void {\n console.error(\"[journey] subscriber threw:\", error);\n}\n\n/**\n * Object.is over own enumerable keys \u2014 for flat snapshot sub-objects. The\n * key check is load-bearing: equal key counts alone would call `{a: undefined}`\n * and `{b: undefined}` equal, since both read `undefined` at every compared key.\n */\nexport const shallowEqual = (\n a: Readonly<Record<string, unknown>>,\n b: Readonly<Record<string, unknown>>\n): boolean => {\n const keys = Object.keys(a);\n if (keys.length !== Object.keys(b).length) return false;\n return keys.every((key) => hasOwn(b, key) && Object.is(a[key], b[key]));\n};\n", "import type { JourneyRuntime } from \"./runtime\";\nimport type { AnyNavigationWork } from \"./runtime.types\";\nimport type {\n ContextUpdater,\n JourneyEventPayloads,\n JourneyMachineBase,\n JourneySubscriptionEvent,\n Unsubscribe\n} from \"./types\";\n\n/**\n * Builds the stable machine surface over a runtime. The object (and every\n * nested group) is created once \u2014 all changing state lives in the snapshot.\n */\nexport function buildMachineSurface(\n runtime: JourneyRuntime\n): JourneyMachineBase<unknown, string> & { plugins: Readonly<Record<string, unknown>> } {\n return {\n getSnapshot: () => runtime.store.getSnapshot(),\n controls: {\n start: () => runtime.start(),\n pause: () => runtime.pause(),\n resume: () => runtime.resume(),\n complete: (payload?: unknown) => runtime.complete(payload),\n terminate: (payload?: unknown) => runtime.terminate(payload),\n restart: () => runtime.restart()\n },\n dispose: () => runtime.dispose(),\n navigate: {\n goToStepById: (id: string) => runtime.goToStepById(id),\n goToPreviousStep: (n?: number) => runtime.goToPreviousStep(n),\n goToNextStep: (work) => runtime.goToNextStep(work as AnyNavigationWork | undefined),\n goToLastVisitedStep: () => runtime.goToLastVisitedStep()\n },\n subscriptions: {\n subscribe: (listener: () => void): Unsubscribe => runtime.store.subscribe(listener),\n subscribeEvent: <TEvent extends JourneySubscriptionEvent>(\n event: TEvent,\n listener: (payload: JourneyEventPayloads<unknown, string>[TEvent]) => void\n ): Unsubscribe => runtime.store.subscribeEvent(event, listener)\n },\n context: {\n update: (updater: ContextUpdater<unknown>) => runtime.updateContext(updater)\n },\n async: {\n clearError: () => runtime.clearAsyncError()\n },\n plugins: runtime.pluginApis\n };\n}\n", "/**\n * Environment detection for diagnostics that must not survive into production.\n *\n * Two resolvers live here and they answer deliberately different questions.\n * They are not interchangeable, and the difference is the point:\n *\n * - {@link isDevelopmentEnvironment} asks *\"should I print a developer\n * warning?\"* and is **permissive** \u2014 an unset `NODE_ENV` counts as\n * development, because an unconfigured environment is someone's machine and\n * the cost of a stray warning there is far lower than the cost of a silently\n * swallowed one.\n * - {@link resolveNonProductionEnvironment} asks *\"should I switch on a feature\n * that has a runtime cost?\"* and is **conservative** \u2014 an unset environment\n * counts as production, because auto-enabling a devtools bridge in an\n * unconfigured deployment leaks internal state to anything listening.\n *\n * Permissive for output, conservative for behaviour. Changing either default to\n * match the other would break one of those two properties.\n */\n\nimport { isRecord } from \"./predicates\";\n\ntype DiagnosticGlobal = typeof globalThis & {\n __DEV__?: unknown;\n process?: {\n env?: {\n NODE_ENV?: string;\n };\n };\n};\n\n/**\n * Reports whether developer-facing diagnostics should be emitted.\n *\n * A boolean `__DEV__` global wins outright \u2014 bundlers inline it, and test\n * suites set it to exercise warning paths that `NODE_ENV=test` would otherwise\n * suppress. Otherwise an unset or `\"development\"` `NODE_ENV` is development,\n * and anything else (including `\"test\"` and `\"production\"`) is not.\n *\n * @returns `true` when warnings and errors should reach the console.\n */\nexport const isDevelopmentEnvironment = (): boolean => {\n const diagnosticGlobal = globalThis as DiagnosticGlobal;\n if (typeof diagnosticGlobal.__DEV__ === \"boolean\") {\n return diagnosticGlobal.__DEV__;\n }\n\n const nodeEnv = diagnosticGlobal.process?.env?.NODE_ENV;\n return nodeEnv === undefined || nodeEnv === \"development\";\n};\n\n/**\n * Logs a warning, but only where {@link isDevelopmentEnvironment} holds.\n *\n * The `detail` argument is forwarded as a second console argument rather than\n * interpolated, so objects stay inspectable in devtools instead of collapsing\n * to `[object Object]`. Omitting it logs the message alone, avoiding a trailing\n * `undefined` in the output.\n *\n * @param message - The warning text.\n * @param detail - Optional structured context to log alongside the message.\n */\nexport const warnInDevelopment = (message: string, detail?: unknown): void => {\n if (!isDevelopmentEnvironment() || typeof console === \"undefined\") {\n return;\n }\n\n if (detail === undefined) {\n console.warn(message);\n return;\n }\n\n // `message` goes through a constant `%s` rather than standing as the format\n // string itself: callers build it by interpolation, so a `%` in an\n // interpolated value would otherwise be read as a directive and consume\n // `detail`.\n console.warn(\"%s\", message, detail);\n};\n\n/**\n * The subset of a bundler's `import.meta.env` this module reads.\n *\n * Callers pass `import.meta.env` in rather than this module reading it,\n * because `import.meta` is a syntax error in a CommonJS build \u2014 keeping it at\n * the call site lets the bundler that understands it do the substitution.\n */\nexport type NonProductionBundlerEnv = {\n /** Vite-style development flag. */\n DEV?: unknown;\n /** Vite-style production flag. Takes precedence over {@link NonProductionBundlerEnv.DEV}. */\n PROD?: unknown;\n};\n\ntype ProcessLike = { env?: { NODE_ENV?: string } };\n\nconst resolveImportMetaEnvironment = (\n bundlerEnv: NonProductionBundlerEnv | null | undefined\n): boolean | null => {\n if (!isRecord(bundlerEnv)) {\n return null;\n }\n if (bundlerEnv.PROD === true) {\n return false;\n }\n if (bundlerEnv.DEV === true) {\n return true;\n }\n return null;\n};\n\nconst resolveNodeEnvironment = (nodeEnv: string | undefined): boolean | null => {\n if (typeof nodeEnv !== \"string\") {\n return null;\n }\n return nodeEnv !== \"production\";\n};\n\nconst readAmbientNodeEnv = (): string | undefined => {\n const processLike = (globalThis as typeof globalThis & { process?: ProcessLike }).process;\n return processLike?.env?.NODE_ENV;\n};\n\n/**\n * Decides whether the current environment is something other than production,\n * for features that should not switch themselves on in a shipped app.\n *\n * Sources are consulted in order \u2014 bundler flags, then `NODE_ENV` \u2014 and the\n * first that gives a definite answer wins. When none does, the answer is\n * `false`: an environment that never said it was safe is treated as production.\n *\n * Passing `nodeEnv` explicitly, *including as `undefined`*, opts out of reading\n * the ambient `process.env.NODE_ENV`. That lets a caller say \"I have looked and\n * there is no value\" and get the conservative answer, rather than having this\n * function reach for a global the caller deliberately ignored.\n *\n * @param options - Environment sources. Omit entirely to read ambient `NODE_ENV`.\n * @param options.bundlerEnv - A bundler's `import.meta.env`, if available.\n * @param options.nodeEnv - An explicit `NODE_ENV`; presence of the key disables the ambient read.\n * @returns `true` only when a source positively indicates a non-production environment.\n */\nexport const resolveNonProductionEnvironment = (\n options: {\n bundlerEnv?: NonProductionBundlerEnv | null | undefined;\n nodeEnv?: string | undefined;\n } = {}\n): boolean => {\n const resolvedNodeEnv = \"nodeEnv\" in options ? options.nodeEnv : readAmbientNodeEnv();\n\n return (\n resolveImportMetaEnvironment(options.bundlerEnv ?? null) ??\n resolveNodeEnvironment(resolvedNodeEnv) ??\n false\n );\n};\n", "import { reportListenerError } from \"./helpers\";\nimport type {\n JourneyEventPayloads,\n JourneySnapshot,\n JourneySubscriptionEvent,\n Unsubscribe\n} from \"./types\";\n\n/**\n * Snapshot holder + subscription hub. Snapshots are immutable and rebuilt by\n * the runtime; the store only distributes them.\n */\nexport class JourneyStore<TContext, TStepId extends string> {\n private snapshot: JourneySnapshot<TContext, TStepId>;\n private readonly listeners = new Set<() => void>();\n private readonly eventListeners = new Map<\n JourneySubscriptionEvent,\n Set<(payload: never) => void>\n >();\n private disposed = false;\n private readonly onListenerError: ((error: unknown) => void) | undefined;\n\n constructor(\n initial: JourneySnapshot<TContext, TStepId>,\n onListenerError?: (error: unknown) => void\n ) {\n this.snapshot = initial;\n this.onListenerError = onListenerError;\n }\n\n /**\n * Isolation stays unconditional; the configured reporter only routes the\n * report. Internal, but reachable from the runtime so plugin-boundary\n * failures land in the same place as subscriber failures.\n */\n report(error: unknown): void {\n if (!this.onListenerError) {\n reportListenerError(error);\n return;\n }\n try {\n this.onListenerError(error);\n } catch (reporterError) {\n reportListenerError(reporterError);\n }\n }\n\n getSnapshot(): JourneySnapshot<TContext, TStepId> {\n return this.snapshot;\n }\n\n /** Replaces the snapshot and notifies every subscriber. */\n publish(next: JourneySnapshot<TContext, TStepId>): void {\n // Structural sharing upstream returns the previous object verbatim when\n // nothing changed \u2014 such publishes are complete no-ops.\n if (Object.is(this.snapshot, next)) return;\n this.snapshot = next;\n for (const listener of [...this.listeners]) {\n try {\n listener();\n } catch (error) {\n this.report(error);\n }\n }\n }\n\n /**\n * Notifies on every committed snapshot. Deriving a slice and skipping\n * unchanged values is the caller's job \u2014 in React that is `useSelector`,\n * which has to own the comparison anyway to keep render identity stable.\n */\n subscribe(listener: () => void): Unsubscribe {\n if (this.disposed) return () => undefined;\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n subscribeEvent<TEvent extends JourneySubscriptionEvent>(\n event: TEvent,\n listener: (payload: JourneyEventPayloads<TContext, TStepId>[TEvent]) => void\n ): Unsubscribe {\n if (this.disposed) return () => undefined;\n let listeners = this.eventListeners.get(event);\n if (!listeners) {\n listeners = new Set();\n this.eventListeners.set(event, listeners);\n }\n listeners.add(listener as (payload: never) => void);\n return () => {\n listeners.delete(listener as (payload: never) => void);\n };\n }\n\n emit<TEvent extends JourneySubscriptionEvent>(\n event: TEvent,\n payload: JourneyEventPayloads<TContext, TStepId>[TEvent]\n ): void {\n const listeners = this.eventListeners.get(event);\n if (!listeners) return;\n for (const listener of [...listeners]) {\n try {\n (listener as (value: unknown) => void)(payload);\n } catch (error) {\n this.report(error);\n }\n }\n }\n\n dispose(): void {\n this.disposed = true;\n this.listeners.clear();\n this.eventListeners.clear();\n }\n}\n", "import { isDevelopmentEnvironment } from \"@rxova/journey-common/dev\";\nimport { JourneyError } from \"./errors\";\nimport {\n describeTransition,\n eventWorkKey,\n hasOwn,\n LOADING_ASYNC,\n MAX_RAISED_EVENTS,\n shallowEqual,\n SUCCESS_ASYNC,\n transitionInfo\n} from \"./helpers\";\nimport { JourneyStore } from \"./store\";\nimport type {\n AnyHookArgs,\n AnyNavigationWork,\n AnyOnEffect,\n AnySendWork,\n AnySendWorkArgs,\n NavigationFailure,\n RuntimeConfig,\n RuntimeTransition,\n TimelineOp,\n TransitionListener,\n WorkDirection\n} from \"./runtime.types\";\nimport type {\n ContextUpdater,\n CurrentStepBase,\n JourneyEventObject,\n GraphTransitionSnapshot,\n JourneyOutcome,\n JourneySnapshot,\n JourneyStatus,\n NavigationResult,\n PluginHost,\n StepAsyncState,\n StepEnterDirection,\n TransitionInfo\n} from \"./types\";\n\n/**\n * Dev-only shallow freeze of the context.\n *\n * Every other snapshot slice is frozen, so an unfrozen context is a surprising\n * gap: mutating it in place changes nothing the machine can observe \u2014 no\n * publish, no re-render, no subscriber \u2014 and the bug is silent. Freezing turns\n * it into a throw where it happens.\n *\n * Shallow, matching how the rest of the snapshot is frozen; deep-freezing would\n * cost a full walk per update and break Maps, Dates, and class instances that\n * legitimately live in a context. Development only, so production pays nothing.\n */\nconst freezeContextInDevelopment = <T>(context: T): T =>\n typeof context === \"object\" && context !== null && isDevelopmentEnvironment()\n ? Object.freeze(context)\n : context;\n\nconst EMPTY_METADATA: Readonly<Record<string, unknown>> = Object.freeze({});\nconst EMPTY_PLUGINS: Readonly<Record<string, unknown>> = Object.freeze({});\n\n/** Freezes and returns the rebuilt sub-object, or the previous one when content-equal. */\nconst shared = <T extends object>(next: T, previous: T | null | undefined): T =>\n previous != null &&\n shallowEqual(next as Record<string, unknown>, previous as Record<string, unknown>)\n ? previous\n : Object.freeze(next);\n\n/** Reuses the previous frozen array when elements are pairwise equal. */\nconst sharedArray = <T>(\n next: readonly T[],\n previous: readonly T[] | undefined,\n equal: (a: T, b: T) => boolean = Object.is\n): readonly T[] =>\n previous !== undefined &&\n previous.length === next.length &&\n next.every((item, index) => equal(item, previous[index] as T))\n ? previous\n : (Object.freeze([...next]) as readonly T[]);\n\nconst getGraphGuardState = (\n guard: RuntimeTransition[\"when\"],\n enabled: boolean\n): GraphTransitionSnapshot<string, string>[\"guard\"] => {\n if (guard === undefined) return \"none\";\n return enabled ? \"passed\" : \"failed\";\n};\n\nexport class JourneyRuntime {\n readonly store: JourneyStore<unknown, string>;\n readonly pluginApis: Record<string, unknown> = {};\n\n private readonly config: RuntimeConfig;\n private status: JourneyStatus = \"idle\";\n private timeline: string[] = [];\n private currentIndex = -1;\n private context: unknown;\n private outcome: JourneyOutcome | null = null;\n private visitCounts = new Map<string, number>();\n private entryAsync: StepAsyncState = SUCCESS_ASYNC;\n private pending: {\n phase: \"working\" | \"leaving\" | \"entering\";\n from: string | null;\n /** Null while a graph send runs its work: the target is not resolved yet. */\n to: string | null;\n } | null = null;\n private disposed = false;\n /** One-shot seed for the first start(); restart() always enters fresh. */\n private restoreSeed: RuntimeConfig[\"restore\"] | null = null;\n /** Bumped by terminate/restart/dispose so stale hook continuations bail out. */\n private generation = 0;\n private raiseQueue: JourneyEventObject[] = [];\n private processingRaised = false;\n private lastPluginExtensions: Readonly<Record<string, unknown>> = {};\n /** The last built snapshot \u2014 the sharing baseline for buildSnapshot(). */\n private lastSnapshot: JourneySnapshot | null = null;\n private readonly frozenStepOrder: readonly string[];\n /**\n * Per-step registration stacks, innermost last. Resolution is last-wins, but\n * a stack (rather than a single slot) is what lets an unregister restore the\n * registration it shadowed \u2014 two owners guarding one step is the normal case\n * for component-scoped wrappers, and dropping to \"ungated\" when the newer one\n * unmounts would fail silently.\n */\n private readonly transitionListeners = new Set<TransitionListener>();\n private readonly disposeCallbacks: (() => void)[] = [];\n private readonly snapshotDerivers = new Map<\n string,\n (snapshot: JourneySnapshot, previous: unknown) => unknown\n >();\n\n constructor(config: RuntimeConfig) {\n this.config = config;\n this.frozenStepOrder = Object.freeze([...config.stepIds]) as readonly string[];\n this.restoreSeed = config.restore ?? null;\n this.context = freezeContextInDevelopment(\n config.restore ? config.restore.context : config.initialContext\n );\n this.store = new JourneyStore(this.buildSnapshot(), config.onListenerError);\n this.setupPlugins();\n this.store.publish(this.buildSnapshot());\n if (config.autoStart) this.start();\n }\n\n // \u2500\u2500 lifecycle \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n start(): boolean {\n if (this.disposed || this.status !== \"idle\") return false;\n this.setStatus(\"running\");\n void this.enterInitialStep();\n return true;\n }\n\n pause(): boolean {\n if (this.disposed || this.status !== \"running\" || this.pending) return false;\n this.setStatus(\"paused\");\n return true;\n }\n\n resume(): boolean {\n if (this.disposed || this.status !== \"paused\") return false;\n this.setStatus(\"running\");\n return true;\n }\n\n complete(payload?: unknown): boolean {\n if (this.disposed || this.status !== \"running\" || this.pending) return false;\n this.outcome = Object.freeze({ type: \"completed\", payload }) as JourneyOutcome;\n this.setStatus(\"completed\");\n return true;\n }\n\n terminate(payload?: unknown): boolean {\n if (this.disposed || this.status === \"terminated\") return false;\n this.generation += 1;\n this.pending = null;\n this.entryAsync = SUCCESS_ASYNC;\n this.raiseQueue = [];\n this.outcome = Object.freeze({ type: \"terminated\", payload }) as JourneyOutcome;\n this.setStatus(\"terminated\");\n return true;\n }\n\n restart(): boolean {\n if (this.disposed || (this.status !== \"completed\" && this.status !== \"terminated\")) {\n return false;\n }\n this.generation += 1;\n this.pending = null;\n this.raiseQueue = [];\n this.timeline = [];\n this.currentIndex = -1;\n this.context = freezeContextInDevelopment(this.config.initialContext);\n this.outcome = null;\n this.visitCounts = new Map();\n this.entryAsync = SUCCESS_ASYNC;\n this.setStatus(\"running\");\n void this.enterInitialStep();\n return true;\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.generation += 1;\n this.pending = null;\n this.raiseQueue = [];\n for (const callback of this.disposeCallbacks.splice(0)) {\n try {\n callback();\n } catch {\n // dispose callbacks must never break teardown\n }\n }\n this.transitionListeners.clear();\n this.store.dispose();\n }\n\n // \u2500\u2500 context \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n updateContext(updater: ContextUpdater<unknown>): void {\n if (this.disposed) return;\n const previous = this.context;\n this.context = freezeContextInDevelopment(updater(previous));\n const snapshot = this.publish();\n this.store.emit(\"contextChange\", { snapshot, previous, current: this.context });\n }\n\n clearAsyncError(): void {\n if (this.disposed || !this.entryAsync.isError) return;\n this.entryAsync = SUCCESS_ASYNC;\n this.publish();\n }\n\n // \u2500\u2500 navigation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n goToStepById(id: string): Promise<NavigationResult> {\n const rejected = this.checkNavigable();\n if (rejected) return this.blocked(rejected, id);\n if (!hasOwn(this.config.steps, id))\n return this.blocked({ ok: false, reason: \"invalid-target\" }, id);\n if (id === this.currentStepId()) return this.blocked({ ok: false, reason: \"no-op\" }, id);\n\n if (this.config.kind === \"graph\") {\n const transition = this.config.transitions.find(\n (candidate) =>\n candidate.from === this.currentStepId() &&\n candidate.to === id &&\n this.isEnabled(candidate)\n );\n if (!transition) return this.blocked({ ok: false, reason: \"invalid-target\" }, id);\n return this.runNavigation(id, { kind: \"append\" }, this.eventFor(transition), transition);\n }\n return this.runNavigation(id, { kind: \"append\" }, null, null);\n }\n\n goToPreviousStep(n = 1): Promise<NavigationResult> {\n const rejected = this.checkNavigable();\n if (rejected) return this.blocked(rejected, null);\n if (this.currentIndex <= 0) return this.blocked({ ok: false, reason: \"out-of-bounds\" }, null);\n const index = Math.max(0, this.currentIndex - Math.max(1, Math.floor(n)));\n const target = this.timeline[index] as string;\n return this.runNavigation(\n target,\n { kind: \"pointer\", index },\n null,\n null,\n undefined,\n \"backward\"\n );\n }\n\n goToNextStep(work?: AnyNavigationWork): Promise<NavigationResult> {\n const rejected = this.checkNavigable();\n if (rejected) return this.blocked(rejected, null);\n if (this.currentIndex < this.timeline.length - 1) {\n const index = this.currentIndex + 1;\n const target = this.timeline[index] as string;\n return this.runNavigation(target, { kind: \"pointer\", index }, null, null, work, \"forward\");\n }\n if (this.config.kind === \"linear\") {\n const orderIndex = this.config.stepIds.indexOf(this.currentStepId() ?? \"\");\n const target = this.config.stepIds[orderIndex + 1];\n if (target === undefined) return this.blocked({ ok: false, reason: \"out-of-bounds\" }, null);\n return this.runNavigation(target, { kind: \"append\" }, null, null, work, \"forward\");\n }\n return this.blocked({ ok: false, reason: \"out-of-bounds\" }, null);\n }\n\n goToLastVisitedStep(): Promise<NavigationResult> {\n const rejected = this.checkNavigable();\n if (rejected) return this.blocked(rejected, null);\n const tip = this.timeline.length - 1;\n if (this.currentIndex >= tip) return this.blocked({ ok: false, reason: \"no-op\" }, null);\n const target = this.timeline[tip] as string;\n return this.runNavigation(target, { kind: \"pointer\", index: tip }, null, null);\n }\n\n /** Linear-only: declared-order index navigation, delegating to `goToStepById`. */\n goToStepByIndex(index: number): Promise<NavigationResult> {\n const target = Number.isInteger(index) ? this.config.stepIds[index] : undefined;\n if (target === undefined) {\n return this.blocked({ ok: false, reason: \"invalid-target\" }, null);\n }\n return this.goToStepById(target);\n }\n\n /** Graph-only primary verb; also drives raised events. */\n send(type: string, payload?: unknown, work?: AnySendWork): Promise<NavigationResult> {\n const rejected = this.checkNavigable();\n if (rejected) return this.blocked(rejected, null);\n const event: JourneyEventObject =\n payload === undefined ? { type } : ({ type, payload } as JourneyEventObject);\n\n const from = this.currentStepId();\n const declaredWork =\n work ?? (from === null ? undefined : this.config.eventWork?.[eventWorkKey(from, type)]);\n if (declaredWork) return this.sendWithWork(type, event, declaredWork);\n\n const transition = this.resolveTransition(type);\n if (!transition) {\n return this.blocked({ ok: false, reason: \"no-enabled-transition\" }, null);\n }\n return this.runNavigation(transition.to, { kind: \"append\" }, event, transition);\n }\n\n /**\n * Work-carrying send: the async runs *before* routing, so its `commit` can\n * stage the very context the guards are then evaluated against. Guards stay\n * sync and pure \u2014 the work supplies facts, the definition still picks the\n * edge.\n *\n * The machine holds its position for the whole `working` phase (`pending.to`\n * is null: there is no target yet). If no candidate is enabled once the\n * context is staged, the staged context is discarded and nothing is\n * published \u2014 either the send routed and committed, or neither happened.\n */\n private async sendWithWork(\n type: string,\n event: JourneyEventObject,\n work: AnySendWork\n ): Promise<NavigationResult> {\n const generation = this.generation;\n const from = this.currentStepId();\n if (from === null) return this.blocked({ ok: false, reason: \"not-running\" }, null);\n\n let stagedContext = this.context;\n let contextWasUpdated = false;\n let result: unknown;\n\n this.pending = { phase: \"working\", from, to: null };\n this.entryAsync = LOADING_ASYNC;\n this.publish();\n\n try {\n const args: AnySendWorkArgs = {\n snapshot: this.store.getSnapshot(),\n from,\n event,\n handlers: this.config.handlers\n };\n result = await this.withTimeout(\n Promise.resolve(work.run(args)),\n `send work(${work.label ?? `${type} from ${from}`})`,\n work.timeoutMs\n );\n if (!this.isCurrent(generation)) return this.staleResult();\n const commitResult = (work.commit as ((value: unknown) => unknown) | undefined)?.({\n ...args,\n result,\n updateContext: (updater: ContextUpdater<unknown>) => {\n stagedContext = updater(stagedContext);\n contextWasUpdated = true;\n }\n });\n if (typeof commitResult === \"object\" && commitResult !== null && \"then\" in commitResult) {\n throw new JourneyError(\"async-commit\", \"send work commit must be synchronous\");\n }\n } catch (error) {\n if (!this.isCurrent(generation)) return this.staleResult();\n this.pending = null;\n this.entryAsync = Object.freeze({\n isLoading: false,\n isSuccess: false,\n isError: true,\n error\n });\n const snapshot = this.publish();\n this.store.emit(\"error\", { snapshot, error, phase: \"work\", stepId: from });\n return this.blocked({ ok: false, reason: \"error\", error }, null);\n }\n\n if (!this.isCurrent(generation)) return this.staleResult();\n\n // Route against the staged context, not the committed one. The run result is\n // passed along too, but guard types expose only context and handlers: a\n // routing fact reaches them through what `commit` staged.\n const transition = this.resolveTransition(type, stagedContext, result);\n if (!transition) {\n // Roll back: the staged context is dropped along with the move.\n this.pending = null;\n this.entryAsync = SUCCESS_ASYNC;\n this.publish();\n return this.blocked({ ok: false, reason: \"no-enabled-transition\" }, null);\n }\n\n return this.commitAndSettle(\n from,\n transition.to,\n { kind: \"append\" },\n event,\n transition,\n generation,\n stagedContext,\n contextWasUpdated,\n \"jump\"\n );\n }\n\n // \u2500\u2500 plugin host \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private setupPlugins(): void {\n const host: PluginHost = {\n getSnapshot: () => this.store.getSnapshot(),\n structure: Object.freeze({\n kind: this.config.kind,\n stepIds: Object.freeze([...this.config.stepIds]) as readonly string[],\n initial: this.config.initial,\n transitions: Object.freeze(\n this.config.transitions.map((transition) =>\n Object.freeze({\n event: transition.event,\n from: transition.from,\n to: transition.to,\n guarded: transition.when !== undefined,\n label: transition.label ?? null,\n index: transition.index\n })\n )\n )\n }),\n onTransition: (callback) => {\n this.transitionListeners.add(callback as TransitionListener);\n return () => this.transitionListeners.delete(callback as TransitionListener);\n },\n onNavigationBlocked: (callback) => this.store.subscribeEvent(\"navigationBlocked\", callback),\n onStatusChange: (callback) => this.store.subscribeEvent(\"statusChange\", callback),\n onContextChange: (callback) => this.store.subscribeEvent(\"contextChange\", callback),\n onError: (callback) => this.store.subscribeEvent(\"error\", callback),\n onDispose: (callback) => {\n this.disposeCallbacks.push(callback);\n },\n reportError: (error) => this.store.report(error)\n };\n // A failure part-way through leaves earlier plugins already subscribed and\n // holding onDispose callbacks \u2014 but the machine is never returned, so\n // dispose() is unreachable and their timers and subscriptions would live\n // for the process lifetime. Tear down before rethrowing, so a rejected\n // construction leaks nothing.\n try {\n for (const plugin of this.config.plugins) {\n if (hasOwn(this.pluginApis, plugin.name)) {\n throw new JourneyError(\n \"duplicate-plugin-name\",\n `duplicate plugin name \"${plugin.name}\"`,\n {\n pluginName: plugin.name\n }\n );\n }\n const contribution = plugin.setup(host);\n this.pluginApis[plugin.name] = contribution.api;\n if (contribution.deriveSnapshot) {\n this.snapshotDerivers.set(\n plugin.name,\n contribution.deriveSnapshot as (snapshot: JourneySnapshot, previous: unknown) => unknown\n );\n }\n }\n } catch (error) {\n this.dispose();\n throw error;\n }\n }\n\n // \u2500\u2500 internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private currentStepId(): string | null {\n return this.currentIndex >= 0 ? (this.timeline[this.currentIndex] as string) : null;\n }\n\n private eventFor(transition: RuntimeTransition): JourneyEventObject {\n return { type: transition.event };\n }\n\n /**\n * `context` is explicit so a work-carrying `send` can evaluate guards against\n * the context its `commit` just staged, rather than the committed one.\n * `result` is the work's run result during that same routing pass; outside a\n * work send (plain sends, snapshot introspection) guards see it as undefined.\n */\n private isEnabled(\n transition: RuntimeTransition,\n context: unknown = this.context,\n result?: unknown\n ): boolean {\n if (!transition.when) return true;\n try {\n return transition.when({ context, handlers: this.config.handlers, result });\n } catch {\n return false;\n }\n }\n\n /** First enabled candidate for `event` from the current step, in declaration order. */\n private resolveTransition(\n event: string,\n context: unknown = this.context,\n result?: unknown\n ): RuntimeTransition | undefined {\n return this.config.transitions.find(\n (candidate) =>\n candidate.event === event &&\n candidate.from === this.currentStepId() &&\n this.isEnabled(candidate, context, result)\n );\n }\n\n private checkNavigable(): NavigationFailure | null {\n if (this.disposed) return { ok: false, reason: \"disposed\" };\n if (this.status !== \"running\") return { ok: false, reason: \"not-running\" };\n if (this.pending) return { ok: false, reason: \"transitioning\" };\n return null;\n }\n\n private setStatus(next: JourneyStatus): void {\n const previous = this.status;\n this.status = next;\n const snapshot = this.publish();\n this.store.emit(\"statusChange\", { snapshot, previous, current: next });\n // Plugin taps may have updated state the snapshot derives from.\n this.refreshPluginSnapshot();\n }\n\n /** Re-derives `snapshot.plugins` after plugin taps ran post-publish. */\n private refreshPluginSnapshot(): void {\n if (this.snapshotDerivers.size > 0) this.publish();\n }\n\n private blocked(failure: NavigationFailure, target: string | null): Promise<NavigationResult> {\n if (failure.reason !== \"disposed\") {\n const payload: {\n snapshot: JourneySnapshot;\n reason: NavigationFailure[\"reason\"];\n from: string | null;\n to: string | null;\n error?: unknown;\n } = {\n snapshot: this.store.getSnapshot(),\n reason: failure.reason,\n from: this.currentStepId(),\n to: target\n };\n if (\"error\" in failure) payload.error = failure.error;\n this.store.emit(\"navigationBlocked\", payload);\n }\n return Promise.resolve({ ...failure, from: this.currentStepId(), to: target });\n }\n\n private hookArgs(\n from: string | null,\n to: string,\n event: JourneyEventObject | null,\n transition: TransitionInfo | null\n ): AnyHookArgs {\n return {\n snapshot: this.store.getSnapshot(),\n from,\n to,\n event,\n transition,\n updateContext: (updater) => this.updateContext(updater),\n raise: (raised) => {\n if (this.config.kind !== \"graph\" || this.disposed) return;\n this.raiseQueue.push(raised);\n }\n };\n }\n\n private async invokeEffect(\n effect: AnyOnEffect | undefined,\n args: AnyHookArgs,\n label: string,\n timeoutMs?: number\n ): Promise<{ error: unknown } | null> {\n if (!effect) return null;\n try {\n await this.withTimeout(Promise.resolve(effect(args)), label, timeoutMs);\n return null;\n } catch (error) {\n return { error };\n }\n }\n\n /**\n * `overrideMs` is the declaring edge's own budget. It wins over\n * `defaultTimeoutMs` so that one slow third-party call does not force every\n * other edge onto the slow one's budget; `undefined` falls back to the\n * global, and a global of `undefined` means no bound at all.\n */\n private withTimeout<T>(promise: Promise<T>, label: string, overrideMs?: number): Promise<T> {\n const ms = overrideMs ?? this.config.defaultTimeoutMs;\n if (ms === undefined) return promise;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new Error(`journey: ${label} timed out after ${ms}ms`)),\n ms\n );\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (error) => {\n clearTimeout(timer);\n reject(error);\n }\n );\n });\n }\n\n /** Entry on start()/restart(): no onLeave, `from` is null, event is null. */\n private async enterInitialStep(): Promise<void> {\n const generation = this.generation;\n const seed = this.restoreSeed;\n this.restoreSeed = null;\n if (seed) {\n const to = seed.timeline[seed.currentIndex] as string;\n this.pending = { phase: \"entering\", from: null, to };\n this.timeline = [...seed.timeline];\n this.currentIndex = seed.currentIndex;\n // Persisted records carry no visit counts; occurrences in the restored\n // timeline are the best-effort reconstruction. commitEntry adds one more\n // for the re-entered current step, so it reports isFirstTimeVisit: false.\n for (const id of seed.timeline) {\n this.visitCounts.set(id, (this.visitCounts.get(id) ?? 0) + 1);\n }\n this.commitEntry(null, to, \"jump\");\n await this.runEntryEffects(null, to, null, null, generation);\n return;\n }\n const to = this.config.startAt ?? this.config.initial;\n this.pending = { phase: \"entering\", from: null, to };\n this.timeline = [to];\n this.currentIndex = 0;\n this.commitEntry(null, to, \"jump\");\n await this.runEntryEffects(null, to, null, null, generation);\n }\n\n private async runNavigation(\n to: string,\n op: TimelineOp,\n event: JourneyEventObject | null,\n transition: RuntimeTransition | null,\n work?: AnyNavigationWork,\n direction?: WorkDirection\n ): Promise<NavigationResult> {\n const generation = this.generation;\n const from = this.currentStepId();\n let stagedContext = this.context;\n let contextWasUpdated = false;\n\n if (work && from !== null && direction) {\n this.pending = { phase: \"working\", from, to };\n this.entryAsync = LOADING_ASYNC;\n this.publish();\n\n try {\n const args = {\n snapshot: this.store.getSnapshot(),\n from,\n to,\n direction\n };\n const result = await this.withTimeout(\n Promise.resolve(work.run(args)),\n `${direction} navigation work(${from} -> ${to})`,\n work.timeoutMs\n );\n if (!this.isCurrent(generation)) return this.staleResult();\n const commitResult = (work.commit as ((value: unknown) => unknown) | undefined)?.({\n ...args,\n result,\n updateContext: (updater: ContextUpdater<unknown>) => {\n stagedContext = updater(stagedContext);\n contextWasUpdated = true;\n }\n });\n if (typeof commitResult === \"object\" && commitResult !== null && \"then\" in commitResult) {\n throw new JourneyError(\"async-commit\", \"navigation work commit must be synchronous\");\n }\n } catch (error) {\n if (!this.isCurrent(generation)) return this.staleResult();\n this.pending = null;\n this.entryAsync = Object.freeze({\n isLoading: false,\n isSuccess: false,\n isError: true,\n error\n });\n const snapshot = this.publish();\n this.store.emit(\"error\", { snapshot, error, phase: \"work\", stepId: from });\n return this.blocked({ ok: false, reason: \"error\", error }, to);\n }\n }\n if (!this.isCurrent(generation)) return this.staleResult();\n\n return this.commitAndSettle(\n from,\n to,\n op,\n event,\n transition,\n generation,\n stagedContext,\n contextWasUpdated,\n direction ?? \"jump\"\n );\n }\n\n /**\n * Publishes the position change and any staged context in one snapshot, then\n * awaits the post-commit effects. Shared by plain navigation and by a\n * work-carrying `send`, which reaches here only once its target is resolved.\n */\n private async commitAndSettle(\n from: string | null,\n to: string,\n op: TimelineOp,\n event: JourneyEventObject | null,\n transition: RuntimeTransition | null,\n generation: number,\n stagedContext: unknown,\n contextWasUpdated: boolean,\n direction: StepEnterDirection\n ): Promise<NavigationResult> {\n const previousContext = this.context;\n if (op.kind === \"pointer\") {\n this.currentIndex = op.index;\n } else {\n this.timeline = [...this.timeline.slice(0, this.currentIndex + 1), to];\n this.currentIndex = this.timeline.length - 1;\n }\n if (contextWasUpdated) this.context = freezeContextInDevelopment(stagedContext);\n const fromStep = from === null ? undefined : this.config.steps[from];\n this.pending = { phase: fromStep?.onLeave ? \"leaving\" : \"entering\", from, to };\n this.commitEntry(\n from,\n to,\n direction,\n contextWasUpdated ? { previous: previousContext, current: stagedContext } : undefined,\n fromStep?.onLeave !== undefined || transition?.onTransition !== undefined\n );\n\n await this.runEntryEffects(from, to, event, transition, generation);\n return { ok: true, from, to };\n }\n\n /** Shared commit bookkeeping for navigations and the initial entry. */\n private commitEntry(\n from: string | null,\n to: string,\n direction: StepEnterDirection,\n contextChange?: { previous: unknown; current: unknown },\n hasPreEnterEffect = false\n ): void {\n this.visitCounts.set(to, (this.visitCounts.get(to) ?? 0) + 1);\n const toStep = this.config.steps[to];\n this.entryAsync = hasPreEnterEffect || toStep?.onEnter ? LOADING_ASYNC : SUCCESS_ASYNC;\n const snapshot = this.publish();\n if (contextChange) this.store.emit(\"contextChange\", { snapshot, ...contextChange });\n if (from !== null) this.store.emit(\"stepLeave\", { snapshot, from, to });\n this.store.emit(\"stepEnter\", { snapshot, from, to, direction });\n }\n\n /** Post-commit effects: step `onLeave`, transition effect, then step `onEnter`. */\n private async runEntryEffects(\n from: string | null,\n to: string,\n event: JourneyEventObject | null,\n transition: RuntimeTransition | null,\n generation: number\n ): Promise<void> {\n const fromStep = from === null ? undefined : this.config.steps[from];\n const toStep = this.config.steps[to];\n const edge = transitionInfo(transition);\n const failures: { error: unknown; phase: \"leave\" | \"enter\" | \"transition\"; stepId: string }[] =\n [];\n\n const leaveFailure = await this.invokeEffect(\n fromStep?.onLeave,\n this.hookArgs(from, to, event, edge),\n `onLeave(${from ?? \"\"})`\n );\n if (!this.isCurrent(generation)) return;\n if (leaveFailure && from !== null) {\n failures.push({ error: leaveFailure.error, phase: \"leave\", stepId: from });\n }\n\n this.pending = { phase: \"entering\", from, to };\n this.publish();\n\n const transitionFailure = await this.invokeEffect(\n transition?.onTransition,\n this.hookArgs(from, to, event, edge),\n `onTransition(${transition ? describeTransition(transition) : (event?.type ?? \"\")})`,\n transition?.timeoutMs\n );\n if (!this.isCurrent(generation)) return;\n if (transitionFailure) {\n failures.push({ error: transitionFailure.error, phase: \"transition\", stepId: to });\n }\n\n const enterFailure = await this.invokeEffect(\n toStep?.onEnter,\n this.hookArgs(from, to, event, edge),\n `onEnter(${to})`\n );\n if (!this.isCurrent(generation)) return;\n if (enterFailure) failures.push({ error: enterFailure.error, phase: \"enter\", stepId: to });\n\n this.entryAsync = failures[0]\n ? Object.freeze({\n isLoading: false,\n isSuccess: false,\n isError: true,\n error: failures[0].error\n })\n : SUCCESS_ASYNC;\n this.pending = null;\n const snapshot = this.publish();\n for (const failure of failures) {\n this.store.emit(\"error\", {\n snapshot,\n error: failure.error,\n phase: failure.phase,\n stepId: failure.stepId\n });\n }\n for (const listener of [...this.transitionListeners]) {\n try {\n listener({ from, to, snapshot });\n } catch {\n // plugin taps are isolated\n }\n }\n this.refreshPluginSnapshot();\n void this.processRaisedEvents(generation);\n }\n\n /**\n * Raised events run FIFO after the transition settles; a cascade longer than\n * {@link MAX_RAISED_EVENTS} is dropped and surfaced as an `error` event.\n */\n private async processRaisedEvents(generation: number): Promise<void> {\n if (this.processingRaised || !this.isCurrent(generation)) return;\n this.processingRaised = true;\n let processed = 0;\n try {\n while (this.raiseQueue.length > 0 && this.isCurrent(generation)) {\n if (this.status !== \"running\") {\n this.raiseQueue = [];\n return;\n }\n processed += 1;\n if (processed > MAX_RAISED_EVENTS) {\n this.raiseQueue = [];\n this.store.emit(\"error\", {\n snapshot: this.store.getSnapshot(),\n error: new Error(\n `journey: raised-event cascade exceeded ${MAX_RAISED_EVENTS} events; queue dropped`\n ),\n phase: \"raise\",\n stepId: this.currentStepId()\n });\n return;\n }\n const next = this.raiseQueue.shift() as JourneyEventObject;\n // `processingRaised` stays true: the sent event's own settle re-enters\n // processRaisedEvents and must bail so this loop keeps one counter.\n await this.send(next.type, (next as { payload?: unknown }).payload);\n }\n } finally {\n this.processingRaised = false;\n }\n }\n\n private isCurrent(generation: number): boolean {\n return !this.disposed && generation === this.generation;\n }\n\n private staleResult(): NavigationResult {\n // The operation was invalidated mid-flight (terminate/restart/dispose), so\n // its target is no longer meaningful \u2014 only where the machine ended up is.\n const from = this.currentStepId();\n return this.disposed\n ? { ok: false, reason: \"disposed\", from, to: null }\n : { ok: false, reason: \"not-running\", from, to: null };\n }\n\n private publish(): JourneySnapshot {\n const snapshot = this.buildSnapshot();\n this.store.publish(snapshot);\n return snapshot;\n }\n\n // \u2500\u2500 snapshot derivation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private buildSnapshot(): JourneySnapshot {\n // Structural sharing: every sub-object reuses the previous snapshot's\n // reference when content-identical, and a fully unchanged snapshot returns\n // the previous object itself \u2014 subscribers (and framework bindings diffing\n // by reference) see identity change exactly when content changes.\n const previous = this.lastSnapshot;\n const currentId = this.currentStepId();\n const visitedNext: Record<string, boolean> = {};\n let visitedStepCount = 0;\n for (const id of this.config.stepIds) {\n const seen = (this.visitCounts.get(id) ?? 0) > 0;\n visitedNext[id] = seen;\n if (seen) visitedStepCount += 1;\n }\n\n const previousHistory = previous?.history;\n const visited =\n previousHistory != null && shallowEqual(previousHistory.visited, visitedNext)\n ? previousHistory.visited\n : (Object.freeze(visitedNext) as Readonly<Record<string, boolean>>);\n\n const base = {\n status: this.status,\n context: this.context,\n transition: shared(\n {\n pending: this.pending !== null,\n phase: this.pending?.phase ?? null,\n from: this.pending?.from ?? null,\n to: this.pending?.to ?? null\n },\n previous?.transition\n ),\n history: shared(\n {\n timeline: sharedArray(this.timeline, previousHistory?.timeline),\n currentIndex: this.currentIndex,\n visited,\n canGoBack: this.currentIndex > 0,\n canGoForward: this.currentIndex >= 0 && this.currentIndex < this.timeline.length - 1\n },\n previousHistory\n ),\n machine: shared({ outcome: this.outcome }, previous?.machine)\n };\n\n const currentBase: CurrentStepBase<string, unknown> | null =\n currentId === null\n ? null\n : {\n id: currentId,\n metadata: this.config.steps[currentId]?.metadata ?? EMPTY_METADATA,\n isFirstTimeVisit: (this.visitCounts.get(currentId) ?? 0) === 1,\n async: this.entryAsync\n };\n\n let snapshot: JourneySnapshot;\n if (this.config.kind === \"linear\") {\n const previousLinear = previous?.type === \"linear\" ? previous : null;\n const orderIndex = currentId === null ? -1 : this.config.stepIds.indexOf(currentId);\n snapshot = {\n ...base,\n type: \"linear\",\n currentStep:\n currentBase === null\n ? null\n : shared(\n {\n ...currentBase,\n index: orderIndex,\n isFirstStep: orderIndex === 0,\n isLastStep: orderIndex === this.config.stepIds.length - 1\n },\n previousLinear?.currentStep\n ),\n steps: shared(\n {\n totalSteps: this.config.stepIds.length,\n stepOrder: this.frozenStepOrder,\n visitedStepCount\n },\n previousLinear?.steps\n ),\n plugins: EMPTY_PLUGINS\n } as JourneySnapshot;\n } else {\n const declaredEvents: string[] = [];\n const availableEvents: string[] = [];\n const availableSteps: string[] = [];\n const outgoingTransitions: GraphTransitionSnapshot<string, string>[] = [];\n const priorities = new Map<string, number>();\n const selectedEvents = new Set<string>();\n let hasOutgoing = false;\n if (currentId !== null) {\n for (const transition of this.config.transitions) {\n if (transition.from !== currentId) continue;\n hasOutgoing = true;\n if (!declaredEvents.includes(transition.event)) declaredEvents.push(transition.event);\n\n const priority = priorities.get(transition.event) ?? 0;\n priorities.set(transition.event, priority + 1);\n const enabled = this.isEnabled(transition);\n const selected = enabled && !selectedEvents.has(transition.event);\n if (selected) selectedEvents.add(transition.event);\n outgoingTransitions.push(\n Object.freeze({\n event: transition.event,\n to: transition.to,\n priority,\n guard: getGraphGuardState(transition.when, enabled),\n enabled,\n selected\n })\n );\n\n if (enabled) {\n if (!availableEvents.includes(transition.event)) availableEvents.push(transition.event);\n if (!availableSteps.includes(transition.to)) availableSteps.push(transition.to);\n }\n }\n }\n const previousGraph = previous?.type === \"graph\" ? previous : null;\n snapshot = {\n ...base,\n type: \"graph\",\n currentStep:\n currentBase === null\n ? null\n : shared({ ...currentBase, isTerminal: !hasOutgoing }, previousGraph?.currentStep),\n steps: shared(\n { totalSteps: this.config.stepIds.length, visitedStepCount },\n previousGraph?.steps\n ),\n declaredEvents: sharedArray(declaredEvents, previousGraph?.declaredEvents),\n availableEvents: sharedArray(availableEvents, previousGraph?.availableEvents),\n availableSteps: sharedArray(availableSteps, previousGraph?.availableSteps),\n outgoingTransitions: sharedArray(\n outgoingTransitions,\n previousGraph?.outgoingTransitions,\n (a, b) => shallowEqual(a, b as unknown as Record<string, unknown>)\n ),\n plugins: EMPTY_PLUGINS\n } as JourneySnapshot;\n }\n\n if (this.snapshotDerivers.size > 0) {\n const extensions: Record<string, unknown> = {};\n for (const [name, derive] of this.snapshotDerivers) {\n // Derivers run on every publish and in the constructor, so an\n // unguarded throw here took down every transition. Isolate like any\n // other plugin tap: report, then carry the plugin's previous slice\n // forward so consumers reading snapshot.plugins[name] do not see it\n // blink to undefined.\n try {\n extensions[name] = derive(snapshot, this.lastPluginExtensions[name]);\n } catch (error) {\n this.store.report(error);\n if (hasOwn(this.lastPluginExtensions, name)) {\n extensions[name] = this.lastPluginExtensions[name];\n }\n }\n }\n this.lastPluginExtensions = extensions;\n const previousPlugins = previous?.plugins;\n snapshot = {\n ...snapshot,\n plugins:\n previousPlugins != null && shallowEqual(previousPlugins, extensions)\n ? previousPlugins\n : Object.freeze(extensions)\n } as JourneySnapshot;\n }\n\n const frozen = Object.freeze(snapshot) as JourneySnapshot;\n const result =\n previous !== null &&\n shallowEqual(\n frozen as unknown as Record<string, unknown>,\n previous as unknown as Record<string, unknown>\n )\n ? previous\n : frozen;\n this.lastSnapshot = result;\n return result;\n }\n}\n", "import { JourneyError } from \"../../core/errors\";\nimport type { JourneyPersistedState, JourneyStorage, PersistenceReason } from \"./persistence.types\";\nimport type { JourneyPersistOption, JourneySnapshot } from \"../../core/types\";\n\n/** Every observation kind a save can be scheduled on. */\nexport const DEFAULT_SAVE_REASONS: readonly PersistenceReason[] = [\n \"context\",\n \"transition\",\n \"status\"\n];\n\n/** Omitted means \"write immediately\"; anything else is clamped to a whole >= 0. */\nexport function normalizeDebounceMs(value: number | undefined): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return 0;\n return Math.max(0, Math.trunc(value));\n}\n\nexport function buildPersistedState(snapshot: JourneySnapshot, now: number): JourneyPersistedState {\n return {\n status: snapshot.status,\n context: snapshot.context,\n timeline: snapshot.history.timeline,\n currentIndex: snapshot.history.currentIndex,\n savedAt: now\n };\n}\n\nconst JOURNEY_STATUSES = new Set([\n \"idle\",\n \"running\",\n \"paused\",\n \"completed\",\n \"terminated\"\n]) as ReadonlySet<string>;\n\n/**\n * Keys that must never survive `JSON.parse` into machine state.\n *\n * `JSON.parse` creates `__proto__` as an ordinary own property rather than\n * reassigning the prototype, so the parsed object is safe in isolation. It stops\n * being safe the moment application code spreads or `Object.assign`s it into a\n * fresh object \u2014 the own key is then copied as a *prototype assignment*. Storage\n * is attacker-reachable, so the shape is scrubbed before it can reach a context.\n */\nconst UNSAFE_KEYS = [\"__proto__\", \"constructor\", \"prototype\"] as const;\n\nfunction scrub(value: unknown, depth = 0): unknown {\n if (depth > 50 || value === null || typeof value !== \"object\") return value;\n if (Array.isArray(value)) return value.map((item) => scrub(item, depth + 1));\n\n const output: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) {\n if ((UNSAFE_KEYS as readonly string[]).includes(key)) continue;\n output[key] = scrub(item, depth + 1);\n }\n return output;\n}\n\n/**\n * Parses a stored value; malformed or foreign payloads yield `null`.\n *\n * Validation is deliberately total: this is the only gate between an untrusted\n * storage entry and machine state, and `readPersisted()` hands the result\n * straight to application code typed as `JourneyPersistedState`.\n */\nexport function parsePersistedState(raw: string | null): JourneyPersistedState | null {\n if (raw === null) return null;\n let value: unknown;\n try {\n value = JSON.parse(raw);\n } catch {\n return null;\n }\n if (typeof value !== \"object\" || value === null) return null;\n const candidate = value as Record<string, unknown>;\n if (\n typeof candidate.status !== \"string\" ||\n !JOURNEY_STATUSES.has(candidate.status) ||\n !Array.isArray(candidate.timeline) ||\n !candidate.timeline.every((id) => typeof id === \"string\") ||\n typeof candidate.currentIndex !== \"number\" ||\n !Number.isInteger(candidate.currentIndex) ||\n typeof candidate.savedAt !== \"number\" ||\n !Number.isFinite(candidate.savedAt)\n ) {\n return null;\n }\n return {\n status: candidate.status,\n context: scrub(candidate.context),\n timeline: candidate.timeline,\n currentIndex: candidate.currentIndex,\n savedAt: candidate.savedAt\n } as JourneyPersistedState;\n}\n\n/**\n * Resolves the `persist` option's storage; throws when none is available.\n *\n * Reading `globalThis.localStorage` can itself throw \u2014 a third-party iframe\n * with storage blocked, or Safari's Lockdown Mode \u2014 rather than returning\n * undefined. Unguarded, that surfaced as a raw `SecurityError` out of\n * `createLinearJourney`, which reads as a library crash rather than an\n * environment that cannot persist. The failure stays loud (silently disabling\n * persistence loses data with no signal) but is now a `journey:` error naming\n * the fix, with the original kept as `cause`.\n */\nexport function resolvePersistStorage(option: JourneyPersistOption): JourneyStorage {\n if (option.storage) return option.storage;\n\n let ambient: JourneyStorage | undefined;\n try {\n ambient = globalThis.localStorage as JourneyStorage | undefined;\n } catch (error) {\n throw new JourneyError(\n \"storage-unavailable\",\n \"localStorage access was blocked by the environment; pass persist.storage explicitly\",\n {},\n error\n );\n }\n\n if (!ambient) {\n throw new JourneyError(\n \"storage-unavailable\",\n \"persist.storage is required when localStorage is unavailable\"\n );\n }\n return ambient;\n}\n\n/**\n * Reads a persisted record that can seed this machine, or `null`. Restore is\n * best-effort by design: terminal-status records, records whose timeline\n * mentions a step the current definition no longer declares (definition\n * drift), and malformed/foreign payloads are all ignored rather than thrown.\n */\nexport function readRestorableState(\n option: JourneyPersistOption,\n isDeclaredStep: (id: string) => boolean\n): JourneyPersistedState | null {\n let raw: string | null;\n try {\n raw = resolvePersistStorage(option).getItem(option.key);\n } catch {\n return null;\n }\n const record = parsePersistedState(raw);\n if (!record) return null;\n if (record.status !== \"running\" && record.status !== \"paused\") return null;\n if (!Number.isInteger(record.currentIndex)) return null;\n if (record.currentIndex < 0 || record.currentIndex >= record.timeline.length) return null;\n for (const id of record.timeline) {\n if (typeof id !== \"string\" || !isDeclaredStep(id)) return null;\n }\n return record;\n}\n", "import { warnInDevelopment } from \"@rxova/journey-common/dev\";\nimport {\n buildPersistedState,\n DEFAULT_SAVE_REASONS,\n normalizeDebounceMs,\n parsePersistedState,\n resolvePersistStorage\n} from \"./persistence.helpers\";\nimport type {\n JourneyPersistedState,\n PersistenceApi,\n PersistencePluginOptions,\n PersistenceReason,\n PersistenceState\n} from \"./persistence.types\";\nimport type { JourneyPersistOption, JourneyPlugin } from \"../../core/types\";\n\nexport {\n buildPersistedState,\n DEFAULT_SAVE_REASONS,\n normalizeDebounceMs,\n parsePersistedState\n} from \"./persistence.helpers\";\n\nconst IDLE_STATE: PersistenceState = { status: \"idle\", lastSavedAt: null, error: null };\n\n/**\n * Persists a serializable slice of machine state (status, context, timeline) on\n * every transition, status change, and context change. `saveOn` narrows which\n * of those trigger a write; `debounceMs` collapses a burst of them into one.\n *\n * The plugin itself is save-side only (plugins observe, they cannot seed the\n * runtime). Restore happens through the creation-time `persist` option, which\n * reads a restorable record before the machine is built; `readPersisted()`\n * exposes the saved state for callers wiring this plugin explicitly.\n */\nexport function createPersistencePlugin(\n options: PersistencePluginOptions\n): JourneyPlugin<\"persistence\", PersistenceApi, PersistenceState> {\n const now = options.now ?? Date.now;\n const debounceMs = normalizeDebounceMs(options.debounceMs);\n const saveReasons = new Set<PersistenceReason>(options.saveOn ?? DEFAULT_SAVE_REASONS);\n // Per plugin *instance*, not per machine: mutable state is scoped to setup(),\n // but `options` is not \u2014 two machines sharing one instance write the same key\n // and silently clobber each other.\n let setupCount = 0;\n return {\n name: \"persistence\",\n setup(host) {\n setupCount += 1;\n if (setupCount > 1) {\n warnInDevelopment(\n `journey: persistence plugin instance shared by ${setupCount} machines; they overwrite key \"${options.key}\". Create one per machine.`\n );\n }\n let lastWritten: JourneyPersistedState | null = null;\n let state: PersistenceState = IDLE_STATE;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let disposed = false;\n\n const succeeded = (written: JourneyPersistedState) => {\n lastWritten = written;\n state = { status: \"saved\", lastSavedAt: written.savedAt, error: null };\n };\n\n const failed = (error: unknown) => {\n state = { ...state, status: \"error\", error };\n host.reportError(error);\n };\n\n /**\n * Writes now. Returns a promise only so `flushPersisted` can be awaited;\n * the immediate path stays synchronous up to the `setItem` call, which is\n * what lets a throwing adapter surface through the runtime's listener\n * isolation exactly as it always did.\n */\n const save = (): void | Promise<void> => {\n const written = buildPersistedState(host.getSnapshot(), now());\n state = { ...state, status: \"saving\" };\n let result: void | Promise<void>;\n try {\n result = options.storage.setItem(options.key, JSON.stringify(written));\n } catch (error) {\n // Recorded here, but rethrown so the runtime's listener isolation\n // reports it exactly as it always did.\n state = { ...state, status: \"error\", error };\n throw error;\n }\n // `setItem` may be async. Discarding that promise turned a rejecting\n // adapter into an unhandled rejection, which terminates the process\n // under Node's default `--unhandled-rejections=throw`.\n if (result !== undefined) {\n return result.then(() => succeeded(written), failed);\n }\n succeeded(written);\n };\n\n const cancelTimer = () => {\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n };\n\n /**\n * A debounced write happens on a timer, so there is no synchronous caller\n * left to throw to \u2014 its failures land in `state` and `reportError`\n * instead. The immediate path keeps throwing.\n */\n const runDebounced = () => {\n timer = null;\n try {\n const result = save();\n if (result !== undefined) void result;\n } catch (error) {\n failed(error);\n }\n };\n\n const onObservation = (reason: PersistenceReason) => {\n if (disposed || !saveReasons.has(reason)) return;\n if (debounceMs === 0) {\n void save();\n return;\n }\n cancelTimer();\n state = { ...state, status: \"pending\" };\n timer = setTimeout(runDebounced, debounceMs);\n };\n\n host.onContextChange(() => onObservation(\"context\"));\n host.onTransition(() => onObservation(\"transition\"));\n host.onStatusChange(({ current }) => {\n if (current === \"terminated\" && options.clearOnTerminate) {\n cancelTimer();\n lastWritten = null;\n state = IDLE_STATE;\n options.storage.removeItem(options.key);\n return;\n }\n onObservation(\"status\");\n });\n host.onDispose(() => {\n disposed = true;\n cancelTimer();\n });\n\n return {\n api: {\n inspectPersistedState: () => lastWritten,\n getPersistenceState: () => state,\n readPersisted: () => parsePersistedState(options.storage.getItem(options.key)),\n clearPersisted: () => {\n cancelTimer();\n lastWritten = null;\n state = IDLE_STATE;\n // Called directly by user code; record the failure here rather than\n // throwing out of an API whose sibling writes are all contained.\n try {\n options.storage.removeItem(options.key);\n } catch (error) {\n failed(error);\n }\n },\n flushPersisted: async () => {\n cancelTimer();\n try {\n await save();\n } catch (error) {\n failed(error);\n }\n }\n },\n deriveSnapshot: (_snapshot, previous) => (previous === state ? previous : state)\n };\n }\n };\n}\n\n/** Expands the creation-time `persist` option into the persistence plugin. */\nexport function persistOptionToPlugin(\n option: JourneyPersistOption\n): JourneyPlugin<\"persistence\", PersistenceApi, PersistenceState> {\n return createPersistencePlugin({ key: option.key, storage: resolvePersistStorage(option) });\n}\n", "import { JourneyError } from \"../core/errors\";\nimport { hasOwn } from \"../core/helpers\";\nimport { buildMachineSurface } from \"../core/machine\";\nimport { JourneyRuntime } from \"../core/runtime\";\nimport { persistOptionToPlugin } from \"../plugins/persistence/persistence\";\nimport { readRestorableState } from \"../plugins/persistence/persistence.helpers\";\nimport type { RuntimeStep } from \"../core/runtime.types\";\nimport type {\n CompletePayloadOf,\n JourneyTerminationPayloads,\n LinearJourneyDefinition,\n LinearJourneyMachine,\n LinearStepConfig,\n TerminatePayloadOf\n} from \"./linear.types\";\nimport type { AnyJourneyPlugin, JourneyRuntimeOptions } from \"../core/types\";\nimport type { Bag, MetaOf } from \"../graph/bag.types\";\n\n/**\n * Creates a linear journey runtime from a pure-data definition.\n *\n * Declared order drives `goToNextStep`'s fallback at the timeline tip and the\n * order-based snapshot fields (`index`, `isFirstStep`, `isLastStep`,\n * `stepOrder`). `goToNextStep` on the last step never auto-completes.\n */\nexport function createLinearJourney<\n const TStepId extends string,\n TContext,\n TTerminationPayloads extends JourneyTerminationPayloads = JourneyTerminationPayloads,\n // Defaults to the empty tuple, matching createGraphJourney. Defaulting to\n // `readonly AnyJourneyPlugin[]` collapsed PluginApis to `{ [x: string]: never }`\n // \u2014 an index signature that accepts any key \u2014 so `machine.plugins.typo`\n // compiled clean whenever plugins were omitted or the first generics were\n // supplied explicitly.\n const TPlugins extends readonly AnyJourneyPlugin[] = readonly [],\n TMeta = Record<string, unknown>\n>(\n definition: LinearJourneyDefinition<TStepId, TContext, TTerminationPayloads, TMeta>,\n options: JourneyRuntimeOptions<TPlugins, NoInfer<TStepId>> = {}\n): LinearJourneyMachine<\n TContext,\n TStepId,\n TMeta,\n TPlugins,\n CompletePayloadOf<TTerminationPayloads>,\n TerminatePayloadOf<TTerminationPayloads>\n> {\n if (definition.steps.length === 0) {\n throw new JourneyError(\"empty-definition\", \"a linear journey needs at least one step\");\n }\n\n const stepIds: string[] = [];\n const steps: Record<string, RuntimeStep> = {};\n for (const input of definition.steps) {\n const config: LinearStepConfig<\n TContext,\n TStepId,\n TMeta,\n CompletePayloadOf<TTerminationPayloads>,\n TerminatePayloadOf<TTerminationPayloads>\n > = typeof input === \"string\" ? { id: input } : input;\n if (hasOwn(steps, config.id)) {\n throw new JourneyError(\"duplicate-step-id\", `duplicate step id \"${config.id}\"`, {\n stepId: config.id\n });\n }\n stepIds.push(config.id);\n const runtimeStep: {\n metadata: unknown;\n onEnter?: NonNullable<RuntimeStep[\"onEnter\"]>;\n onLeave?: NonNullable<RuntimeStep[\"onLeave\"]>;\n } = { metadata: config.metadata ?? {} };\n if (config.onEnter) {\n runtimeStep.onEnter = config.onEnter as unknown as NonNullable<RuntimeStep[\"onEnter\"]>;\n }\n if (config.onLeave) {\n runtimeStep.onLeave = config.onLeave as unknown as NonNullable<RuntimeStep[\"onLeave\"]>;\n }\n steps[config.id] = runtimeStep;\n }\n\n if (options.startAt !== undefined && !hasOwn(steps, options.startAt)) {\n throw new JourneyError(\"unknown-step\", `startAt references unknown step \"${options.startAt}\"`, {\n stepId: options.startAt\n });\n }\n\n // Explicit `startAt` wins over a persisted record; restore is best-effort.\n const restored =\n options.persist && options.startAt === undefined\n ? readRestorableState(options.persist, (id) => hasOwn(steps, id))\n : null;\n\n const runtime = new JourneyRuntime({\n kind: \"linear\",\n stepIds,\n steps,\n initial: stepIds[0] as string,\n ...(options.startAt !== undefined ? { startAt: options.startAt } : {}),\n initialContext: definition.context,\n ...(restored\n ? {\n restore: {\n context: restored.context,\n timeline: restored.timeline,\n currentIndex: restored.currentIndex\n }\n }\n : {}),\n transitions: [],\n handlers: undefined,\n autoStart: options.autoStart ?? true,\n defaultTimeoutMs: options.defaultTimeoutMs,\n ...(options.onListenerError !== undefined ? { onListenerError: options.onListenerError } : {}),\n plugins: [\n ...(options.persist ? [persistOptionToPlugin(options.persist)] : []),\n ...(options.plugins ?? [])\n ]\n });\n\n const surface = buildMachineSurface(runtime);\n return {\n ...surface,\n navigate: {\n ...surface.navigate,\n goToStepByIndex: (index: number) => runtime.goToStepByIndex(index)\n }\n } as unknown as LinearJourneyMachine<\n TContext,\n TStepId,\n TMeta,\n TPlugins,\n CompletePayloadOf<TTerminationPayloads>,\n TerminatePayloadOf<TTerminationPayloads>\n >;\n}\n\n/**\n * Returns a `createLinearJourney` with its types pinned up front instead of\n * inferred.\n *\n * The linear tier infers almost everything from the definition already \u2014 step\n * ids from the `steps` tuple, context from its value \u2014 so reach for this only\n * to pin a `meta` shape, or to share one bag with steps authored in separate\n * files.\n *\n * A standalone export rather than a property on the factory: attaching one\n * would be a module-level side effect, and that defeats tree-shaking badly\n * enough that importing only `createLinearJourney` pulled the whole graph tier\n * into the bundle.\n *\n * ```ts\n * const checkout = withLinearTypes<CheckoutBag>()({\n * steps: [\"account\", \"shipping\", \"review\"],\n * context: initialContext\n * });\n * ```\n */\nexport const withLinearTypes =\n <TBag extends Bag>() =>\n <const TPlugins extends readonly AnyJourneyPlugin[] = readonly []>(\n definition: LinearJourneyDefinition<\n TBag[\"stepId\"],\n TBag[\"context\"],\n JourneyTerminationPayloads,\n MetaOf<TBag>\n >,\n options: JourneyRuntimeOptions<TPlugins, TBag[\"stepId\"]> = {}\n ): LinearJourneyMachine<TBag[\"context\"], TBag[\"stepId\"], MetaOf<TBag>, TPlugins> =>\n createLinearJourney(definition, options) as unknown as LinearJourneyMachine<\n TBag[\"context\"],\n TBag[\"stepId\"],\n MetaOf<TBag>,\n TPlugins\n >;\n", "import { JourneyError } from \"../core/errors\";\nimport { eventWorkKey, hasOwn } from \"../core/helpers\";\nimport { buildMachineSurface } from \"../core/machine\";\nimport { JourneyRuntime } from \"../core/runtime\";\nimport { persistOptionToPlugin } from \"../plugins/persistence/persistence\";\nimport { readRestorableState } from \"../plugins/persistence/persistence.helpers\";\nimport type { RuntimeStep, RuntimeTransition } from \"../core/runtime.types\";\nimport type {\n GraphJourneyMachine,\n GraphJourneyOptions,\n GraphStepConfig,\n LooseGraphDefinition,\n LooseOnEntry,\n LooseTransition,\n MutableRuntimeStep,\n MutableRuntimeTransition,\n MutableSendWork\n} from \"./graph.types\";\nimport type { AnySendWork } from \"../core/runtime.types\";\nimport type { Bag, GraphDefinition, HandlersOf, MetaOf } from \"./bag.types\";\nimport type {\n AnyJourneyPlugin,\n CompletePayloadOf,\n JourneyEventObject,\n JourneyTerminationPayloads,\n TerminatePayloadOf\n} from \"../core/types\";\n\n/**\n * Both validators run at build time rather than at the first send. A label only\n * ever shows up in an error message and a timeout only ever fires under load,\n * so a malformed one would otherwise stay invisible until the moment it was\n * needed to explain something else.\n */\nconst assertLabel = (label: unknown, where: string, meta: { event: string; stepId: string }) => {\n if (typeof label !== \"string\" || label.length === 0) {\n throw new JourneyError(\n \"invalid-label\",\n `${where} must declare \"label\" as a non-empty string`,\n meta\n );\n }\n return label;\n};\n\nconst assertTimeout = (ms: unknown, where: string, meta: { event: string; stepId: string }) => {\n if (typeof ms !== \"number\" || !Number.isFinite(ms) || ms <= 0) {\n throw new JourneyError(\n \"invalid-timeout\",\n `${where} must declare \"timeoutMs\" as a finite number greater than 0`,\n meta\n );\n }\n return ms;\n};\n\n/**\n * Flattens each step's colocated `on` into the runtime's flat transition list,\n * in declaration order, and validates every target.\n *\n * Order is per step, then per event, then per candidate. That differs from the\n * old central map's global per-event order, but only for the same event\n * declared from two steps \u2014 and candidates are filtered by `from` before order\n * is consulted, so the selected edge is unchanged. `first-enabled-in-declared-\n * order` is asserted directly in graph.test.ts.\n *\n * `from` cannot dangle here: it is the key of the step that declares the entry.\n */\nexport function normalizeGraphDefinition(definition: LooseGraphDefinition): {\n stepIds: string[];\n steps: Record<string, RuntimeStep>;\n transitions: RuntimeTransition[];\n eventWork: Record<string, AnySendWork>;\n} {\n const stepIds = Object.keys(definition.steps);\n if (stepIds.length === 0) {\n throw new JourneyError(\"empty-definition\", \"a graph journey needs at least one step\");\n }\n if (!stepIds.includes(definition.initial)) {\n throw new JourneyError(\n \"unknown-initial-step\",\n `initial step \"${definition.initial}\" is not a declared step`,\n { stepId: definition.initial }\n );\n }\n\n const steps: Record<string, RuntimeStep> = {};\n for (const id of stepIds) {\n const config = definition.steps[id] as GraphStepConfig;\n const runtimeStep: MutableRuntimeStep = { metadata: config.metadata ?? {} };\n if (config.onEnter) {\n runtimeStep.onEnter = config.onEnter as unknown as NonNullable<RuntimeStep[\"onEnter\"]>;\n }\n if (config.onLeave) {\n runtimeStep.onLeave = config.onLeave as unknown as NonNullable<RuntimeStep[\"onLeave\"]>;\n }\n steps[id] = runtimeStep;\n }\n\n const transitions: RuntimeTransition[] = [];\n const eventWork: Record<string, AnySendWork> = {};\n\n const pushCandidate = (\n event: string,\n from: string,\n candidate: LooseTransition,\n index: number\n ): void => {\n if (!stepIds.includes(candidate.to)) {\n throw new JourneyError(\n \"dangling-transition\",\n `transition \"${event}\" references unknown step \"${candidate.to}\"`,\n { event, stepId: candidate.to }\n );\n }\n const where = `transition \"${event}\"[${index}] on step \"${from}\"`;\n const runtimeTransition: MutableRuntimeTransition = { event, from, to: candidate.to, index };\n if (candidate.when) runtimeTransition.when = candidate.when;\n if (candidate.onTransition) runtimeTransition.onTransition = candidate.onTransition;\n if (candidate.label !== undefined) {\n runtimeTransition.label = assertLabel(candidate.label, where, { event, stepId: from });\n }\n if (candidate.timeoutMs !== undefined) {\n runtimeTransition.timeoutMs = assertTimeout(candidate.timeoutMs, where, {\n event,\n stepId: from\n });\n }\n transitions.push(runtimeTransition);\n };\n\n for (const from of stepIds) {\n const on = definition.steps[from]?.on;\n if (!on) continue;\n for (const [event, entry] of Object.entries(on)) {\n if (entry === undefined) continue;\n if (typeof entry === \"string\") {\n pushCandidate(event, from, { to: entry }, 0);\n continue;\n }\n if (Array.isArray(entry)) {\n entry.forEach((candidate, index) => pushCandidate(event, from, candidate, index));\n continue;\n }\n const declared = entry as Exclude<LooseOnEntry, string | readonly LooseTransition[]>;\n const where = `work on \"${event}\" on step \"${from}\"`;\n const work: MutableSendWork = { run: declared.run };\n if (declared.commit) work.commit = declared.commit;\n if (declared.label !== undefined) {\n work.label = assertLabel(declared.label, where, { event, stepId: from });\n }\n if (declared.timeoutMs !== undefined) {\n work.timeoutMs = assertTimeout(declared.timeoutMs, where, { event, stepId: from });\n }\n eventWork[eventWorkKey(from, event)] = work;\n declared.candidates.forEach((candidate, index) =>\n pushCandidate(event, from, candidate, index)\n );\n }\n }\n\n return { stepIds, steps, transitions, eventWork };\n}\n\n/**\n * Creates a graph journey runtime from a pure-data definition.\n *\n * `send(event, payload?)` is the primary verb; `goToStepById` is\n * transition-gated sugar (fires only if an enabled transition targets that\n * id). Timeline moves bypass transition gating \u2014 retracing a walked path is\n * always legal. Step `onLeave` effects still run after those moves commit.\n */\nexport function createGraphJourney<\n TContext,\n TStepId extends string,\n TEvents extends JourneyEventObject = JourneyEventObject,\n THandlers = unknown,\n TMeta = Record<string, unknown>,\n const TPlugins extends readonly AnyJourneyPlugin[] = readonly [],\n TTerminationPayloads extends JourneyTerminationPayloads = JourneyTerminationPayloads\n>(\n // Inline shape (not GraphJourneyDefinition) so TStepId infers from the\n // steps-record keys alone: every other occurrence is NoInfer-wrapped,\n // otherwise `initial` would win inference and collapse the id union.\n definition: {\n readonly steps: Readonly<\n Record<\n TStepId,\n GraphStepConfig<\n NoInfer<TContext>,\n NoInfer<TStepId>,\n NoInfer<TEvents>,\n TMeta,\n NoInfer<THandlers>\n >\n >\n >;\n readonly initial: NoInfer<TStepId>;\n readonly context: TContext;\n readonly handlers?: THandlers;\n /** @internal Builder-produced; opaque by design (see GraphJourneyDefinition). */\n readonly eventWork?: Readonly<Record<string, unknown>>;\n readonly $events?: TEvents;\n readonly $payloads?: TTerminationPayloads;\n },\n options: GraphJourneyOptions<NoInfer<THandlers>, TPlugins, NoInfer<TStepId>> = {}\n // THandlers is load-bearing: it types `handlers` inside send work, which is\n // the only channel injected clients reach. Omitting it here let the\n // annotation win over the cast below and erased it to `unknown`.\n): GraphJourneyMachine<\n TContext,\n TStepId,\n TEvents,\n TMeta,\n TPlugins,\n CompletePayloadOf<TTerminationPayloads>,\n TerminatePayloadOf<TTerminationPayloads>\n> {\n const { stepIds, steps, transitions, eventWork } = normalizeGraphDefinition(\n definition as unknown as LooseGraphDefinition\n );\n\n if (options.startAt !== undefined && !hasOwn(steps, options.startAt)) {\n throw new JourneyError(\"unknown-step\", `startAt references unknown step \"${options.startAt}\"`, {\n stepId: options.startAt\n });\n }\n\n // Explicit `startAt` wins over a persisted record; restore is best-effort.\n const restored =\n options.persist && options.startAt === undefined\n ? readRestorableState(options.persist, (id) => hasOwn(steps, id))\n : null;\n\n const runtime = new JourneyRuntime({\n kind: \"graph\",\n stepIds,\n steps,\n initial: definition.initial,\n ...(options.startAt !== undefined ? { startAt: options.startAt } : {}),\n initialContext: definition.context,\n ...(restored\n ? {\n restore: {\n context: restored.context,\n timeline: restored.timeline,\n currentIndex: restored.currentIndex\n }\n }\n : {}),\n transitions,\n ...(Object.keys(eventWork).length > 0 ? { eventWork } : {}),\n handlers: options.handlers ?? definition.handlers,\n autoStart: options.autoStart ?? true,\n defaultTimeoutMs: options.defaultTimeoutMs,\n ...(options.onListenerError !== undefined ? { onListenerError: options.onListenerError } : {}),\n plugins: [\n ...(options.persist ? [persistOptionToPlugin(options.persist)] : []),\n ...(options.plugins ?? [])\n ]\n });\n\n const machine = {\n ...buildMachineSurface(runtime),\n send: (type: string, payload?: unknown) => runtime.send(type, payload)\n };\n return machine as unknown as GraphJourneyMachine<\n TContext,\n TStepId,\n TEvents,\n TMeta,\n TPlugins,\n CompletePayloadOf<TTerminationPayloads>,\n TerminatePayloadOf<TTerminationPayloads>\n >;\n}\n\n/**\n * Creates a graph journey factory with its types pinned up front instead of\n * inferred.\n *\n * Reach for it when the definition cannot supply a type on its own \u2014\n * `handlers`, a `meta` shape, or a `run` result, none of which sit at an\n * inference site \u2014 or when the same bag is shared by steps authored in\n * separate files. The definition is then *checked* against the bag rather than\n * read for types.\n *\n * ```ts\n * const login = withGraphTypes<AuthBag>()({\n * initial: \"login\",\n * context: initialContext,\n * steps: { login: { on: { submit: \"twofa\" } }, twofa: {} }\n * });\n * ```\n *\n * Plain `createGraphJourney(definition)` stays the default: step ids infer from\n * the `steps` keys and event names from the `on` keys.\n */\nexport const withGraphTypes =\n <TBag extends Bag>() =>\n <const TPlugins extends readonly AnyJourneyPlugin[] = readonly []>(\n definition: GraphDefinition<TBag>,\n options: GraphJourneyOptions<HandlersOf<TBag>, TPlugins, TBag[\"stepId\"]> = {}\n ): GraphJourneyMachine<TBag[\"context\"], TBag[\"stepId\"], TBag[\"events\"], MetaOf<TBag>, TPlugins> =>\n createGraphJourney(\n definition as unknown as Parameters<typeof createGraphJourney>[0],\n options as unknown as Parameters<typeof createGraphJourney>[1]\n ) as unknown as GraphJourneyMachine<\n TBag[\"context\"],\n TBag[\"stepId\"],\n TBag[\"events\"],\n MetaOf<TBag>,\n TPlugins\n >;\n", "import type { Bag, HandlersOf, MetaOf, ResultOf } from \"./bag.types\";\nimport type { GraphOnEntry, GraphTransition, SendWorkArgs } from \"./graph.types\";\nimport type { ContextUpdater, GraphSnapshot } from \"../core/types\";\n\n/** The event an entry is declared under, narrowed out of the bag's union. */\ntype TriggerOf<TBag extends Bag, TType extends TBag[\"events\"][\"type\"]> = Extract<\n TBag[\"events\"],\n { type: TType }\n>;\n\ntype WorkArgs<TBag extends Bag, TType extends TBag[\"events\"][\"type\"]> = SendWorkArgs<\n TBag[\"stepId\"],\n TriggerOf<TBag, TType>,\n GraphSnapshot<TBag[\"context\"], TBag[\"stepId\"], MetaOf<TBag>, TBag[\"events\"]>,\n HandlersOf<TBag>\n>;\n\n/**\n * The config {@link defineWork} checks.\n *\n * The same shape as the object arm of {@link GraphOnEntry}, with two\n * differences that only a function call can provide: `TResult` is a free type\n * parameter here rather than a fixed argument, and `event` is narrowed to the\n * key the entry is declared under.\n */\nexport type WorkConfig<TBag extends Bag, TType extends TBag[\"events\"][\"type\"], TResult> = {\n readonly run: (args: WorkArgs<TBag, TType>) => TResult | Promise<TResult>;\n readonly commit?: (\n args: WorkArgs<TBag, TType> & {\n readonly result: TResult;\n readonly updateContext: (updater: ContextUpdater<TBag[\"context\"]>) => void;\n }\n ) => void;\n /** Names this work in timeout and error messages. */\n readonly label?: string;\n /** Budget for `run`, overriding `defaultTimeoutMs`. */\n readonly timeoutMs?: number;\n /**\n * Guards here stay total functions of context, as everywhere else: the run\n * result reaches them only through the context `commit` stages. Routing\n * directly on the result was removed in v2 because the same guards run during\n * snapshot derivation, where no send is in flight \u2014 `availableEvents` would\n * then disagree with what a send actually does.\n */\n readonly candidates: readonly GraphTransition<\n TBag[\"context\"],\n TBag[\"stepId\"],\n TBag[\"events\"],\n HandlersOf<TBag>,\n MetaOf<TBag>,\n TriggerOf<TBag, TType>\n >[];\n};\n\n/**\n * Declares an event's async so that `run`'s return type flows into `commit` and\n * into the candidates' guards.\n *\n * Written straight into a definition, `run` sits at a property position, which\n * is not an inference site \u2014 so `result` is `unknown` unless the type is\n * restated in the bag's `results`. Pinning it there works, but it is a second\n * place to keep in sync, and it is one result type per event name rather than\n * per (step, event) pair. Passing the same config through a generic function\n * call puts `TResult` back at an inference site, so it is read off `run` and\n * nothing needs restating:\n *\n * ```ts\n * on: {\n * SUBMIT: defineWork<AuthBag, \"SUBMIT\">()({\n * run: ({ handlers }) => handlers.login(), // TResult inferred here\n * commit: ({ result, updateContext }) => // ...and typed here\n * updateContext((c) => ({ ...c, token: result.token, needsTwoFactor: result.twoFactor })),\n * timeoutMs: 10_000,\n * candidates: [\n * { to: \"twofa\", label: \"needs-2fa\", when: ({ context }) => context.needsTwoFactor },\n * { to: \"home\", label: \"logged-in\" }\n * ]\n * })\n * }\n * ```\n *\n * The call is curried because TypeScript infers all of a call's type arguments\n * or none: naming the bag and the event inline would opt `TResult` out of\n * inference too, which is the problem being solved. The empty second call is\n * the price of pinning the first two and inferring the third.\n *\n * Pairs with a bag, so reach for it through `withGraphTypes<TBag>()` rather\n * than plain `createGraphJourney`: the bag is where `stepId`, `events` and\n * `handlers` come from, and a definition that infers those itself will not line\n * up with them.\n *\n * At runtime this returns its argument unchanged. The cast is what erases the\n * narrowed `event` and the inferred `TResult` back down to the slot's wider\n * shape \u2014 `commit`'s `result` sits at a contravariant position, so a pinned\n * config cannot be assigned into an `unknown` slot directly. That is the same\n * erasure the v1 builder did, and it is sound because the config has already\n * been checked, against sharper types, at this call site.\n */\nexport const defineWork =\n <TBag extends Bag, TType extends TBag[\"events\"][\"type\"] = TBag[\"events\"][\"type\"]>() =>\n <TResult>(\n config: WorkConfig<TBag, TType, TResult>\n ): GraphOnEntry<\n TBag[\"context\"],\n TBag[\"stepId\"],\n TBag[\"events\"],\n HandlersOf<TBag>,\n MetaOf<TBag>,\n ResultOf<TBag, TType>,\n TriggerOf<TBag, TType>\n > =>\n config as unknown as GraphOnEntry<\n TBag[\"context\"],\n TBag[\"stepId\"],\n TBag[\"events\"],\n HandlersOf<TBag>,\n MetaOf<TBag>,\n ResultOf<TBag, TType>,\n TriggerOf<TBag, TType>\n >;\n", "import { normalizeGraphDefinition } from \"../graph/graph\";\nimport type { DiagnosticsIssue, DiagnosticsResult } from \"./diagnostics.types\";\nimport type { JourneyStructure } from \"../core/types\";\n\nfunction analyzeJourneyStructure(structure: JourneyStructure): DiagnosticsResult {\n const issues: DiagnosticsIssue[] = [];\n const stepIds = [...structure.stepIds];\n\n // Shadowed transitions: after an unguarded candidate for (from, event),\n // later candidates for the same key can never be selected.\n const shadowedIndexes = new Set<number>();\n const unguardedSeen = new Set<string>();\n structure.transitions.forEach((transition, index) => {\n const key = `${transition.from} ${transition.event}`;\n if (unguardedSeen.has(key)) {\n shadowedIndexes.add(index);\n issues.push({\n code: \"shadowed-transition\",\n severity: \"warning\",\n from: transition.from,\n event: transition.event,\n message: `Transition \"${transition.from}.${transition.event}\" is shadowed by an earlier unconditional candidate.`\n });\n return;\n }\n if (!transition.guarded) unguardedSeen.add(key);\n });\n\n const activeTransitions = structure.transitions.filter((_, index) => !shadowedIndexes.has(index));\n const outgoing = (stepId: string) =>\n activeTransitions.filter((transition) => transition.from === stepId);\n\n const reachable = new Set<string>();\n const queue = [structure.initial];\n while (queue.length > 0) {\n const stepId = queue.pop() as string;\n if (reachable.has(stepId)) continue;\n reachable.add(stepId);\n for (const transition of outgoing(stepId)) queue.push(transition.to);\n }\n\n for (const stepId of stepIds) {\n if (reachable.has(stepId)) continue;\n issues.push({\n code: \"unreachable-step\",\n severity: \"warning\",\n stepId,\n message: `Step \"${stepId}\" is unreachable from the initial step \"${structure.initial}\".`\n });\n }\n\n const terminalStepIds = stepIds.filter((stepId) => outgoing(stepId).length === 0);\n\n // Cycle detection over the reachable subgraph.\n const cycleKeys = new Set<string>();\n const visited = new Set<string>();\n const stack: string[] = [];\n const walk = (stepId: string) => {\n visited.add(stepId);\n stack.push(stepId);\n for (const transition of outgoing(stepId)) {\n const stackIndex = stack.indexOf(transition.to);\n if (stackIndex >= 0) {\n const cycleSteps = [...stack.slice(stackIndex), transition.to];\n const cycleKey = cycleSteps.join(\" \");\n if (!cycleKeys.has(cycleKey)) {\n cycleKeys.add(cycleKey);\n issues.push({\n code: \"cycle-detected\",\n severity: \"warning\",\n from: transition.from,\n event: transition.event,\n steps: cycleSteps,\n message: `Cycle detected: ${cycleSteps.join(\" -> \")}.`\n });\n }\n continue;\n }\n if (!visited.has(transition.to)) walk(transition.to);\n }\n stack.pop();\n };\n walk(structure.initial);\n\n const terminalPathExists = terminalStepIds.some((stepId) => reachable.has(stepId));\n if (!terminalPathExists) {\n issues.push({\n code: \"no-terminal-path\",\n severity: \"warning\",\n stepId: structure.initial,\n message: `No terminal step is reachable from the initial step \"${structure.initial}\".`\n });\n }\n\n return {\n issues,\n summary: {\n stepCount: stepIds.length,\n reachableStepCount: reachable.size,\n unreachableStepCount: stepIds.length - reachable.size,\n terminalStepIds,\n cycleCount: cycleKeys.size,\n shadowedTransitionCount: shadowedIndexes.size,\n terminalPathExists\n }\n };\n}\n\n/**\n * Structural analysis of a graph definition: unreachable steps, shadowed\n * transitions (an earlier unguarded candidate on the same `(from, event)`\n * always wins), cycles, and terminal-path existence. Completion is explicit in\n * this model, so terminal steps are reported as facts in the summary, not as\n * dead-end issues.\n *\n * A plain function over the definition rather than a plugin over a machine.\n * Nothing here needs a runtime \u2014 it is the definition that is being checked \u2014\n * so this runs in a test or a build step, before any machine exists. Linear\n * journeys have no transition graph and so nothing to analyze.\n */\nexport function analyzeStructure(definition: {\n readonly steps: object;\n readonly initial: string;\n}): DiagnosticsResult {\n const { stepIds, transitions } = normalizeGraphDefinition(\n definition as Parameters<typeof normalizeGraphDefinition>[0]\n );\n const structure: JourneyStructure = {\n kind: \"graph\",\n stepIds,\n initial: definition.initial,\n transitions: transitions.map((transition) => ({\n event: transition.event,\n from: transition.from,\n to: transition.to,\n guarded: transition.when !== undefined,\n label: transition.label ?? null,\n index: transition.index\n }))\n };\n return analyzeJourneyStructure(structure);\n}\n"],
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EACA,QAAS,CACP,UAAWC,EAAQ,OACnB,mBAAoBU,EAAU,KAC9B,qBAAsBV,EAAQ,OAASU,EAAU,KACjD,gBAAAE,EACA,WAAYC,EAAU,KACtB,wBAAyBZ,EAAgB,KACzC,mBAAAmB,CACF,CACF,CACF,CAcO,SAASC,GAAiBC,EAGX,CACpB,GAAM,CAAE,QAAAtB,EAAS,YAAAuB,CAAY,EAAIC,EAC/BF,CACF,EACMxB,EAA8B,CAClC,KAAM,QACN,QAAAE,EACA,QAASsB,EAAW,QACpB,YAAaC,EAAY,IAAKpB,IAAgB,CAC5C,MAAOA,EAAW,MAClB,KAAMA,EAAW,KACjB,GAAIA,EAAW,GACf,QAASA,EAAW,OAAS,OAC7B,MAAOA,EAAW,OAAS,KAC3B,MAAOA,EAAW,KACpB,EAAE,CACJ,EACA,OAAON,GAAwBC,CAAS,CAC1C",
|
|
6
|
-
"names": ["JourneyError", "code", "message", "details", "cause", "isJourneyError", "value", "eventWorkKey", "from", "event", "describeTransition", "transition", "transitionInfo", "SUCCESS_ASYNC", "LOADING_ASYNC", "hasOwn", "target", "key", "reportListenerError", "error", "
|
|
3
|
+
"sources": ["../src/core/errors.ts", "../src/core/helpers.ts", "../src/core/machine.ts", "../src/internal/dev.ts", "../../../node_modules/.pnpm/@rxova+ts-utils@0.2.1_react@19.3.0/node_modules/@rxova/ts-utils/dist/index.js", "../src/core/store.ts", "../src/core/runtime.ts", "../src/plugins/persistence/persistence.helpers.ts", "../src/plugins/persistence/persistence.ts", "../src/linear/linear.ts", "../src/graph/graph.ts", "../src/graph/work.ts", "../src/diagnostics/diagnostics.helpers.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Machine-readable reasons a journey can refuse to build or operate.\n *\n * Closed on purpose: consumers should be able to `switch` over it exhaustively.\n * Adding a member is a minor change; removing or repurposing one is not done\n * within a major.\n */\nexport type JourneyErrorCode =\n /** A definition declared no steps. */\n | \"empty-definition\"\n /** The same step id was declared twice. */\n | \"duplicate-step-id\"\n /** A step id was referenced that the definition does not declare. */\n | \"unknown-step\"\n /** `initial` names a step the definition does not declare. */\n | \"unknown-initial-step\"\n /** A transition's `from` or `to` names a step that does not exist. */\n | \"dangling-transition\"\n /** Two plugins claimed the same `name`. */\n | \"duplicate-plugin-name\"\n /** Persistence was requested but no usable storage could be resolved. */\n | \"storage-unavailable\"\n /** Navigation work's `commit` returned a promise; it must be synchronous. */\n | \"async-commit\"\n /** A transition or work entry declared `label` as something other than a non-empty string. */\n | \"invalid-label\"\n /** A transition or work entry declared `timeoutMs` as something other than a positive finite number. */\n | \"invalid-timeout\";\n\nexport type JourneyErrorDetails = {\n /** The offending step id, where one caused the failure. */\n readonly stepId?: string;\n /** The offending event name, for transition failures. */\n readonly event?: string;\n /** The offending plugin name, for plugin failures. */\n readonly pluginName?: string;\n};\n\n/**\n * Every error core throws itself.\n *\n * Before this existed, distinguishing \"duplicate plugin name\" from \"unknown step\n * in transition\" meant matching on the message text \u2014 which quietly made every\n * message a compatibility promise. `code` is the stable contract; `message` is\n * for humans and may be reworded in any release.\n *\n * Errors surfaced through `NavigationResult.error` and the `error` subscription\n * event stay `unknown`: those carry whatever the caller's own work threw, which\n * core cannot constrain.\n */\nexport class JourneyError extends Error {\n readonly code: JourneyErrorCode;\n readonly stepId: string | undefined;\n readonly event: string | undefined;\n readonly pluginName: string | undefined;\n\n constructor(\n code: JourneyErrorCode,\n message: string,\n details: JourneyErrorDetails = {},\n cause?: unknown,\n ) {\n super(`journey: ${message}`, cause === undefined ? undefined : { cause });\n this.name = \"JourneyError\";\n this.code = code;\n this.stepId = details.stepId;\n this.event = details.event;\n this.pluginName = details.pluginName;\n }\n}\n\n/** Narrowing helper, so consumers need not import the class to test for it. */\nexport const isJourneyError = (value: unknown): value is JourneyError =>\n value instanceof JourneyError;\n", "import type { RuntimeTransition } from \"./runtime.types\";\nimport type { StepAsyncState, TransitionInfo } from \"./types\";\n\n/** Hard cap on events processed from one raise cascade before it is dropped. */\nexport const MAX_RAISED_EVENTS = 25;\n\n/**\n * Key for definition-declared send work. Work belongs to an (origin step,\n * event) pair, not to an event alone \u2014 the same event name can be declared\n * from several steps with different work on each. Length-prefixing the step id\n * keeps the key injective without reserving a separator character.\n */\nexport const eventWorkKey = (from: string, event: string): string =>\n `${from.length}:${from}${event}`;\n\n/**\n * How one edge is named in errors and timeout messages.\n *\n * A declared label wins outright \u2014 that is the point of declaring one. Without\n * it the fallback still has to distinguish candidates that share an event and\n * a target and differ only by guard, so it carries the declaration index:\n * `submit[1] (login -> twofa)`.\n */\nexport const describeTransition = (transition: RuntimeTransition): string =>\n transition.label ??\n `${transition.event}[${transition.index}] (${transition.from} -> ${transition.to})`;\n\n/**\n * The public, generics-free view of an edge handed to step hooks. Built once\n * per navigation and shared by the three hooks it runs \u2014 and left unfrozen,\n * like the hook args it rides on, since it does not outlive them.\n */\nexport const transitionInfo = (transition: RuntimeTransition | null): TransitionInfo | null =>\n transition === null\n ? null\n : {\n event: transition.event,\n from: transition.from,\n to: transition.to,\n label: transition.label ?? null,\n index: transition.index,\n };\n\nexport const SUCCESS_ASYNC: StepAsyncState = Object.freeze({\n isLoading: false,\n isSuccess: true,\n isError: false,\n error: null,\n});\n\nexport const LOADING_ASYNC: StepAsyncState = Object.freeze({\n isLoading: true,\n isSuccess: false,\n isError: false,\n error: null,\n});\n\n/**\n * Own-property membership, for every guard that asks \"is this a declared id?\".\n *\n * `in` walks the prototype chain, so `\"toString\" in steps` is true for any\n * object literal. Using it to validate step ids let `toString`, `constructor`,\n * `__proto__`, `hasOwnProperty` and friends pass as declared steps \u2014 including\n * ids arriving from a persisted record or a route parameter, which are not\n * developer-authored. Own-property checks are the only correct test here.\n */\nexport const hasOwn = (target: object, key: string): boolean => Object.hasOwn(target, key);\n\n/** Subscriber exceptions are isolated so one listener cannot break the pipeline. */\nexport function reportListenerError(error: unknown): void {\n console.error(\"[journey] subscriber threw:\", error);\n}\n", "import type { JourneyRuntime } from \"./runtime\";\nimport type { AnyNavigationWork } from \"./runtime.types\";\nimport type {\n ContextUpdater,\n JourneyEventPayloads,\n JourneyMachineBase,\n JourneySubscriptionEvent,\n Unsubscribe,\n} from \"./types\";\n\n/**\n * Builds the stable machine surface over a runtime. The object (and every\n * nested group) is created once \u2014 all changing state lives in the snapshot.\n */\nexport function buildMachineSurface(\n runtime: JourneyRuntime,\n): JourneyMachineBase<unknown, string> & { plugins: Readonly<Record<string, unknown>> } {\n return {\n getSnapshot: () => runtime.store.getSnapshot(),\n controls: {\n start: () => runtime.start(),\n pause: () => runtime.pause(),\n resume: () => runtime.resume(),\n complete: (payload?: unknown) => runtime.complete(payload),\n terminate: (payload?: unknown) => runtime.terminate(payload),\n restart: () => runtime.restart(),\n },\n dispose: () => runtime.dispose(),\n navigate: {\n goToStepById: (id: string) => runtime.goToStepById(id),\n goToPreviousStep: (n?: number) => runtime.goToPreviousStep(n),\n goToNextStep: (work) => runtime.goToNextStep(work as AnyNavigationWork | undefined),\n goToLastVisitedStep: () => runtime.goToLastVisitedStep(),\n },\n subscriptions: {\n subscribe: (listener: () => void): Unsubscribe => runtime.store.subscribe(listener),\n subscribeEvent: <TEvent extends JourneySubscriptionEvent>(\n event: TEvent,\n listener: (payload: JourneyEventPayloads<unknown, string>[TEvent]) => void,\n ): Unsubscribe => runtime.store.subscribeEvent(event, listener),\n },\n context: {\n update: (updater: ContextUpdater<unknown>) => runtime.updateContext(updater),\n },\n async: {\n clearError: () => runtime.clearAsyncError(),\n },\n plugins: runtime.pluginApis,\n };\n}\n", "/**\n * Developer diagnostics that must not survive into production.\n *\n * {@link isDevelopmentEnvironment} asks *\"should I print a developer\n * warning?\"* and is **permissive**: an unset `NODE_ENV` counts as development,\n * because an unconfigured environment is someone's machine and the cost of a\n * stray warning there is far lower than the cost of a silently swallowed one.\n * `NODE_ENV=test` is not development, so test runs stay quiet unless a test\n * opts in through `__DEV__`.\n *\n * Kept here rather than taken from `@rxova/ts-utils`: its `isDevelopment`\n * treats `NODE_ENV=test` as development and reads `process.env.NODE_ENV`\n * literally, which a consumer's bundler rewrites. This reads it through\n * `globalThis`, as the shipped builds always have.\n */\n\ntype DiagnosticGlobal = typeof globalThis & {\n __DEV__?: unknown;\n process?: {\n env?: {\n NODE_ENV?: string;\n };\n };\n};\n\n/**\n * Reports whether developer-facing diagnostics should be emitted.\n *\n * A boolean `__DEV__` global wins outright \u2014 bundlers inline it, and test\n * suites set it to exercise warning paths that `NODE_ENV=test` would otherwise\n * suppress. Otherwise an unset or `\"development\"` `NODE_ENV` is development,\n * and anything else (including `\"test\"` and `\"production\"`) is not.\n *\n * @returns `true` when warnings and errors should reach the console.\n */\nexport const isDevelopmentEnvironment = (): boolean => {\n const diagnosticGlobal = globalThis as DiagnosticGlobal;\n if (typeof diagnosticGlobal.__DEV__ === \"boolean\") {\n return diagnosticGlobal.__DEV__;\n }\n\n const nodeEnv = diagnosticGlobal.process?.env?.NODE_ENV;\n return nodeEnv === undefined || nodeEnv === \"development\";\n};\n\n/**\n * Logs a warning, but only where {@link isDevelopmentEnvironment} holds.\n *\n * The `detail` argument is forwarded as a second console argument rather than\n * interpolated, so objects stay inspectable in devtools instead of collapsing\n * to `[object Object]`. Omitting it logs the message alone, avoiding a trailing\n * `undefined` in the output.\n *\n * @param message - The warning text.\n * @param detail - Optional structured context to log alongside the message.\n */\nexport const warnInDevelopment = (message: string, detail?: unknown): void => {\n if (!isDevelopmentEnvironment() || typeof console === \"undefined\") {\n return;\n }\n\n if (detail === undefined) {\n console.warn(message);\n return;\n }\n\n // `message` goes through a constant `%s` rather than standing as the format\n // string itself: callers build it by interpolation, so a `%` in an\n // interpolated value would otherwise be read as a directive and consume\n // `detail`.\n console.warn(\"%s\", message, detail);\n};\n", "import { i as isDevelopment, n as canUseDOM, r as createDevWarner, t as matchMediaList } from \"./match-media-list-C1t1r7On.js\";\n//#region src/predicates/is-object-like.ts\n/**\n* Any non-null object: arrays, class instances and null-prototype bags\n* included. The `typeof value === 'object' && value !== null` check, named.\n* Safe to read a property off, nothing more.\n*/\nconst isObjectLike = (value) => typeof value === \"object\" && value !== null;\n//#endregion\n//#region src/predicates/is-record.ts\n/**\n* A non-null, non-array object, indexable by string key. Class instances pass;\n* reach for {@link isPlainObject} when a `Date` or a `Map` must not.\n*/\nconst isRecord = (value) => isObjectLike(value) && !Array.isArray(value);\n//#endregion\n//#region src/predicates/is-plain-object.ts\n/**\n* A plain data object: an object literal, a `JSON.parse` result, or an\n* `Object.create(null)` bag. Arrays and class instances are rejected, because\n* key-wise iteration silently mangles them.\n*/\nconst isPlainObject = (value) => {\n\tif (!isRecord(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n};\n//#endregion\n//#region src/safe/try-read.ts\n/**\n* Reads a property, reporting whether the read itself succeeded. Code that\n* inspects a value it does not own must not replace the problem it is\n* reporting with a new one raised by a getter or a revoked proxy.\n*/\nconst tryRead = (value, key) => {\n\ttry {\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: Reflect.get(value, key)\n\t\t};\n\t} catch {\n\t\treturn { ok: false };\n\t}\n};\n//#endregion\n//#region src/safe/read-property.ts\n/** Reads a property, treating an inaccessible one as absent. */\nconst readProperty = (value, key) => tryRead(value, key).value;\n//#endregion\n//#region src/safe/read-string.ts\n/** Reads a string property, treating an inaccessible or differently typed one as absent. */\nconst readString = (value, key) => {\n\tconst property = readProperty(value, key);\n\treturn typeof property === \"string\" ? property : void 0;\n};\n//#endregion\n//#region src/safe/has-property.ts\n/** `key in value`, without letting a proxy's `has` trap escape. */\nconst hasProperty = (value, key) => {\n\ttry {\n\t\treturn Reflect.has(value, key);\n\t} catch {\n\t\treturn false;\n\t}\n};\n//#endregion\n//#region src/safe/safe-keys.ts\n/** Enumerable own keys, or none when a proxy refuses inspection. */\nconst safeKeys = (value) => {\n\ttry {\n\t\treturn Object.keys(value);\n\t} catch {\n\t\treturn [];\n\t}\n};\n//#endregion\n//#region src/safe/is-instance-of.ts\n/** `instanceof`, without letting a proxy or a custom `Symbol.hasInstance` escape. */\nconst isInstanceOf = (value, constructor) => {\n\ttry {\n\t\treturn value instanceof constructor;\n\t} catch {\n\t\treturn false;\n\t}\n};\n//#endregion\n//#region src/safe/object-tag.ts\n/**\n* The `[object Tag]` string, which survives realms where `instanceof` does not:\n* a `Map` from an iframe is not `instanceof Map` here, but its tag is still\n* `[object Map]`. Undefined when even that is refused.\n*/\nconst objectTag = (value) => {\n\ttry {\n\t\treturn Object.prototype.toString.call(value);\n\t} catch {\n\t\treturn;\n\t}\n};\n//#endregion\n//#region src/safe/array-items.ts\n/** A snapshot of an array before walking it, or undefined for anything else. */\nconst arrayItems = (value) => {\n\ttry {\n\t\treturn Array.isArray(value) ? Array.from(value) : void 0;\n\t} catch {\n\t\treturn;\n\t}\n};\n//#endregion\n//#region src/errors/is-error.ts\n/**\n* A real `Error`, from this realm or another. An object that merely has a\n* `message` is not one: that looser shape is a policy some callers want and\n* others must not have, so it stays with them.\n*/\nconst isError = (value) => isInstanceOf(value, Error) || isObjectLike(value) && objectTag(value) === \"[object Error]\";\n//#endregion\n//#region src/errors/error-message.ts\n/**\n* The message to show for anything thrown. An `Error` gives its `message`, a\n* string is its own message, and anything else goes through `String()`, which\n* can itself throw \u2014 a null-prototype object has no `toString` \u2014 so that falls\n* back to the object's tag rather than escaping the handler it runs in.\n*/\nconst errorMessage = (value) => {\n\tif (typeof value === \"string\") return value;\n\tif (isError(value)) return readString(value, \"message\") ?? \"\";\n\ttry {\n\t\treturn String(value);\n\t} catch {\n\t\treturn objectTag(value) ?? \"Unknown error\";\n\t}\n};\n//#endregion\n//#region src/equality/shallow-equal.ts\n/**\n* `Object.is` for primitives and identical references; otherwise both sides\n* must be objects of the same kind (array or not) holding the same own\n* enumerable keys, each `Object.is`-equal.\n*\n* The own-key check is load-bearing: comparing key counts and values alone\n* calls `{ a: undefined }` and `{ b: undefined }` equal, because both read\n* `undefined` at every key compared.\n*/\nconst shallowEqual = (a, b) => {\n\tif (Object.is(a, b)) return true;\n\tif (typeof a !== \"object\" || a === null || typeof b !== \"object\" || b === null) return false;\n\tif (Array.isArray(a) !== Array.isArray(b)) return false;\n\tconst left = a;\n\tconst right = b;\n\tconst keys = Object.keys(left);\n\tif (keys.length !== Object.keys(right).length) return false;\n\treturn keys.every((key) => Object.hasOwn(right, key) && Object.is(left[key], right[key]));\n};\n//#endregion\n//#region src/freeze/deep-freeze.ts\n/**\n* Freezes a value and everything reachable from it, and returns it.\n*\n* Typed arrays and DataViews are left alone, because freezing a non-empty one\n* throws. A Map or Set cannot have its entries locked \u2014 `map.set()` still works\n* after `Object.freeze` \u2014 but the keys and values it holds are frozen. The value\n* is frozen before its children, so a reference cycle ends at the `isFrozen`\n* check instead of looping.\n*/\nconst deepFreeze = (value) => {\n\tif (typeof value !== \"object\" || value === null || Object.isFrozen(value)) return value;\n\tif (ArrayBuffer.isView(value)) return value;\n\tObject.freeze(value);\n\tif (value instanceof Map) for (const [key, entry] of value) {\n\t\tdeepFreeze(key);\n\t\tdeepFreeze(entry);\n\t}\n\telse if (value instanceof Set) for (const entry of value) deepFreeze(entry);\n\telse for (const key of Object.keys(value)) deepFreeze(value[key]);\n\treturn value;\n};\n//#endregion\n//#region src/number/clamp.ts\n/**\n* `value` held within `[min, max]`. NaN stays NaN, so a bad input is visible\n* rather than silently becoming a bound. A range whose ends are reversed is a\n* bug at the call site, so it throws instead of picking one.\n*/\nconst clamp = (value, min, max) => {\n\tif (min > max) throw new RangeError(`clamp: min ${String(min)} is above max ${String(max)}`);\n\treturn Math.min(max, Math.max(min, value));\n};\n//#endregion\n//#region src/env/is-non-production.ts\nconst ambientNodeEnv = () => {\n\ttry {\n\t\treturn process.env.NODE_ENV;\n\t} catch {\n\t\treturn;\n\t}\n};\n/**\n* Whether the environment has positively said it is not production \u2014 the\n* question to ask before switching on something with a runtime cost, such as a\n* devtools bridge.\n*\n* Conservative where `isDevelopment` is permissive: a bundler's `PROD === true`\n* says no and `DEV === true` says yes; otherwise a string `NODE_ENV` decides\n* (anything but `production` is yes); and when nothing answers, the answer is\n* **no**, because an environment that never said it was safe is treated as a\n* shipped app. Permissive for output, conservative for behaviour.\n*\n* Passing `nodeEnv`, even as `undefined`, means \"I have looked\": the ambient\n* `process.env.NODE_ENV` is not read.\n*/\nconst isNonProduction = (options = {}) => {\n\tconst { bundlerEnv } = options;\n\tif (isObjectLike(bundlerEnv)) {\n\t\tif (bundlerEnv.PROD === true) return false;\n\t\tif (bundlerEnv.DEV === true) return true;\n\t}\n\tconst nodeEnv = \"nodeEnv\" in options ? options.nodeEnv : ambientNodeEnv();\n\treturn typeof nodeEnv === \"string\" && nodeEnv !== \"production\";\n};\n//#endregion\n//#region src/errors/is-error-like.ts\n/**\n* Anything shaped like an error: an object whose `message` is a string. Looser\n* than `isError` on purpose \u2014 a plain `{ message }` from JSON, a DOMException\n* from another realm and an error-like from a library that does not extend\n* `Error` all pass. A getter or proxy that throws on `message` makes it false\n* rather than making the check throw.\n*\n* Narrowed to `Error` because that is what callers read off it (`message`, and\n* optionally `name`, `stack`, `cause`); only `message` is guaranteed.\n*/\nconst isErrorLike = (value) => isObjectLike(value) && typeof readProperty(value, \"message\") === \"string\";\n//#endregion\n//#region src/internal/random/notified-fallbacks.ts\n/**\n* The `onFallback` callbacks `randomHex` has already called. Weak, so a\n* callback created per call is not kept alive by having been notified once.\n*/\nconst notifiedFallbacks = /* @__PURE__ */ new WeakSet();\n//#endregion\n//#region src/internal/random/to-hex.ts\n/** One byte as two lowercase hex digits. */\nconst toHex = (byte) => byte.toString(16).padStart(2, \"0\");\n//#endregion\n//#region src/random/random-hex.ts\n/**\n* `bytes` random bytes as lowercase hex, so the string is `2 * bytes` long.\n*\n* `crypto.getRandomValues`, deliberately, not `crypto.randomUUID`: `randomUUID`\n* exists only in secure contexts, so it is undefined on a plain-http origin (an\n* intranet app, a LAN staging box), while `getRandomValues` works there, in\n* workers, Node, Deno and Bun. Where even that is missing (an exotic host with\n* no polyfill) the bytes come from `Math.random` rather than the call throwing,\n* and `onFallback` is told once, because an id that quietly stops being\n* unpredictable is worse than one that says so.\n*\n* `getRandomValues` fills at most 65,536 bytes per call; ids never come close.\n*/\nconst randomHex = (bytes, { onFallback } = {}) => {\n\tif (!Number.isInteger(bytes) || bytes < 0) throw new RangeError(`randomHex: bytes must be a non-negative integer, got ${String(bytes)}`);\n\tconst crypto = globalThis.crypto;\n\tif (typeof crypto?.getRandomValues === \"function\") return Array.from(crypto.getRandomValues(new Uint8Array(bytes)), toHex).join(\"\");\n\tif (onFallback !== void 0 && !notifiedFallbacks.has(onFallback)) {\n\t\tnotifiedFallbacks.add(onFallback);\n\t\tonFallback();\n\t}\n\treturn Array.from({ length: bytes }, () => toHex(Math.floor(Math.random() * 256))).join(\"\");\n};\n//#endregion\n//#region src/internal/string/html-entities.ts\n/** The five characters `escapeHtml` replaces, and what each becomes. */\nconst HTML_ENTITIES = {\n\t\"&\": \"&\",\n\t\"<\": \"<\",\n\t\">\": \">\",\n\t\"\\\"\": \""\",\n\t\"'\": \"'\"\n};\n//#endregion\n//#region src/string/escape-html.ts\n/**\n* Text made safe to put between tags or inside a quoted attribute, in HTML and\n* in XML alike: `& < > \" '` become entities, everything else is left as it is.\n* The apostrophe is `'` rather than `'`, which HTML 4 lacks.\n*\n* Not a sanitizer: it does not make a value safe inside a `<script>`, a\n* `style`, an unquoted attribute or a URL attribute that may hold\n* `javascript:`.\n*/\nconst escapeHtml = (value) => value.replace(/[&<>\"']/g, (char) => HTML_ENTITIES[char]);\n//#endregion\n//#region src/dom/prefers-reduced-motion.ts\n/**\n* Whether the user asked the system for less motion, read once, now. False on\n* the server and where `matchMedia` is missing (jsdom leaves it out), so the\n* default is the animated path a page was designed with.\n*\n* For a value that follows the setting while a component is mounted, use\n* `useMediaQuery('(prefers-reduced-motion: reduce)')` from `@rxova/ts-utils/react`.\n*/\nconst prefersReducedMotion = () => matchMediaList(\"(prefers-reduced-motion: reduce)\")?.matches ?? false;\n//#endregion\nexport { arrayItems, canUseDOM, clamp, createDevWarner, deepFreeze, errorMessage, escapeHtml, hasProperty, isDevelopment, isError, isErrorLike, isInstanceOf, isNonProduction, isObjectLike, isPlainObject, isRecord, objectTag, prefersReducedMotion, randomHex, readProperty, readString, safeKeys, shallowEqual, tryRead };\n", "import { reportListenerError } from \"./helpers\";\nimport type {\n JourneyEventPayloads,\n JourneySnapshot,\n JourneySubscriptionEvent,\n Unsubscribe,\n} from \"./types\";\n\n/**\n * Snapshot holder + subscription hub. Snapshots are immutable and rebuilt by\n * the runtime; the store only distributes them.\n */\nexport class JourneyStore<TContext, TStepId extends string> {\n private snapshot: JourneySnapshot<TContext, TStepId>;\n private readonly listeners = new Set<() => void>();\n private readonly eventListeners = new Map<\n JourneySubscriptionEvent,\n Set<(payload: never) => void>\n >();\n private disposed = false;\n private readonly onListenerError: ((error: unknown) => void) | undefined;\n\n constructor(\n initial: JourneySnapshot<TContext, TStepId>,\n onListenerError?: (error: unknown) => void,\n ) {\n this.snapshot = initial;\n this.onListenerError = onListenerError;\n }\n\n /**\n * Isolation stays unconditional; the configured reporter only routes the\n * report. Internal, but reachable from the runtime so plugin-boundary\n * failures land in the same place as subscriber failures.\n */\n report(error: unknown): void {\n if (!this.onListenerError) {\n reportListenerError(error);\n return;\n }\n try {\n this.onListenerError(error);\n } catch (reporterError) {\n reportListenerError(reporterError);\n }\n }\n\n getSnapshot(): JourneySnapshot<TContext, TStepId> {\n return this.snapshot;\n }\n\n /** Replaces the snapshot and notifies every subscriber. */\n publish(next: JourneySnapshot<TContext, TStepId>): void {\n // Structural sharing upstream returns the previous object verbatim when\n // nothing changed \u2014 such publishes are complete no-ops.\n if (Object.is(this.snapshot, next)) return;\n this.snapshot = next;\n for (const listener of [...this.listeners]) {\n try {\n listener();\n } catch (error) {\n this.report(error);\n }\n }\n }\n\n /**\n * Notifies on every committed snapshot. Deriving a slice and skipping\n * unchanged values is the caller's job \u2014 in React that is `useSelector`,\n * which has to own the comparison anyway to keep render identity stable.\n */\n subscribe(listener: () => void): Unsubscribe {\n if (this.disposed) return () => undefined;\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n subscribeEvent<TEvent extends JourneySubscriptionEvent>(\n event: TEvent,\n listener: (payload: JourneyEventPayloads<TContext, TStepId>[TEvent]) => void,\n ): Unsubscribe {\n if (this.disposed) return () => undefined;\n let listeners = this.eventListeners.get(event);\n if (!listeners) {\n listeners = new Set();\n this.eventListeners.set(event, listeners);\n }\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n }\n\n emit<TEvent extends JourneySubscriptionEvent>(\n event: TEvent,\n payload: JourneyEventPayloads<TContext, TStepId>[TEvent],\n ): void {\n const listeners = this.eventListeners.get(event);\n if (!listeners) return;\n for (const listener of [...listeners]) {\n try {\n (listener as (value: unknown) => void)(payload);\n } catch (error) {\n this.report(error);\n }\n }\n }\n\n dispose(): void {\n this.disposed = true;\n this.listeners.clear();\n this.eventListeners.clear();\n }\n}\n", "import { isDevelopmentEnvironment } from \"../internal/dev\";\nimport { shallowEqual } from \"@rxova/ts-utils\";\nimport { JourneyError } from \"./errors\";\nimport {\n describeTransition,\n eventWorkKey,\n hasOwn,\n LOADING_ASYNC,\n MAX_RAISED_EVENTS,\n SUCCESS_ASYNC,\n transitionInfo,\n} from \"./helpers\";\nimport { JourneyStore } from \"./store\";\nimport type {\n AnyHookArgs,\n AnyNavigationWork,\n AnyOnEffect,\n AnySendWork,\n AnySendWorkArgs,\n NavigationFailure,\n RuntimeConfig,\n RuntimeTransition,\n TimelineOp,\n TransitionListener,\n WorkDirection,\n} from \"./runtime.types\";\nimport type {\n ContextUpdater,\n CurrentStepBase,\n JourneyEventObject,\n GraphTransitionSnapshot,\n JourneyOutcome,\n JourneySnapshot,\n JourneyStatus,\n NavigationResult,\n PluginHost,\n StepAsyncState,\n StepEnterDirection,\n TransitionInfo,\n} from \"./types\";\n\n/**\n * Dev-only shallow freeze of the context.\n *\n * Every other snapshot slice is frozen, so an unfrozen context is a surprising\n * gap: mutating it in place changes nothing the machine can observe \u2014 no\n * publish, no re-render, no subscriber \u2014 and the bug is silent. Freezing turns\n * it into a throw where it happens.\n *\n * Shallow, matching how the rest of the snapshot is frozen; deep-freezing would\n * cost a full walk per update and break Maps, Dates, and class instances that\n * legitimately live in a context. Development only, so production pays nothing.\n */\nconst freezeContextInDevelopment = <T>(context: T): T =>\n typeof context === \"object\" && context !== null && isDevelopmentEnvironment()\n ? Object.freeze(context)\n : context;\n\nconst EMPTY_METADATA: Readonly<Record<string, unknown>> = Object.freeze({});\nconst EMPTY_PLUGINS: Readonly<Record<string, unknown>> = Object.freeze({});\n\n/** Freezes and returns the rebuilt sub-object, or the previous one when content-equal. */\nconst shared = <T extends object>(next: T, previous: T | null | undefined): T =>\n previous != null && shallowEqual(next, previous) ? previous : Object.freeze(next);\n\n/** Reuses the previous frozen array when elements are pairwise equal. */\nconst sharedArray = <T>(\n next: readonly T[],\n previous: readonly T[] | undefined,\n equal: (a: T, b: T) => boolean = Object.is,\n): readonly T[] =>\n previous !== undefined &&\n previous.length === next.length &&\n next.every((item, index) => equal(item, previous[index] as T))\n ? previous\n : Object.freeze<readonly T[]>([...next]);\n\nconst getGraphGuardState = (\n guard: RuntimeTransition[\"when\"],\n enabled: boolean,\n): GraphTransitionSnapshot<string, string>[\"guard\"] => {\n if (guard === undefined) return \"none\";\n return enabled ? \"passed\" : \"failed\";\n};\n\nexport class JourneyRuntime {\n readonly store: JourneyStore<unknown, string>;\n readonly pluginApis: Record<string, unknown> = {};\n\n private readonly config: RuntimeConfig;\n private status: JourneyStatus = \"idle\";\n private timeline: string[] = [];\n private currentIndex = -1;\n private context: unknown;\n private outcome: JourneyOutcome | null = null;\n private visitCounts = new Map<string, number>();\n private entryAsync: StepAsyncState = SUCCESS_ASYNC;\n private pending: {\n phase: \"working\" | \"leaving\" | \"entering\";\n from: string | null;\n /** Null while a graph send runs its work: the target is not resolved yet. */\n to: string | null;\n } | null = null;\n private disposed = false;\n /** One-shot seed for the first start(); restart() always enters fresh. */\n private restoreSeed: RuntimeConfig[\"restore\"] | null = null;\n /** Bumped by terminate/restart/dispose so stale hook continuations bail out. */\n private generation = 0;\n private raiseQueue: JourneyEventObject[] = [];\n private processingRaised = false;\n private lastPluginExtensions: Readonly<Record<string, unknown>> = {};\n /** The last built snapshot \u2014 the sharing baseline for buildSnapshot(). */\n private lastSnapshot: JourneySnapshot | null = null;\n private readonly frozenStepOrder: readonly string[];\n /**\n * Per-step registration stacks, innermost last. Resolution is last-wins, but\n * a stack (rather than a single slot) is what lets an unregister restore the\n * registration it shadowed \u2014 two owners guarding one step is the normal case\n * for component-scoped wrappers, and dropping to \"ungated\" when the newer one\n * unmounts would fail silently.\n */\n private readonly transitionListeners = new Set<TransitionListener>();\n private readonly disposeCallbacks: (() => void)[] = [];\n private readonly snapshotDerivers = new Map<\n string,\n (snapshot: JourneySnapshot, previous: unknown) => unknown\n >();\n\n constructor(config: RuntimeConfig) {\n this.config = config;\n this.frozenStepOrder = Object.freeze<readonly string[]>([...config.stepIds]);\n this.restoreSeed = config.restore ?? null;\n this.context = freezeContextInDevelopment(\n config.restore ? config.restore.context : config.initialContext,\n );\n this.store = new JourneyStore(this.buildSnapshot(), config.onListenerError);\n this.setupPlugins();\n this.store.publish(this.buildSnapshot());\n if (config.autoStart) this.start();\n }\n\n // \u2500\u2500 lifecycle \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n start(): boolean {\n if (this.disposed || this.status !== \"idle\") return false;\n this.setStatus(\"running\");\n void this.enterInitialStep();\n return true;\n }\n\n pause(): boolean {\n if (this.disposed || this.status !== \"running\" || this.pending) return false;\n this.setStatus(\"paused\");\n return true;\n }\n\n resume(): boolean {\n if (this.disposed || this.status !== \"paused\") return false;\n this.setStatus(\"running\");\n return true;\n }\n\n complete(payload?: unknown): boolean {\n if (this.disposed || this.status !== \"running\" || this.pending) return false;\n this.outcome = Object.freeze({ type: \"completed\", payload });\n this.setStatus(\"completed\");\n return true;\n }\n\n terminate(payload?: unknown): boolean {\n if (this.disposed || this.status === \"terminated\") return false;\n this.generation += 1;\n this.pending = null;\n this.entryAsync = SUCCESS_ASYNC;\n this.raiseQueue = [];\n this.outcome = Object.freeze({ type: \"terminated\", payload });\n this.setStatus(\"terminated\");\n return true;\n }\n\n restart(): boolean {\n if (this.disposed || (this.status !== \"completed\" && this.status !== \"terminated\")) {\n return false;\n }\n this.generation += 1;\n this.pending = null;\n this.raiseQueue = [];\n this.timeline = [];\n this.currentIndex = -1;\n this.context = freezeContextInDevelopment(this.config.initialContext);\n this.outcome = null;\n this.visitCounts = new Map();\n this.entryAsync = SUCCESS_ASYNC;\n this.setStatus(\"running\");\n void this.enterInitialStep();\n return true;\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.generation += 1;\n this.pending = null;\n this.raiseQueue = [];\n for (const callback of this.disposeCallbacks.splice(0)) {\n try {\n callback();\n } catch {\n // dispose callbacks must never break teardown\n }\n }\n this.transitionListeners.clear();\n this.store.dispose();\n }\n\n // \u2500\u2500 context \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n updateContext(updater: ContextUpdater<unknown>): void {\n if (this.disposed) return;\n const previous = this.context;\n this.context = freezeContextInDevelopment(updater(previous));\n const snapshot = this.publish();\n this.store.emit(\"contextChange\", { snapshot, previous, current: this.context });\n }\n\n clearAsyncError(): void {\n if (this.disposed || !this.entryAsync.isError) return;\n this.entryAsync = SUCCESS_ASYNC;\n this.publish();\n }\n\n // \u2500\u2500 navigation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n goToStepById(id: string): Promise<NavigationResult> {\n const rejected = this.checkNavigable();\n if (rejected) return this.blocked(rejected, id);\n if (!hasOwn(this.config.steps, id))\n return this.blocked({ ok: false, reason: \"invalid-target\" }, id);\n if (id === this.currentStepId()) return this.blocked({ ok: false, reason: \"no-op\" }, id);\n\n if (this.config.kind === \"graph\") {\n const transition = this.config.transitions.find(\n (candidate) =>\n candidate.from === this.currentStepId() &&\n candidate.to === id &&\n this.isEnabled(candidate),\n );\n if (!transition) return this.blocked({ ok: false, reason: \"invalid-target\" }, id);\n return this.runNavigation(id, { kind: \"append\" }, this.eventFor(transition), transition);\n }\n return this.runNavigation(id, { kind: \"append\" }, null, null);\n }\n\n goToPreviousStep(n = 1): Promise<NavigationResult> {\n const rejected = this.checkNavigable();\n if (rejected) return this.blocked(rejected, null);\n if (this.currentIndex <= 0) return this.blocked({ ok: false, reason: \"out-of-bounds\" }, null);\n const index = Math.max(0, this.currentIndex - Math.max(1, Math.floor(n)));\n const target = this.timeline[index] as string;\n return this.runNavigation(\n target,\n { kind: \"pointer\", index },\n null,\n null,\n undefined,\n \"backward\",\n );\n }\n\n goToNextStep(work?: AnyNavigationWork): Promise<NavigationResult> {\n const rejected = this.checkNavigable();\n if (rejected) return this.blocked(rejected, null);\n if (this.currentIndex < this.timeline.length - 1) {\n const index = this.currentIndex + 1;\n const target = this.timeline[index] as string;\n return this.runNavigation(target, { kind: \"pointer\", index }, null, null, work, \"forward\");\n }\n if (this.config.kind === \"linear\") {\n const orderIndex = this.config.stepIds.indexOf(this.currentStepId() ?? \"\");\n const target = this.config.stepIds[orderIndex + 1];\n if (target === undefined) return this.blocked({ ok: false, reason: \"out-of-bounds\" }, null);\n return this.runNavigation(target, { kind: \"append\" }, null, null, work, \"forward\");\n }\n return this.blocked({ ok: false, reason: \"out-of-bounds\" }, null);\n }\n\n goToLastVisitedStep(): Promise<NavigationResult> {\n const rejected = this.checkNavigable();\n if (rejected) return this.blocked(rejected, null);\n const tip = this.timeline.length - 1;\n if (this.currentIndex >= tip) return this.blocked({ ok: false, reason: \"no-op\" }, null);\n const target = this.timeline[tip] as string;\n return this.runNavigation(target, { kind: \"pointer\", index: tip }, null, null);\n }\n\n /** Linear-only: declared-order index navigation, delegating to `goToStepById`. */\n goToStepByIndex(index: number): Promise<NavigationResult> {\n const target = Number.isInteger(index) ? this.config.stepIds[index] : undefined;\n if (target === undefined) {\n return this.blocked({ ok: false, reason: \"invalid-target\" }, null);\n }\n return this.goToStepById(target);\n }\n\n /** Graph-only primary verb; also drives raised events. */\n send(type: string, payload?: unknown, work?: AnySendWork): Promise<NavigationResult> {\n const rejected = this.checkNavigable();\n if (rejected) return this.blocked(rejected, null);\n const event: JourneyEventObject = payload === undefined ? { type } : { type, payload };\n\n const from = this.currentStepId();\n const declaredWork =\n work ?? (from === null ? undefined : this.config.eventWork?.[eventWorkKey(from, type)]);\n if (declaredWork) return this.sendWithWork(type, event, declaredWork);\n\n const transition = this.resolveTransition(type);\n if (!transition) {\n return this.blocked({ ok: false, reason: \"no-enabled-transition\" }, null);\n }\n return this.runNavigation(transition.to, { kind: \"append\" }, event, transition);\n }\n\n /**\n * Work-carrying send: the async runs *before* routing, so its `commit` can\n * stage the very context the guards are then evaluated against. Guards stay\n * sync and pure \u2014 the work supplies facts, the definition still picks the\n * edge.\n *\n * The machine holds its position for the whole `working` phase (`pending.to`\n * is null: there is no target yet). If no candidate is enabled once the\n * context is staged, the staged context is discarded and nothing is\n * published \u2014 either the send routed and committed, or neither happened.\n */\n private async sendWithWork(\n type: string,\n event: JourneyEventObject,\n work: AnySendWork,\n ): Promise<NavigationResult> {\n const generation = this.generation;\n const from = this.currentStepId();\n if (from === null) return this.blocked({ ok: false, reason: \"not-running\" }, null);\n\n let stagedContext = this.context;\n let contextWasUpdated = false;\n let result: unknown;\n\n this.pending = { phase: \"working\", from, to: null };\n this.entryAsync = LOADING_ASYNC;\n this.publish();\n\n try {\n const args: AnySendWorkArgs = {\n snapshot: this.store.getSnapshot(),\n from,\n event,\n handlers: this.config.handlers,\n };\n result = await this.withTimeout(\n Promise.resolve(work.run(args)),\n `send work(${work.label ?? `${type} from ${from}`})`,\n work.timeoutMs,\n );\n if (!this.isCurrent(generation)) return this.staleResult();\n const commitResult = (work.commit as ((value: unknown) => unknown) | undefined)?.({\n ...args,\n result,\n updateContext: (updater: ContextUpdater<unknown>) => {\n stagedContext = updater(stagedContext);\n contextWasUpdated = true;\n },\n });\n if (typeof commitResult === \"object\" && commitResult !== null && \"then\" in commitResult) {\n throw new JourneyError(\"async-commit\", \"send work commit must be synchronous\");\n }\n } catch (error) {\n if (!this.isCurrent(generation)) return this.staleResult();\n this.pending = null;\n this.entryAsync = Object.freeze({\n isLoading: false,\n isSuccess: false,\n isError: true,\n error,\n });\n const snapshot = this.publish();\n this.store.emit(\"error\", { snapshot, error, phase: \"work\", stepId: from });\n return this.blocked({ ok: false, reason: \"error\", error }, null);\n }\n\n if (!this.isCurrent(generation)) return this.staleResult();\n\n // Route against the staged context, not the committed one. The run result is\n // passed along too, but guard types expose only context and handlers: a\n // routing fact reaches them through what `commit` staged.\n const transition = this.resolveTransition(type, stagedContext, result);\n if (!transition) {\n // Roll back: the staged context is dropped along with the move.\n this.pending = null;\n this.entryAsync = SUCCESS_ASYNC;\n this.publish();\n return this.blocked({ ok: false, reason: \"no-enabled-transition\" }, null);\n }\n\n return this.commitAndSettle(\n from,\n transition.to,\n { kind: \"append\" },\n event,\n transition,\n generation,\n stagedContext,\n contextWasUpdated,\n \"jump\",\n );\n }\n\n // \u2500\u2500 plugin host \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private setupPlugins(): void {\n const host: PluginHost = {\n getSnapshot: () => this.store.getSnapshot(),\n structure: Object.freeze({\n kind: this.config.kind,\n stepIds: Object.freeze<readonly string[]>([...this.config.stepIds]),\n initial: this.config.initial,\n transitions: Object.freeze(\n this.config.transitions.map((transition) =>\n Object.freeze({\n event: transition.event,\n from: transition.from,\n to: transition.to,\n guarded: transition.when !== undefined,\n label: transition.label ?? null,\n index: transition.index,\n }),\n ),\n ),\n }),\n onTransition: (callback) => {\n this.transitionListeners.add(callback);\n return () => this.transitionListeners.delete(callback);\n },\n onNavigationBlocked: (callback) => this.store.subscribeEvent(\"navigationBlocked\", callback),\n onStatusChange: (callback) => this.store.subscribeEvent(\"statusChange\", callback),\n onContextChange: (callback) => this.store.subscribeEvent(\"contextChange\", callback),\n onError: (callback) => this.store.subscribeEvent(\"error\", callback),\n onDispose: (callback) => {\n this.disposeCallbacks.push(callback);\n },\n reportError: (error) => this.store.report(error),\n };\n // A failure part-way through leaves earlier plugins already subscribed and\n // holding onDispose callbacks \u2014 but the machine is never returned, so\n // dispose() is unreachable and their timers and subscriptions would live\n // for the process lifetime. Tear down before rethrowing, so a rejected\n // construction leaks nothing.\n try {\n for (const plugin of this.config.plugins) {\n if (hasOwn(this.pluginApis, plugin.name)) {\n throw new JourneyError(\n \"duplicate-plugin-name\",\n `duplicate plugin name \"${plugin.name}\"`,\n {\n pluginName: plugin.name,\n },\n );\n }\n const contribution = plugin.setup(host);\n this.pluginApis[plugin.name] = contribution.api;\n if (contribution.deriveSnapshot) {\n this.snapshotDerivers.set(\n plugin.name,\n contribution.deriveSnapshot as (\n snapshot: JourneySnapshot,\n previous: unknown,\n ) => unknown,\n );\n }\n }\n } catch (error) {\n this.dispose();\n throw error;\n }\n }\n\n // \u2500\u2500 internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private currentStepId(): string | null {\n return this.currentIndex >= 0 ? (this.timeline[this.currentIndex] as string) : null;\n }\n\n private eventFor(transition: RuntimeTransition): JourneyEventObject {\n return { type: transition.event };\n }\n\n /**\n * `context` is explicit so a work-carrying `send` can evaluate guards against\n * the context its `commit` just staged, rather than the committed one.\n * `result` is the work's run result during that same routing pass; outside a\n * work send (plain sends, snapshot introspection) guards see it as undefined.\n */\n private isEnabled(\n transition: RuntimeTransition,\n context: unknown = this.context,\n result?: unknown,\n ): boolean {\n if (!transition.when) return true;\n try {\n return transition.when({ context, handlers: this.config.handlers, result });\n } catch {\n return false;\n }\n }\n\n /** First enabled candidate for `event` from the current step, in declaration order. */\n private resolveTransition(\n event: string,\n context: unknown = this.context,\n result?: unknown,\n ): RuntimeTransition | undefined {\n return this.config.transitions.find(\n (candidate) =>\n candidate.event === event &&\n candidate.from === this.currentStepId() &&\n this.isEnabled(candidate, context, result),\n );\n }\n\n private checkNavigable(): NavigationFailure | null {\n if (this.disposed) return { ok: false, reason: \"disposed\" };\n if (this.status !== \"running\") return { ok: false, reason: \"not-running\" };\n if (this.pending) return { ok: false, reason: \"transitioning\" };\n return null;\n }\n\n private setStatus(next: JourneyStatus): void {\n const previous = this.status;\n this.status = next;\n const snapshot = this.publish();\n this.store.emit(\"statusChange\", { snapshot, previous, current: next });\n // Plugin taps may have updated state the snapshot derives from.\n this.refreshPluginSnapshot();\n }\n\n /** Re-derives `snapshot.plugins` after plugin taps ran post-publish. */\n private refreshPluginSnapshot(): void {\n if (this.snapshotDerivers.size > 0) this.publish();\n }\n\n private blocked(failure: NavigationFailure, target: string | null): Promise<NavigationResult> {\n if (failure.reason !== \"disposed\") {\n const payload: {\n snapshot: JourneySnapshot;\n reason: NavigationFailure[\"reason\"];\n from: string | null;\n to: string | null;\n error?: unknown;\n } = {\n snapshot: this.store.getSnapshot(),\n reason: failure.reason,\n from: this.currentStepId(),\n to: target,\n };\n if (\"error\" in failure) payload.error = failure.error;\n this.store.emit(\"navigationBlocked\", payload);\n }\n return Promise.resolve({ ...failure, from: this.currentStepId(), to: target });\n }\n\n private hookArgs(\n from: string | null,\n to: string,\n event: JourneyEventObject | null,\n transition: TransitionInfo | null,\n ): AnyHookArgs {\n return {\n snapshot: this.store.getSnapshot(),\n from,\n to,\n event,\n transition,\n updateContext: (updater) => this.updateContext(updater),\n raise: (raised) => {\n if (this.config.kind !== \"graph\" || this.disposed) return;\n this.raiseQueue.push(raised);\n },\n };\n }\n\n private async invokeEffect(\n effect: AnyOnEffect | undefined,\n args: AnyHookArgs,\n label: string,\n timeoutMs?: number,\n ): Promise<{ error: unknown } | null> {\n if (!effect) return null;\n try {\n await this.withTimeout(Promise.resolve(effect(args)), label, timeoutMs);\n return null;\n } catch (error) {\n return { error };\n }\n }\n\n /**\n * `overrideMs` is the declaring edge's own budget. It wins over\n * `defaultTimeoutMs` so that one slow third-party call does not force every\n * other edge onto the slow one's budget; `undefined` falls back to the\n * global, and a global of `undefined` means no bound at all.\n */\n private withTimeout<T>(promise: Promise<T>, label: string, overrideMs?: number): Promise<T> {\n const ms = overrideMs ?? this.config.defaultTimeoutMs;\n if (ms === undefined) return promise;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new Error(`journey: ${label} timed out after ${ms}ms`)),\n ms,\n );\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (error) => {\n clearTimeout(timer);\n reject(error);\n },\n );\n });\n }\n\n /** Entry on start()/restart(): no onLeave, `from` is null, event is null. */\n private async enterInitialStep(): Promise<void> {\n const generation = this.generation;\n const seed = this.restoreSeed;\n this.restoreSeed = null;\n if (seed) {\n const to = seed.timeline[seed.currentIndex] as string;\n this.pending = { phase: \"entering\", from: null, to };\n this.timeline = [...seed.timeline];\n this.currentIndex = seed.currentIndex;\n // Persisted records carry no visit counts; occurrences in the restored\n // timeline are the best-effort reconstruction. commitEntry adds one more\n // for the re-entered current step, so it reports isFirstTimeVisit: false.\n for (const id of seed.timeline) {\n this.visitCounts.set(id, (this.visitCounts.get(id) ?? 0) + 1);\n }\n this.commitEntry(null, to, \"jump\");\n await this.runEntryEffects(null, to, null, null, generation);\n return;\n }\n const to = this.config.startAt ?? this.config.initial;\n this.pending = { phase: \"entering\", from: null, to };\n this.timeline = [to];\n this.currentIndex = 0;\n this.commitEntry(null, to, \"jump\");\n await this.runEntryEffects(null, to, null, null, generation);\n }\n\n private async runNavigation(\n to: string,\n op: TimelineOp,\n event: JourneyEventObject | null,\n transition: RuntimeTransition | null,\n work?: AnyNavigationWork,\n direction?: WorkDirection,\n ): Promise<NavigationResult> {\n const generation = this.generation;\n const from = this.currentStepId();\n let stagedContext = this.context;\n let contextWasUpdated = false;\n\n if (work && from !== null && direction) {\n this.pending = { phase: \"working\", from, to };\n this.entryAsync = LOADING_ASYNC;\n this.publish();\n\n try {\n const args = {\n snapshot: this.store.getSnapshot(),\n from,\n to,\n direction,\n };\n const result = await this.withTimeout(\n Promise.resolve(work.run(args)),\n `${direction} navigation work(${from} -> ${to})`,\n work.timeoutMs,\n );\n if (!this.isCurrent(generation)) return this.staleResult();\n const commitResult = (work.commit as ((value: unknown) => unknown) | undefined)?.({\n ...args,\n result,\n updateContext: (updater: ContextUpdater<unknown>) => {\n stagedContext = updater(stagedContext);\n contextWasUpdated = true;\n },\n });\n if (typeof commitResult === \"object\" && commitResult !== null && \"then\" in commitResult) {\n throw new JourneyError(\"async-commit\", \"navigation work commit must be synchronous\");\n }\n } catch (error) {\n if (!this.isCurrent(generation)) return this.staleResult();\n this.pending = null;\n this.entryAsync = Object.freeze({\n isLoading: false,\n isSuccess: false,\n isError: true,\n error,\n });\n const snapshot = this.publish();\n this.store.emit(\"error\", { snapshot, error, phase: \"work\", stepId: from });\n return this.blocked({ ok: false, reason: \"error\", error }, to);\n }\n }\n if (!this.isCurrent(generation)) return this.staleResult();\n\n return this.commitAndSettle(\n from,\n to,\n op,\n event,\n transition,\n generation,\n stagedContext,\n contextWasUpdated,\n direction ?? \"jump\",\n );\n }\n\n /**\n * Publishes the position change and any staged context in one snapshot, then\n * awaits the post-commit effects. Shared by plain navigation and by a\n * work-carrying `send`, which reaches here only once its target is resolved.\n */\n private async commitAndSettle(\n from: string | null,\n to: string,\n op: TimelineOp,\n event: JourneyEventObject | null,\n transition: RuntimeTransition | null,\n generation: number,\n stagedContext: unknown,\n contextWasUpdated: boolean,\n direction: StepEnterDirection,\n ): Promise<NavigationResult> {\n const previousContext = this.context;\n if (op.kind === \"pointer\") {\n this.currentIndex = op.index;\n } else {\n this.timeline = [...this.timeline.slice(0, this.currentIndex + 1), to];\n this.currentIndex = this.timeline.length - 1;\n }\n if (contextWasUpdated) this.context = freezeContextInDevelopment(stagedContext);\n const fromStep = from === null ? undefined : this.config.steps[from];\n this.pending = { phase: fromStep?.onLeave ? \"leaving\" : \"entering\", from, to };\n this.commitEntry(\n from,\n to,\n direction,\n contextWasUpdated ? { previous: previousContext, current: stagedContext } : undefined,\n fromStep?.onLeave !== undefined || transition?.onTransition !== undefined,\n );\n\n await this.runEntryEffects(from, to, event, transition, generation);\n return { ok: true, from, to };\n }\n\n /** Shared commit bookkeeping for navigations and the initial entry. */\n private commitEntry(\n from: string | null,\n to: string,\n direction: StepEnterDirection,\n contextChange?: { previous: unknown; current: unknown },\n hasPreEnterEffect = false,\n ): void {\n this.visitCounts.set(to, (this.visitCounts.get(to) ?? 0) + 1);\n const toStep = this.config.steps[to];\n this.entryAsync = hasPreEnterEffect || toStep?.onEnter ? LOADING_ASYNC : SUCCESS_ASYNC;\n const snapshot = this.publish();\n if (contextChange) this.store.emit(\"contextChange\", { snapshot, ...contextChange });\n if (from !== null) this.store.emit(\"stepLeave\", { snapshot, from, to });\n this.store.emit(\"stepEnter\", { snapshot, from, to, direction });\n }\n\n /** Post-commit effects: step `onLeave`, transition effect, then step `onEnter`. */\n private async runEntryEffects(\n from: string | null,\n to: string,\n event: JourneyEventObject | null,\n transition: RuntimeTransition | null,\n generation: number,\n ): Promise<void> {\n const fromStep = from === null ? undefined : this.config.steps[from];\n const toStep = this.config.steps[to];\n const edge = transitionInfo(transition);\n const failures: { error: unknown; phase: \"leave\" | \"enter\" | \"transition\"; stepId: string }[] =\n [];\n\n const leaveFailure = await this.invokeEffect(\n fromStep?.onLeave,\n this.hookArgs(from, to, event, edge),\n `onLeave(${from ?? \"\"})`,\n );\n if (!this.isCurrent(generation)) return;\n if (leaveFailure && from !== null) {\n failures.push({ error: leaveFailure.error, phase: \"leave\", stepId: from });\n }\n\n this.pending = { phase: \"entering\", from, to };\n this.publish();\n\n const transitionFailure = await this.invokeEffect(\n transition?.onTransition,\n this.hookArgs(from, to, event, edge),\n `onTransition(${transition ? describeTransition(transition) : (event?.type ?? \"\")})`,\n transition?.timeoutMs,\n );\n if (!this.isCurrent(generation)) return;\n if (transitionFailure) {\n failures.push({ error: transitionFailure.error, phase: \"transition\", stepId: to });\n }\n\n const enterFailure = await this.invokeEffect(\n toStep?.onEnter,\n this.hookArgs(from, to, event, edge),\n `onEnter(${to})`,\n );\n if (!this.isCurrent(generation)) return;\n if (enterFailure) failures.push({ error: enterFailure.error, phase: \"enter\", stepId: to });\n\n this.entryAsync = failures[0]\n ? Object.freeze({\n isLoading: false,\n isSuccess: false,\n isError: true,\n error: failures[0].error,\n })\n : SUCCESS_ASYNC;\n this.pending = null;\n const snapshot = this.publish();\n for (const failure of failures) {\n this.store.emit(\"error\", {\n snapshot,\n error: failure.error,\n phase: failure.phase,\n stepId: failure.stepId,\n });\n }\n for (const listener of [...this.transitionListeners]) {\n try {\n listener({ from, to, snapshot });\n } catch {\n // plugin taps are isolated\n }\n }\n this.refreshPluginSnapshot();\n void this.processRaisedEvents(generation);\n }\n\n /**\n * Raised events run FIFO after the transition settles; a cascade longer than\n * {@link MAX_RAISED_EVENTS} is dropped and surfaced as an `error` event.\n */\n private async processRaisedEvents(generation: number): Promise<void> {\n if (this.processingRaised || !this.isCurrent(generation)) return;\n this.processingRaised = true;\n let processed = 0;\n try {\n while (this.raiseQueue.length > 0 && this.isCurrent(generation)) {\n if (this.status !== \"running\") {\n this.raiseQueue = [];\n return;\n }\n processed += 1;\n if (processed > MAX_RAISED_EVENTS) {\n this.raiseQueue = [];\n this.store.emit(\"error\", {\n snapshot: this.store.getSnapshot(),\n error: new Error(\n `journey: raised-event cascade exceeded ${MAX_RAISED_EVENTS} events; queue dropped`,\n ),\n phase: \"raise\",\n stepId: this.currentStepId(),\n });\n return;\n }\n const next = this.raiseQueue.shift() as JourneyEventObject;\n // `processingRaised` stays true: the sent event's own settle re-enters\n // processRaisedEvents and must bail so this loop keeps one counter.\n await this.send(next.type, (next as { payload?: unknown }).payload);\n }\n } finally {\n this.processingRaised = false;\n }\n }\n\n private isCurrent(generation: number): boolean {\n return !this.disposed && generation === this.generation;\n }\n\n private staleResult(): NavigationResult {\n // The operation was invalidated mid-flight (terminate/restart/dispose), so\n // its target is no longer meaningful \u2014 only where the machine ended up is.\n const from = this.currentStepId();\n return this.disposed\n ? { ok: false, reason: \"disposed\", from, to: null }\n : { ok: false, reason: \"not-running\", from, to: null };\n }\n\n private publish(): JourneySnapshot {\n const snapshot = this.buildSnapshot();\n this.store.publish(snapshot);\n return snapshot;\n }\n\n // \u2500\u2500 snapshot derivation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private buildSnapshot(): JourneySnapshot {\n // Structural sharing: every sub-object reuses the previous snapshot's\n // reference when content-identical, and a fully unchanged snapshot returns\n // the previous object itself \u2014 subscribers (and framework bindings diffing\n // by reference) see identity change exactly when content changes.\n const previous = this.lastSnapshot;\n const currentId = this.currentStepId();\n const visitedNext: Record<string, boolean> = {};\n let visitedStepCount = 0;\n for (const id of this.config.stepIds) {\n const seen = (this.visitCounts.get(id) ?? 0) > 0;\n visitedNext[id] = seen;\n if (seen) visitedStepCount += 1;\n }\n\n const previousHistory = previous?.history;\n const visited =\n previousHistory != null && shallowEqual(previousHistory.visited, visitedNext)\n ? previousHistory.visited\n : Object.freeze<Record<string, boolean>>(visitedNext);\n\n const base = {\n status: this.status,\n context: this.context,\n transition: shared(\n {\n pending: this.pending !== null,\n phase: this.pending?.phase ?? null,\n from: this.pending?.from ?? null,\n to: this.pending?.to ?? null,\n },\n previous?.transition,\n ),\n history: shared(\n {\n timeline: sharedArray(this.timeline, previousHistory?.timeline),\n currentIndex: this.currentIndex,\n visited,\n canGoBack: this.currentIndex > 0,\n canGoForward: this.currentIndex >= 0 && this.currentIndex < this.timeline.length - 1,\n },\n previousHistory,\n ),\n machine: shared({ outcome: this.outcome }, previous?.machine),\n };\n\n const currentBase: CurrentStepBase<string, unknown> | null =\n currentId === null\n ? null\n : {\n id: currentId,\n metadata: this.config.steps[currentId]?.metadata ?? EMPTY_METADATA,\n isFirstTimeVisit: (this.visitCounts.get(currentId) ?? 0) === 1,\n async: this.entryAsync,\n };\n\n let snapshot: JourneySnapshot;\n if (this.config.kind === \"linear\") {\n const previousLinear = previous?.type === \"linear\" ? previous : null;\n const orderIndex = currentId === null ? -1 : this.config.stepIds.indexOf(currentId);\n snapshot = {\n ...base,\n type: \"linear\",\n currentStep:\n currentBase === null\n ? null\n : shared(\n {\n ...currentBase,\n index: orderIndex,\n isFirstStep: orderIndex === 0,\n isLastStep: orderIndex === this.config.stepIds.length - 1,\n },\n previousLinear?.currentStep,\n ),\n steps: shared(\n {\n totalSteps: this.config.stepIds.length,\n stepOrder: this.frozenStepOrder,\n visitedStepCount,\n },\n previousLinear?.steps,\n ),\n plugins: EMPTY_PLUGINS,\n };\n } else {\n const declaredEvents: string[] = [];\n const availableEvents: string[] = [];\n const availableSteps: string[] = [];\n const outgoingTransitions: GraphTransitionSnapshot<string, string>[] = [];\n const priorities = new Map<string, number>();\n const selectedEvents = new Set<string>();\n let hasOutgoing = false;\n if (currentId !== null) {\n for (const transition of this.config.transitions) {\n if (transition.from !== currentId) continue;\n hasOutgoing = true;\n if (!declaredEvents.includes(transition.event)) declaredEvents.push(transition.event);\n\n const priority = priorities.get(transition.event) ?? 0;\n priorities.set(transition.event, priority + 1);\n const enabled = this.isEnabled(transition);\n const selected = enabled && !selectedEvents.has(transition.event);\n if (selected) selectedEvents.add(transition.event);\n outgoingTransitions.push(\n Object.freeze({\n event: transition.event,\n to: transition.to,\n priority,\n guard: getGraphGuardState(transition.when, enabled),\n enabled,\n selected,\n }),\n );\n\n if (enabled) {\n if (!availableEvents.includes(transition.event)) availableEvents.push(transition.event);\n if (!availableSteps.includes(transition.to)) availableSteps.push(transition.to);\n }\n }\n }\n const previousGraph = previous?.type === \"graph\" ? previous : null;\n snapshot = {\n ...base,\n type: \"graph\",\n currentStep:\n currentBase === null\n ? null\n : shared({ ...currentBase, isTerminal: !hasOutgoing }, previousGraph?.currentStep),\n steps: shared(\n { totalSteps: this.config.stepIds.length, visitedStepCount },\n previousGraph?.steps,\n ),\n declaredEvents: sharedArray(declaredEvents, previousGraph?.declaredEvents),\n availableEvents: sharedArray(availableEvents, previousGraph?.availableEvents),\n availableSteps: sharedArray(availableSteps, previousGraph?.availableSteps),\n outgoingTransitions: sharedArray(\n outgoingTransitions,\n previousGraph?.outgoingTransitions,\n (a, b) => shallowEqual(a, b as unknown as Record<string, unknown>),\n ),\n plugins: EMPTY_PLUGINS,\n };\n }\n\n if (this.snapshotDerivers.size > 0) {\n const extensions: Record<string, unknown> = {};\n for (const [name, derive] of this.snapshotDerivers) {\n // Derivers run on every publish and in the constructor, so an\n // unguarded throw here took down every transition. Isolate like any\n // other plugin tap: report, then carry the plugin's previous slice\n // forward so consumers reading snapshot.plugins[name] do not see it\n // blink to undefined.\n try {\n extensions[name] = derive(snapshot, this.lastPluginExtensions[name]);\n } catch (error) {\n this.store.report(error);\n if (hasOwn(this.lastPluginExtensions, name)) {\n extensions[name] = this.lastPluginExtensions[name];\n }\n }\n }\n this.lastPluginExtensions = extensions;\n const previousPlugins = previous?.plugins;\n snapshot = {\n ...snapshot,\n plugins:\n previousPlugins != null && shallowEqual(previousPlugins, extensions)\n ? previousPlugins\n : Object.freeze(extensions),\n };\n }\n\n const frozen = Object.freeze(snapshot) as JourneySnapshot;\n const result = previous !== null && shallowEqual(frozen, previous) ? previous : frozen;\n this.lastSnapshot = result;\n return result;\n }\n}\n", "import { JourneyError } from \"../../core/errors\";\nimport type { JourneyPersistedState, JourneyStorage, PersistenceReason } from \"./persistence.types\";\nimport type { JourneyPersistOption, JourneySnapshot } from \"../../core/types\";\n\n/** Every observation kind a save can be scheduled on. */\nexport const DEFAULT_SAVE_REASONS: readonly PersistenceReason[] = [\n \"context\",\n \"transition\",\n \"status\",\n];\n\n/** Omitted means \"write immediately\"; anything else is clamped to a whole >= 0. */\nexport function normalizeDebounceMs(value: number | undefined): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return 0;\n return Math.max(0, Math.trunc(value));\n}\n\nexport function buildPersistedState(snapshot: JourneySnapshot, now: number): JourneyPersistedState {\n return {\n status: snapshot.status,\n context: snapshot.context,\n timeline: snapshot.history.timeline,\n currentIndex: snapshot.history.currentIndex,\n savedAt: now,\n };\n}\n\nconst JOURNEY_STATUSES = new Set([\n \"idle\",\n \"running\",\n \"paused\",\n \"completed\",\n \"terminated\",\n]) as ReadonlySet<string>;\n\n/**\n * Keys that must never survive `JSON.parse` into machine state.\n *\n * `JSON.parse` creates `__proto__` as an ordinary own property rather than\n * reassigning the prototype, so the parsed object is safe in isolation. It stops\n * being safe the moment application code spreads or `Object.assign`s it into a\n * fresh object \u2014 the own key is then copied as a *prototype assignment*. Storage\n * is attacker-reachable, so the shape is scrubbed before it can reach a context.\n */\nconst UNSAFE_KEYS = [\"__proto__\", \"constructor\", \"prototype\"] as const;\n\nfunction scrub(value: unknown, depth = 0): unknown {\n if (depth > 50 || value === null || typeof value !== \"object\") return value;\n if (Array.isArray(value)) return value.map((item) => scrub(item, depth + 1));\n\n const output: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) {\n if ((UNSAFE_KEYS as readonly string[]).includes(key)) continue;\n output[key] = scrub(item, depth + 1);\n }\n return output;\n}\n\n/**\n * Parses a stored value; malformed or foreign payloads yield `null`.\n *\n * Validation is deliberately total: this is the only gate between an untrusted\n * storage entry and machine state, and `readPersisted()` hands the result\n * straight to application code typed as `JourneyPersistedState`.\n */\nexport function parsePersistedState(raw: string | null): JourneyPersistedState | null {\n if (raw === null) return null;\n let value: unknown;\n try {\n value = JSON.parse(raw);\n } catch {\n return null;\n }\n if (typeof value !== \"object\" || value === null) return null;\n const candidate = value as Record<string, unknown>;\n if (\n typeof candidate.status !== \"string\" ||\n !JOURNEY_STATUSES.has(candidate.status) ||\n !Array.isArray(candidate.timeline) ||\n !candidate.timeline.every((id) => typeof id === \"string\") ||\n typeof candidate.currentIndex !== \"number\" ||\n !Number.isInteger(candidate.currentIndex) ||\n typeof candidate.savedAt !== \"number\" ||\n !Number.isFinite(candidate.savedAt)\n ) {\n return null;\n }\n return {\n status: candidate.status,\n context: scrub(candidate.context),\n timeline: candidate.timeline,\n currentIndex: candidate.currentIndex,\n savedAt: candidate.savedAt,\n } as JourneyPersistedState;\n}\n\n/**\n * Resolves the `persist` option's storage; throws when none is available.\n *\n * Reading `globalThis.localStorage` can itself throw \u2014 a third-party iframe\n * with storage blocked, or Safari's Lockdown Mode \u2014 rather than returning\n * undefined. Unguarded, that surfaced as a raw `SecurityError` out of\n * `createLinearJourney`, which reads as a library crash rather than an\n * environment that cannot persist. The failure stays loud (silently disabling\n * persistence loses data with no signal) but is now a `journey:` error naming\n * the fix, with the original kept as `cause`.\n */\nexport function resolvePersistStorage(option: JourneyPersistOption): JourneyStorage {\n if (option.storage) return option.storage;\n\n let ambient: JourneyStorage | undefined;\n try {\n ambient = globalThis.localStorage;\n } catch (error) {\n throw new JourneyError(\n \"storage-unavailable\",\n \"localStorage access was blocked by the environment; pass persist.storage explicitly\",\n {},\n error,\n );\n }\n\n if (!ambient) {\n throw new JourneyError(\n \"storage-unavailable\",\n \"persist.storage is required when localStorage is unavailable\",\n );\n }\n return ambient;\n}\n\n/**\n * Reads a persisted record that can seed this machine, or `null`. Restore is\n * best-effort by design: terminal-status records, records whose timeline\n * mentions a step the current definition no longer declares (definition\n * drift), and malformed/foreign payloads are all ignored rather than thrown.\n */\nexport function readRestorableState(\n option: JourneyPersistOption,\n isDeclaredStep: (id: string) => boolean,\n): JourneyPersistedState | null {\n let raw: string | null;\n try {\n raw = resolvePersistStorage(option).getItem(option.key);\n } catch {\n return null;\n }\n const record = parsePersistedState(raw);\n if (!record) return null;\n if (record.status !== \"running\" && record.status !== \"paused\") return null;\n if (!Number.isInteger(record.currentIndex)) return null;\n if (record.currentIndex < 0 || record.currentIndex >= record.timeline.length) return null;\n for (const id of record.timeline) {\n if (typeof id !== \"string\" || !isDeclaredStep(id)) return null;\n }\n return record;\n}\n", "import { warnInDevelopment } from \"../../internal/dev\";\nimport {\n buildPersistedState,\n DEFAULT_SAVE_REASONS,\n normalizeDebounceMs,\n parsePersistedState,\n resolvePersistStorage,\n} from \"./persistence.helpers\";\nimport type {\n JourneyPersistedState,\n PersistenceApi,\n PersistencePluginOptions,\n PersistenceReason,\n PersistenceState,\n} from \"./persistence.types\";\nimport type { JourneyPersistOption, JourneyPlugin } from \"../../core/types\";\n\nexport {\n buildPersistedState,\n DEFAULT_SAVE_REASONS,\n normalizeDebounceMs,\n parsePersistedState,\n} from \"./persistence.helpers\";\n\nconst IDLE_STATE: PersistenceState = { status: \"idle\", lastSavedAt: null, error: null };\n\n/**\n * Persists a serializable slice of machine state (status, context, timeline) on\n * every transition, status change, and context change. `saveOn` narrows which\n * of those trigger a write; `debounceMs` collapses a burst of them into one.\n *\n * The plugin itself is save-side only (plugins observe, they cannot seed the\n * runtime). Restore happens through the creation-time `persist` option, which\n * reads a restorable record before the machine is built; `readPersisted()`\n * exposes the saved state for callers wiring this plugin explicitly.\n */\nexport function createPersistencePlugin(\n options: PersistencePluginOptions,\n): JourneyPlugin<\"persistence\", PersistenceApi, PersistenceState> {\n const now = options.now ?? Date.now;\n const debounceMs = normalizeDebounceMs(options.debounceMs);\n const saveReasons = new Set<PersistenceReason>(options.saveOn ?? DEFAULT_SAVE_REASONS);\n // Per plugin *instance*, not per machine: mutable state is scoped to setup(),\n // but `options` is not \u2014 two machines sharing one instance write the same key\n // and silently clobber each other.\n let setupCount = 0;\n return {\n name: \"persistence\",\n setup(host) {\n setupCount += 1;\n if (setupCount > 1) {\n warnInDevelopment(\n `journey: persistence plugin instance shared by ${setupCount} machines; they overwrite key \"${options.key}\". Create one per machine.`,\n );\n }\n let lastWritten: JourneyPersistedState | null = null;\n let state: PersistenceState = IDLE_STATE;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let disposed = false;\n\n const succeeded = (written: JourneyPersistedState) => {\n lastWritten = written;\n state = { status: \"saved\", lastSavedAt: written.savedAt, error: null };\n };\n\n const failed = (error: unknown) => {\n state = { ...state, status: \"error\", error };\n host.reportError(error);\n };\n\n /**\n * Writes now. Returns a promise only so `flushPersisted` can be awaited;\n * the immediate path stays synchronous up to the `setItem` call, which is\n * what lets a throwing adapter surface through the runtime's listener\n * isolation exactly as it always did.\n */\n const save = (): void | Promise<void> => {\n const written = buildPersistedState(host.getSnapshot(), now());\n state = { ...state, status: \"saving\" };\n let result: void | Promise<void>;\n try {\n result = options.storage.setItem(options.key, JSON.stringify(written));\n } catch (error) {\n // Recorded here, but rethrown so the runtime's listener isolation\n // reports it exactly as it always did.\n state = { ...state, status: \"error\", error };\n throw error;\n }\n // `setItem` may be async. Discarding that promise turned a rejecting\n // adapter into an unhandled rejection, which terminates the process\n // under Node's default `--unhandled-rejections=throw`.\n if (result !== undefined) {\n return result.then(() => succeeded(written), failed);\n }\n succeeded(written);\n };\n\n const cancelTimer = () => {\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n };\n\n /**\n * A debounced write happens on a timer, so there is no synchronous caller\n * left to throw to \u2014 its failures land in `state` and `reportError`\n * instead. The immediate path keeps throwing.\n */\n const runDebounced = () => {\n timer = null;\n try {\n const result = save();\n if (result !== undefined) void result;\n } catch (error) {\n failed(error);\n }\n };\n\n const onObservation = (reason: PersistenceReason) => {\n if (disposed || !saveReasons.has(reason)) return;\n if (debounceMs === 0) {\n void save();\n return;\n }\n cancelTimer();\n state = { ...state, status: \"pending\" };\n timer = setTimeout(runDebounced, debounceMs);\n };\n\n host.onContextChange(() => onObservation(\"context\"));\n host.onTransition(() => onObservation(\"transition\"));\n host.onStatusChange(({ current }) => {\n if (current === \"terminated\" && options.clearOnTerminate) {\n cancelTimer();\n lastWritten = null;\n state = IDLE_STATE;\n options.storage.removeItem(options.key);\n return;\n }\n onObservation(\"status\");\n });\n host.onDispose(() => {\n disposed = true;\n cancelTimer();\n });\n\n return {\n api: {\n inspectPersistedState: () => lastWritten,\n getPersistenceState: () => state,\n readPersisted: () => parsePersistedState(options.storage.getItem(options.key)),\n clearPersisted: () => {\n cancelTimer();\n lastWritten = null;\n state = IDLE_STATE;\n // Called directly by user code; record the failure here rather than\n // throwing out of an API whose sibling writes are all contained.\n try {\n options.storage.removeItem(options.key);\n } catch (error) {\n failed(error);\n }\n },\n flushPersisted: async () => {\n cancelTimer();\n try {\n await save();\n } catch (error) {\n failed(error);\n }\n },\n },\n deriveSnapshot: (_snapshot, previous) => (previous === state ? previous : state),\n };\n },\n };\n}\n\n/** Expands the creation-time `persist` option into the persistence plugin. */\nexport function persistOptionToPlugin(\n option: JourneyPersistOption,\n): JourneyPlugin<\"persistence\", PersistenceApi, PersistenceState> {\n return createPersistencePlugin({ key: option.key, storage: resolvePersistStorage(option) });\n}\n", "import { JourneyError } from \"../core/errors\";\nimport { hasOwn } from \"../core/helpers\";\nimport { buildMachineSurface } from \"../core/machine\";\nimport { JourneyRuntime } from \"../core/runtime\";\nimport { persistOptionToPlugin } from \"../plugins/persistence/persistence\";\nimport { readRestorableState } from \"../plugins/persistence/persistence.helpers\";\nimport type { RuntimeStep } from \"../core/runtime.types\";\nimport type {\n CompletePayloadOf,\n JourneyTerminationPayloads,\n LinearJourneyDefinition,\n LinearJourneyMachine,\n LinearStepConfig,\n TerminatePayloadOf,\n} from \"./linear.types\";\nimport type { AnyJourneyPlugin, JourneyRuntimeOptions } from \"../core/types\";\nimport type { Bag, MetaOf } from \"../graph/bag.types\";\n\n/**\n * Creates a linear journey runtime from a pure-data definition.\n *\n * Declared order drives `goToNextStep`'s fallback at the timeline tip and the\n * order-based snapshot fields (`index`, `isFirstStep`, `isLastStep`,\n * `stepOrder`). `goToNextStep` on the last step never auto-completes.\n */\nexport function createLinearJourney<\n const TStepId extends string,\n TContext,\n TTerminationPayloads extends JourneyTerminationPayloads = JourneyTerminationPayloads,\n // Defaults to the empty tuple, matching createGraphJourney. Defaulting to\n // `readonly AnyJourneyPlugin[]` collapsed PluginApis to `{ [x: string]: never }`\n // \u2014 an index signature that accepts any key \u2014 so `machine.plugins.typo`\n // compiled clean whenever plugins were omitted or the first generics were\n // supplied explicitly.\n const TPlugins extends readonly AnyJourneyPlugin[] = readonly [],\n TMeta = Record<string, unknown>,\n>(\n definition: LinearJourneyDefinition<TStepId, TContext, TTerminationPayloads, TMeta>,\n options: JourneyRuntimeOptions<TPlugins, NoInfer<TStepId>> = {},\n): LinearJourneyMachine<\n TContext,\n TStepId,\n TMeta,\n TPlugins,\n CompletePayloadOf<TTerminationPayloads>,\n TerminatePayloadOf<TTerminationPayloads>\n> {\n if (definition.steps.length === 0) {\n throw new JourneyError(\"empty-definition\", \"a linear journey needs at least one step\");\n }\n\n const stepIds: string[] = [];\n const steps: Record<string, RuntimeStep> = {};\n for (const input of definition.steps) {\n const config: LinearStepConfig<\n TContext,\n TStepId,\n TMeta,\n CompletePayloadOf<TTerminationPayloads>,\n TerminatePayloadOf<TTerminationPayloads>\n > = typeof input === \"string\" ? { id: input } : input;\n if (hasOwn(steps, config.id)) {\n throw new JourneyError(\"duplicate-step-id\", `duplicate step id \"${config.id}\"`, {\n stepId: config.id,\n });\n }\n stepIds.push(config.id);\n const runtimeStep: {\n metadata: unknown;\n onEnter?: NonNullable<RuntimeStep[\"onEnter\"]>;\n onLeave?: NonNullable<RuntimeStep[\"onLeave\"]>;\n } = { metadata: config.metadata ?? {} };\n if (config.onEnter) {\n runtimeStep.onEnter = config.onEnter as unknown as NonNullable<RuntimeStep[\"onEnter\"]>;\n }\n if (config.onLeave) {\n runtimeStep.onLeave = config.onLeave as unknown as NonNullable<RuntimeStep[\"onLeave\"]>;\n }\n steps[config.id] = runtimeStep;\n }\n\n if (options.startAt !== undefined && !hasOwn(steps, options.startAt)) {\n throw new JourneyError(\"unknown-step\", `startAt references unknown step \"${options.startAt}\"`, {\n stepId: options.startAt,\n });\n }\n\n // Explicit `startAt` wins over a persisted record; restore is best-effort.\n const restored =\n options.persist && options.startAt === undefined\n ? readRestorableState(options.persist, (id) => hasOwn(steps, id))\n : null;\n\n const runtime = new JourneyRuntime({\n kind: \"linear\",\n stepIds,\n steps,\n initial: stepIds[0] as string,\n ...(options.startAt !== undefined ? { startAt: options.startAt } : {}),\n initialContext: definition.context,\n ...(restored\n ? {\n restore: {\n context: restored.context,\n timeline: restored.timeline,\n currentIndex: restored.currentIndex,\n },\n }\n : {}),\n transitions: [],\n handlers: undefined,\n autoStart: options.autoStart ?? true,\n defaultTimeoutMs: options.defaultTimeoutMs,\n ...(options.onListenerError !== undefined ? { onListenerError: options.onListenerError } : {}),\n plugins: [\n ...(options.persist ? [persistOptionToPlugin(options.persist)] : []),\n ...(options.plugins ?? []),\n ],\n });\n\n const surface = buildMachineSurface(runtime);\n return {\n ...surface,\n navigate: {\n ...surface.navigate,\n goToStepByIndex: (index: number) => runtime.goToStepByIndex(index),\n },\n } as unknown as LinearJourneyMachine<\n TContext,\n TStepId,\n TMeta,\n TPlugins,\n CompletePayloadOf<TTerminationPayloads>,\n TerminatePayloadOf<TTerminationPayloads>\n >;\n}\n\n/**\n * Returns a `createLinearJourney` with its types pinned up front instead of\n * inferred.\n *\n * The linear tier infers almost everything from the definition already \u2014 step\n * ids from the `steps` tuple, context from its value \u2014 so reach for this only\n * to pin a `meta` shape, or to share one bag with steps authored in separate\n * files.\n *\n * A standalone export rather than a property on the factory: attaching one\n * would be a module-level side effect, and that defeats tree-shaking badly\n * enough that importing only `createLinearJourney` pulled the whole graph tier\n * into the bundle.\n *\n * ```ts\n * const checkout = withLinearTypes<CheckoutBag>()({\n * steps: [\"account\", \"shipping\", \"review\"],\n * context: initialContext\n * });\n * ```\n */\nexport const withLinearTypes =\n <TBag extends Bag>() =>\n <const TPlugins extends readonly AnyJourneyPlugin[] = readonly []>(\n definition: LinearJourneyDefinition<\n TBag[\"stepId\"],\n TBag[\"context\"],\n JourneyTerminationPayloads,\n MetaOf<TBag>\n >,\n options: JourneyRuntimeOptions<TPlugins, TBag[\"stepId\"]> = {},\n ): LinearJourneyMachine<TBag[\"context\"], TBag[\"stepId\"], MetaOf<TBag>, TPlugins> =>\n createLinearJourney(definition, options);\n", "import { JourneyError } from \"../core/errors\";\nimport { eventWorkKey, hasOwn } from \"../core/helpers\";\nimport { buildMachineSurface } from \"../core/machine\";\nimport { JourneyRuntime } from \"../core/runtime\";\nimport { persistOptionToPlugin } from \"../plugins/persistence/persistence\";\nimport { readRestorableState } from \"../plugins/persistence/persistence.helpers\";\nimport type { RuntimeStep, RuntimeTransition } from \"../core/runtime.types\";\nimport type {\n GraphJourneyMachine,\n GraphJourneyOptions,\n GraphStepConfig,\n LooseGraphDefinition,\n LooseOnEntry,\n LooseTransition,\n MutableRuntimeStep,\n MutableRuntimeTransition,\n MutableSendWork,\n} from \"./graph.types\";\nimport type { AnySendWork } from \"../core/runtime.types\";\nimport type { Bag, GraphDefinition, HandlersOf, MetaOf } from \"./bag.types\";\nimport type {\n AnyJourneyPlugin,\n CompletePayloadOf,\n JourneyEventObject,\n JourneyTerminationPayloads,\n TerminatePayloadOf,\n} from \"../core/types\";\n\n/**\n * Both validators run at build time rather than at the first send. A label only\n * ever shows up in an error message and a timeout only ever fires under load,\n * so a malformed one would otherwise stay invisible until the moment it was\n * needed to explain something else.\n */\nconst assertLabel = (label: unknown, where: string, meta: { event: string; stepId: string }) => {\n if (typeof label !== \"string\" || label.length === 0) {\n throw new JourneyError(\n \"invalid-label\",\n `${where} must declare \"label\" as a non-empty string`,\n meta,\n );\n }\n return label;\n};\n\nconst assertTimeout = (ms: unknown, where: string, meta: { event: string; stepId: string }) => {\n if (typeof ms !== \"number\" || !Number.isFinite(ms) || ms <= 0) {\n throw new JourneyError(\n \"invalid-timeout\",\n `${where} must declare \"timeoutMs\" as a finite number greater than 0`,\n meta,\n );\n }\n return ms;\n};\n\n/**\n * Flattens each step's colocated `on` into the runtime's flat transition list,\n * in declaration order, and validates every target.\n *\n * Order is per step, then per event, then per candidate. That differs from the\n * old central map's global per-event order, but only for the same event\n * declared from two steps \u2014 and candidates are filtered by `from` before order\n * is consulted, so the selected edge is unchanged. `first-enabled-in-declared-\n * order` is asserted directly in graph.test.ts.\n *\n * `from` cannot dangle here: it is the key of the step that declares the entry.\n */\nexport function normalizeGraphDefinition(definition: LooseGraphDefinition): {\n stepIds: string[];\n steps: Record<string, RuntimeStep>;\n transitions: RuntimeTransition[];\n eventWork: Record<string, AnySendWork>;\n} {\n const stepIds = Object.keys(definition.steps);\n if (stepIds.length === 0) {\n throw new JourneyError(\"empty-definition\", \"a graph journey needs at least one step\");\n }\n if (!stepIds.includes(definition.initial)) {\n throw new JourneyError(\n \"unknown-initial-step\",\n `initial step \"${definition.initial}\" is not a declared step`,\n { stepId: definition.initial },\n );\n }\n\n const steps: Record<string, RuntimeStep> = {};\n for (const id of stepIds) {\n const config = definition.steps[id] as GraphStepConfig;\n const runtimeStep: MutableRuntimeStep = { metadata: config.metadata ?? {} };\n if (config.onEnter) {\n runtimeStep.onEnter = config.onEnter as unknown as NonNullable<RuntimeStep[\"onEnter\"]>;\n }\n if (config.onLeave) {\n runtimeStep.onLeave = config.onLeave as unknown as NonNullable<RuntimeStep[\"onLeave\"]>;\n }\n steps[id] = runtimeStep;\n }\n\n const transitions: RuntimeTransition[] = [];\n const eventWork: Record<string, AnySendWork> = {};\n\n const pushCandidate = (\n event: string,\n from: string,\n candidate: LooseTransition,\n index: number,\n ): void => {\n if (!stepIds.includes(candidate.to)) {\n throw new JourneyError(\n \"dangling-transition\",\n `transition \"${event}\" references unknown step \"${candidate.to}\"`,\n { event, stepId: candidate.to },\n );\n }\n const where = `transition \"${event}\"[${index}] on step \"${from}\"`;\n const runtimeTransition: MutableRuntimeTransition = { event, from, to: candidate.to, index };\n if (candidate.when) runtimeTransition.when = candidate.when;\n if (candidate.onTransition) runtimeTransition.onTransition = candidate.onTransition;\n if (candidate.label !== undefined) {\n runtimeTransition.label = assertLabel(candidate.label, where, { event, stepId: from });\n }\n if (candidate.timeoutMs !== undefined) {\n runtimeTransition.timeoutMs = assertTimeout(candidate.timeoutMs, where, {\n event,\n stepId: from,\n });\n }\n transitions.push(runtimeTransition);\n };\n\n for (const from of stepIds) {\n const on = definition.steps[from]?.on;\n if (!on) continue;\n for (const [event, entry] of Object.entries(on)) {\n if (entry === undefined) continue;\n if (typeof entry === \"string\") {\n pushCandidate(event, from, { to: entry }, 0);\n continue;\n }\n if (Array.isArray(entry)) {\n (entry as readonly LooseTransition[]).forEach((candidate, index) =>\n pushCandidate(event, from, candidate, index),\n );\n continue;\n }\n const declared = entry as Exclude<LooseOnEntry, string | readonly LooseTransition[]>;\n const where = `work on \"${event}\" on step \"${from}\"`;\n const work: MutableSendWork = { run: declared.run };\n if (declared.commit) work.commit = declared.commit;\n if (declared.label !== undefined) {\n work.label = assertLabel(declared.label, where, { event, stepId: from });\n }\n if (declared.timeoutMs !== undefined) {\n work.timeoutMs = assertTimeout(declared.timeoutMs, where, { event, stepId: from });\n }\n eventWork[eventWorkKey(from, event)] = work;\n declared.candidates.forEach((candidate, index) =>\n pushCandidate(event, from, candidate, index),\n );\n }\n }\n\n return { stepIds, steps, transitions, eventWork };\n}\n\n/**\n * Creates a graph journey runtime from a pure-data definition.\n *\n * `send(event, payload?)` is the primary verb; `goToStepById` is\n * transition-gated sugar (fires only if an enabled transition targets that\n * id). Timeline moves bypass transition gating \u2014 retracing a walked path is\n * always legal. Step `onLeave` effects still run after those moves commit.\n */\nexport function createGraphJourney<\n TContext,\n TStepId extends string,\n TEvents extends JourneyEventObject = JourneyEventObject,\n THandlers = unknown,\n TMeta = Record<string, unknown>,\n const TPlugins extends readonly AnyJourneyPlugin[] = readonly [],\n TTerminationPayloads extends JourneyTerminationPayloads = JourneyTerminationPayloads,\n>(\n // Inline shape (not GraphJourneyDefinition) so TStepId infers from the\n // steps-record keys alone: every other occurrence is NoInfer-wrapped,\n // otherwise `initial` would win inference and collapse the id union.\n definition: {\n readonly steps: Readonly<\n Record<\n TStepId,\n GraphStepConfig<\n NoInfer<TContext>,\n NoInfer<TStepId>,\n NoInfer<TEvents>,\n TMeta,\n NoInfer<THandlers>\n >\n >\n >;\n readonly initial: NoInfer<TStepId>;\n readonly context: TContext;\n readonly handlers?: THandlers;\n /** @internal Builder-produced; opaque by design (see GraphJourneyDefinition). */\n readonly eventWork?: Readonly<Record<string, unknown>>;\n readonly $events?: TEvents;\n readonly $payloads?: TTerminationPayloads;\n },\n options: GraphJourneyOptions<NoInfer<THandlers>, TPlugins, NoInfer<TStepId>> = {},\n // THandlers is load-bearing: it types `handlers` inside send work, which is\n // the only channel injected clients reach. Omitting it here let the\n // annotation win over the cast below and erased it to `unknown`.\n): GraphJourneyMachine<\n TContext,\n TStepId,\n TEvents,\n TMeta,\n TPlugins,\n CompletePayloadOf<TTerminationPayloads>,\n TerminatePayloadOf<TTerminationPayloads>\n> {\n const { stepIds, steps, transitions, eventWork } = normalizeGraphDefinition(\n definition as unknown as LooseGraphDefinition,\n );\n\n if (options.startAt !== undefined && !hasOwn(steps, options.startAt)) {\n throw new JourneyError(\"unknown-step\", `startAt references unknown step \"${options.startAt}\"`, {\n stepId: options.startAt,\n });\n }\n\n // Explicit `startAt` wins over a persisted record; restore is best-effort.\n const restored =\n options.persist && options.startAt === undefined\n ? readRestorableState(options.persist, (id) => hasOwn(steps, id))\n : null;\n\n const runtime = new JourneyRuntime({\n kind: \"graph\",\n stepIds,\n steps,\n initial: definition.initial,\n ...(options.startAt !== undefined ? { startAt: options.startAt } : {}),\n initialContext: definition.context,\n ...(restored\n ? {\n restore: {\n context: restored.context,\n timeline: restored.timeline,\n currentIndex: restored.currentIndex,\n },\n }\n : {}),\n transitions,\n ...(Object.keys(eventWork).length > 0 ? { eventWork } : {}),\n handlers: options.handlers ?? definition.handlers,\n autoStart: options.autoStart ?? true,\n defaultTimeoutMs: options.defaultTimeoutMs,\n ...(options.onListenerError !== undefined ? { onListenerError: options.onListenerError } : {}),\n plugins: [\n ...(options.persist ? [persistOptionToPlugin(options.persist)] : []),\n ...(options.plugins ?? []),\n ],\n });\n\n const machine = {\n ...buildMachineSurface(runtime),\n send: (type: string, payload?: unknown) => runtime.send(type, payload),\n };\n return machine as unknown as GraphJourneyMachine<\n TContext,\n TStepId,\n TEvents,\n TMeta,\n TPlugins,\n CompletePayloadOf<TTerminationPayloads>,\n TerminatePayloadOf<TTerminationPayloads>\n >;\n}\n\n/**\n * Creates a graph journey factory with its types pinned up front instead of\n * inferred.\n *\n * Reach for it when the definition cannot supply a type on its own \u2014\n * `handlers`, a `meta` shape, or a `run` result, none of which sit at an\n * inference site \u2014 or when the same bag is shared by steps authored in\n * separate files. The definition is then *checked* against the bag rather than\n * read for types.\n *\n * ```ts\n * const login = withGraphTypes<AuthBag>()({\n * initial: \"login\",\n * context: initialContext,\n * steps: { login: { on: { submit: \"twofa\" } }, twofa: {} }\n * });\n * ```\n *\n * Plain `createGraphJourney(definition)` stays the default: step ids infer from\n * the `steps` keys and event names from the `on` keys.\n */\nexport const withGraphTypes =\n <TBag extends Bag>() =>\n <const TPlugins extends readonly AnyJourneyPlugin[] = readonly []>(\n definition: GraphDefinition<TBag>,\n options: GraphJourneyOptions<HandlersOf<TBag>, TPlugins, TBag[\"stepId\"]> = {},\n ): GraphJourneyMachine<TBag[\"context\"], TBag[\"stepId\"], TBag[\"events\"], MetaOf<TBag>, TPlugins> =>\n createGraphJourney(\n definition as unknown as Parameters<typeof createGraphJourney>[0],\n options as unknown as Parameters<typeof createGraphJourney>[1],\n ) as unknown as GraphJourneyMachine<\n TBag[\"context\"],\n TBag[\"stepId\"],\n TBag[\"events\"],\n MetaOf<TBag>,\n TPlugins\n >;\n", "import type { Bag, HandlersOf, MetaOf, ResultOf } from \"./bag.types\";\nimport type { GraphOnEntry, GraphTransition, SendWorkArgs } from \"./graph.types\";\nimport type { ContextUpdater, GraphSnapshot } from \"../core/types\";\n\n/** The event an entry is declared under, narrowed out of the bag's union. */\ntype TriggerOf<TBag extends Bag, TType extends TBag[\"events\"][\"type\"]> = Extract<\n TBag[\"events\"],\n { type: TType }\n>;\n\ntype WorkArgs<TBag extends Bag, TType extends TBag[\"events\"][\"type\"]> = SendWorkArgs<\n TBag[\"stepId\"],\n TriggerOf<TBag, TType>,\n GraphSnapshot<TBag[\"context\"], TBag[\"stepId\"], MetaOf<TBag>, TBag[\"events\"]>,\n HandlersOf<TBag>\n>;\n\n/**\n * The config {@link defineWork} checks.\n *\n * The same shape as the object arm of {@link GraphOnEntry}, with two\n * differences that only a function call can provide: `TResult` is a free type\n * parameter here rather than a fixed argument, and `event` is narrowed to the\n * key the entry is declared under.\n */\nexport type WorkConfig<TBag extends Bag, TType extends TBag[\"events\"][\"type\"], TResult> = {\n readonly run: (args: WorkArgs<TBag, TType>) => TResult | Promise<TResult>;\n readonly commit?: (\n args: WorkArgs<TBag, TType> & {\n readonly result: TResult;\n readonly updateContext: (updater: ContextUpdater<TBag[\"context\"]>) => void;\n },\n ) => void;\n /** Names this work in timeout and error messages. */\n readonly label?: string;\n /** Budget for `run`, overriding `defaultTimeoutMs`. */\n readonly timeoutMs?: number;\n /**\n * Guards here stay total functions of context, as everywhere else: the run\n * result reaches them only through the context `commit` stages. Routing\n * directly on the result was removed in v2 because the same guards run during\n * snapshot derivation, where no send is in flight \u2014 `availableEvents` would\n * then disagree with what a send actually does.\n */\n readonly candidates: readonly GraphTransition<\n TBag[\"context\"],\n TBag[\"stepId\"],\n TBag[\"events\"],\n HandlersOf<TBag>,\n MetaOf<TBag>,\n TriggerOf<TBag, TType>\n >[];\n};\n\n/**\n * Declares an event's async so that `run`'s return type flows into `commit` and\n * into the candidates' guards.\n *\n * Written straight into a definition, `run` sits at a property position, which\n * is not an inference site \u2014 so `result` is `unknown` unless the type is\n * restated in the bag's `results`. Pinning it there works, but it is a second\n * place to keep in sync, and it is one result type per event name rather than\n * per (step, event) pair. Passing the same config through a generic function\n * call puts `TResult` back at an inference site, so it is read off `run` and\n * nothing needs restating:\n *\n * ```ts\n * on: {\n * SUBMIT: defineWork<AuthBag, \"SUBMIT\">()({\n * run: ({ handlers }) => handlers.login(), // TResult inferred here\n * commit: ({ result, updateContext }) => // ...and typed here\n * updateContext((c) => ({ ...c, token: result.token, needsTwoFactor: result.twoFactor })),\n * timeoutMs: 10_000,\n * candidates: [\n * { to: \"twofa\", label: \"needs-2fa\", when: ({ context }) => context.needsTwoFactor },\n * { to: \"home\", label: \"logged-in\" }\n * ]\n * })\n * }\n * ```\n *\n * The call is curried because TypeScript infers all of a call's type arguments\n * or none: naming the bag and the event inline would opt `TResult` out of\n * inference too, which is the problem being solved. The empty second call is\n * the price of pinning the first two and inferring the third.\n *\n * Pairs with a bag, so reach for it through `withGraphTypes<TBag>()` rather\n * than plain `createGraphJourney`: the bag is where `stepId`, `events` and\n * `handlers` come from, and a definition that infers those itself will not line\n * up with them.\n *\n * At runtime this returns its argument unchanged. The cast is what erases the\n * narrowed `event` and the inferred `TResult` back down to the slot's wider\n * shape \u2014 `commit`'s `result` sits at a contravariant position, so a pinned\n * config cannot be assigned into an `unknown` slot directly. That is the same\n * erasure the v1 builder did, and it is sound because the config has already\n * been checked, against sharper types, at this call site.\n */\nexport const defineWork =\n <TBag extends Bag, TType extends TBag[\"events\"][\"type\"] = TBag[\"events\"][\"type\"]>() =>\n <TResult>(\n config: WorkConfig<TBag, TType, TResult>,\n ): GraphOnEntry<\n TBag[\"context\"],\n TBag[\"stepId\"],\n TBag[\"events\"],\n HandlersOf<TBag>,\n MetaOf<TBag>,\n ResultOf<TBag, TType>,\n TriggerOf<TBag, TType>\n > =>\n config as unknown as GraphOnEntry<\n TBag[\"context\"],\n TBag[\"stepId\"],\n TBag[\"events\"],\n HandlersOf<TBag>,\n MetaOf<TBag>,\n ResultOf<TBag, TType>,\n TriggerOf<TBag, TType>\n >;\n", "import { normalizeGraphDefinition } from \"../graph/graph\";\nimport type { DiagnosticsIssue, DiagnosticsResult } from \"./diagnostics.types\";\nimport type { JourneyStructure } from \"../core/types\";\n\nfunction analyzeJourneyStructure(structure: JourneyStructure): DiagnosticsResult {\n const issues: DiagnosticsIssue[] = [];\n const stepIds = [...structure.stepIds];\n\n // Shadowed transitions: after an unguarded candidate for (from, event),\n // later candidates for the same key can never be selected.\n const shadowedIndexes = new Set<number>();\n const unguardedSeen = new Set<string>();\n structure.transitions.forEach((transition, index) => {\n const key = `${transition.from} ${transition.event}`;\n if (unguardedSeen.has(key)) {\n shadowedIndexes.add(index);\n issues.push({\n code: \"shadowed-transition\",\n severity: \"warning\",\n from: transition.from,\n event: transition.event,\n message: `Transition \"${transition.from}.${transition.event}\" is shadowed by an earlier unconditional candidate.`,\n });\n return;\n }\n if (!transition.guarded) unguardedSeen.add(key);\n });\n\n const activeTransitions = structure.transitions.filter((_, index) => !shadowedIndexes.has(index));\n const outgoing = (stepId: string) =>\n activeTransitions.filter((transition) => transition.from === stepId);\n\n const reachable = new Set<string>();\n const queue = [structure.initial];\n while (queue.length > 0) {\n const stepId = queue.pop() as string;\n if (reachable.has(stepId)) continue;\n reachable.add(stepId);\n for (const transition of outgoing(stepId)) queue.push(transition.to);\n }\n\n for (const stepId of stepIds) {\n if (reachable.has(stepId)) continue;\n issues.push({\n code: \"unreachable-step\",\n severity: \"warning\",\n stepId,\n message: `Step \"${stepId}\" is unreachable from the initial step \"${structure.initial}\".`,\n });\n }\n\n const terminalStepIds = stepIds.filter((stepId) => outgoing(stepId).length === 0);\n\n // Cycle detection over the reachable subgraph.\n const cycleKeys = new Set<string>();\n const visited = new Set<string>();\n const stack: string[] = [];\n const walk = (stepId: string) => {\n visited.add(stepId);\n stack.push(stepId);\n for (const transition of outgoing(stepId)) {\n const stackIndex = stack.indexOf(transition.to);\n if (stackIndex >= 0) {\n const cycleSteps = [...stack.slice(stackIndex), transition.to];\n const cycleKey = cycleSteps.join(\" \");\n if (!cycleKeys.has(cycleKey)) {\n cycleKeys.add(cycleKey);\n issues.push({\n code: \"cycle-detected\",\n severity: \"warning\",\n from: transition.from,\n event: transition.event,\n steps: cycleSteps,\n message: `Cycle detected: ${cycleSteps.join(\" -> \")}.`,\n });\n }\n continue;\n }\n if (!visited.has(transition.to)) walk(transition.to);\n }\n stack.pop();\n };\n walk(structure.initial);\n\n const terminalPathExists = terminalStepIds.some((stepId) => reachable.has(stepId));\n if (!terminalPathExists) {\n issues.push({\n code: \"no-terminal-path\",\n severity: \"warning\",\n stepId: structure.initial,\n message: `No terminal step is reachable from the initial step \"${structure.initial}\".`,\n });\n }\n\n return {\n issues,\n summary: {\n stepCount: stepIds.length,\n reachableStepCount: reachable.size,\n unreachableStepCount: stepIds.length - reachable.size,\n terminalStepIds,\n cycleCount: cycleKeys.size,\n shadowedTransitionCount: shadowedIndexes.size,\n terminalPathExists,\n },\n };\n}\n\n/**\n * Structural analysis of a graph definition: unreachable steps, shadowed\n * transitions (an earlier unguarded candidate on the same `(from, event)`\n * always wins), cycles, and terminal-path existence. Completion is explicit in\n * this model, so terminal steps are reported as facts in the summary, not as\n * dead-end issues.\n *\n * A plain function over the definition rather than a plugin over a machine.\n * Nothing here needs a runtime \u2014 it is the definition that is being checked \u2014\n * so this runs in a test or a build step, before any machine exists. Linear\n * journeys have no transition graph and so nothing to analyze.\n */\nexport function analyzeStructure(definition: {\n readonly steps: object;\n readonly initial: string;\n}): DiagnosticsResult {\n const { stepIds, transitions } = normalizeGraphDefinition(\n definition as Parameters<typeof normalizeGraphDefinition>[0],\n );\n const structure: JourneyStructure = {\n kind: \"graph\",\n stepIds,\n initial: definition.initial,\n transitions: transitions.map((transition) => ({\n event: transition.event,\n from: transition.from,\n to: transition.to,\n guarded: transition.when !== undefined,\n label: transition.label ?? null,\n index: transition.index,\n })),\n };\n return analyzeJourneyStructure(structure);\n}\n"],
|
|
5
|
+
"mappings": "AAkDO,IAAMA,EAAN,cAA2B,KAAM,CAMtC,YACEC,EACAC,EACAC,EAA+B,CAAC,EAChCC,EACA,CACA,MAAM,YAAYF,CAAO,GAAIE,IAAU,OAAY,OAAY,CAAE,MAAAA,CAAM,CAAC,EACxE,KAAK,KAAO,eACZ,KAAK,KAAOH,EACZ,KAAK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ACL,OAAAC,EACA,QAAS,CACP,UAAWC,EAAQ,OACnB,mBAAoBU,EAAU,KAC9B,qBAAsBV,EAAQ,OAASU,EAAU,KACjD,gBAAAE,EACA,WAAYC,EAAU,KACtB,wBAAyBZ,EAAgB,KACzC,mBAAAmB,CACF,CACF,CACF,CAcO,SAASC,GAAiBC,EAGX,CACpB,GAAM,CAAE,QAAAtB,EAAS,YAAAuB,CAAY,EAAIC,EAC/BF,CACF,EACMxB,EAA8B,CAClC,KAAM,QACN,QAAAE,EACA,QAASsB,EAAW,QACpB,YAAaC,EAAY,IAAKpB,IAAgB,CAC5C,MAAOA,EAAW,MAClB,KAAMA,EAAW,KACjB,GAAIA,EAAW,GACf,QAASA,EAAW,OAAS,OAC7B,MAAOA,EAAW,OAAS,KAC3B,MAAOA,EAAW,KACpB,EAAE,CACJ,EACA,OAAON,GAAwBC,CAAS,CAC1C",
|
|
6
|
+
"names": ["JourneyError", "code", "message", "details", "cause", "isJourneyError", "value", "eventWorkKey", "from", "event", "describeTransition", "transition", "transitionInfo", "SUCCESS_ASYNC", "LOADING_ASYNC", "hasOwn", "target", "key", "reportListenerError", "error", "buildMachineSurface", "runtime", "payload", "id", "n", "work", "listener", "event", "updater", "isDevelopmentEnvironment", "diagnosticGlobal", "nodeEnv", "warnInDevelopment", "message", "detail", "shallowEqual", "a", "b", "left", "right", "keys", "key", "JourneyStore", "initial", "onListenerError", "error", "reportListenerError", "reporterError", "next", "listener", "event", "listeners", "payload", "freezeContextInDevelopment", "context", "isDevelopmentEnvironment", "EMPTY_METADATA", "EMPTY_PLUGINS", "shared", "next", "previous", "shallowEqual", "sharedArray", "equal", "item", "index", "getGraphGuardState", "guard", "enabled", "JourneyRuntime", "config", "SUCCESS_ASYNC", "JourneyStore", "payload", "callback", "updater", "snapshot", "id", "rejected", "hasOwn", "transition", "candidate", "n", "target", "work", "orderIndex", "tip", "type", "event", "from", "declaredWork", "eventWorkKey", "generation", "stagedContext", "contextWasUpdated", "result", "LOADING_ASYNC", "args", "commitResult", "JourneyError", "error", "host", "plugin", "contribution", "failure", "to", "raised", "effect", "label", "timeoutMs", "promise", "overrideMs", "ms", "resolve", "reject", "timer", "value", "seed", "op", "direction", "previousContext", "fromStep", "contextChange", "hasPreEnterEffect", "toStep", "edge", "transitionInfo", "failures", "leaveFailure", "transitionFailure", "describeTransition", "enterFailure", "listener", "processed", "currentId", "visitedNext", "visitedStepCount", "seen", "previousHistory", "visited", "base", "currentBase", "previousLinear", "declaredEvents", "availableEvents", "availableSteps", "outgoingTransitions", "priorities", "selectedEvents", "hasOutgoing", "priority", "selected", "previousGraph", "a", "b", "extensions", "name", "derive", "previousPlugins", "frozen", "DEFAULT_SAVE_REASONS", "normalizeDebounceMs", "value", "buildPersistedState", "snapshot", "now", "JOURNEY_STATUSES", "UNSAFE_KEYS", "scrub", "depth", "item", "output", "key", "parsePersistedState", "raw", "candidate", "id", "resolvePersistStorage", "option", "ambient", "error", "JourneyError", "readRestorableState", "isDeclaredStep", "record", "IDLE_STATE", "createPersistencePlugin", "options", "now", "debounceMs", "normalizeDebounceMs", "saveReasons", "DEFAULT_SAVE_REASONS", "setupCount", "host", "warnInDevelopment", "lastWritten", "state", "timer", "disposed", "succeeded", "written", "failed", "error", "save", "buildPersistedState", "result", "cancelTimer", "runDebounced", "onObservation", "reason", "current", "parsePersistedState", "_snapshot", "previous", "persistOptionToPlugin", "option", "resolvePersistStorage", "createLinearJourney", "definition", "options", "JourneyError", "stepIds", "steps", "input", "config", "hasOwn", "runtimeStep", "restored", "readRestorableState", "id", "runtime", "JourneyRuntime", "persistOptionToPlugin", "surface", "buildMachineSurface", "index", "withLinearTypes", "assertLabel", "label", "where", "meta", "JourneyError", "assertTimeout", "ms", "normalizeGraphDefinition", "definition", "stepIds", "steps", "id", "config", "runtimeStep", "transitions", "eventWork", "pushCandidate", "event", "from", "candidate", "index", "runtimeTransition", "on", "entry", "declared", "work", "eventWorkKey", "createGraphJourney", "options", "hasOwn", "restored", "readRestorableState", "runtime", "JourneyRuntime", "persistOptionToPlugin", "buildMachineSurface", "type", "payload", "withGraphTypes", "defineWork", "config", "analyzeJourneyStructure", "structure", "issues", "stepIds", "shadowedIndexes", "unguardedSeen", "transition", "index", "key", "activeTransitions", "_", "outgoing", "stepId", "reachable", "queue", "terminalStepIds", "cycleKeys", "visited", "stack", "walk", "stackIndex", "cycleSteps", "cycleKey", "terminalPathExists", "analyzeStructure", "definition", "transitions", "normalizeGraphDefinition"]
|
|
7
7
|
}
|