@rxova/journey-core 0.7.0 → 1.0.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +236 -105
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.cts +5 -4
- package/dist/index.d.ts +5 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +4 -4
- package/dist/journey-builder/index.d.cts +5 -0
- package/dist/journey-builder/index.d.ts +5 -0
- package/dist/journey-builder/types.d.cts +126 -0
- package/dist/journey-builder/types.d.ts +126 -0
- package/dist/journey-machine/async-state.d.cts +12 -0
- package/dist/journey-machine/async-state.d.ts +12 -0
- package/dist/journey-machine/computed.d.cts +2 -0
- package/dist/journey-machine/computed.d.ts +2 -0
- package/dist/journey-machine/controls.d.cts +17 -0
- package/dist/journey-machine/controls.d.ts +17 -0
- package/dist/journey-machine/helpers.d.cts +52 -0
- package/dist/journey-machine/helpers.d.ts +52 -0
- package/dist/journey-machine/index.d.cts +3 -0
- package/dist/journey-machine/index.d.ts +3 -0
- package/dist/journey-machine/navigation.d.cts +32 -0
- package/dist/journey-machine/navigation.d.ts +32 -0
- package/dist/journey-machine/plugin-controller.d.cts +15 -0
- package/dist/journey-machine/plugin-controller.d.ts +15 -0
- package/dist/journey-machine/resolve-journey-definition.d.cts +2 -0
- package/dist/journey-machine/resolve-journey-definition.d.ts +2 -0
- package/dist/journey-machine/runtime.d.cts +33 -0
- package/dist/journey-machine/runtime.d.ts +33 -0
- package/dist/journey-machine/send.d.cts +9 -0
- package/dist/journey-machine/send.d.ts +9 -0
- package/dist/plugins/analytics/index.cjs +2 -0
- package/dist/plugins/analytics/index.cjs.map +7 -0
- package/dist/plugins/analytics/index.d.cts +25 -0
- package/dist/plugins/analytics/index.d.ts +25 -0
- package/dist/plugins/analytics/index.js +2 -0
- package/dist/plugins/analytics/index.js.map +7 -0
- package/dist/plugins/autosave/index.cjs +2 -0
- package/dist/plugins/autosave/index.cjs.map +7 -0
- package/dist/plugins/autosave/index.d.cts +17 -0
- package/dist/plugins/autosave/index.d.ts +17 -0
- package/dist/plugins/autosave/index.js +2 -0
- package/dist/plugins/autosave/index.js.map +7 -0
- package/dist/plugins/diagnostics/diagnostics.d.cts +3 -0
- package/dist/plugins/diagnostics/diagnostics.d.ts +3 -0
- package/dist/plugins/diagnostics/index.cjs +2 -0
- package/dist/plugins/diagnostics/index.cjs.map +7 -0
- package/dist/plugins/diagnostics/index.d.cts +15 -0
- package/dist/plugins/diagnostics/index.d.ts +15 -0
- package/dist/plugins/diagnostics/index.js +2 -0
- package/dist/plugins/diagnostics/index.js.map +7 -0
- package/dist/plugins/execution-paths/execution-paths.d.cts +6 -0
- package/dist/plugins/execution-paths/execution-paths.d.ts +6 -0
- package/dist/plugins/execution-paths/index.cjs +2 -0
- package/dist/plugins/execution-paths/index.cjs.map +7 -0
- package/dist/plugins/execution-paths/index.d.cts +18 -0
- package/dist/plugins/execution-paths/index.d.ts +18 -0
- package/dist/plugins/execution-paths/index.js +2 -0
- package/dist/plugins/execution-paths/index.js.map +7 -0
- package/dist/plugins/persistence/controller.d.cts +17 -0
- package/dist/plugins/persistence/controller.d.ts +17 -0
- package/dist/plugins/persistence/index.cjs +2 -0
- package/dist/plugins/persistence/index.cjs.map +7 -0
- package/dist/plugins/persistence/index.d.cts +12 -0
- package/dist/plugins/persistence/index.d.ts +12 -0
- package/dist/plugins/persistence/index.js +2 -0
- package/dist/plugins/persistence/index.js.map +7 -0
- package/dist/plugins/replay/index.cjs +2 -0
- package/dist/plugins/replay/index.cjs.map +7 -0
- package/dist/plugins/replay/index.d.cts +27 -0
- package/dist/plugins/replay/index.d.ts +27 -0
- package/dist/plugins/replay/index.js +2 -0
- package/dist/plugins/replay/index.js.map +7 -0
- package/dist/types/analytics.types.d.cts +33 -0
- package/dist/types/analytics.types.d.ts +33 -0
- package/dist/types/autosave.types.d.cts +23 -0
- package/dist/types/autosave.types.d.ts +23 -0
- package/dist/types/diagnostics.types.d.cts +38 -0
- package/dist/types/diagnostics.types.d.ts +38 -0
- package/dist/types/index.d.cts +9 -0
- package/dist/types/index.d.ts +9 -4
- package/dist/types/journey.types.d.cts +191 -0
- package/dist/types/journey.types.d.ts +140 -167
- package/dist/types/machine.types.d.cts +104 -0
- package/dist/types/machine.types.d.ts +104 -0
- package/dist/types/observation.types.d.cts +83 -0
- package/dist/types/observation.types.d.ts +83 -0
- package/dist/types/persistence.types.d.cts +34 -0
- package/dist/types/persistence.types.d.ts +13 -20
- package/dist/types/replay.types.d.cts +35 -0
- package/dist/types/replay.types.d.ts +35 -0
- package/dist/types/transitions.types.d.cts +122 -0
- package/dist/types/transitions.types.d.ts +100 -57
- package/package.json +92 -2
- package/dist/machine-helpers.d.ts +0 -23
- package/dist/machine.d.ts +0 -11
- package/dist/persistence.d.ts +0 -17
- package/dist/transitions.d.ts +0 -62
- package/dist/types.d.ts +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var x=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),J=e=>Array.isArray(e)?e.map(n=>J(n)):x(e)?Object.fromEntries(Object.entries(e).map(([n,t])=>[n,J(t)])):e,O=e=>{if(e===null)return"null";if(Array.isArray(e))return"array";if(typeof e=="object"){let n=e.constructor?.name;return n&&n!=="Object"?n:"object"}return typeof e};function P(e,n,t,s=[]){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return;let r=s.length===0?n:`${n}.${s.join(".")}`;if(e===void 0)throw new Error(`${r} must be JSON-serializable. Received undefined.`);if(typeof e=="bigint"||typeof e=="symbol"||typeof e=="function")throw new Error(`${r} must be JSON-serializable. Received ${typeof e}.`);if(typeof e!="object")throw new Error(`${r} must be JSON-serializable. Received ${O(e)}.`);if(t.seen.has(e))throw new Error(`${r} must be JSON-serializable. Circular references are not supported.`);if(t.seen.add(e),Array.isArray(e)){for(let[o,i]of e.entries())P(i,n,t,[...s,String(o)]);return}if(!x(e))throw new Error(`${r} must be JSON-serializable. Received non-plain ${O(e)}.`);for(let[o,i]of Object.entries(e))P(i,n,t,[...s,o])}function g(e,n="Journey context"){return P(e,n,{seen:new WeakSet}),e}var W=e=>J(g(e));var R=e=>[...new Set(e)],q=(e,n)=>Object.fromEntries(n.map(t=>[t,e[t]===!0])),I=(e,n)=>{let t=n??R(e),s=Object.fromEntries(t.map(r=>[r,!1]));for(let r of e)s[r]=!0;return s};var K=()=>{let e=globalThis;if(typeof e.__DEV__=="boolean")return e.__DEV__;let n=e.process?.env?.NODE_ENV;return n===void 0||n==="development"},j=(e,n)=>{if(!(!K()||typeof console>"u")){if(n===void 0){console.warn(e);return}console.warn(e,n)}};var U=()=>({phase:"idle",eventType:null,transitionId:null,error:null}),M=e=>({isLoading:!1,byStep:Object.fromEntries(Object.keys(e).map(t=>[t,U()]))});var E=(e,n,t,s,r,o)=>{if(e.length===0)throw new Error("Journey timeline cannot be empty.");let i=Math.max(0,Math.min(Math.trunc(n),e.length-1)),u=e[i],c=R(o?[...Object.keys(o),...e]:e);return{status:s,currentStepId:u,history:{timeline:[...e],index:i},context:W(t),visited:o?q(o,c):I(e,c),async:J(r)}};var k=e=>typeof e=="object"&&e!==null,$=e=>e==="idled"||e==="running"||e==="completed"||e==="terminated",Q=(e,n)=>{if(typeof e!="string")throw new Error(`Persistence ${n} entries must be strings.`);let t=e.trim();if(!t)throw new Error(`Persistence ${n} entries must not be empty.`);if(t.includes("[")||t.includes("]")||t.includes("*")||t.startsWith(".")||t.endsWith(".")||t.includes(".."))throw new Error(`Persistence ${n} entry "${t}" must use exact dot-separated object keys.`);let s=t.split(".");if(s.some(r=>!r||r.trim()!==r||/^[0-9]+$/.test(r)))throw new Error(`Persistence ${n} entry "${t}" must use exact dot-separated object keys.`);return s},V=(e,n)=>{if(e===void 0)return null;if(!Array.isArray(e))throw new Error(`Persistence ${n} must be an array of dot-separated strings.`);let t=new Map;for(let s of e){let r=Q(s,n);t.set(r.join("."),r)}return[...t.values()]},D=(e,n)=>n.length<=e.length&&n.every((t,s)=>e[s]===t),L=(e,n)=>e.some(t=>D(n,t)),X=(e,n)=>e.some(t=>D(t,n)),_=(e,n,t,s=[])=>{if(L(t,s))return{value:void 0,changed:!0,included:!1};let r=n===null,o=r||L(n,s),i=r||X(n,s);if(!o&&!i)return{value:void 0,changed:!0,included:!1};if(!x(e))return{value:e,changed:!o,included:o};let u=!1,c={};for(let[y,T]of Object.entries(e)){let p=_(T,n,t,[...s,y]);if(!p.included){u=!0;continue}c[y]=p.value,p.changed&&(u=!0)}return{value:c,changed:u||Object.keys(c).length!==Object.keys(e).length,included:!0}},F=(e,n)=>{if(x(e)&&x(n)){let t=new Map;for(let[s,r]of Object.entries(e))t.set(s,r);for(let[s,r]of Object.entries(n))t.set(s,F(e[s],r));return Object.fromEntries(t)}return n===void 0?e??null:n},Y=(e,n)=>F(e,n),Z=()=>{let e=globalThis.localStorage;return!e||typeof e.getItem!="function"||typeof e.setItem!="function"||typeof e.removeItem!="function"?null:e},C=(e,n)=>{if(n){n(e);return}j("Journey persistence encountered an error without an onError handler.",e)},ee=e=>{if(!e)return null;let n=e.storage;if(n==null)try{n=Z()}catch(r){return C(r,e.onError),null}if(!n)return null;let t,s;try{let r=V(e.allowList,"allowList"),o=V(e.blockList,"blockList");t=r?r.map(i=>i.join(".")):void 0,s=o?o.map(i=>i.join(".")):[]}catch(r){return C(r,e.onError),null}return{key:e.key,storage:n,version:e.version??1,clearOnReset:e.clearOnReset??!0,...t?{allowList:t}:{},blockList:s,serialize:e.serialize??JSON.stringify,deserialize:e.deserialize??JSON.parse,...e.migrate?{migrate:e.migrate}:{},...e.onError?{onError:e.onError}:{}}},ne=(e,n,t)=>{let s=I(n,t);if(k(e)){let r=!1,o={...s};for(let i of t){let u=e[i];if(u===!0){o[i]=!0;continue}if(u===!1){s[i]&&(r=!0);continue}r=!0}return{visited:o,needsRewrite:r}}if(Array.isArray(e)){let r=I(e.filter(i=>typeof i=="string"&&t.includes(i)),t);return{visited:Object.fromEntries(t.map(i=>[i,s[i]||r[i]])),needsRewrite:!0}}return{visited:s,needsRewrite:!0}},z=(e,n,t)=>{if(!k(e))return null;let s=!1,r=k(e.history)?e.history:null;r||(s=!0);let o=r?.timeline??e.timeline,i=Array.isArray(o)?o.filter(a=>typeof a=="string"&&a in n):[],u=typeof e.currentStepId=="string"&&e.currentStepId in n?e.currentStepId:typeof e.current=="string"&&e.current in n?e.current:null;if(i.length===0){if(!u)return null;i.push(u),s=!0}let c=i.length-1,y=r?.index??e.index;if(typeof y=="number"&&Number.isFinite(y))c=Math.max(0,Math.min(Math.trunc(y),i.length-1)),c!==y&&(s=!0);else if(u){let a=i.lastIndexOf(u);a>=0&&(c=a,s=!0)}let T=$(e.status)?e.status:"idled";$(e.status)||(s=!0);let p=Object.keys(n),{visited:S,needsRewrite:m}=ne(e.visited,i,p);return m&&(s=!0),{snapshot:{currentStepId:i[c],history:{timeline:i,index:c},context:g("context"in e?e.context:t,"Persisted journey context"),status:T,visited:S},needsRewrite:s}},N=e=>{let{initial:n,context:t,steps:s,options:r}=e,o=ee(r),i=o?.allowList?o.allowList.map(a=>a.split(".")):null,u=o?o.blockList.map(a=>a.split(".")):[],c=a=>{C(a,o?.onError)},y=a=>{if(!o||i===null&&u.length===0)return{context:a,changed:!1};if(!x(a))return{context:a,changed:!1};let d=_(a,i,u);return{context:d.included&&x(d.value)?d.value:{},changed:d.changed}},T=a=>{if(o)try{let{context:d}=y(a.context),l={version:o.version,snapshot:{currentStepId:a.currentStepId,history:{timeline:[...a.history.timeline],index:a.history.index},context:d,status:a.status,visited:{...a.visited}}};o.storage.setItem(o.key,o.serialize(l))}catch(d){c(d)}},p=()=>{if(o)try{o.storage.removeItem(o.key)}catch(a){c(a)}},S=()=>E([n],0,t,"idled",M(s)),m=(a=S())=>{let d=E(a.history.timeline,a.history.index,a.context,a.status,a.async,a.visited);if(!o)return d;try{let l=o.storage.getItem(o.key);if(!l)return d;let h=o.deserialize(l);if(!k(h))return d;let b=h.version;if(typeof b!="number")return d;let f=null,v=!1;if(b===o.version){let w=z(h.snapshot,s,t);f=w?.snapshot??null,v=!!w?.needsRewrite}else if(o.migrate){let w=o.migrate(h.snapshot,b);f=z(w,s,t)?.snapshot??null,v=f!==null,f||c(new Error(`Journey persistence migrate() returned data that could not be coerced into a valid snapshot. Falling back to the initial snapshot (persisted version: ${b}, current version: ${o.version}).`))}if(!f)return d;let{context:H,changed:G}=y(f.context),B=Y(d.context,H),A=E(f.history.timeline,f.history.index,g(B,"Hydrated journey context"),f.status==="running"?"idled":f.status,d.async,f.visited);return(v||G)&&T(A),A}catch(l){return c(l),d}};return{clearOnReset:o?.clearOnReset??!0,hydrateSnapshot:m,persistSnapshot:T,removePersistedSnapshot:p}};var te=["context","navigation","reset","start","transition"],re=e=>typeof e!="number"||!Number.isFinite(e)?300:Math.max(0,Math.trunc(e)),ue=e=>{let n=re(e.debounceMs),t=e.hydrate??!0,s=new Set(e.saveOn??te),r={status:"idle"},o=null,i=null,u=!1;return{name:"autosave",__extension__:void 0,setup:(({resolvedJourney:y})=>{let T=e,p=N({initial:y.initial,context:y.context,steps:y.steps,options:{...T,onError:d=>{u=!0,r={status:"error",...r.lastSavedAt!==void 0?{lastSavedAt:r.lastSavedAt}:{},...r.pendingReason!==void 0?{pendingReason:r.pendingReason}:{},error:d},T.onError?.(d)}}}),S=()=>{o!==null&&(clearTimeout(o),o=null)},m=()=>{if(S(),!i)return;let d=i;if(i=null,u=!1,p.persistSnapshot(d.snapshot),u)return;let l=Date.now();r={status:"saved",lastSavedAt:l},T.onSaved?.({snapshot:d.snapshot,reason:d.reason,timestamp:l})},a=(d,l)=>{if(i={snapshot:d,reason:l},r={status:"pending",...r.lastSavedAt!==void 0?{lastSavedAt:r.lastSavedAt}:{},pendingReason:l},n===0){m();return}S(),o=setTimeout(()=>{m()},n)};return{hydrateSnapshot:d=>t?p.hydrateSnapshot(d):d,onSnapshotChange:({snapshot:d,reason:l})=>{if(l!=="async"){if(l==="reset"&&p.clearOnReset){S(),i=null,p.removePersistedSnapshot(),r={status:"idle"};return}s.has(l)&&a(d,l)}},augmentMachine:()=>({getAutosaveState:()=>({...r}),flushAutosave:async()=>{m()},clearAutosave:()=>{S(),i=null,p.removePersistedSnapshot(),r={status:"idle"}}}),dispose:()=>{S()}}})}};export{ue as createAutosavePlugin};
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/journey-machine/helpers.ts", "../../../src/plugins/persistence/controller.ts", "../../../src/plugins/autosave/index.ts"],
|
|
4
|
+
"sourcesContent": ["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 type {\n JourneyPersistedState,\n JourneyPersistenceOptions,\n JourneyStorage,\n ResolvedPersistence\n} from \"../../types/persistence.types\";\nimport type {\n JourneyJsonValue,\n JourneyJsonObject,\n JourneySnapshot,\n JourneySnapshotStateBase,\n JourneyStatus\n} from \"../../types/journey.types\";\nimport {\n assertSerializableContext,\n buildInitialAsyncState,\n buildSnapshot,\n buildVisitedFromTimeline,\n isPlainObject,\n warnInDevelopment\n} from \"../../journey-machine/helpers\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst isStatusValue = (value: unknown): value is JourneyStatus =>\n value === \"idled\" || value === \"running\" || value === \"completed\" || value === \"terminated\";\n\ntype PersistencePath = readonly string[];\n\nconst normalizePersistencePath = (\n path: unknown,\n optionName: \"allowList\" | \"blockList\"\n): PersistencePath => {\n if (typeof path !== \"string\") {\n throw new Error(`Persistence ${optionName} entries must be strings.`);\n }\n\n const trimmedPath = path.trim();\n if (!trimmedPath) {\n throw new Error(`Persistence ${optionName} entries must not be empty.`);\n }\n\n if (\n trimmedPath.includes(\"[\") ||\n trimmedPath.includes(\"]\") ||\n trimmedPath.includes(\"*\") ||\n trimmedPath.startsWith(\".\") ||\n trimmedPath.endsWith(\".\") ||\n trimmedPath.includes(\"..\")\n ) {\n throw new Error(\n `Persistence ${optionName} entry \"${trimmedPath}\" must use exact dot-separated object keys.`\n );\n }\n\n const segments = trimmedPath.split(\".\");\n if (\n segments.some((segment) => !segment || segment.trim() !== segment || /^[0-9]+$/.test(segment))\n ) {\n throw new Error(\n `Persistence ${optionName} entry \"${trimmedPath}\" must use exact dot-separated object keys.`\n );\n }\n\n return segments;\n};\n\nconst normalizePersistencePaths = (\n paths: unknown,\n optionName: \"allowList\" | \"blockList\"\n): readonly PersistencePath[] | null => {\n if (paths === undefined) {\n return null;\n }\n\n if (!Array.isArray(paths)) {\n throw new Error(`Persistence ${optionName} must be an array of dot-separated strings.`);\n }\n\n const normalized = new Map<string, PersistencePath>();\n for (const path of paths) {\n const resolvedPath = normalizePersistencePath(path, optionName);\n normalized.set(resolvedPath.join(\".\"), resolvedPath);\n }\n\n return [...normalized.values()];\n};\n\nconst pathStartsWith = (path: readonly string[], prefix: readonly string[]): boolean =>\n prefix.length <= path.length && prefix.every((segment, index) => path[index] === segment);\n\nconst pathHasAncestorMatch = (\n candidates: readonly PersistencePath[],\n path: readonly string[]\n): boolean => candidates.some((candidate) => pathStartsWith(path, candidate));\n\nconst pathHasDescendantMatch = (\n candidates: readonly PersistencePath[],\n path: readonly string[]\n): boolean => candidates.some((candidate) => pathStartsWith(candidate, path));\n\nconst filterContextValue = (\n value: unknown,\n allowList: readonly PersistencePath[] | null,\n blockList: readonly PersistencePath[],\n path: readonly string[] = []\n): { value: unknown; changed: boolean; included: boolean } => {\n if (pathHasAncestorMatch(blockList, path)) {\n return { value: undefined, changed: true, included: false };\n }\n\n const allowAll = allowList === null;\n const pathIsAllowed = allowAll || pathHasAncestorMatch(allowList, path);\n const pathHasAllowedDescendants = allowAll || pathHasDescendantMatch(allowList, path);\n\n if (!pathIsAllowed && !pathHasAllowedDescendants) {\n return { value: undefined, changed: true, included: false };\n }\n\n if (!isPlainObject(value)) {\n return {\n value,\n changed: !pathIsAllowed,\n included: pathIsAllowed\n };\n }\n\n let changed = false;\n const nextValue: Record<string, unknown> = {};\n\n for (const [key, childValue] of Object.entries(value)) {\n const result = filterContextValue(childValue, allowList, blockList, [...path, key]);\n if (!result.included) {\n changed = true;\n continue;\n }\n\n nextValue[key] = result.value;\n if (result.changed) {\n changed = true;\n }\n }\n\n return {\n value: nextValue,\n changed: changed || Object.keys(nextValue).length !== Object.keys(value).length,\n included: true\n };\n};\n\nconst mergePersistedValue = (\n initialValue: JourneyJsonValue | undefined,\n persistedValue: unknown\n): JourneyJsonValue => {\n if (isPlainObject(initialValue) && isPlainObject(persistedValue)) {\n const mergedEntries = new Map<string, JourneyJsonValue>();\n\n for (const [key, value] of Object.entries(initialValue)) {\n mergedEntries.set(key, value as JourneyJsonValue);\n }\n\n for (const [key, value] of Object.entries(persistedValue)) {\n mergedEntries.set(\n key,\n mergePersistedValue(initialValue[key] as JourneyJsonValue | undefined, value)\n );\n }\n\n return Object.fromEntries(mergedEntries) as JourneyJsonValue;\n }\n\n return persistedValue === undefined\n ? (initialValue ?? null)\n : (persistedValue as JourneyJsonValue);\n};\n\nconst mergePersistedContext = <TContext extends JourneyJsonObject>(\n initialContext: TContext,\n persistedContext: unknown\n): TContext => mergePersistedValue(initialContext, persistedContext) as TContext;\n\nconst resolveDefaultStorage = (): JourneyStorage | null => {\n const localStorageCandidate = (globalThis as { localStorage?: Partial<JourneyStorage> })\n .localStorage;\n\n if (\n !localStorageCandidate ||\n typeof localStorageCandidate.getItem !== \"function\" ||\n typeof localStorageCandidate.setItem !== \"function\" ||\n typeof localStorageCandidate.removeItem !== \"function\"\n ) {\n return null;\n }\n\n return localStorageCandidate as JourneyStorage;\n};\n\nconst reportPersistenceError = (error: unknown, onError?: (error: unknown) => void) => {\n if (onError) {\n onError(error);\n return;\n }\n\n warnInDevelopment(\"Journey persistence encountered an error without an onError handler.\", error);\n};\n\nconst resolvePersistence = <TContext extends JourneyJsonObject, TStepId extends string>(\n options?: JourneyPersistenceOptions<TContext, TStepId>\n): ResolvedPersistence<TContext, TStepId> | null => {\n if (!options) {\n return null;\n }\n\n let storage: JourneyStorage | null | undefined = options.storage;\n if (storage == null) {\n try {\n storage = resolveDefaultStorage();\n } catch (error) {\n reportPersistenceError(error, options.onError);\n return null;\n }\n }\n\n if (!storage) {\n return null;\n }\n\n let allowList: readonly string[] | undefined;\n let blockList: readonly string[];\n\n try {\n const normalizedAllowList = normalizePersistencePaths(options.allowList, \"allowList\");\n const normalizedBlockList = normalizePersistencePaths(options.blockList, \"blockList\");\n\n allowList = normalizedAllowList ? normalizedAllowList.map((path) => path.join(\".\")) : undefined;\n blockList = normalizedBlockList ? normalizedBlockList.map((path) => path.join(\".\")) : [];\n } catch (error) {\n reportPersistenceError(error, options.onError);\n return null;\n }\n\n return {\n key: options.key,\n storage,\n version: options.version ?? 1,\n clearOnReset: options.clearOnReset ?? true,\n ...(allowList ? { allowList } : {}),\n blockList,\n serialize: options.serialize ?? JSON.stringify,\n deserialize: options.deserialize ?? JSON.parse,\n ...(options.migrate ? { migrate: options.migrate } : {}),\n ...(options.onError ? { onError: options.onError } : {})\n };\n};\n\nconst resolveVisitedFromPersistence = <TStepId extends string>(\n visitedSource: unknown,\n timeline: readonly TStepId[],\n stepIds: readonly TStepId[]\n): {\n visited: Record<TStepId, boolean>;\n needsRewrite: boolean;\n} => {\n const visitedFromTimeline = buildVisitedFromTimeline(timeline, stepIds);\n\n if (isRecord(visitedSource)) {\n let needsRewrite = false;\n const visited = { ...visitedFromTimeline };\n\n for (const stepId of stepIds) {\n const persistedValue = visitedSource[stepId];\n\n if (persistedValue === true) {\n visited[stepId] = true;\n continue;\n }\n\n if (persistedValue === false) {\n if (visitedFromTimeline[stepId]) {\n needsRewrite = true;\n }\n continue;\n }\n\n needsRewrite = true;\n }\n\n return { visited, needsRewrite };\n }\n\n if (Array.isArray(visitedSource)) {\n const visitedFromArray = buildVisitedFromTimeline(\n visitedSource.filter(\n (step): step is TStepId => typeof step === \"string\" && stepIds.includes(step as TStepId)\n ) as TStepId[],\n stepIds\n );\n const visited = Object.fromEntries(\n stepIds.map((stepId) => [stepId, visitedFromTimeline[stepId] || visitedFromArray[stepId]])\n ) as Record<TStepId, boolean>;\n\n return { visited, needsRewrite: true };\n }\n\n return { visited: visitedFromTimeline, needsRewrite: true };\n};\n\nconst coercePersistedSnapshot = <TContext extends JourneyJsonObject, TStepId extends string>(\n value: unknown,\n steps: Record<TStepId, unknown>,\n fallbackContext: TContext\n): {\n snapshot: JourneySnapshotStateBase<TContext, TStepId>;\n needsRewrite: boolean;\n} | null => {\n if (!isRecord(value)) {\n return null;\n }\n\n let needsRewrite = false;\n\n const rawHistory = isRecord(value.history) ? value.history : null;\n if (!rawHistory) {\n needsRewrite = true;\n }\n\n const rawTimeline = rawHistory?.timeline ?? value.timeline;\n const timeline = Array.isArray(rawTimeline)\n ? (rawTimeline.filter(\n (step): step is TStepId => typeof step === \"string\" && step in steps\n ) as TStepId[])\n : [];\n\n const currentStepIdValue =\n typeof value.currentStepId === \"string\" && value.currentStepId in steps\n ? (value.currentStepId as TStepId)\n : typeof value.current === \"string\" && value.current in steps\n ? (value.current as TStepId)\n : null;\n\n if (timeline.length === 0) {\n if (!currentStepIdValue) {\n return null;\n }\n timeline.push(currentStepIdValue);\n needsRewrite = true;\n }\n\n let index = timeline.length - 1;\n const rawIndex = rawHistory?.index ?? value.index;\n if (typeof rawIndex === \"number\" && Number.isFinite(rawIndex)) {\n index = Math.max(0, Math.min(Math.trunc(rawIndex), timeline.length - 1));\n if (index !== rawIndex) {\n needsRewrite = true;\n }\n } else if (currentStepIdValue) {\n const inferredIndex = timeline.lastIndexOf(currentStepIdValue);\n if (inferredIndex >= 0) {\n index = inferredIndex;\n needsRewrite = true;\n }\n }\n\n const status = isStatusValue(value.status) ? value.status : \"idled\";\n if (!isStatusValue(value.status)) {\n needsRewrite = true;\n }\n\n const stepIds = Object.keys(steps) as TStepId[];\n const { visited, needsRewrite: visitedNeedsRewrite } = resolveVisitedFromPersistence(\n value.visited,\n timeline,\n stepIds\n );\n if (visitedNeedsRewrite) {\n needsRewrite = true;\n }\n\n return {\n snapshot: {\n currentStepId: timeline[index] as TStepId,\n history: {\n timeline,\n index\n },\n context: assertSerializableContext(\n (\"context\" in value ? value.context : fallbackContext) as TContext,\n \"Persisted journey context\"\n ),\n status,\n visited\n },\n needsRewrite\n };\n};\n\n/**\n * Creates a persistence controller for snapshots, including hydration,\n * serialization, and storage error handling.\n */\nexport const createPersistenceController = <\n TContext extends JourneyJsonObject,\n TStepId extends string\n>(args: {\n initial: TStepId;\n context: TContext;\n steps: Record<TStepId, unknown>;\n options?: JourneyPersistenceOptions<TContext, TStepId>;\n}) => {\n const { initial, context, steps, options } = args;\n const persistence = resolvePersistence(options);\n const allowList = persistence?.allowList\n ? persistence.allowList.map((path) => path.split(\".\"))\n : null;\n const blockList = persistence ? persistence.blockList.map((path) => path.split(\".\")) : [];\n\n const reportResolvedPersistenceError = (error: unknown) => {\n reportPersistenceError(error, persistence?.onError);\n };\n\n const filterPersistedContext = (value: TContext): { context: TContext; changed: boolean } => {\n if (!persistence || (allowList === null && blockList.length === 0)) {\n return { context: value, changed: false };\n }\n\n if (!isPlainObject(value)) {\n return { context: value, changed: false };\n }\n\n const filtered = filterContextValue(value, allowList, blockList);\n const filteredContext =\n filtered.included && isPlainObject(filtered.value) ? filtered.value : {};\n\n return {\n context: filteredContext as TContext,\n changed: filtered.changed\n };\n };\n\n const persistSnapshot = (snapshot: JourneySnapshot<TContext, TStepId>) => {\n if (!persistence) {\n return;\n }\n\n try {\n const { context: persistedContext } = filterPersistedContext(snapshot.context);\n const persistedState: JourneyPersistedState<TContext, TStepId> = {\n version: persistence.version,\n snapshot: {\n currentStepId: snapshot.currentStepId,\n history: {\n timeline: [...snapshot.history.timeline],\n index: snapshot.history.index\n },\n context: persistedContext,\n status: snapshot.status,\n visited: { ...snapshot.visited }\n }\n };\n persistence.storage.setItem(persistence.key, persistence.serialize(persistedState));\n } catch (error) {\n reportResolvedPersistenceError(error);\n }\n };\n\n const removePersistedSnapshot = () => {\n if (!persistence) {\n return;\n }\n\n try {\n persistence.storage.removeItem(persistence.key);\n } catch (error) {\n reportResolvedPersistenceError(error);\n }\n };\n\n const buildBaseSnapshot = () =>\n buildSnapshot([initial], 0, context, \"idled\", buildInitialAsyncState(steps));\n const hydrateSnapshot = (\n baseSnapshot: JourneySnapshot<TContext, TStepId> = buildBaseSnapshot()\n ): JourneySnapshot<TContext, TStepId> => {\n const resolvedBaseSnapshot = buildSnapshot(\n baseSnapshot.history.timeline,\n baseSnapshot.history.index,\n baseSnapshot.context,\n baseSnapshot.status,\n baseSnapshot.async,\n baseSnapshot.visited\n );\n if (!persistence) {\n return resolvedBaseSnapshot;\n }\n\n try {\n const rawPersisted = persistence.storage.getItem(persistence.key);\n if (!rawPersisted) {\n return resolvedBaseSnapshot;\n }\n\n const parsed = persistence.deserialize(rawPersisted);\n if (!isRecord(parsed)) {\n return resolvedBaseSnapshot;\n }\n\n const persistedVersion = parsed.version;\n if (typeof persistedVersion !== \"number\") {\n return resolvedBaseSnapshot;\n }\n\n let persistedSnapshot: JourneySnapshotStateBase<TContext, TStepId> | null = null;\n let shouldRewritePersisted = false;\n\n if (persistedVersion === persistence.version) {\n const coerced = coercePersistedSnapshot(parsed.snapshot, steps, context);\n persistedSnapshot = coerced?.snapshot ?? null;\n shouldRewritePersisted = Boolean(coerced?.needsRewrite);\n } else if (persistence.migrate) {\n const migrated = persistence.migrate(parsed.snapshot, persistedVersion);\n const coerced = coercePersistedSnapshot(migrated, steps, context);\n persistedSnapshot = coerced?.snapshot ?? null;\n shouldRewritePersisted = persistedSnapshot !== null;\n\n if (!persistedSnapshot) {\n reportResolvedPersistenceError(\n new Error(\n \"Journey persistence migrate() returned data that could not be coerced into a valid snapshot. \" +\n `Falling back to the initial snapshot (persisted version: ${persistedVersion}, current version: ${persistence.version}).`\n )\n );\n }\n }\n\n if (!persistedSnapshot) {\n return resolvedBaseSnapshot;\n }\n\n const { context: filteredContext, changed: contextWasFiltered } = filterPersistedContext(\n persistedSnapshot.context\n );\n const hydratedContext = mergePersistedContext(resolvedBaseSnapshot.context, filteredContext);\n\n const hydratedSnapshot = buildSnapshot(\n persistedSnapshot.history.timeline,\n persistedSnapshot.history.index,\n assertSerializableContext(hydratedContext, \"Hydrated journey context\"),\n persistedSnapshot.status === \"running\" ? \"idled\" : persistedSnapshot.status,\n resolvedBaseSnapshot.async,\n persistedSnapshot.visited\n );\n\n if (shouldRewritePersisted || contextWasFiltered) {\n persistSnapshot(hydratedSnapshot);\n }\n\n return hydratedSnapshot;\n } catch (error) {\n reportResolvedPersistenceError(error);\n return resolvedBaseSnapshot;\n }\n };\n\n return {\n clearOnReset: persistence?.clearOnReset ?? true,\n hydrateSnapshot,\n persistSnapshot,\n removePersistedSnapshot\n };\n};\n", "import { createPersistenceController } from \"../persistence/controller\";\n\nimport type {\n JourneyAutosavePluginOptions,\n JourneyAutosaveState,\n JourneyJsonObject,\n JourneyMachine,\n JourneyMachinePlugin,\n JourneyMachineSnapshotReason,\n JourneySnapshot\n} from \"../../types\";\n\nconst DEFAULT_SAVE_REASONS = [\"context\", \"navigation\", \"reset\", \"start\", \"transition\"] as const;\n\nconst normalizeDebounceMs = (value: number | undefined) => {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return 300;\n }\n\n return Math.max(0, Math.trunc(value));\n};\n\nexport type JourneyAutosaveMachineExtension = {\n getAutosaveState: () => JourneyAutosaveState;\n flushAutosave: () => Promise<void>;\n clearAutosave: () => void;\n};\n\nexport type JourneyAutosaveMachine<\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> = JourneyMachine<TContext, TStepId, TEventMap, TStepMeta, THandlers> &\n JourneyAutosaveMachineExtension;\n\n/**\n * Creates a plugin that debounces snapshot persistence and exposes autosave\n * runtime state without requiring the persistence plugin as a public dependency.\n */\nexport const createAutosavePlugin = <TContext extends JourneyJsonObject, TStepId extends string>(\n options: JourneyAutosavePluginOptions<TContext, TStepId>\n) => {\n const debounceMs = normalizeDebounceMs(options.debounceMs);\n const hydrate = options.hydrate ?? true;\n const saveReasons = new Set(options.saveOn ?? DEFAULT_SAVE_REASONS);\n let autosaveState: JourneyAutosaveState = { status: \"idle\" };\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n let pending: {\n snapshot: JourneySnapshot<JourneyJsonObject, string>;\n reason: JourneyMachineSnapshotReason;\n } | null = null;\n let lastSaveErrored = false;\n\n const setup = (({ resolvedJourney }) => {\n const resolvedOptions = options as unknown as JourneyAutosavePluginOptions<TContext, TStepId>;\n const controller = createPersistenceController({\n initial: resolvedJourney.initial as unknown as TStepId,\n context: resolvedJourney.context as unknown as TContext,\n steps: resolvedJourney.steps as unknown as Record<TStepId, unknown>,\n options: {\n ...resolvedOptions,\n onError: (error) => {\n lastSaveErrored = true;\n autosaveState = {\n status: \"error\",\n ...(autosaveState.lastSavedAt !== undefined\n ? { lastSavedAt: autosaveState.lastSavedAt }\n : {}),\n ...(autosaveState.pendingReason !== undefined\n ? { pendingReason: autosaveState.pendingReason }\n : {}),\n error\n };\n resolvedOptions.onError?.(error);\n }\n } as JourneyAutosavePluginOptions<TContext, TStepId>\n });\n\n const clearTimer = () => {\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n };\n\n const commitPending = () => {\n clearTimer();\n if (!pending) {\n return;\n }\n\n const current = pending;\n pending = null;\n lastSaveErrored = false;\n controller.persistSnapshot(\n current.snapshot as unknown as Parameters<typeof controller.persistSnapshot>[0]\n );\n if (lastSaveErrored) {\n return;\n }\n\n const timestamp = Date.now();\n autosaveState = {\n status: \"saved\",\n lastSavedAt: timestamp\n };\n resolvedOptions.onSaved?.({\n snapshot: current.snapshot as unknown as JourneySnapshot<TContext, TStepId>,\n reason: current.reason,\n timestamp\n });\n };\n\n const scheduleSave = (\n snapshot: Parameters<typeof controller.persistSnapshot>[0],\n reason: JourneyMachineSnapshotReason\n ) => {\n pending = {\n snapshot: snapshot as unknown as JourneySnapshot<JourneyJsonObject, string>,\n reason\n };\n autosaveState = {\n status: \"pending\",\n ...(autosaveState.lastSavedAt !== undefined\n ? { lastSavedAt: autosaveState.lastSavedAt }\n : {}),\n pendingReason: reason\n };\n\n if (debounceMs === 0) {\n commitPending();\n return;\n }\n\n clearTimer();\n timeoutId = setTimeout(() => {\n commitPending();\n }, debounceMs);\n };\n\n return {\n hydrateSnapshot: (snapshot) =>\n hydrate\n ? (controller.hydrateSnapshot(snapshot as never) as unknown as typeof snapshot)\n : snapshot,\n onSnapshotChange: ({ snapshot, reason }) => {\n if (reason === \"async\") {\n return;\n }\n\n if (reason === \"reset\" && controller.clearOnReset) {\n clearTimer();\n pending = null;\n controller.removePersistedSnapshot();\n autosaveState = { status: \"idle\" };\n return;\n }\n\n if (!saveReasons.has(reason)) {\n return;\n }\n\n scheduleSave(\n snapshot as unknown as Parameters<typeof controller.persistSnapshot>[0],\n reason\n );\n },\n augmentMachine: () => ({\n getAutosaveState: () => ({ ...autosaveState }),\n flushAutosave: async () => {\n commitPending();\n },\n clearAutosave: () => {\n clearTimer();\n pending = null;\n controller.removePersistedSnapshot();\n autosaveState = { status: \"idle\" };\n }\n }),\n dispose: () => {\n clearTimer();\n }\n };\n }) as JourneyMachinePlugin[\"setup\"];\n\n return {\n name: \"autosave\",\n __extension__: undefined as unknown as JourneyAutosaveMachineExtension,\n setup\n } satisfies JourneyMachinePlugin;\n};\n\nexport type { JourneyAutosavePluginOptions, JourneyAutosaveState } from \"../../types\";\n"],
|
|
5
|
+
"mappings": "AA4BO,IAAMA,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,EAAiBL,GAA2B,CAChD,GAAIA,IAAU,KACZ,MAAO,OAGT,GAAI,MAAM,QAAQA,CAAK,EACrB,MAAO,QA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,CAAU,CACf,EAEA,MAAO,CACL,gBAAkBiB,GAChBhB,EACKQ,EAAW,gBAAgBQ,CAAiB,EAC7CA,EACN,iBAAkB,CAAC,CAAE,SAAAA,EAAU,OAAAC,CAAO,IAAM,CAC1C,GAAIA,IAAW,QAIf,IAAIA,IAAW,SAAWT,EAAW,aAAc,CACjDG,EAAW,EACXP,EAAU,KACVI,EAAW,wBAAwB,EACnCN,EAAgB,CAAE,OAAQ,MAAO,EACjC,MACF,CAEKD,EAAY,IAAIgB,CAAM,GAI3BF,EACEC,EACAC,CACF,EACF,EACA,eAAgB,KAAO,CACrB,iBAAkB,KAAO,CAAE,GAAGf,CAAc,GAC5C,cAAe,SAAY,CACzBU,EAAc,CAChB,EACA,cAAe,IAAM,CACnBD,EAAW,EACXP,EAAU,KACVI,EAAW,wBAAwB,EACnCN,EAAgB,CAAE,OAAQ,MAAO,CACnC,CACF,GACA,QAAS,IAAM,CACbS,EAAW,CACb,CACF,CACF,EAMA,CACF",
|
|
6
|
+
"names": ["isPlainObject", "value", "cloneSerializableValue", "entry", "key", "entryValue", "describeValue", "constructorName", "assertSerializableValue", "label", "state", "path", "pathLabel", "index", "assertSerializableContext", "context", "cloneContext", "unique", "items", "normalizeVisited", "visited", "stepIds", "stepId", "buildVisitedFromTimeline", "timeline", "resolvedStepIds", "isDevelopmentEnvironment", "diagnosticGlobal", "nodeEnv", "warnInDevelopment", "message", "detail", "buildIdleStepAsyncState", "buildInitialAsyncState", "steps", "stepId", "buildSnapshot", "timeline", "index", "context", "status", "asyncState", "visited", "safeIndex", "currentStepId", "stepIds", "unique", "cloneContext", "normalizeVisited", "buildVisitedFromTimeline", "cloneSerializableValue", "isRecord", "value", "isStatusValue", "normalizePersistencePath", "path", "optionName", "trimmedPath", "segments", "segment", "normalizePersistencePaths", "paths", "normalized", "resolvedPath", "pathStartsWith", "prefix", "index", "pathHasAncestorMatch", "candidates", "candidate", "pathHasDescendantMatch", "filterContextValue", "allowList", "blockList", "allowAll", "pathIsAllowed", "pathHasAllowedDescendants", "isPlainObject", "changed", "nextValue", "key", "childValue", "result", "mergePersistedValue", "initialValue", "persistedValue", "mergedEntries", "mergePersistedContext", "initialContext", "persistedContext", "resolveDefaultStorage", "localStorageCandidate", "reportPersistenceError", "error", "onError", "warnInDevelopment", "resolvePersistence", "options", "storage", "normalizedAllowList", "normalizedBlockList", "resolveVisitedFromPersistence", "visitedSource", "timeline", "stepIds", "visitedFromTimeline", "buildVisitedFromTimeline", "needsRewrite", "visited", "stepId", "visitedFromArray", "step", "coercePersistedSnapshot", "steps", "fallbackContext", "rawHistory", "rawTimeline", "currentStepIdValue", "rawIndex", "inferredIndex", "status", "visitedNeedsRewrite", "assertSerializableContext", "createPersistenceController", "args", "initial", "context", "persistence", "reportResolvedPersistenceError", "filterPersistedContext", "filtered", "persistSnapshot", "snapshot", "persistedState", "removePersistedSnapshot", "buildBaseSnapshot", "buildSnapshot", "buildInitialAsyncState", "hydrateSnapshot", "baseSnapshot", "resolvedBaseSnapshot", "rawPersisted", "parsed", "persistedVersion", "persistedSnapshot", "shouldRewritePersisted", "coerced", "migrated", "filteredContext", "contextWasFiltered", "hydratedContext", "hydratedSnapshot", "DEFAULT_SAVE_REASONS", "normalizeDebounceMs", "value", "createAutosavePlugin", "options", "debounceMs", "hydrate", "saveReasons", "autosaveState", "timeoutId", "pending", "lastSaveErrored", "resolvedJourney", "resolvedOptions", "controller", "createPersistenceController", "error", "clearTimer", "commitPending", "current", "timestamp", "scheduleSave", "snapshot", "reason"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { JourneyDefinition, JourneyDiagnosticsOptions, JourneyDiagnosticsResult, JourneyFullEventType, JourneyJsonObject } from "../../types";
|
|
2
|
+
/** Analyzes a journey definition for structural diagnostics such as dead ends and cycles. */
|
|
3
|
+
export declare function getJourneyDiagnostics<TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown>, TStepMeta = unknown, THandlers extends Record<string, unknown> = Record<never, never>>(journey: JourneyDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>, options?: JourneyDiagnosticsOptions): JourneyDiagnosticsResult<TStepId, JourneyFullEventType<TEventMap>>;
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { JourneyDefinition, JourneyDiagnosticsOptions, JourneyDiagnosticsResult, JourneyFullEventType, JourneyJsonObject } from "../../types";
|
|
2
|
+
/** Analyzes a journey definition for structural diagnostics such as dead ends and cycles. */
|
|
3
|
+
export declare function getJourneyDiagnostics<TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown>, TStepMeta = unknown, THandlers extends Record<string, unknown> = Record<never, never>>(journey: JourneyDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>, options?: JourneyDiagnosticsOptions): JourneyDiagnosticsResult<TStepId, JourneyFullEventType<TEventMap>>;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var v=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var P=Object.prototype.hasOwnProperty;var H=(n,r)=>{for(var i in r)v(n,i,{get:r[i],enumerable:!0})},N=(n,r,i,a)=>{if(r&&typeof r=="object"||typeof r=="function")for(let c of L(r))!P.call(n,c)&&c!==i&&v(n,c,{get:()=>r[c],enumerable:!(a=j(r,c))||a.enumerable});return n};var V=n=>N(v({},"__esModule",{value:!0}),n);var _={};H(_,{createDiagnosticsPlugin:()=>F,getJourneyDiagnostics:()=>g});module.exports=V(_);var z=n=>typeof n=="number"&&Number.isFinite(n),I=(n,r)=>{if(n!==void 0&&!z(n))throw new Error(`${r} must define a finite numeric "timeoutMs" when provided.`)};var J=n=>n.event==="completeJourney"?"COMPLETE":n.event==="terminateJourney"?"TERMINATED":n.to;var A=n=>{let r=2166136261;for(let i=0;i<n.length;i+=1)r^=n.charCodeAt(i),r=Math.imul(r,16777619);return(r>>>0).toString(16).padStart(8,"0")},C=n=>{let r=new Map,i=new Set;return n.map(a=>{let c=a.event==="completeJourney"?"COMPLETE":a.event==="terminateJourney"?"TERMINATED":String(a.to),o=JSON.stringify({from:a.from,event:a.event,target:c}),y=(r.get(o)??0)+1;r.set(o,y);let u=JSON.stringify({from:a.from,event:a.event,target:c,ordinal:y}),l=0,f=(()=>{let T=A(u);for(;i.has(T);)l+=1,T=A(`${u}:${l}`);return T})();return i.add(f),{...a,id:f,...a.label!==void 0?{label:a.label}:{}}})},D=n=>{let r=[],{transitions:i}=n;if(i===void 0)return{...n,transitions:C(r)};if(Array.isArray(i)){if(i.length===0)throw new Error("Journey linear transitions must include the initial step as the first item.");let[o,...y]=i;if(typeof o!="string")throw new Error("Journey linear transitions at index 0 must be a step id string.");if(!(o in n.steps))throw new Error(`Journey linear transitions reference unknown step "${o}".`);let u=n.initial??o;if(n.initial!==void 0&&!i.map(e=>typeof e=="string"?e:e.step).includes(n.initial))throw new Error(`Journey initial step "${n.initial}" does not exist in linear transitions.`);let l=o,f=new Set([o]);for(let[T,e]of y.entries()){let s=T+1;if(typeof e=="string"){if(!(e in n.steps))throw new Error(`Journey linear transitions reference unknown step "${e}".`);if(f.has(e))throw new Error(`Journey linear transitions contain duplicate step "${e}" at index ${s}.`);f.add(e),r.push({from:l,event:"goToNextStep",to:e}),l=e;continue}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Journey linear transitions at index ${s} must be a step id string or step config object.`);let w=new Set(["step","label","updateContext","onEnter","onLeave","timeoutMs"]);for(let x of Object.keys(e))if(!w.has(x))throw new Error(`Journey linear transition object at index ${s} contains unsupported field "${x}". Allowed fields are "step", "label", "updateContext", "onEnter", "onLeave", and "timeoutMs".`);if(typeof e.step!="string")throw new Error(`Journey linear transition object at index ${s} must define string "step".`);if(!(e.step in n.steps))throw new Error(`Journey linear transitions reference unknown step "${e.step}".`);if(f.has(e.step))throw new Error(`Journey linear transitions contain duplicate step "${e.step}" at index ${s}.`);if(f.add(e.step),e.updateContext!==void 0&&typeof e.updateContext!="function")throw new Error(`Journey linear transition object at index ${s} must define "updateContext" as a function when provided.`);if(e.onEnter!==void 0&&typeof e.onEnter!="function")throw new Error(`Journey linear transition object at index ${s} must define "onEnter" as a function when provided.`);if(e.onLeave!==void 0&&typeof e.onLeave!="function")throw new Error(`Journey linear transition object at index ${s} must define "onLeave" as a function when provided.`);I(e.timeoutMs,`Journey linear transition object at index ${s}`),r.push({...e.label!==void 0?{label:e.label}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},...e.updateContext!==void 0?{updateContext:e.updateContext}:{},...e.onEnter!==void 0?{onEnter:e.onEnter}:{},...e.onLeave!==void 0?{onLeave:e.onLeave}:{},from:l,event:"goToNextStep",to:e.step}),l=e.step}return{...n,initial:u,transitions:C(r)}}if(!i||typeof i!="object")throw new Error("Journey transitions must be an array or an object map when provided.");let a=i,c=[...Object.entries(a).filter(([o])=>o!=="global"),...a.global?[["global",a.global]]:[]];for(let[o,y]of c){if(o!=="global"&&!(o in n.steps))throw new Error(`Journey transitions reference unknown step "${o}".`);if(!y||typeof y!="object"||Array.isArray(y))throw new Error(`Journey transitions for "${o}" must be an event map object.`);for(let[u,l]of Object.entries(y)){let f=u==="completeJourney"||u==="terminateJourney",T=f&&(l===!0||Array.isArray(l)&&l.length===0)?[{}]:l;if(!Array.isArray(T))throw new Error(`Journey transitions for "${o}.${u}" must be an array.`);for(let[e,s]of T.entries()){if(!s||typeof s!="object")throw new Error(`Journey transition at "${o}.${u}[${e}]" must be an object.`);let w=new Set(f?["when","updateContext","onEnter","onLeave","label","timeoutMs"]:["to","when","updateContext","onEnter","onLeave","label","timeoutMs"]);for(let x of Object.keys(s))if(!w.has(x))throw new Error(`Journey transition at "${o}.${u}[${e}]" contains unsupported field "${x}".`);if(!f&&typeof s.to!="string")throw new Error(`Journey transition at "${o}.${u}[${e}]" must define string "to".`);if(s.when!==void 0&&typeof s.when!="function")throw new Error(`Journey transition at "${o}.${u}[${e}]" must define "when" as a function when provided.`);if(s.updateContext!==void 0&&typeof s.updateContext!="function")throw new Error(`Journey transition at "${o}.${u}[${e}]" must define "updateContext" as a function when provided.`);if(s.onEnter!==void 0&&typeof s.onEnter!="function")throw new Error(`Journey transition at "${o}.${u}[${e}]" must define "onEnter" as a function when provided.`);if(s.onLeave!==void 0&&typeof s.onLeave!="function")throw new Error(`Journey transition at "${o}.${u}[${e}]" must define "onLeave" as a function when provided.`);if(s.label!==void 0&&typeof s.label!="string")throw new Error(`Journey transition at "${o}.${u}[${e}]" must define "label" as a string when provided.`);I(s.timeoutMs,`Journey transition at "${o}.${u}[${e}]"`),r.push({...s,from:o==="global"?"*":o,event:u})}}}return{...n,transitions:C(r)}};var G=(n,r)=>`${n}\0${r}`;function g(n,r={}){let i=D(n),a=n.transitions===void 0?"headless":Array.isArray(n.transitions)?"linear":"graph",c=Object.keys(i.steps),o=[],y=r.requireExplicitCompletion??!1;if(a==="headless")return{issues:o,summary:{mode:a,stepCount:c.length,reachableStepCount:c.length>0?1:0,unreachableStepCount:0,deadEndCount:0,cycleCount:0,shadowedTransitionCount:0,graphChecksSkipped:!0,terminalPathExists:!1}};let l=new Set,f=new Map;i.transitions.forEach((t,d)=>{let p=G(t.from,t.event),m=f.get(p);if(m){l.add(d),o.push({code:"shadowed-transition",severity:"warning",from:t.from,eventType:t.event,transitionId:t.id,...t.label!==void 0?{label:t.label}:{},message:m.transitionId===null?`Transition "${t.from}.${t.event}" is shadowed by an earlier unconditional transition.`:`Transition "${t.from}.${t.event}" is shadowed by unconditional transition "${m.transitionId}".`});return}t.when===void 0&&f.set(p,{transitionId:t.id??null})});let T=i.transitions.filter((t,d)=>!l.has(d)),e=t=>a==="linear"&&Array.isArray(n.transitions)&&n.transitions[n.transitions.length-1]!==void 0&&(typeof n.transitions[n.transitions.length-1]=="string"?n.transitions[n.transitions.length-1]:n.transitions[n.transitions.length-1].step)===t&&!y,s=t=>T.filter(d=>d.from==="*"||d.from===t),w=new Set,x=t=>{if(!w.has(t)){w.add(t);for(let d of s(t)){let p=J(d);p==="COMPLETE"||p==="TERMINATED"||x(p)}}};x(i.initial);for(let t of c)w.has(t)||o.push({code:"unreachable-step",severity:"warning",stepId:t,message:`Step "${t}" is unreachable from the initial step "${i.initial}".`});for(let t of w)e(t)||s(t).length>0||o.push({code:"dead-end-step",severity:"error",stepId:t,message:`Step "${t}" is reachable but has no outgoing transitions or terminal exit.`});let M=new Set,$=new Set,h=[],k=t=>{$.add(t),h.push(t);for(let d of s(t)){let p=J(d);if(p==="COMPLETE"||p==="TERMINATED")continue;let m=h.indexOf(p);if(m>=0){let b=[...h.slice(m),p],S=b.join("\0");M.has(S)||(M.add(S),o.push({code:"cycle-detected",severity:"warning",from:d.from,eventType:d.event,transitionId:d.id,...d.label!==void 0?{label:d.label}:{},steps:b,message:`Cycle detected: ${b.join(" -> ")}.`}));continue}$.has(p)||k(p)}h.pop()};k(i.initial);let E=new Map,R=(t,d=new Set)=>{let p=E.get(t);if(p!==void 0)return p;if(e(t))return E.set(t,!0),!0;if(d.has(t))return!1;d.add(t);let m=s(t).some(b=>{let S=J(b);return S==="COMPLETE"||S==="TERMINATED"?!0:R(S,d)});return d.delete(t),E.set(t,m),m},O=R(i.initial);return O||o.push({code:"no-terminal-path",severity:"warning",stepId:i.initial,message:`No terminal path is reachable from the initial step "${i.initial}".`}),{issues:o,summary:{mode:a,stepCount:c.length,reachableStepCount:w.size,unreachableStepCount:c.length-w.size,deadEndCount:o.filter(t=>t.code==="dead-end-step").length,cycleCount:o.filter(t=>t.code==="cycle-detected").length,shadowedTransitionCount:o.filter(t=>t.code==="shadowed-transition").length,graphChecksSkipped:!1,terminalPathExists:O}}}var F=()=>({name:"diagnostics",setup:({journey:n,options:r})=>({augmentMachine:()=>({getDiagnostics:i=>g(n,{requireExplicitCompletion:i?.requireExplicitCompletion??r.requireExplicitCompletion})})})});0&&(module.exports={createDiagnosticsPlugin,getJourneyDiagnostics});
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/plugins/diagnostics/index.ts", "../../../src/journey-machine/helpers.ts", "../../../src/journey-machine/resolve-journey-definition.ts", "../../../src/plugins/diagnostics/diagnostics.ts"],
|
|
4
|
+
"sourcesContent": ["import { getJourneyDiagnostics } from \"./diagnostics\";\n\nimport type {\n JourneyDiagnosticsOptions,\n JourneyDiagnosticsResult,\n JourneyFullEventType,\n JourneyJsonObject,\n JourneyMachine,\n JourneyMachinePlugin\n} from \"../../types\";\n\nexport type JourneyDiagnosticsMachineExtension<\n TStepId extends string,\n TEventType extends string\n> = {\n getDiagnostics: (\n options?: JourneyDiagnosticsOptions\n ) => JourneyDiagnosticsResult<TStepId, TEventType>;\n};\n\nexport type JourneyDiagnosticsMachine<\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> = JourneyMachine<TContext, TStepId, TEventMap, TStepMeta, THandlers> &\n JourneyDiagnosticsMachineExtension<TStepId, JourneyFullEventType<TEventMap>>;\n\n/** Creates a plugin that augments a machine with structural diagnostics helpers. */\nexport const createDiagnosticsPlugin = () =>\n ({\n name: \"diagnostics\",\n setup: ({ journey, options }) => ({\n augmentMachine: () => ({\n getDiagnostics: (diagnosticsOptions?: JourneyDiagnosticsOptions) =>\n getJourneyDiagnostics(journey, {\n requireExplicitCompletion:\n diagnosticsOptions?.requireExplicitCompletion ?? options.requireExplicitCompletion\n })\n })\n })\n }) satisfies JourneyMachinePlugin;\n\nexport { getJourneyDiagnostics } from \"./diagnostics\";\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 { 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", "/* eslint-disable no-redeclare */\nimport { resolveTransitionTarget } from \"../../journey-machine/helpers\";\nimport { resolveJourneyDefinition } from \"../../journey-machine/resolve-journey-definition\";\n\nimport type {\n JourneyDefinition,\n JourneyDiagnosticsIssue,\n JourneyDiagnosticsOptions,\n JourneyDiagnosticsResult,\n JourneyFullEventType,\n JourneyJsonObject,\n JourneyMode\n} from \"../../types\";\n\nconst buildShadowKey = (from: string, event: string) => `${from}\\u0000${event}`;\n\n/** Analyzes a journey definition for structural diagnostics such as dead ends and cycles. */\nexport function getJourneyDiagnostics<\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 options?: JourneyDiagnosticsOptions\n): JourneyDiagnosticsResult<TStepId, JourneyFullEventType<TEventMap>>;\nexport function getJourneyDiagnostics<\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 options: JourneyDiagnosticsOptions = {}\n): JourneyDiagnosticsResult<TStepId, JourneyFullEventType<TEventMap>> {\n type TEventType = JourneyFullEventType<TEventMap>;\n const resolvedJourney = resolveJourneyDefinition(journey);\n const mode: JourneyMode =\n journey.transitions === undefined\n ? \"headless\"\n : Array.isArray(journey.transitions)\n ? \"linear\"\n : \"graph\";\n const stepIds = Object.keys(resolvedJourney.steps) as TStepId[];\n const issues: JourneyDiagnosticsIssue<TStepId, TEventType>[] = [];\n const requireExplicitCompletion = options.requireExplicitCompletion ?? false;\n const graphChecksSkipped = mode === \"headless\";\n\n if (graphChecksSkipped) {\n return {\n issues,\n summary: {\n mode,\n stepCount: stepIds.length,\n reachableStepCount: stepIds.length > 0 ? 1 : 0,\n unreachableStepCount: 0,\n deadEndCount: 0,\n cycleCount: 0,\n shadowedTransitionCount: 0,\n graphChecksSkipped: true,\n terminalPathExists: false\n }\n };\n }\n\n const shadowedTransitionIndexes = new Set<number>();\n const unconditionalTransitionByKey = new Map<string, { transitionId: string | null }>();\n\n resolvedJourney.transitions.forEach((transition, index) => {\n const key = buildShadowKey(transition.from, transition.event);\n const blocker = unconditionalTransitionByKey.get(key);\n\n if (blocker) {\n shadowedTransitionIndexes.add(index);\n issues.push({\n code: \"shadowed-transition\",\n severity: \"warning\",\n from: transition.from,\n eventType: transition.event as TEventType,\n transitionId: transition.id,\n ...(transition.label !== undefined ? { label: transition.label } : {}),\n message:\n blocker.transitionId === null\n ? `Transition \"${transition.from}.${transition.event}\" is shadowed by an earlier unconditional transition.`\n : `Transition \"${transition.from}.${transition.event}\" is shadowed by unconditional transition \"${blocker.transitionId}\".`\n });\n return;\n }\n\n if (transition.when === undefined) {\n unconditionalTransitionByKey.set(key, {\n transitionId: transition.id ?? null\n });\n }\n });\n\n const activeTransitions = resolvedJourney.transitions.filter(\n (_, index) => !shadowedTransitionIndexes.has(index)\n );\n const isImplicitlyTerminalStep = (stepId: TStepId) =>\n mode === \"linear\" &&\n Array.isArray(journey.transitions) &&\n journey.transitions[journey.transitions.length - 1] !== undefined &&\n (typeof journey.transitions[journey.transitions.length - 1] === \"string\"\n ? journey.transitions[journey.transitions.length - 1]\n : journey.transitions[journey.transitions.length - 1].step) === stepId &&\n !requireExplicitCompletion;\n\n const getOutgoingTransitions = (stepId: TStepId) =>\n activeTransitions.filter((transition) => transition.from === \"*\" || transition.from === stepId);\n\n const reachable = new Set<TStepId>();\n const markReachable = (stepId: TStepId) => {\n if (reachable.has(stepId)) {\n return;\n }\n\n reachable.add(stepId);\n for (const transition of getOutgoingTransitions(stepId)) {\n const target = resolveTransitionTarget(transition);\n if (target === \"COMPLETE\" || target === \"TERMINATED\") {\n continue;\n }\n markReachable(target);\n }\n };\n markReachable(resolvedJourney.initial);\n\n for (const stepId of stepIds) {\n if (reachable.has(stepId)) {\n continue;\n }\n\n issues.push({\n code: \"unreachable-step\",\n severity: \"warning\",\n stepId,\n message: `Step \"${stepId}\" is unreachable from the initial step \"${resolvedJourney.initial}\".`\n });\n }\n\n for (const stepId of reachable) {\n if (isImplicitlyTerminalStep(stepId)) {\n continue;\n }\n\n if (getOutgoingTransitions(stepId).length > 0) {\n continue;\n }\n\n issues.push({\n code: \"dead-end-step\",\n severity: \"error\",\n stepId,\n message: `Step \"${stepId}\" is reachable but has no outgoing transitions or terminal exit.`\n });\n }\n\n const cycleKeys = new Set<string>();\n const visitedForCycles = new Set<TStepId>();\n const stack: TStepId[] = [];\n\n const walkCycles = (stepId: TStepId) => {\n visitedForCycles.add(stepId);\n stack.push(stepId);\n\n for (const transition of getOutgoingTransitions(stepId)) {\n const target = resolveTransitionTarget(transition);\n if (target === \"COMPLETE\" || target === \"TERMINATED\") {\n continue;\n }\n\n const stackIndex = stack.indexOf(target);\n if (stackIndex >= 0) {\n const cycleSteps = [...stack.slice(stackIndex), target];\n const cycleKey = cycleSteps.join(\"\\u0000\");\n if (!cycleKeys.has(cycleKey)) {\n cycleKeys.add(cycleKey);\n issues.push({\n code: \"cycle-detected\",\n severity: \"warning\",\n from: transition.from,\n eventType: transition.event as TEventType,\n transitionId: transition.id,\n ...(transition.label !== undefined ? { label: transition.label } : {}),\n steps: cycleSteps,\n message: `Cycle detected: ${cycleSteps.join(\" -> \")}.`\n });\n }\n continue;\n }\n\n if (!visitedForCycles.has(target)) {\n walkCycles(target);\n }\n }\n\n stack.pop();\n };\n\n walkCycles(resolvedJourney.initial);\n\n const terminalMemo = new Map<TStepId, boolean>();\n const canReachTerminal = (stepId: TStepId, pending = new Set<TStepId>()): boolean => {\n const memoized = terminalMemo.get(stepId);\n if (memoized !== undefined) {\n return memoized;\n }\n\n if (isImplicitlyTerminalStep(stepId)) {\n terminalMemo.set(stepId, true);\n return true;\n }\n\n if (pending.has(stepId)) {\n return false;\n }\n\n pending.add(stepId);\n const terminalReachable = getOutgoingTransitions(stepId).some((transition) => {\n const target = resolveTransitionTarget(transition);\n if (target === \"COMPLETE\" || target === \"TERMINATED\") {\n return true;\n }\n return canReachTerminal(target, pending);\n });\n pending.delete(stepId);\n terminalMemo.set(stepId, terminalReachable);\n return terminalReachable;\n };\n\n const terminalPathExists = canReachTerminal(resolvedJourney.initial);\n if (!terminalPathExists) {\n issues.push({\n code: \"no-terminal-path\",\n severity: \"warning\",\n stepId: resolvedJourney.initial,\n message: `No terminal path is reachable from the initial step \"${resolvedJourney.initial}\".`\n });\n }\n\n return {\n issues,\n summary: {\n mode,\n stepCount: stepIds.length,\n reachableStepCount: reachable.size,\n unreachableStepCount: stepIds.length - reachable.size,\n deadEndCount: issues.filter((issue) => issue.code === \"dead-end-step\").length,\n cycleCount: issues.filter((issue) => issue.code === \"cycle-detected\").length,\n shadowedTransitionCount: issues.filter((issue) => issue.code === \"shadowed-transition\")\n .length,\n graphChecksSkipped: false,\n terminalPathExists\n }\n };\n}\n/* eslint-enable no-redeclare */\n"],
|
|
5
|
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B,IAAMiB,EAAoBhB,EAAuBD,CAAM,EAAE,KAAMP,GAAe,CAC5E,IAAMW,EAASC,EAAwBZ,CAAU,EACjD,OAAIW,IAAW,YAAcA,IAAW,aAC/B,GAEFU,EAAiBV,EAAQW,CAAO,CACzC,CAAC,EACD,OAAAA,EAAQ,OAAOf,CAAM,EACrBa,EAAa,IAAIb,EAAQiB,CAAiB,EACnCA,CACT,EAEMC,EAAqBJ,EAAiB7B,EAAgB,OAAO,EACnE,OAAKiC,GACH7B,EAAO,KAAK,CACV,KAAM,mBACN,SAAU,UACV,OAAQJ,EAAgB,QACxB,QAAS,wDAAwDA,EAAgB,OAAO,IAC1F,CAAC,EAGI,CACL,OAAAI,EACA,QAAS,CACP,KAAAF,EACA,UAAWC,EAAQ,OACnB,mBAAoBc,EAAU,KAC9B,qBAAsBd,EAAQ,OAASc,EAAU,KACjD,aAAcb,EAAO,OAAQ8B,GAAUA,EAAM,OAAS,eAAe,EAAE,OACvE,WAAY9B,EAAO,OAAQ8B,GAAUA,EAAM,OAAS,gBAAgB,EAAE,OACtE,wBAAyB9B,EAAO,OAAQ8B,GAAUA,EAAM,OAAS,qBAAqB,EACnF,OACH,mBAAoB,GACpB,mBAAAD,CACF,CACF,CACF,CHpOO,IAAME,EAA0B,KACpC,CACC,KAAM,cACN,MAAO,CAAC,CAAE,QAAAC,EAAS,QAAAC,CAAQ,KAAO,CAChC,eAAgB,KAAO,CACrB,eAAiBC,GACfC,EAAsBH,EAAS,CAC7B,0BACEE,GAAoB,2BAA6BD,EAAQ,yBAC7D,CAAC,CACL,EACF,EACF",
|
|
6
|
+
"names": ["diagnostics_exports", "__export", "createDiagnosticsPlugin", "getJourneyDiagnostics", "__toCommonJS", "isFiniteNumber", "value", "validateFiniteTimeout", "timeoutMs", "label", "resolveTransitionTarget", "transition", "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", "buildShadowKey", "from", "event", "getJourneyDiagnostics", "journey", "options", "resolvedJourney", "resolveJourneyDefinition", "mode", "stepIds", "issues", "requireExplicitCompletion", "shadowedTransitionIndexes", "unconditionalTransitionByKey", "transition", "index", "key", "blocker", "activeTransitions", "_", "isImplicitlyTerminalStep", "stepId", "getOutgoingTransitions", "reachable", "markReachable", "target", "resolveTransitionTarget", "cycleKeys", "visitedForCycles", "stack", "walkCycles", "stackIndex", "cycleSteps", "cycleKey", "terminalMemo", "canReachTerminal", "pending", "memoized", "terminalReachable", "terminalPathExists", "issue", "createDiagnosticsPlugin", "journey", "options", "diagnosticsOptions", "getJourneyDiagnostics"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { JourneyDiagnosticsOptions, JourneyDiagnosticsResult, JourneyFullEventType, JourneyJsonObject, JourneyMachine } from "../../types";
|
|
2
|
+
export type JourneyDiagnosticsMachineExtension<TStepId extends string, TEventType extends string> = {
|
|
3
|
+
getDiagnostics: (options?: JourneyDiagnosticsOptions) => JourneyDiagnosticsResult<TStepId, TEventType>;
|
|
4
|
+
};
|
|
5
|
+
export type JourneyDiagnosticsMachine<TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown> = Record<never, never>, TStepMeta = unknown, THandlers extends Record<string, unknown> = Record<never, never>> = JourneyMachine<TContext, TStepId, TEventMap, TStepMeta, THandlers> & JourneyDiagnosticsMachineExtension<TStepId, JourneyFullEventType<TEventMap>>;
|
|
6
|
+
/** Creates a plugin that augments a machine with structural diagnostics helpers. */
|
|
7
|
+
export declare const createDiagnosticsPlugin: () => {
|
|
8
|
+
name: string;
|
|
9
|
+
setup: <TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown> = Record<never, never>, TStepMeta = unknown, THandlers extends Record<string, unknown> = Record<never, never>>({ journey, options }: import("../../types").JourneyMachinePluginSetupContext<TContext, TStepId, TEventMap, TStepMeta, THandlers>) => {
|
|
10
|
+
augmentMachine: () => {
|
|
11
|
+
getDiagnostics: (diagnosticsOptions?: JourneyDiagnosticsOptions) => JourneyDiagnosticsResult<TStepId, JourneyFullEventType<TEventMap>>;
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
export { getJourneyDiagnostics } from "./diagnostics";
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { JourneyDiagnosticsOptions, JourneyDiagnosticsResult, JourneyFullEventType, JourneyJsonObject, JourneyMachine } from "../../types";
|
|
2
|
+
export type JourneyDiagnosticsMachineExtension<TStepId extends string, TEventType extends string> = {
|
|
3
|
+
getDiagnostics: (options?: JourneyDiagnosticsOptions) => JourneyDiagnosticsResult<TStepId, TEventType>;
|
|
4
|
+
};
|
|
5
|
+
export type JourneyDiagnosticsMachine<TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown> = Record<never, never>, TStepMeta = unknown, THandlers extends Record<string, unknown> = Record<never, never>> = JourneyMachine<TContext, TStepId, TEventMap, TStepMeta, THandlers> & JourneyDiagnosticsMachineExtension<TStepId, JourneyFullEventType<TEventMap>>;
|
|
6
|
+
/** Creates a plugin that augments a machine with structural diagnostics helpers. */
|
|
7
|
+
export declare const createDiagnosticsPlugin: () => {
|
|
8
|
+
name: string;
|
|
9
|
+
setup: <TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown> = Record<never, never>, TStepMeta = unknown, THandlers extends Record<string, unknown> = Record<never, never>>({ journey, options }: import("../../types").JourneyMachinePluginSetupContext<TContext, TStepId, TEventMap, TStepMeta, THandlers>) => {
|
|
10
|
+
augmentMachine: () => {
|
|
11
|
+
getDiagnostics: (diagnosticsOptions?: JourneyDiagnosticsOptions) => JourneyDiagnosticsResult<TStepId, JourneyFullEventType<TEventMap>>;
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
export { getJourneyDiagnostics } from "./diagnostics";
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var D=t=>typeof t=="number"&&Number.isFinite(t),E=(t,s)=>{if(t!==void 0&&!D(t))throw new Error(`${s} must define a finite numeric "timeoutMs" when provided.`)};var J=t=>t.event==="completeJourney"?"COMPLETE":t.event==="terminateJourney"?"TERMINATED":t.to;var O=t=>{let s=2166136261;for(let i=0;i<t.length;i+=1)s^=t.charCodeAt(i),s=Math.imul(s,16777619);return(s>>>0).toString(16).padStart(8,"0")},v=t=>{let s=new Map,i=new Set;return t.map(d=>{let T=d.event==="completeJourney"?"COMPLETE":d.event==="terminateJourney"?"TERMINATED":String(d.to),o=JSON.stringify({from:d.from,event:d.event,target:T}),f=(s.get(o)??0)+1;s.set(o,f);let u=JSON.stringify({from:d.from,event:d.event,target:T,ordinal:f}),p=0,l=(()=>{let y=O(u);for(;i.has(y);)p+=1,y=O(`${u}:${p}`);return y})();return i.add(l),{...d,id:l,...d.label!==void 0?{label:d.label}:{}}})},A=t=>{let s=[],{transitions:i}=t;if(i===void 0)return{...t,transitions:v(s)};if(Array.isArray(i)){if(i.length===0)throw new Error("Journey linear transitions must include the initial step as the first item.");let[o,...f]=i;if(typeof o!="string")throw new Error("Journey linear transitions at index 0 must be a step id string.");if(!(o in t.steps))throw new Error(`Journey linear transitions reference unknown step "${o}".`);let u=t.initial??o;if(t.initial!==void 0&&!i.map(e=>typeof e=="string"?e:e.step).includes(t.initial))throw new Error(`Journey initial step "${t.initial}" does not exist in linear transitions.`);let p=o,l=new Set([o]);for(let[y,e]of f.entries()){let r=y+1;if(typeof e=="string"){if(!(e in t.steps))throw new Error(`Journey linear transitions reference unknown step "${e}".`);if(l.has(e))throw new Error(`Journey linear transitions contain duplicate step "${e}" at index ${r}.`);l.add(e),s.push({from:p,event:"goToNextStep",to:e}),p=e;continue}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Journey linear transitions at index ${r} must be a step id string or step config object.`);let w=new Set(["step","label","updateContext","onEnter","onLeave","timeoutMs"]);for(let x of Object.keys(e))if(!w.has(x))throw new Error(`Journey linear transition object at index ${r} contains unsupported field "${x}". Allowed fields are "step", "label", "updateContext", "onEnter", "onLeave", and "timeoutMs".`);if(typeof e.step!="string")throw new Error(`Journey linear transition object at index ${r} must define string "step".`);if(!(e.step in t.steps))throw new Error(`Journey linear transitions reference unknown step "${e.step}".`);if(l.has(e.step))throw new Error(`Journey linear transitions contain duplicate step "${e.step}" at index ${r}.`);if(l.add(e.step),e.updateContext!==void 0&&typeof e.updateContext!="function")throw new Error(`Journey linear transition object at index ${r} must define "updateContext" as a function when provided.`);if(e.onEnter!==void 0&&typeof e.onEnter!="function")throw new Error(`Journey linear transition object at index ${r} must define "onEnter" as a function when provided.`);if(e.onLeave!==void 0&&typeof e.onLeave!="function")throw new Error(`Journey linear transition object at index ${r} must define "onLeave" as a function when provided.`);E(e.timeoutMs,`Journey linear transition object at index ${r}`),s.push({...e.label!==void 0?{label:e.label}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},...e.updateContext!==void 0?{updateContext:e.updateContext}:{},...e.onEnter!==void 0?{onEnter:e.onEnter}:{},...e.onLeave!==void 0?{onLeave:e.onLeave}:{},from:p,event:"goToNextStep",to:e.step}),p=e.step}return{...t,initial:u,transitions:v(s)}}if(!i||typeof i!="object")throw new Error("Journey transitions must be an array or an object map when provided.");let d=i,T=[...Object.entries(d).filter(([o])=>o!=="global"),...d.global?[["global",d.global]]:[]];for(let[o,f]of T){if(o!=="global"&&!(o in t.steps))throw new Error(`Journey transitions reference unknown step "${o}".`);if(!f||typeof f!="object"||Array.isArray(f))throw new Error(`Journey transitions for "${o}" must be an event map object.`);for(let[u,p]of Object.entries(f)){let l=u==="completeJourney"||u==="terminateJourney",y=l&&(p===!0||Array.isArray(p)&&p.length===0)?[{}]:p;if(!Array.isArray(y))throw new Error(`Journey transitions for "${o}.${u}" must be an array.`);for(let[e,r]of y.entries()){if(!r||typeof r!="object")throw new Error(`Journey transition at "${o}.${u}[${e}]" must be an object.`);let w=new Set(l?["when","updateContext","onEnter","onLeave","label","timeoutMs"]:["to","when","updateContext","onEnter","onLeave","label","timeoutMs"]);for(let x of Object.keys(r))if(!w.has(x))throw new Error(`Journey transition at "${o}.${u}[${e}]" contains unsupported field "${x}".`);if(!l&&typeof r.to!="string")throw new Error(`Journey transition at "${o}.${u}[${e}]" must define string "to".`);if(r.when!==void 0&&typeof r.when!="function")throw new Error(`Journey transition at "${o}.${u}[${e}]" must define "when" as a function when provided.`);if(r.updateContext!==void 0&&typeof r.updateContext!="function")throw new Error(`Journey transition at "${o}.${u}[${e}]" must define "updateContext" as a function when provided.`);if(r.onEnter!==void 0&&typeof r.onEnter!="function")throw new Error(`Journey transition at "${o}.${u}[${e}]" must define "onEnter" as a function when provided.`);if(r.onLeave!==void 0&&typeof r.onLeave!="function")throw new Error(`Journey transition at "${o}.${u}[${e}]" must define "onLeave" as a function when provided.`);if(r.label!==void 0&&typeof r.label!="string")throw new Error(`Journey transition at "${o}.${u}[${e}]" must define "label" as a string when provided.`);E(r.timeoutMs,`Journey transition at "${o}.${u}[${e}]"`),s.push({...r,from:o==="global"?"*":o,event:u})}}}return{...t,transitions:v(s)}};var j=(t,s)=>`${t}\0${s}`;function I(t,s={}){let i=A(t),d=t.transitions===void 0?"headless":Array.isArray(t.transitions)?"linear":"graph",T=Object.keys(i.steps),o=[],f=s.requireExplicitCompletion??!1;if(d==="headless")return{issues:o,summary:{mode:d,stepCount:T.length,reachableStepCount:T.length>0?1:0,unreachableStepCount:0,deadEndCount:0,cycleCount:0,shadowedTransitionCount:0,graphChecksSkipped:!0,terminalPathExists:!1}};let p=new Set,l=new Map;i.transitions.forEach((n,a)=>{let c=j(n.from,n.event),m=l.get(c);if(m){p.add(a),o.push({code:"shadowed-transition",severity:"warning",from:n.from,eventType:n.event,transitionId:n.id,...n.label!==void 0?{label:n.label}:{},message:m.transitionId===null?`Transition "${n.from}.${n.event}" is shadowed by an earlier unconditional transition.`:`Transition "${n.from}.${n.event}" is shadowed by unconditional transition "${m.transitionId}".`});return}n.when===void 0&&l.set(c,{transitionId:n.id??null})});let y=i.transitions.filter((n,a)=>!p.has(a)),e=n=>d==="linear"&&Array.isArray(t.transitions)&&t.transitions[t.transitions.length-1]!==void 0&&(typeof t.transitions[t.transitions.length-1]=="string"?t.transitions[t.transitions.length-1]:t.transitions[t.transitions.length-1].step)===n&&!f,r=n=>y.filter(a=>a.from==="*"||a.from===n),w=new Set,x=n=>{if(!w.has(n)){w.add(n);for(let a of r(n)){let c=J(a);c==="COMPLETE"||c==="TERMINATED"||x(c)}}};x(i.initial);for(let n of T)w.has(n)||o.push({code:"unreachable-step",severity:"warning",stepId:n,message:`Step "${n}" is unreachable from the initial step "${i.initial}".`});for(let n of w)e(n)||r(n).length>0||o.push({code:"dead-end-step",severity:"error",stepId:n,message:`Step "${n}" is reachable but has no outgoing transitions or terminal exit.`});let C=new Set,M=new Set,h=[],$=n=>{M.add(n),h.push(n);for(let a of r(n)){let c=J(a);if(c==="COMPLETE"||c==="TERMINATED")continue;let m=h.indexOf(c);if(m>=0){let b=[...h.slice(m),c],S=b.join("\0");C.has(S)||(C.add(S),o.push({code:"cycle-detected",severity:"warning",from:a.from,eventType:a.event,transitionId:a.id,...a.label!==void 0?{label:a.label}:{},steps:b,message:`Cycle detected: ${b.join(" -> ")}.`}));continue}M.has(c)||$(c)}h.pop()};$(i.initial);let g=new Map,k=(n,a=new Set)=>{let c=g.get(n);if(c!==void 0)return c;if(e(n))return g.set(n,!0),!0;if(a.has(n))return!1;a.add(n);let m=r(n).some(b=>{let S=J(b);return S==="COMPLETE"||S==="TERMINATED"?!0:k(S,a)});return a.delete(n),g.set(n,m),m},R=k(i.initial);return R||o.push({code:"no-terminal-path",severity:"warning",stepId:i.initial,message:`No terminal path is reachable from the initial step "${i.initial}".`}),{issues:o,summary:{mode:d,stepCount:T.length,reachableStepCount:w.size,unreachableStepCount:T.length-w.size,deadEndCount:o.filter(n=>n.code==="dead-end-step").length,cycleCount:o.filter(n=>n.code==="cycle-detected").length,shadowedTransitionCount:o.filter(n=>n.code==="shadowed-transition").length,graphChecksSkipped:!1,terminalPathExists:R}}}var F=()=>({name:"diagnostics",setup:({journey:t,options:s})=>({augmentMachine:()=>({getDiagnostics:i=>I(t,{requireExplicitCompletion:i?.requireExplicitCompletion??s.requireExplicitCompletion})})})});export{F as createDiagnosticsPlugin,I as getJourneyDiagnostics};
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/journey-machine/helpers.ts", "../../../src/journey-machine/resolve-journey-definition.ts", "../../../src/plugins/diagnostics/diagnostics.ts", "../../../src/plugins/diagnostics/index.ts"],
|
|
4
|
+
"sourcesContent": ["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 { 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", "/* eslint-disable no-redeclare */\nimport { resolveTransitionTarget } from \"../../journey-machine/helpers\";\nimport { resolveJourneyDefinition } from \"../../journey-machine/resolve-journey-definition\";\n\nimport type {\n JourneyDefinition,\n JourneyDiagnosticsIssue,\n JourneyDiagnosticsOptions,\n JourneyDiagnosticsResult,\n JourneyFullEventType,\n JourneyJsonObject,\n JourneyMode\n} from \"../../types\";\n\nconst buildShadowKey = (from: string, event: string) => `${from}\\u0000${event}`;\n\n/** Analyzes a journey definition for structural diagnostics such as dead ends and cycles. */\nexport function getJourneyDiagnostics<\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 options?: JourneyDiagnosticsOptions\n): JourneyDiagnosticsResult<TStepId, JourneyFullEventType<TEventMap>>;\nexport function getJourneyDiagnostics<\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 options: JourneyDiagnosticsOptions = {}\n): JourneyDiagnosticsResult<TStepId, JourneyFullEventType<TEventMap>> {\n type TEventType = JourneyFullEventType<TEventMap>;\n const resolvedJourney = resolveJourneyDefinition(journey);\n const mode: JourneyMode =\n journey.transitions === undefined\n ? \"headless\"\n : Array.isArray(journey.transitions)\n ? \"linear\"\n : \"graph\";\n const stepIds = Object.keys(resolvedJourney.steps) as TStepId[];\n const issues: JourneyDiagnosticsIssue<TStepId, TEventType>[] = [];\n const requireExplicitCompletion = options.requireExplicitCompletion ?? false;\n const graphChecksSkipped = mode === \"headless\";\n\n if (graphChecksSkipped) {\n return {\n issues,\n summary: {\n mode,\n stepCount: stepIds.length,\n reachableStepCount: stepIds.length > 0 ? 1 : 0,\n unreachableStepCount: 0,\n deadEndCount: 0,\n cycleCount: 0,\n shadowedTransitionCount: 0,\n graphChecksSkipped: true,\n terminalPathExists: false\n }\n };\n }\n\n const shadowedTransitionIndexes = new Set<number>();\n const unconditionalTransitionByKey = new Map<string, { transitionId: string | null }>();\n\n resolvedJourney.transitions.forEach((transition, index) => {\n const key = buildShadowKey(transition.from, transition.event);\n const blocker = unconditionalTransitionByKey.get(key);\n\n if (blocker) {\n shadowedTransitionIndexes.add(index);\n issues.push({\n code: \"shadowed-transition\",\n severity: \"warning\",\n from: transition.from,\n eventType: transition.event as TEventType,\n transitionId: transition.id,\n ...(transition.label !== undefined ? { label: transition.label } : {}),\n message:\n blocker.transitionId === null\n ? `Transition \"${transition.from}.${transition.event}\" is shadowed by an earlier unconditional transition.`\n : `Transition \"${transition.from}.${transition.event}\" is shadowed by unconditional transition \"${blocker.transitionId}\".`\n });\n return;\n }\n\n if (transition.when === undefined) {\n unconditionalTransitionByKey.set(key, {\n transitionId: transition.id ?? null\n });\n }\n });\n\n const activeTransitions = resolvedJourney.transitions.filter(\n (_, index) => !shadowedTransitionIndexes.has(index)\n );\n const isImplicitlyTerminalStep = (stepId: TStepId) =>\n mode === \"linear\" &&\n Array.isArray(journey.transitions) &&\n journey.transitions[journey.transitions.length - 1] !== undefined &&\n (typeof journey.transitions[journey.transitions.length - 1] === \"string\"\n ? journey.transitions[journey.transitions.length - 1]\n : journey.transitions[journey.transitions.length - 1].step) === stepId &&\n !requireExplicitCompletion;\n\n const getOutgoingTransitions = (stepId: TStepId) =>\n activeTransitions.filter((transition) => transition.from === \"*\" || transition.from === stepId);\n\n const reachable = new Set<TStepId>();\n const markReachable = (stepId: TStepId) => {\n if (reachable.has(stepId)) {\n return;\n }\n\n reachable.add(stepId);\n for (const transition of getOutgoingTransitions(stepId)) {\n const target = resolveTransitionTarget(transition);\n if (target === \"COMPLETE\" || target === \"TERMINATED\") {\n continue;\n }\n markReachable(target);\n }\n };\n markReachable(resolvedJourney.initial);\n\n for (const stepId of stepIds) {\n if (reachable.has(stepId)) {\n continue;\n }\n\n issues.push({\n code: \"unreachable-step\",\n severity: \"warning\",\n stepId,\n message: `Step \"${stepId}\" is unreachable from the initial step \"${resolvedJourney.initial}\".`\n });\n }\n\n for (const stepId of reachable) {\n if (isImplicitlyTerminalStep(stepId)) {\n continue;\n }\n\n if (getOutgoingTransitions(stepId).length > 0) {\n continue;\n }\n\n issues.push({\n code: \"dead-end-step\",\n severity: \"error\",\n stepId,\n message: `Step \"${stepId}\" is reachable but has no outgoing transitions or terminal exit.`\n });\n }\n\n const cycleKeys = new Set<string>();\n const visitedForCycles = new Set<TStepId>();\n const stack: TStepId[] = [];\n\n const walkCycles = (stepId: TStepId) => {\n visitedForCycles.add(stepId);\n stack.push(stepId);\n\n for (const transition of getOutgoingTransitions(stepId)) {\n const target = resolveTransitionTarget(transition);\n if (target === \"COMPLETE\" || target === \"TERMINATED\") {\n continue;\n }\n\n const stackIndex = stack.indexOf(target);\n if (stackIndex >= 0) {\n const cycleSteps = [...stack.slice(stackIndex), target];\n const cycleKey = cycleSteps.join(\"\\u0000\");\n if (!cycleKeys.has(cycleKey)) {\n cycleKeys.add(cycleKey);\n issues.push({\n code: \"cycle-detected\",\n severity: \"warning\",\n from: transition.from,\n eventType: transition.event as TEventType,\n transitionId: transition.id,\n ...(transition.label !== undefined ? { label: transition.label } : {}),\n steps: cycleSteps,\n message: `Cycle detected: ${cycleSteps.join(\" -> \")}.`\n });\n }\n continue;\n }\n\n if (!visitedForCycles.has(target)) {\n walkCycles(target);\n }\n }\n\n stack.pop();\n };\n\n walkCycles(resolvedJourney.initial);\n\n const terminalMemo = new Map<TStepId, boolean>();\n const canReachTerminal = (stepId: TStepId, pending = new Set<TStepId>()): boolean => {\n const memoized = terminalMemo.get(stepId);\n if (memoized !== undefined) {\n return memoized;\n }\n\n if (isImplicitlyTerminalStep(stepId)) {\n terminalMemo.set(stepId, true);\n return true;\n }\n\n if (pending.has(stepId)) {\n return false;\n }\n\n pending.add(stepId);\n const terminalReachable = getOutgoingTransitions(stepId).some((transition) => {\n const target = resolveTransitionTarget(transition);\n if (target === \"COMPLETE\" || target === \"TERMINATED\") {\n return true;\n }\n return canReachTerminal(target, pending);\n });\n pending.delete(stepId);\n terminalMemo.set(stepId, terminalReachable);\n return terminalReachable;\n };\n\n const terminalPathExists = canReachTerminal(resolvedJourney.initial);\n if (!terminalPathExists) {\n issues.push({\n code: \"no-terminal-path\",\n severity: \"warning\",\n stepId: resolvedJourney.initial,\n message: `No terminal path is reachable from the initial step \"${resolvedJourney.initial}\".`\n });\n }\n\n return {\n issues,\n summary: {\n mode,\n stepCount: stepIds.length,\n reachableStepCount: reachable.size,\n unreachableStepCount: stepIds.length - reachable.size,\n deadEndCount: issues.filter((issue) => issue.code === \"dead-end-step\").length,\n cycleCount: issues.filter((issue) => issue.code === \"cycle-detected\").length,\n shadowedTransitionCount: issues.filter((issue) => issue.code === \"shadowed-transition\")\n .length,\n graphChecksSkipped: false,\n terminalPathExists\n }\n };\n}\n/* eslint-enable no-redeclare */\n", "import { getJourneyDiagnostics } from \"./diagnostics\";\n\nimport type {\n JourneyDiagnosticsOptions,\n JourneyDiagnosticsResult,\n JourneyFullEventType,\n JourneyJsonObject,\n JourneyMachine,\n JourneyMachinePlugin\n} from \"../../types\";\n\nexport type JourneyDiagnosticsMachineExtension<\n TStepId extends string,\n TEventType extends string\n> = {\n getDiagnostics: (\n options?: JourneyDiagnosticsOptions\n ) => JourneyDiagnosticsResult<TStepId, TEventType>;\n};\n\nexport type JourneyDiagnosticsMachine<\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> = JourneyMachine<TContext, TStepId, TEventMap, TStepMeta, THandlers> &\n JourneyDiagnosticsMachineExtension<TStepId, JourneyFullEventType<TEventMap>>;\n\n/** Creates a plugin that augments a machine with structural diagnostics helpers. */\nexport const createDiagnosticsPlugin = () =>\n ({\n name: \"diagnostics\",\n setup: ({ journey, options }) => ({\n augmentMachine: () => ({\n getDiagnostics: (diagnosticsOptions?: JourneyDiagnosticsOptions) =>\n getJourneyDiagnostics(journey, {\n requireExplicitCompletion:\n diagnosticsOptions?.requireExplicitCompletion ?? options.requireExplicitCompletion\n })\n })\n })\n }) satisfies JourneyMachinePlugin;\n\nexport { getJourneyDiagnostics } from \"./diagnostics\";\n"],
|
|
5
|
+
"mappings": "AAsQA,IAAMA,EAAkBC,GACtB,OAAOA,GAAU,UAAY,OAAO,SAASA,CAAK,EAEvCC,EAAwB,CAACC,EAAoBC,IAAkB,CAC1E,GAAID,IAAc,QAAa,CAACH,EAAeG,CAAS,EACtD,MAAM,IAAI,MAAM,GAAGC,CAAK,0DAA0D,CAEtF,EAwJO,IAAMC,EAMXC,GAEAA,EAAW,QAAU,kBACjB,WACAA,EAAW,QAAU,mBACnB,aACCA,EAAW,GCtapB,IAAMC,EAA4BC,GAAkB,CAClD,IAAIC,EAAO,WACX,QAASC,EAAQ,EAAGA,EAAQF,EAAM,OAAQE,GAAS,EACjDD,GAAQD,EAAM,WAAWE,CAAK,EAC9BD,EAAO,KAAK,KAAKA,EAAM,QAAQ,EAEjC,OAAQA,IAAS,GAAG,SAAS,EAAE,EAAE,SAAS,EAAG,GAAG,CAClD,EAEME,EAMJC,GACyE,CACzE,IAAMC,EAAwB,IAAI,IAC5BC,EAAU,IAAI,IAEpB,OAAOF,EAAY,IAAKG,GAAe,CACrC,IAAMC,EACJD,EAAW,QAAU,kBACjB,WACAA,EAAW,QAAU,mBACnB,aACA,OAAOA,EAAW,EAAE,EACtBE,EAAW,KAAK,UAAU,CAC9B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C,CAAQ,KAAO,CAChC,eAAgB,KAAO,CACrB,eAAiBC,GACfC,EAAsBH,EAAS,CAC7B,0BACEE,GAAoB,2BAA6BD,EAAQ,yBAC7D,CAAC,CACL,EACF,EACF",
|
|
6
|
+
"names": ["isFiniteNumber", "value", "validateFiniteTimeout", "timeoutMs", "label", "resolveTransitionTarget", "transition", "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", "buildShadowKey", "from", "event", "getJourneyDiagnostics", "journey", "options", "resolvedJourney", "resolveJourneyDefinition", "mode", "stepIds", "issues", "requireExplicitCompletion", "shadowedTransitionIndexes", "unconditionalTransitionByKey", "transition", "index", "key", "blocker", "activeTransitions", "_", "isImplicitlyTerminalStep", "stepId", "getOutgoingTransitions", "reachable", "markReachable", "target", "resolveTransitionTarget", "cycleKeys", "visitedForCycles", "stack", "walkCycles", "stackIndex", "cycleSteps", "cycleKey", "terminalMemo", "canReachTerminal", "pending", "memoized", "terminalReachable", "terminalPathExists", "issue", "createDiagnosticsPlugin", "journey", "options", "diagnosticsOptions", "getJourneyDiagnostics"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { JourneyDefinition, JourneyExecutionPathOptions, JourneyExecutionPathsResult, JourneyFullEventType, JourneyJsonObject, JourneyResolvedDefinition } from "../../types";
|
|
2
|
+
/**
|
|
3
|
+
* Enumerates structural execution paths from a resolved journey definition.
|
|
4
|
+
*/
|
|
5
|
+
export declare function getExecutionPaths<TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown>, TStepMeta = unknown, THandlers extends Record<string, unknown> = Record<never, never>>(journey: JourneyDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>, options?: JourneyExecutionPathOptions): JourneyExecutionPathsResult<TStepId, JourneyFullEventType<TEventMap>>;
|
|
6
|
+
export declare function getExecutionPaths<TContext extends JourneyJsonObject, TStepId extends string, TEventMap extends Record<string, unknown>, TStepMeta = unknown, THandlers extends Record<string, unknown> = Record<never, never>>(journey: JourneyResolvedDefinition<TContext, TStepId, TEventMap, TStepMeta, THandlers>, options?: JourneyExecutionPathOptions): JourneyExecutionPathsResult<TStepId, JourneyFullEventType<TEventMap>>;
|