@rxova/journey-core 1.0.0-rc.3 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/README.md +182 -186
  2. package/dist/connectors/immer/immer.cjs +2 -0
  3. package/dist/connectors/immer/immer.cjs.map +7 -0
  4. package/dist/connectors/immer/immer.d.cts +11 -0
  5. package/dist/connectors/immer/immer.d.ts +11 -0
  6. package/dist/connectors/immer/immer.js +2 -0
  7. package/dist/connectors/immer/immer.js.map +7 -0
  8. package/dist/connectors/immer/immer.types.d.cts +9 -0
  9. package/dist/connectors/immer/immer.types.d.ts +9 -0
  10. package/dist/core/errors.d.cts +57 -0
  11. package/dist/core/errors.d.ts +57 -0
  12. package/dist/core/helpers.d.cts +46 -0
  13. package/dist/core/helpers.d.ts +46 -0
  14. package/dist/core/machine.d.cts +9 -0
  15. package/dist/core/machine.d.ts +9 -0
  16. package/dist/core/runtime.d.cts +115 -0
  17. package/dist/core/runtime.d.ts +115 -0
  18. package/dist/core/runtime.types.d.cts +112 -0
  19. package/dist/core/runtime.types.d.ts +112 -0
  20. package/dist/core/store.d.cts +31 -0
  21. package/dist/core/store.d.ts +31 -0
  22. package/dist/core/types.d.cts +481 -0
  23. package/dist/core/types.d.ts +481 -0
  24. package/dist/diagnostics/diagnostics.helpers.d.cts +17 -0
  25. package/dist/diagnostics/diagnostics.helpers.d.ts +17 -0
  26. package/dist/diagnostics/diagnostics.types.d.cts +22 -0
  27. package/dist/diagnostics/diagnostics.types.d.ts +22 -0
  28. package/dist/graph/bag.types.d.cts +91 -0
  29. package/dist/graph/bag.types.d.ts +91 -0
  30. package/dist/graph/graph.d.cts +63 -0
  31. package/dist/graph/graph.d.ts +63 -0
  32. package/dist/graph/graph.types.d.cts +212 -0
  33. package/dist/graph/graph.types.d.ts +212 -0
  34. package/dist/graph/work.d.cts +81 -0
  35. package/dist/graph/work.d.ts +81 -0
  36. package/dist/index.cjs +1 -1
  37. package/dist/index.cjs.map +4 -4
  38. package/dist/index.d.cts +13 -5
  39. package/dist/index.d.ts +13 -5
  40. package/dist/index.js +1 -1
  41. package/dist/index.js.map +4 -4
  42. package/dist/linear/linear.d.cts +33 -0
  43. package/dist/linear/linear.d.ts +33 -0
  44. package/dist/linear/linear.types.d.cts +28 -0
  45. package/dist/linear/linear.types.d.ts +28 -0
  46. package/dist/plugins/analytics/analytics.d.cts +8 -0
  47. package/dist/plugins/analytics/analytics.d.ts +8 -0
  48. package/dist/plugins/analytics/analytics.helpers.d.cts +2 -0
  49. package/dist/plugins/analytics/analytics.helpers.d.ts +2 -0
  50. package/dist/plugins/analytics/analytics.types.d.cts +27 -0
  51. package/dist/plugins/analytics/analytics.types.d.ts +27 -0
  52. package/dist/plugins/execution-paths/execution-paths.d.cts +7 -4
  53. package/dist/plugins/execution-paths/execution-paths.d.ts +7 -4
  54. package/dist/plugins/execution-paths/execution-paths.types.d.cts +21 -0
  55. package/dist/plugins/execution-paths/execution-paths.types.d.ts +21 -0
  56. package/dist/plugins/index.cjs +2 -0
  57. package/dist/plugins/index.cjs.map +7 -0
  58. package/dist/plugins/index.d.cts +19 -0
  59. package/dist/plugins/index.d.ts +19 -0
  60. package/dist/plugins/index.js +2 -0
  61. package/dist/plugins/index.js.map +7 -0
  62. package/dist/plugins/persistence/persistence.d.cts +16 -0
  63. package/dist/plugins/persistence/persistence.d.ts +16 -0
  64. package/dist/plugins/persistence/persistence.helpers.d.cts +34 -0
  65. package/dist/plugins/persistence/persistence.helpers.d.ts +34 -0
  66. package/dist/plugins/persistence/persistence.types.d.cts +63 -0
  67. package/dist/plugins/persistence/persistence.types.d.ts +63 -0
  68. package/dist/plugins/replay/replay.d.cts +7 -0
  69. package/dist/plugins/replay/replay.d.ts +7 -0
  70. package/dist/plugins/replay/replay.helpers.d.cts +22 -0
  71. package/dist/plugins/replay/replay.helpers.d.ts +22 -0
  72. package/dist/plugins/replay/replay.types.d.cts +28 -0
  73. package/dist/plugins/replay/replay.types.d.ts +28 -0
  74. package/package.json +61 -79
  75. package/dist/journey-builder/index.d.cts +0 -5
  76. package/dist/journey-builder/index.d.ts +0 -5
  77. package/dist/journey-builder/types.d.cts +0 -126
  78. package/dist/journey-builder/types.d.ts +0 -126
  79. package/dist/journey-machine/async-state.d.cts +0 -12
  80. package/dist/journey-machine/async-state.d.ts +0 -12
  81. package/dist/journey-machine/computed.d.cts +0 -2
  82. package/dist/journey-machine/computed.d.ts +0 -2
  83. package/dist/journey-machine/controls.d.cts +0 -17
  84. package/dist/journey-machine/controls.d.ts +0 -17
  85. package/dist/journey-machine/helpers.d.cts +0 -52
  86. package/dist/journey-machine/helpers.d.ts +0 -52
  87. package/dist/journey-machine/index.d.cts +0 -3
  88. package/dist/journey-machine/index.d.ts +0 -3
  89. package/dist/journey-machine/navigation.d.cts +0 -32
  90. package/dist/journey-machine/navigation.d.ts +0 -32
  91. package/dist/journey-machine/plugin-controller.d.cts +0 -15
  92. package/dist/journey-machine/plugin-controller.d.ts +0 -15
  93. package/dist/journey-machine/resolve-journey-definition.d.cts +0 -2
  94. package/dist/journey-machine/resolve-journey-definition.d.ts +0 -2
  95. package/dist/journey-machine/runtime.d.cts +0 -33
  96. package/dist/journey-machine/runtime.d.ts +0 -33
  97. package/dist/journey-machine/send.d.cts +0 -9
  98. package/dist/journey-machine/send.d.ts +0 -9
  99. package/dist/plugins/analytics/index.cjs +0 -2
  100. package/dist/plugins/analytics/index.cjs.map +0 -7
  101. package/dist/plugins/analytics/index.d.cts +0 -25
  102. package/dist/plugins/analytics/index.d.ts +0 -25
  103. package/dist/plugins/analytics/index.js +0 -2
  104. package/dist/plugins/analytics/index.js.map +0 -7
  105. package/dist/plugins/autosave/index.cjs +0 -2
  106. package/dist/plugins/autosave/index.cjs.map +0 -7
  107. package/dist/plugins/autosave/index.d.cts +0 -17
  108. package/dist/plugins/autosave/index.d.ts +0 -17
  109. package/dist/plugins/autosave/index.js +0 -2
  110. package/dist/plugins/autosave/index.js.map +0 -7
  111. package/dist/plugins/diagnostics/diagnostics.d.cts +0 -3
  112. package/dist/plugins/diagnostics/diagnostics.d.ts +0 -3
  113. package/dist/plugins/diagnostics/index.cjs +0 -2
  114. package/dist/plugins/diagnostics/index.cjs.map +0 -7
  115. package/dist/plugins/diagnostics/index.d.cts +0 -15
  116. package/dist/plugins/diagnostics/index.d.ts +0 -15
  117. package/dist/plugins/diagnostics/index.js +0 -2
  118. package/dist/plugins/diagnostics/index.js.map +0 -7
  119. package/dist/plugins/execution-paths/index.cjs +0 -2
  120. package/dist/plugins/execution-paths/index.cjs.map +0 -7
  121. package/dist/plugins/execution-paths/index.d.cts +0 -18
  122. package/dist/plugins/execution-paths/index.d.ts +0 -18
  123. package/dist/plugins/execution-paths/index.js +0 -2
  124. package/dist/plugins/execution-paths/index.js.map +0 -7
  125. package/dist/plugins/persistence/controller.d.cts +0 -17
  126. package/dist/plugins/persistence/controller.d.ts +0 -17
  127. package/dist/plugins/persistence/index.cjs +0 -2
  128. package/dist/plugins/persistence/index.cjs.map +0 -7
  129. package/dist/plugins/persistence/index.d.cts +0 -12
  130. package/dist/plugins/persistence/index.d.ts +0 -12
  131. package/dist/plugins/persistence/index.js +0 -2
  132. package/dist/plugins/persistence/index.js.map +0 -7
  133. package/dist/plugins/replay/index.cjs +0 -2
  134. package/dist/plugins/replay/index.cjs.map +0 -7
  135. package/dist/plugins/replay/index.d.cts +0 -27
  136. package/dist/plugins/replay/index.d.ts +0 -27
  137. package/dist/plugins/replay/index.js +0 -2
  138. package/dist/plugins/replay/index.js.map +0 -7
  139. package/dist/types/analytics.types.d.cts +0 -33
  140. package/dist/types/analytics.types.d.ts +0 -33
  141. package/dist/types/autosave.types.d.cts +0 -23
  142. package/dist/types/autosave.types.d.ts +0 -23
  143. package/dist/types/diagnostics.types.d.cts +0 -38
  144. package/dist/types/diagnostics.types.d.ts +0 -38
  145. package/dist/types/index.d.cts +0 -9
  146. package/dist/types/index.d.ts +0 -9
  147. package/dist/types/journey.types.d.cts +0 -191
  148. package/dist/types/journey.types.d.ts +0 -191
  149. package/dist/types/machine.types.d.cts +0 -104
  150. package/dist/types/machine.types.d.ts +0 -104
  151. package/dist/types/observation.types.d.cts +0 -83
  152. package/dist/types/observation.types.d.ts +0 -83
  153. package/dist/types/persistence.types.d.cts +0 -34
  154. package/dist/types/persistence.types.d.ts +0 -34
  155. package/dist/types/replay.types.d.cts +0 -35
  156. package/dist/types/replay.types.d.ts +0 -35
  157. package/dist/types/transitions.types.d.cts +0 -122
  158. package/dist/types/transitions.types.d.ts +0 -122
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/index.ts", "../src/journey-machine/helpers.ts", "../src/journey-machine/async-state.ts", "../src/journey-machine/computed.ts", "../src/journey-machine/controls.ts", "../src/journey-machine/navigation.ts", "../src/journey-machine/plugin-controller.ts", "../src/journey-machine/runtime.ts", "../src/journey-machine/send.ts", "../src/journey-machine/resolve-journey-definition.ts", "../src/journey-machine/index.ts", "../src/journey-builder/index.ts"],
4
- "sourcesContent": ["export { createJourneyMachine } from \"./journey-machine\";\nexport { createJourneyBuilder } from \"./journey-builder\";\nexport { JourneyDisposedError } from \"./journey-machine/helpers\";\nexport type {\n JourneyBuilder,\n JourneyBuilderCustomEventKey,\n JourneyBuilderDefinition,\n JourneyBuilderDefinitionMetadata,\n JourneyBuilderGuard,\n JourneyBuilderOnEntry,\n JourneyBuilderTerminalCandidate,\n JourneyBuilderTerminalEntry,\n JourneyStepBuilder,\n JourneyToBuilder\n} from \"./journey-builder\";\nexport {\n type JourneyAnalyticsEventName,\n type JourneyAnalyticsEventPayload,\n type JourneyAnalyticsPluginOptions,\n type JourneyAnalyticsTrackedEvent,\n type JourneyAutosavePluginOptions,\n type JourneyAutosaveState,\n type JourneyAutosaveStatus,\n type JourneyComputed,\n type JourneyCompleteObservationEvent,\n type JourneyDiagnosticsIssue,\n type JourneyDiagnosticsIssueCode,\n type JourneyDiagnosticsIssueSeverity,\n type JourneyDiagnosticsOptions,\n type JourneyDiagnosticsResult,\n type JourneyDiagnosticsSummary,\n type JourneyDefaultEventType,\n type JourneyDefinition,\n type JourneyEqualityFn,\n type JourneyExecutionPathOptions,\n type JourneyExecutionPathsResult,\n type JourneyFullEventType,\n type JourneyJsonObject,\n type JourneyJsonValue,\n type JourneyLinearStep,\n type JourneyLifecycleErrorContext,\n type JourneyLifecycleErrorObservationEvent,\n type JourneyLifecycleErrorPhase,\n type JourneyLifecycleArgs,\n type JourneyMachine,\n type JourneyMachineOptions,\n type JourneyMachinePlugin,\n type JourneyMachineWithPlugins,\n type JourneyObservationEvent,\n type JourneyPayloadFor,\n type JourneyResolvedTransition,\n type JourneyResetObservationEvent,\n type JourneyReplayEntry,\n type JourneyReplayEventEntry,\n type JourneyReplayExportOptions,\n type JourneyReplayPluginOptions,\n type JourneyReplaySession,\n type JourneyReplaySnapshotEntry,\n type JourneySelector,\n type JourneySendEvent,\n type JourneySendResult,\n type JourneySnapshot,\n type JourneyStartObservationEvent,\n type JourneyStepAsyncState,\n type JourneyStepDefinition,\n type JourneyStepLifecycleCallback,\n type JourneyTerminateObservationEvent,\n type JourneyTransitionArgsForEvent,\n type JourneyTransitionUpdateContextArgsForEvent\n} from \"./types\";\n", "import type {\n JourneyAsyncState,\n JourneyEvent,\n JourneyGoToEvent,\n JourneyJsonObject,\n JourneyJsonValue,\n JourneyPayloadFor,\n JourneyResolvedTransition,\n JourneySendEvent,\n JourneySendResult,\n JourneySnapshot,\n JourneyStatus,\n JourneyStepAsyncState,\n JourneyTerminal,\n JourneyTransition,\n JourneyTransitionArgs\n} from \"../types\";\n\nexport const assertStepExists = <TStepId extends string>(\n steps: Record<TStepId, unknown>,\n stepId: TStepId,\n message: string\n) => {\n if (!(stepId in steps)) {\n throw new Error(message);\n }\n};\n\nexport const isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);\n\nconst cloneSerializableValue = <T extends JourneyJsonValue>(value: T): T => {\n if (Array.isArray(value)) {\n return value.map((entry) => cloneSerializableValue(entry)) as T;\n }\n\n if (isPlainObject(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([key, entryValue]) => [\n key,\n cloneSerializableValue(entryValue as JourneyJsonValue)\n ])\n ) as T;\n }\n\n return value;\n};\n\ntype SerializableCheckState = {\n readonly seen: WeakSet<object>;\n};\n\nconst describeValue = (value: unknown): string => {\n if (value === null) {\n return \"null\";\n }\n\n if (Array.isArray(value)) {\n return \"array\";\n }\n\n if (typeof value === \"object\") {\n const constructorName = (value as { constructor?: { name?: string } }).constructor?.name;\n return constructorName && constructorName !== \"Object\" ? constructorName : \"object\";\n }\n\n return typeof value;\n};\n\nfunction assertSerializableValue(\n value: unknown,\n label: string,\n state: SerializableCheckState,\n path: readonly string[] = []\n): asserts value is JourneyJsonValue {\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return;\n }\n\n const pathLabel = path.length === 0 ? label : `${label}.${path.join(\".\")}`;\n\n if (value === undefined) {\n throw new Error(`${pathLabel} must be JSON-serializable. Received undefined.`);\n }\n\n if (typeof value === \"bigint\" || typeof value === \"symbol\" || typeof value === \"function\") {\n throw new Error(`${pathLabel} must be JSON-serializable. Received ${typeof value}.`);\n }\n\n if (typeof value !== \"object\") {\n throw new Error(`${pathLabel} must be JSON-serializable. Received ${describeValue(value)}.`);\n }\n\n if (state.seen.has(value)) {\n throw new Error(\n `${pathLabel} must be JSON-serializable. Circular references are not supported.`\n );\n }\n\n state.seen.add(value);\n\n if (Array.isArray(value)) {\n for (const [index, entryValue] of value.entries()) {\n assertSerializableValue(entryValue, label, state, [...path, String(index)]);\n }\n return;\n }\n\n if (!isPlainObject(value)) {\n throw new Error(\n `${pathLabel} must be JSON-serializable. Received non-plain ${describeValue(value)}.`\n );\n }\n\n for (const [key, entryValue] of Object.entries(value)) {\n assertSerializableValue(entryValue, label, state, [...path, key]);\n }\n}\n\nexport function assertSerializableContext<TContext extends JourneyJsonObject>(\n context: TContext,\n label = \"Journey context\"\n): TContext {\n assertSerializableValue(context, label, { seen: new WeakSet() });\n return context;\n}\n\nexport const cloneContext = <TContext extends JourneyJsonObject>(context: TContext): TContext =>\n cloneSerializableValue(assertSerializableContext(context));\n\nconst cloneDefinitionValueFallback = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map((entry) => cloneDefinitionValueFallback(entry));\n }\n\n if (value instanceof Date) {\n return new Date(value.getTime());\n }\n\n if (value instanceof Map) {\n return new Map(\n [...value.entries()].map(([key, entryValue]) => [\n cloneDefinitionValueFallback(key),\n cloneDefinitionValueFallback(entryValue)\n ])\n );\n }\n\n if (value instanceof Set) {\n return new Set([...value].map((entry) => cloneDefinitionValueFallback(entry)));\n }\n\n if (isPlainObject(value)) {\n return Object.fromEntries(\n Object.entries(value).map(([key, entryValue]) => [\n key,\n cloneDefinitionValueFallback(entryValue)\n ])\n );\n }\n\n return value;\n};\n\nexport const cloneMetaValue = <T>(value: T): T => {\n if ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) {\n return value;\n }\n\n if (typeof structuredClone === \"function\") {\n try {\n return structuredClone(value);\n } catch {\n return cloneDefinitionValueFallback(value) as T;\n }\n } else {\n return cloneDefinitionValueFallback(value) as T;\n }\n};\n\nconst freezeSnapshotValue = (value: unknown) => {\n if (typeof value !== \"object\" || value === null || Object.isFrozen(value)) {\n return;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n freezeSnapshotValue(item);\n }\n Object.freeze(value);\n return;\n }\n\n if (!isPlainObject(value)) {\n return;\n }\n\n for (const entryValue of Object.values(value)) {\n freezeSnapshotValue(entryValue);\n }\n Object.freeze(value);\n};\n\nexport const normalizeStepCount = (steps?: number): number => {\n if (typeof steps !== \"number\" || !Number.isFinite(steps)) {\n return 1;\n }\n return Math.max(1, Math.trunc(steps));\n};\n\nexport const now = (): number => Date.now();\n\nconst unique = <T>(items: readonly T[]): T[] => [...new Set(items)];\n\nconst normalizeVisited = <TStepId extends string>(\n visited: Record<TStepId, boolean>,\n stepIds: readonly TStepId[]\n): Record<TStepId, boolean> =>\n Object.fromEntries(stepIds.map((stepId) => [stepId, visited[stepId] === true])) as Record<\n TStepId,\n boolean\n >;\n\nexport const buildVisitedFromTimeline = <TStepId extends string>(\n timeline: readonly TStepId[],\n stepIds?: readonly TStepId[]\n): Record<TStepId, boolean> => {\n const resolvedStepIds = stepIds ?? unique(timeline);\n const visited = Object.fromEntries(resolvedStepIds.map((stepId) => [stepId, false])) as Record<\n TStepId,\n boolean\n >;\n\n for (const stepId of timeline) {\n visited[stepId] = true;\n }\n\n return visited;\n};\n\nexport const appendVisited = <TStepId extends string>(\n visited: Record<TStepId, boolean>,\n current: TStepId\n): Record<TStepId, boolean> => ({\n ...visited,\n [current]: true\n});\n\nexport const isPromiseLike = <T>(value: T | PromiseLike<T>): value is PromiseLike<T> =>\n typeof value === \"object\" &&\n value !== null &&\n \"then\" in value &&\n typeof (value as { then: unknown }).then === \"function\";\n\nconst isFiniteNumber = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value);\n\nexport const validateFiniteTimeout = (timeoutMs: unknown, label: string) => {\n if (timeoutMs !== undefined && !isFiniteNumber(timeoutMs)) {\n throw new Error(`${label} must define a finite numeric \"timeoutMs\" when provided.`);\n }\n};\n\nexport class JourneyTimeoutError extends Error {\n override name = \"JourneyTimeoutError\";\n\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class JourneyDisposedError extends Error {\n override name = \"JourneyDisposedError\";\n readonly operation: string;\n\n constructor(operation: string) {\n super(`Journey machine has been disposed; \"${operation}\" can no longer be used.`);\n this.operation = operation;\n }\n}\n\ntype DiagnosticGlobal = typeof globalThis & {\n __DEV__?: unknown;\n process?: {\n env?: {\n NODE_ENV?: string;\n };\n };\n};\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\nexport const warnInDevelopment = (message: string, detail?: unknown) => {\n if (!isDevelopmentEnvironment() || typeof console === \"undefined\") {\n return;\n }\n\n if (detail === undefined) {\n console.warn(message);\n return;\n }\n\n console.warn(message, detail);\n};\n\nexport const errorInDevelopment = (message: string, detail?: unknown) => {\n if (!isDevelopmentEnvironment() || typeof console === \"undefined\") {\n return;\n }\n\n if (detail === undefined) {\n console.error(message);\n return;\n }\n\n console.error(message, detail);\n};\n\nexport const withTimeout = async <T>(\n promise: PromiseLike<T>,\n timeoutMs: number | undefined,\n buildError: () => Error\n): Promise<T> => {\n if (!isFiniteNumber(timeoutMs) || timeoutMs <= 0) {\n return await promise;\n }\n\n return await new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(buildError());\n }, timeoutMs);\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\nexport const withAbortSignal = async <T>(\n promise: PromiseLike<T>,\n signal: AbortSignal\n): Promise<T> => {\n if (signal.aborted) {\n throw signal.reason;\n }\n\n return await new Promise<T>((resolve, reject) => {\n const onAbort = () => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(signal.reason);\n };\n\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (error) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n }\n );\n });\n};\n\nexport const buildIdleStepAsyncState = (): JourneyStepAsyncState => ({\n phase: \"idle\",\n eventType: null,\n transitionId: null,\n error: null\n});\n\nexport const buildInitialAsyncState = <TStepId extends string>(\n steps: Record<TStepId, unknown>\n): JourneyAsyncState<TStepId> => {\n const byStep = Object.fromEntries(\n Object.keys(steps).map((stepId) => [stepId, buildIdleStepAsyncState()])\n ) as Record<TStepId, JourneyStepAsyncState>;\n\n return {\n isLoading: false,\n byStep\n };\n};\n\nexport const isGoToStepByIdEvent = <\n TStepId extends string,\n TEventMap extends Record<string, unknown>\n>(\n event: JourneySendEvent<TStepId, TEventMap>\n): event is JourneyGoToEvent<TStepId, JourneyPayloadFor<TEventMap, \"goToStepById\">> =>\n event.type === \"goToStepById\" && \"stepId\" in event;\n\nexport const isTerminalTarget = <TStepId extends string>(\n target: TStepId | JourneyTerminal\n): target is JourneyTerminal => target === \"COMPLETE\" || target === \"TERMINATED\";\n\nexport const resolveTransitionTarget = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>\n>(\n transition: JourneyTransition<TContext, TStepId, TEventMap, THandlers>\n): TStepId | JourneyTerminal =>\n transition.event === \"completeJourney\"\n ? \"COMPLETE\"\n : transition.event === \"terminateJourney\"\n ? \"TERMINATED\"\n : (transition.to as TStepId | JourneyTerminal);\n\nexport const validateJourneyTransitions = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>\n>(\n transitions: readonly JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers>[],\n steps: Record<TStepId, unknown>\n) => {\n const stepRegistry = steps as Record<string, unknown>;\n const allowedKeys = new Set([\n \"from\",\n \"event\",\n \"to\",\n \"when\",\n \"updateContext\",\n \"onEnter\",\n \"onLeave\",\n \"id\",\n \"label\",\n \"timeoutMs\"\n ]);\n\n for (const [index, transition] of transitions.entries()) {\n if (!transition || typeof transition !== \"object\") {\n throw new Error(`Journey transition at index ${index} must be an object.`);\n }\n\n for (const key of Object.keys(transition)) {\n if (!allowedKeys.has(key)) {\n throw new Error(\n `Journey transition at index ${index} contains unsupported field \"${key}\".`\n );\n }\n }\n\n if (typeof transition.from !== \"string\" || typeof transition.event !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} must define string \"from\" and \"event\".`\n );\n }\n\n if (transition.from !== \"*\" && !(transition.from in stepRegistry)) {\n throw new Error(\n `Journey transition at index ${index} references unknown from step \"${transition.from}\".`\n );\n }\n\n validateFiniteTimeout(transition.timeoutMs, `Journey transition at index ${index}`);\n\n if (transition.when !== undefined && typeof transition.when !== \"function\") {\n throw new Error(\n `Journey transition at index ${index} must define \"when\" as a function when provided.`\n );\n }\n\n if (transition.updateContext !== undefined && typeof transition.updateContext !== \"function\") {\n throw new Error(\n `Journey transition at index ${index} must define \"updateContext\" as a function when provided.`\n );\n }\n\n if (transition.onEnter !== undefined && typeof transition.onEnter !== \"function\") {\n throw new Error(\n `Journey transition at index ${index} must define \"onEnter\" as a function when provided.`\n );\n }\n\n if (transition.onLeave !== undefined && typeof transition.onLeave !== \"function\") {\n throw new Error(\n `Journey transition at index ${index} must define \"onLeave\" as a function when provided.`\n );\n }\n\n if (transition.id !== undefined && typeof transition.id !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} must define \"id\" as a string when provided.`\n );\n }\n\n if (transition.label !== undefined && typeof transition.label !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} must define \"label\" as a string when provided.`\n );\n }\n\n if (transition.event === \"completeJourney\" || transition.event === \"terminateJourney\") {\n if (\"to\" in transition && transition.to !== undefined) {\n throw new Error(\n `Journey transition at index ${index} with event \"${transition.event}\" cannot define \"to\".`\n );\n }\n continue;\n }\n\n if (typeof transition.to !== \"string\") {\n throw new Error(\n `Journey transition at index ${index} with event \"${transition.event}\" must define string \"to\".`\n );\n }\n\n if (!isTerminalTarget(transition.to) && !(transition.to in stepRegistry)) {\n throw new Error(\n `Journey transition at index ${index} points to unknown step \"${transition.to}\".`\n );\n }\n }\n};\n\nexport const buildSendResult = <TContext extends JourneyJsonObject, TStepId extends string>(\n snapshot: JourneySnapshot<TContext, TStepId>,\n transitioned: boolean,\n options: {\n transitionId?: string;\n label?: string;\n error?: unknown;\n } = {}\n): JourneySendResult<TContext, TStepId> => ({\n transitioned,\n ...(options.transitionId !== undefined ? { transitionId: options.transitionId } : {}),\n ...(options.label !== undefined ? { label: options.label } : {}),\n ...(\"error\" in options ? { error: options.error } : {}),\n snapshot\n});\n\nexport const buildSnapshot = <TContext extends JourneyJsonObject, TStepId extends string>(\n timeline: readonly TStepId[],\n index: number,\n context: TContext,\n status: JourneyStatus,\n asyncState: JourneyAsyncState<TStepId>,\n visited?: Record<TStepId, boolean>\n): JourneySnapshot<TContext, TStepId> => {\n if (timeline.length === 0) {\n throw new Error(\"Journey timeline cannot be empty.\");\n }\n\n const safeIndex = Math.max(0, Math.min(Math.trunc(index), timeline.length - 1));\n const currentStepId = timeline[safeIndex] as TStepId;\n const stepIds = unique(\n visited ? ([...(Object.keys(visited) as TStepId[]), ...timeline] as const) : timeline\n );\n\n return {\n status,\n currentStepId,\n history: {\n timeline: [...timeline],\n index: safeIndex\n },\n context: cloneContext(context),\n visited: visited\n ? normalizeVisited(visited, stepIds)\n : buildVisitedFromTimeline(timeline, stepIds),\n async: cloneSerializableValue(\n asyncState as unknown as JourneyJsonValue\n ) as JourneyAsyncState<TStepId>\n };\n};\n\nexport const stabilizeSnapshot = <TContext extends JourneyJsonObject, TStepId extends string>(\n snapshot: JourneySnapshot<TContext, TStepId>\n): JourneySnapshot<TContext, TStepId> => {\n const stableSnapshot: JourneySnapshot<TContext, TStepId> = {\n ...snapshot,\n history: {\n timeline: [...snapshot.history.timeline],\n index: snapshot.history.index\n },\n context: cloneContext(snapshot.context),\n visited: { ...snapshot.visited },\n async: cloneSerializableValue(\n snapshot.async as unknown as JourneyJsonValue\n ) as JourneyAsyncState<TStepId>\n };\n\n freezeSnapshotValue(stableSnapshot);\n return stableSnapshot;\n};\n\nexport const selectTransition = async <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>,\n TTransition extends {\n from: TStepId | \"*\";\n event: string;\n when?: (\n args: JourneyTransitionArgs<TContext, TStepId, TEventMap, THandlers>\n ) => boolean | Promise<boolean>;\n timeoutMs?: number;\n id?: string;\n label?: string;\n }\n>(\n transitions: readonly TTransition[],\n snapshot: JourneySnapshot<TContext, TStepId>,\n event: JourneyEvent<TStepId, TEventMap>,\n signal: AbortSignal,\n handlers: THandlers,\n hooks?: {\n onAsyncGuardStart?: (transition: TTransition) => void;\n onAsyncGuardSuccess?: (transition: TTransition) => void;\n onAsyncGuardError?: (transition: TTransition, error: unknown) => void;\n },\n defaultTimeoutMs?: number\n): Promise<TTransition | null> => {\n for (const transition of transitions) {\n const fromMatches = transition.from === \"*\" || transition.from === snapshot.currentStepId;\n const eventMatches = transition.event === event.type;\n\n if (!fromMatches || !eventMatches) {\n continue;\n }\n\n if (!transition.when) {\n return transition;\n }\n\n let guardResult: boolean | Promise<boolean>;\n if (signal.aborted) {\n throw signal.reason;\n }\n\n guardResult = (\n transition.when as (\n args: JourneyTransitionArgs<TContext, TStepId, TEventMap, THandlers>\n ) => boolean | Promise<boolean>\n )({\n snapshot,\n context: snapshot.context,\n from: snapshot.currentStepId,\n timeline: snapshot.history.timeline,\n index: snapshot.history.index,\n event,\n signal,\n handlers\n });\n\n const asyncGuard = isPromiseLike(guardResult);\n const asyncGuardPromise = asyncGuard ? (guardResult as PromiseLike<boolean>) : null;\n\n let allowed: boolean;\n try {\n if (asyncGuard) {\n hooks?.onAsyncGuardStart?.(transition);\n allowed = await withTimeout(\n withAbortSignal(asyncGuardPromise as PromiseLike<boolean>, signal),\n transition.timeoutMs ?? defaultTimeoutMs,\n () =>\n new JourneyTimeoutError(\n `Transition guard timed out after ${transition.timeoutMs ?? defaultTimeoutMs}ms (event: ${event.type}, transition: ${transition.id ?? \"<anonymous>\"}).`\n )\n );\n } else {\n allowed = guardResult as boolean;\n }\n } catch (error) {\n if (asyncGuard) {\n hooks?.onAsyncGuardError?.(transition, error);\n }\n throw error;\n }\n\n if (asyncGuard) {\n hooks?.onAsyncGuardSuccess?.(transition);\n }\n\n if (allowed) {\n return transition;\n }\n }\n\n return null;\n};\n\nexport const transitionSnapshot = <TContext extends JourneyJsonObject, TStepId extends string>(\n snapshot: JourneySnapshot<TContext, TStepId>,\n nextCurrent: TStepId,\n nextContext: TContext\n): JourneySnapshot<TContext, TStepId> => {\n const baseTimeline = snapshot.history.timeline.slice(0, snapshot.history.index + 1);\n let nextTimeline = baseTimeline;\n if (nextCurrent !== snapshot.currentStepId) {\n nextTimeline = [...baseTimeline, nextCurrent];\n }\n\n const nextIndex = nextTimeline.length - 1;\n const visited = appendVisited(snapshot.visited, nextCurrent);\n\n return buildSnapshot(\n nextTimeline,\n nextIndex,\n nextContext,\n snapshot.status,\n snapshot.async,\n visited\n );\n};\n", "import { buildIdleStepAsyncState } from \"./helpers\";\n\nimport type {\n JourneyAsyncPhase,\n JourneyAsyncState,\n JourneyJsonObject,\n JourneyStepAsyncState\n} from \"../types\";\nimport type { JourneyMachineRuntime } from \"./runtime\";\n\nexport type JourneyMachineAsyncStateController<TStepId extends string> = {\n syncState: (asyncState: JourneyAsyncState<TStepId>) => void;\n updateStepAsync: (\n stepId: TStepId,\n updater: (\n current: JourneyAsyncState<TStepId>[\"byStep\"][TStepId]\n ) => JourneyAsyncState<TStepId>[\"byStep\"][TStepId],\n runVersion?: number\n ) => void;\n setStepLoading: (\n stepId: TStepId,\n phase: JourneyAsyncPhase,\n eventType: string,\n transitionId?: string,\n runVersion?: number\n ) => void;\n setStepIdle: (stepId: TStepId, runVersion?: number) => void;\n setStepError: (\n stepId: TStepId,\n eventType: string,\n error: unknown,\n transitionId?: string,\n runVersion?: number\n ) => void;\n};\n\nexport const createJourneyMachineAsyncStateController = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>\n>({\n runtime\n}: {\n runtime: JourneyMachineRuntime<TContext, TStepId, TEventMap>;\n}): JourneyMachineAsyncStateController<TStepId> => {\n const isAsyncLoadingPhase = (phase: JourneyAsyncPhase): boolean => phase === \"evaluating-when\";\n\n const countLoadingSteps = (asyncState: JourneyAsyncState<TStepId>): number =>\n (Object.values(asyncState.byStep) as JourneyStepAsyncState[]).reduce(\n (count, state) => count + (isAsyncLoadingPhase(state.phase) ? 1 : 0),\n 0\n );\n\n let loadingCount = countLoadingSteps(runtime.peekSnapshot().async);\n\n const syncState = (asyncState: JourneyAsyncState<TStepId>) => {\n loadingCount = countLoadingSteps(asyncState);\n };\n\n const updateStepAsync = (\n stepId: TStepId,\n updater: (\n current: JourneyAsyncState<TStepId>[\"byStep\"][TStepId]\n ) => JourneyAsyncState<TStepId>[\"byStep\"][TStepId],\n runVersion?: number\n ) => {\n if (runVersion !== undefined && !runtime.isRunActive(runVersion)) {\n return;\n }\n\n const snapshot = runtime.peekSnapshot();\n const current = snapshot.async.byStep[stepId] ?? buildIdleStepAsyncState();\n const next = updater(current);\n if (\n current.phase === next.phase &&\n current.eventType === next.eventType &&\n current.transitionId === next.transitionId &&\n current.error === next.error\n ) {\n return;\n }\n\n const nextByStep = {\n ...snapshot.async.byStep,\n [stepId]: next\n };\n const wasLoading = isAsyncLoadingPhase(current.phase);\n const willBeLoading = isAsyncLoadingPhase(next.phase);\n const nextLoadingCount =\n wasLoading === willBeLoading ? loadingCount : loadingCount + (willBeLoading ? 1 : -1);\n runtime.setSnapshot(\n {\n ...snapshot,\n async: {\n isLoading: nextLoadingCount > 0,\n byStep: nextByStep\n }\n },\n { notify: true, reason: \"async\" }\n );\n loadingCount = nextLoadingCount;\n };\n\n return {\n syncState,\n updateStepAsync,\n setStepLoading: (\n stepId: TStepId,\n phase: JourneyAsyncPhase,\n eventType: string,\n transitionId?: string,\n runVersion?: number\n ) => {\n updateStepAsync(\n stepId,\n () => ({\n phase,\n eventType,\n transitionId: transitionId ?? null,\n error: null\n }),\n runVersion\n );\n },\n setStepIdle: (stepId: TStepId, runVersion?: number) => {\n updateStepAsync(stepId, () => buildIdleStepAsyncState(), runVersion);\n },\n setStepError: (\n stepId: TStepId,\n eventType: string,\n error: unknown,\n transitionId?: string,\n runVersion?: number\n ) => {\n updateStepAsync(\n stepId,\n () => ({\n phase: \"error\",\n eventType,\n transitionId: transitionId ?? null,\n error\n }),\n runVersion\n );\n }\n };\n};\n", "import type {\n JourneyComputed,\n JourneyDefinition,\n JourneyJsonObject,\n JourneyLinearTransitions,\n JourneyMode,\n JourneyResolvedDefinition,\n JourneySnapshot\n} from \"../types\";\n\nconst resolveLinearStepOrder = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>\n>(\n transitions: JourneyLinearTransitions<TContext, TStepId, TEventMap, THandlers>\n): readonly TStepId[] =>\n transitions.map((entry) =>\n typeof entry === \"string\" ? entry : entry.step\n ) as readonly TStepId[];\n\nconst countVisitedSteps = <TStepId extends string>(visited: Record<TStepId, boolean>): number => {\n let count = 0;\n for (const stepId in visited) {\n if (visited[stepId]) {\n count += 1;\n }\n }\n return count;\n};\n\nexport const createJourneyMachineComputedGetter = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n TStepMeta,\n THandlers extends Record<string, unknown>\n>(\n journey: JourneyDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>,\n resolvedJourney: JourneyResolvedDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>,\n getSnapshot: () => JourneySnapshot<TContext, TStepId>\n): (() => JourneyComputed<TStepId>) => {\n const mode: JourneyMode =\n journey.transitions === undefined\n ? \"headless\"\n : Array.isArray(journey.transitions)\n ? \"linear\"\n : \"graph\";\n const linearStepOrder =\n mode === \"linear\"\n ? resolveLinearStepOrder(\n journey.transitions as JourneyLinearTransitions<\n TContext,\n TStepId,\n Record<never, never>,\n THandlers\n >\n )\n : null;\n\n return () => {\n const snapshot = getSnapshot();\n const activeStepIndex = snapshot.history.index;\n const base = {\n activeStepId: snapshot.currentStepId,\n activeStepIndex,\n visitedStepCount: countVisitedSteps(snapshot.visited),\n isLoading: snapshot.async.isLoading,\n isIdle: snapshot.status === \"idled\",\n isRunning: snapshot.status === \"running\",\n isComplete: snapshot.status === \"completed\",\n isTerminated: snapshot.status === \"terminated\",\n isInitialStep: snapshot.currentStepId === resolvedJourney.initial\n } as const;\n\n if (mode === \"linear\" && linearStepOrder !== null) {\n const stepCount = linearStepOrder.length;\n const linearIndex = linearStepOrder.indexOf(snapshot.currentStepId);\n\n return {\n ...base,\n activeStepIndex: linearIndex === -1 ? activeStepIndex : linearIndex,\n mode: \"linear\",\n stepCount,\n journeyLength: stepCount,\n isFirstStep: linearIndex === 0,\n isLastStep: linearIndex === stepCount - 1,\n stepOrder: linearStepOrder\n };\n }\n\n if (mode === \"graph\") {\n return {\n ...base,\n mode: \"graph\"\n };\n }\n\n return {\n ...base,\n mode: \"headless\"\n };\n };\n};\n", "import {\n assertSerializableContext,\n buildInitialAsyncState,\n buildSnapshot,\n cloneContext,\n now,\n warnInDevelopment\n} from \"./helpers\";\n\nimport type { JourneyJsonObject, JourneySnapshot } from \"../types\";\nimport type { JourneyMachineAsyncStateController } from \"./async-state\";\nimport type { JourneyMachineRuntime } from \"./runtime\";\n\nexport type JourneyMachineControls<TContext extends JourneyJsonObject, TStepId extends string> = {\n startJourney: () => Promise<JourneySnapshot<TContext, TStepId>>;\n resetJourney: () => Promise<JourneySnapshot<TContext, TStepId>>;\n updateContext: (\n updater: (context: TContext) => TContext\n ) => Promise<JourneySnapshot<TContext, TStepId>>;\n clearStepError: (stepId?: TStepId) => Promise<JourneySnapshot<TContext, TStepId>>;\n dispose: () => void;\n};\n\nexport const createJourneyMachineControls = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>\n>({\n runtime,\n asyncState,\n initial,\n initialContext,\n steps\n}: {\n runtime: JourneyMachineRuntime<TContext, TStepId, TEventMap>;\n asyncState: JourneyMachineAsyncStateController<TStepId>;\n initial: TStepId;\n initialContext: TContext;\n steps: Record<TStepId, unknown>;\n}): JourneyMachineControls<TContext, TStepId> => {\n const warnDisposedNoop = (operation: string) => {\n warnInDevelopment(`Journey machine has been disposed; \"${operation}\" is a no-op.`);\n };\n\n const buildResetSnapshot = () =>\n buildSnapshot(\n [initial],\n 0,\n cloneContext(initialContext),\n \"idled\",\n buildInitialAsyncState(steps)\n );\n\n return {\n startJourney: () => {\n if (runtime.isDisposed()) {\n warnDisposedNoop(\"startJourney\");\n return Promise.resolve(runtime.getSnapshot());\n }\n\n return runtime.queue(\n async () => {\n const snapshot = runtime.peekSnapshot();\n if (snapshot.status !== \"idled\") {\n return runtime.getSnapshot();\n }\n\n const committedSnapshot = runtime.setSnapshot(\n {\n ...snapshot,\n status: \"running\"\n },\n { notify: true, reason: \"start\" }\n );\n runtime.emit({\n type: \"journey.start\",\n stepId: committedSnapshot.currentStepId,\n timestamp: now()\n });\n return runtime.getSnapshot();\n },\n () => runtime.getSnapshot()\n );\n },\n resetJourney: () => {\n if (runtime.isDisposed()) {\n warnDisposedNoop(\"resetJourney\");\n return Promise.resolve(runtime.getSnapshot());\n }\n\n runtime.cancelInFlight();\n return runtime.queue(\n async () => {\n const committedSnapshot = runtime.setSnapshot(buildResetSnapshot(), {\n notify: true,\n reason: \"reset\"\n });\n runtime.emit({\n type: \"journey.reset\",\n stepId: committedSnapshot.currentStepId,\n timestamp: now()\n });\n asyncState.syncState(committedSnapshot.async);\n return runtime.getSnapshot();\n },\n () => runtime.getSnapshot()\n );\n },\n updateContext: (updater) => {\n if (runtime.isDisposed()) {\n warnDisposedNoop(\"updateContext\");\n return Promise.resolve(runtime.getSnapshot());\n }\n\n return runtime.queue(\n async () => {\n const snapshot = runtime.peekSnapshot();\n const nextContext = assertSerializableContext(updater(cloneContext(snapshot.context)));\n const committedSnapshot = runtime.setSnapshot(\n {\n ...snapshot,\n context: nextContext\n },\n { notify: true, reason: \"context\" }\n );\n return committedSnapshot;\n },\n () => runtime.getSnapshot()\n );\n },\n clearStepError: (stepId?: TStepId) => {\n if (runtime.isDisposed()) {\n warnDisposedNoop(\"clearStepError\");\n return Promise.resolve(runtime.getSnapshot());\n }\n\n return runtime.queue(\n async () => {\n const snapshot = runtime.peekSnapshot();\n const resolvedStep = stepId ?? snapshot.currentStepId;\n if (!(resolvedStep in steps)) {\n return runtime.getSnapshot();\n }\n\n asyncState.setStepIdle(resolvedStep);\n return runtime.getSnapshot();\n },\n () => runtime.getSnapshot()\n );\n },\n dispose: () => {\n runtime.dispose();\n }\n };\n};\n", "import {\n assertStepExists,\n buildSendResult,\n buildSnapshot,\n normalizeStepCount,\n now,\n transitionSnapshot\n} from \"./helpers\";\n\nimport type {\n JourneyEvent,\n JourneyJsonObject,\n JourneyResolvedTransition,\n JourneySendResult,\n JourneySnapshot,\n JourneyTerminal\n} from \"../types\";\nimport type { JourneyMachineRuntime } from \"./runtime\";\n\nexport type JourneyLifecycleScheduler<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>\n> = (args: {\n previousSnapshot: JourneySnapshot<TContext, TStepId>;\n snapshot: JourneySnapshot<TContext, TStepId>;\n from: TStepId;\n to: TStepId | JourneyTerminal;\n event:\n | JourneyEvent<TStepId, TEventMap>\n | { type: \"goToLastVisitedStep\" }\n | { type: \"goToPreviousStep\" };\n transitionId: string | null;\n label?: string;\n runVersion: number;\n transition?: JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers>;\n}) => void;\n\nexport type JourneyMachineNavigationController<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>\n> = {\n applyPreviousNavigation: (\n requestedSteps?: number,\n transitionId?: string,\n runVersion?: number\n ) => JourneySendResult<TContext, TStepId>;\n applyLastVisitedNavigation: (\n transitionId?: string,\n runVersion?: number\n ) => JourneySendResult<TContext, TStepId>;\n hasDeclaredTransitionForEvent: (fromStep: TStepId, eventType: string) => boolean;\n commitTerminalTransition: (\n fromStep: TStepId,\n target: JourneyTerminal,\n transitionEvent: { type: string },\n transitionId: string | null,\n transition: JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers> | undefined,\n nextContext: TContext,\n runVersion?: number\n ) => JourneySendResult<TContext, TStepId>;\n commitStepTransition: (\n fromStep: TStepId,\n target: TStepId,\n transitionEvent: JourneyEvent<TStepId, TEventMap>,\n transition: JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers>,\n nextContext: TContext,\n runVersion?: number\n ) => JourneySendResult<TContext, TStepId>;\n};\n\nexport const createJourneyMachineNavigationController = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>\n>({\n runtime,\n steps,\n transitions,\n scheduleLifecycle\n}: {\n runtime: JourneyMachineRuntime<TContext, TStepId, TEventMap>;\n steps: Record<TStepId, unknown>;\n transitions: readonly JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers>[];\n scheduleLifecycle: JourneyLifecycleScheduler<TContext, TStepId, TEventMap, THandlers>;\n}): JourneyMachineNavigationController<TContext, TStepId, TEventMap, THandlers> => ({\n applyPreviousNavigation: (requestedSteps?: number, transitionId?: string, runVersion = 0) => {\n const snapshot = runtime.peekSnapshot();\n if (snapshot.status !== \"running\") {\n return buildSendResult(runtime.getSnapshot(), false);\n }\n\n const stepsToGoBack = normalizeStepCount(requestedSteps);\n if (snapshot.history.index === 0) {\n return buildSendResult(runtime.getSnapshot(), false);\n }\n\n const from = snapshot.currentStepId;\n const nextIndex = Math.max(0, snapshot.history.index - stepsToGoBack);\n const appliedSteps = snapshot.history.index - nextIndex;\n if (appliedSteps <= 0) {\n return buildSendResult(runtime.getSnapshot(), false);\n }\n\n runtime.emit({ type: \"step.exit\", stepId: from, timestamp: now() });\n const committedSnapshot = runtime.setSnapshot(\n buildSnapshot(\n snapshot.history.timeline,\n nextIndex,\n snapshot.context,\n snapshot.status,\n snapshot.async,\n snapshot.visited\n ),\n {\n notify: true,\n reason: \"navigation\"\n }\n );\n\n runtime.emit({\n type: \"navigation.previous\",\n from,\n to: committedSnapshot.currentStepId,\n requestedSteps: stepsToGoBack,\n appliedSteps,\n timestamp: now()\n });\n runtime.emit({ type: \"step.enter\", stepId: committedSnapshot.currentStepId, timestamp: now() });\n scheduleLifecycle({\n previousSnapshot: snapshot,\n snapshot: committedSnapshot,\n from,\n to: committedSnapshot.currentStepId,\n event: { type: \"goToPreviousStep\" },\n transitionId: transitionId ?? null,\n runVersion\n });\n\n return buildSendResult(committedSnapshot, true, {\n ...(transitionId !== undefined ? { transitionId } : {})\n });\n },\n applyLastVisitedNavigation: (transitionId?: string, runVersion = 0) => {\n const snapshot = runtime.peekSnapshot();\n if (snapshot.status !== \"running\") {\n return buildSendResult(runtime.getSnapshot(), false);\n }\n\n const targetIndex = snapshot.history.timeline.length - 1;\n if (snapshot.history.index >= targetIndex) {\n return buildSendResult(runtime.getSnapshot(), false);\n }\n\n const from = snapshot.currentStepId;\n runtime.emit({ type: \"step.exit\", stepId: from, timestamp: now() });\n const committedSnapshot = runtime.setSnapshot(\n buildSnapshot(\n snapshot.history.timeline,\n targetIndex,\n snapshot.context,\n snapshot.status,\n snapshot.async,\n snapshot.visited\n ),\n {\n notify: true,\n reason: \"navigation\"\n }\n );\n\n runtime.emit({\n type: \"navigation.lastVisited\",\n from,\n to: committedSnapshot.currentStepId,\n timestamp: now()\n });\n runtime.emit({ type: \"step.enter\", stepId: committedSnapshot.currentStepId, timestamp: now() });\n scheduleLifecycle({\n previousSnapshot: snapshot,\n snapshot: committedSnapshot,\n from,\n to: committedSnapshot.currentStepId,\n event: { type: \"goToLastVisitedStep\" },\n transitionId: transitionId ?? null,\n runVersion\n });\n\n return buildSendResult(committedSnapshot, true, {\n ...(transitionId !== undefined ? { transitionId } : {})\n });\n },\n hasDeclaredTransitionForEvent: (fromStep: TStepId, eventType: string) =>\n transitions.some((transition) => {\n const fromMatches = transition.from === \"*\" || transition.from === fromStep;\n return fromMatches && transition.event === eventType;\n }),\n commitTerminalTransition: (\n fromStep: TStepId,\n target: JourneyTerminal,\n transitionEvent: { type: string },\n transitionId: string | null,\n transition: JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers> | undefined,\n nextContext: TContext,\n runVersion = 0\n ) => {\n const snapshot = runtime.peekSnapshot();\n const normalizedTimeline = snapshot.history.timeline.slice(0, snapshot.history.index + 1);\n const committedSnapshot = runtime.setSnapshot(\n {\n ...snapshot,\n history: {\n timeline: normalizedTimeline,\n index: normalizedTimeline.length - 1\n },\n context: nextContext,\n status: target === \"COMPLETE\" ? \"completed\" : \"terminated\"\n },\n {\n notify: true,\n reason: \"transition\"\n }\n );\n\n runtime.emit({\n type: \"transition.success\",\n from: fromStep,\n to: target,\n eventType: transitionEvent.type,\n transitionId,\n ...(transition?.label !== undefined ? { label: transition.label } : {}),\n timestamp: now()\n });\n runtime.emit({\n type: target === \"COMPLETE\" ? \"journey.completed\" : \"journey.terminated\",\n stepId: committedSnapshot.currentStepId,\n timestamp: now()\n });\n scheduleLifecycle({\n previousSnapshot: snapshot,\n snapshot: committedSnapshot,\n from: fromStep,\n to: target,\n event: transitionEvent as JourneyEvent<TStepId, TEventMap>,\n transitionId,\n ...(transition?.label !== undefined ? { label: transition.label } : {}),\n runVersion,\n ...(transition !== undefined ? { transition } : {})\n });\n\n return buildSendResult(committedSnapshot, true, {\n ...(transitionId !== null ? { transitionId } : {}),\n ...(transition?.label !== undefined ? { label: transition.label } : {})\n });\n },\n commitStepTransition: (\n fromStep: TStepId,\n target: TStepId,\n transitionEvent: JourneyEvent<TStepId, TEventMap>,\n transition: JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers>,\n nextContext: TContext,\n runVersion = 0\n ) => {\n assertStepExists(steps, target, `Transition points to unknown step \"${target}\".`);\n\n const snapshot = runtime.peekSnapshot();\n const beforeCurrent = snapshot.currentStepId;\n if (beforeCurrent !== target) {\n runtime.emit({ type: \"step.exit\", stepId: beforeCurrent, timestamp: now() });\n }\n\n const committedSnapshot = runtime.setSnapshot(\n transitionSnapshot(snapshot, target, nextContext),\n {\n notify: true,\n reason: \"transition\"\n }\n );\n\n runtime.emit({\n type: \"transition.success\",\n from: fromStep,\n to: committedSnapshot.currentStepId,\n eventType: transitionEvent.type,\n transitionId: transition.id,\n ...(transition.label !== undefined ? { label: transition.label } : {}),\n timestamp: now()\n });\n if (beforeCurrent !== committedSnapshot.currentStepId) {\n runtime.emit({\n type: \"step.enter\",\n stepId: committedSnapshot.currentStepId,\n timestamp: now()\n });\n }\n scheduleLifecycle({\n previousSnapshot: snapshot,\n snapshot: committedSnapshot,\n from: fromStep,\n to: committedSnapshot.currentStepId,\n event: transitionEvent,\n transitionId: transition.id,\n ...(transition.label !== undefined ? { label: transition.label } : {}),\n runVersion,\n transition\n });\n\n return buildSendResult(committedSnapshot, true, {\n transitionId: transition.id,\n ...(transition.label !== undefined ? { label: transition.label } : {})\n });\n }\n});\n", "import { isPromiseLike, warnInDevelopment } from \"./helpers\";\n\nimport type {\n JourneyDefinition,\n JourneyJsonObject,\n JourneyMachine,\n JourneyMachinePlugin,\n JourneyMachinePluginHooks,\n JourneyMachinePluginSetupContext,\n JourneyMachineSnapshotReason,\n JourneyResolvedDefinition,\n JourneySnapshot\n} from \"../types\";\n\nexport type JourneyMachinePluginController<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n TStepMeta,\n THandlers extends Record<string, unknown>\n> = {\n hydrateSnapshot: (\n snapshot: JourneySnapshot<TContext, TStepId>\n ) => JourneySnapshot<TContext, TStepId>;\n onSnapshotChange: (args: {\n previousSnapshot: JourneySnapshot<TContext, TStepId>;\n snapshot: JourneySnapshot<TContext, TStepId>;\n reason: JourneyMachineSnapshotReason;\n }) => void;\n extendMachine: (\n machine: JourneyMachine<TContext, TStepId, TEventMap, TStepMeta, THandlers>\n ) => JourneyMachine<TContext, TStepId, TEventMap, TStepMeta, THandlers>;\n dispose: () => void;\n};\n\nexport const createJourneyMachinePluginController = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n TStepMeta,\n THandlers extends Record<string, unknown> = Record<never, never>\n>({\n plugins,\n setupContext\n}: {\n plugins: readonly JourneyMachinePlugin[];\n setupContext: JourneyMachinePluginSetupContext<\n TContext,\n TStepId,\n TEventMap,\n TStepMeta,\n THandlers\n >;\n}): JourneyMachinePluginController<TContext, TStepId, TEventMap, TStepMeta, THandlers> => {\n const hooks: {\n name: string;\n hooks: JourneyMachinePluginHooks<TContext, TStepId, TEventMap, TStepMeta, THandlers>;\n }[] = [];\n\n for (const plugin of plugins) {\n try {\n hooks.push({\n name: plugin.name,\n hooks: plugin.setup(setupContext) as JourneyMachinePluginHooks<\n TContext,\n TStepId,\n TEventMap,\n TStepMeta,\n THandlers\n >\n });\n } catch (error) {\n for (const initializedPlugin of [...hooks].reverse()) {\n try {\n initializedPlugin.hooks.dispose?.();\n } catch {\n // Preserve the original setup error; cleanup failures are secondary.\n }\n }\n\n const message = error instanceof Error ? error.message : String(error);\n const pluginError = new Error(`Journey plugin \"${plugin.name}\" setup failed: ${message}`);\n Object.assign(pluginError, { cause: error });\n throw pluginError;\n }\n }\n\n return {\n hydrateSnapshot: (snapshot) =>\n hooks.reduce(\n (currentSnapshot, plugin) =>\n plugin.hooks.hydrateSnapshot?.(currentSnapshot) ?? currentSnapshot,\n snapshot\n ),\n onSnapshotChange: ({ previousSnapshot, snapshot, reason }) => {\n let firstError: unknown;\n for (const plugin of hooks) {\n try {\n const result = plugin.hooks.onSnapshotChange?.({\n previousSnapshot,\n snapshot,\n reason\n });\n if (isPromiseLike(result)) {\n warnInDevelopment(\n `Journey plugin \"${plugin.name}\" returned a Promise from onSnapshotChange. ` +\n \"This hook must be synchronous; returning a Promise blocks the machine and the await is dropped.\"\n );\n }\n } catch (error) {\n firstError ??= error;\n }\n }\n if (firstError !== undefined) {\n throw firstError;\n }\n },\n extendMachine: (machine) => {\n const extensionTarget = machine as JourneyMachine<\n TContext,\n TStepId,\n TEventMap,\n TStepMeta,\n THandlers\n >;\n const writableExtensionTarget = machine as Record<string, unknown>;\n const pluginExtensionKeys = new Map<string, string>();\n\n for (const plugin of hooks) {\n const extension = plugin.hooks.augmentMachine?.({\n machine,\n journey: setupContext.journey as JourneyDefinition<\n TContext,\n TStepId,\n TEventMap,\n TStepMeta,\n THandlers\n >,\n resolvedJourney: setupContext.resolvedJourney as JourneyResolvedDefinition<\n TContext,\n TStepId,\n TEventMap,\n TStepMeta,\n THandlers\n >\n });\n\n if (!extension) {\n continue;\n }\n\n for (const [key, value] of Object.entries(extension)) {\n const existingPlugin = pluginExtensionKeys.get(key);\n if (existingPlugin) {\n throw new Error(\n `Journey plugin \"${plugin.name}\" cannot add \"${key}\" \u2014 already provided by plugin \"${existingPlugin}\".`\n );\n }\n if (key in extensionTarget) {\n throw new Error(\n `Journey plugin \"${plugin.name}\" cannot override machine property \"${key}\".`\n );\n }\n pluginExtensionKeys.set(key, plugin.name);\n writableExtensionTarget[key] = value;\n }\n }\n\n return extensionTarget;\n },\n dispose: () => {\n let firstError: unknown;\n for (const plugin of hooks) {\n try {\n plugin.hooks.dispose?.();\n } catch (error) {\n firstError ??= error;\n }\n }\n if (firstError !== undefined) {\n throw firstError;\n }\n }\n };\n};\n", "import { errorInDevelopment, stabilizeSnapshot } from \"./helpers\";\n\nimport type {\n JourneyEqualityFn,\n JourneyJsonObject,\n JourneyMachineSnapshotReason,\n JourneyObservationEvent,\n JourneySelector,\n JourneySnapshot\n} from \"../types\";\n\ntype SnapshotOptions = {\n notify?: boolean;\n reason?: JourneyMachineSnapshotReason;\n};\n\nexport type JourneyMachineRuntime<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>\n> = {\n getSnapshot: () => JourneySnapshot<TContext, TStepId>;\n peekSnapshot: () => JourneySnapshot<TContext, TStepId>;\n setSnapshot: (\n nextSnapshot: JourneySnapshot<TContext, TStepId>,\n options?: SnapshotOptions\n ) => JourneySnapshot<TContext, TStepId>;\n isDisposed: () => boolean;\n isRunActive: (runVersion: number) => boolean;\n cancelInFlight: () => void;\n openLifecycle: (runVersion: number) => AbortController | null;\n closeLifecycle: (controller: AbortController) => void;\n queue: <T>(\n runner: (runVersion: number, signal: AbortSignal) => Promise<T>,\n onCanceled: () => T\n ) => Promise<T>;\n notify: () => void;\n emit: (event: JourneyObservationEvent<TStepId, TEventMap>) => void;\n subscribe: (listener: () => void) => () => void;\n subscribeSelector: <TSelected>(\n selector: JourneySelector<TContext, TStepId, TSelected>,\n listener: (next: TSelected, previous: TSelected) => void,\n equalityFn?: JourneyEqualityFn<TSelected>\n ) => () => void;\n subscribeEvent: (\n listener: (event: JourneyObservationEvent<TStepId, TEventMap>) => void\n ) => () => void;\n dispose: () => void;\n};\n\nexport const createJourneyMachineRuntime = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>\n>({\n snapshot: initialSnapshot,\n onSnapshotChange,\n onDispose,\n onListenerError\n}: {\n snapshot: JourneySnapshot<TContext, TStepId>;\n onSnapshotChange?: (args: {\n previousSnapshot: JourneySnapshot<TContext, TStepId>;\n snapshot: JourneySnapshot<TContext, TStepId>;\n reason: JourneyMachineSnapshotReason;\n }) => void;\n onDispose?: () => void;\n onListenerError?: (error: unknown, context: \"snapshot\" | \"event\") => void;\n}): JourneyMachineRuntime<TContext, TStepId, TEventMap> => {\n let snapshot = stabilizeSnapshot(initialSnapshot);\n let exposedSnapshot = stabilizeSnapshot(snapshot);\n const listeners = new Set<() => void>();\n const eventListeners = new Set<(event: JourneyObservationEvent<TStepId, TEventMap>) => void>();\n let actionQueue: Promise<void> = Promise.resolve();\n let lifecycleVersion = 0;\n let isDisposed = false;\n let activeAbortController: AbortController | null = null;\n const lifecycleAbortControllers = new Set<AbortController>();\n const reportListenerError =\n onListenerError ??\n ((error: unknown, context: \"snapshot\" | \"event\") => {\n errorInDevelopment(`Journey ${context} listener threw an error.`, error);\n });\n\n const notify = () => {\n for (const listener of listeners) {\n try {\n listener();\n } catch (error) {\n // Individual listener failure must not block other listeners.\n reportListenerError(error, \"snapshot\");\n }\n }\n };\n\n const emit = (event: JourneyObservationEvent<TStepId, TEventMap>) => {\n for (const listener of eventListeners) {\n try {\n listener(event);\n } catch (error) {\n // Individual listener failure must not block other listeners.\n reportListenerError(error, \"event\");\n }\n }\n };\n\n const setSnapshot = (\n nextSnapshot: JourneySnapshot<TContext, TStepId>,\n options: SnapshotOptions = {}\n ) => {\n const previousExposedSnapshot = exposedSnapshot;\n const stableSnapshot = stabilizeSnapshot(nextSnapshot);\n const nextExposedSnapshot = stabilizeSnapshot(stableSnapshot);\n onSnapshotChange?.({\n previousSnapshot: stabilizeSnapshot(previousExposedSnapshot),\n snapshot: stabilizeSnapshot(nextExposedSnapshot),\n reason: options.reason ?? \"transition\"\n });\n snapshot = stableSnapshot;\n exposedSnapshot = nextExposedSnapshot;\n if (options.notify) {\n notify();\n }\n return nextExposedSnapshot;\n };\n\n const isRunActive = (runVersion: number): boolean =>\n !isDisposed && runVersion === lifecycleVersion;\n\n const cancelInFlight = () => {\n lifecycleVersion += 1;\n if (activeAbortController && !activeAbortController.signal.aborted) {\n activeAbortController.abort();\n }\n activeAbortController = null;\n for (const controller of lifecycleAbortControllers) {\n if (!controller.signal.aborted) {\n controller.abort();\n }\n }\n lifecycleAbortControllers.clear();\n actionQueue = Promise.resolve();\n };\n\n const openLifecycle = (runVersion: number): AbortController | null => {\n if (!isRunActive(runVersion)) {\n return null;\n }\n\n const controller = new AbortController();\n if (!isRunActive(runVersion)) {\n controller.abort();\n return null;\n }\n\n lifecycleAbortControllers.add(controller);\n return controller;\n };\n\n const closeLifecycle = (controller: AbortController) => {\n lifecycleAbortControllers.delete(controller);\n };\n\n const queue = <T>(\n runner: (runVersion: number, signal: AbortSignal) => Promise<T>,\n onCanceled: () => T\n ): Promise<T> => {\n const runVersion = lifecycleVersion;\n const createQueuedRunner = async () => {\n if (!isRunActive(runVersion)) {\n return onCanceled();\n }\n const abortController = new AbortController();\n activeAbortController = abortController;\n\n try {\n if (!isRunActive(runVersion)) {\n abortController.abort();\n return onCanceled();\n }\n\n return await runner(runVersion, abortController.signal);\n } finally {\n if (activeAbortController === abortController) {\n activeAbortController = null;\n }\n }\n };\n\n const resultPromise = actionQueue.then(createQueuedRunner, createQueuedRunner);\n // Both handlers map to `undefined` intentionally: a failed operation must\n // not block subsequent queued operations \u2014 each entry runs independently.\n actionQueue = resultPromise.then(\n () => undefined,\n () => undefined\n );\n return resultPromise;\n };\n\n const subscribe = (listener: () => void) => {\n if (isDisposed) {\n return () => undefined;\n }\n\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n };\n\n const subscribeSelector = <TSelected>(\n selector: JourneySelector<TContext, TStepId, TSelected>,\n listener: (next: TSelected, previous: TSelected) => void,\n equalityFn?: JourneyEqualityFn<TSelected>\n ) => {\n if (isDisposed) {\n return () => undefined;\n }\n\n const isEqual = equalityFn ?? Object.is;\n let selected = selector(exposedSnapshot);\n\n return subscribe(() => {\n const nextSelected = selector(exposedSnapshot);\n if (isEqual(selected, nextSelected)) {\n return;\n }\n\n const previous = selected;\n selected = nextSelected;\n listener(nextSelected, previous);\n });\n };\n\n const subscribeEvent = (\n listener: (event: JourneyObservationEvent<TStepId, TEventMap>) => void\n ) => {\n if (isDisposed) {\n return () => undefined;\n }\n\n eventListeners.add(listener);\n return () => {\n eventListeners.delete(listener);\n };\n };\n\n const dispose = () => {\n if (isDisposed) {\n return;\n }\n\n isDisposed = true;\n cancelInFlight();\n listeners.clear();\n eventListeners.clear();\n onDispose?.();\n };\n\n return {\n getSnapshot: () => exposedSnapshot,\n peekSnapshot: () => snapshot,\n setSnapshot,\n isDisposed: () => isDisposed,\n isRunActive,\n cancelInFlight,\n openLifecycle,\n closeLifecycle,\n queue,\n notify,\n emit,\n subscribe,\n subscribeSelector,\n subscribeEvent,\n dispose\n };\n};\n", "import {\n assertSerializableContext,\n assertStepExists,\n buildSendResult,\n JourneyDisposedError,\n isGoToStepByIdEvent,\n isTerminalTarget,\n now,\n resolveTransitionTarget,\n selectTransition,\n stabilizeSnapshot\n} from \"./helpers\";\n\nimport type {\n JourneyEvent,\n JourneyJsonObject,\n JourneyResolvedTransition,\n JourneySendEvent,\n JourneySendResult,\n JourneyTransitionArgsForEvent,\n JourneyTransitionUpdateContextArgsForEvent\n} from \"../types\";\nimport type { JourneyMachineAsyncStateController } from \"./async-state\";\nimport type { JourneyMachineNavigationController } from \"./navigation\";\nimport type { JourneyMachineRuntime } from \"./runtime\";\n\ntype RuntimeSendEvent<\n TStepId extends string,\n TEventMap extends Record<string, unknown>\n> = JourneySendEvent<TStepId, TEventMap>;\n\ntype RuntimeTransitionEvent<\n TStepId extends string,\n TEventMap extends Record<string, unknown>\n> = JourneyEvent<TStepId, TEventMap>;\n\ntype RuntimeTransition<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>\n> = JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers>;\n\nexport type JourneyMachineSendController<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>\n> = {\n executeSend: (\n event: JourneySendEvent<TStepId, TEventMap>,\n runVersion: number,\n signal: AbortSignal\n ) => Promise<JourneySendResult<TContext, TStepId>>;\n buildCanceledSendResult: (operation?: string) => JourneySendResult<TContext, TStepId>;\n};\n\nexport const createJourneyMachineSendController = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>\n>(\n runtime: JourneyMachineRuntime<TContext, TStepId, TEventMap>,\n asyncState: JourneyMachineAsyncStateController<TStepId>,\n navigation: JourneyMachineNavigationController<TContext, TStepId, TEventMap, THandlers>,\n headless: boolean,\n steps: Record<TStepId, unknown>,\n transitions: readonly JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers>[],\n handlers: THandlers,\n requireExplicitCompletion: boolean,\n defaultTimeoutMs: number | undefined\n): JourneyMachineSendController<TContext, TStepId, TEventMap> => {\n const buildCanceledSendResult = (operation = \"send\"): JourneySendResult<TContext, TStepId> =>\n buildSendResult(runtime.getSnapshot(), false, {\n ...(runtime.isDisposed() ? { error: new JourneyDisposedError(operation) } : {})\n });\n\n const buildErroredSendResult = (\n error: unknown,\n transitionId?: string,\n label?: string\n ): JourneySendResult<TContext, TStepId> =>\n buildSendResult(runtime.getSnapshot(), false, {\n ...(transitionId !== undefined ? { transitionId } : {}),\n ...(label !== undefined ? { label } : {}),\n error\n });\n\n const buildTransitionErrorResult = (\n fromStep: TStepId,\n eventType: string,\n error: unknown,\n transitionId: string | null,\n label: string | undefined,\n runVersion: number,\n skipAsyncStateUpdate = false\n ): JourneySendResult<TContext, TStepId> => {\n if (!skipAsyncStateUpdate) {\n asyncState.setStepError(fromStep, eventType, error, transitionId ?? undefined, runVersion);\n }\n runtime.emit({\n type: \"transition.error\",\n from: fromStep,\n eventType,\n transitionId,\n ...(label !== undefined ? { label } : {}),\n error,\n timestamp: now()\n });\n return buildErroredSendResult(error, transitionId ?? undefined, label);\n };\n\n const resolveTransitionsForSend = (\n event: RuntimeSendEvent<TStepId, TEventMap>,\n fromStep: TStepId\n ): {\n transitionsToEvaluate: readonly RuntimeTransition<TContext, TStepId, TEventMap, THandlers>[];\n earlyResult: JourneySendResult<TContext, TStepId> | null;\n } => {\n if (!isGoToStepByIdEvent(event)) {\n return { transitionsToEvaluate: transitions, earlyResult: null };\n }\n\n assertStepExists(steps, event.stepId, `Cannot goToStepById unknown step \"${event.stepId}\".`);\n\n return {\n transitionsToEvaluate: transitions.filter((transition) => {\n const fromMatches = transition.from === \"*\" || transition.from === fromStep;\n return (\n fromMatches &&\n transition.event === \"goToStepById\" &&\n \"to\" in transition &&\n transition.to === event.stepId\n );\n }),\n earlyResult: null\n };\n };\n\n const selectTransitionForSend = async (\n transitionsToEvaluate: readonly RuntimeTransition<TContext, TStepId, TEventMap, THandlers>[],\n transitionEvent: RuntimeTransitionEvent<TStepId, TEventMap>,\n fromStep: TStepId,\n runVersion: number,\n signal: AbortSignal\n ): Promise<\n | {\n transition: RuntimeTransition<TContext, TStepId, TEventMap, THandlers> | null;\n earlyResult: null;\n }\n | { transition: null; earlyResult: JourneySendResult<TContext, TStepId> }\n > => {\n let transition;\n let asyncGuardErrorTransitionId: string | null = null;\n let asyncGuardErrorLabel: string | undefined;\n let asyncGuardErrorHandled = false;\n try {\n transition = (await selectTransition(\n transitionsToEvaluate as unknown as never,\n stabilizeSnapshot(runtime.peekSnapshot()),\n transitionEvent,\n signal,\n handlers,\n {\n onAsyncGuardStart: (currentTransition) => {\n asyncState.setStepLoading(\n fromStep,\n \"evaluating-when\",\n transitionEvent.type,\n currentTransition.id,\n runVersion\n );\n },\n onAsyncGuardSuccess: () => {\n asyncState.setStepIdle(fromStep, runVersion);\n },\n onAsyncGuardError: (currentTransition, error) => {\n asyncGuardErrorTransitionId = currentTransition.id ?? null;\n asyncGuardErrorLabel = currentTransition.label;\n asyncGuardErrorHandled = true;\n asyncState.setStepError(\n fromStep,\n transitionEvent.type,\n error,\n currentTransition.id,\n runVersion\n );\n }\n },\n defaultTimeoutMs\n )) as RuntimeTransition<TContext, TStepId, TEventMap, THandlers> | null;\n } catch (error) {\n if (!runtime.isRunActive(runVersion)) {\n return { transition: null, earlyResult: buildCanceledSendResult(transitionEvent.type) };\n }\n\n return {\n transition: null,\n earlyResult: buildTransitionErrorResult(\n fromStep,\n transitionEvent.type,\n error,\n asyncGuardErrorTransitionId,\n asyncGuardErrorLabel,\n runVersion,\n asyncGuardErrorHandled\n )\n };\n }\n\n return { transition, earlyResult: null };\n };\n\n const handleNoTransitionMatch = (\n event: RuntimeSendEvent<TStepId, TEventMap>,\n fromStep: TStepId,\n runVersion: number\n ): JourneySendResult<TContext, TStepId> => {\n if (isGoToStepByIdEvent(event)) {\n return buildCanceledSendResult(event.type);\n }\n\n if (event.type === \"goToPreviousStep\") {\n const fallbackResult = navigation.applyPreviousNavigation(1, event.type, runVersion);\n if (fallbackResult.transitioned) {\n runtime.emit({\n type: \"transition.success\",\n from: fromStep,\n to: fallbackResult.snapshot.currentStepId,\n eventType: event.type,\n transitionId: null,\n timestamp: now()\n });\n }\n return fallbackResult;\n }\n\n if (\n event.type === \"goToNextStep\" &&\n !requireExplicitCompletion &&\n !navigation.hasDeclaredTransitionForEvent(fromStep, \"goToNextStep\")\n ) {\n return navigation.commitTerminalTransition(\n fromStep,\n \"COMPLETE\",\n event,\n null,\n undefined,\n runtime.peekSnapshot().context,\n runVersion\n );\n }\n\n if (\n event.type === \"completeJourney\" &&\n !navigation.hasDeclaredTransitionForEvent(fromStep, \"completeJourney\")\n ) {\n return navigation.commitTerminalTransition(\n fromStep,\n \"COMPLETE\",\n event,\n null,\n undefined,\n runtime.peekSnapshot().context,\n runVersion\n );\n }\n\n if (\n event.type === \"terminateJourney\" &&\n !navigation.hasDeclaredTransitionForEvent(fromStep, \"terminateJourney\")\n ) {\n return navigation.commitTerminalTransition(\n fromStep,\n \"TERMINATED\",\n event,\n null,\n undefined,\n runtime.peekSnapshot().context,\n runVersion\n );\n }\n\n return buildCanceledSendResult(event.type);\n };\n\n const resolveNextContext = (\n transition: RuntimeTransition<TContext, TStepId, TEventMap, THandlers>,\n transitionEvent: RuntimeTransitionEvent<TStepId, TEventMap>,\n fromStep: TStepId,\n runVersion: number\n ):\n | { nextContext: TContext; earlyResult: null }\n | { nextContext: null; earlyResult: JourneySendResult<TContext, TStepId> } => {\n const snapshot = runtime.peekSnapshot();\n if (!transition.updateContext) {\n return { nextContext: snapshot.context, earlyResult: null };\n }\n\n try {\n const nextContext = (\n transition.updateContext as (\n args: JourneyTransitionUpdateContextArgsForEvent<\n TContext,\n TStepId,\n TEventMap,\n typeof transitionEvent.type\n >\n ) => TContext\n )({\n snapshot: stabilizeSnapshot(snapshot),\n context: snapshot.context,\n from: snapshot.currentStepId,\n timeline: snapshot.history.timeline,\n index: snapshot.history.index,\n event: transitionEvent as JourneyTransitionArgsForEvent<\n TContext,\n TStepId,\n TEventMap,\n THandlers,\n typeof transitionEvent.type\n >[\"event\"]\n });\n\n return {\n nextContext: assertSerializableContext(nextContext),\n earlyResult: null\n };\n } catch (error) {\n if (!runtime.isRunActive(runVersion)) {\n return { nextContext: null, earlyResult: buildCanceledSendResult(transitionEvent.type) };\n }\n\n return {\n nextContext: null,\n earlyResult: buildTransitionErrorResult(\n fromStep,\n transitionEvent.type,\n error,\n transition.id,\n transition.label,\n runVersion\n )\n };\n }\n };\n\n return {\n buildCanceledSendResult,\n executeSend: async (\n event: RuntimeSendEvent<TStepId, TEventMap>,\n runVersion: number,\n signal: AbortSignal\n ): Promise<JourneySendResult<TContext, TStepId>> => {\n if (runtime.peekSnapshot().status !== \"running\") {\n return buildCanceledSendResult(event.type);\n }\n\n const fromStep = runtime.peekSnapshot().currentStepId;\n const transitionEvent = event as RuntimeTransitionEvent<TStepId, TEventMap>;\n runtime.emit({ type: \"transition.start\", from: fromStep, event, timestamp: now() });\n\n if (headless) {\n if (isGoToStepByIdEvent(event)) {\n return navigation.commitStepTransition(\n fromStep,\n event.stepId,\n transitionEvent,\n {\n from: fromStep,\n event: \"goToStepById\",\n to: event.stepId\n } as RuntimeTransition<TContext, TStepId, TEventMap, THandlers>,\n runtime.peekSnapshot().context,\n runVersion\n );\n }\n\n if (\n event.type !== \"completeJourney\" &&\n event.type !== \"terminateJourney\" &&\n event.type !== \"goToPreviousStep\"\n ) {\n return buildCanceledSendResult(event.type);\n }\n }\n\n const transitionResolution = resolveTransitionsForSend(event, fromStep);\n if (transitionResolution.earlyResult) {\n return transitionResolution.earlyResult;\n }\n\n const selectionResolution = await selectTransitionForSend(\n transitionResolution.transitionsToEvaluate,\n transitionEvent,\n fromStep,\n runVersion,\n signal\n );\n if (selectionResolution.earlyResult) {\n return selectionResolution.earlyResult;\n }\n\n if (!runtime.isRunActive(runVersion)) {\n return buildCanceledSendResult(event.type);\n }\n\n const { transition } = selectionResolution;\n if (!transition) {\n return handleNoTransitionMatch(event, fromStep, runVersion);\n }\n\n asyncState.setStepIdle(fromStep, runVersion);\n\n const contextResolution = resolveNextContext(\n transition,\n transitionEvent,\n fromStep,\n runVersion\n );\n if (contextResolution.earlyResult) {\n return contextResolution.earlyResult;\n }\n\n const target = resolveTransitionTarget(transition);\n if (isTerminalTarget(target)) {\n return navigation.commitTerminalTransition(\n fromStep,\n target,\n transitionEvent,\n transition.id ?? null,\n transition,\n contextResolution.nextContext,\n runVersion\n );\n }\n\n return navigation.commitStepTransition(\n fromStep,\n target,\n transitionEvent,\n transition,\n contextResolution.nextContext,\n runVersion\n );\n }\n };\n};\n", "import { validateFiniteTimeout } from \"./helpers\";\n\nimport type {\n JourneyDefinition,\n JourneyJsonObject,\n JourneyResolvedDefinition,\n JourneyResolvedTransition,\n JourneyTransition,\n JourneyTransitionGraph\n} from \"../types\";\n\nconst hashTransitionDescriptor = (value: string) => {\n let hash = 2166136261;\n for (let index = 0; index < value.length; index += 1) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 16777619);\n }\n return (hash >>> 0).toString(16).padStart(8, \"0\");\n};\n\nconst buildResolvedTransitions = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>\n>(\n transitions: readonly JourneyTransition<TContext, TStepId, TEventMap, THandlers>[]\n): JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers>[] => {\n const transitionRouteCounts = new Map<string, number>();\n const usedIds = new Set<string>();\n\n return transitions.map((transition) => {\n const target =\n transition.event === \"completeJourney\"\n ? \"COMPLETE\"\n : transition.event === \"terminateJourney\"\n ? \"TERMINATED\"\n : String(transition.to);\n const routeKey = JSON.stringify({\n from: transition.from,\n event: transition.event,\n target\n });\n const ordinal = (transitionRouteCounts.get(routeKey) ?? 0) + 1;\n transitionRouteCounts.set(routeKey, ordinal);\n\n const descriptor = JSON.stringify({\n from: transition.from,\n event: transition.event,\n target,\n ordinal\n });\n\n let suffix = 0;\n const id = (() => {\n let candidate = hashTransitionDescriptor(descriptor);\n while (usedIds.has(candidate)) {\n suffix += 1;\n candidate = hashTransitionDescriptor(`${descriptor}:${suffix}`);\n }\n return candidate;\n })();\n usedIds.add(id);\n\n return {\n ...transition,\n id,\n ...(transition.label !== undefined ? { label: transition.label } : {})\n } as JourneyResolvedTransition<TContext, TStepId, TEventMap, THandlers>;\n });\n};\n\nexport const resolveJourneyDefinition = <\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n TStepMeta = unknown,\n THandlers extends Record<string, unknown> = Record<never, never>\n>(\n journey: JourneyDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>\n): JourneyResolvedDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers> => {\n type TEventType = string;\n const resolvedTransitions: JourneyTransition<TContext, TStepId, TEventMap, THandlers>[] = [];\n const { transitions } = journey;\n\n if (transitions === undefined) {\n return {\n ...journey,\n transitions: buildResolvedTransitions(resolvedTransitions)\n } as JourneyResolvedDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>;\n }\n\n if (Array.isArray(transitions)) {\n if (transitions.length === 0) {\n throw new Error(\n \"Journey linear transitions must include the initial step as the first item.\"\n );\n }\n\n const [initialStep, ...linearEntries] = transitions;\n if (typeof initialStep !== \"string\") {\n throw new Error(\"Journey linear transitions at index 0 must be a step id string.\");\n }\n\n if (!(initialStep in journey.steps)) {\n throw new Error(`Journey linear transitions reference unknown step \"${initialStep}\".`);\n }\n\n // Resolve initial: use journey.initial if provided (start from middle), otherwise array[0]\n const resolvedInitial = (journey.initial ?? initialStep) as TStepId;\n\n if (journey.initial !== undefined) {\n const allStepIds = transitions.map((entry) =>\n typeof entry === \"string\" ? entry : entry.step\n );\n if (!allStepIds.includes(journey.initial)) {\n throw new Error(\n `Journey initial step \"${journey.initial}\" does not exist in linear transitions.`\n );\n }\n }\n\n let previousStep = initialStep as TStepId;\n const seenSteps = new Set<string>([initialStep]);\n for (const [offset, entry] of linearEntries.entries()) {\n const index = offset + 1;\n if (typeof entry === \"string\") {\n if (!(entry in journey.steps)) {\n throw new Error(`Journey linear transitions reference unknown step \"${entry}\".`);\n }\n\n if (seenSteps.has(entry)) {\n throw new Error(\n `Journey linear transitions contain duplicate step \"${entry}\" at index ${index}.`\n );\n }\n seenSteps.add(entry);\n\n resolvedTransitions.push({\n from: previousStep,\n event: \"goToNextStep\" as TEventType,\n to: entry as TStepId\n } as JourneyTransition<TContext, TStepId, TEventMap, THandlers>);\n previousStep = entry as TStepId;\n continue;\n }\n\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) {\n throw new Error(\n `Journey linear transitions at index ${index} must be a step id string or step config object.`\n );\n }\n\n const allowedKeys = new Set([\n \"step\",\n \"label\",\n \"updateContext\",\n \"onEnter\",\n \"onLeave\",\n \"timeoutMs\"\n ]);\n for (const key of Object.keys(entry)) {\n if (!allowedKeys.has(key)) {\n throw new Error(\n `Journey linear transition object at index ${index} contains unsupported field \"${key}\". Allowed fields are \"step\", \"label\", \"updateContext\", \"onEnter\", \"onLeave\", and \"timeoutMs\".`\n );\n }\n }\n\n if (typeof entry.step !== \"string\") {\n throw new Error(\n `Journey linear transition object at index ${index} must define string \"step\".`\n );\n }\n\n if (!(entry.step in journey.steps)) {\n throw new Error(`Journey linear transitions reference unknown step \"${entry.step}\".`);\n }\n\n if (seenSteps.has(entry.step)) {\n throw new Error(\n `Journey linear transitions contain duplicate step \"${entry.step}\" at index ${index}.`\n );\n }\n seenSteps.add(entry.step);\n\n if (entry.updateContext !== undefined && typeof entry.updateContext !== \"function\") {\n throw new Error(\n `Journey linear transition object at index ${index} must define \"updateContext\" as a function when provided.`\n );\n }\n\n if (entry.onEnter !== undefined && typeof entry.onEnter !== \"function\") {\n throw new Error(\n `Journey linear transition object at index ${index} must define \"onEnter\" as a function when provided.`\n );\n }\n\n if (entry.onLeave !== undefined && typeof entry.onLeave !== \"function\") {\n throw new Error(\n `Journey linear transition object at index ${index} must define \"onLeave\" as a function when provided.`\n );\n }\n\n validateFiniteTimeout(entry.timeoutMs, `Journey linear transition object at index ${index}`);\n\n resolvedTransitions.push({\n ...(entry.label !== undefined ? { label: entry.label } : {}),\n ...(entry.timeoutMs !== undefined ? { timeoutMs: entry.timeoutMs } : {}),\n ...(entry.updateContext !== undefined ? { updateContext: entry.updateContext } : {}),\n ...(entry.onEnter !== undefined ? { onEnter: entry.onEnter } : {}),\n ...(entry.onLeave !== undefined ? { onLeave: entry.onLeave } : {}),\n from: previousStep,\n event: \"goToNextStep\" as TEventType,\n to: entry.step as TStepId\n } as JourneyTransition<TContext, TStepId, TEventMap, THandlers>);\n previousStep = entry.step as TStepId;\n }\n\n return {\n ...journey,\n initial: resolvedInitial,\n transitions: buildResolvedTransitions(resolvedTransitions)\n };\n }\n\n if (!transitions || typeof transitions !== \"object\") {\n throw new Error(\"Journey transitions must be an array or an object map when provided.\");\n }\n\n const transitionGraph = transitions as JourneyTransitionGraph<\n TContext,\n TStepId,\n TEventMap,\n THandlers\n >;\n\n const orderedGraphEntries = [\n ...Object.entries(transitionGraph).filter(([fromKey]) => fromKey !== \"global\"),\n ...(transitionGraph.global ? ([[\"global\", transitionGraph.global]] as const) : [])\n ];\n\n for (const [fromKey, eventMap] of orderedGraphEntries) {\n if (fromKey !== \"global\" && !(fromKey in journey.steps)) {\n throw new Error(`Journey transitions reference unknown step \"${fromKey}\".`);\n }\n\n if (!eventMap || typeof eventMap !== \"object\" || Array.isArray(eventMap)) {\n throw new Error(`Journey transitions for \"${fromKey}\" must be an event map object.`);\n }\n\n for (const [event, rawEdges] of Object.entries(eventMap) as Array<\n [TEventType, (typeof eventMap)[TEventType] | true]\n >) {\n const isTerminal = event === \"completeJourney\" || event === \"terminateJourney\";\n const edges =\n isTerminal && (rawEdges === true || (Array.isArray(rawEdges) && rawEdges.length === 0))\n ? [{}]\n : rawEdges;\n\n if (!Array.isArray(edges)) {\n throw new Error(`Journey transitions for \"${fromKey}.${event}\" must be an array.`);\n }\n\n for (const [index, edge] of edges.entries()) {\n if (!edge || typeof edge !== \"object\") {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must be an object.`\n );\n }\n\n const allowedKeys = new Set(\n isTerminal\n ? [\"when\", \"updateContext\", \"onEnter\", \"onLeave\", \"label\", \"timeoutMs\"]\n : [\"to\", \"when\", \"updateContext\", \"onEnter\", \"onLeave\", \"label\", \"timeoutMs\"]\n );\n for (const key of Object.keys(edge)) {\n if (!allowedKeys.has(key)) {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" contains unsupported field \"${key}\".`\n );\n }\n }\n\n if (!isTerminal && typeof (edge as { to?: unknown }).to !== \"string\") {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must define string \"to\".`\n );\n }\n\n if ((edge as { when?: unknown }).when !== undefined && typeof edge.when !== \"function\") {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must define \"when\" as a function when provided.`\n );\n }\n\n if (\n (edge as { updateContext?: unknown }).updateContext !== undefined &&\n typeof edge.updateContext !== \"function\"\n ) {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must define \"updateContext\" as a function when provided.`\n );\n }\n\n if (\n (edge as { onEnter?: unknown }).onEnter !== undefined &&\n typeof edge.onEnter !== \"function\"\n ) {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must define \"onEnter\" as a function when provided.`\n );\n }\n\n if (\n (edge as { onLeave?: unknown }).onLeave !== undefined &&\n typeof edge.onLeave !== \"function\"\n ) {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must define \"onLeave\" as a function when provided.`\n );\n }\n\n if ((edge as { label?: unknown }).label !== undefined && typeof edge.label !== \"string\") {\n throw new Error(\n `Journey transition at \"${fromKey}.${event}[${index}]\" must define \"label\" as a string when provided.`\n );\n }\n\n validateFiniteTimeout(\n (edge as { timeoutMs?: unknown }).timeoutMs,\n `Journey transition at \"${fromKey}.${event}[${index}]\"`\n );\n\n resolvedTransitions.push({\n ...edge,\n from: (fromKey === \"global\" ? \"*\" : fromKey) as TStepId | \"*\",\n event\n } as JourneyTransition<TContext, TStepId, TEventMap, THandlers>);\n }\n }\n }\n\n return {\n ...journey,\n transitions: buildResolvedTransitions(resolvedTransitions)\n } as JourneyResolvedDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>;\n};\n", "import { createJourneyMachineAsyncStateController } from \"./async-state\";\nimport { createJourneyMachineComputedGetter } from \"./computed\";\nimport { createJourneyMachineControls } from \"./controls\";\nimport {\n createJourneyMachineNavigationController,\n type JourneyLifecycleScheduler\n} from \"./navigation\";\nimport { createJourneyMachinePluginController } from \"./plugin-controller\";\nimport { createJourneyMachineRuntime } from \"./runtime\";\nimport { createJourneyMachineSendController } from \"./send\";\nimport {\n assertSerializableContext,\n assertStepExists,\n buildInitialAsyncState,\n buildSendResult,\n buildSnapshot,\n cloneContext,\n cloneMetaValue,\n isTerminalTarget,\n now,\n validateFiniteTimeout,\n validateJourneyTransitions\n} from \"./helpers\";\nimport { resolveJourneyDefinition } from \"./resolve-journey-definition\";\n\nimport type {\n JourneyDefinition,\n JourneyJsonObject,\n JourneyMachine,\n JourneyMachinePlugin,\n JourneyMachineOptions,\n JourneyMachineWithPlugins,\n JourneySendEvent,\n JourneySendResult\n} from \"../types\";\n\n/** Creates a journey machine from a definition and optional runtime/plugin options. */\nexport function createJourneyMachine<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown> = Record<never, never>,\n TStepMeta = unknown,\n THandlers extends Record<string, unknown> = Record<never, never>,\n TPlugins extends readonly JourneyMachinePlugin[] = []\n>(\n journey: JourneyDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>,\n options?: JourneyMachineOptions<TPlugins>\n): JourneyMachineWithPlugins<TContext, TStepId, TEventMap, TStepMeta, THandlers, TPlugins> {\n if (!journey.steps || typeof journey.steps !== \"object\") {\n throw new Error(\"Journey steps must be a record object.\");\n }\n\n if (\n journey.transitions !== undefined &&\n (journey.transitions === null ||\n (typeof journey.transitions !== \"object\" && !Array.isArray(journey.transitions)))\n ) {\n throw new Error(\"Journey transitions must be an array or an object map when provided.\");\n }\n\n for (const stepId of Object.keys(journey.steps)) {\n if (stepId === \"*\" || stepId === \"global\" || stepId === \"COMPLETE\" || stepId === \"TERMINATED\") {\n throw new Error(`Step id \"${stepId}\" is reserved and cannot be used as a step name.`);\n }\n }\n\n if (journey.initial === undefined && !Array.isArray(journey.transitions)) {\n throw new Error(\n 'Journey \"initial\" is required for graph and headless definitions. ' +\n \"For linear transitions, initial defaults to the first array element.\"\n );\n }\n\n assertSerializableContext(journey.context);\n const resolvedJourney = resolveJourneyDefinition(journey);\n\n assertStepExists(\n resolvedJourney.steps,\n resolvedJourney.initial,\n `Journey initial step \"${resolvedJourney.initial}\" does not exist in steps registry.`\n );\n validateJourneyTransitions(resolvedJourney.transitions, resolvedJourney.steps);\n\n const requireExplicitCompletion = options?.requireExplicitCompletion ?? false;\n validateFiniteTimeout(options?.defaultTimeoutMs, \"Journey machine options\");\n const defaultTimeoutMs = options?.defaultTimeoutMs;\n const initialContextTemplate = cloneContext(resolvedJourney.context);\n const stepMeta = Object.fromEntries(\n (Object.keys(resolvedJourney.steps) as TStepId[]).map((stepId) => [\n stepId,\n cloneMetaValue(resolvedJourney.steps[stepId].meta)\n ])\n ) as Record<TStepId, TStepMeta>;\n\n const buildInitialSnapshot = () =>\n buildSnapshot(\n [resolvedJourney.initial],\n 0,\n cloneContext(initialContextTemplate),\n \"idled\",\n buildInitialAsyncState(resolvedJourney.steps)\n );\n\n const pluginController = createJourneyMachinePluginController<\n TContext,\n TStepId,\n TEventMap,\n TStepMeta,\n THandlers\n >({\n plugins: options?.plugins ?? [],\n setupContext: {\n journey,\n resolvedJourney,\n options: {\n requireExplicitCompletion,\n defaultTimeoutMs\n },\n buildInitialSnapshot\n }\n });\n\n const initialSnapshot = pluginController.hydrateSnapshot(buildInitialSnapshot());\n assertSerializableContext(initialSnapshot.context, \"Journey hydrated context\");\n\n const onListenerError = options?.onListenerError;\n const onLifecycleError = options?.onLifecycleError;\n const runtime = createJourneyMachineRuntime<TContext, TStepId, TEventMap>({\n snapshot: initialSnapshot,\n onSnapshotChange: pluginController.onSnapshotChange,\n onDispose: pluginController.dispose,\n ...(onListenerError !== undefined ? { onListenerError } : {})\n });\n const asyncState = createJourneyMachineAsyncStateController<TContext, TStepId, TEventMap>({\n runtime\n });\n\n let dispatchSend: (\n event: JourneySendEvent<TStepId, TEventMap>\n ) => Promise<JourneySendResult<TContext, TStepId>> = () =>\n Promise.resolve(buildSendResult(runtime.getSnapshot(), false));\n\n const scheduleLifecycle: JourneyLifecycleScheduler<TContext, TStepId, TEventMap, THandlers> = ({\n previousSnapshot,\n snapshot,\n from,\n to,\n event,\n transitionId,\n label,\n runVersion,\n transition\n }) => {\n const sourceStep = resolvedJourney.steps[from];\n const targetStep = isTerminalTarget(to) ? null : resolvedJourney.steps[to];\n const handlers = (resolvedJourney.handlers ?? {}) as THandlers;\n const dispatch = (nextEvent: JourneySendEvent<TStepId, TEventMap>) => {\n if (!runtime.isRunActive(runVersion) || runtime.isDisposed()) {\n return Promise.resolve(buildSendResult(runtime.getSnapshot(), false));\n }\n return dispatchSend(nextEvent);\n };\n const lifecycleAbortController = runtime.openLifecycle(runVersion);\n if (!lifecycleAbortController) {\n return;\n }\n const { signal } = lifecycleAbortController;\n const reportLifecycleError = (\n error: unknown,\n phase: \"step.onLeave\" | \"transition.onLeave\" | \"step.onEnter\" | \"transition.onEnter\"\n ) => {\n const context = {\n phase,\n from,\n to,\n eventType: event.type,\n transitionId,\n ...(label !== undefined ? { label } : {})\n } as const;\n runtime.emit({\n type: \"lifecycle.error\",\n ...context,\n error,\n timestamp: now()\n });\n onLifecycleError?.(error, context);\n };\n\n void (async () => {\n try {\n if (sourceStep?.onLeave) {\n try {\n await sourceStep.onLeave({\n snapshot: previousSnapshot,\n context: previousSnapshot.context,\n from,\n to,\n event,\n transitionId,\n ...(label !== undefined ? { label } : {}),\n handlers,\n signal,\n dispatch\n });\n } catch (error) {\n if (signal.aborted || !runtime.isRunActive(runVersion)) {\n return;\n }\n reportLifecycleError(error, \"step.onLeave\");\n return;\n }\n }\n\n if (!runtime.isRunActive(runVersion)) {\n return;\n }\n\n if (transition?.onLeave) {\n try {\n await transition.onLeave({\n snapshot: previousSnapshot,\n context: previousSnapshot.context,\n from,\n to,\n event,\n transitionId,\n ...(transition.label !== undefined ? { label: transition.label } : {}),\n handlers,\n signal,\n dispatch\n });\n } catch (error) {\n if (signal.aborted || !runtime.isRunActive(runVersion)) {\n return;\n }\n reportLifecycleError(error, \"transition.onLeave\");\n return;\n }\n }\n\n if (!runtime.isRunActive(runVersion)) {\n return;\n }\n\n if (targetStep?.onEnter) {\n try {\n await targetStep.onEnter({\n snapshot,\n context: snapshot.context,\n from,\n to,\n event,\n transitionId,\n ...(label !== undefined ? { label } : {}),\n handlers,\n signal,\n dispatch\n });\n } catch (error) {\n if (signal.aborted || !runtime.isRunActive(runVersion)) {\n return;\n }\n reportLifecycleError(error, \"step.onEnter\");\n return;\n }\n }\n\n if (!runtime.isRunActive(runVersion)) {\n return;\n }\n\n if (transition?.onEnter) {\n try {\n await transition.onEnter({\n snapshot,\n context: snapshot.context,\n from,\n to,\n event,\n transitionId,\n ...(transition.label !== undefined ? { label: transition.label } : {}),\n handlers,\n signal,\n dispatch\n });\n } catch (error) {\n if (signal.aborted || !runtime.isRunActive(runVersion)) {\n return;\n }\n reportLifecycleError(error, \"transition.onEnter\");\n return;\n }\n }\n } finally {\n runtime.closeLifecycle(lifecycleAbortController);\n }\n })();\n };\n\n const navigation = createJourneyMachineNavigationController<\n TContext,\n TStepId,\n TEventMap,\n THandlers\n >({\n runtime,\n steps: resolvedJourney.steps,\n transitions: resolvedJourney.transitions,\n scheduleLifecycle\n });\n\n const sendController = createJourneyMachineSendController<\n TContext,\n TStepId,\n TEventMap,\n THandlers\n >(\n runtime,\n asyncState,\n navigation,\n journey.transitions === undefined,\n resolvedJourney.steps,\n resolvedJourney.transitions,\n (resolvedJourney.handlers ?? {}) as THandlers,\n requireExplicitCompletion,\n defaultTimeoutMs\n );\n\n const controls = createJourneyMachineControls<TContext, TStepId, TEventMap>({\n runtime,\n asyncState,\n initial: resolvedJourney.initial,\n initialContext: initialContextTemplate,\n steps: resolvedJourney.steps\n });\n\n const getComputed = createJourneyMachineComputedGetter(\n journey,\n resolvedJourney,\n runtime.getSnapshot\n );\n\n const machine: JourneyMachine<TContext, TStepId, TEventMap, TStepMeta, THandlers> = {\n getSnapshot: runtime.getSnapshot,\n getStepMeta: (stepId) => cloneMetaValue(stepMeta[stepId]),\n getComputed,\n startJourney: controls.startJourney,\n subscribe: runtime.subscribe,\n subscribeSelector: runtime.subscribeSelector,\n subscribeEvent: runtime.subscribeEvent,\n subscribeStart: (listener) =>\n runtime.subscribeEvent((event) => {\n if (event.type === \"journey.start\") {\n listener(event);\n }\n }),\n subscribeReset: (listener) =>\n runtime.subscribeEvent((event) => {\n if (event.type === \"journey.reset\") {\n listener(event);\n }\n }),\n subscribeComplete: (listener) =>\n runtime.subscribeEvent((event) => {\n if (event.type === \"journey.completed\") {\n listener(event);\n }\n }),\n subscribeTerminate: (listener) =>\n runtime.subscribeEvent((event) => {\n if (event.type === \"journey.terminated\") {\n listener(event);\n }\n }),\n resetJourney: controls.resetJourney,\n updateContext: controls.updateContext,\n clearStepError: controls.clearStepError,\n dispose: controls.dispose,\n goToPreviousStep: (steps) =>\n runtime.queue(\n async (runVersion) =>\n navigation.applyPreviousNavigation(steps, \"goToPreviousStep\", runVersion),\n () => sendController.buildCanceledSendResult(\"goToPreviousStep\")\n ),\n goToLastVisitedStep: () =>\n runtime.queue(\n async (runVersion) =>\n navigation.applyLastVisitedNavigation(\"goToLastVisitedStep\", runVersion),\n () => sendController.buildCanceledSendResult(\"goToLastVisitedStep\")\n ),\n goToNextStep: () =>\n machine.send({ type: \"goToNextStep\" } as JourneySendEvent<TStepId, TEventMap>),\n goToStepById: (stepId: TStepId) =>\n machine.send({ type: \"goToStepById\", stepId } as JourneySendEvent<TStepId, TEventMap>),\n terminateJourney: (payload) =>\n payload === undefined\n ? machine.send({ type: \"terminateJourney\" } as JourneySendEvent<TStepId, TEventMap>)\n : machine.send({\n type: \"terminateJourney\",\n payload\n } as JourneySendEvent<TStepId, TEventMap>),\n completeJourney: (payload) =>\n payload === undefined\n ? machine.send({ type: \"completeJourney\" } as JourneySendEvent<TStepId, TEventMap>)\n : machine.send({\n type: \"completeJourney\",\n payload\n } as JourneySendEvent<TStepId, TEventMap>),\n send: (event) =>\n runtime.queue(\n (runVersion, signal) => sendController.executeSend(event, runVersion, signal),\n () => sendController.buildCanceledSendResult(event.type)\n )\n };\n\n dispatchSend = machine.send;\n\n return pluginController.extendMachine(machine) as JourneyMachineWithPlugins<\n TContext,\n TStepId,\n TEventMap,\n TStepMeta,\n THandlers,\n TPlugins\n >;\n}\n", "import type {\n JourneyFullEventType,\n JourneyJsonObject,\n JourneyStepDefinition,\n JourneyTransitionGraph\n} from \"../types\";\nimport type {\n JourneyBuilder,\n JourneyBuilderCustomEventKey,\n JourneyBuilderDefinition,\n JourneyBuilderCandidate,\n JourneyBuilderGuard,\n JourneyBuilderLifecycle,\n JourneyBuilderOnEntry,\n JourneyBuilderTerminalCandidate,\n JourneyBuilderTerminalEntry,\n JourneyBuilderTerminalEventKey,\n JourneyBuilderUpdateContext,\n JourneyBuilderStepEventKey,\n JourneyStepBuilder,\n JourneyToBuilder,\n JourneyToBuilderUnused,\n JourneyToBuilderUsage\n} from \"./types\";\n\nexport type {\n JourneyBuilder,\n JourneyBuilderCustomEventKey,\n JourneyBuilderDefinition,\n JourneyBuilderDefinitionMetadata,\n JourneyBuilderGuard,\n JourneyBuilderLifecycle,\n JourneyBuilderOnEntry,\n JourneyBuilderTerminalCandidate,\n JourneyBuilderTerminalEntry,\n JourneyBuilderUpdateContext,\n JourneyStepBuilder,\n JourneyToBuilder\n} from \"./types\";\n\ntype RawCandidate = {\n readonly _to: string;\n readonly _when?: unknown;\n readonly _updateContext?: unknown;\n readonly _onEnter?: unknown;\n readonly _onLeave?: unknown;\n readonly _label?: string | undefined;\n readonly _timeoutMs?: number | undefined;\n};\n\ntype RawTerminalCandidate = {\n readonly when?: unknown;\n readonly updateContext?: unknown;\n readonly onEnter?: unknown;\n readonly onLeave?: unknown;\n readonly label?: string | undefined;\n readonly timeoutMs?: number | undefined;\n};\n\nfunction makeToBuilder<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown>,\n THandlers extends Record<string, unknown>,\n TEventType extends JourneyFullEventType<TEventMap>,\n TUsed extends JourneyToBuilderUsage = JourneyToBuilderUnused\n>(\n candidate: JourneyBuilderCandidate<TContext, TStepId, TEventMap, THandlers, TEventType>\n): JourneyToBuilder<TContext, TStepId, TEventMap, THandlers, TEventType, TUsed> {\n return {\n _candidate: candidate,\n when(guard: JourneyBuilderGuard<TContext, TStepId, TEventMap, THandlers, TEventType>) {\n return makeToBuilder<\n TContext,\n TStepId,\n TEventMap,\n THandlers,\n TEventType,\n Omit<TUsed, \"when\"> & { readonly when: true }\n >({ ...candidate, _when: guard });\n },\n updateContext(fn: JourneyBuilderUpdateContext<TContext, TStepId, TEventMap, TEventType>) {\n return makeToBuilder<\n TContext,\n TStepId,\n TEventMap,\n THandlers,\n TEventType,\n Omit<TUsed, \"updateContext\"> & { readonly updateContext: true }\n >({ ...candidate, _updateContext: fn });\n },\n onEnter(fn: JourneyBuilderLifecycle<TContext, TStepId, TEventMap, THandlers>) {\n return makeToBuilder<\n TContext,\n TStepId,\n TEventMap,\n THandlers,\n TEventType,\n Omit<TUsed, \"onEnter\"> & { readonly onEnter: true }\n >({ ...candidate, _onEnter: fn });\n },\n onLeave(fn: JourneyBuilderLifecycle<TContext, TStepId, TEventMap, THandlers>) {\n return makeToBuilder<\n TContext,\n TStepId,\n TEventMap,\n THandlers,\n TEventType,\n Omit<TUsed, \"onLeave\"> & { readonly onLeave: true }\n >({ ...candidate, _onLeave: fn });\n },\n label(label: string) {\n return makeToBuilder<\n TContext,\n TStepId,\n TEventMap,\n THandlers,\n TEventType,\n Omit<TUsed, \"label\"> & { readonly label: true }\n >({ ...candidate, _label: label });\n },\n timeoutMs(ms: number) {\n return makeToBuilder<\n TContext,\n TStepId,\n TEventMap,\n THandlers,\n TEventType,\n Omit<TUsed, \"timeoutMs\"> & { readonly timeoutMs: true }\n >({ ...candidate, _timeoutMs: ms });\n }\n } as JourneyToBuilder<TContext, TStepId, TEventMap, THandlers, TEventType, TUsed>;\n}\n\nfunction candidateToEdge(c: RawCandidate): Record<string, unknown> {\n const edge: Record<string, unknown> = { to: c._to };\n if (c._when !== undefined) edge.when = c._when;\n if (c._updateContext !== undefined) edge.updateContext = c._updateContext;\n if (c._onEnter !== undefined) edge.onEnter = c._onEnter;\n if (c._onLeave !== undefined) edge.onLeave = c._onLeave;\n if (c._label !== undefined) edge.label = c._label;\n if (c._timeoutMs !== undefined) edge.timeoutMs = c._timeoutMs;\n return edge;\n}\n\nfunction terminalCandidateToEdge(c: RawTerminalCandidate): Record<string, unknown> {\n const edge: Record<string, unknown> = {};\n if (c.when !== undefined) edge.when = c.when;\n if (c.updateContext !== undefined) edge.updateContext = c.updateContext;\n if (c.onEnter !== undefined) edge.onEnter = c.onEnter;\n if (c.onLeave !== undefined) edge.onLeave = c.onLeave;\n if (c.label !== undefined) edge.label = c.label;\n if (c.timeoutMs !== undefined) edge.timeoutMs = c.timeoutMs;\n return edge;\n}\n\n/** Creates a typed builder for authoring journey definitions with `createStep`, `to`, and `build` helpers. */\nexport function createJourneyBuilder<\n TContext extends JourneyJsonObject,\n TStepId extends string,\n TEventMap extends Record<string, unknown> = Record<never, never>,\n TStepMeta = unknown,\n THandlers extends Record<string, unknown> = Record<never, never>\n>(): JourneyBuilder<TContext, TStepId, TEventMap, TStepMeta, THandlers> {\n type WideNonTerminalEntry = JourneyBuilderOnEntry<\n TContext,\n TStepId,\n TEventMap,\n THandlers,\n JourneyBuilderStepEventKey<TEventMap>\n >;\n type WideTerminalEntry = JourneyBuilderTerminalEntry<\n TContext,\n TStepId,\n TEventMap,\n THandlers,\n JourneyBuilderTerminalEventKey<TEventMap>\n >;\n type BuilderWithCandidate = { readonly _candidate: RawCandidate };\n\n function to(stepId: TStepId): JourneyToBuilder<TContext, TStepId, TEventMap, THandlers> {\n return makeToBuilder({\n _to: stepId,\n _when: undefined,\n _updateContext: undefined,\n _onEnter: undefined,\n _onLeave: undefined,\n _label: undefined,\n _timeoutMs: undefined\n });\n }\n\n function resolveEntry(entry: WideNonTerminalEntry): readonly BuilderWithCandidate[] {\n if (typeof entry === \"function\") {\n const scopedTo = to as (\n stepId: TStepId\n ) => JourneyToBuilder<\n TContext,\n TStepId,\n TEventMap,\n THandlers,\n JourneyBuilderStepEventKey<TEventMap>\n >;\n return entry({ to: scopedTo });\n }\n\n return entry as readonly BuilderWithCandidate[];\n }\n\n function resolveTerminalEntry(entry: WideTerminalEntry): true | readonly unknown[] {\n if (entry === true || entry.length === 0) {\n return entry;\n }\n\n return (\n entry as readonly JourneyBuilderTerminalCandidate<\n TContext,\n TStepId,\n TEventMap,\n THandlers,\n JourneyBuilderTerminalEventKey<TEventMap>\n >[]\n ).map((candidate) => terminalCandidateToEdge(candidate));\n }\n\n function createStep<TStepKey extends TStepId>(\n id: TStepKey,\n config?: {\n meta?: TStepMeta;\n onEnter?: unknown;\n onLeave?: unknown;\n on?: Record<string, unknown>;\n }\n ) {\n return {\n id,\n _meta: config?.meta,\n _onEnter: config?.onEnter,\n _onLeave: config?.onLeave,\n _on: config?.on\n } as JourneyStepBuilder<\n TContext,\n TStepId,\n TStepKey,\n TEventMap,\n TStepMeta,\n THandlers,\n JourneyBuilderCustomEventKey<TEventMap>\n >;\n }\n\n function build(input: {\n initial: TStepId;\n context: TContext;\n handlers?: THandlers;\n steps: readonly JourneyStepBuilder<\n TContext,\n TStepId,\n TStepId,\n TEventMap,\n TStepMeta,\n THandlers,\n JourneyBuilderCustomEventKey<TEventMap>\n >[];\n global?: {\n [key: string]: unknown;\n };\n }): JourneyBuilderDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers> {\n const stepsRecord = {} as Record<\n TStepId,\n JourneyStepDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>\n >;\n const transitionGraph = {} as Record<string, unknown>;\n\n for (const stepBuilder of input.steps) {\n stepsRecord[stepBuilder.id] = {\n ...(stepBuilder._meta !== undefined ? { meta: stepBuilder._meta } : {}),\n ...(stepBuilder._onEnter !== undefined ? { onEnter: stepBuilder._onEnter } : {}),\n ...(stepBuilder._onLeave !== undefined ? { onLeave: stepBuilder._onLeave } : {})\n };\n\n if (stepBuilder._on) {\n const stepTransitions: Record<string, unknown> = {};\n\n for (const [eventType, entry] of Object.entries(stepBuilder._on)) {\n if (!entry) continue;\n\n if (eventType === \"completeJourney\" || eventType === \"terminateJourney\") {\n stepTransitions[eventType] = resolveTerminalEntry(entry as WideTerminalEntry);\n continue;\n }\n\n const builders = resolveEntry(entry as WideNonTerminalEntry);\n stepTransitions[eventType] = builders.map((builder) =>\n candidateToEdge(builder._candidate)\n );\n }\n\n transitionGraph[stepBuilder.id] = stepTransitions;\n }\n }\n\n if (input.global) {\n const globalTransitions: Record<string, unknown> = {};\n\n for (const [eventType, value] of Object.entries(input.global)) {\n if (value === undefined) continue;\n\n if (eventType === \"completeJourney\" || eventType === \"terminateJourney\") {\n globalTransitions[eventType] = resolveTerminalEntry(value as WideTerminalEntry);\n } else if (Array.isArray(value)) {\n globalTransitions[eventType] = (\n value as readonly JourneyToBuilder<TContext, TStepId, TEventMap, THandlers>[]\n ).map((builder) => candidateToEdge(builder._candidate));\n }\n }\n\n transitionGraph.global = globalTransitions;\n }\n\n return {\n initial: input.initial,\n context: input.context,\n ...(input.handlers !== undefined ? { handlers: input.handlers } : {}),\n steps: stepsRecord,\n transitions: transitionGraph as JourneyTransitionGraph<\n TContext,\n TStepId,\n TEventMap,\n THandlers\n >\n } as JourneyBuilderDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>;\n }\n\n return {\n createStep,\n to,\n build\n } as unknown as JourneyBuilder<TContext, TStepId, TEventMap, TStepMeta, THandlers>;\n}\n"],
5
- "mappings": "ubAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,0BAAAE,EAAA,yBAAAC,GAAA,yBAAAC,KAAA,eAAAC,GAAAL,ICkBO,IAAMM,EAAmB,CAC9BC,EACAC,EACAC,IACG,CACH,GAAI,EAAED,KAAUD,GACd,MAAM,IAAI,MAAME,CAAO,CAE3B,EAEaC,EAAiBC,GAC5B,OAAOA,GAAU,UACjBA,IAAU,MACV,CAAC,MAAM,QAAQA,CAAK,IACnB,OAAO,eAAeA,CAAK,IAAM,OAAO,WAAa,OAAO,eAAeA,CAAK,IAAM,MAEnFC,EAAsDD,GACtD,MAAM,QAAQA,CAAK,EACdA,EAAM,IAAKE,GAAUD,EAAuBC,CAAK,CAAC,EAGvDH,EAAcC,CAAK,EACd,OAAO,YACZ,OAAO,QAAQA,CAAK,EAAE,IAAI,CAAC,CAACG,EAAKC,CAAU,IAAM,CAC/CD,EACAF,EAAuBG,CAA8B,CACvD,CAAC,CACH,EAGKJ,EAOHK,GAAiBL,GAA2B,CAChD,GAAIA,IAAU,KACZ,MAAO,OAGT,GAAI,MAAM,QAAQA,CAAK,EACrB,MAAO,QAGT,GAAI,OAAOA,GAAU,SAAU,CAC7B,IAAMM,EAAmBN,EAA8C,aAAa,KACpF,OAAOM,GAAmBA,IAAoB,SAAWA,EAAkB,QAC7E,CAEA,OAAO,OAAON,CAChB,EAEA,SAASO,GACPP,EACAQ,EACAC,EACAC,EAA0B,CAAC,EACQ,CACnC,GACEV,IAAU,MACV,OAAOA,GAAU,UACjB,OAAOA,GAAU,UACjB,OAAOA,GAAU,UAEjB,OAGF,IAAMW,EAAYD,EAAK,SAAW,EAAIF,EAAQ,GAAGA,CAAK,IAAIE,EAAK,KAAK,GAAG,CAAC,GAExE,GAA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F,EAEIA,EAAY,IAAK,CACnB,IAAMC,EAA2C,CAAC,EAElD,OAAW,CAACC,EAAWX,CAAK,IAAK,OAAO,QAAQS,EAAY,GAAG,EAAG,CAChE,GAAI,CAACT,EAAO,SAEZ,GAAIW,IAAc,mBAAqBA,IAAc,mBAAoB,CACvED,EAAgBC,CAAS,EAAIV,EAAqBD,CAA0B,EAC5E,QACF,CAEA,IAAMY,EAAWb,EAAaC,CAA6B,EAC3DU,EAAgBC,CAAS,EAAIC,EAAS,IAAKC,GACzCrB,GAAgBqB,EAAQ,UAAU,CACpC,CACF,CAEAL,EAAgBC,EAAY,EAAE,EAAIC,CACpC,CAGF,GAAIJ,EAAM,OAAQ,CAChB,IAAMQ,EAA6C,CAAC,EAEpD,OAAW,CAACH,EAAWI,CAAK,IAAK,OAAO,QAAQT,EAAM,MAAM,EACtDS,IAAU,SAEVJ,IAAc,mBAAqBA,IAAc,mBACnDG,EAAkBH,CAAS,EAAIV,EAAqBc,CAA0B,EACrE,MAAM,QAAQA,CAAK,IAC5BD,EAAkBH,CAAS,EACzBI,EACA,IAAKF,GAAYrB,GAAgBqB,EAAQ,UAAU,CAAC,IAI1DL,EAAgB,OAASM,CAC3B,CAEA,MAAO,CACL,QAASR,EAAM,QACf,QAASA,EAAM,QACf,GAAIA,EAAM,WAAa,OAAY,CAAE,SAAUA,EAAM,QAAS,EAAI,CAAC,EACnE,MAAOC,EACP,YAAaC,CAMf,CACF,CAEA,MAAO,CACL,WAAAN,EACA,GAAAL,EACA,MAAAQ,CACF,CACF",
6
- "names": ["index_exports", "__export", "JourneyDisposedError", "createJourneyBuilder", "createJourneyMachine", "__toCommonJS", "assertStepExists", "steps", "stepId", "message", "isPlainObject", "value", "cloneSerializableValue", "entry", "key", "entryValue", "describeValue", "constructorName", "assertSerializableValue", "label", "state", "path", "pathLabel", "index", "assertSerializableContext", "context", "cloneContext", "cloneDefinitionValueFallback", "cloneMetaValue", "freezeSnapshotValue", "item", "normalizeStepCount", "now", "unique", "items", "normalizeVisited", "visited", "stepIds", "buildVisitedFromTimeline", "timeline", "resolvedStepIds", "appendVisited", "current", "isPromiseLike", "isFiniteNumber", "validateFiniteTimeout", "timeoutMs", "JourneyTimeoutError", "JourneyDisposedError", "operation", "isDevelopmentEnvironment", "diagnosticGlobal", "nodeEnv", "warnInDevelopment", "detail", "errorInDevelopment", "withTimeout", "promise", "buildError", "resolve", "reject", "timer", "error", "withAbortSignal", "signal", "onAbort", "buildIdleStepAsyncState", "buildInitialAsyncState", "isGoToStepByIdEvent", "event", "isTerminalTarget", "target", "resolveTransitionTarget", "transition", "validateJourneyTransitions", "transitions", "stepRegistry", "allowedKeys", "buildSendResult", "snapshot", "transitioned", "options", "buildSnapshot", "status", "asyncState", "safeIndex", "currentStepId", "stabilizeSnapshot", "stableSnapshot", "selectTransition", "handlers", "hooks", "defaultTimeoutMs", "fromMatches", "eventMatches", "guardResult", "asyncGuard", "asyncGuardPromise", "allowed", "transitionSnapshot", "nextCurrent", "nextContext", "baseTimeline", "nextTimeline", "nextIndex", "createJourneyMachineAsyncStateController", "runtime", "isAsyncLoadingPhase", "phase", "countLoadingSteps", "asyncState", "count", "state", "loadingCount", "syncState", "updateStepAsync", "stepId", "updater", "runVersion", "snapshot", "current", "buildIdleStepAsyncState", "next", "nextByStep", "wasLoading", "willBeLoading", "nextLoadingCount", "eventType", "transitionId", "error", "resolveLinearStepOrder", "transitions", "entry", "countVisitedSteps", "visited", "count", "stepId", "createJourneyMachineComputedGetter", "journey", "resolvedJourney", "getSnapshot", "mode", "linearStepOrder", "snapshot", "activeStepIndex", "base", "stepCount", "linearIndex", "createJourneyMachineControls", "runtime", "asyncState", "initial", "initialContext", "steps", "warnDisposedNoop", "operation", "warnInDevelopment", "buildResetSnapshot", "buildSnapshot", "cloneContext", "buildInitialAsyncState", "snapshot", "committedSnapshot", "now", "updater", "nextContext", "assertSerializableContext", "stepId", "resolvedStep", "createJourneyMachineNavigationController", "runtime", "steps", "transitions", "scheduleLifecycle", "requestedSteps", "transitionId", "runVersion", "snapshot", "buildSendResult", "stepsToGoBack", "normalizeStepCount", "from", "nextIndex", "appliedSteps", "now", "committedSnapshot", "buildSnapshot", "targetIndex", "fromStep", "eventType", "transition", "target", "transitionEvent", "nextContext", "normalizedTimeline", "assertStepExists", "beforeCurrent", "transitionSnapshot", "createJourneyMachinePluginController", "plugins", "setupContext", "hooks", "plugin", "error", "initializedPlugin", "message", "pluginError", "snapshot", "currentSnapshot", "previousSnapshot", "reason", "firstError", "result", "isPromiseLike", "warnInDevelopment", "machine", "extensionTarget", "writableExtensionTarget", "pluginExtensionKeys", "extension", "key", "value", "existingPlugin", "createJourneyMachineRuntime", "initialSnapshot", "onSnapshotChange", "onDispose", "onListenerError", "snapshot", "stabilizeSnapshot", "exposedSnapshot", "listeners", "eventListeners", "actionQueue", "lifecycleVersion", "isDisposed", "activeAbortController", "lifecycleAbortControllers", "reportListenerError", "error", "context", "errorInDevelopment", "notify", "listener", "emit", "event", "setSnapshot", "nextSnapshot", "options", "previousExposedSnapshot", "stableSnapshot", "nextExposedSnapshot", "isRunActive", "runVersion", "cancelInFlight", "controller", "openLifecycle", "closeLifecycle", "queue", "runner", "onCanceled", "createQueuedRunner", "abortController", "resultPromise", "subscribe", "selector", "equalityFn", "isEqual", "selected", "nextSelected", "previous", "createJourneyMachineSendController", "runtime", "asyncState", "navigation", "headless", "steps", "transitions", "handlers", "requireExplicitCompletion", "defaultTimeoutMs", "buildCanceledSendResult", "operation", "buildSendResult", "JourneyDisposedError", "buildErroredSendResult", "error", "transitionId", "label", "buildTransitionErrorResult", "fromStep", "eventType", "runVersion", "skipAsyncStateUpdate", "now", "resolveTransitionsForSend", "event", "isGoToStepByIdEvent", "assertStepExists", "transition", "selectTransitionForSend", "transitionsToEvaluate", "transitionEvent", "signal", "asyncGuardErrorTransitionId", "asyncGuardErrorLabel", "asyncGuardErrorHandled", "selectTransition", "stabilizeSnapshot", "currentTransition", "handleNoTransitionMatch", "fallbackResult", "resolveNextContext", "snapshot", "nextContext", "assertSerializableContext", "transitionResolution", "selectionResolution", "contextResolution", "target", "resolveTransitionTarget", "isTerminalTarget", "hashTransitionDescriptor", "value", "hash", "index", "buildResolvedTransitions", "transitions", "transitionRouteCounts", "usedIds", "transition", "target", "routeKey", "ordinal", "descriptor", "suffix", "id", "candidate", "resolveJourneyDefinition", "journey", "resolvedTransitions", "initialStep", "linearEntries", "resolvedInitial", "entry", "previousStep", "seenSteps", "offset", "allowedKeys", "key", "validateFiniteTimeout", "transitionGraph", "orderedGraphEntries", "fromKey", "eventMap", "event", "rawEdges", "isTerminal", "edges", "edge", "createJourneyMachine", "journey", "options", "stepId", "assertSerializableContext", "resolvedJourney", "resolveJourneyDefinition", "assertStepExists", "validateJourneyTransitions", "requireExplicitCompletion", "validateFiniteTimeout", "defaultTimeoutMs", "initialContextTemplate", "cloneContext", "stepMeta", "cloneMetaValue", "buildInitialSnapshot", "buildSnapshot", "buildInitialAsyncState", "pluginController", "createJourneyMachinePluginController", "initialSnapshot", "onListenerError", "onLifecycleError", "runtime", "createJourneyMachineRuntime", "asyncState", "createJourneyMachineAsyncStateController", "dispatchSend", "buildSendResult", "scheduleLifecycle", "previousSnapshot", "snapshot", "from", "to", "event", "transitionId", "label", "runVersion", "transition", "sourceStep", "targetStep", "isTerminalTarget", "handlers", "dispatch", "nextEvent", "lifecycleAbortController", "signal", "reportLifecycleError", "error", "phase", "context", "now", "navigation", "createJourneyMachineNavigationController", "sendController", "createJourneyMachineSendController", "controls", "createJourneyMachineControls", "getComputed", "createJourneyMachineComputedGetter", "machine", "listener", "steps", "payload", "makeToBuilder", "candidate", "guard", "fn", "label", "ms", "candidateToEdge", "c", "edge", "terminalCandidateToEdge", "createJourneyBuilder", "to", "stepId", "resolveEntry", "entry", "resolveTerminalEntry", "createStep", "id", "config", "build", "input", "stepsRecord", "transitionGraph", "stepBuilder", "stepTransitions", "eventType", "builders", "builder", "globalTransitions", "value"]
3
+ "sources": ["../src/index.ts", "../src/core/errors.ts", "../src/core/helpers.ts", "../src/core/machine.ts", "../../common/src/dev.ts", "../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": ["export { createLinearJourney, withLinearTypes } from \"./linear/linear\";\nexport type {\n CompletePayloadOf,\n JourneyTerminationPayloads,\n LinearJourneyDefinition,\n LinearJourneyMachine,\n LinearStepConfig,\n LinearStepIdOf,\n LinearStepInput,\n TerminatePayloadOf\n} from \"./linear/linear.types\";\n\n// normalizeGraphDefinition is deliberately not exported: its return type names\n// RuntimeStep/RuntimeTransition, which are internal and have no export path, so\n// publishing it would freeze those shapes into the 1.0 contract.\nexport { createGraphJourney, withGraphTypes } from \"./graph/graph\";\nexport type {\n GraphHookArgs,\n GraphJourneyDefinition,\n GraphJourneyMachine,\n GraphJourneyOptions,\n GraphOnEntry,\n GraphStepConfig,\n GraphTransition,\n SendArgs,\n SendVerb,\n SendWork,\n SendWorkArgs,\n TransitionGuard\n} from \"./graph/graph.types\";\n\n// Puts a declared `run` back at an inference site, so `commit` and the\n// reads its result type off it instead of the bag.\nexport { defineWork } from \"./graph/work\";\nexport type { WorkConfig } from \"./graph/work\";\n\n// The bag exists so steps can live in separate files, and so `withTypes` has\n// somewhere to pin what a definition cannot infer on its own.\nexport type {\n Bag,\n GraphDefinition,\n GraphStep,\n HandlersOf,\n MetaOf,\n ResultOf,\n ResultsOf\n} from \"./graph/bag.types\";\n\n// A plain function, not a plugin: checking a definition needs no runtime, so\n// this runs in a test or a build step before any machine exists.\nexport { analyzeStructure } from \"./diagnostics/diagnostics.helpers\";\nexport type { DiagnosticsIssue, DiagnosticsResult } from \"./diagnostics/diagnostics.types\";\n\nexport { JourneyError, isJourneyError } from \"./core/errors\";\nexport type { JourneyErrorCode, JourneyErrorDetails } from \"./core/errors\";\n\nexport type {\n AnyJourneyPlugin,\n ContextUpdater,\n CurrentStepBase,\n GraphGuardState,\n GraphSnapshot,\n GraphTransitionSnapshot,\n JourneyControls,\n JourneyEventObject,\n JourneyEventPayload,\n JourneyEventPayloads,\n JourneyHistoryState,\n JourneyMachineBase,\n JourneyNavigation,\n JourneyOutcome,\n JourneyPersistOption,\n JourneyPlugin,\n JourneyRuntimeOptions,\n JourneySnapshot,\n JourneySnapshotBase,\n JourneyStatus,\n JourneyStructure,\n JourneySubscriptionEvent,\n JourneySubscriptions,\n LinearSnapshot,\n MachineState,\n NavigationFailureReason,\n NavigationDirection,\n NavigationResult,\n StepEnterDirection,\n NavigationWork,\n NavigationWorkArgs,\n OnEnterHook,\n OnLeaveHook,\n PluginApis,\n PluginHost,\n StepAsyncState,\n StepHookArgs,\n TransitionInfo,\n TransitionState,\n Unsubscribe\n} from \"./core/types\";\n\n// Named by the exported JourneyPersistOption, so it has to be reachable here too.\nexport type { JourneyStorage } from \"./plugins/persistence/persistence.types\";\n", "/**\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"],
5
+ "mappings": "mbAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,kBAAAE,EAAA,qBAAAC,GAAA,uBAAAC,EAAA,wBAAAC,EAAA,eAAAC,GAAA,mBAAAC,EAAA,mBAAAC,GAAA,oBAAAC,KAAA,eAAAC,GAAAV,ICkDO,IAAMW,EAAN,cAA2B,KAAM,CAMtC,YACEC,EACAC,EACAC,EAA+B,CAAC,EAChCC,EACA,CACA,MAAM,YAAYF,CAA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,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": ["index_exports", "__export", "JourneyError", "analyzeStructure", "createGraphJourney", "createLinearJourney", "defineWork", "isJourneyError", "withGraphTypes", "withLinearTypes", "__toCommonJS", "JourneyError", "code", "message", "details", "cause", "isJourneyError", "value", "eventWorkKey", "from", "event", "describeTransition", "transition", "transitionInfo", "SUCCESS_ASYNC", "LOADING_ASYNC", "hasOwn", "target", "key", "reportListenerError", "error", "shallowEqual", "a", "b", "keys", "buildMachineSurface", "runtime", "payload", "id", "n", "work", "listener", "event", "updater", "isDevelopmentEnvironment", "diagnosticGlobal", "nodeEnv", "warnInDevelopment", "message", "detail", "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
  }