@cyoda/workflow-core 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +27 -0
- package/dist/index.cjs +2004 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +2646 -0
- package/dist/index.d.ts +2646 -0
- package/dist/index.js +1920 -0
- package/dist/index.js.map +1 -0
- package/package.json +52 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/types/operator.ts","../src/types/api.ts","../src/schema/name.ts","../src/schema/operator.ts","../src/schema/criterion.ts","../src/schema/processor.ts","../src/schema/workflow.ts","../src/schema/payload.ts","../src/parse/errors.ts","../src/parse/operator-alias.ts","../src/identity/assign.ts","../src/normalize/input.ts","../src/validate/helpers.ts","../src/validate/semantic.ts","../src/validate/schema.ts","../src/parse/parse-import.ts","../src/parse/parse-export.ts","../src/parse/parse-editor-document.ts","../src/normalize/output.ts","../src/serialize/stringify.ts","../src/serialize/payload.ts","../src/identity/lookup.ts","../src/identity/id-for.ts","../src/validate/index.ts","../src/patch/apply.ts","../src/patch/invert.ts","../src/migrate/registry.ts"],"sourcesContent":["// Public API of @cyoda/workflow-core.\n// Per spec §3: explicit re-exports only; no `export *`.\n\nexport type {\n ArrayCriterion,\n ConcurrencyToken,\n Criterion,\n DomainPatch,\n EdgeAnchor,\n EdgeAnchorPair,\n EditorMetadata,\n EditorViewport,\n EntityFieldHintProvider,\n EntityIdentity,\n ExecutionMode,\n ExportPayload,\n ExportResult,\n ExternalizedProcessor,\n ExternalizedProcessorConfig,\n FieldHint,\n FunctionConfig,\n FunctionCriterion,\n GroupCriterion,\n HostRef,\n ImportMode,\n ImportPayload,\n ImportResult,\n JsonValue,\n LifecycleCriterion,\n OperatorType,\n Processor,\n ProcessorPointer,\n SaveStatus,\n ScheduledProcessor,\n Severity,\n SimpleCriterion,\n State,\n StateCode,\n StatePointer,\n SyntheticIdMap,\n Transition,\n TransitionName,\n TransitionPointer,\n CriterionPointer,\n ValidationIssue,\n Workflow,\n WorkflowApi,\n WorkflowEditorDocument,\n WorkflowSession,\n WorkflowUiMeta,\n} from \"./types/index.js\";\n\nexport {\n OPERATOR_TYPES,\n WorkflowApiConflictError,\n WorkflowApiTransportError,\n} from \"./types/index.js\";\n\nexport {\n ArrayCriterionSchema,\n CriterionSchema,\n ExecutionModeSchema,\n ExportPayloadSchema,\n ExternalizedProcessorSchema,\n FunctionConfigSchema,\n FunctionCriterionSchema,\n GroupCriterionSchema,\n ImportPayloadSchema,\n LifecycleCriterionSchema,\n NAME_REGEX,\n NameSchema,\n OperatorEnum,\n ProcessorSchema,\n ScheduledProcessorSchema,\n SimpleCriterionSchema,\n StateSchema,\n TransitionSchema,\n WorkflowSchema,\n} from \"./schema/index.js\";\n\nexport {\n ParseJsonError,\n SchemaError,\n normalizeOperatorAlias,\n parseEditorDocument,\n parseExportPayload,\n parseImportPayload,\n} from \"./parse/index.js\";\nexport type { ParseResult } from \"./parse/index.js\";\n\nexport {\n normalizeCriterion,\n normalizeProcessor,\n normalizeWorkflowInput,\n outputCriterion,\n outputFunctionConfig,\n outputProcessor,\n outputTransition,\n outputWorkflow,\n} from \"./normalize/index.js\";\n\nexport {\n prettyStringify,\n serializeEditorDocument,\n serializeExportPayload,\n serializeImportPayload,\n} from \"./serialize/index.js\";\n\nexport {\n assignSyntheticIds,\n idFor,\n lookupById,\n mintCriterionIds,\n} from \"./identity/index.js\";\nexport type { IdRef, LookupResult } from \"./identity/index.js\";\n\nexport {\n validateAll,\n validateExportSchema,\n validateImportSchema,\n validateSemantics,\n validateSession,\n zodErrorToIssues,\n} from \"./validate/index.js\";\n\nexport {\n applyPatch,\n applyPatches,\n invertPatch,\n validateAfterPatch,\n} from \"./patch/index.js\";\n\nexport {\n findMigrationPath,\n listMigrations,\n migrateSession,\n registerMigration,\n} from \"./migrate/index.js\";\nexport type { MigrationEntry, MigrationFn } from \"./migrate/index.js\";\n","export type OperatorType =\n | \"EQUALS\"\n | \"NOT_EQUAL\"\n | \"IS_NULL\"\n | \"NOT_NULL\"\n | \"GREATER_THAN\"\n | \"LESS_THAN\"\n | \"GREATER_OR_EQUAL\"\n | \"LESS_OR_EQUAL\"\n | \"BETWEEN\"\n | \"BETWEEN_INCLUSIVE\"\n | \"CONTAINS\"\n | \"NOT_CONTAINS\"\n | \"STARTS_WITH\"\n | \"NOT_STARTS_WITH\"\n | \"ENDS_WITH\"\n | \"NOT_ENDS_WITH\"\n | \"MATCHES_PATTERN\"\n | \"LIKE\"\n | \"IEQUALS\"\n | \"INOT_EQUAL\"\n | \"ICONTAINS\"\n | \"INOT_CONTAINS\"\n | \"ISTARTS_WITH\"\n | \"INOT_STARTS_WITH\"\n | \"IENDS_WITH\"\n | \"INOT_ENDS_WITH\"\n | \"IS_UNCHANGED\"\n | \"IS_CHANGED\";\n\nexport const OPERATOR_TYPES: ReadonlySet<OperatorType> = new Set<OperatorType>([\n \"EQUALS\",\n \"NOT_EQUAL\",\n \"IS_NULL\",\n \"NOT_NULL\",\n \"GREATER_THAN\",\n \"LESS_THAN\",\n \"GREATER_OR_EQUAL\",\n \"LESS_OR_EQUAL\",\n \"BETWEEN\",\n \"BETWEEN_INCLUSIVE\",\n \"CONTAINS\",\n \"NOT_CONTAINS\",\n \"STARTS_WITH\",\n \"NOT_STARTS_WITH\",\n \"ENDS_WITH\",\n \"NOT_ENDS_WITH\",\n \"MATCHES_PATTERN\",\n \"LIKE\",\n \"IEQUALS\",\n \"INOT_EQUAL\",\n \"ICONTAINS\",\n \"INOT_CONTAINS\",\n \"ISTARTS_WITH\",\n \"INOT_STARTS_WITH\",\n \"IENDS_WITH\",\n \"INOT_ENDS_WITH\",\n \"IS_UNCHANGED\",\n \"IS_CHANGED\",\n]);\n\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [k: string]: JsonValue };\n","import type { EntityIdentity, ExportPayload, ImportMode, ImportPayload } from \"./session.js\";\n\n/**\n * Opaque concurrency token returned by `exportWorkflows` and echoed back\n * on `importWorkflows` to enable 409 detection (spec §17.4).\n *\n * [Unverified] The shape of this token is a spec §30 open question — keep it\n * opaque so servers can use ETags, revision numbers, or session nonces\n * interchangeably.\n */\nexport type ConcurrencyToken = string;\n\nexport interface ExportResult {\n payload: ExportPayload;\n concurrencyToken: ConcurrencyToken | null;\n}\n\nexport interface ImportResult {\n /** New concurrency token assigned by the server after the import succeeded. */\n concurrencyToken: ConcurrencyToken | null;\n}\n\n/**\n * Contract between the configurator shell and the Cyoda backend (spec §17.1).\n * Implementations are expected to be thin wrappers around a REST client;\n * the editor never constructs requests directly.\n */\nexport interface WorkflowApi {\n /**\n * Fetch the active workflows for an entity. When `concurrencyToken`\n * is present on the result, the save flow passes it back on the next\n * import to detect 409 conflicts.\n */\n exportWorkflows(entity: EntityIdentity): Promise<ExportResult>;\n\n /**\n * Submit a workflow payload to the backend.\n *\n * Implementations MUST throw `WorkflowApiConflictError` when the server\n * responds with a 409 (stale concurrency token).\n */\n importWorkflows(\n entity: EntityIdentity,\n payload: ImportPayload,\n opts?: { concurrencyToken?: ConcurrencyToken | null },\n ): Promise<ImportResult>;\n}\n\n/**\n * Thrown by `importWorkflows` when the backend responds with a 409\n * (spec §17.4). The editor shell surfaces a non-dismissable banner offering\n * Reload (re-fetch + discard local) or Force overwrite (resend without\n * the token).\n */\nexport class WorkflowApiConflictError extends Error {\n override readonly name = \"WorkflowApiConflictError\";\n constructor(\n public readonly entity: EntityIdentity,\n public readonly serverConcurrencyToken: ConcurrencyToken | null,\n message = \"Workflow save conflict: server state has changed.\",\n ) {\n super(message);\n }\n}\n\n/**\n * Thrown by either API method when the transport itself fails (network\n * error, 5xx). Separate class so the save modal can distinguish transient\n * failures from genuine concurrency conflicts.\n */\nexport class WorkflowApiTransportError extends Error {\n override readonly name = \"WorkflowApiTransportError\";\n constructor(\n public override readonly cause: unknown,\n message = \"Workflow API transport error.\",\n ) {\n super(message);\n }\n}\n\n/**\n * JSONPath hint provider for criterion editing (spec §17.2, §15.3).\n * Optional — when omitted, criterion JSONPath inputs fall back to free-text.\n */\nexport interface EntityFieldHintProvider {\n /**\n * Return a flat list of JSONPath candidates for the given entity at\n * the call-site depth. The result is used to power an autocomplete\n * dropdown; implementations should cache per-entity internally.\n */\n listFieldPaths(entity: EntityIdentity): Promise<FieldHint[]>;\n}\n\nexport interface FieldHint {\n jsonPath: string;\n /** Human-readable type (string | number | boolean | object | array). */\n type: string;\n /** Optional description for hover. */\n description?: string;\n}\n\n/** Visible save-flow state surfaced to the UI shell (spec §17.3). */\nexport type SaveStatus =\n | { kind: \"idle\" }\n | { kind: \"confirming\"; mode: ImportMode; requiresExplicitConfirm: boolean }\n | { kind: \"saving\" }\n | { kind: \"success\"; at: number }\n | { kind: \"conflict\"; serverConcurrencyToken: ConcurrencyToken | null }\n | { kind: \"error\"; message: string };\n","import { z } from \"zod\";\n\nexport const NAME_REGEX = /^[A-Za-z][A-Za-z0-9_-]*$/;\n\nexport const NameSchema = z\n .string()\n .regex(NAME_REGEX, \"Invalid name: must start with a letter and contain only letters, digits, _ or -\");\n","import { z } from \"zod\";\nimport type { OperatorType } from \"../types/operator.js\";\n\nexport const OperatorEnum = z.enum([\n \"EQUALS\",\n \"NOT_EQUAL\",\n \"IS_NULL\",\n \"NOT_NULL\",\n \"GREATER_THAN\",\n \"LESS_THAN\",\n \"GREATER_OR_EQUAL\",\n \"LESS_OR_EQUAL\",\n \"BETWEEN\",\n \"BETWEEN_INCLUSIVE\",\n \"CONTAINS\",\n \"NOT_CONTAINS\",\n \"STARTS_WITH\",\n \"NOT_STARTS_WITH\",\n \"ENDS_WITH\",\n \"NOT_ENDS_WITH\",\n \"MATCHES_PATTERN\",\n \"LIKE\",\n \"IEQUALS\",\n \"INOT_EQUAL\",\n \"ICONTAINS\",\n \"INOT_CONTAINS\",\n \"ISTARTS_WITH\",\n \"INOT_STARTS_WITH\",\n \"IENDS_WITH\",\n \"INOT_ENDS_WITH\",\n \"IS_UNCHANGED\",\n \"IS_CHANGED\",\n] satisfies [OperatorType, ...OperatorType[]]);\n","import { z } from \"zod\";\nimport type { Criterion } from \"../types/criterion.js\";\nimport { NameSchema } from \"./name.js\";\nimport { OperatorEnum } from \"./operator.js\";\n\nexport const FunctionConfigSchema = z.object({\n attachEntity: z.boolean().optional(),\n calculationNodesTags: z.string().optional(),\n responseTimeoutMs: z.number().int().nonnegative().optional(),\n retryPolicy: z.string().optional(),\n context: z.string().optional(),\n});\n\nexport const SimpleCriterionSchema = z.object({\n type: z.literal(\"simple\"),\n jsonPath: z.string().min(1),\n operation: OperatorEnum,\n value: z.unknown().optional(),\n});\n\nexport const LifecycleCriterionSchema = z.object({\n type: z.literal(\"lifecycle\"),\n field: z.enum([\"state\", \"creationDate\", \"previousTransition\"]),\n operation: OperatorEnum,\n value: z.unknown().optional(),\n});\n\nexport const ArrayCriterionSchema = z.object({\n type: z.literal(\"array\"),\n jsonPath: z.string().min(1),\n operation: OperatorEnum,\n value: z.array(z.string()),\n});\n\n// Recursive shapes. Typed as `z.ZodType<Criterion>` via cast because zod's\n// inferred type for `z.lazy` can't see through the self-reference and\n// exactOptionalPropertyTypes makes the structural match fragile.\nexport const CriterionSchema: z.ZodType<Criterion> = z.lazy(() =>\n z.union([\n SimpleCriterionSchema,\n GroupCriterionSchema,\n FunctionCriterionSchema,\n LifecycleCriterionSchema,\n ArrayCriterionSchema,\n ]),\n) as unknown as z.ZodType<Criterion>;\n\nexport const GroupCriterionSchema = z.lazy(() =>\n z.object({\n type: z.literal(\"group\"),\n operator: z.enum([\"AND\", \"OR\", \"NOT\"]),\n conditions: z.array(CriterionSchema).min(1),\n }),\n);\n\nexport const FunctionCriterionSchema = z.lazy(() =>\n z.object({\n type: z.literal(\"function\"),\n function: z.object({\n name: NameSchema,\n config: FunctionConfigSchema.optional(),\n criterion: CriterionSchema.optional(),\n }),\n }),\n);\n","import { z } from \"zod\";\nimport { FunctionConfigSchema } from \"./criterion.js\";\nimport { NameSchema } from \"./name.js\";\n\nexport const ExecutionModeSchema = z.enum([\"SYNC\", \"ASYNC_SAME_TX\", \"ASYNC_NEW_TX\"]);\n\nexport const ExternalizedProcessorSchema = z.object({\n type: z.literal(\"externalized\"),\n name: NameSchema,\n executionMode: ExecutionModeSchema.optional(),\n config: FunctionConfigSchema.and(\n z.object({\n asyncResult: z.boolean().optional(),\n crossoverToAsyncMs: z.number().int().nonnegative().optional(),\n }),\n ).optional(),\n});\n\nexport const ScheduledProcessorSchema = z.object({\n type: z.literal(\"scheduled\"),\n name: NameSchema,\n config: z.object({\n delayMs: z.number().int().nonnegative(),\n transition: z.string().min(1),\n timeoutMs: z.number().int().nonnegative().optional(),\n }),\n});\n\nexport const ProcessorSchema = z.discriminatedUnion(\"type\", [\n ExternalizedProcessorSchema,\n ScheduledProcessorSchema,\n]);\n","import { z } from \"zod\";\nimport { CriterionSchema } from \"./criterion.js\";\nimport { NameSchema } from \"./name.js\";\nimport { ProcessorSchema } from \"./processor.js\";\n\nexport const TransitionSchema = z.object({\n name: NameSchema,\n next: NameSchema,\n manual: z.boolean(),\n disabled: z.boolean(),\n criterion: CriterionSchema.optional(),\n processors: z.array(ProcessorSchema).optional(),\n});\n\nexport const StateSchema = z.object({\n transitions: z.array(TransitionSchema),\n});\n\nexport const WorkflowSchema = z.object({\n version: z.string().min(1),\n name: NameSchema,\n desc: z.string().optional(),\n initialState: NameSchema,\n active: z.boolean(),\n criterion: CriterionSchema.optional(),\n states: z\n .record(NameSchema, StateSchema)\n .refine((s) => Object.keys(s).length > 0, \"Workflow must have at least one state\"),\n});\n","import { z } from \"zod\";\nimport { NameSchema } from \"./name.js\";\nimport { WorkflowSchema } from \"./workflow.js\";\n\nexport const ImportPayloadSchema = z.object({\n importMode: z.enum([\"MERGE\", \"REPLACE\", \"ACTIVATE\"]),\n workflows: z.array(WorkflowSchema).min(1),\n});\n\nexport const ExportPayloadSchema = z.object({\n entityName: NameSchema,\n modelVersion: z.number().int().positive(),\n workflows: z.array(WorkflowSchema).min(1),\n});\n","export class SchemaError extends Error {\n constructor(message: string, public readonly path?: (string | number)[]) {\n super(message);\n this.name = \"SchemaError\";\n }\n}\n\nexport class ParseJsonError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ParseJsonError\";\n }\n}\n","import { SchemaError } from \"./errors.js\";\n\ntype UnknownRecord = Record<string, unknown>;\n\nconst isObject = (v: unknown): v is UnknownRecord =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\n/**\n * Rewrite `operatorType` → `operation` in-place on a deep-cloned JSON tree.\n * If both are present and agree, drop `operatorType`.\n * If both are present and disagree, throw SchemaError.\n *\n * Only applies to criterion-shaped nodes (type: simple | lifecycle | array).\n */\nexport function normalizeOperatorAlias(raw: unknown): unknown {\n if (Array.isArray(raw)) {\n return raw.map((item) => normalizeOperatorAlias(item));\n }\n if (!isObject(raw)) return raw;\n\n const result: UnknownRecord = {};\n for (const [k, v] of Object.entries(raw)) {\n result[k] = normalizeOperatorAlias(v);\n }\n\n const type = result[\"type\"];\n const needsAlias =\n type === \"simple\" || type === \"lifecycle\" || type === \"array\" || type === undefined;\n\n if (needsAlias && \"operatorType\" in result) {\n const alias = result[\"operatorType\"];\n const existing = result[\"operation\"];\n if (existing !== undefined && existing !== alias) {\n throw new SchemaError(\n `Conflicting \"operation\" and \"operatorType\" values: ${JSON.stringify(existing)} vs ${JSON.stringify(alias)}`,\n );\n }\n result[\"operation\"] = existing ?? alias;\n delete result[\"operatorType\"];\n }\n return result;\n}\n","import { v4 as uuidv4 } from \"uuid\";\nimport type {\n CriterionPointer,\n EditorMetadata,\n HostRef,\n ProcessorPointer,\n StatePointer,\n SyntheticIdMap,\n TransitionPointer,\n WorkflowUiMeta,\n} from \"../types/editor.js\";\nimport type { Criterion } from \"../types/criterion.js\";\nimport type { WorkflowSession } from \"../types/session.js\";\nimport type { Workflow } from \"../types/workflow.js\";\n\nfunction emptyIds(): SyntheticIdMap {\n return {\n workflows: {},\n states: {},\n transitions: {},\n processors: {},\n criteria: {},\n };\n}\n\nfunction indexPriorStates(prior?: EditorMetadata): Record<string, string> {\n if (!prior) return {};\n const out: Record<string, string> = {};\n for (const [uuid, ptr] of Object.entries(prior.ids.states)) {\n out[`${ptr.workflow}:${ptr.state}`] = uuid;\n }\n return out;\n}\n\n/**\n * Build lookup `(workflow, state) → transitionUuid[]` in insertion order from\n * the prior metadata. Used to reuse transition UUIDs by ordinal position so\n * that patches produced against one revision remain applicable against the\n * next (spec §6.2: tuple-based reuse).\n */\nfunction indexPriorTransitions(prior?: EditorMetadata): Record<string, string[]> {\n if (!prior) return {};\n const out: Record<string, string[]> = {};\n for (const [uuid, ptr] of Object.entries(prior.ids.transitions)) {\n const key = `${ptr.workflow}:${ptr.state}`;\n (out[key] ??= []).push(uuid);\n }\n return out;\n}\n\nfunction indexPriorProcessors(prior?: EditorMetadata): Record<string, string[]> {\n if (!prior) return {};\n const out: Record<string, string[]> = {};\n for (const [uuid, ptr] of Object.entries(prior.ids.processors)) {\n const key = ptr.transitionUuid;\n (out[key] ??= []).push(uuid);\n }\n return out;\n}\n\n/**\n * Assign synthetic UUIDs to every addressable element. When `prior` is\n * provided, reuse IDs per spec §6.2:\n * - workflows reused by name;\n * - states reused by (workflow, stateCode);\n * - transitions reused by (workflow, state, ordinal-at-parse-time);\n * - processors reused by (transitionUuid, ordinal-at-parse-time).\n * Anything without a match is minted fresh.\n */\nexport function assignSyntheticIds(\n session: WorkflowSession,\n prior?: EditorMetadata,\n): EditorMetadata {\n const ids = emptyIds();\n const priorWorkflowIds = prior?.ids.workflows ?? {};\n const priorStatesByKey = indexPriorStates(prior);\n const priorTransitionsByKey = indexPriorTransitions(prior);\n const priorProcessorsByTransition = indexPriorProcessors(prior);\n const workflowUi: Record<string, WorkflowUiMeta> = prior?.workflowUi ?? {};\n\n for (const wf of session.workflows) {\n const wfUuid = priorWorkflowIds[wf.name] ?? uuidv4();\n ids.workflows[wf.name] = wfUuid;\n assignForWorkflow(\n wf,\n ids,\n priorStatesByKey,\n priorTransitionsByKey,\n priorProcessorsByTransition,\n );\n }\n\n return {\n revision: prior?.revision ?? 0,\n ids,\n workflowUi,\n ...(prior?.lastValidJsonHash !== undefined\n ? { lastValidJsonHash: prior.lastValidJsonHash }\n : {}),\n };\n}\n\nfunction assignForWorkflow(\n wf: Workflow,\n ids: SyntheticIdMap,\n priorStatesByKey: Record<string, string>,\n priorTransitionsByKey: Record<string, string[]>,\n priorProcessorsByTransition: Record<string, string[]>,\n): void {\n for (const stateCode of Object.keys(wf.states)) {\n const key = `${wf.name}:${stateCode}`;\n const uuid = priorStatesByKey[key] ?? uuidv4();\n const ptr: StatePointer = { workflow: wf.name, state: stateCode };\n ids.states[uuid] = ptr;\n }\n\n for (const [stateCode, state] of Object.entries(wf.states)) {\n const priorTs = priorTransitionsByKey[`${wf.name}:${stateCode}`] ?? [];\n state.transitions.forEach((t, idx) => {\n const tUuid = priorTs[idx] ?? uuidv4();\n const tPtr: TransitionPointer = {\n workflow: wf.name,\n state: stateCode,\n transitionUuid: tUuid,\n };\n ids.transitions[tUuid] = tPtr;\n\n if (t.processors) {\n const priorPs = priorProcessorsByTransition[tUuid] ?? [];\n t.processors.forEach((_p, pIdx) => {\n const pUuid = priorPs[pIdx] ?? uuidv4();\n const pPtr: ProcessorPointer = {\n workflow: wf.name,\n state: stateCode,\n transitionUuid: tUuid,\n processorUuid: pUuid,\n };\n ids.processors[pUuid] = pPtr;\n });\n }\n\n if (t.criterion) {\n mintCriterionIds(\n t.criterion,\n {\n kind: \"transition\",\n workflow: wf.name,\n state: stateCode,\n transitionUuid: tUuid,\n },\n [\"criterion\"],\n ids,\n );\n }\n });\n }\n\n if (wf.criterion) {\n mintCriterionIds(\n wf.criterion,\n { kind: \"workflow\", workflow: wf.name },\n [\"criterion\"],\n ids,\n );\n }\n}\n\nexport function mintCriterionIds(\n c: Criterion,\n host: HostRef,\n path: string[],\n ids: SyntheticIdMap,\n): void {\n const uuid = uuidv4();\n const ptr: CriterionPointer = { host, path: [...path] };\n ids.criteria[uuid] = ptr;\n\n switch (c.type) {\n case \"group\":\n c.conditions.forEach((child, idx) => {\n mintCriterionIds(child, host, [...path, \"conditions\", String(idx)], ids);\n });\n return;\n case \"function\":\n if (c.function.criterion) {\n mintCriterionIds(\n c.function.criterion,\n host,\n [...path, \"function\", \"criterion\"],\n ids,\n );\n }\n return;\n default:\n return;\n }\n}\n","import type { Workflow } from \"../types/workflow.js\";\nimport type { Processor } from \"../types/processor.js\";\nimport type { Criterion } from \"../types/criterion.js\";\n\n/**\n * Input normalization (spec §8.1) — runs after schema parse.\n * Mutates a deep-cloned structure; return the normalized form.\n *\n * 1. Drop empty optional containers (processors: [], criterion: {} already rejected by schema).\n * 2. Trim whitespace on name fields.\n * 3. Coerce numeric fields to integers — already enforced by Zod int().\n * 4. Coerce empty desc to undefined.\n */\nexport function normalizeWorkflowInput(workflow: Workflow): Workflow {\n const out: Workflow = {\n ...workflow,\n name: workflow.name.trim(),\n version: workflow.version.trim(),\n initialState: workflow.initialState.trim(),\n states: {},\n };\n\n if (workflow.desc !== undefined) {\n const trimmed = workflow.desc;\n if (trimmed.length === 0) {\n delete out.desc;\n } else {\n out.desc = trimmed;\n }\n }\n\n if (workflow.criterion !== undefined) {\n out.criterion = normalizeCriterion(workflow.criterion);\n }\n\n for (const [code, state] of Object.entries(workflow.states)) {\n const trimmedCode = code.trim();\n const normTransitions = state.transitions.map((t) => {\n const nt = {\n ...t,\n name: t.name.trim(),\n next: t.next.trim(),\n };\n if (t.criterion !== undefined) nt.criterion = normalizeCriterion(t.criterion);\n if (t.processors !== undefined) {\n if (t.processors.length === 0) {\n delete nt.processors;\n } else {\n nt.processors = t.processors.map(normalizeProcessor);\n }\n }\n return nt;\n });\n out.states[trimmedCode] = { transitions: normTransitions };\n }\n\n return out;\n}\n\nexport function normalizeCriterion(criterion: Criterion): Criterion {\n switch (criterion.type) {\n case \"simple\":\n return criterion;\n case \"group\":\n return { ...criterion, conditions: criterion.conditions.map(normalizeCriterion) };\n case \"function\": {\n const fn = criterion.function;\n const out: Criterion = {\n type: \"function\",\n function: {\n name: fn.name.trim(),\n ...(fn.config !== undefined ? { config: fn.config } : {}),\n ...(fn.criterion !== undefined\n ? { criterion: normalizeCriterion(fn.criterion) }\n : {}),\n },\n };\n return out;\n }\n case \"lifecycle\":\n return criterion;\n case \"array\":\n return criterion;\n }\n}\n\nexport function normalizeProcessor(p: Processor): Processor {\n if (p.type === \"externalized\") {\n return { ...p, name: p.name.trim() };\n }\n return {\n ...p,\n name: p.name.trim(),\n config: { ...p.config, transition: p.config.transition.trim() },\n };\n}\n","import { NAME_REGEX } from \"../schema/name.js\";\nimport type { Criterion } from \"../types/criterion.js\";\nimport type { WorkflowSession } from \"../types/session.js\";\nimport type { Transition, Workflow } from \"../types/workflow.js\";\n\nexport function isValidName(name: string): boolean {\n return NAME_REGEX.test(name);\n}\n\n/**\n * Walk every criterion node (pre-order) across a workflow session.\n * Yields the criterion and a breadcrumb describing where it was found.\n */\nexport function* walkCriteria(\n session: WorkflowSession,\n): Generator<{ criterion: Criterion; where: CriterionLocation }> {\n for (const wf of session.workflows) {\n if (wf.criterion) {\n yield* walkInner(wf.criterion, { kind: \"workflow\", workflow: wf.name });\n }\n for (const [stateCode, state] of Object.entries(wf.states)) {\n for (let i = 0; i < state.transitions.length; i++) {\n const t = state.transitions[i]!;\n if (t.criterion) {\n yield* walkInner(t.criterion, {\n kind: \"transition\",\n workflow: wf.name,\n state: stateCode,\n transitionIndex: i,\n transitionName: t.name,\n });\n }\n }\n }\n }\n}\n\nexport type CriterionLocation =\n | { kind: \"workflow\"; workflow: string }\n | {\n kind: \"transition\";\n workflow: string;\n state: string;\n transitionIndex: number;\n transitionName: string;\n };\n\nfunction* walkInner(\n c: Criterion,\n where: CriterionLocation,\n): Generator<{ criterion: Criterion; where: CriterionLocation }> {\n yield { criterion: c, where };\n if (c.type === \"group\") {\n for (const child of c.conditions) yield* walkInner(child, where);\n } else if (c.type === \"function\" && c.function.criterion) {\n yield* walkInner(c.function.criterion, where);\n }\n}\n\nexport function* walkTransitions(\n wf: Workflow,\n): Generator<{ state: string; transition: Transition; index: number }> {\n for (const [stateCode, state] of Object.entries(wf.states)) {\n for (let i = 0; i < state.transitions.length; i++) {\n yield { state: stateCode, transition: state.transitions[i]!, index: i };\n }\n }\n}\n\nexport function transitionNames(wf: Workflow): string[] {\n const out: string[] = [];\n for (const state of Object.values(wf.states)) {\n for (const t of state.transitions) out.push(t.name);\n }\n return out;\n}\n","import type { WorkflowEditorDocument } from \"../types/editor.js\";\nimport type { WorkflowSession } from \"../types/session.js\";\nimport type { ValidationIssue } from \"../types/validation.js\";\nimport type { Workflow } from \"../types/workflow.js\";\nimport { isValidName, walkCriteria } from \"./helpers.js\";\n\nconst LIFECYCLE_FIELDS = new Set([\"state\", \"creationDate\", \"previousTransition\"]);\n\n/**\n * Full semantic validation over a workflow session.\n * Returns all issues found; never throws.\n */\nexport function validateSemantics(\n session: WorkflowSession,\n doc?: WorkflowEditorDocument,\n): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n\n issues.push(...duplicateWorkflowNames(session));\n\n for (const wf of session.workflows) {\n issues.push(...validateWorkflow(wf, doc));\n }\n\n issues.push(...criterionRules(session));\n\n if (session.workflows.length === 1) {\n const only = session.workflows[0];\n if (only && only.criterion !== undefined) {\n issues.push({\n severity: \"info\",\n code: \"unused-workflow-criterion\",\n message:\n \"Workflow-level criterion is set but the session has only one workflow.\",\n });\n }\n }\n\n return issues;\n}\n\nfunction duplicateWorkflowNames(session: WorkflowSession): ValidationIssue[] {\n const seen = new Map<string, number>();\n for (const wf of session.workflows) {\n seen.set(wf.name, (seen.get(wf.name) ?? 0) + 1);\n }\n const out: ValidationIssue[] = [];\n for (const [name, count] of seen) {\n if (count > 1) {\n out.push({\n severity: \"error\",\n code: \"duplicate-workflow-name\",\n message: `Duplicate workflow name: \"${name}\" (appears ${count}×)`,\n detail: { name, count },\n });\n }\n }\n return out;\n}\n\nfunction validateWorkflow(\n wf: Workflow,\n doc?: WorkflowEditorDocument,\n): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n\n // missing-initial-state\n if (!wf.initialState || wf.initialState.length === 0) {\n issues.push({\n severity: \"error\",\n code: \"missing-initial-state\",\n message: `Workflow \"${wf.name}\" has no initialState.`,\n ...idFor(doc, wf.name, \"workflow\"),\n });\n } else if (!(wf.initialState in wf.states)) {\n issues.push({\n severity: \"error\",\n code: \"unknown-initial-state\",\n message: `Workflow \"${wf.name}\" initialState \"${wf.initialState}\" is not a state.`,\n ...idFor(doc, wf.name, \"workflow\"),\n });\n }\n\n // name regex\n if (!isValidName(wf.name)) {\n issues.push({\n severity: \"error\",\n code: \"name-regex-violation\",\n message: `Workflow name \"${wf.name}\" is invalid.`,\n });\n }\n\n for (const [stateCode, state] of Object.entries(wf.states)) {\n if (!isValidName(stateCode)) {\n issues.push({\n severity: \"error\",\n code: \"name-regex-violation\",\n message: `State code \"${stateCode}\" is invalid.`,\n });\n }\n\n // duplicate transition names within a state\n const transitionSeen = new Map<string, number>();\n for (const t of state.transitions) {\n transitionSeen.set(t.name, (transitionSeen.get(t.name) ?? 0) + 1);\n if (!isValidName(t.name)) {\n issues.push({\n severity: \"error\",\n code: \"name-regex-violation\",\n message: `Transition name \"${t.name}\" is invalid.`,\n });\n }\n if (!(t.next in wf.states)) {\n issues.push({\n severity: \"error\",\n code: \"unknown-transition-target\",\n message: `Transition \"${t.name}\" on \"${stateCode}\" targets unknown state \"${t.next}\".`,\n });\n }\n\n // duplicate processor names within a transition\n if (t.processors) {\n const pSeen = new Map<string, number>();\n for (const p of t.processors) {\n pSeen.set(p.name, (pSeen.get(p.name) ?? 0) + 1);\n if (!isValidName(p.name)) {\n issues.push({\n severity: \"error\",\n code: \"name-regex-violation\",\n message: `Processor name \"${p.name}\" is invalid.`,\n });\n }\n if (p.type === \"scheduled\" && p.config.transition.length === 0) {\n issues.push({\n severity: \"error\",\n code: \"scheduled-missing-target\",\n message: `Scheduled processor \"${p.name}\" has empty target transition.`,\n });\n }\n if (p.type === \"externalized\" && p.config) {\n if (\n p.config.crossoverToAsyncMs !== undefined &&\n p.config.asyncResult !== true\n ) {\n issues.push({\n severity: \"warning\",\n code: \"crossover-without-async-result\",\n message: `Processor \"${p.name}\" sets crossoverToAsyncMs but asyncResult is not true.`,\n });\n }\n }\n }\n for (const [name, count] of pSeen) {\n if (count > 1) {\n issues.push({\n severity: \"error\",\n code: \"duplicate-processor-name\",\n message: `Duplicate processor name \"${name}\" on transition \"${t.name}\".`,\n });\n }\n }\n if (t.processors.length > 5) {\n issues.push({\n severity: \"warning\",\n code: \"processor-overload\",\n message: `Transition \"${t.name}\" has ${t.processors.length} processors (>5).`,\n });\n }\n }\n\n // disabled-transition-on-active-workflow\n if (t.disabled && wf.active) {\n issues.push({\n severity: \"warning\",\n code: \"disabled-transition-on-active-workflow\",\n message: `Transition \"${t.name}\" is disabled in active workflow \"${wf.name}\".`,\n });\n }\n\n // scheduled-target-unresolved\n if (t.processors) {\n for (const p of t.processors) {\n if (p.type === \"scheduled\") {\n const names = collectTransitionNames(wf);\n if (!names.has(p.config.transition)) {\n issues.push({\n severity: \"warning\",\n code: \"scheduled-target-unresolved\",\n message: `Scheduled processor \"${p.name}\" targets unknown transition \"${p.config.transition}\" in workflow.`,\n });\n }\n }\n }\n }\n }\n for (const [name, count] of transitionSeen) {\n if (count > 1) {\n issues.push({\n severity: \"error\",\n code: \"duplicate-transition-name\",\n message: `Duplicate transition name \"${name}\" on state \"${stateCode}\".`,\n });\n }\n }\n\n // excessive-fan-out\n if (state.transitions.length > 8) {\n issues.push({\n severity: \"warning\",\n code: \"excessive-fan-out\",\n message: `State \"${stateCode}\" has ${state.transitions.length} outgoing transitions (>8).`,\n });\n }\n\n // all-transitions-manual\n if (\n state.transitions.length > 0 &&\n state.transitions.every((t) => t.manual === true)\n ) {\n issues.push({\n severity: \"warning\",\n code: \"all-transitions-manual\",\n message: `State \"${stateCode}\" has only manual transitions.`,\n });\n }\n\n // terminal-state-derived\n if (state.transitions.length === 0 && stateCode !== wf.initialState) {\n issues.push({\n severity: \"info\",\n code: \"terminal-state-derived\",\n message: `State \"${stateCode}\" is terminal.`,\n });\n }\n }\n\n // unreachable-state\n const reachable = reachableStates(wf);\n for (const stateCode of Object.keys(wf.states)) {\n if (!reachable.has(stateCode) && stateCode !== wf.initialState) {\n issues.push({\n severity: \"warning\",\n code: \"unreachable-state\",\n message: `State \"${stateCode}\" is unreachable from the initial state.`,\n });\n }\n }\n\n // workflow-inactive\n if (!wf.active) {\n issues.push({\n severity: \"info\",\n code: \"workflow-inactive\",\n message: `Workflow \"${wf.name}\" is inactive.`,\n });\n }\n\n // sync-on-likely-bottleneck-transition\n const reachableAuto = reachableAutoStates(wf);\n for (const [stateCode, state] of Object.entries(wf.states)) {\n if (!reachableAuto.has(stateCode)) continue;\n for (const t of state.transitions) {\n if (t.manual) continue;\n if (!t.processors) continue;\n for (const p of t.processors) {\n if (p.type === \"externalized\" && p.executionMode === \"SYNC\") {\n issues.push({\n severity: \"warning\",\n code: \"sync-on-likely-bottleneck-transition\",\n message: `SYNC processor \"${p.name}\" on auto-reachable transition \"${t.name}\" may block the main path.`,\n });\n }\n }\n }\n }\n\n return issues;\n}\n\nfunction criterionRules(session: WorkflowSession): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n for (const { criterion, where } of walkCriteria(session)) {\n switch (criterion.type) {\n case \"function\":\n if (!criterion.function.name || criterion.function.name.length === 0) {\n issues.push({\n severity: \"error\",\n code: \"function-missing-name\",\n message: `Function criterion has empty name (at ${describe(where)}).`,\n });\n } else if (!isValidName(criterion.function.name)) {\n issues.push({\n severity: \"error\",\n code: \"name-regex-violation\",\n message: `Function criterion name \"${criterion.function.name}\" is invalid.`,\n });\n }\n if (!criterion.function.criterion) {\n issues.push({\n severity: \"warning\",\n code: \"function-without-quick-exit\",\n message: `Function criterion \"${criterion.function.name}\" has no local quick-exit criterion.`,\n });\n }\n break;\n case \"array\":\n for (const v of criterion.value) {\n if (typeof v !== \"string\") {\n issues.push({\n severity: \"error\",\n code: \"array-non-string-value\",\n message: `Array criterion value contains a non-string element.`,\n });\n break;\n }\n }\n break;\n case \"lifecycle\":\n if (!LIFECYCLE_FIELDS.has(criterion.field)) {\n issues.push({\n severity: \"error\",\n code: \"lifecycle-invalid-field\",\n message: `Lifecycle criterion field \"${criterion.field}\" is invalid.`,\n });\n }\n break;\n case \"group\":\n if (criterion.operator === \"NOT\" && criterion.conditions.length > 1) {\n issues.push({\n severity: \"warning\",\n code: \"not-with-multiple-conditions\",\n message: `NOT group has ${criterion.conditions.length} conditions; should have exactly one.`,\n });\n }\n break;\n case \"simple\":\n break;\n }\n }\n return issues;\n}\n\nfunction reachableStates(wf: Workflow): Set<string> {\n const visited = new Set<string>();\n if (!(wf.initialState in wf.states)) return visited;\n const queue: string[] = [wf.initialState];\n visited.add(wf.initialState);\n while (queue.length) {\n const cur = queue.shift()!;\n const state = wf.states[cur];\n if (!state) continue;\n for (const t of state.transitions) {\n if (!visited.has(t.next) && t.next in wf.states) {\n visited.add(t.next);\n queue.push(t.next);\n }\n }\n }\n return visited;\n}\n\nfunction reachableAutoStates(wf: Workflow): Set<string> {\n // States reachable from initial without traversing a manual gate.\n const visited = new Set<string>();\n if (!(wf.initialState in wf.states)) return visited;\n const queue: string[] = [wf.initialState];\n visited.add(wf.initialState);\n while (queue.length) {\n const cur = queue.shift()!;\n const state = wf.states[cur];\n if (!state) continue;\n for (const t of state.transitions) {\n if (t.manual) continue;\n if (!visited.has(t.next) && t.next in wf.states) {\n visited.add(t.next);\n queue.push(t.next);\n }\n }\n }\n return visited;\n}\n\nfunction collectTransitionNames(wf: Workflow): Set<string> {\n const out = new Set<string>();\n for (const state of Object.values(wf.states)) {\n for (const t of state.transitions) out.add(t.name);\n }\n return out;\n}\n\ntype CriterionLoc =\n | { kind: \"workflow\"; workflow: string }\n | {\n kind: \"transition\";\n workflow: string;\n state: string;\n transitionIndex: number;\n transitionName: string;\n };\n\nfunction describe(w: CriterionLoc): string {\n if (w.kind === \"workflow\") return `workflow \"${w.workflow}\"`;\n return `transition \"${w.transitionName}\" on \"${w.workflow}:${w.state}\"`;\n}\n\nfunction idFor(\n doc: WorkflowEditorDocument | undefined,\n workflowName: string,\n _kind: \"workflow\",\n): { targetId?: string } {\n if (!doc) return {};\n const id = doc.meta.ids.workflows[workflowName];\n return id ? { targetId: id } : {};\n}\n","import type { ZodError } from \"zod\";\nimport type { ValidationIssue } from \"../types/validation.js\";\n\n/**\n * Convert a ZodError into ValidationIssue[] with `severity: \"error\"`.\n * The `code` is \"schema-\" + Zod's own error code; path is embedded in detail.\n */\nexport function zodErrorToIssues(err: ZodError): ValidationIssue[] {\n return err.issues.map((issue) => ({\n severity: \"error\",\n code: `schema-${issue.code}`,\n message: issue.message,\n detail: {\n path: issue.path,\n },\n }));\n}\n","import { assignSyntheticIds } from \"../identity/assign.js\";\nimport { normalizeWorkflowInput } from \"../normalize/input.js\";\nimport { ImportPayloadSchema } from \"../schema/payload.js\";\nimport type { EditorMetadata, WorkflowEditorDocument } from \"../types/editor.js\";\nimport type { ImportPayload, WorkflowSession } from \"../types/session.js\";\nimport type { ValidationIssue } from \"../types/validation.js\";\nimport { validateSemantics } from \"../validate/semantic.js\";\nimport { zodErrorToIssues } from \"../validate/schema.js\";\nimport { ParseJsonError } from \"./errors.js\";\nimport { normalizeOperatorAlias } from \"./operator-alias.js\";\n\nexport interface ParseResult<T> {\n ok: boolean;\n value?: T;\n document?: WorkflowEditorDocument;\n issues: ValidationIssue[];\n}\n\nfunction parseJsonSafe(json: string): { ok: true; value: unknown } | { ok: false; err: string } {\n try {\n return { ok: true, value: JSON.parse(json) };\n } catch (e) {\n return { ok: false, err: (e as Error).message };\n }\n}\n\n/**\n * Parse a Cyoda import-payload JSON string into a WorkflowEditorDocument.\n * Pipeline: JSON.parse → operator-alias normalisation → Zod → input normalisation\n * → assignSyntheticIds → semantic validation.\n */\nexport function parseImportPayload(\n json: string,\n prior?: EditorMetadata,\n): ParseResult<ImportPayload> {\n const parsed = parseJsonSafe(json);\n if (!parsed.ok) {\n throw new ParseJsonError(`Invalid JSON: ${parsed.err}`);\n }\n\n let aliased: unknown;\n try {\n aliased = normalizeOperatorAlias(parsed.value);\n } catch (e) {\n return {\n ok: false,\n issues: [\n {\n severity: \"error\",\n code: \"operator-alias-conflict\",\n message: (e as Error).message,\n },\n ],\n };\n }\n\n const schemaResult = ImportPayloadSchema.safeParse(aliased);\n if (!schemaResult.success) {\n return { ok: false, issues: zodErrorToIssues(schemaResult.error) };\n }\n\n const normalizedWorkflows = schemaResult.data.workflows.map(normalizeWorkflowInput);\n const session: WorkflowSession = {\n entity: null,\n importMode: schemaResult.data.importMode,\n workflows: normalizedWorkflows,\n };\n\n const meta = assignSyntheticIds(session, prior);\n const document: WorkflowEditorDocument = { session, meta };\n\n const issues = validateSemantics(session, document);\n const hasError = issues.some((i) => i.severity === \"error\");\n\n return {\n ok: !hasError,\n value: { importMode: session.importMode, workflows: session.workflows },\n document,\n issues,\n };\n}\n","import { assignSyntheticIds } from \"../identity/assign.js\";\nimport { normalizeWorkflowInput } from \"../normalize/input.js\";\nimport { ExportPayloadSchema } from \"../schema/payload.js\";\nimport type { EditorMetadata, WorkflowEditorDocument } from \"../types/editor.js\";\nimport type { ExportPayload, WorkflowSession } from \"../types/session.js\";\nimport { validateSemantics } from \"../validate/semantic.js\";\nimport { zodErrorToIssues } from \"../validate/schema.js\";\nimport { ParseJsonError } from \"./errors.js\";\nimport { normalizeOperatorAlias } from \"./operator-alias.js\";\nimport type { ParseResult } from \"./parse-import.js\";\n\nexport function parseExportPayload(\n json: string,\n prior?: EditorMetadata,\n): ParseResult<ExportPayload> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(json);\n } catch (e) {\n throw new ParseJsonError(`Invalid JSON: ${(e as Error).message}`);\n }\n\n let aliased: unknown;\n try {\n aliased = normalizeOperatorAlias(parsed);\n } catch (e) {\n return {\n ok: false,\n issues: [\n {\n severity: \"error\",\n code: \"operator-alias-conflict\",\n message: (e as Error).message,\n },\n ],\n };\n }\n\n const schemaResult = ExportPayloadSchema.safeParse(aliased);\n if (!schemaResult.success) {\n return { ok: false, issues: zodErrorToIssues(schemaResult.error) };\n }\n\n const normalizedWorkflows = schemaResult.data.workflows.map(normalizeWorkflowInput);\n const session: WorkflowSession = {\n entity: {\n entityName: schemaResult.data.entityName,\n modelVersion: schemaResult.data.modelVersion,\n },\n importMode: \"MERGE\",\n workflows: normalizedWorkflows,\n };\n\n const meta = assignSyntheticIds(session, prior);\n const document: WorkflowEditorDocument = { session, meta };\n\n const issues = validateSemantics(session, document);\n const hasError = issues.some((i) => i.severity === \"error\");\n\n return {\n ok: !hasError,\n value: {\n entityName: schemaResult.data.entityName,\n modelVersion: schemaResult.data.modelVersion,\n workflows: session.workflows,\n },\n document,\n issues,\n };\n}\n","import { z } from \"zod\";\nimport { ImportPayloadSchema } from \"../schema/payload.js\";\nimport type { WorkflowEditorDocument } from \"../types/editor.js\";\nimport { assignSyntheticIds } from \"../identity/assign.js\";\nimport { normalizeWorkflowInput } from \"../normalize/input.js\";\nimport { normalizeOperatorAlias } from \"./operator-alias.js\";\nimport { validateSemantics } from \"../validate/semantic.js\";\nimport { zodErrorToIssues } from \"../validate/schema.js\";\nimport { ParseJsonError } from \"./errors.js\";\nimport type { ParseResult } from \"./parse-import.js\";\n\nconst EditorDocumentSchema = z.object({\n session: z.object({\n entity: z\n .object({\n entityName: z.string(),\n modelVersion: z.number().int().positive(),\n })\n .nullable(),\n importMode: z.enum([\"MERGE\", \"REPLACE\", \"ACTIVATE\"]),\n workflows: z.array(z.unknown()),\n }),\n meta: z\n .object({\n revision: z.number().int().nonnegative(),\n ids: z.unknown(),\n workflowUi: z.record(z.unknown()),\n lastValidJsonHash: z.string().optional(),\n })\n .passthrough(),\n});\n\nexport function parseEditorDocument(\n json: string,\n): ParseResult<WorkflowEditorDocument> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(json);\n } catch (e) {\n throw new ParseJsonError(`Invalid JSON: ${(e as Error).message}`);\n }\n\n const outerResult = EditorDocumentSchema.safeParse(parsed);\n if (!outerResult.success) {\n return { ok: false, issues: zodErrorToIssues(outerResult.error) };\n }\n\n const aliased = normalizeOperatorAlias(outerResult.data.session);\n const inner = ImportPayloadSchema.omit({ importMode: true }).extend({\n importMode: z.enum([\"MERGE\", \"REPLACE\", \"ACTIVATE\"]),\n });\n const sessionResult = inner.safeParse({\n importMode: outerResult.data.session.importMode,\n workflows: (aliased as { workflows: unknown }).workflows,\n });\n if (!sessionResult.success) {\n return { ok: false, issues: zodErrorToIssues(sessionResult.error) };\n }\n\n const normalizedWorkflows = sessionResult.data.workflows.map(normalizeWorkflowInput);\n const session = {\n entity: outerResult.data.session.entity,\n importMode: sessionResult.data.importMode,\n workflows: normalizedWorkflows,\n };\n\n const meta = assignSyntheticIds(\n session,\n outerResult.data.meta as WorkflowEditorDocument[\"meta\"],\n );\n const document: WorkflowEditorDocument = { session, meta };\n const issues = validateSemantics(session, document);\n const hasError = issues.some((i) => i.severity === \"error\");\n\n return { ok: !hasError, document, value: document, issues };\n}\n","import type { Criterion, FunctionConfig } from \"../types/criterion.js\";\nimport type {\n ExternalizedProcessor,\n ExternalizedProcessorConfig,\n Processor,\n} from \"../types/processor.js\";\nimport type { Transition, Workflow } from \"../types/workflow.js\";\n\n/**\n * Output normalization (spec §8.2) — deterministic shaping for serialization.\n * Returns plain objects in the exact keys the serializer will emit.\n */\n\nexport function outputWorkflow(w: Workflow): Record<string, unknown> {\n const out: Record<string, unknown> = {\n version: w.version,\n name: w.name,\n };\n if (w.desc !== undefined) out[\"desc\"] = w.desc;\n out[\"initialState\"] = w.initialState;\n out[\"active\"] = w.active;\n if (w.criterion !== undefined) out[\"criterion\"] = outputCriterion(w.criterion);\n out[\"states\"] = outputStates(w.states);\n return out;\n}\n\nfunction outputStates(states: Workflow[\"states\"]): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [code, state] of Object.entries(states)) {\n out[code] = { transitions: state.transitions.map(outputTransition) };\n }\n return out;\n}\n\nexport function outputTransition(t: Transition): Record<string, unknown> {\n const out: Record<string, unknown> = {\n name: t.name,\n next: t.next,\n manual: t.manual,\n disabled: t.disabled,\n };\n if (t.criterion !== undefined) out[\"criterion\"] = outputCriterion(t.criterion);\n if (t.processors !== undefined && t.processors.length > 0) {\n out[\"processors\"] = t.processors.map(outputProcessor);\n }\n return out;\n}\n\nexport function outputCriterion(c: Criterion): Record<string, unknown> {\n switch (c.type) {\n case \"simple\": {\n const out: Record<string, unknown> = {\n type: \"simple\",\n jsonPath: c.jsonPath,\n operation: c.operation,\n };\n if (c.value !== undefined) out[\"value\"] = c.value;\n return out;\n }\n case \"group\":\n return {\n type: \"group\",\n operator: c.operator,\n conditions: c.conditions.map(outputCriterion),\n };\n case \"function\": {\n const fn: Record<string, unknown> = { name: c.function.name };\n if (c.function.config !== undefined) {\n const config = outputFunctionConfig(c.function.config);\n if (Object.keys(config).length > 0) fn[\"config\"] = config;\n }\n if (c.function.criterion !== undefined) {\n fn[\"criterion\"] = outputCriterion(c.function.criterion);\n }\n return { type: \"function\", function: fn };\n }\n case \"lifecycle\": {\n const out: Record<string, unknown> = {\n type: \"lifecycle\",\n field: c.field,\n operation: c.operation,\n };\n if (c.value !== undefined) out[\"value\"] = c.value;\n return out;\n }\n case \"array\":\n return {\n type: \"array\",\n jsonPath: c.jsonPath,\n operation: c.operation,\n value: c.value,\n };\n }\n}\n\nexport function outputProcessor(p: Processor): Record<string, unknown> {\n if (p.type === \"externalized\") return outputExternalizedProcessor(p);\n return {\n type: \"scheduled\",\n name: p.name,\n config: outputScheduledConfig(p.config),\n };\n}\n\nfunction outputScheduledConfig(\n cfg: { delayMs: number; transition: string; timeoutMs?: number },\n): Record<string, unknown> {\n const out: Record<string, unknown> = {\n delayMs: cfg.delayMs,\n transition: cfg.transition,\n };\n if (cfg.timeoutMs !== undefined) out[\"timeoutMs\"] = cfg.timeoutMs;\n return out;\n}\n\nfunction outputExternalizedProcessor(p: ExternalizedProcessor): Record<string, unknown> {\n const out: Record<string, unknown> = {\n type: \"externalized\",\n name: p.name,\n };\n // Omit executionMode when it is the default ASYNC_NEW_TX (spec §8.2).\n if (p.executionMode !== undefined && p.executionMode !== \"ASYNC_NEW_TX\") {\n out[\"executionMode\"] = p.executionMode;\n }\n if (p.config !== undefined) {\n const cfg = outputExternalizedConfig(p.config);\n if (Object.keys(cfg).length > 0) out[\"config\"] = cfg;\n }\n return out;\n}\n\nfunction outputExternalizedConfig(cfg: ExternalizedProcessorConfig): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n // attachEntity: omit when false.\n if (cfg.attachEntity === true) out[\"attachEntity\"] = true;\n if (cfg.calculationNodesTags !== undefined && cfg.calculationNodesTags !== \"\") {\n out[\"calculationNodesTags\"] = cfg.calculationNodesTags;\n }\n if (cfg.responseTimeoutMs !== undefined) out[\"responseTimeoutMs\"] = cfg.responseTimeoutMs;\n if (cfg.retryPolicy !== undefined && cfg.retryPolicy !== \"\") {\n out[\"retryPolicy\"] = cfg.retryPolicy;\n }\n if (cfg.context !== undefined && cfg.context !== \"\") out[\"context\"] = cfg.context;\n // asyncResult: omit when false.\n if (cfg.asyncResult === true) out[\"asyncResult\"] = true;\n // crossoverToAsyncMs: pair-only with asyncResult === true.\n if (cfg.asyncResult === true && cfg.crossoverToAsyncMs !== undefined) {\n out[\"crossoverToAsyncMs\"] = cfg.crossoverToAsyncMs;\n }\n return out;\n}\n\nexport function outputFunctionConfig(\n cfg: NonNullable<Criterion extends { type: \"function\" } ? never : never> | FunctionConfig,\n): Record<string, unknown> {\n const c = cfg as FunctionConfig;\n const out: Record<string, unknown> = {};\n if (c.attachEntity === true) out[\"attachEntity\"] = true;\n if (c.calculationNodesTags !== undefined && c.calculationNodesTags !== \"\") {\n out[\"calculationNodesTags\"] = c.calculationNodesTags;\n }\n if (c.responseTimeoutMs !== undefined) out[\"responseTimeoutMs\"] = c.responseTimeoutMs;\n if (c.retryPolicy !== undefined && c.retryPolicy !== \"\") out[\"retryPolicy\"] = c.retryPolicy;\n if (c.context !== undefined && c.context !== \"\") out[\"context\"] = c.context;\n return out;\n}\n","/**\n * Deterministic pretty stringify — 2-space indent, LF line endings, trailing newline.\n * Assumes input object has its keys in the desired emission order; we preserve\n * insertion order (as V8 does for string keys).\n */\nexport function prettyStringify(value: unknown): string {\n const body = JSON.stringify(value, null, 2);\n // JSON.stringify uses system line endings in most runtimes, but the spec\n // uses \\n between tokens. Force LF regardless of host.\n const lfOnly = body.replace(/\\r\\n/g, \"\\n\");\n return lfOnly + \"\\n\";\n}\n","import { outputWorkflow } from \"../normalize/output.js\";\nimport type { WorkflowEditorDocument } from \"../types/editor.js\";\nimport type { EntityIdentity } from \"../types/session.js\";\nimport { prettyStringify } from \"./stringify.js\";\n\n/**\n * Serialize an editor document as an ImportPayload JSON string.\n * Import payloads have keys ordered: importMode, workflows.\n */\nexport function serializeImportPayload(doc: WorkflowEditorDocument): string {\n const payload = {\n importMode: doc.session.importMode,\n workflows: doc.session.workflows.map(outputWorkflow),\n };\n return prettyStringify(payload);\n}\n\n/**\n * Serialize an editor document as an ExportPayload JSON string.\n * Export payloads have keys ordered: entityName, modelVersion, workflows.\n *\n * If the caller provides an `entity` override, it is used; otherwise the\n * session's entity is required (else throws).\n */\nexport function serializeExportPayload(\n doc: WorkflowEditorDocument,\n entity?: EntityIdentity,\n): string {\n const e = entity ?? doc.session.entity;\n if (e == null) {\n throw new Error(\"serializeExportPayload requires an entity identity\");\n }\n const payload = {\n entityName: e.entityName,\n modelVersion: e.modelVersion,\n workflows: doc.session.workflows.map(outputWorkflow),\n };\n return prettyStringify(payload);\n}\n\n/**\n * Serialize the full editor document (session + metadata) for in-app persistence.\n * Not for export to Cyoda.\n */\nexport function serializeEditorDocument(doc: WorkflowEditorDocument): string {\n return prettyStringify({\n session: {\n entity: doc.session.entity,\n importMode: doc.session.importMode,\n workflows: doc.session.workflows.map(outputWorkflow),\n },\n meta: doc.meta,\n });\n}\n","import type { Criterion } from \"../types/criterion.js\";\nimport type { HostRef, WorkflowEditorDocument } from \"../types/editor.js\";\nimport type { Processor } from \"../types/processor.js\";\nimport type { State, Transition, Workflow } from \"../types/workflow.js\";\n\nexport type LookupResult =\n | { kind: \"workflow\"; workflow: Workflow }\n | { kind: \"state\"; workflow: Workflow; state: State; stateCode: string }\n | { kind: \"transition\"; workflow: Workflow; state: State; transition: Transition }\n | { kind: \"processor\"; transition: Transition; processor: Processor }\n | {\n kind: \"criterion\";\n criterion: Criterion;\n parent: { host: HostRef; path: string[] };\n }\n | null;\n\nexport function lookupById(doc: WorkflowEditorDocument, uuid: string): LookupResult {\n const { ids } = doc.meta;\n const session = doc.session;\n\n // Workflow?\n for (const [name, wfUuid] of Object.entries(ids.workflows)) {\n if (wfUuid === uuid) {\n const workflow = session.workflows.find((w) => w.name === name);\n if (workflow) return { kind: \"workflow\", workflow };\n }\n }\n\n // State?\n const statePtr = ids.states[uuid];\n if (statePtr) {\n const workflow = session.workflows.find((w) => w.name === statePtr.workflow);\n if (!workflow) return null;\n const state = workflow.states[statePtr.state];\n if (!state) return null;\n return { kind: \"state\", workflow, state, stateCode: statePtr.state };\n }\n\n // Transition?\n const tPtr = ids.transitions[uuid];\n if (tPtr) {\n const workflow = session.workflows.find((w) => w.name === tPtr.workflow);\n if (!workflow) return null;\n const state = workflow.states[tPtr.state];\n if (!state) return null;\n const transition = findTransitionByUuid(doc, tPtr.workflow, tPtr.state, uuid);\n if (!transition) return null;\n return { kind: \"transition\", workflow, state, transition };\n }\n\n // Processor?\n const pPtr = ids.processors[uuid];\n if (pPtr) {\n const transition = findTransitionByUuid(\n doc,\n pPtr.workflow,\n pPtr.state,\n pPtr.transitionUuid,\n );\n if (!transition) return null;\n const processor = findProcessorByUuid(doc, uuid);\n if (!processor) return null;\n return { kind: \"processor\", transition, processor };\n }\n\n // Criterion?\n const cPtr = ids.criteria[uuid];\n if (cPtr) {\n const host = resolveHost(doc, cPtr.host);\n if (host === null) return null;\n const criterion = walkPath(host, cPtr.path);\n if (!criterion) return null;\n return {\n kind: \"criterion\",\n criterion,\n parent: { host: cPtr.host, path: cPtr.path },\n };\n }\n\n return null;\n}\n\nfunction findTransitionByUuid(\n doc: WorkflowEditorDocument,\n workflowName: string,\n stateCode: string,\n transitionUuid: string,\n): Transition | null {\n const workflow = doc.session.workflows.find((w) => w.name === workflowName);\n if (!workflow) return null;\n const state = workflow.states[stateCode];\n if (!state) return null;\n // Transitions are identified by UUID in ids map; we need to find by index.\n // Since assignment walks state.transitions in order, we reconstruct by\n // iterating the same order to find the index matching the uuid.\n const orderedUuids = listTransitionUuidsForState(doc, workflowName, stateCode);\n const idx = orderedUuids.indexOf(transitionUuid);\n if (idx < 0) return null;\n return state.transitions[idx] ?? null;\n}\n\nfunction listTransitionUuidsForState(\n doc: WorkflowEditorDocument,\n workflowName: string,\n stateCode: string,\n): string[] {\n const out: string[] = [];\n for (const [uuid, ptr] of Object.entries(doc.meta.ids.transitions)) {\n if (ptr.workflow === workflowName && ptr.state === stateCode) {\n out.push(uuid);\n }\n }\n // Sort by the order they appear in state.transitions — we cannot recover\n // from the map alone, so we keep insertion order by relying on Object.entries.\n return out;\n}\n\nfunction findProcessorByUuid(\n doc: WorkflowEditorDocument,\n processorUuid: string,\n): Processor | null {\n const ptr = doc.meta.ids.processors[processorUuid];\n if (!ptr) return null;\n const transition = findTransitionByUuid(\n doc,\n ptr.workflow,\n ptr.state,\n ptr.transitionUuid,\n );\n if (!transition || !transition.processors) return null;\n // Determine index by counting ProcessorPointers with same transitionUuid\n // appearing before this one in insertion order.\n const orderedUuids: string[] = [];\n for (const [uuid, pPtr] of Object.entries(doc.meta.ids.processors)) {\n if (pPtr.transitionUuid === ptr.transitionUuid) orderedUuids.push(uuid);\n }\n const idx = orderedUuids.indexOf(processorUuid);\n if (idx < 0) return null;\n return transition.processors[idx] ?? null;\n}\n\nfunction resolveHost(\n doc: WorkflowEditorDocument,\n host: HostRef,\n): Criterion | Workflow | Transition | null {\n const workflow = doc.session.workflows.find((w) => w.name === host.workflow);\n if (!workflow) return null;\n if (host.kind === \"workflow\") return workflow;\n if (host.kind === \"transition\") {\n const state = workflow.states[host.state];\n if (!state) return null;\n return findTransitionByUuid(doc, host.workflow, host.state, host.transitionUuid);\n }\n // processorConfig: not used in v1; return null.\n return null;\n}\n\nfunction walkPath(\n root: Workflow | Transition | Criterion,\n path: string[],\n): Criterion | null {\n let node: unknown = root;\n for (const segment of path) {\n if (node == null || typeof node !== \"object\") return null;\n node = (node as Record<string, unknown>)[segment];\n if (node == null) return null;\n if (Array.isArray(node)) continue; // we only index arrays with numeric segments\n }\n if (!node || typeof node !== \"object\") return null;\n const maybe = node as { type?: string };\n if (\n maybe.type === \"simple\" ||\n maybe.type === \"group\" ||\n maybe.type === \"function\" ||\n maybe.type === \"lifecycle\" ||\n maybe.type === \"array\"\n ) {\n return node as Criterion;\n }\n return null;\n}\n","import type { EditorMetadata, HostRef } from \"../types/editor.js\";\n\nexport type IdRef =\n | { kind: \"workflow\"; workflow: string }\n | { kind: \"state\"; workflow: string; state: string }\n | {\n kind: \"transition\";\n workflow: string;\n state: string;\n transitionName: string;\n ordinal: number;\n }\n | { kind: \"processor\"; transitionUuid: string; processorName: string; ordinal: number }\n | { kind: \"criterion\"; host: HostRef; path: string[] };\n\n/**\n * Resolve an address-style reference to a synthetic UUID using the current metadata.\n * Returns `null` if no such ID exists.\n *\n * Transition lookups use (workflow, state) + ordinal: we return the Nth\n * transition UUID registered for that state (in insertion order).\n */\nexport function idFor(meta: EditorMetadata, ref: IdRef): string | null {\n switch (ref.kind) {\n case \"workflow\":\n return meta.ids.workflows[ref.workflow] ?? null;\n case \"state\": {\n for (const [uuid, ptr] of Object.entries(meta.ids.states)) {\n if (ptr.workflow === ref.workflow && ptr.state === ref.state) return uuid;\n }\n return null;\n }\n case \"transition\": {\n const matches: string[] = [];\n for (const [uuid, ptr] of Object.entries(meta.ids.transitions)) {\n if (ptr.workflow === ref.workflow && ptr.state === ref.state) {\n matches.push(uuid);\n }\n }\n return matches[ref.ordinal] ?? null;\n }\n case \"processor\": {\n const matches: string[] = [];\n for (const [uuid, ptr] of Object.entries(meta.ids.processors)) {\n if (ptr.transitionUuid === ref.transitionUuid) matches.push(uuid);\n }\n return matches[ref.ordinal] ?? null;\n }\n case \"criterion\": {\n const target = JSON.stringify(ref.path);\n for (const [uuid, ptr] of Object.entries(meta.ids.criteria)) {\n if (\n JSON.stringify(ptr.host) === JSON.stringify(ref.host) &&\n JSON.stringify(ptr.path) === target\n ) {\n return uuid;\n }\n }\n return null;\n }\n }\n}\n","import { ImportPayloadSchema, ExportPayloadSchema } from \"../schema/payload.js\";\nimport type { WorkflowEditorDocument } from \"../types/editor.js\";\nimport type { WorkflowSession } from \"../types/session.js\";\nimport type { ValidationIssue } from \"../types/validation.js\";\nimport { zodErrorToIssues } from \"./schema.js\";\nimport { validateSemantics } from \"./semantic.js\";\n\nexport { validateSemantics } from \"./semantic.js\";\nexport { zodErrorToIssues } from \"./schema.js\";\n\n/**\n * Validate a raw payload against the ImportPayload schema. Returns any issues.\n */\nexport function validateImportSchema(raw: unknown): ValidationIssue[] {\n const parsed = ImportPayloadSchema.safeParse(raw);\n return parsed.success ? [] : zodErrorToIssues(parsed.error);\n}\n\n/**\n * Validate a raw payload against the ExportPayload schema. Returns any issues.\n */\nexport function validateExportSchema(raw: unknown): ValidationIssue[] {\n const parsed = ExportPayloadSchema.safeParse(raw);\n return parsed.success ? [] : zodErrorToIssues(parsed.error);\n}\n\n/**\n * Combined schema + semantic validation over a document.\n */\nexport function validateAll(doc: WorkflowEditorDocument): ValidationIssue[] {\n return validateSemantics(doc.session, doc);\n}\n\n/**\n * Combined schema + semantic validation over a session (without metadata).\n */\nexport function validateSession(session: WorkflowSession): ValidationIssue[] {\n return validateSemantics(session);\n}\n","import { produce } from \"immer\";\nimport { assignSyntheticIds } from \"../identity/assign.js\";\nimport type { WorkflowEditorDocument } from \"../types/editor.js\";\nimport type { DomainPatch } from \"../types/patch.js\";\nimport type { WorkflowSession } from \"../types/session.js\";\nimport type { Workflow } from \"../types/workflow.js\";\nimport { validateSemantics } from \"../validate/semantic.js\";\nimport type { ValidationIssue } from \"../types/validation.js\";\n\n/**\n * Apply a patch to a document, returning a new document.\n * - Refreshes synthetic IDs for the new session.\n * - Bumps revision.\n * - Re-runs semantic validation (issues stored separately; doc itself is the\n * canonical source, issues are computed via validateAll by callers).\n */\nexport function applyPatch(\n doc: WorkflowEditorDocument,\n patch: DomainPatch,\n): WorkflowEditorDocument {\n // UI-only patches short-circuit the session pipeline.\n if (patch.op === \"setEdgeAnchors\") {\n return applySetEdgeAnchors(doc, patch);\n }\n\n const nextSession = produce(doc.session, (d) => {\n // Cast to break immer's WritableDraft recursion over the deeply-nested\n // Criterion union — we rely on structural mutation with no type gain.\n const draft = d as unknown as WorkflowSession;\n switch (patch.op) {\n case \"addWorkflow\":\n draft.workflows.push(patch.workflow);\n return;\n case \"removeWorkflow\":\n draft.workflows = draft.workflows.filter((w) => w.name !== patch.workflow);\n return;\n case \"updateWorkflowMeta\": {\n const wf = draft.workflows.find((w) => w.name === patch.workflow);\n if (!wf) return;\n Object.assign(wf, patch.updates);\n return;\n }\n case \"renameWorkflow\": {\n const wf = draft.workflows.find((w) => w.name === patch.from);\n if (!wf) return;\n wf.name = patch.to;\n return;\n }\n case \"setInitialState\": {\n const wf = draft.workflows.find((w) => w.name === patch.workflow);\n if (!wf) return;\n wf.initialState = patch.stateCode;\n return;\n }\n case \"setWorkflowCriterion\": {\n const wf = draft.workflows.find((w) => w.name === patch.workflow);\n if (!wf) return;\n if (patch.criterion === undefined) delete wf.criterion;\n else wf.criterion = patch.criterion;\n return;\n }\n case \"addState\": {\n const wf = draft.workflows.find((w) => w.name === patch.workflow);\n if (!wf) return;\n if (!(patch.stateCode in wf.states)) {\n wf.states[patch.stateCode] = { transitions: [] };\n }\n return;\n }\n case \"renameState\": {\n const wf = draft.workflows.find((w) => w.name === patch.workflow);\n if (!wf) return;\n renameStateCascading(wf, patch.from, patch.to);\n return;\n }\n case \"removeState\": {\n const wf = draft.workflows.find((w) => w.name === patch.workflow);\n if (!wf) return;\n removeStateCascading(wf, patch.stateCode);\n return;\n }\n case \"addTransition\": {\n const wf = draft.workflows.find((w) => w.name === patch.workflow);\n if (!wf) return;\n const state = wf.states[patch.fromState];\n if (!state) return;\n state.transitions.push(patch.transition);\n return;\n }\n case \"updateTransition\": {\n const loc = locateTransition(doc, patch.transitionUuid);\n if (!loc) return;\n const wf = draft.workflows.find((w) => w.name === loc.workflow);\n const state = wf?.states[loc.state];\n const transition = state?.transitions[loc.index];\n if (!transition) return;\n Object.assign(transition, patch.updates);\n return;\n }\n case \"removeTransition\": {\n const loc = locateTransition(doc, patch.transitionUuid);\n if (!loc) return;\n const wf = draft.workflows.find((w) => w.name === loc.workflow);\n const state = wf?.states[loc.state];\n if (!state) return;\n state.transitions.splice(loc.index, 1);\n return;\n }\n case \"reorderTransition\": {\n const wf = draft.workflows.find((w) => w.name === patch.workflow);\n const state = wf?.states[patch.fromState];\n if (!state) return;\n const loc = locateTransition(doc, patch.transitionUuid);\n if (!loc) return;\n const [item] = state.transitions.splice(loc.index, 1);\n if (!item) return;\n state.transitions.splice(patch.toIndex, 0, item);\n return;\n }\n case \"addProcessor\": {\n const loc = locateTransition(doc, patch.transitionUuid);\n if (!loc) return;\n const wf = draft.workflows.find((w) => w.name === loc.workflow);\n const state = wf?.states[loc.state];\n const transition = state?.transitions[loc.index];\n if (!transition) return;\n if (!transition.processors) transition.processors = [];\n const idx = patch.index ?? transition.processors.length;\n transition.processors.splice(idx, 0, patch.processor);\n return;\n }\n case \"updateProcessor\": {\n const procLoc = locateProcessor(doc, patch.processorUuid);\n if (!procLoc) return;\n const wf = draft.workflows.find((w) => w.name === procLoc.workflow);\n const state = wf?.states[procLoc.state];\n const transition = state?.transitions[procLoc.transitionIndex];\n const processor = transition?.processors?.[procLoc.processorIndex];\n if (!processor) return;\n Object.assign(processor, patch.updates);\n return;\n }\n case \"removeProcessor\": {\n const procLoc = locateProcessor(doc, patch.processorUuid);\n if (!procLoc) return;\n const wf = draft.workflows.find((w) => w.name === procLoc.workflow);\n const state = wf?.states[procLoc.state];\n const transition = state?.transitions[procLoc.transitionIndex];\n if (!transition?.processors) return;\n transition.processors.splice(procLoc.processorIndex, 1);\n if (transition.processors.length === 0) delete transition.processors;\n return;\n }\n case \"reorderProcessor\": {\n const procLoc = locateProcessor(doc, patch.processorUuid);\n if (!procLoc) return;\n const wf = draft.workflows.find((w) => w.name === procLoc.workflow);\n const state = wf?.states[procLoc.state];\n const transition = state?.transitions[procLoc.transitionIndex];\n if (!transition?.processors) return;\n const [item] = transition.processors.splice(procLoc.processorIndex, 1);\n if (!item) return;\n transition.processors.splice(patch.toIndex, 0, item);\n return;\n }\n case \"setCriterion\": {\n // Apply a criterion change at the given host + path.\n const host = patch.host;\n const wf = draft.workflows.find((w) => w.name === host.workflow);\n if (!wf) return;\n let container: unknown;\n if (host.kind === \"workflow\") container = wf;\n else if (host.kind === \"transition\") {\n const state = wf.states[host.state];\n if (!state) return;\n const loc = locateTransition(doc, host.transitionUuid);\n if (!loc) return;\n container = state.transitions[loc.index];\n } else {\n // processorConfig not supported in v1 patch apply.\n return;\n }\n applyCriterionAtPath(\n container as Record<string, unknown>,\n patch.path,\n patch.criterion,\n );\n return;\n }\n case \"setImportMode\":\n draft.importMode = patch.mode;\n return;\n case \"setEntity\":\n draft.entity = patch.entity;\n return;\n case \"replaceSession\":\n draft.workflows = patch.session.workflows;\n draft.importMode = patch.session.importMode;\n draft.entity = patch.session.entity;\n return;\n }\n });\n\n const nextMeta = assignSyntheticIds(nextSession, doc.meta);\n return {\n session: nextSession,\n meta: { ...nextMeta, revision: doc.meta.revision + 1 },\n };\n}\n\n/**\n * Convenience: apply multiple patches in sequence.\n */\nexport function applyPatches(\n doc: WorkflowEditorDocument,\n patches: DomainPatch[],\n): WorkflowEditorDocument {\n return patches.reduce((d, p) => applyPatch(d, p), doc);\n}\n\nexport function validateAfterPatch(\n doc: WorkflowEditorDocument,\n): ValidationIssue[] {\n return validateSemantics(doc.session, doc);\n}\n\n// ----- helpers -----\n\nfunction applySetEdgeAnchors(\n doc: WorkflowEditorDocument,\n patch: Extract<DomainPatch, { op: \"setEdgeAnchors\" }>,\n): WorkflowEditorDocument {\n const ptr = doc.meta.ids.transitions[patch.transitionUuid];\n if (!ptr) return { ...doc, meta: { ...doc.meta, revision: doc.meta.revision + 1 } };\n\n const workflowUi = { ...doc.meta.workflowUi };\n const current = workflowUi[ptr.workflow] ?? {};\n const edgeAnchors = { ...(current.edgeAnchors ?? {}) };\n\n if (patch.anchors === null) {\n delete edgeAnchors[patch.transitionUuid];\n } else {\n edgeAnchors[patch.transitionUuid] = { ...patch.anchors };\n }\n\n workflowUi[ptr.workflow] = {\n ...current,\n edgeAnchors: Object.keys(edgeAnchors).length > 0 ? edgeAnchors : undefined,\n };\n\n return {\n session: doc.session,\n meta: {\n ...doc.meta,\n workflowUi,\n revision: doc.meta.revision + 1,\n },\n };\n}\n\nfunction renameStateCascading(wf: Workflow, from: string, to: string): void {\n if (!(from in wf.states) || from === to) return;\n wf.states[to] = wf.states[from]!;\n delete wf.states[from];\n for (const state of Object.values(wf.states)) {\n for (const t of state.transitions) {\n if (t.next === from) t.next = to;\n }\n }\n if (wf.initialState === from) wf.initialState = to;\n}\n\nfunction removeStateCascading(wf: Workflow, stateCode: string): void {\n if (!(stateCode in wf.states)) return;\n delete wf.states[stateCode];\n for (const state of Object.values(wf.states)) {\n state.transitions = state.transitions.filter((t) => t.next !== stateCode);\n }\n if (wf.initialState === stateCode) wf.initialState = \"\";\n}\n\nfunction locateTransition(\n doc: WorkflowEditorDocument,\n transitionUuid: string,\n): { workflow: string; state: string; index: number } | null {\n const ptr = doc.meta.ids.transitions[transitionUuid];\n if (!ptr) return null;\n // We need the ordinal index of this transition within the state.\n // Build the list of transition UUIDs for the same (workflow, state) and find ours.\n const ordered: string[] = [];\n for (const [uuid, p] of Object.entries(doc.meta.ids.transitions)) {\n if (p.workflow === ptr.workflow && p.state === ptr.state) ordered.push(uuid);\n }\n const idx = ordered.indexOf(transitionUuid);\n if (idx < 0) return null;\n return { workflow: ptr.workflow, state: ptr.state, index: idx };\n}\n\nfunction locateProcessor(\n doc: WorkflowEditorDocument,\n processorUuid: string,\n): {\n workflow: string;\n state: string;\n transitionIndex: number;\n processorIndex: number;\n} | null {\n const ptr = doc.meta.ids.processors[processorUuid];\n if (!ptr) return null;\n const tLoc = locateTransition(doc, ptr.transitionUuid);\n if (!tLoc) return null;\n const ordered: string[] = [];\n for (const [uuid, p] of Object.entries(doc.meta.ids.processors)) {\n if (p.transitionUuid === ptr.transitionUuid) ordered.push(uuid);\n }\n const pIdx = ordered.indexOf(processorUuid);\n if (pIdx < 0) return null;\n return {\n workflow: tLoc.workflow,\n state: tLoc.state,\n transitionIndex: tLoc.index,\n processorIndex: pIdx,\n };\n}\n\nfunction applyCriterionAtPath(\n container: Record<string, unknown>,\n path: string[],\n criterion: unknown,\n): void {\n if (path.length === 0) return;\n let node = container;\n for (let i = 0; i < path.length - 1; i++) {\n const seg = path[i]!;\n const next = node[seg];\n if (next === undefined || next === null) return;\n if (Array.isArray(next)) {\n const idx = Number(path[i + 1]);\n const arr = next as unknown[];\n const target = arr[idx];\n if (target === undefined || typeof target !== \"object\") return;\n node = target as Record<string, unknown>;\n i++; // consumed both the array key and the index\n } else if (typeof next === \"object\") {\n node = next as Record<string, unknown>;\n } else {\n return;\n }\n }\n const lastSeg = path[path.length - 1]!;\n if (criterion === undefined) {\n delete node[lastSeg];\n } else {\n node[lastSeg] = criterion;\n }\n}\n","import type { WorkflowEditorDocument } from \"../types/editor.js\";\nimport type { DomainPatch } from \"../types/patch.js\";\nimport type { Criterion } from \"../types/criterion.js\";\nimport type { Processor } from \"../types/processor.js\";\nimport type { Transition, Workflow } from \"../types/workflow.js\";\n\n/**\n * Produce the inverse of `patch` relative to the pre-apply document `doc`.\n * Applying `patch` to `doc`, then applying `invertPatch(doc, patch)` to the\n * result, returns a document equal to `doc` modulo `meta.revision`.\n *\n * Complex cascading operations (removeState, removeWorkflow, renameWorkflow,\n * replaceSession) invert via a captured-slice `replaceSession` — this is the\n * simplest provably correct inverse, at the cost of coarser undo grain.\n */\nexport function invertPatch(\n doc: WorkflowEditorDocument,\n patch: DomainPatch,\n): DomainPatch {\n switch (patch.op) {\n case \"addWorkflow\":\n return { op: \"removeWorkflow\", workflow: patch.workflow.name };\n\n case \"removeWorkflow\":\n case \"renameWorkflow\":\n case \"removeState\":\n case \"renameState\":\n case \"replaceSession\":\n return { op: \"replaceSession\", session: cloneSession(doc) };\n\n case \"updateWorkflowMeta\": {\n const wf = findWorkflow(doc, patch.workflow);\n if (!wf) return noop();\n const prior: Partial<Pick<Workflow, \"version\" | \"desc\" | \"active\">> = {};\n for (const key of Object.keys(patch.updates) as Array<keyof typeof patch.updates>) {\n (prior as Record<string, unknown>)[key] = wf[key];\n }\n return { op: \"updateWorkflowMeta\", workflow: patch.workflow, updates: prior };\n }\n\n case \"setInitialState\": {\n const wf = findWorkflow(doc, patch.workflow);\n if (!wf) return noop();\n return {\n op: \"setInitialState\",\n workflow: patch.workflow,\n stateCode: wf.initialState,\n };\n }\n\n case \"setWorkflowCriterion\": {\n const wf = findWorkflow(doc, patch.workflow);\n if (!wf) return noop();\n return wf.criterion\n ? {\n op: \"setWorkflowCriterion\",\n workflow: patch.workflow,\n criterion: cloneCriterion(wf.criterion),\n }\n : { op: \"setWorkflowCriterion\", workflow: patch.workflow };\n }\n\n case \"addState\":\n return {\n op: \"removeState\",\n workflow: patch.workflow,\n stateCode: patch.stateCode,\n };\n\n case \"addTransition\": {\n // Inverse needs the minted UUID of the newly added transition,\n // which only exists post-apply. We emit a replaceSession fallback.\n return { op: \"replaceSession\", session: cloneSession(doc) };\n }\n\n case \"updateTransition\": {\n const t = findTransition(doc, patch.transitionUuid);\n if (!t) return noop();\n const prior: Partial<Transition> = {};\n for (const key of Object.keys(patch.updates) as Array<keyof Transition>) {\n (prior as Record<string, unknown>)[key] = t[key];\n }\n return {\n op: \"updateTransition\",\n transitionUuid: patch.transitionUuid,\n updates: prior,\n };\n }\n\n case \"removeTransition\":\n case \"reorderTransition\":\n return { op: \"replaceSession\", session: cloneSession(doc) };\n\n case \"addProcessor\":\n return { op: \"replaceSession\", session: cloneSession(doc) };\n\n case \"updateProcessor\": {\n const p = findProcessor(doc, patch.processorUuid);\n if (!p) return noop();\n const prior: Partial<Processor> = {};\n for (const key of Object.keys(patch.updates) as Array<keyof Processor>) {\n (prior as Record<string, unknown>)[key] = (p as unknown as Record<string, unknown>)[key];\n }\n return {\n op: \"updateProcessor\",\n processorUuid: patch.processorUuid,\n updates: prior,\n };\n }\n\n case \"removeProcessor\":\n case \"reorderProcessor\":\n return { op: \"replaceSession\", session: cloneSession(doc) };\n\n case \"setCriterion\": {\n const prior = readCriterionAt(doc, patch.host, patch.path);\n return prior === undefined\n ? { op: \"setCriterion\", host: patch.host, path: patch.path }\n : {\n op: \"setCriterion\",\n host: patch.host,\n path: patch.path,\n criterion: cloneCriterion(prior),\n };\n }\n\n case \"setImportMode\":\n return { op: \"setImportMode\", mode: doc.session.importMode };\n\n case \"setEntity\":\n return { op: \"setEntity\", entity: doc.session.entity };\n\n case \"setEdgeAnchors\": {\n const ptr = doc.meta.ids.transitions[patch.transitionUuid];\n if (!ptr) return noop();\n const prior =\n doc.meta.workflowUi[ptr.workflow]?.edgeAnchors?.[patch.transitionUuid];\n return {\n op: \"setEdgeAnchors\",\n transitionUuid: patch.transitionUuid,\n anchors: prior ? { ...prior } : null,\n };\n }\n }\n}\n\nfunction noop(): DomainPatch {\n return { op: \"setImportMode\", mode: \"MERGE\" };\n}\n\nfunction findWorkflow(doc: WorkflowEditorDocument, name: string): Workflow | undefined {\n return doc.session.workflows.find((w) => w.name === name);\n}\n\nfunction findTransition(\n doc: WorkflowEditorDocument,\n transitionUuid: string,\n): Transition | undefined {\n const ptr = doc.meta.ids.transitions[transitionUuid];\n if (!ptr) return undefined;\n const wf = findWorkflow(doc, ptr.workflow);\n const state = wf?.states[ptr.state];\n if (!state) return undefined;\n const ordered: string[] = [];\n for (const [uuid, p] of Object.entries(doc.meta.ids.transitions)) {\n if (p.workflow === ptr.workflow && p.state === ptr.state) ordered.push(uuid);\n }\n const idx = ordered.indexOf(transitionUuid);\n return state.transitions[idx];\n}\n\nfunction findProcessor(\n doc: WorkflowEditorDocument,\n processorUuid: string,\n): Processor | undefined {\n const ptr = doc.meta.ids.processors[processorUuid];\n if (!ptr) return undefined;\n const t = findTransition(doc, ptr.transitionUuid);\n if (!t?.processors) return undefined;\n const ordered: string[] = [];\n for (const [uuid, p] of Object.entries(doc.meta.ids.processors)) {\n if (p.transitionUuid === ptr.transitionUuid) ordered.push(uuid);\n }\n const idx = ordered.indexOf(processorUuid);\n return t.processors[idx];\n}\n\nfunction readCriterionAt(\n doc: WorkflowEditorDocument,\n host: { kind: string; workflow: string; state?: string; transitionUuid?: string },\n path: string[],\n): Criterion | undefined {\n const wf = findWorkflow(doc, host.workflow);\n if (!wf) return undefined;\n let container: Record<string, unknown> | undefined;\n if (host.kind === \"workflow\") {\n container = wf as unknown as Record<string, unknown>;\n } else if (host.kind === \"transition\" && host.transitionUuid) {\n const t = findTransition(doc, host.transitionUuid);\n if (!t) return undefined;\n container = t as unknown as Record<string, unknown>;\n } else {\n return undefined;\n }\n let node: unknown = container;\n for (const seg of path) {\n if (node === null || node === undefined) return undefined;\n if (Array.isArray(node)) {\n node = node[Number(seg)];\n } else if (typeof node === \"object\") {\n node = (node as Record<string, unknown>)[seg];\n } else {\n return undefined;\n }\n }\n return node as Criterion | undefined;\n}\n\nfunction cloneSession(doc: WorkflowEditorDocument) {\n return structuredClone(doc.session);\n}\n\nfunction cloneCriterion(c: Criterion): Criterion {\n return structuredClone(c);\n}\n","import type { WorkflowSession } from \"../types/session.js\";\n\nexport type MigrationFn = (session: WorkflowSession) => WorkflowSession;\n\nexport interface MigrationEntry {\n from: string;\n to: string;\n migrate: MigrationFn;\n}\n\nconst registry: MigrationEntry[] = [];\n\nexport function registerMigration(entry: MigrationEntry): void {\n const dup = registry.find((e) => e.from === entry.from && e.to === entry.to);\n if (dup) return;\n registry.push(entry);\n}\n\nexport function listMigrations(): readonly MigrationEntry[] {\n return registry;\n}\n\nexport function findMigrationPath(from: string, to: string): MigrationEntry[] | null {\n if (from === to) return [];\n const visited = new Set<string>();\n const queue: Array<{ version: string; path: MigrationEntry[] }> = [\n { version: from, path: [] },\n ];\n while (queue.length > 0) {\n const head = queue.shift()!;\n if (head.version === to) return head.path;\n if (visited.has(head.version)) continue;\n visited.add(head.version);\n for (const entry of registry) {\n if (entry.from === head.version) {\n queue.push({ version: entry.to, path: [...head.path, entry] });\n }\n }\n }\n return null;\n}\n\nexport function migrateSession(\n session: WorkflowSession,\n from: string,\n to: string,\n): WorkflowSession {\n const path = findMigrationPath(from, to);\n if (!path) {\n throw new Error(`No migration path from ${from} to ${to}`);\n }\n return path.reduce((s, entry) => entry.migrate(s), session);\n}\n\n// Register the identity migration so callers can opt into version metadata\n// without special-casing the default.\nregisterMigration({ from: \"1.0\", to: \"1.0\", migrate: (s) => s });\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,eAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC8BO,IAAM,iBAA4C,oBAAI,IAAkB;AAAA,EAC7E;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