@cyoda/workflow-core 0.1.0 → 0.2.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/README.md +93 -7
- package/dist/index.cjs +952 -113
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +298 -87
- package/dist/index.d.ts +298 -87
- package/dist/index.js +938 -113
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../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":["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":";AA8BO,IAAM,iBAA4C,oBAAI,IAAkB;AAAA,EAC7E;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;;;ACLM,IAAM,2BAAN,cAAuC,MAAM;AAAA,EAElD,YACkB,QACA,wBAChB,UAAU,qDACV;AACA,UAAM,OAAO;AAJG;AACA;AAAA,EAIlB;AAAA,EALkB;AAAA,EACA;AAAA,EAHA,OAAO;AAQ3B;AAOO,IAAM,4BAAN,cAAwC,MAAM;AAAA,EAEnD,YAC2B,OACzB,UAAU,iCACV;AACA,UAAM,OAAO;AAHY;AAAA,EAI3B;AAAA,EAJ2B;AAAA,EAFT,OAAO;AAO3B;;;AC9EA,SAAS,SAAS;AAEX,IAAM,aAAa;AAEnB,IAAM,aAAa,EACvB,OAAO,EACP,MAAM,YAAY,iFAAiF;;;ACNtG,SAAS,KAAAA,UAAS;AAGX,IAAM,eAAeA,GAAE,KAAK;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;A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AI,MAAM,SAAS,KAAK,SAAS;AAC/B,cAAM,KAAK,EAAE,SAAS,MAAM,IAAI,MAAM,CAAC,GAAG,KAAK,MAAM,KAAK,EAAE,CAAC;AAAA,MAC/D;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEO,SAAS,eACd,SACA,MACA,IACiB;AACjB,QAAM,OAAO,kBAAkB,MAAM,EAAE;AACvC,MAAI,CAAC,MAAM;AACT,UAAM,IAAI,MAAM,0BAA0B,IAAI,OAAO,EAAE,EAAE;AAAA,EAC3D;AACA,SAAO,KAAK,OAAO,CAAC,GAAG,UAAU,MAAM,QAAQ,CAAC,GAAG,OAAO;AAC5D;AAIA,kBAAkB,EAAE,MAAM,OAAO,IAAI,OAAO,SAAS,CAAC,MAAM,EAAE,CAAC;","names":["z","z","z","z","z","z","z","z","z","z","z","idFor"]}
|
|
1
|
+
{"version":3,"sources":["../src/types/operator.ts","../src/types/transaction.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/criteria/operators.ts","../src/normalize/input.ts","../src/criteria/jsonPathSubset.ts","../src/identity/id-for.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/validate/index.ts","../src/patch/apply.ts","../src/patch/invert.ts","../src/patch/transaction.ts","../src/migrate/registry.ts","../src/criteria/describe.ts"],"sourcesContent":["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 { DomainPatch } from \"./patch.js\";\n\n/**\n * A group of patches that form a single logical user action and therefore a\n * single undo step. The caller is responsible for pre-computing both the\n * forward `patches` and their exact `inverses` (in forward order — the undo\n * machinery reverses and applies them in reverse order at undo time).\n */\nexport interface PatchTransaction {\n summary: string;\n patches: DomainPatch[];\n inverses: DomainPatch[];\n /** Selection to restore after the transaction is undone. */\n selectionAfter?: unknown;\n}\n\n/**\n * Thrown by applyPatch when a patch would create a name collision or other\n * integrity violation.\n */\nexport class PatchConflictError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PatchConflictError\";\n }\n}\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([\n \"SYNC\",\n \"ASYNC_SAME_TX\",\n \"ASYNC_NEW_TX\",\n \"COMMIT_BEFORE_DISPATCH\",\n]);\n\nexport const ExternalizedProcessorSchema = z.object({\n type: z.literal(\"externalized\"),\n name: NameSchema,\n executionMode: ExecutionModeSchema.optional(),\n startNewTxOnDispatch: z.boolean().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().default(false),\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 { OperatorType } from \"../types/operator.js\";\n\n// Engine-verified canonical operator catalogue (26 entries).\n// Source of truth: cyoda-go `internal/domain/search/operators.go:33-60`.\n// See ai/critrion-specs.md §3.1.\nexport const SUPPORTED_SIMPLE_OPERATORS: ReadonlySet<OperatorType> = new Set<OperatorType>([\n \"EQUALS\",\n \"NOT_EQUAL\",\n \"GREATER_THAN\",\n \"LESS_THAN\",\n \"GREATER_OR_EQUAL\",\n \"LESS_OR_EQUAL\",\n \"CONTAINS\",\n \"NOT_CONTAINS\",\n \"STARTS_WITH\",\n \"NOT_STARTS_WITH\",\n \"ENDS_WITH\",\n \"NOT_ENDS_WITH\",\n \"LIKE\",\n \"IS_NULL\",\n \"NOT_NULL\",\n \"BETWEEN\",\n \"BETWEEN_INCLUSIVE\",\n \"MATCHES_PATTERN\",\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]);\n\n// Operators present in the OperatorType union but NOT implemented by the engine.\n// Editor must surface but never offer for new criteria. See spec §3.2.\nexport const UNSUPPORTED_OPERATORS: ReadonlySet<OperatorType> = new Set<OperatorType>([\n \"IS_UNCHANGED\",\n \"IS_CHANGED\",\n]);\n\n// Group-condition operators the engine implements. NOT is in the schema for\n// round-trip but is NOT implemented in cyoda-go (`internal/match/match.go:119-147`).\nexport const SUPPORTED_GROUP_OPERATORS = [\"AND\", \"OR\"] as const satisfies readonly (\"AND\" | \"OR\")[];\n\n// Criterion-tree depth limits.\n// MAX_CRITERION_DEPTH is the engine import limit (spec §2.2). Trees at or\n// above this depth are rejected by cyoda-go's importer.\n// CRITERION_DEPTH_WARNING_THRESHOLD is the UI/editor soft limit — beyond this\n// depth, criteria are hard to read and edit.\nexport const MAX_CRITERION_DEPTH = 50;\nexport const CRITERION_DEPTH_WARNING_THRESHOLD = 5;\n\nexport type OperatorGroupId =\n | \"equality\"\n | \"ordering\"\n | \"range\"\n | \"substring\"\n | \"pattern\"\n | \"null\";\n\nexport interface OperatorGroup {\n readonly id: OperatorGroupId;\n readonly label: string;\n readonly operators: readonly OperatorType[];\n}\n\nexport const OPERATOR_GROUPS: readonly OperatorGroup[] = [\n {\n id: \"equality\",\n label: \"Equality\",\n operators: [\"EQUALS\", \"NOT_EQUAL\", \"IEQUALS\", \"INOT_EQUAL\"],\n },\n {\n id: \"ordering\",\n label: \"Ordering\",\n operators: [\"GREATER_THAN\", \"LESS_THAN\", \"GREATER_OR_EQUAL\", \"LESS_OR_EQUAL\"],\n },\n {\n id: \"range\",\n label: \"Range\",\n operators: [\"BETWEEN\", \"BETWEEN_INCLUSIVE\"],\n },\n {\n id: \"substring\",\n label: \"Substring\",\n operators: [\n \"CONTAINS\",\n \"NOT_CONTAINS\",\n \"ICONTAINS\",\n \"INOT_CONTAINS\",\n \"STARTS_WITH\",\n \"NOT_STARTS_WITH\",\n \"ISTARTS_WITH\",\n \"INOT_STARTS_WITH\",\n \"ENDS_WITH\",\n \"NOT_ENDS_WITH\",\n \"IENDS_WITH\",\n \"INOT_ENDS_WITH\",\n ],\n },\n {\n id: \"pattern\",\n label: \"Pattern\",\n operators: [\"LIKE\", \"MATCHES_PATTERN\"],\n },\n {\n id: \"null\",\n label: \"Null\",\n operators: [\"IS_NULL\", \"NOT_NULL\"],\n },\n];\n\nexport type OperatorValueShape = \"scalar\" | \"range\" | \"none\";\n\n// Per-operator value shape used by UI widgets and value validation.\n// \"range\" = two-element [low, high] array; \"none\" = value ignored at runtime\n// but emitted as null on the wire (spec §4.4). Unsupported operators are\n// not listed here — callers must check SUPPORTED_SIMPLE_OPERATORS first.\nexport const OPERATOR_VALUE_SHAPE: Readonly<Record<OperatorType, OperatorValueShape>> = {\n EQUALS: \"scalar\",\n NOT_EQUAL: \"scalar\",\n GREATER_THAN: \"scalar\",\n LESS_THAN: \"scalar\",\n GREATER_OR_EQUAL: \"scalar\",\n LESS_OR_EQUAL: \"scalar\",\n CONTAINS: \"scalar\",\n NOT_CONTAINS: \"scalar\",\n STARTS_WITH: \"scalar\",\n NOT_STARTS_WITH: \"scalar\",\n ENDS_WITH: \"scalar\",\n NOT_ENDS_WITH: \"scalar\",\n LIKE: \"scalar\",\n MATCHES_PATTERN: \"scalar\",\n IEQUALS: \"scalar\",\n INOT_EQUAL: \"scalar\",\n ICONTAINS: \"scalar\",\n INOT_CONTAINS: \"scalar\",\n ISTARTS_WITH: \"scalar\",\n INOT_STARTS_WITH: \"scalar\",\n IENDS_WITH: \"scalar\",\n INOT_ENDS_WITH: \"scalar\",\n BETWEEN: \"range\",\n BETWEEN_INCLUSIVE: \"range\",\n IS_NULL: \"none\",\n NOT_NULL: \"none\",\n IS_UNCHANGED: \"none\",\n IS_CHANGED: \"none\",\n};\n","import type { Workflow } from \"../types/workflow.js\";\nimport type { Processor } from \"../types/processor.js\";\nimport type { Criterion } from \"../types/criterion.js\";\nimport { MAX_CRITERION_DEPTH } from \"../criteria/operators.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, depth = 0): Criterion {\n if (depth >= MAX_CRITERION_DEPTH) {\n // Tree already exceeds the engine import limit. The semantic validator\n // will report a criterion-depth-limit error; return the node unchanged\n // here to prevent a stack overflow on pathologically nested input.\n return criterion;\n }\n switch (criterion.type) {\n case \"simple\":\n // Spec §4.4: IS_NULL / NOT_NULL ignore `value` at runtime, but OpenAPI\n // marks it required. Force value: null so internal state and wire form\n // agree and round-trips stay exact.\n if (criterion.operation === \"IS_NULL\" || criterion.operation === \"NOT_NULL\") {\n return { ...criterion, value: null };\n }\n return criterion;\n case \"group\":\n return {\n ...criterion,\n conditions: criterion.conditions.map((c) => normalizeCriterion(c, depth + 1)),\n };\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, depth + 1) }\n : {}),\n },\n };\n return out;\n }\n case \"lifecycle\":\n if (criterion.operation === \"IS_NULL\" || criterion.operation === \"NOT_NULL\") {\n return { ...criterion, value: null };\n }\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","// JSONPath subset supported by cyoda-go's gjson translator\n// (`internal/match/match.go:40-59`). The engine does NOT run a full JSONPath\n// parser: filters and recursive descent silently fail. See spec §5.\n//\n// Accept: `$`, `$.field`, `$.a.b.c`, `$.list[0]`, `$.list[0].x`,\n// `$.list[*]`, `$.list[*].x`.\n// Reject: recursive descent (`..`), filter expressions (`[?(@…)]`),\n// bracketed quoted keys (`['foo']`), missing `$` root, malformed\n// brackets, segment names with whitespace or reserved punctuation.\n\nexport type JsonPathRejectReason =\n | \"empty\"\n | \"missing-root\"\n | \"recursive-descent\"\n | \"filter-expression\"\n | \"malformed\";\n\nexport type JsonPathValidationResult =\n | { ok: true }\n | { ok: false; reason: JsonPathRejectReason };\n\nconst SEGMENT_RE = /^[A-Za-z_][A-Za-z0-9_-]*$/;\nconst INDEX_RE = /^(?:\\d+|\\*)$/;\n\nexport function validateJsonPathSubset(path: string): JsonPathValidationResult {\n if (path.length === 0) return { ok: false, reason: \"empty\" };\n if (path[0] !== \"$\") return { ok: false, reason: \"missing-root\" };\n\n // Bare root.\n if (path === \"$\") return { ok: true };\n\n let i = 1;\n while (i < path.length) {\n const ch = path[i];\n\n if (ch === \".\") {\n // Recursive descent.\n if (path[i + 1] === \".\") return { ok: false, reason: \"recursive-descent\" };\n\n // Read a dot-segment.\n i += 1;\n const start = i;\n while (i < path.length && path[i] !== \".\" && path[i] !== \"[\") i += 1;\n const segment = path.slice(start, i);\n if (!SEGMENT_RE.test(segment)) return { ok: false, reason: \"malformed\" };\n continue;\n }\n\n if (ch === \"[\") {\n // Filter expression — gjson translator does not rewrite these.\n if (path[i + 1] === \"?\") return { ok: false, reason: \"filter-expression\" };\n // Bracketed quoted keys not supported.\n if (path[i + 1] === \"'\" || path[i + 1] === '\"') return { ok: false, reason: \"malformed\" };\n\n const end = path.indexOf(\"]\", i);\n if (end === -1) return { ok: false, reason: \"malformed\" };\n const inner = path.slice(i + 1, end);\n if (!INDEX_RE.test(inner)) return { ok: false, reason: \"malformed\" };\n i = end + 1;\n continue;\n }\n\n return { ok: false, reason: \"malformed\" };\n }\n\n return { ok: true };\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 { NAME_REGEX } from \"../schema/name.js\";\nimport { MAX_CRITERION_DEPTH } from \"../criteria/operators.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 depth = 0,\n): Generator<{ criterion: Criterion; where: CriterionLocation }> {\n yield { criterion: c, where };\n if (depth >= MAX_CRITERION_DEPTH) {\n // Tree already exceeds the engine limit. The iterative criterionMaxDepth\n // check in criterionDepthRules will report the error; stop here to\n // prevent a stack overflow on pathologically nested input.\n return;\n }\n if (c.type === \"group\") {\n for (const child of c.conditions) yield* walkInner(child, where, depth + 1);\n } else if (c.type === \"function\" && c.function.criterion) {\n yield* walkInner(c.function.criterion, where, depth + 1);\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 {\n CRITERION_DEPTH_WARNING_THRESHOLD,\n MAX_CRITERION_DEPTH,\n UNSUPPORTED_OPERATORS,\n} from \"../criteria/operators.js\";\nimport { validateJsonPathSubset } from \"../criteria/jsonPathSubset.js\";\nimport { idFor as identityIdFor } from \"../identity/id-for.js\";\nimport type { Criterion } from \"../types/criterion.js\";\nimport type { WorkflowEditorDocument } from \"../types/editor.js\";\nimport type { WorkflowSession } from \"../types/session.js\";\nimport type { ValidationIssue } from \"../types/validation.js\";\nimport type { Transition, 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 issues.push(...criterionDepthRules(session));\n issues.push(...automatedOrderingRules(session, doc));\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 (\n p.type === \"externalized\" &&\n p.startNewTxOnDispatch === true &&\n p.executionMode !== \"COMMIT_BEFORE_DISPATCH\"\n ) {\n issues.push({\n severity: \"warning\",\n code: \"start-new-tx-without-commit-before-dispatch\",\n message: `Processor \"${p.name}\" sets startNewTxOnDispatch but executionMode is not COMMIT_BEFORE_DISPATCH.`,\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 const arrPathCheck = validateJsonPathSubset(criterion.jsonPath);\n if (!arrPathCheck.ok) {\n issues.push({\n severity: \"error\",\n code: \"invalid-jsonpath-subset\",\n message: `Array criterion jsonPath \"${criterion.jsonPath}\" is not in the supported subset (${arrPathCheck.reason}) (at ${describe(where)}).`,\n detail: { jsonPath: criterion.jsonPath, reason: arrPathCheck.reason },\n });\n }\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 }\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 if (UNSUPPORTED_OPERATORS.has(criterion.operation)) {\n issues.push({\n severity: \"warning\",\n code: \"unsupported-operator\",\n message: `Operator \"${criterion.operation}\" is not implemented by the engine (at ${describe(where)}).`,\n detail: { operation: criterion.operation },\n });\n }\n break;\n case \"group\":\n if (criterion.operator === \"NOT\") {\n issues.push({\n severity: \"warning\",\n code: \"unsupported-group-operator\",\n message: `Group operator \"NOT\" is not implemented by the engine (at ${describe(where)}).`,\n detail: { operator: \"NOT\" },\n });\n if (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 }\n break;\n case \"simple\": {\n const pathCheck = validateJsonPathSubset(criterion.jsonPath);\n if (!pathCheck.ok) {\n issues.push({\n severity: \"error\",\n code: \"invalid-jsonpath-subset\",\n message: `Simple criterion jsonPath \"${criterion.jsonPath}\" is not in the supported subset (${pathCheck.reason}) (at ${describe(where)}).`,\n detail: { jsonPath: criterion.jsonPath, reason: pathCheck.reason },\n });\n } else if (criterion.jsonPath.startsWith(\"$._meta\")) {\n // Spec §5: lifecycle metadata is only accessible via LifecycleCondition;\n // a SimpleCondition on `$._meta.*` resolves to a literal data field and\n // will never match.\n issues.push({\n severity: \"warning\",\n code: \"lifecycle-path-in-simple\",\n message: `Simple criterion path \"${criterion.jsonPath}\" looks like a lifecycle path; use a lifecycle criterion instead (at ${describe(where)}).`,\n detail: { jsonPath: criterion.jsonPath },\n });\n }\n\n if (UNSUPPORTED_OPERATORS.has(criterion.operation)) {\n issues.push({\n severity: \"warning\",\n code: \"unsupported-operator\",\n message: `Operator \"${criterion.operation}\" is not implemented by the engine (at ${describe(where)}).`,\n detail: { operation: criterion.operation },\n });\n }\n\n if (criterion.operation === \"BETWEEN\" || criterion.operation === \"BETWEEN_INCLUSIVE\") {\n if (!Array.isArray(criterion.value) || criterion.value.length !== 2) {\n issues.push({\n severity: \"error\",\n code: \"simple-between-shape\",\n message: `Operator \"${criterion.operation}\" requires a two-element [low, high] array value (at ${describe(where)}).`,\n detail: { operation: criterion.operation },\n });\n }\n }\n\n if (\n criterion.operation === \"LIKE\" &&\n typeof criterion.value === \"string\" &&\n /[%_]/.test(criterion.value)\n ) {\n // Spec §3.1: LIKE has no escape mechanism; `%` and `_` are always\n // wildcards.\n issues.push({\n severity: \"warning\",\n code: \"like-wildcard-warning\",\n message: `LIKE pattern contains \"%\" or \"_\" which are always wildcards (no escape mechanism) (at ${describe(where)}).`,\n });\n }\n\n if (\n criterion.operation === \"MATCHES_PATTERN\" &&\n typeof criterion.value === \"string\" &&\n criterion.value.length > 0 &&\n !criterion.value.startsWith(\"^\") &&\n !criterion.value.endsWith(\"$\")\n ) {\n // Spec §3.1: MATCHES_PATTERN has no implicit anchoring.\n issues.push({\n severity: \"warning\",\n code: \"matches-pattern-unanchored\",\n message: `MATCHES_PATTERN regex is unanchored; include \"^\"/\"$\" for whole-string match (at ${describe(where)}).`,\n });\n }\n break;\n }\n }\n }\n return issues;\n}\n\nfunction criterionDepthRules(session: WorkflowSession): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n for (const wf of session.workflows) {\n if (wf.criterion) {\n pushDepthIssue(issues, criterionMaxDepth(wf.criterion), {\n kind: \"workflow\",\n workflow: wf.name,\n });\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) continue;\n pushDepthIssue(issues, criterionMaxDepth(t.criterion), {\n kind: \"transition\",\n workflow: wf.name,\n state: stateCode,\n transitionIndex: i,\n transitionName: t.name,\n });\n }\n }\n }\n return issues;\n}\n\nfunction pushDepthIssue(\n issues: ValidationIssue[],\n maxDepth: number,\n where: CriterionLoc,\n): void {\n if (maxDepth >= MAX_CRITERION_DEPTH) {\n issues.push({\n severity: \"error\",\n code: \"criterion-depth-limit\",\n message: `Criterion tree depth ${maxDepth} exceeds engine limit ${MAX_CRITERION_DEPTH} (at ${describe(where)}).`,\n detail: { maxDepth, threshold: MAX_CRITERION_DEPTH },\n });\n }\n if (maxDepth >= CRITERION_DEPTH_WARNING_THRESHOLD) {\n issues.push({\n severity: \"warning\",\n code: \"criterion-depth-warning\",\n message: `Criterion tree depth ${maxDepth} is hard to read; consider flattening (at ${describe(where)}).`,\n detail: { maxDepth, threshold: CRITERION_DEPTH_WARNING_THRESHOLD },\n });\n }\n}\n\nfunction criterionMaxDepth(root: Criterion): number {\n // Iterative DFS: each frame is { node, depth }.\n const stack: { node: Criterion; depth: number }[] = [{ node: root, depth: 1 }];\n let max = 0;\n while (stack.length > 0) {\n const { node, depth } = stack.pop()!;\n if (depth > max) max = depth;\n if (node.type === \"group\") {\n for (const child of node.conditions) stack.push({ node: child, depth: depth + 1 });\n } else if (node.type === \"function\" && node.function.criterion) {\n stack.push({ node: node.function.criterion, depth: depth + 1 });\n }\n }\n return max;\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\nfunction transitionTargetId(\n doc: WorkflowEditorDocument | undefined,\n workflow: string,\n state: string,\n declarationIndex: number,\n): { targetId?: string } {\n if (!doc) return {};\n const id = identityIdFor(doc.meta, {\n kind: \"transition\",\n workflow,\n state,\n transitionName: \"\",\n ordinal: declarationIndex,\n });\n return id ? { targetId: id } : {};\n}\n\nfunction automatedOrderingRules(\n session: WorkflowSession,\n doc?: WorkflowEditorDocument,\n): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n for (const wf of session.workflows) {\n for (const [stateCode, state] of Object.entries(wf.states)) {\n const automated: Array<{ index: number; t: Transition }> = [];\n state.transitions.forEach((t, index) => {\n if (t.manual !== true && t.disabled !== true) {\n automated.push({ index, t });\n }\n });\n\n const nullIdx = automated.findIndex(({ t }) => t.criterion === undefined);\n if (nullIdx === -1 || nullIdx === automated.length - 1) continue;\n\n const nullEntry = automated[nullIdx]!;\n issues.push({\n severity: \"warning\",\n code: \"null-criterion-not-last\",\n message: `Transition \"${nullEntry.t.name}\" on state \"${stateCode}\" is automated and has no criterion, so it always fires; later automated transitions on this state are unreachable.`,\n ...transitionTargetId(doc, wf.name, stateCode, nullEntry.index),\n detail: {\n workflow: wf.name,\n state: stateCode,\n transitionName: nullEntry.t.name,\n },\n });\n\n for (let j = nullIdx + 1; j < automated.length; j++) {\n const dead = automated[j]!;\n issues.push({\n severity: \"warning\",\n code: \"unreachable-automated-transition\",\n message: `Transition \"${dead.t.name}\" on state \"${stateCode}\" is unreachable: an earlier automated transition (\"${nullEntry.t.name}\") has no criterion and will always fire first.`,\n ...transitionTargetId(doc, wf.name, stateCode, dead.index),\n detail: {\n workflow: wf.name,\n state: stateCode,\n transitionName: dead.t.name,\n blockedBy: nullEntry.t.name,\n },\n });\n }\n }\n }\n return issues;\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\n/** Maximum JSON string length accepted by the parser (5 MB). */\nexport const MAX_JSON_BYTES = 5 * 1024 * 1024;\n\n/**\n * Maximum JSON object/array nesting depth accepted before any recursive\n * processing begins. Prevents stack overflows in `normalizeOperatorAlias`,\n * Zod's recursive criterion schema, and downstream traversal helpers.\n */\nexport const MAX_JSON_OBJECT_DEPTH = 200;\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 * Iterative DFS that returns `true` when any node in the JSON tree is nested\n * more than `limit` levels deep. Never recurses — safe for any input depth.\n */\nfunction exceedsObjectDepth(value: unknown, limit: number): boolean {\n const stack: { val: unknown; depth: number }[] = [{ val: value, depth: 1 }];\n while (stack.length > 0) {\n const { val, depth } = stack.pop()!;\n if (depth > limit) return true;\n if (typeof val !== \"object\" || val === null) continue;\n const children = Array.isArray(val) ? val : Object.values(val as Record<string, unknown>);\n for (const child of children) {\n if (typeof child === \"object\" && child !== null) {\n stack.push({ val: child, depth: depth + 1 });\n }\n }\n }\n return false;\n}\n\n/**\n * Parse a Cyoda import-payload JSON string into a WorkflowEditorDocument.\n * Pipeline: size guard → JSON.parse → depth guard → operator-alias normalisation\n * → Zod → input normalisation → assignSyntheticIds → semantic validation.\n */\nexport function parseImportPayload(\n json: string,\n prior?: EditorMetadata,\n): ParseResult<ImportPayload> {\n if (json.length > MAX_JSON_BYTES) {\n throw new ParseJsonError(\n `Workflow JSON exceeds the maximum allowed size of ${MAX_JSON_BYTES / (1024 * 1024)} MB.`,\n );\n }\n\n const parsed = parseJsonSafe(json);\n if (!parsed.ok) {\n throw new ParseJsonError(`Invalid JSON: ${parsed.err}`);\n }\n\n if (exceedsObjectDepth(parsed.value, MAX_JSON_OBJECT_DEPTH)) {\n throw new ParseJsonError(\n `Workflow JSON nesting depth exceeds the maximum allowed depth of ${MAX_JSON_OBJECT_DEPTH}.`,\n );\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(coerceCanonicalDefaults(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\n/**\n * Pre-schema coercion for canonical Cyoda workflow payloads that omit fields\n * the schema considers required with a known safe default.\n *\n * - Processor objects with a `name` but no `type` default to `\"externalized\"`.\n * The `disabled` field on transitions is handled by `z.boolean().default(false)`\n * directly in the schema.\n *\n * This runs before Zod validation on the raw parsed value so we can keep the\n * discriminated union schema unchanged and preserve round-trip semantics.\n */\nfunction coerceCanonicalDefaults(value: unknown): unknown {\n if (!isObj(value)) return value;\n const v = value as Record<string, unknown>;\n if (!Array.isArray(v[\"workflows\"])) return value;\n return {\n ...v,\n workflows: v[\"workflows\"].map((wf) => {\n if (!isObj(wf)) return wf;\n const w = wf as Record<string, unknown>;\n if (!isObj(w[\"states\"])) return wf;\n const states = w[\"states\"] as Record<string, unknown>;\n const nextStates: Record<string, unknown> = {};\n for (const [code, state] of Object.entries(states)) {\n if (!isObj(state)) { nextStates[code] = state; continue; }\n const s = state as Record<string, unknown>;\n if (!Array.isArray(s[\"transitions\"])) { nextStates[code] = state; continue; }\n nextStates[code] = {\n ...s,\n transitions: s[\"transitions\"].map((t) => {\n if (!isObj(t)) return t;\n const tx = t as Record<string, unknown>;\n if (!Array.isArray(tx[\"processors\"])) return t;\n return {\n ...tx,\n processors: tx[\"processors\"].map((p) => {\n if (!isObj(p)) return p;\n const proc = p as Record<string, unknown>;\n if (typeof proc[\"type\"] === \"string\") return p;\n return { type: \"externalized\", ...proc };\n }),\n };\n }),\n };\n }\n return { ...w, states: nextStates };\n }),\n };\n}\n\nfunction isObj(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\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 // Spec §4.4: emit explicit null for IS_NULL/NOT_NULL to satisfy the\n // OpenAPI `required` constraint on `value`.\n if (c.operation === \"IS_NULL\" || c.operation === \"NOT_NULL\") {\n out[\"value\"] = null;\n } else if (c.value !== undefined) {\n out[\"value\"] = c.value;\n }\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.operation === \"IS_NULL\" || c.operation === \"NOT_NULL\") {\n out[\"value\"] = null;\n } else if (c.value !== undefined) {\n out[\"value\"] = c.value;\n }\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 out[\"executionMode\"] = p.executionMode ?? \"ASYNC_NEW_TX\";\n if (\"startNewTxOnDispatch\" in p && p.startNewTxOnDispatch !== undefined) {\n out[\"startNewTxOnDispatch\"] = p.startNewTxOnDispatch;\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 { 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 { CommentMeta, WorkflowUiMeta, WorkflowEditorDocument } from \"../types/editor.js\";\nimport type { DomainPatch } from \"../types/patch.js\";\nimport type { WorkflowSession } from \"../types/session.js\";\nimport { PatchConflictError } from \"../types/transaction.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\") return applySetEdgeAnchors(doc, patch);\n if (patch.op === \"setNodePosition\") return applySetNodePosition(doc, patch);\n if (patch.op === \"removeNodePosition\") return applyRemoveNodePosition(doc, patch);\n if (patch.op === \"resetLayout\") return applyResetLayout(doc, patch);\n if (patch.op === \"addComment\") return applyAddComment(doc, patch);\n if (patch.op === \"updateComment\") return applyUpdateComment(doc, patch);\n if (patch.op === \"removeComment\") return applyRemoveComment(doc, patch);\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 if (patch.to !== patch.from && patch.to in wf.states) {\n throw new PatchConflictError(\n `State \"${patch.to}\" already exists in workflow \"${patch.workflow}\"`,\n );\n }\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 \"moveTransitionSource\": {\n const wf = draft.workflows.find((w) => w.name === patch.workflow);\n if (!wf) return;\n const fromState = wf.states[patch.fromState];\n const toState = wf.states[patch.toState];\n if (!fromState || !toState) return;\n const idx = fromState.transitions.findIndex((t) => t.name === patch.transitionName);\n if (idx < 0) return;\n if (\n patch.fromState !== patch.toState &&\n toState.transitions.some((t) => t.name === patch.transitionName)\n ) {\n throw new PatchConflictError(\n `Transition \"${patch.transitionName}\" already exists in state \"${patch.toState}\"`,\n );\n }\n const [transition] = fromState.transitions.splice(idx, 1);\n if (transition) toState.transitions.push(transition);\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 preserveMovedTransitionUuid(doc, patch, nextSession, nextMeta);\n const cleanedWorkflowUi = cleanupWorkflowUi(nextMeta.workflowUi, nextSession, nextMeta);\n return {\n session: nextSession,\n meta: { ...nextMeta, workflowUi: cleanedWorkflowUi, 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 applySetNodePosition(\n doc: WorkflowEditorDocument,\n patch: Extract<DomainPatch, { op: \"setNodePosition\" }>,\n): WorkflowEditorDocument {\n const workflowUi = { ...doc.meta.workflowUi };\n const current = workflowUi[patch.workflow] ?? {};\n const nodes = { ...(current.layout?.nodes ?? {}) };\n nodes[patch.stateCode] = { x: patch.x, y: patch.y, pinned: patch.pinned ?? true };\n workflowUi[patch.workflow] = { ...current, layout: { nodes } };\n return {\n session: doc.session,\n meta: { ...doc.meta, workflowUi, revision: doc.meta.revision + 1 },\n };\n}\n\nfunction applyRemoveNodePosition(\n doc: WorkflowEditorDocument,\n patch: Extract<DomainPatch, { op: \"removeNodePosition\" }>,\n): WorkflowEditorDocument {\n const workflowUi = { ...doc.meta.workflowUi };\n const current = workflowUi[patch.workflow] ?? {};\n const nodes = { ...(current.layout?.nodes ?? {}) };\n delete nodes[patch.stateCode];\n workflowUi[patch.workflow] = {\n ...current,\n layout: Object.keys(nodes).length > 0 ? { nodes } : undefined,\n };\n return {\n session: doc.session,\n meta: { ...doc.meta, workflowUi, revision: doc.meta.revision + 1 },\n };\n}\n\nfunction applyResetLayout(\n doc: WorkflowEditorDocument,\n patch: Extract<DomainPatch, { op: \"resetLayout\" }>,\n): WorkflowEditorDocument {\n const workflowUi = { ...doc.meta.workflowUi };\n const current = workflowUi[patch.workflow] ?? {};\n workflowUi[patch.workflow] = { ...current, layout: undefined };\n return {\n session: doc.session,\n meta: { ...doc.meta, workflowUi, revision: doc.meta.revision + 1 },\n };\n}\n\nfunction applyAddComment(\n doc: WorkflowEditorDocument,\n patch: Extract<DomainPatch, { op: \"addComment\" }>,\n): WorkflowEditorDocument {\n const workflowUi = { ...doc.meta.workflowUi };\n const current = workflowUi[patch.workflow] ?? {};\n const comments = { ...(current.comments ?? {}), [patch.comment.id]: patch.comment };\n workflowUi[patch.workflow] = { ...current, comments };\n return {\n session: doc.session,\n meta: { ...doc.meta, workflowUi, revision: doc.meta.revision + 1 },\n };\n}\n\nfunction applyUpdateComment(\n doc: WorkflowEditorDocument,\n patch: Extract<DomainPatch, { op: \"updateComment\" }>,\n): WorkflowEditorDocument {\n const workflowUi = { ...doc.meta.workflowUi };\n const current = workflowUi[patch.workflow] ?? {};\n const existing = current.comments?.[patch.commentId];\n if (!existing) return { ...doc, meta: { ...doc.meta, revision: doc.meta.revision + 1 } };\n const updated: CommentMeta = { ...existing, ...patch.updates, id: existing.id };\n const comments = { ...(current.comments ?? {}), [patch.commentId]: updated };\n workflowUi[patch.workflow] = { ...current, comments };\n return {\n session: doc.session,\n meta: { ...doc.meta, workflowUi, revision: doc.meta.revision + 1 },\n };\n}\n\nfunction applyRemoveComment(\n doc: WorkflowEditorDocument,\n patch: Extract<DomainPatch, { op: \"removeComment\" }>,\n): WorkflowEditorDocument {\n const workflowUi = { ...doc.meta.workflowUi };\n const current = workflowUi[patch.workflow] ?? {};\n const comments = { ...(current.comments ?? {}) };\n delete comments[patch.commentId];\n workflowUi[patch.workflow] = {\n ...current,\n comments: Object.keys(comments).length > 0 ? comments : undefined,\n };\n return {\n session: doc.session,\n meta: { ...doc.meta, workflowUi, revision: doc.meta.revision + 1 },\n };\n}\n\nfunction preserveMovedTransitionUuid(\n priorDoc: WorkflowEditorDocument,\n patch: DomainPatch,\n nextSession: WorkflowSession,\n nextMeta: WorkflowEditorDocument[\"meta\"],\n): void {\n if (patch.op !== \"moveTransitionSource\") return;\n const oldUuid = transitionUuidByName(\n priorDoc,\n patch.workflow,\n patch.fromState,\n patch.transitionName,\n );\n if (!oldUuid) return;\n const newUuid = transitionUuidByNameInSession(\n nextSession,\n nextMeta,\n patch.workflow,\n patch.toState,\n patch.transitionName,\n );\n if (!newUuid || newUuid === oldUuid) return;\n const newPtr = nextMeta.ids.transitions[newUuid];\n if (!newPtr) return;\n\n delete nextMeta.ids.transitions[newUuid];\n nextMeta.ids.transitions[oldUuid] = {\n ...newPtr,\n transitionUuid: oldUuid,\n };\n\n for (const processorPtr of Object.values(nextMeta.ids.processors)) {\n if (processorPtr.transitionUuid === newUuid) {\n processorPtr.transitionUuid = oldUuid;\n }\n }\n for (const criterionPtr of Object.values(nextMeta.ids.criteria)) {\n const host = criterionPtr.host;\n if (\n (host.kind === \"transition\" || host.kind === \"processorConfig\") &&\n host.transitionUuid === newUuid\n ) {\n host.transitionUuid = oldUuid;\n }\n }\n}\n\nfunction transitionUuidByName(\n doc: WorkflowEditorDocument,\n workflow: string,\n state: string,\n transitionName: string,\n): string | null {\n return transitionUuidByNameInSession(doc.session, doc.meta, workflow, state, transitionName);\n}\n\nfunction transitionUuidByNameInSession(\n session: WorkflowSession,\n meta: WorkflowEditorDocument[\"meta\"],\n workflow: string,\n state: string,\n transitionName: string,\n): string | null {\n const wf = session.workflows.find((candidate) => candidate.name === workflow);\n const transitions = wf?.states[state]?.transitions ?? [];\n const index = transitions.findIndex((transition) => transition.name === transitionName);\n if (index < 0) return null;\n const ordered = Object.entries(meta.ids.transitions)\n .filter(([, ptr]) => ptr.workflow === workflow && ptr.state === state)\n .map(([uuid]) => uuid);\n return ordered[index] ?? null;\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\n/**\n * Remove stale layout positions and comments that reference states/transitions\n * no longer present in the session (e.g. after a replaceSession from a JSON edit).\n */\nfunction cleanupWorkflowUi(\n workflowUi: Record<string, WorkflowUiMeta>,\n session: WorkflowSession,\n meta?: WorkflowEditorDocument[\"meta\"],\n): Record<string, WorkflowUiMeta> {\n const wfNames = new Set(session.workflows.map((w) => w.name));\n const result: Record<string, WorkflowUiMeta> = {};\n const validTransitionIdsByWorkflow = new Map<string, Set<string>>();\n if (meta) {\n for (const [uuid, ptr] of Object.entries(meta.ids.transitions)) {\n let set = validTransitionIdsByWorkflow.get(ptr.workflow);\n if (!set) {\n set = new Set<string>();\n validTransitionIdsByWorkflow.set(ptr.workflow, set);\n }\n set.add(uuid);\n }\n }\n\n for (const [wfName, ui] of Object.entries(workflowUi)) {\n if (!wfNames.has(wfName)) continue; // workflow deleted — drop its entire UI meta\n const wf = session.workflows.find((w) => w.name === wfName);\n const existingStates = wf ? new Set(Object.keys(wf.states)) : new Set<string>();\n const allTransitionNames = new Set<string>();\n if (wf) {\n for (const state of Object.values(wf.states)) {\n for (const t of state.transitions) allTransitionNames.add(t.name);\n }\n }\n\n // Clean layout nodes: remove positions for states that no longer exist.\n let layout = ui.layout;\n if (layout?.nodes) {\n const cleanNodes = Object.fromEntries(\n Object.entries(layout.nodes).filter(([code]) => existingStates.has(code)),\n );\n layout = Object.keys(cleanNodes).length > 0 ? { nodes: cleanNodes } : undefined;\n }\n\n // Clean comments: detach comments whose attached state/transition was removed.\n let comments = ui.comments;\n if (comments) {\n const cleanComments: Record<string, CommentMeta> = {};\n for (const [id, c] of Object.entries(comments)) {\n if (\n c.attachedTo?.kind === \"state\" && !existingStates.has(c.attachedTo.stateCode)\n ) {\n // Detach instead of delete — keep the note, just float it.\n cleanComments[id] = { ...c, attachedTo: { kind: \"free\" } };\n } else if (\n c.attachedTo?.kind === \"transition\" &&\n !allTransitionNames.has(c.attachedTo.transitionName)\n ) {\n cleanComments[id] = { ...c, attachedTo: { kind: \"free\" } };\n } else {\n cleanComments[id] = c;\n }\n }\n comments = Object.keys(cleanComments).length > 0 ? cleanComments : undefined;\n }\n\n let edgeAnchors = ui.edgeAnchors;\n if (edgeAnchors && meta) {\n const validTransitionIds = validTransitionIdsByWorkflow.get(wfName) ?? new Set<string>();\n const cleanAnchors = Object.fromEntries(\n Object.entries(edgeAnchors).filter(([transitionUuid]) =>\n validTransitionIds.has(transitionUuid),\n ),\n );\n edgeAnchors = Object.keys(cleanAnchors).length > 0 ? cleanAnchors : undefined;\n }\n\n result[wfName] = { ...ui, layout, comments, edgeAnchors };\n }\n\n return result;\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 * Notes:\n * - `addTransition` and `addProcessor` cannot determine the newly minted UUID\n * from the pre-apply doc alone; callers that need exact inverses for these\n * should use `dispatchTransaction` and supply the inverse explicitly.\n * - `removeWorkflow`, `renameWorkflow`, and `removeState` invert via a captured\n * `replaceSession` snapshot — correct but coarse.\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 \"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 { op: \"setInitialState\", workflow: patch.workflow, stateCode: wf.initialState };\n }\n\n case \"setWorkflowCriterion\": {\n const wf = findWorkflow(doc, patch.workflow);\n if (!wf) return noop();\n return wf.criterion\n ? { op: \"setWorkflowCriterion\", workflow: patch.workflow, criterion: cloneCriterion(wf.criterion) }\n : { op: \"setWorkflowCriterion\", workflow: patch.workflow };\n }\n\n case \"addState\":\n return { op: \"removeState\", workflow: patch.workflow, stateCode: patch.stateCode };\n\n case \"renameState\":\n // Exact inverse: swap from/to. Collision check in apply prevents silent overwrite.\n return { op: \"renameState\", workflow: patch.workflow, from: patch.to, to: patch.from };\n\n case \"addTransition\":\n // Cannot know the minted UUID pre-apply. Callers that need exact undo\n // should use dispatchTransaction and supply { op: \"removeTransition\", transitionUuid }.\n return { op: \"replaceSession\", session: cloneSession(doc) };\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 { op: \"updateTransition\", transitionUuid: patch.transitionUuid, updates: prior };\n }\n\n case \"removeTransition\": {\n // Exact inverse: re-add the transition with its full captured data.\n const loc = locateTransition(doc, patch.transitionUuid);\n if (!loc) return noop();\n const wf = findWorkflow(doc, loc.workflow);\n const state = wf?.states[loc.state];\n const t = state?.transitions[loc.index];\n if (!t) return noop();\n return {\n op: \"addTransition\",\n workflow: loc.workflow,\n fromState: loc.state,\n transition: structuredClone(t),\n };\n }\n\n case \"reorderTransition\": {\n const loc = locateTransition(doc, patch.transitionUuid);\n if (!loc) return noop();\n // UUIDs are positional. After reorder + assignSyntheticIds, the UUID that was at\n // toIndex in the pre-apply doc now points to our moved item. Use that UUID for the inverse.\n const orderedForState: string[] = [];\n for (const [uuid, p] of Object.entries(doc.meta.ids.transitions)) {\n if (p.workflow === patch.workflow && p.state === patch.fromState) {\n orderedForState.push(uuid);\n }\n }\n const uuidAtTarget = orderedForState[patch.toIndex] ?? patch.transitionUuid;\n return {\n op: \"reorderTransition\",\n workflow: patch.workflow,\n fromState: patch.fromState,\n transitionUuid: uuidAtTarget,\n toIndex: loc.index,\n };\n }\n\n case \"moveTransitionSource\":\n return {\n op: \"moveTransitionSource\",\n workflow: patch.workflow,\n fromState: patch.toState,\n toState: patch.fromState,\n transitionName: patch.transitionName,\n };\n\n case \"addProcessor\":\n // Cannot know the minted UUID pre-apply. Use dispatchTransaction for exact undo.\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 { op: \"updateProcessor\", processorUuid: patch.processorUuid, updates: prior };\n }\n\n case \"removeProcessor\": {\n const ptr = doc.meta.ids.processors[patch.processorUuid];\n if (!ptr) return noop();\n const procLoc = locateProcessor(doc, patch.processorUuid);\n if (!procLoc) return noop();\n const wf = findWorkflow(doc, procLoc.workflow);\n const state = wf?.states[procLoc.state];\n const t = state?.transitions[procLoc.transitionIndex];\n const p = t?.processors?.[procLoc.processorIndex];\n if (!p) return noop();\n return {\n op: \"addProcessor\",\n transitionUuid: ptr.transitionUuid,\n processor: structuredClone(p),\n index: procLoc.processorIndex,\n };\n }\n\n case \"reorderProcessor\": {\n const procLoc = locateProcessor(doc, patch.processorUuid);\n if (!procLoc) return noop();\n // Same positional UUID logic as reorderTransition.\n const orderedForTransition: string[] = [];\n for (const [uuid, p] of Object.entries(doc.meta.ids.processors)) {\n if (p.transitionUuid === patch.transitionUuid) orderedForTransition.push(uuid);\n }\n const uuidAtTarget = orderedForTransition[patch.toIndex] ?? patch.processorUuid;\n return {\n op: \"reorderProcessor\",\n transitionUuid: patch.transitionUuid,\n processorUuid: uuidAtTarget,\n toIndex: procLoc.processorIndex,\n };\n }\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 : { op: \"setCriterion\", host: patch.host, path: patch.path, criterion: cloneCriterion(prior) };\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 = 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 case \"setNodePosition\": {\n const prior = doc.meta.workflowUi[patch.workflow]?.layout?.nodes?.[patch.stateCode];\n if (!prior) {\n return { op: \"removeNodePosition\", workflow: patch.workflow, stateCode: patch.stateCode };\n }\n return { op: \"setNodePosition\", workflow: patch.workflow, stateCode: patch.stateCode, ...prior };\n }\n\n case \"removeNodePosition\": {\n const prior = doc.meta.workflowUi[patch.workflow]?.layout?.nodes?.[patch.stateCode];\n if (!prior) return noop();\n return { op: \"setNodePosition\", workflow: patch.workflow, stateCode: patch.stateCode, ...prior };\n }\n\n case \"resetLayout\":\n // Coarse: restores entire session snapshot (layout lives in meta, not session,\n // so this is a no-op for session but correct for meta via replaceSession being\n // handled separately). For now, resetLayout is intentionally not undoable\n // and callers should use silentReplace. Returning noop as a safe fallback.\n return noop();\n\n case \"addComment\":\n return { op: \"removeComment\", workflow: patch.workflow, commentId: patch.comment.id };\n\n case \"updateComment\": {\n const prior = doc.meta.workflowUi[patch.workflow]?.comments?.[patch.commentId];\n if (!prior) return noop();\n const priorUpdates: Partial<typeof prior> = {};\n for (const key of Object.keys(patch.updates) as Array<keyof typeof patch.updates>) {\n (priorUpdates as Record<string, unknown>)[key] = prior[key];\n }\n return { op: \"updateComment\", workflow: patch.workflow, commentId: patch.commentId, updates: priorUpdates };\n }\n\n case \"removeComment\": {\n const prior = doc.meta.workflowUi[patch.workflow]?.comments?.[patch.commentId];\n if (!prior) return noop();\n return { op: \"addComment\", workflow: patch.workflow, comment: structuredClone(prior) };\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 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 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): { workflow: string; state: string; transitionIndex: number; processorIndex: number } | 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 { workflow: tLoc.workflow, state: tLoc.state, transitionIndex: tLoc.index, processorIndex: pIdx };\n}\n\nfunction findTransition(\n doc: WorkflowEditorDocument,\n transitionUuid: string,\n): Transition | undefined {\n const loc = locateTransition(doc, transitionUuid);\n if (!loc) return undefined;\n const wf = findWorkflow(doc, loc.workflow);\n return wf?.states[loc.state]?.transitions[loc.index];\n}\n\nfunction findProcessor(\n doc: WorkflowEditorDocument,\n processorUuid: string,\n): Processor | undefined {\n const loc = locateProcessor(doc, processorUuid);\n if (!loc) return undefined;\n const wf = findWorkflow(doc, loc.workflow);\n const t = wf?.states[loc.state]?.transitions[loc.transitionIndex];\n return t?.processors?.[loc.processorIndex];\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 { WorkflowEditorDocument } from \"../types/editor.js\";\nimport type { PatchTransaction } from \"../types/transaction.js\";\nimport { applyPatch } from \"./apply.js\";\nimport { invertPatch } from \"./invert.js\";\n\n/**\n * Apply all patches in a transaction in sequence and return the resulting doc.\n */\nexport function applyTransaction(\n doc: WorkflowEditorDocument,\n tx: PatchTransaction,\n): WorkflowEditorDocument {\n return tx.patches.reduce((d, p) => applyPatch(d, p), doc);\n}\n\n/**\n * Build the inverse of a transaction.\n *\n * Convention: `tx.inverses` contains the inverse patches in UNDO-APPLICATION\n * ORDER (i.e. the last patch is undone first). `invertTransaction` simply uses\n * `tx.inverses` as the forward patches of the returned transaction.\n *\n * If `tx.inverses` is empty, falls back to computing each inverse\n * individually from `doc` and reversing to get the correct undo order.\n */\nexport function invertTransaction(\n doc: WorkflowEditorDocument,\n tx: PatchTransaction,\n): PatchTransaction {\n if (tx.inverses.length > 0) {\n return {\n summary: `Undo: ${tx.summary}`,\n patches: tx.inverses,\n inverses: tx.patches,\n };\n }\n // Fallback: compute inverses per patch then reverse to get undo-application order.\n const computed = tx.patches.map((p) => invertPatch(doc, p)).reverse();\n return {\n summary: `Undo: ${tx.summary}`,\n patches: computed,\n inverses: tx.patches,\n };\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","import type { Criterion } from \"../types/criterion.js\";\nimport type { OperatorType } from \"../types/operator.js\";\n\nconst OPERATOR_SYMBOL: Readonly<Partial<Record<OperatorType, string>>> = {\n EQUALS: \"=\",\n NOT_EQUAL: \"≠\",\n GREATER_THAN: \">\",\n LESS_THAN: \"<\",\n GREATER_OR_EQUAL: \"≥\",\n LESS_OR_EQUAL: \"≤\",\n IEQUALS: \"=\",\n INOT_EQUAL: \"≠\",\n};\n\nexport function describeCriterion(c: Criterion): string {\n switch (c.type) {\n case \"simple\":\n return describeBinary(c.jsonPath, c.operation, c.value);\n case \"group\": {\n const n = c.conditions.length;\n return `${c.operator} (${n} condition${n === 1 ? \"\" : \"s\"})`;\n }\n case \"function\":\n return `Function: ${c.function.name || \"<unnamed>\"}`;\n case \"lifecycle\":\n return describeBinary(c.field, c.operation, c.value);\n case \"array\": {\n const n = c.value.length;\n return `${c.jsonPath} ${c.operation} [${n} value${n === 1 ? \"\" : \"s\"}]`;\n }\n }\n}\n\nfunction describeBinary(lhs: string, op: OperatorType, value: unknown): string {\n if (op === \"IS_NULL\") return `${lhs} IS NULL`;\n if (op === \"NOT_NULL\") return `${lhs} IS NOT NULL`;\n if (op === \"IS_CHANGED\") return `${lhs} CHANGED`;\n if (op === \"IS_UNCHANGED\") return `${lhs} UNCHANGED`;\n if (op === \"BETWEEN\" || op === \"BETWEEN_INCLUSIVE\") {\n const inclusive = op === \"BETWEEN_INCLUSIVE\";\n if (Array.isArray(value) && value.length === 2) {\n return `${lhs} ∈ ${inclusive ? \"[\" : \"(\"}${formatValue(value[0])}, ${formatValue(value[1])}${inclusive ? \"]\" : \")\"}`;\n }\n return `${lhs} ${op} ${formatValue(value)}`;\n }\n const symbol = OPERATOR_SYMBOL[op] ?? op;\n return `${lhs} ${symbol} ${formatValue(value)}`;\n}\n\nfunction formatValue(v: unknown): string {\n if (v === undefined) return \"?\";\n if (typeof v === \"string\") return JSON.stringify(v);\n return JSON.stringify(v);\n}\n"],"mappings":";AA8BO,IAAM,iBAA4C,oBAAI,IAAkB;AAAA,EAC7E;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA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