@stonecrop/stonecrop 0.34.0 → 0.35.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.
@@ -1 +1 @@
1
- {"version":3,"file":"stonecrop.js","names":[],"sources":["../src/client-handler.ts","../src/draft.ts","../src/stores/operation-log.ts","../src/field-triggers.ts","../src/stores/hst.ts","../src/stonecrop.ts","../src/composables/stonecrop.ts","../src/client-action.ts","../src/composables/lazy-link.ts","../src/composables/operation-log.ts","../src/doctype.ts","../src/registry.ts","../src/plugins/index.ts","../src/stores/validation.ts","../src/types/schema-validator.ts","../src/schema-validator.ts","../src/index.ts"],"sourcesContent":["/**\n * clientHandler execution\n * Pure executor for docbuilder-authored client handlers.\n * @packageDocumentation\n */\n\n/**\n * Named capabilities injected into a clientHandler body as function parameters.\n * The caller (the assembly composable) owns what each name resolves to — typically\n * `router`, `record`, `runAction`, and a read-only `graphql`.\n *\n * @public\n */\nexport type ClientHandlerApi = Record<string, unknown>\n\n// AsyncFunction is not a global; reach it via an async function's constructor so authored\n// bodies can use top-level `await` without writing an async wrapper.\n// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- an async function's constructor is always the AsyncFunction constructor\nconst AsyncFunction = Object.getPrototypeOf(async () => {}).constructor as new (\n\t...args: string[]\n) => (...args: unknown[]) => Promise<unknown>\n\n/**\n * Execute a docbuilder-authored `clientHandler` body against an injected API map.\n *\n * `code` is a function *body* (statements), not a full function — authored in the\n * docbuilder code editor and stored on `ActionDefinition.clientHandler`. It is compiled\n * with the AsyncFunction constructor, so `await` works directly. Each key of `api`\n * becomes a parameter name bound to its value, so a handler can reference `router`,\n * `record`, `runAction`, etc. by name.\n *\n * This executor is deliberately concern-free: it performs no routing, dispatch, or HST\n * writes itself — the caller assembles `api`. The injected set is an *intent* contract,\n * not a sandbox (an AsyncFunction body can still reach `fetch`/`window`); enforcement of\n * what a handler may actually do lives server-side, not here.\n *\n * Errors are propagated to the caller as a rejected promise — syntax errors at compile\n * time and thrown errors / rejections at run time — so callers handle both uniformly.\n *\n * @param code - the clientHandler body, e.g. `\"router.push('/users')\"`\n * @param api - named capabilities injected as parameters (default: none)\n * @returns whatever the body returns (typically `void`)\n *\n * @example\n * ```ts\n * await executeClientHandler(\"await runAction('Assign', [record.id])\", { runAction, record })\n * ```\n *\n * @public\n */\nexport async function executeClientHandler(code: string, api: ClientHandlerApi = {}): Promise<unknown> {\n\tconst names = Object.keys(api)\n\tconst fn = new AsyncFunction(...names, code)\n\treturn fn(...names.map(name => api[name]))\n}\n","/**\n * The route identity of a record the user is composing that does not exist on the server yet.\n *\n * Rejected: minting `new-<timestamp>` so a draft had a store key too. Nothing ever created that\n * HST node, so every write to `doctype.<draftId>.<field>` threw on the missing ancestor, and the\n * form's data survived only because Vue cached the empty object the getter returned and the form\n * mutated it in place — any invalidation discarded the edits silently. Seeding the node instead\n * makes the draft a phantom row, because `getRecords` lists every key under the doctype.\n *\n * So a draft is held off-HST by whoever renders the form, and reaches the server as an action\n * carrying no record id, which the write path already reads as \"create\".\n */\n\n/**\n * The record-id segment a draft route carries: `/{doctype}/new`.\n *\n * Route only — never a store key, and never sent: an action dispatched for a draft omits the id\n * rather than sending this.\n *\n * @public\n */\nexport const DRAFT_RECORD_ID = 'new'\n\n/**\n * Whether a record id refers to a record that has not been saved yet.\n *\n * Guard anything that assumes the record exists — fetching it, resolving its links, judging\n * workflow readiness — with this rather than the literal. The shell and this package once spelled\n * the rule differently, which left every guard here dead.\n *\n * @param recordId - The record id to test\n * @returns `true` when the id is the draft segment, `false` for a real identity or no id at all\n *\n * @public\n */\nexport function isDraftRecordId(recordId: string | null | undefined): boolean {\n\treturn recordId === DRAFT_RECORD_ID\n}\n","import { defineStore } from 'pinia'\nimport { ref, computed, watch } from 'vue'\nimport { useLocalStorage } from '@vueuse/core'\n\nimport type { HSTNode } from './hst'\nimport type {\n\tCrossTabMessage,\n\tHSTOperation,\n\tHSTOperationInput,\n\tOperationLogConfig,\n\tOperationLogSnapshot,\n\tOperationSource,\n\tUndoRedoState,\n} from '../types/operation-log'\n\n/**\n * Generate a UUID using crypto API or fallback\n */\nfunction generateId(): string {\n\tif (typeof crypto !== 'undefined' && crypto.randomUUID) {\n\t\treturn crypto.randomUUID()\n\t}\n\t// Fallback for environments without crypto.randomUUID\n\treturn `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`\n}\n\n/**\n * Serialize a message for BroadcastChannel\n * Converts Date objects to ISO strings for structured clone compatibility\n */\ntype SerializedOperation = Omit<HSTOperation, 'timestamp'> & { timestamp: string }\ntype SerializedCrossTabMessage = Omit<CrossTabMessage, 'timestamp' | 'operation' | 'operations'> & {\n\ttimestamp: string\n\toperation?: SerializedOperation\n\toperations?: SerializedOperation[]\n}\n\nfunction serializeForBroadcast(message: CrossTabMessage): SerializedCrossTabMessage {\n\tconst serialized: SerializedCrossTabMessage = {\n\t\ttype: message.type,\n\t\tclientId: message.clientId,\n\t\ttimestamp: message.timestamp.toISOString(),\n\t}\n\n\tif (message.operation) {\n\t\tserialized.operation = {\n\t\t\t...message.operation,\n\t\t\ttimestamp: message.operation.timestamp.toISOString(),\n\t\t}\n\t}\n\n\tif (message.operations) {\n\t\tserialized.operations = message.operations.map(op => ({\n\t\t\t...op,\n\t\t\ttimestamp: op.timestamp.toISOString(),\n\t\t}))\n\t}\n\n\treturn serialized\n}\n\n/**\n * Deserialize a message from BroadcastChannel\n * Converts ISO strings back to Date objects\n */\nfunction deserializeFromBroadcast(serialized: SerializedCrossTabMessage): CrossTabMessage {\n\tconst message: CrossTabMessage = {\n\t\ttype: serialized.type,\n\t\tclientId: serialized.clientId,\n\t\ttimestamp: new Date(serialized.timestamp),\n\t}\n\n\tif (serialized.operation) {\n\t\tmessage.operation = {\n\t\t\t...serialized.operation,\n\t\t\ttimestamp: new Date(serialized.operation.timestamp),\n\t\t}\n\t}\n\n\tif (serialized.operations) {\n\t\tmessage.operations = serialized.operations.map(op => ({\n\t\t\t...op,\n\t\t\ttimestamp: new Date(op.timestamp),\n\t\t}))\n\t}\n\n\treturn message\n}\n\n/**\n * Revert an operation (apply beforeValue)\n */\nfunction revertOperation(operation: HSTOperation, store: HSTNode) {\n\tif ((operation.type === 'set' || operation.type === 'delete') && store && typeof store.set === 'function') {\n\t\tstore.set(operation.path, operation.beforeValue, 'undo')\n\t}\n}\n\n/**\n * Apply an operation (apply afterValue)\n */\nfunction applyOperation(operation: HSTOperation, store: HSTNode) {\n\tif ((operation.type === 'set' || operation.type === 'delete') && store && typeof store.set === 'function') {\n\t\tstore.set(operation.path, operation.afterValue, 'redo')\n\t}\n}\n\n/**\n * Global HST Operation Log Store\n * Tracks all mutations with full metadata for undo/redo, sync, and audit\n *\n * @public\n */\nexport const useOperationLogStore = defineStore('hst-operation-log', () => {\n\t// Configuration\n\tconst config = ref<OperationLogConfig>({\n\t\tmaxOperations: 100,\n\t\tenableCrossTabSync: true,\n\t\tenablePersistence: false,\n\t\tpersistenceKeyPrefix: 'stonecrop-ops',\n\t})\n\n\t// State\n\tconst operations = ref<HSTOperation[]>([])\n\tconst currentIndex = ref(-1) // Points to the last applied operation\n\tconst clientId = ref(generateId())\n\tconst batchMode = ref(false)\n\tconst batchStack = ref<{ id: string; operations: HSTOperation[] }[]>([])\n\n\t// Computed\n\tconst canUndo = computed(() => {\n\t\t// Can undo if there are operations and we're not at the beginning\n\t\tif (currentIndex.value < 0) return false\n\n\t\t// Check if the operation at currentIndex is reversible\n\t\tconst operation = operations.value[currentIndex.value]\n\t\treturn operation?.reversible ?? false\n\t})\n\n\tconst canRedo = computed(() => {\n\t\t// Can redo if there are operations ahead of current index\n\t\treturn currentIndex.value < operations.value.length - 1\n\t})\n\n\tconst undoCount = computed(() => {\n\t\tlet count = 0\n\t\tfor (let i = currentIndex.value; i >= 0; i--) {\n\t\t\tif (operations.value[i]?.reversible) count++\n\t\t\telse break\n\t\t}\n\t\treturn count\n\t})\n\n\tconst redoCount = computed(() => {\n\t\treturn operations.value.length - 1 - currentIndex.value\n\t})\n\n\tconst undoRedoState = computed((): UndoRedoState => ({\n\t\tcanUndo: canUndo.value,\n\t\tcanRedo: canRedo.value,\n\t\tundoCount: undoCount.value,\n\t\tredoCount: redoCount.value,\n\t\tcurrentIndex: currentIndex.value,\n\t}))\n\n\t// Core Methods\n\n\t/**\n\t * Configure the operation log\n\t */\n\tfunction configure(options: Partial<OperationLogConfig>) {\n\t\tconfig.value = { ...config.value, ...options }\n\n\t\t// Set up persistence if enabled\n\t\tif (config.value.enablePersistence) {\n\t\t\tloadFromPersistence()\n\t\t\tsetupPersistenceWatcher()\n\t\t}\n\n\t\t// Set up cross-tab sync if enabled\n\t\tif (config.value.enableCrossTabSync) {\n\t\t\tsetupCrossTabSync()\n\t\t}\n\t}\n\n\t/**\n\t * Add an operation to the log\n\t */\n\tfunction addOperation(operation: HSTOperationInput, source: OperationSource = 'user') {\n\t\tconst fullOperation: HSTOperation = {\n\t\t\t...operation,\n\t\t\tid: generateId(),\n\t\t\ttimestamp: new Date(),\n\t\t\tsource: source,\n\t\t\tuserId: config.value.userId,\n\t\t}\n\n\t\t// Apply filter if configured\n\t\tif (config.value.operationFilter && !config.value.operationFilter(fullOperation)) {\n\t\t\treturn fullOperation.id\n\t\t}\n\n\t\t// If in batch mode, collect operations in current batch\n\t\tif (batchMode.value && batchStack.value.length > 0) {\n\t\t\tbatchStack.value[batchStack.value.length - 1].operations.push(fullOperation)\n\t\t\treturn fullOperation.id\n\t\t}\n\n\t\t// Remove any operations after current index (they become invalid after new operation)\n\t\tif (currentIndex.value < operations.value.length - 1) {\n\t\t\toperations.value = operations.value.slice(0, currentIndex.value + 1)\n\t\t}\n\n\t\t// Add new operation\n\t\toperations.value.push(fullOperation)\n\t\tcurrentIndex.value++\n\n\t\t// Enforce max operations limit\n\t\tif (config.value.maxOperations && operations.value.length > config.value.maxOperations) {\n\t\t\tconst overflow = operations.value.length - config.value.maxOperations\n\t\t\toperations.value = operations.value.slice(overflow)\n\t\t\tcurrentIndex.value -= overflow\n\t\t}\n\n\t\t// Broadcast to other tabs\n\t\tif (config.value.enableCrossTabSync) {\n\t\t\tbroadcastOperation(fullOperation)\n\t\t}\n\n\t\treturn fullOperation.id\n\t}\n\n\t/**\n\t * Start batch mode - collect multiple operations\n\t */\n\tfunction startBatch() {\n\t\tbatchMode.value = true\n\t\tbatchStack.value.push({\n\t\t\tid: generateId(),\n\t\t\toperations: [],\n\t\t})\n\t}\n\n\t/**\n\t * Commit batch - create a single batch operation\n\t */\n\tfunction commitBatch(description?: string): string | null {\n\t\tif (!batchMode.value || batchStack.value.length === 0) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst currentBatchData = batchStack.value.pop()!\n\t\tconst batchOperations = currentBatchData.operations\n\n\t\tif (batchOperations.length === 0) {\n\t\t\t// Empty batch - just pop and continue if there are outer batches\n\t\t\tif (batchStack.value.length === 0) {\n\t\t\t\tbatchMode.value = false\n\t\t\t}\n\t\t\treturn null\n\t\t}\n\n\t\tconst batchId = currentBatchData.id\n\t\tconst allReversible = batchOperations.every(op => op.reversible)\n\n\t\t// Create ancestor batch operation\n\t\tconst batchOperation: HSTOperation = {\n\t\t\tid: batchId,\n\t\t\ttype: 'batch',\n\t\t\tpath: '', // Batch doesn't have a single path\n\t\t\tfieldname: '',\n\t\t\tbeforeValue: null,\n\t\t\tafterValue: null,\n\t\t\tdoctype: batchOperations[0]?.doctype || '',\n\t\t\ttimestamp: new Date(),\n\t\t\tsource: 'user',\n\t\t\treversible: allReversible,\n\t\t\tirreversibleReason: allReversible ? undefined : 'Contains irreversible operations',\n\t\t\tdescendantOperationIds: batchOperations.map(op => op.id),\n\t\t\tmetadata: { description },\n\t\t}\n\n\t\t// Add ancestor operation ID to all descendants\n\t\tbatchOperations.forEach(op => {\n\t\t\top.ancestorOperationId = batchId\n\t\t})\n\n\t\t// If we're inside a ancestor batch, add this batch as a descendant of the ancestor\n\t\tif (batchStack.value.length > 0) {\n\t\t\t// Nested batch - add the batch operation to the ancestor batch\n\t\t\tbatchStack.value[batchStack.value.length - 1].operations.push(batchOperation)\n\t\t} else {\n\t\t\t// Top-level batch - add to the operations log\n\t\t\toperations.value.push(...batchOperations, batchOperation)\n\t\t\tcurrentIndex.value = operations.value.length - 1\n\t\t}\n\n\t\t// Broadcast batch\n\t\tif (config.value.enableCrossTabSync) {\n\t\t\tbroadcastBatch(batchOperations, batchOperation)\n\t\t}\n\n\t\t// If no more batches on stack, exit batch mode\n\t\tif (batchStack.value.length === 0) {\n\t\t\tbatchMode.value = false\n\t\t}\n\n\t\treturn batchId\n\t}\n\n\t/**\n\t * Cancel batch mode without committing\n\t */\n\tfunction cancelBatch() {\n\t\tbatchStack.value = []\n\t\tbatchMode.value = false\n\t}\n\n\t/**\n\t * Undo the last operation\n\t */\n\tfunction undo(store: HSTNode): boolean {\n\t\tif (!canUndo.value) return false\n\n\t\tconst operation = operations.value[currentIndex.value]\n\n\t\tif (!operation.reversible) {\n\t\t\t// Warn about irreversible operation\n\t\t\tif (typeof console !== 'undefined' && operation.irreversibleReason) {\n\t\t\t\tconsole.warn('Cannot undo irreversible operation:', operation.irreversibleReason)\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\n\t\ttry {\n\t\t\t// Handle batch operations\n\t\t\tif (operation.type === 'batch' && operation.descendantOperationIds) {\n\t\t\t\t// Undo all descendant operations in reverse order\n\t\t\t\tfor (let i = operation.descendantOperationIds.length - 1; i >= 0; i--) {\n\t\t\t\t\tconst descendantId = operation.descendantOperationIds[i]\n\t\t\t\t\tconst descendantOp = operations.value.find(op => op.id === descendantId)\n\t\t\t\t\tif (descendantOp) {\n\t\t\t\t\t\trevertOperation(descendantOp, store)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Undo single operation\n\t\t\t\trevertOperation(operation, store)\n\t\t\t}\n\n\t\t\tcurrentIndex.value--\n\n\t\t\t// Broadcast undo to other tabs\n\t\t\tif (config.value.enableCrossTabSync) {\n\t\t\t\tbroadcastUndo(operation)\n\t\t\t}\n\n\t\t\treturn true\n\t\t} catch (error) {\n\t\t\t// Log error in development\n\t\t\tif (typeof console !== 'undefined') {\n\t\t\t\tconsole.error('Undo failed:', error)\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\n\t/**\n\t * Redo the next operation\n\t */\n\tfunction redo(store: HSTNode): boolean {\n\t\tif (!canRedo.value) return false\n\n\t\tconst operation = operations.value[currentIndex.value + 1]\n\n\t\ttry {\n\t\t\t// Handle batch operations\n\t\t\tif (operation.type === 'batch' && operation.descendantOperationIds) {\n\t\t\t\t// Redo all descendant operations in order\n\t\t\t\tfor (const descendantId of operation.descendantOperationIds) {\n\t\t\t\t\tconst descendantOp = operations.value.find(op => op.id === descendantId)\n\t\t\t\t\tif (descendantOp) {\n\t\t\t\t\t\tapplyOperation(descendantOp, store)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Redo single operation\n\t\t\t\tapplyOperation(operation, store)\n\t\t\t}\n\n\t\t\tcurrentIndex.value++\n\n\t\t\t// Broadcast redo to other tabs\n\t\t\tif (config.value.enableCrossTabSync) {\n\t\t\t\tbroadcastRedo(operation)\n\t\t\t}\n\n\t\t\treturn true\n\t\t} catch (error) {\n\t\t\t// Log error in development\n\t\t\tif (typeof console !== 'undefined') {\n\t\t\t\tconsole.error('Redo failed:', error)\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\n\t/**\n\t * Get operation log snapshot for debugging\n\t */\n\tfunction getSnapshot(): OperationLogSnapshot {\n\t\tconst reversibleOps = operations.value.filter(op => op.reversible).length\n\t\tconst timestamps = operations.value.map(op => op.timestamp)\n\n\t\treturn {\n\t\t\toperations: [...operations.value],\n\t\t\tcurrentIndex: currentIndex.value,\n\t\t\ttotalOperations: operations.value.length,\n\t\t\treversibleOperations: reversibleOps,\n\t\t\tirreversibleOperations: operations.value.length - reversibleOps,\n\t\t\toldestOperation: timestamps.length > 0 ? new Date(Math.min(...timestamps.map(t => t.getTime()))) : undefined,\n\t\t\tnewestOperation: timestamps.length > 0 ? new Date(Math.max(...timestamps.map(t => t.getTime()))) : undefined,\n\t\t}\n\t}\n\n\t/**\n\t * Clear all operations\n\t */\n\tfunction clear() {\n\t\toperations.value = []\n\t\tcurrentIndex.value = -1\n\t}\n\n\t/**\n\t * Get operations for a specific doctype and recordId\n\t */\n\tfunction getOperationsFor(doctype: string, recordId?: string): HSTOperation[] {\n\t\treturn operations.value.filter(op => op.doctype === doctype && (recordId === undefined || op.recordId === recordId))\n\t}\n\n\t/**\n\t * Mark an operation as irreversible\n\t * @param operationId - The ID of the operation to mark\n\t * @param reason - The reason why the operation is irreversible\n\t */\n\tfunction markIrreversible(operationId: string, reason: string) {\n\t\tconst operation = operations.value.find(op => op.id === operationId)\n\t\tif (operation) {\n\t\t\toperation.reversible = false\n\t\t\toperation.irreversibleReason = reason\n\t\t}\n\t}\n\n\t/**\n\t * Log an action execution (stateless actions like print, email, etc.)\n\t * These operations are tracked but typically not reversible\n\t * @param doctype - The doctype the action was executed on\n\t * @param actionName - The name of the action that was executed\n\t * @param recordIds - Optional array of record IDs the action was executed on\n\t * @param result - The result of the action execution\n\t * @param error - Optional error message if action failed\n\t * @returns The operation ID\n\t */\n\tfunction logAction(\n\t\tdoctype: string,\n\t\tactionName: string,\n\t\trecordIds?: string[],\n\t\tresult: 'success' | 'failure' | 'pending' = 'success',\n\t\terror?: string\n\t): string {\n\t\tconst operation: HSTOperationInput = {\n\t\t\ttype: 'action',\n\t\t\tpath: recordIds && recordIds.length > 0 ? `${doctype}.${recordIds[0]}` : doctype,\n\t\t\tfieldname: '',\n\t\t\tbeforeValue: null,\n\t\t\tafterValue: null,\n\t\t\tdoctype,\n\t\t\trecordId: recordIds && recordIds.length > 0 ? recordIds[0] : undefined,\n\t\t\treversible: false, // Actions are typically not reversible\n\t\t\tactionName,\n\t\t\tactionRecordIds: recordIds,\n\t\t\tactionResult: result,\n\t\t\tactionError: error,\n\t\t}\n\n\t\treturn addOperation(operation)\n\t}\n\n\t// Cross-tab synchronization\n\tlet broadcastChannel: BroadcastChannel | null = null\n\n\tfunction setupCrossTabSync() {\n\t\tif (typeof window === 'undefined' || !window.BroadcastChannel) return\n\n\t\tbroadcastChannel = new BroadcastChannel('stonecrop-operation-log')\n\n\t\tbroadcastChannel.addEventListener('message', (event: MessageEvent) => {\n\t\t\tconst rawMessage = event.data\n\n\t\t\tif (!rawMessage || typeof rawMessage !== 'object') return\n\n\t\t\tconst message = deserializeFromBroadcast(rawMessage)\n\n\t\t\t// Ignore messages from this tab\n\t\t\tif (message.clientId === clientId.value) return\n\n\t\t\tif (message.type === 'operation' && message.operation) {\n\t\t\t\t// Add operation from another tab\n\t\t\t\toperations.value.push({ ...message.operation, source: 'sync' })\n\t\t\t\tcurrentIndex.value = operations.value.length - 1\n\t\t\t} else if (message.type === 'operation' && message.operations) {\n\t\t\t\t// Add batch operations from another tab\n\t\t\t\toperations.value.push(\n\t\t\t\t\t...message.operations.map((op): HSTOperation => Object.assign({}, op, { source: 'sync' as const }))\n\t\t\t\t)\n\t\t\t\tcurrentIndex.value = operations.value.length - 1\n\t\t\t}\n\t\t})\n\t}\n\n\tfunction broadcastOperation(operation: HSTOperation) {\n\t\tif (!broadcastChannel) return\n\n\t\tconst message: CrossTabMessage = {\n\t\t\ttype: 'operation',\n\t\t\toperation,\n\t\t\tclientId: clientId.value,\n\t\t\ttimestamp: new Date(),\n\t\t}\n\t\t// oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel.postMessage does not accept targetOrigin; rule only applies to window.postMessage\n\t\tbroadcastChannel.postMessage(serializeForBroadcast(message))\n\t}\n\n\tfunction broadcastBatch(descendantOps: HSTOperation[], batchOp: HSTOperation) {\n\t\tif (!broadcastChannel) return\n\n\t\tconst message: CrossTabMessage = {\n\t\t\ttype: 'operation',\n\t\t\toperations: [...descendantOps, batchOp],\n\t\t\tclientId: clientId.value,\n\t\t\ttimestamp: new Date(),\n\t\t}\n\t\t// oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel.postMessage does not accept targetOrigin; rule only applies to window.postMessage\n\t\tbroadcastChannel.postMessage(serializeForBroadcast(message))\n\t}\n\n\tfunction broadcastUndo(operation: HSTOperation) {\n\t\tif (!broadcastChannel) return\n\n\t\tconst message: CrossTabMessage = {\n\t\t\ttype: 'undo',\n\t\t\toperation,\n\t\t\tclientId: clientId.value,\n\t\t\ttimestamp: new Date(),\n\t\t}\n\t\t// oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel.postMessage does not accept targetOrigin; rule only applies to window.postMessage\n\t\tbroadcastChannel.postMessage(serializeForBroadcast(message))\n\t}\n\n\tfunction broadcastRedo(operation: HSTOperation) {\n\t\tif (!broadcastChannel) return\n\n\t\tconst message: CrossTabMessage = {\n\t\t\ttype: 'redo',\n\t\t\toperation,\n\t\t\tclientId: clientId.value,\n\t\t\ttimestamp: new Date(),\n\t\t}\n\t\t// oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel.postMessage does not accept targetOrigin; rule only applies to window.postMessage\n\t\tbroadcastChannel.postMessage(serializeForBroadcast(message))\n\t}\n\n\t// Persistence using VueUse\n\ttype PersistedData = {\n\t\toperations: Array<Omit<HSTOperation, 'timestamp'> & { timestamp: string }>\n\t\tcurrentIndex: number\n\t}\n\n\tconst persistedData = useLocalStorage<PersistedData | null>('stonecrop-operations', null, {\n\t\tserializer: {\n\t\t\tread: (v: string) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst data = JSON.parse(v)\n\t\t\t\t\treturn data\n\t\t\t\t} catch {\n\t\t\t\t\treturn null\n\t\t\t\t}\n\t\t\t},\n\t\t\twrite: (v: PersistedData | null) => {\n\t\t\t\tif (!v) return ''\n\t\t\t\treturn JSON.stringify(v)\n\t\t\t},\n\t\t},\n\t})\n\n\tfunction loadFromPersistence() {\n\t\tif (typeof window === 'undefined') return\n\n\t\ttry {\n\t\t\tconst data = persistedData.value\n\t\t\tif (data && Array.isArray(data.operations)) {\n\t\t\t\toperations.value = data.operations.map(op => ({\n\t\t\t\t\t...op,\n\t\t\t\t\ttimestamp: new Date(op.timestamp),\n\t\t\t\t}))\n\t\t\t\tcurrentIndex.value = data.currentIndex ?? -1\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Log error in development\n\t\t\tif (typeof console !== 'undefined') {\n\t\t\t\tconsole.error('Failed to load operations from persistence:', error)\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction saveToPersistence() {\n\t\tif (typeof window === 'undefined') return\n\n\t\ttry {\n\t\t\tpersistedData.value = {\n\t\t\t\toperations: operations.value.map(op => ({\n\t\t\t\t\t...op,\n\t\t\t\t\ttimestamp: op.timestamp.toISOString(),\n\t\t\t\t})),\n\t\t\t\tcurrentIndex: currentIndex.value,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Log error in development\n\t\t\tif (typeof console !== 'undefined') {\n\t\t\t\tconsole.error('Failed to save operations to persistence:', error)\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction setupPersistenceWatcher() {\n\t\twatch(\n\t\t\t[operations, currentIndex],\n\t\t\t() => {\n\t\t\t\tif (config.value.enablePersistence) {\n\t\t\t\t\tsaveToPersistence()\n\t\t\t\t}\n\t\t\t},\n\t\t\t{ deep: true }\n\t\t)\n\t}\n\n\treturn {\n\t\t// State\n\t\toperations,\n\t\tcurrentIndex,\n\t\tconfig,\n\t\tclientId,\n\t\tundoRedoState,\n\n\t\t// Computed\n\t\tcanUndo,\n\t\tcanRedo,\n\t\tundoCount,\n\t\tredoCount,\n\n\t\t// Methods\n\t\tconfigure,\n\t\taddOperation,\n\t\tstartBatch,\n\t\tcommitBatch,\n\t\tcancelBatch,\n\t\tundo,\n\t\tredo,\n\t\tclear,\n\t\tgetOperationsFor,\n\t\tgetSnapshot,\n\t\tmarkIrreversible,\n\t\tlogAction,\n\t}\n})\n","import type { Map as ImmutableMap } from 'immutable'\nimport { useOperationLogStore } from './stores/operation-log'\nimport type {\n\tFieldAction,\n\tFieldActionFunction,\n\tFieldChangeContext,\n\tFieldTriggerExecutionResult,\n\tFieldTriggerOptions,\n\tActionExecutionResult,\n\tTransitionChangeContext,\n\tTransitionActionFunction,\n\tTransitionExecutionResult,\n} from './types/field-triggers'\n\n/**\n * Field trigger execution engine integrated with Registry\n * Singleton pattern following Registry implementation\n * @public\n */\nexport class FieldTriggerEngine {\n\t/**\n\t * The root FieldTriggerEngine instance\n\t */\n\tstatic _root: FieldTriggerEngine\n\n\tprivate options!: FieldTriggerOptions & { defaultTimeout: number; debug: boolean; enableRollback: boolean }\n\tprivate doctypeActions = new Map<string, Map<string, string[]>>() // doctype -> action/field -> functions\n\tprivate doctypeTransitions = new Map<string, Map<string, string[]>>() // doctype -> transition -> functions\n\tprivate fieldRollbackConfig = new Map<string, Map<string, boolean>>() // doctype -> field -> rollback enabled\n\tprivate globalActions = new Map<string, FieldActionFunction>() // action name -> function\n\tprivate globalTransitionActions = new Map<string, TransitionActionFunction>() // transition action name -> function\n\n\t/**\n\t * Creates a new FieldTriggerEngine instance (singleton pattern)\n\t * @param options - Configuration options for the field trigger engine\n\t */\n\tconstructor(options: FieldTriggerOptions = {}) {\n\t\tif (FieldTriggerEngine._root) {\n\t\t\treturn FieldTriggerEngine._root\n\t\t}\n\t\tFieldTriggerEngine._root = this\n\t\tthis.options = {\n\t\t\tdefaultTimeout: options.defaultTimeout ?? 5000,\n\t\t\tdebug: options.debug ?? false,\n\t\t\tenableRollback: options.enableRollback ?? true,\n\t\t\terrorHandler: options.errorHandler,\n\t\t}\n\t\treturn this\n\t}\n\n\t/**\n\t * Register a global action function\n\t * @param name - The name of the action\n\t * @param fn - The action function\n\t */\n\tregisterAction(name: string, fn: FieldActionFunction): void {\n\t\tthis.globalActions.set(name, fn)\n\t}\n\n\t/**\n\t * Look up a registered action function by name.\n\t * Returns `undefined` if the action has not been registered.\n\t * @param name - The action name\n\t */\n\tgetAction(name: string): FieldActionFunction | undefined {\n\t\treturn this.globalActions.get(name)\n\t}\n\n\t/**\n\t * Register a global XState transition action function\n\t * @param name - The name of the transition action\n\t * @param fn - The transition action function\n\t */\n\tregisterTransitionAction(name: string, fn: TransitionActionFunction): void {\n\t\tthis.globalTransitionActions.set(name, fn)\n\t}\n\n\t/**\n\t * Configure rollback behavior for a specific field trigger\n\t * @param doctype - The doctype name\n\t * @param fieldname - The field name\n\t * @param enableRollback - Whether to enable rollback\n\t */\n\tsetFieldRollback(doctype: string, fieldname: string, enableRollback: boolean): void {\n\t\tif (!this.fieldRollbackConfig.has(doctype)) {\n\t\t\tthis.fieldRollbackConfig.set(doctype, new Map())\n\t\t}\n\t\tthis.fieldRollbackConfig.get(doctype)!.set(fieldname, enableRollback)\n\t}\n\n\t/**\n\t * Get rollback configuration for a specific field trigger\n\t */\n\tprivate getFieldRollback(doctype: string, fieldname: string): boolean | undefined {\n\t\treturn this.fieldRollbackConfig.get(doctype)?.get(fieldname)\n\t}\n\n\t/**\n\t * Register actions from a doctype - both regular actions and field triggers\n\t * Separates XState transitions (uppercase) from field triggers (lowercase)\n\t * @param doctype - The doctype name\n\t * @param actions - The actions to register (supports Immutable Map, Map, or plain object)\n\t */\n\tregisterDoctypeActions(\n\t\tdoctype: string,\n\t\tactions: ImmutableMap<string, string[]> | Map<string, string[]> | Record<string, string[]> | undefined\n\t): void {\n\t\tif (!actions) return\n\n\t\tconst actionMap = new Map<string, string[]>()\n\t\tconst transitionMap = new Map<string, string[]>()\n\n\t\t// Convert from different Map types to regular Map\n\t\t// Check for Immutable.js Map first (has entrySeq method)\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Immutable.js interop: runtime duck-type check follows\n\t\tconst immutableActions = actions as ImmutableMap<string, string[]>\n\t\tif (typeof immutableActions.entrySeq === 'function') {\n\t\t\t// Immutable Map\n\t\t\timmutableActions.entrySeq().forEach(([key, value]: [string, string[]]) => {\n\t\t\t\tthis.categorizeAction(key, value, actionMap, transitionMap)\n\t\t\t})\n\t\t} else if (actions instanceof Map) {\n\t\t\t// Regular Map\n\t\t\tfor (const [key, value] of actions) {\n\t\t\t\tthis.categorizeAction(key, value, actionMap, transitionMap)\n\t\t\t}\n\t\t} else if (actions && typeof actions === 'object') {\n\t\t\t// Plain object\n\t\t\tObject.entries(actions).forEach(([key, value]) => {\n\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Object.entries value type is unknown at runtime; guarded by typeof object check above\n\t\t\t\tthis.categorizeAction(key, value as string[], actionMap, transitionMap)\n\t\t\t})\n\t\t}\n\n\t\t// Always set the maps, even if empty\n\t\tthis.doctypeActions.set(doctype, actionMap)\n\t\tthis.doctypeTransitions.set(doctype, transitionMap)\n\t}\n\n\t/**\n\t * Categorize an action as either a field trigger or XState transition\n\t * Uses uppercase convention: UPPERCASE = transition, lowercase/mixed = field trigger\n\t */\n\tprivate categorizeAction(\n\t\tkey: string,\n\t\tvalue: string[],\n\t\tactionMap: Map<string, string[]>,\n\t\ttransitionMap: Map<string, string[]>\n\t): void {\n\t\t// Check if the key is all uppercase (XState transition convention)\n\t\tif (this.isTransitionKey(key)) {\n\t\t\ttransitionMap.set(key, value)\n\t\t} else {\n\t\t\tactionMap.set(key, value)\n\t\t}\n\t}\n\n\t/**\n\t * Determine if a key represents an XState transition\n\t * Transitions are identified by being all uppercase\n\t */\n\tprivate isTransitionKey(key: string): boolean {\n\t\t// Must be all uppercase letters/numbers/underscores\n\t\treturn /^[A-Z0-9_]+$/.test(key) && key.length > 0\n\t}\n\n\t/**\n\t * Execute field triggers for a changed field\n\t * @param context - The field change context\n\t * @param options - Execution options (timeout and enableRollback)\n\t */\n\tasync executeFieldTriggers(\n\t\tcontext: FieldChangeContext,\n\t\toptions: { timeout?: number; enableRollback?: boolean } = {}\n\t): Promise<FieldTriggerExecutionResult> {\n\t\tconst { doctype, fieldname } = context\n\t\tconst triggers = this.findFieldTriggers(doctype, fieldname)\n\n\t\tif (triggers.length === 0) {\n\t\t\treturn {\n\t\t\t\tpath: context.path,\n\t\t\t\tactionResults: [],\n\t\t\t\ttotalExecutionTime: 0,\n\t\t\t\tallSucceeded: true,\n\t\t\t\tstoppedOnError: false,\n\t\t\t\trolledBack: false,\n\t\t\t}\n\t\t}\n\n\t\tconst startTime = performance.now()\n\t\tconst actionResults: ActionExecutionResult[] = []\n\t\tlet stoppedOnError = false\n\t\tlet rolledBack = false\n\t\tlet snapshot: any = undefined\n\n\t\t// Determine if rollback is enabled (priority: execution option > field config > global setting)\n\t\tconst fieldRollbackConfig = this.getFieldRollback(doctype, fieldname)\n\t\tconst rollbackEnabled = options.enableRollback ?? fieldRollbackConfig ?? this.options.enableRollback\n\n\t\t// Capture snapshot before executing actions if rollback is enabled\n\t\tif (rollbackEnabled && context.store) {\n\t\t\tsnapshot = this.captureSnapshot(context)\n\t\t}\n\n\t\t// Execute actions sequentially — each action may depend on state set by the previous; stop-on-error semantics require sequential execution\n\t\tfor (const actionName of triggers) {\n\t\t\ttry {\n\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- intentionally sequential; actions are order-dependent and stop on first failure\n\t\t\t\tconst actionResult = await this.executeAction(actionName, context, options.timeout)\n\t\t\t\tactionResults.push(actionResult)\n\n\t\t\t\tif (!actionResult.success) {\n\t\t\t\t\tstoppedOnError = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconst actionError = error instanceof Error ? error : new Error(String(error))\n\t\t\t\tconst errorResult: ActionExecutionResult = {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: actionError,\n\t\t\t\t\texecutionTime: 0,\n\t\t\t\t\taction: actionName,\n\t\t\t\t}\n\t\t\t\tactionResults.push(errorResult)\n\t\t\t\tstoppedOnError = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Perform rollback if enabled, errors occurred, and we have a snapshot\n\t\tif (rollbackEnabled && stoppedOnError && snapshot && context.store) {\n\t\t\ttry {\n\t\t\t\tthis.restoreSnapshot(context, snapshot)\n\t\t\t\trolledBack = true\n\t\t\t} catch (rollbackError) {\n\t\t\t\tconsole.error('[FieldTriggers] Rollback failed:', rollbackError)\n\t\t\t}\n\t\t}\n\n\t\tconst totalExecutionTime = performance.now() - startTime\n\n\t\t// Call global error handler if configured and errors occurred\n\t\tconst failedResults = actionResults.filter(r => !r.success && r.error != null)\n\t\tif (failedResults.length > 0 && this.options.errorHandler) {\n\t\t\tfor (const failedResult of failedResults) {\n\t\t\t\ttry {\n\t\t\t\t\tif (failedResult.error) {\n\t\t\t\t\t\tthis.options.errorHandler(failedResult.error, context, failedResult.action)\n\t\t\t\t\t}\n\t\t\t\t} catch (handlerError) {\n\t\t\t\t\tconsole.error('[FieldTriggers] Error in global error handler:', handlerError)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst result: FieldTriggerExecutionResult = {\n\t\t\tpath: context.path,\n\t\t\tactionResults,\n\t\t\ttotalExecutionTime,\n\t\t\tallSucceeded: actionResults.every(r => r.success),\n\t\t\tstoppedOnError,\n\t\t\trolledBack,\n\t\t\tsnapshot: this.options.debug && rollbackEnabled ? snapshot : undefined, // Only include snapshot in debug mode if rollback is enabled\n\t\t}\n\n\t\treturn result\n\t}\n\n\t/**\n\t * Execute XState transition actions\n\t * Similar to field triggers but specifically for FSM state transitions\n\t * @param context - The transition change context\n\t * @param options - Execution options (timeout)\n\t */\n\tasync executeTransitionActions(\n\t\tcontext: TransitionChangeContext,\n\t\toptions: { timeout?: number } = {}\n\t): Promise<TransitionExecutionResult[]> {\n\t\tconst { doctype, transition } = context\n\t\tconst transitionActions = this.findTransitionActions(doctype, transition)\n\n\t\tif (transitionActions.length === 0) {\n\t\t\treturn []\n\t\t}\n\n\t\tconst results: TransitionExecutionResult[] = []\n\n\t\t// Execute transition actions sequentially — transitions are state-machine steps; order and stop-on-error are required\n\t\tfor (const actionName of transitionActions) {\n\t\t\ttry {\n\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- intentionally sequential; transition actions are order-dependent and stop on first failure\n\t\t\t\tconst actionResult = await this.executeTransitionAction(actionName, context, options.timeout)\n\t\t\t\tresults.push(actionResult)\n\n\t\t\t\tif (!actionResult.success) {\n\t\t\t\t\t// Stop on first error for transitions\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconst actionError = error instanceof Error ? error : new Error(String(error))\n\t\t\t\tconst errorResult: TransitionExecutionResult = {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: actionError,\n\t\t\t\t\texecutionTime: 0,\n\t\t\t\t\taction: actionName,\n\t\t\t\t\ttransition,\n\t\t\t\t}\n\t\t\t\tresults.push(errorResult)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Call global error handler if configured and errors occurred\n\t\tconst failedResults = results.filter(r => !r.success)\n\t\tif (failedResults.length > 0 && this.options.errorHandler) {\n\t\t\tfor (const failedResult of failedResults) {\n\t\t\t\ttry {\n\t\t\t\t\t// Call with FieldChangeContext (base context type)\n\t\t\t\t\tif (failedResult.error) {\n\t\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- action result carries string name; FieldAction cast required by errorHandler signature\n\t\t\t\t\t\tthis.options.errorHandler(failedResult.error, context, failedResult.action as unknown as FieldAction)\n\t\t\t\t\t}\n\t\t\t\t} catch (handlerError) {\n\t\t\t\t\tconsole.error('[FieldTriggers] Error in global error handler:', handlerError)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn results\n\t}\n\n\t/**\n\t * Find transition actions for a specific doctype and transition\n\t */\n\tprivate findTransitionActions(doctype: string, transition: string): string[] {\n\t\tconst doctypeTransitions = this.doctypeTransitions.get(doctype)\n\t\tif (!doctypeTransitions) return []\n\n\t\treturn doctypeTransitions.get(transition) || []\n\t}\n\n\t/**\n\t * Execute a single transition action by name\n\t */\n\tprivate async executeTransitionAction(\n\t\tactionName: string,\n\t\tcontext: TransitionChangeContext,\n\t\ttimeout?: number\n\t): Promise<TransitionExecutionResult> {\n\t\tconst startTime = performance.now()\n\t\tconst actionTimeout = timeout ?? this.options.defaultTimeout\n\n\t\ttry {\n\t\t\t// Look up action in transition-specific registry first, then fall back to global\n\t\t\tlet actionFn = this.globalTransitionActions.get(actionName)\n\n\t\t\t// If not found in transition registry, try regular action registry\n\t\t\t// This allows sharing actions between field triggers and transitions\n\t\t\tif (!actionFn) {\n\t\t\t\tconst regularActionFn = this.globalActions.get(actionName)\n\t\t\t\tif (regularActionFn) {\n\t\t\t\t\t// Wrap regular action to accept TransitionChangeContext\n\t\t\t\t\tactionFn = regularActionFn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!actionFn) {\n\t\t\t\tthrow new Error(`Transition action \"${actionName}\" not found in registry`)\n\t\t\t}\n\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- actionFn may be FieldActionFunction set from globalActions fallback; polymorphic function type\n\t\t\tawait this.executeWithTimeout(actionFn as FieldActionFunction, context, actionTimeout)\n\t\t\tconst executionTime = performance.now() - startTime\n\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\texecutionTime,\n\t\t\t\taction: actionName,\n\t\t\t\ttransition: context.transition,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst executionTime = performance.now() - startTime\n\t\t\tconst actionError = error instanceof Error ? error : new Error(String(error))\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: actionError,\n\t\t\t\texecutionTime,\n\t\t\t\taction: actionName,\n\t\t\t\ttransition: context.transition,\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Find field triggers for a specific doctype and field\n\t * Field triggers are identified by keys that look like field paths (contain dots or match field names)\n\t */\n\tprivate findFieldTriggers(doctype: string, fieldname: string): string[] {\n\t\tconst doctypeActions = this.doctypeActions.get(doctype)\n\t\tif (!doctypeActions) return []\n\n\t\tconst triggers: string[] = []\n\n\t\tfor (const [key, actionNames] of doctypeActions) {\n\t\t\t// Check if this key is a field trigger pattern\n\t\t\tif (this.isFieldTriggerKey(key, fieldname)) {\n\t\t\t\ttriggers.push(...actionNames)\n\t\t\t}\n\t\t}\n\n\t\treturn triggers\n\t}\n\n\t/**\n\t * Determine if an action key represents a field trigger\n\t * Field triggers can be:\n\t * - Exact field name match: \"emailAddress\"\n\t * - Wildcard patterns: \"emailAddress.*\", \"*.is_primary\"\n\t * - Nested field paths: \"address.street\", \"contact.email\"\n\t */\n\tprivate isFieldTriggerKey(key: string, fieldname: string): boolean {\n\t\t// Exact match\n\t\tif (key === fieldname) return true\n\n\t\t// Contains dots - likely a field path pattern\n\t\tif (key.includes('.')) {\n\t\t\treturn this.matchFieldPattern(key, fieldname)\n\t\t}\n\n\t\t// Contains wildcards\n\t\tif (key.includes('*')) {\n\t\t\treturn this.matchFieldPattern(key, fieldname)\n\t\t}\n\n\t\treturn false\n\t}\n\n\t/**\n\t * Match a field pattern against a field name\n\t * Supports wildcards (*) for dynamic segments\n\t */\n\tprivate matchFieldPattern(pattern: string, fieldname: string): boolean {\n\t\tconst patternParts = pattern.split('.')\n\t\tconst fieldParts = fieldname.split('.')\n\n\t\tif (patternParts.length !== fieldParts.length) {\n\t\t\treturn false\n\t\t}\n\n\t\tfor (let i = 0; i < patternParts.length; i++) {\n\t\t\tconst patternPart = patternParts[i]\n\t\t\tconst fieldPart = fieldParts[i]\n\n\t\t\tif (patternPart === '*') {\n\t\t\t\t// Wildcard matches any segment\n\t\t\t\tcontinue\n\t\t\t} else if (patternPart !== fieldPart) {\n\t\t\t\t// Exact match required\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t}\n\n\t/**\n\t * Execute a single action by name\n\t */\n\tprivate async executeAction(\n\t\tactionName: string,\n\t\tcontext: FieldChangeContext,\n\t\ttimeout?: number\n\t): Promise<ActionExecutionResult> {\n\t\tconst startTime = performance.now()\n\t\tconst actionTimeout = timeout ?? this.options.defaultTimeout\n\n\t\ttry {\n\t\t\t// Look up action in global registry\n\t\t\tconst actionFn = this.globalActions.get(actionName)\n\t\t\tif (!actionFn) {\n\t\t\t\tthrow new Error(`Action \"${actionName}\" not found in registry`)\n\t\t\t}\n\n\t\t\tawait this.executeWithTimeout(actionFn, context, actionTimeout)\n\t\t\tconst executionTime = performance.now() - startTime\n\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\texecutionTime,\n\t\t\t\taction: actionName,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst executionTime = performance.now() - startTime\n\t\t\tconst actionError = error instanceof Error ? error : new Error(String(error))\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: actionError,\n\t\t\t\texecutionTime,\n\t\t\t\taction: actionName,\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Execute a function with timeout\n\t */\n\tprivate async executeWithTimeout(\n\t\tfn: FieldActionFunction,\n\t\tcontext: FieldChangeContext,\n\t\ttimeout: number\n\t): Promise<unknown> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timeoutId = setTimeout(() => {\n\t\t\t\treject(new Error(`Action timeout after ${timeout}ms`))\n\t\t\t}, timeout)\n\n\t\t\tPromise.resolve(fn(context))\n\t\t\t\t.then(result => {\n\t\t\t\t\tclearTimeout(timeoutId)\n\t\t\t\t\treturn resolve(result)\n\t\t\t\t})\n\t\t\t\t.catch(error => {\n\t\t\t\t\tclearTimeout(timeoutId)\n\t\t\t\t\treject(error instanceof Error ? error : new Error(String(error)))\n\t\t\t\t})\n\t\t})\n\t}\n\n\t/**\n\t * Capture a snapshot of the record state before executing actions\n\t * This creates a deep copy of the record data for potential rollback\n\t */\n\tprivate captureSnapshot(context: FieldChangeContext): any {\n\t\tif (!context.store || !context.doctype || !context.recordId) {\n\t\t\treturn undefined\n\t\t}\n\n\t\ttry {\n\t\t\t// Get the record path (doctype.recordId)\n\t\t\tconst recordPath = `${context.doctype}.${context.recordId}`\n\n\t\t\t// Get the current record data\n\t\t\tconst recordData = context.store.get(recordPath)\n\n\t\t\tif (!recordData || typeof recordData !== 'object') {\n\t\t\t\treturn undefined\n\t\t\t}\n\n\t\t\t// Create a deep copy to avoid reference issues\n\t\t\treturn JSON.parse(JSON.stringify(recordData))\n\t\t} catch (error) {\n\t\t\tif (this.options.debug) {\n\t\t\t\tconsole.warn('[FieldTriggers] Failed to capture snapshot:', error)\n\t\t\t}\n\t\t\treturn undefined\n\t\t}\n\t}\n\n\t/**\n\t * Restore a previously captured snapshot\n\t * This reverts the record to its state before actions were executed\n\t */\n\tprivate restoreSnapshot(context: FieldChangeContext, snapshot: any): void {\n\t\tif (!context.store || !context.doctype || !context.recordId || !snapshot) {\n\t\t\treturn\n\t\t}\n\n\t\ttry {\n\t\t\t// Get the record path (doctype.recordId)\n\t\t\tconst recordPath = `${context.doctype}.${context.recordId}`\n\n\t\t\t// Restore the entire record from snapshot\n\t\t\tcontext.store.set(recordPath, snapshot)\n\n\t\t\tif (this.options.debug) {\n\t\t\t\t// oxlint-disable-next-line no-console\n\t\t\t\tconsole.log(`[FieldTriggers] Rolled back ${recordPath} to previous state`)\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.error('[FieldTriggers] Failed to restore snapshot:', error)\n\t\t\tthrow error\n\t\t}\n\t}\n}\n\n/**\n * Get or create the global field trigger engine singleton\n * @param options - Optional configuration for the field trigger engine\n * @public\n */\nexport function getGlobalTriggerEngine(options?: FieldTriggerOptions): FieldTriggerEngine {\n\treturn new FieldTriggerEngine(options)\n}\n\n/**\n * Register a global action function that can be used in field triggers\n * @param name - The name of the action to register\n * @param fn - The action function to execute when the trigger fires\n * @public\n */\nexport function registerGlobalAction(name: string, fn: FieldActionFunction): void {\n\tconst engine = getGlobalTriggerEngine()\n\tengine.registerAction(name, fn)\n}\n\n/**\n * Register a global XState transition action function\n * @param name - The name of the transition action to register\n * @param fn - The transition action function to execute\n * @public\n */\nexport function registerTransitionAction(name: string, fn: TransitionActionFunction): void {\n\tconst engine = getGlobalTriggerEngine()\n\tengine.registerTransitionAction(name, fn)\n}\n\n/**\n * Configure rollback behavior for a specific field trigger\n * @param doctype - The doctype name\n * @param fieldname - The field name\n * @param enableRollback - Whether to enable automatic rollback for this field\n * @public\n */\nexport function setFieldRollback(doctype: string, fieldname: string, enableRollback: boolean): void {\n\tconst engine = getGlobalTriggerEngine()\n\tengine.setFieldRollback(doctype, fieldname, enableRollback)\n}\n\n/**\n * Manually trigger an XState transition for a specific doctype/record\n * This can be called directly when you need to execute transition actions programmatically\n * @param doctype - The doctype name\n * @param transition - The XState transition name to trigger\n * @param options - Optional configuration for the transition\n * @public\n */\nexport async function triggerTransition(\n\tdoctype: string,\n\ttransition: string,\n\toptions?: {\n\t\trecordId?: string\n\t\tcurrentState?: string\n\t\ttargetState?: string\n\t\tfsmContext?: Record<string, any>\n\t\tpath?: string\n\t}\n): Promise<any> {\n\tconst engine = getGlobalTriggerEngine()\n\n\tconst context: TransitionChangeContext = {\n\t\tpath: options?.path || (options?.recordId ? `${doctype}.${options.recordId}` : doctype),\n\t\tfieldname: '',\n\t\tbeforeValue: undefined,\n\t\tafterValue: undefined,\n\t\toperation: 'set',\n\t\tdoctype,\n\t\trecordId: options?.recordId,\n\t\ttimestamp: new Date(),\n\t\ttransition,\n\t\tcurrentState: options?.currentState,\n\t\ttargetState: options?.targetState,\n\t\tfsmContext: options?.fsmContext,\n\t}\n\n\treturn await engine.executeTransitionActions(context)\n}\n\n/**\n * Mark a specific operation as irreversible.\n * Used to prevent undo of critical operations like publishing or deletion.\n * @param operationId - The ID of the operation to mark as irreversible\n * @param reason - Human-readable reason why the operation cannot be undone\n * @public\n */\nexport function markOperationIrreversible(operationId: string | undefined, reason: string): void {\n\tif (!operationId) return\n\n\ttry {\n\t\tconst store = useOperationLogStore()\n\t\tstore.markIrreversible(operationId, reason)\n\t} catch {\n\t\t// Operation log is optional\n\t}\n}\n","import { getGlobalTriggerEngine } from '../field-triggers'\nimport { useOperationLogStore } from './operation-log'\nimport type { FieldChangeContext, TransitionChangeContext } from '../types/field-triggers'\nimport type { HSTNode } from '../types/hst'\n\n/**\n * Get the operation log store if available\n */\nfunction getOperationLogStore() {\n\ttry {\n\t\treturn useOperationLogStore()\n\t} catch {\n\t\t// Operation log is optional\n\t\treturn null\n\t}\n}\n\n// Type definitions for global Registry\ninterface RegistryGlobal {\n\tRegistry?: {\n\t\t_root?: {\n\t\t\tregistry: Record<string, any>\n\t\t}\n\t}\n}\n\n// Interface for Immutable-like objects\ninterface ImmutableLike {\n\tget(key: string): any\n\tset(key: string, value: any): ImmutableLike\n\thas(key: string): boolean\n\tsize?: number\n\t__ownerID?: any\n\t_map?: any\n\t_list?: any\n\t_origin?: any\n\t_capacity?: any\n\t_defaultValues?: any\n\t_tail?: any\n\t_root?: any\n}\n\n// Interface for Vue reactive objects\ninterface VueReactive {\n\t__v_isReactive: boolean\n\t[key: string]: any\n}\n\n// Interface for Pinia stores\ninterface PiniaStore {\n\t$state?: Record<string, any>\n\t$patch?: (partial: Record<string, any>) => void\n\t$id?: string\n\t[key: string]: any\n}\n\n// Extend global interfaces\ndeclare global {\n\tinterface Window extends RegistryGlobal {}\n\tconst global: RegistryGlobal | undefined\n}\n\n/**\n * Global HST Manager (Singleton)\n * Manages hierarchical state trees and provides access to the global registry.\n *\n * @public\n */\nclass HST {\n\tprivate static instance: HST\n\n\t/**\n\t * Gets the singleton instance of HST\n\t * @returns The HST singleton instance\n\t */\n\tstatic getInstance(): HST {\n\t\tif (!HST.instance) {\n\t\t\tHST.instance = new HST()\n\t\t}\n\t\treturn HST.instance\n\t}\n\n\t/**\n\t * Gets the global registry instance\n\t * @returns The global registry object or undefined if not found\n\t */\n\tgetRegistry(): any {\n\t\t// In test environment, try different ways to access Registry\n\t\t// First, try the global Registry if it exists\n\t\tif (typeof globalThis !== 'undefined') {\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Window interface extended with RegistryGlobal in declare global above; no other way to access globalThis properties\n\t\t\tconst globalRegistry = (globalThis as unknown as RegistryGlobal).Registry?._root\n\t\t\tif (globalRegistry) {\n\t\t\t\treturn globalRegistry\n\t\t\t}\n\t\t}\n\n\t\t// Try to access through window (browser environment)\n\t\tif (typeof window !== 'undefined') {\n\t\t\tconst windowRegistry = window.Registry?._root\n\t\t\tif (windowRegistry) {\n\t\t\t\treturn windowRegistry\n\t\t\t}\n\t\t}\n\n\t\t// Try to access through global (Node environment)\n\t\tif (typeof global !== 'undefined' && global) {\n\t\t\tconst nodeRegistry = global.Registry?._root\n\t\t\tif (nodeRegistry) {\n\t\t\t\treturn nodeRegistry\n\t\t\t}\n\t\t}\n\n\t\t// If we can't find it globally, it might not be set up\n\t\t// This is expected in test environments where Registry is created locally\n\t\treturn undefined\n\t}\n\n\t/**\n\t * Helper method to get doctype metadata from the registry\n\t * @param doctype - The name of the doctype to retrieve metadata for\n\t * @returns The doctype metadata object or undefined if not found\n\t */\n\tgetDoctypeMeta(doctype: string) {\n\t\tconst registry = this.getRegistry()\n\t\tif (registry && typeof registry === 'object' && 'registry' in registry) {\n\t\t\treturn registry.registry[doctype]\n\t\t}\n\t\treturn undefined\n\t}\n}\n\n// Enhanced HST Proxy with tree navigation\nclass HSTProxy implements HSTNode {\n\tprivate target: any\n\tprivate ancestorPath: string\n\tprivate rootNode: HSTNode | null\n\tprivate doctype: string\n\tprivate hst: HST\n\n\tconstructor(target: any, doctype: string, ancestorPath = '', rootNode: HSTNode | null = null) {\n\t\tthis.target = target\n\t\tthis.ancestorPath = ancestorPath\n\t\tthis.rootNode = rootNode || this\n\t\tthis.doctype = doctype\n\t\tthis.hst = HST.getInstance()\n\n\t\treturn new Proxy(this, {\n\t\t\tget(hst, prop) {\n\t\t\t\t// Return HST methods directly\n\t\t\t\tif (prop in hst) return Reflect.get(hst, prop)\n\n\t\t\t\t// Handle property access - return tree nodes for navigation\n\t\t\t\tconst path = String(prop)\n\t\t\t\treturn hst.getNode(path)\n\t\t\t},\n\n\t\t\tset(hst, prop, value) {\n\t\t\t\tconst path = String(prop)\n\t\t\t\thst.set(path, value)\n\t\t\t\treturn true\n\t\t\t},\n\t\t})\n\t}\n\n\tget(path: string): any {\n\t\treturn this.resolveValue(path)\n\t}\n\n\t// Method to get a tree-wrapped node for navigation\n\tgetNode(path: string): HSTNode {\n\t\tconst fullPath = this.resolvePath(path)\n\t\tconst value = this.resolveValue(path)\n\n\t\t// Determine the correct doctype for this node based on the path\n\t\tconst pathSegments = fullPath.split('.')\n\t\tlet nodeDoctype = this.doctype\n\n\t\t// If we're at the root level and this is a StonecropStore, use the first path segment as the doctype\n\t\tif (this.doctype === 'StonecropStore' && pathSegments.length >= 1) {\n\t\t\tnodeDoctype = pathSegments[0]\n\t\t}\n\n\t\t// Always wrap in HSTProxy for tree navigation\n\t\tif (typeof value === 'object' && value !== null && !this.isPrimitive(value)) {\n\t\t\treturn new HSTProxy(value, nodeDoctype, fullPath, this.rootNode)\n\t\t}\n\n\t\t// For primitives, return a minimal wrapper that throws on tree operations\n\t\treturn new HSTProxy(value, nodeDoctype, fullPath, this.rootNode)\n\t}\n\n\tset(path: string, value: any, source: 'user' | 'system' | 'sync' | 'undo' | 'redo' = 'user'): void {\n\t\t// Get current value for change context\n\t\tconst fullPath = this.resolvePath(path)\n\t\tif (fullPath === undefined) {\n\t\t\tconsole.warn('HST.set: resolved path is undefined, skipping operation')\n\t\t\treturn\n\t\t}\n\t\tconst beforeValue = this.has(path) ? this.get(path) : undefined\n\n\t\t// Log operation if not from undo/redo and store is available\n\t\tif (source !== 'undo' && source !== 'redo') {\n\t\t\tconst logStore = getOperationLogStore()\n\t\t\tif (logStore && typeof logStore.addOperation === 'function') {\n\t\t\t\tconst pathSegments = fullPath.split('.')\n\t\t\t\tconst doctype = this.doctype === 'StonecropStore' && pathSegments.length >= 1 ? pathSegments[0] : this.doctype\n\t\t\t\tconst recordId = pathSegments.length >= 2 ? pathSegments[1] : undefined\n\t\t\t\tconst fieldname = pathSegments.slice(2).join('.') || pathSegments[pathSegments.length - 1]\n\n\t\t\t\t// Detect if this is a DELETE operation (setting to undefined when a value existed)\n\t\t\t\tconst isDelete = value === undefined && beforeValue !== undefined\n\t\t\t\tconst operationType: 'set' | 'delete' = isDelete ? 'delete' : 'set'\n\n\t\t\t\tlogStore.addOperation(\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: operationType,\n\t\t\t\t\t\tpath: fullPath,\n\t\t\t\t\t\tfieldname,\n\t\t\t\t\t\tbeforeValue,\n\t\t\t\t\t\tafterValue: value,\n\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\trecordId,\n\t\t\t\t\t\treversible: true, // Default to reversible, can be changed by field triggers\n\t\t\t\t\t},\n\t\t\t\t\tsource\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// Update the value\n\t\tthis.updateValue(path, value)\n\n\t\t// Trigger field actions asynchronously (don't block the set operation)\n\t\tvoid this.triggerFieldActions(fullPath, beforeValue, value)\n\t}\n\n\thas(path: string): boolean {\n\t\ttry {\n\t\t\t// Handle empty path case\n\t\t\tif (path === '') {\n\t\t\t\treturn true // empty path refers to the root object\n\t\t\t}\n\n\t\t\tconst segments = this.parsePath(path)\n\t\t\tlet current = this.target\n\n\t\t\tfor (let i = 0; i < segments.length; i++) {\n\t\t\t\tconst segment = segments[i]\n\n\t\t\t\tif (current === null || current === undefined) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\n\t\t\t\t// Check if this is the last segment\n\t\t\t\tif (i === segments.length - 1) {\n\t\t\t\t\t// For the final property, check if it exists\n\t\t\t\t\tif (this.isImmutable(current)) {\n\t\t\t\t\t\treturn current.has(segment)\n\t\t\t\t\t} else if (this.isPiniaStore(current)) {\n\t\t\t\t\t\treturn (current.$state && segment in current.$state) || segment in current\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn segment in current\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Navigate to the next level\n\t\t\t\tcurrent = this.getProperty(current, segment)\n\t\t\t}\n\n\t\t\treturn false\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Tree navigation methods\n\tgetAncestor(): HSTNode | null {\n\t\tif (!this.ancestorPath) return null\n\n\t\tconst ancestorSegments = this.ancestorPath.split('.').slice(0, -1)\n\t\tconst ancestorPath = ancestorSegments.join('.')\n\n\t\tif (ancestorPath === '') {\n\t\t\treturn this.rootNode\n\t\t}\n\n\t\t// Return a wrapped node, not raw data\n\t\treturn this.rootNode!.getNode(ancestorPath)\n\t}\n\n\tgetRoot(): HSTNode {\n\t\treturn this.rootNode!\n\t}\n\n\tgetPath(): string {\n\t\treturn this.ancestorPath\n\t}\n\n\tgetDepth(): number {\n\t\treturn this.ancestorPath ? this.ancestorPath.split('.').length : 0\n\t}\n\n\tgetBreadcrumbs(): string[] {\n\t\treturn this.ancestorPath ? this.ancestorPath.split('.') : []\n\t}\n\n\t/**\n\t * Trigger an XState transition with optional context data\n\t */\n\tasync triggerTransition(\n\t\ttransition: string,\n\t\tcontext?: { currentState?: string; targetState?: string; fsmContext?: Record<string, any> }\n\t): Promise<any> {\n\t\tconst triggerEngine = getGlobalTriggerEngine()\n\n\t\t// Determine doctype and recordId from the current path\n\t\tconst pathSegments = this.ancestorPath.split('.')\n\t\tlet doctype = this.doctype\n\t\tlet recordId: string | undefined\n\n\t\t// If we're at the root level and this is a StonecropStore, use the first path segment as the doctype\n\t\tif (this.doctype === 'StonecropStore' && pathSegments.length >= 1) {\n\t\t\tdoctype = pathSegments[0]\n\t\t}\n\n\t\t// Extract recordId from path if it follows the expected pattern\n\t\tif (pathSegments.length >= 2) {\n\t\t\trecordId = pathSegments[1]\n\t\t}\n\n\t\t// Build transition context\n\t\tconst transitionContext: TransitionChangeContext = {\n\t\t\tpath: this.ancestorPath,\n\t\t\tfieldname: '', // No specific field for transitions\n\t\t\tbeforeValue: undefined,\n\t\t\tafterValue: undefined,\n\t\t\toperation: 'set',\n\t\t\tdoctype,\n\t\t\trecordId,\n\t\t\ttimestamp: new Date(),\n\t\t\tstore: this.rootNode || undefined,\n\t\t\ttransition,\n\t\t\tcurrentState: context?.currentState,\n\t\t\ttargetState: context?.targetState,\n\t\t\tfsmContext: context?.fsmContext,\n\t\t}\n\n\t\t// Log FSM transition operation\n\t\tconst logStore = getOperationLogStore()\n\t\tif (logStore && typeof logStore.addOperation === 'function') {\n\t\t\tlogStore.addOperation(\n\t\t\t\t{\n\t\t\t\t\ttype: 'transition' as const,\n\t\t\t\t\tpath: this.ancestorPath,\n\t\t\t\t\tfieldname: transition,\n\t\t\t\t\tbeforeValue: context?.currentState,\n\t\t\t\t\tafterValue: context?.targetState,\n\t\t\t\t\tdoctype,\n\t\t\t\t\trecordId,\n\t\t\t\t\treversible: false, // FSM transitions are generally not reversible\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\ttransition,\n\t\t\t\t\t\tcurrentState: context?.currentState,\n\t\t\t\t\t\ttargetState: context?.targetState,\n\t\t\t\t\t\tfsmContext: context?.fsmContext,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t'user'\n\t\t\t)\n\t\t}\n\n\t\t// Execute transition actions\n\t\treturn await triggerEngine.executeTransitionActions(transitionContext)\n\t}\n\n\t// Private helper methods\n\tprivate resolvePath(path: string): string {\n\t\tif (path === '') return this.ancestorPath ?? ''\n\t\treturn this.ancestorPath ? `${this.ancestorPath}.${path}` : path\n\t}\n\n\tprivate resolveValue(path: string): any {\n\t\t// Handle empty path - return the target object\n\t\tif (path === '') {\n\t\t\treturn this.target\n\t\t}\n\n\t\tconst segments = this.parsePath(path)\n\t\tlet current = this.target\n\n\t\tfor (const segment of segments) {\n\t\t\tif (current === null || current === undefined) {\n\t\t\t\treturn undefined\n\t\t\t}\n\n\t\t\tcurrent = this.getProperty(current, segment)\n\t\t}\n\n\t\treturn current\n\t}\n\n\tprivate updateValue(path: string, value: any): void {\n\t\t// Handle empty path case - should throw error\n\t\tif (path === '') {\n\t\t\tthrow new Error('Cannot set value on empty path')\n\t\t}\n\n\t\tconst segments = this.parsePath(path)\n\t\tconst lastSegment = segments.pop()!\n\t\tlet current = this.target\n\n\t\t// Navigate to ancestor object\n\t\tfor (const segment of segments) {\n\t\t\tcurrent = this.getProperty(current, segment)\n\t\t\tif (current === null || current === undefined) {\n\t\t\t\tthrow new Error(`Cannot set property on null/undefined path: ${path}`)\n\t\t\t}\n\t\t}\n\n\t\t// Set the final property\n\t\tthis.setProperty(current, lastSegment, value)\n\t}\n\n\tprivate getProperty(obj: any, key: string): any {\n\t\t// Immutable objects\n\t\tif (this.isImmutable(obj)) {\n\t\t\treturn obj.get(key)\n\t\t}\n\n\t\t// Vue reactive object\n\t\tif (this.isVueReactive(obj)) {\n\t\t\treturn obj[key]\n\t\t}\n\n\t\t// Pinia store\n\t\tif (this.isPiniaStore(obj)) {\n\t\t\treturn obj.$state?.[key] ?? obj[key]\n\t\t}\n\n\t\t// Plain object\n\t\treturn obj[key]\n\t}\n\n\tprivate setProperty(obj: any, key: string, value: any): void {\n\t\t// Immutable objects\n\t\tif (this.isImmutable(obj)) {\n\t\t\tthrow new Error('Cannot directly mutate immutable objects. Use immutable update methods instead.')\n\t\t}\n\n\t\t// Pinia store\n\t\tif (this.isPiniaStore(obj)) {\n\t\t\tif (obj.$patch) {\n\t\t\t\tobj.$patch({ [key]: value })\n\t\t\t} else {\n\t\t\t\tobj[key] = value\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// Vue reactive or plain object\n\t\tobj[key] = value\n\t}\n\n\tprivate async triggerFieldActions(fullPath: string, beforeValue: any, afterValue: any): Promise<void> {\n\t\ttry {\n\t\t\t// Guard against undefined or null fullPath\n\t\t\tif (!fullPath || typeof fullPath !== 'string') {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Skip triggering when the value did not actually change\n\t\t\tif (Object.is(beforeValue, afterValue)) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst pathSegments = fullPath.split('.')\n\n\t\t\t// Only trigger field actions for actual field changes (at least 3 levels deep: doctype.recordId.fieldname)\n\t\t\t// Skip triggering for doctype-level or record-level changes\n\t\t\tif (pathSegments.length < 3) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst triggerEngine = getGlobalTriggerEngine()\n\t\t\tconst fieldname = pathSegments.slice(2).join('.') || pathSegments[pathSegments.length - 1]\n\n\t\t\t// Determine the correct doctype for this path using the same logic as getNode()\n\t\t\t// The path should be in format: \"doctype.recordId.fieldname\"\n\t\t\tlet doctype = this.doctype\n\n\t\t\t// If we're at the root level and this is a StonecropStore, use the first path segment as the doctype\n\t\t\tif (this.doctype === 'StonecropStore' && pathSegments.length >= 1) {\n\t\t\t\tdoctype = pathSegments[0]\n\t\t\t}\n\n\t\t\tlet recordId: string | undefined\n\n\t\t\t// Extract recordId from path if it follows the expected pattern\n\t\t\tif (pathSegments.length >= 2) {\n\t\t\t\trecordId = pathSegments[1]\n\t\t\t}\n\n\t\t\tconst context: FieldChangeContext = {\n\t\t\t\tpath: fullPath,\n\t\t\t\tfieldname,\n\t\t\t\tbeforeValue,\n\t\t\t\tafterValue,\n\t\t\t\toperation: 'set',\n\t\t\t\tdoctype,\n\t\t\t\trecordId,\n\t\t\t\ttimestamp: new Date(),\n\t\t\t\tstore: this.rootNode || undefined, // Pass the root store for snapshot/rollback capabilities\n\t\t\t}\n\n\t\t\tawait triggerEngine.executeFieldTriggers(context)\n\t\t} catch (error) {\n\t\t\t// Silently handle trigger errors to not break the main flow\n\t\t\t// In production, you might want to log this error\n\t\t\tif (error instanceof Error) {\n\t\t\t\tconsole.warn('Field trigger error:', error.message)\n\t\t\t\t// Optional: emit an event or call error handler\n\t\t\t}\n\t\t}\n\t}\n\tprivate isVueReactive(obj: any): obj is VueReactive {\n\t\treturn obj && typeof obj === 'object' && '__v_isReactive' in obj && obj.__v_isReactive === true\n\t}\n\n\tprivate isPiniaStore(obj: any): obj is PiniaStore {\n\t\treturn obj && typeof obj === 'object' && ('$state' in obj || '$patch' in obj || '$id' in obj)\n\t}\n\n\tprivate isImmutable(obj: any): obj is ImmutableLike {\n\t\tif (!obj || typeof obj !== 'object') {\n\t\t\treturn false\n\t\t}\n\n\t\tconst hasGetMethod = 'get' in obj && typeof obj.get === 'function'\n\t\tconst hasSetMethod = 'set' in obj && typeof obj.set === 'function'\n\t\tconst hasHasMethod = 'has' in obj && typeof obj.has === 'function'\n\n\t\tconst hasImmutableMarkers =\n\t\t\t'__ownerID' in obj ||\n\t\t\t'_map' in obj ||\n\t\t\t'_list' in obj ||\n\t\t\t'_origin' in obj ||\n\t\t\t'_capacity' in obj ||\n\t\t\t'_defaultValues' in obj ||\n\t\t\t'_tail' in obj ||\n\t\t\t'_root' in obj ||\n\t\t\t('size' in obj && hasGetMethod && hasSetMethod)\n\n\t\tlet constructorName: string | undefined\n\t\ttry {\n\t\t\tif ('constructor' in obj && obj.constructor && typeof obj.constructor === 'object' && 'name' in obj.constructor) {\n\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- obj.constructor.name accessed after 'name' in check; obj is any throughout this method\n\t\t\t\tconst nameValue = (obj.constructor as { name: unknown }).name\n\t\t\t\tconstructorName = typeof nameValue === 'string' ? nameValue : undefined\n\t\t\t}\n\t\t} catch {\n\t\t\tconstructorName = undefined\n\t\t}\n\n\t\tconst isImmutableConstructor =\n\t\t\tconstructorName &&\n\t\t\t(constructorName.includes('Map') ||\n\t\t\t\tconstructorName.includes('List') ||\n\t\t\t\tconstructorName.includes('Set') ||\n\t\t\t\tconstructorName.includes('Stack') ||\n\t\t\t\tconstructorName.includes('Seq')) &&\n\t\t\t(hasGetMethod || hasSetMethod)\n\n\t\treturn Boolean(\n\t\t\t(hasGetMethod && hasSetMethod && hasHasMethod && hasImmutableMarkers) ||\n\t\t\t(hasGetMethod && hasSetMethod && isImmutableConstructor)\n\t\t)\n\t}\n\n\tprivate isPrimitive(value: any): boolean {\n\t\t// Don't wrap primitive values, functions, or null/undefined\n\t\treturn (\n\t\t\tvalue === null ||\n\t\t\tvalue === undefined ||\n\t\t\ttypeof value === 'string' ||\n\t\t\ttypeof value === 'number' ||\n\t\t\ttypeof value === 'boolean' ||\n\t\t\ttypeof value === 'function' ||\n\t\t\ttypeof value === 'symbol' ||\n\t\t\ttypeof value === 'bigint'\n\t\t)\n\t}\n\n\t/**\n\t * Parse a path string into segments, handling both dot notation and array bracket notation\n\t * @param path - The path string to parse (e.g., \"order.456.line_items[0].product\")\n\t * @returns Array of path segments (e.g., ['order', '456', 'line_items', '0', 'product'])\n\t */\n\tprivate parsePath(path: string): string[] {\n\t\tif (!path) return []\n\n\t\t// Replace array bracket notation with dot notation\n\t\t// items[0] → items.0\n\t\t// items[0][1] → items.0.1\n\t\tconst normalizedPath = path.replace(/\\[(\\d+)\\]/g, '.$1')\n\n\t\treturn normalizedPath.split('.').filter(segment => segment.length > 0)\n\t}\n}\n\n/**\n * Factory function for HST creation\n * Creates a new HSTNode proxy for hierarchical state tree navigation.\n *\n * @param target - The target object to wrap with HST functionality\n * @param doctype - The document type identifier\n * @returns A new HSTNode proxy instance\n *\n * @public\n */\nfunction createHST(target: any, doctype: string): HSTNode {\n\treturn new HSTProxy(target, doctype, '', null)\n}\n\n// Export everything\nexport { HSTProxy, HST, createHST, type HSTNode }\n","import type { DataClient, GetRecordOptions, GetRecordsOptions, GetRecordsResult } from '@stonecrop/schema'\nimport { reactive } from 'vue'\n\nimport Doctype from './doctype'\nimport { isDraftRecordId } from './draft'\nimport Registry from './registry'\nimport { createHST, type HSTNode } from './stores/hst'\nimport { useOperationLogStore } from './stores/operation-log'\nimport type { OperationLogConfig } from './types/operation-log'\nimport type { RouteContext } from './types/registry'\nimport type { PageInfo, StonecropOptions } from './types/stonecrop'\n\n/**\n * Main Stonecrop class with HST integration and built-in Operation Log\n * @public\n */\nexport class Stonecrop {\n\t/**\n\t * Singleton instance of Stonecrop. Only one Stonecrop instance can exist\n\t * per application, ensuring consistent HST state and registry access.\n\t * Subsequent constructor calls return this instance instead of creating new ones.\n\t * @internal\n\t */\n\tstatic _root: Stonecrop\n\n\t/** The HST store instance for reactive state management */\n\tprivate hstStore!: HSTNode\n\tprivate _operationLogStore?: ReturnType<typeof useOperationLogStore>\n\tprivate _operationLogConfig?: Partial<OperationLogConfig>\n\tprivate _client?: DataClient\n\n\t/**\n\t * Per-doctype page info from the last list read, keyed by slug. Reactive so views tracking\n\t * it update on fetch. Deliberately not in HST — see {@link Stonecrop.getRecords}.\n\t */\n\tprivate pageInfo: Record<string, PageInfo> = reactive({})\n\n\t/** The registry instance containing all doctype definitions */\n\treadonly registry!: Registry\n\n\t/**\n\t * Creates a new Stonecrop instance with HST integration (singleton pattern)\n\t * @param registry - The Registry instance containing doctype definitions\n\t * @param operationLogConfig - Optional configuration for the operation log\n\t * @param options - Options including the data client (can be set later via setClient)\n\t */\n\tconstructor(registry: Registry, operationLogConfig?: Partial<OperationLogConfig>, options?: StonecropOptions) {\n\t\tif (Stonecrop._root) {\n\t\t\treturn Stonecrop._root\n\t\t}\n\t\tStonecrop._root = this\n\n\t\tthis.registry = registry\n\n\t\t// Store config for lazy initialization\n\t\tthis._operationLogConfig = operationLogConfig\n\n\t\t// Store data client (can be set later via setClient)\n\t\tthis._client = options?.client\n\n\t\t// Initialize HST store with auto-sync to Registry\n\t\tthis.initializeHSTStore()\n\t\tthis.setupRegistrySync()\n\t\treturn this\n\t}\n\n\t/**\n\t * Set the data client for fetching doctype metadata and records.\n\t * Use this for deferred configuration in Nuxt/Vue plugin setups.\n\t *\n\t * @param client - DataClient implementation (e.g., StonecropClient from \\@stonecrop/graphql-client)\n\t *\n\t * @example\n\t * ```ts\n\t * const { setClient } = useStonecropRegistry()\n\t * const client = new StonecropClient({ endpoint: '/graphql' })\n\t * setClient(client)\n\t * ```\n\t */\n\tsetClient(client: DataClient): void {\n\t\tthis._client = client\n\t}\n\n\t/**\n\t * Get the current data client\n\t * @returns The DataClient instance or undefined if not set\n\t */\n\tgetClient(): DataClient | undefined {\n\t\treturn this._client\n\t}\n\n\t/**\n\t * Get the operation log store (lazy initialization)\n\t * @internal\n\t */\n\tgetOperationLogStore() {\n\t\tif (!this._operationLogStore) {\n\t\t\tthis._operationLogStore = useOperationLogStore()\n\t\t\tif (this._operationLogConfig) {\n\t\t\t\tthis._operationLogStore.configure(this._operationLogConfig)\n\t\t\t}\n\t\t}\n\t\treturn this._operationLogStore\n\t}\n\n\t/**\n\t * Initialize the HST store structure\n\t */\n\tprivate initializeHSTStore(): void {\n\t\tconst initialStoreStructure: Record<string, any> = {}\n\n\t\t// Auto-populate from existing Registry doctypes\n\t\tObject.keys(this.registry.registry).forEach(doctypeSlug => {\n\t\t\tinitialStoreStructure[doctypeSlug] = {}\n\t\t})\n\n\t\t// Wrap the store in Vue's reactive() for automatic change detection\n\t\t// This enables Vue computed properties to track HST store changes\n\t\tthis.hstStore = createHST(reactive(initialStoreStructure), 'StonecropStore')\n\t}\n\n\t/**\n\t * Setup automatic sync with Registry when doctypes are added\n\t */\n\tprivate setupRegistrySync(): void {\n\t\t// Extend Registry.addDoctype to auto-create HST store sections\n\t\tconst originalAddDoctype = this.registry.addDoctype.bind(this.registry)\n\n\t\tthis.registry.addDoctype = (doctype: Doctype) => {\n\t\t\t// Call original method\n\t\t\toriginalAddDoctype(doctype)\n\n\t\t\t// Auto-create HST store section for new doctype\n\t\t\tif (!this.hstStore.has(doctype.slug)) {\n\t\t\t\tthis.hstStore.set(doctype.slug, {})\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Get records hash for a doctype\n\t * @param doctype - The doctype to get records for\n\t * @returns HST node containing records hash\n\t */\n\trecords(doctype: string | Doctype): HSTNode {\n\t\tconst slug = typeof doctype === 'string' ? doctype : doctype.slug\n\t\tthis.ensureDoctypeExists(slug)\n\t\treturn this.hstStore.getNode(slug)\n\t}\n\n\t/**\n\t * Add a record to the store\n\t * @param doctype - The doctype\n\t * @param recordId - The record ID\n\t * @param recordData - The record data\n\t */\n\taddRecord(doctype: string | Doctype, recordId: string, recordData: any): void {\n\t\tconst slug = typeof doctype === 'string' ? doctype : doctype.slug\n\n\t\tthis.ensureDoctypeExists(slug)\n\n\t\t// Store raw record data - let HST handle wrapping with proper hierarchy\n\t\tthis.hstStore.set(`${slug}.${recordId}`, recordData)\n\t}\n\n\t/**\n\t * Get a specific record\n\t * @param doctype - The doctype\n\t * @param recordId - The record ID\n\t * @returns HST node for the record or undefined\n\t */\n\tgetRecordById(doctype: string | Doctype, recordId: string): HSTNode | undefined {\n\t\tconst slug = typeof doctype === 'string' ? doctype : doctype.slug\n\t\tthis.ensureDoctypeExists(slug)\n\n\t\t// First check if the record exists\n\t\tconst recordExists = this.hstStore.has(`${slug}.${recordId}`)\n\t\tif (!recordExists) {\n\t\t\treturn undefined\n\t\t}\n\n\t\t// Check if the actual value is undefined (i.e., record was removed)\n\t\tconst recordValue = this.hstStore.get(`${slug}.${recordId}`)\n\t\tif (recordValue === undefined) {\n\t\t\treturn undefined\n\t\t}\n\n\t\t// Use getNode to get the properly wrapped HST node with correct ancestor relationships\n\t\treturn this.hstStore.getNode(`${slug}.${recordId}`)\n\t}\n\n\t/**\n\t * Remove a record from the store\n\t * @param doctype - The doctype\n\t * @param recordId - The record ID\n\t */\n\tremoveRecord(doctype: string | Doctype, recordId: string): void {\n\t\tconst slug = typeof doctype === 'string' ? doctype : doctype.slug\n\t\tthis.ensureDoctypeExists(slug)\n\n\t\t// Remove the specific record directly by setting to undefined\n\t\tif (this.hstStore.has(`${slug}.${recordId}`)) {\n\t\t\tthis.hstStore.set(`${slug}.${recordId}`, undefined)\n\t\t}\n\t}\n\n\t/**\n\t * Get all record IDs for a doctype\n\t * @param doctype - The doctype\n\t * @returns Array of record IDs\n\t */\n\tgetRecordIds(doctype: string | Doctype): string[] {\n\t\tconst slug = typeof doctype === 'string' ? doctype : doctype.slug\n\t\tthis.ensureDoctypeExists(slug)\n\n\t\tconst doctypeNode = this.hstStore.get(slug)\n\t\tif (!doctypeNode || typeof doctypeNode !== 'object') {\n\t\t\treturn []\n\t\t}\n\n\t\treturn Object.keys(doctypeNode).filter(key => doctypeNode[key] !== undefined)\n\t}\n\n\t/**\n\t * Clear all records for a doctype\n\t * @param doctype - The doctype\n\t */\n\tclearRecords(doctype: string | Doctype): void {\n\t\tconst slug = typeof doctype === 'string' ? doctype : doctype.slug\n\t\tthis.ensureDoctypeExists(slug)\n\n\t\t// Get all record IDs and remove them\n\t\tconst recordIds = this.getRecordIds(slug)\n\t\trecordIds.forEach(recordId => {\n\t\t\tthis.hstStore.set(`${slug}.${recordId}`, undefined)\n\t\t})\n\t}\n\n\t/**\n\t * Setup method for doctype initialization\n\t * @param doctype - The doctype to setup\n\t */\n\tsetup(doctype: Doctype): void {\n\t\t// Ensure doctype exists in store\n\t\tthis.ensureDoctypeExists(doctype.slug)\n\t}\n\n\t/**\n\t * Get the effective blockWorkflows value for a link.\n\t * Returns true if blockWorkflows is explicitly true, or if it's absent and fetch method is 'sync'.\n\t * @param link - The link declaration\n\t * @returns Whether workflows should be blocked until this link is loaded\n\t */\n\tprivate getEffectiveBlockWorkflows(link: { blockWorkflows?: boolean; fetch?: { method?: string } }): boolean {\n\t\tif (link.blockWorkflows !== undefined) {\n\t\t\treturn link.blockWorkflows\n\t\t}\n\t\t// TODO: For custom fetch handlers, this returns false (not blocking), but the custom handler\n\t\t// may still be invoked by useLazyLink. Future: custom handlers should be able to declare they\n\t\t// satisfy blockWorkflows, or validation should reject custom + blockWorkflows: true.\n\t\treturn link.fetch?.method === 'sync'\n\t}\n\n\t/**\n\t * Check if workflow actions are ready to run (all required link data is loaded).\n\t * A link's data is considered loaded if it exists in HST at `slug.recordId.linkname`.\n\t * @param doctype - The doctype to check\n\t * @param recordId - The record ID\n\t * @returns Object with `ready: true` if all blocked links are loaded, or `ready: false` with `blockedLinks` array\n\t */\n\tisWorkflowReady(doctype: Doctype, recordId: string): { ready: boolean; blockedLinks?: string[] } {\n\t\t// New records don't block workflows - they haven't been saved yet\n\t\tif (isDraftRecordId(recordId)) {\n\t\t\treturn { ready: true }\n\t\t}\n\n\t\tconst links = this.registry.getDescendantLinks(doctype.slug)\n\t\tconst blockedLinks: string[] = []\n\n\t\tfor (const link of links) {\n\t\t\tif (this.getEffectiveBlockWorkflows(link)) {\n\t\t\t\tconst linkPath = `${doctype.slug}.${recordId}.${link.fieldname}`\n\t\t\t\tif (!this.hstStore.has(linkPath)) {\n\t\t\t\t\tblockedLinks.push(link.fieldname)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (blockedLinks.length > 0) {\n\t\t\treturn { ready: false, blockedLinks }\n\t\t}\n\t\treturn { ready: true }\n\t}\n\n\t/**\n\t * Fetch a doctype's records from the server and store them in HST.\n\t *\n\t * This is the one read path for a list. Every caller shares its keying rule, so a row is\n\t * always stored under the identity its Edit link will later ask for.\n\t *\n\t * Deliberately unguarded, unlike {@link Stonecrop.getRecord}: a list is a view of data that\n\t * changes, so revisiting one must re-read it rather than serve whatever HST happens to hold.\n\t *\n\t * `options` is forwarded to the client untouched — no row limit is invented here, because\n\t * nothing on this side of the wire knows what is safe for an arbitrary backend. A caller that\n\t * passes none gets whatever the server considers a reasonable page.\n\t *\n\t * `options.offset === 0` (or omitted) replaces the doctype's HST records; `offset > 0` appends.\n\t *\n\t * @param doctype - The doctype\n\t * @param options - Query options (filters, orderBy, limit, offset), forwarded to the client\n\t * @throws Error if no data client has been configured\n\t * @public\n\t */\n\tasync getRecords(doctype: Doctype, options?: GetRecordsOptions): Promise<GetRecordsResult> {\n\t\tif (!this._client) {\n\t\t\tthrow new Error(\n\t\t\t\t'No data client configured. Call setClient() with a DataClient implementation ' +\n\t\t\t\t\t'(e.g., StonecropClient from @stonecrop/graphql-client) before fetching records.'\n\t\t\t)\n\t\t}\n\n\t\tconst result = await this._client.getRecords(doctype, options)\n\t\tconst records = result.data\n\t\tconst offset = options?.offset ?? 0\n\n\t\t// Page info is kept beside HST, not in it. `getRecordIds` reads the raw keys under a\n\t\t// doctype node, so anything filed there becomes a phantom record — the same hazard that\n\t\t// ruled out seeding a draft node.\n\t\tconst pageEntry: PageInfo = {\n\t\t\thasMore: result.hasMore,\n\t\t\toffset,\n\t\t\tlimit: records.length,\n\t\t}\n\t\tif (result.count != null) {\n\t\t\tpageEntry.count = result.count\n\t\t}\n\t\tthis.pageInfo[doctype.slug] = pageEntry\n\n\t\t// offset === 0 replaces the doctype's HST records; offset > 0 appends. A failed fetch\n\t\t// must not clear — that happens only after a successful response lands above.\n\t\tif (offset === 0) {\n\t\t\tthis.clearRecords(doctype)\n\t\t}\n\n\t\t// Key each record by its declared primary key, falling back to `id`. This used to read\n\t\t// `record.id` only, which silently dropped every row of a natural-keyed doctype (no `id`\n\t\t// column at all) — the records never entered HST, so the list rendered empty and no\n\t\t// downstream id-resolution could recover them.\n\t\trecords.forEach(record => {\n\t\t\tconst recordId = doctype.getRecordId(record)\n\t\t\tif (recordId !== undefined) {\n\t\t\t\tthis.addRecord(doctype, recordId, record)\n\t\t\t}\n\t\t})\n\n\t\treturn result\n\t}\n\n\t/**\n\t * What the last {@link Stonecrop.getRecords} for this doctype returned about the wider set.\n\t *\n\t * Answers the question HST cannot: HST holds what was fetched, so counting its keys reports\n\t * how much has been seen, never how much exists. Reactive, so a view reading it re-renders\n\t * when a fetch lands.\n\t *\n\t * @param doctype - The doctype slug string or Doctype object\n\t * @returns Page info, or undefined if this doctype's records have not been fetched\n\t * @public\n\t */\n\tgetPageInfo(doctype: string | Doctype): PageInfo | undefined {\n\t\tconst slug = typeof doctype === 'string' ? doctype : doctype.slug\n\t\treturn this.pageInfo[slug]\n\t}\n\n\t/**\n\t * Fetch a single record from the server and store it in HST.\n\t *\n\t * This is the one read path for a record, and it owns the whole job: deciding whether a fetch\n\t * is warranted, performing it, and writing the result back under the doctype's declared\n\t * identity. Callers ask for a record and get one; they do not re-derive when to ask.\n\t *\n\t * Two cases return without touching the network, because in both the answer is already known:\n\t * a draft does not exist on the server yet, and a record already in HST has been read.\n\t * Refetching the latter would also discard unsaved edits sitting in the store.\n\t *\n\t * @param doctype - The doctype slug string or Doctype object\n\t * @param recordId - The record ID\n\t * @param options - Query options (includeNested, maxDepth), forwarded to the client\n\t * @throws Error if no data client has been configured\n\t * @throws Error if a slug string is given and no matching doctype is found in the registry\n\t * @public\n\t */\n\tasync getRecord(doctype: string | Doctype, recordId: string, options?: GetRecordOptions): Promise<void> {\n\t\tif (!this._client) {\n\t\t\tthrow new Error(\n\t\t\t\t'No data client configured. Call setClient() with a DataClient implementation ' +\n\t\t\t\t\t'(e.g., StonecropClient from @stonecrop/graphql-client) before fetching records.'\n\t\t\t)\n\t\t}\n\n\t\tconst resolved = typeof doctype === 'string' ? this.registry.getDoctype(doctype) : doctype\n\t\tif (!resolved) {\n\t\t\tthrow new Error(`Doctype not found: ${typeof doctype === 'string' ? doctype : doctype.slug}`)\n\t\t}\n\n\t\t// An unsaved draft has no server record, so a fetch could only ever miss. This guard used\n\t\t// to live in every host, which is how the private draft-id scheme leaked into all of them.\n\t\tif (isDraftRecordId(recordId)) {\n\t\t\treturn\n\t\t}\n\n\t\tif (this.getRecordById(resolved.slug, recordId)) {\n\t\t\treturn\n\t\t}\n\n\t\tconst result = await this._client.getRecord(resolved, recordId, options)\n\n\t\tif (result?.record) {\n\t\t\tthis.addRecord(resolved, recordId, result.record)\n\t\t}\n\t}\n\n\t/**\n\t * Dispatch an action to the server via the configured data client, and file the record it\n\t * returns into HST under the identity the *server* settled on.\n\t *\n\t * The write is the point. For a created record the settled identity is never the one that was\n\t * dispatched, so a caller that stores the result under the id it sent files the record under a\n\t * key nothing can fetch and leaves the next save creating a second one. Every host that\n\t * hand-rolled this got it wrong the same way, so it stops being the caller's job — this is the\n\t * write-side twin of {@link Stonecrop.getRecords}, which keys reads by the same rule.\n\t *\n\t * Two things are deliberately NOT done here, because both need the id that was dispatched and\n\t * that lives inside `args` — an opaque array whose shape is a convention between a host's\n\t * client and its server handlers, not something this layer may parse. Dropping the stale key\n\t * and moving the route therefore stay with `useClientAction`, which knows both ids.\n\t *\n\t * A result that states no identity of its own — a `{ state: 'APPROVED' }` outcome — is left\n\t * alone rather than guessed at, for the same reason `settledRecordId` is strict: a partial\n\t * record must not be able to look like a rename.\n\t *\n\t * @param doctype - The doctype\n\t * @param action - Action name to execute (e.g., 'SUBMIT', 'APPROVE', 'save')\n\t * @param args - Action arguments (typically record ID and/or form data)\n\t * @returns Action result with success status, response data, and any error\n\t * @throws Error if no data client has been configured\n\t */\n\tasync dispatchAction(\n\t\tdoctype: Doctype,\n\t\taction: string,\n\t\targs?: unknown[]\n\t): Promise<{ success: boolean; data: unknown; error: string | null }> {\n\t\tif (!this._client) {\n\t\t\tthrow new Error(\n\t\t\t\t'No data client configured. Call setClient() with a DataClient implementation ' +\n\t\t\t\t\t'(e.g., StonecropClient from @stonecrop/graphql-client) before dispatching actions.'\n\t\t\t)\n\t\t}\n\n\t\tconst result = await this._client.runAction(doctype, action, args)\n\n\t\tif (result.success && result.data && typeof result.data === 'object' && !Array.isArray(result.data)) {\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the guard above confirms a non-null, non-array object; the action result payload is an opaque JSON scalar\n\t\t\tconst record = result.data as Record<string, unknown>\n\t\t\t// Require the declared key to be *present* before trusting `getRecordId`, which falls\n\t\t\t// back to `id`. Without that, a handler returning `{ id, total }` for a natural-keyed\n\t\t\t// doctype would relocate the record to a key the adapter cannot look up.\n\t\t\tif (record[doctype.recordIdField] !== undefined) {\n\t\t\t\tconst settledId = doctype.getRecordId(record)\n\t\t\t\tif (settledId !== undefined) {\n\t\t\t\t\tthis.addRecord(doctype, settledId, record)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result\n\t}\n\n\t/**\n\t * Ensure doctype section exists in HST store\n\t * @param slug - The doctype slug\n\t */\n\tprivate ensureDoctypeExists(slug: string): void {\n\t\tif (!this.hstStore.has(slug)) {\n\t\t\tthis.hstStore.set(slug, {})\n\t\t}\n\t}\n\n\t/**\n\t * Get doctype metadata from the registry\n\t * @param context - The route context\n\t * @returns The doctype metadata\n\t */\n\tasync getMeta(context: RouteContext): Promise<any> {\n\t\tif (!this.registry.getMeta) {\n\t\t\tthrow new Error('No getMeta function provided to Registry')\n\t\t}\n\t\treturn await this.registry.getMeta(context)\n\t}\n\n\t/**\n\t * Get the root HST store node for advanced usage\n\t * @returns Root HST node\n\t */\n\tgetStore(): HSTNode {\n\t\treturn this.hstStore\n\t}\n\n\t/**\n\t * Determine the current workflow state for a record.\n\t *\n\t * Reads the record's `status` field from the HST store. If the field is absent or\n\t * empty the doctype's declared `workflow.initial` state is used as the fallback,\n\t * giving callers a reliable state name without having to duplicate that logic.\n\t *\n\t * @param doctype - The doctype slug or Doctype instance\n\t * @param recordId - The record identifier\n\t * @returns The current state name, or an empty string if the doctype has no workflow\n\t *\n\t * @public\n\t */\n\tgetRecordState(doctype: string | Doctype, recordId: string): string {\n\t\tconst slug = typeof doctype === 'string' ? doctype : doctype.slug\n\t\tconst meta = this.registry.getDoctype(slug)\n\t\tif (!meta?.workflow) return ''\n\n\t\tconst record = this.getRecordById(slug, recordId)\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- HSTNode.get returns any; status is always string in workflow records\n\t\tconst status = record?.get('status') as string | undefined\n\n\t\t// Handle both XState format and WorkflowMeta format\n\t\tconst workflow = meta.workflow\n\t\tlet initialState: string\n\n\t\tif (Array.isArray(workflow.states)) {\n\t\t\t// WorkflowMeta format: states is a string array\n\t\t\tinitialState = workflow.states[0] ?? ''\n\t\t} else {\n\t\t\t// XState format: states is an object, use initial or first key\n\t\t\t// oxlint-disable typescript/no-unsafe-type-assertion -- XState MachineConfig has `initial` but type union doesn't expose it; runtime-guarded by typeof check\n\t\t\tinitialState =\n\t\t\t\ttypeof (workflow as { initial?: unknown }).initial === 'string'\n\t\t\t\t\t? (workflow as { initial: string }).initial\n\t\t\t\t\t: (Object.keys(workflow.states ?? {})[0] ?? '')\n\t\t\t// oxlint-enable typescript/no-unsafe-type-assertion\n\t\t}\n\n\t\treturn status || initialState\n\t}\n\n\t/**\n\t * Collect a record payload with all nested doctype fields from HST\n\t * @param doctype - The doctype metadata\n\t * @param recordId - The record ID to collect\n\t * @returns The complete record payload ready for API submission\n\t * @public\n\t */\n\tcollectRecordPayload(doctype: Doctype, recordId: string): Record<string, any> {\n\t\tconst recordPath = `${doctype.slug}.${recordId}`\n\t\tconst recordData = this.hstStore.get(recordPath) || {}\n\n\t\tconst payload: Record<string, any> = { ...recordData }\n\n\t\t// Collect nested data from links\n\t\tif (doctype.links) {\n\t\t\tfor (const [fieldname, link] of Object.entries(doctype.links)) {\n\t\t\t\tconst fieldPath = `${recordPath}.${fieldname}`\n\t\t\t\tconst isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne'\n\n\t\t\t\tif (isMany) {\n\t\t\t\t\tconst arrayData = this.hstStore.get(fieldPath)\n\t\t\t\t\tif (Array.isArray(arrayData)) {\n\t\t\t\t\t\tpayload[fieldname] = arrayData\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst targetDoctype = this.registry.getDoctype(link.target)\n\t\t\t\t\tif (targetDoctype?.links) {\n\t\t\t\t\t\tpayload[fieldname] = this.collectNestedData(fieldPath, targetDoctype)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpayload[fieldname] = this.hstStore.get(fieldPath) || {}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// The store's shape, inline links included. Reducing them to what a column takes is the\n\t\t// adapter's job at dispatch — storage is behind the API.\n\t\treturn payload\n\t}\n\n\t/**\n\t * Scaffold empty descendant records from defaults for all descendant links.\n\t *\n\t * Initializes all scalar and link fields at their HST paths with default values.\n\t * For new records, call this after setting up the doctype to ensure all paths exist.\n\t *\n\t * @param path - HST path (e.g., \"customer.new\")\n\t * @param doctype - The doctype to initialize\n\t * @public\n\t */\n\tinitializeNestedData(path: string, doctype: Doctype): void {\n\t\tconst slug = doctype.slug\n\t\tthis.ensureDoctypeExists(slug)\n\n\t\t// Resolve schema and initialize with defaults\n\t\tconst resolvedSchema = this.registry.resolveSchema(doctype)\n\t\tconst record = this.registry.initializeRecord(resolvedSchema)\n\n\t\t// Ensure the ancestor path exists in HST before setting descendant fields\n\t\tconst existingData = this.hstStore.get(path)\n\t\tif (!existingData) {\n\t\t\tthis.hstStore.set(path, {}, 'system')\n\t\t}\n\n\t\t// Store each field at its own HST path\n\t\tfor (const [key, value] of Object.entries(record)) {\n\t\t\tthis.hstStore.set(`${path}.${key}`, value, 'system')\n\t\t}\n\t}\n\n\t/**\n\t * Fetch a record and its nested data from the server.\n\t *\n\t * Calls `_client.getRecord()` with nested sub-selections and stores each scalar field at its own HST path\n\t * (`slug.recordId.fieldname`), descendants at the link-level path (`slug.recordId.linkname`).\n\t *\n\t * @param path - HST path (e.g., \"recipe.r1\")\n\t * @param doctype - The doctype to fetch\n\t * @param recordId - Record ID to fetch\n\t * @param options - Query options (includeNested to control which links are fetched)\n\t * @throws Error with code `\"CLIENT_REQUIRED\"` if no data client is configured\n\t * @throws Error with code `\"RECORD_NOT_FOUND\"` if the server returns null\n\t * @public\n\t */\n\tasync fetchNestedData(\n\t\tpath: string,\n\t\tdoctype: Doctype,\n\t\trecordId: string,\n\t\toptions?: { includeNested?: boolean | string[] }\n\t): Promise<void> {\n\t\tif (!this._client) {\n\t\t\tthrow createCodedError(\n\t\t\t\t'No data client configured. Call setClient() with a DataClient implementation ' +\n\t\t\t\t\t'(e.g., StonecropClient from @stonecrop/graphql-client) before fetching records.',\n\t\t\t\t'CLIENT_REQUIRED'\n\t\t\t)\n\t\t}\n\n\t\tconst result = await this._client.getRecord({ name: doctype.doctype }, recordId, {\n\t\t\tincludeNested: options?.includeNested ?? true,\n\t\t})\n\n\t\tif (!result?.record) {\n\t\t\tthrow createCodedError(`Record not found: ${doctype.doctype} ${recordId}`, 'RECORD_NOT_FOUND')\n\t\t}\n\n\t\t// Store each scalar field at its own HST path, descendants at link-level path\n\t\tconst slug = doctype.slug\n\t\tthis.ensureDoctypeExists(slug)\n\n\t\t// Ensure the ancestor path exists in HST before setting descendant fields\n\t\tconst existingData = this.hstStore.get(`${slug}.${recordId}`)\n\t\tif (!existingData) {\n\t\t\tthis.hstStore.set(`${slug}.${recordId}`, {}, 'system')\n\t\t}\n\n\t\tfor (const [key, value] of Object.entries(result.record)) {\n\t\t\tthis.hstStore.set(`${slug}.${recordId}.${key}`, value, 'system')\n\t\t}\n\t}\n\n\t/**\n\t * Recursively collect nested data from HST\n\t * @param basePath - The base path in HST (e.g., \"customer.123.address\")\n\t * @param doctype - The doctype whose links drive the recursive traversal\n\t * @returns The collected data object\n\t */\n\tprivate collectNestedData(basePath: string, doctype: Doctype): Record<string, any> {\n\t\tconst data = this.hstStore.get(basePath) || {}\n\t\tconst payload: Record<string, any> = { ...data }\n\n\t\tif (!doctype.links) return payload\n\n\t\tfor (const [fieldname, link] of Object.entries(doctype.links)) {\n\t\t\tconst fieldPath = `${basePath}.${fieldname}`\n\t\t\tconst isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne'\n\n\t\t\tif (isMany) {\n\t\t\t\tconst arrayData = this.hstStore.get(fieldPath)\n\t\t\t\tif (Array.isArray(arrayData)) {\n\t\t\t\t\tpayload[fieldname] = arrayData\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst targetDoctype = this.registry.getDoctype(link.target)\n\t\t\t\tif (targetDoctype?.links) {\n\t\t\t\t\tpayload[fieldname] = this.collectNestedData(fieldPath, targetDoctype)\n\t\t\t\t} else {\n\t\t\t\t\tpayload[fieldname] = this.hstStore.get(fieldPath) || {}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn payload\n\t}\n}\n\n/**\n * Create an Error with a `code` property for programmatic error handling.\n * @internal\n */\ninterface CodedError extends Error {\n\tcode: string\n}\n\nfunction createCodedError(message: string, code: string): CodedError {\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- extending Error with code property; CodedError cast is the standard pattern for typed error objects\n\tconst error = new Error(message) as CodedError\n\terror.code = code\n\treturn error\n}\n","import { type ResolvedField } from '@stonecrop/aform'\nimport { storeToRefs } from 'pinia'\nimport { inject, onMounted, Ref, ref, watch, provide, computed } from 'vue'\n\nimport Doctype from '../doctype'\nimport { isDraftRecordId } from '../draft'\nimport Registry from '../registry'\nimport { Stonecrop } from '../stonecrop'\nimport type { HSTNode } from '../types/hst'\nimport type { BaseStonecropReturn, HSTStonecropReturn, HSTChangeData, OperationLogAPI } from '../types/composable'\nimport type { HSTOperation, OperationLogConfig } from '../types/operation-log'\nimport type { RouteContext } from '../types/registry'\n\n/**\n * Unified Stonecrop composable - handles both general operations and HST reactive integration.\n *\n * Called with no doctype, it returns the Stonecrop instance and the operation log, and touches\n * the network not at all. Name a doctype to get the HST surface.\n *\n * @returns The Stonecrop instance and the operation log\n * @public\n */\nexport function useStonecrop(): BaseStonecropReturn\n/**\n * Unified Stonecrop composable with HST integration for a specific doctype and record.\n *\n * When a `Doctype` instance is passed, all synchronous initialisation (`hstStore`,\n * `resolvedSchema`, `formData`, `handleHSTChange`, operation-log wiring) is performed\n * during `setup()` — before the first render and without awaiting any lifecycle hook.\n * Callers can read `hstStore.value`, `resolvedSchema.value`, and `formData.value`\n * immediately after calling this composable; no `nextTick`, `flushPromises`, or\n * `setTimeout` is required.\n *\n * The only async work in `onMounted` is fetching an existing record from the server when\n * `recordId` is not a draft, and lazy-loading a doctype by slug string. Both need a doctype\n * named here — nothing is inferred from the route.\n *\n * @param options - Configuration with doctype (string slug or Doctype instance) and optional recordId\n * @returns Stonecrop instance with full HST integration utilities\n * @public\n */\nexport function useStonecrop(options: {\n\tregistry?: Registry\n\tdoctype: Doctype | string\n\trecordId?: string\n}): HSTStonecropReturn\n/**\n * @public\n */\nexport function useStonecrop(options?: {\n\tregistry?: Registry\n\tdoctype?: Doctype | string\n\trecordId?: string\n}): BaseStonecropReturn | HSTStonecropReturn {\n\tif (!options) options = {}\n\n\tconst registry = options.registry || inject<Registry>('$registry')\n\tconst providedStonecrop = inject<Stonecrop>('$stonecrop')\n\tconst stonecrop = ref<Stonecrop | undefined>()\n\tconst hstStore = ref<HSTNode>()\n\tconst formData = ref<Record<string, any>>({})\n\n\t// Resolved schema with nested Doctype fields expanded\n\tconst resolvedSchema = ref<ResolvedField[]>([])\n\n\t// Loading state for lazy-loaded doctypes\n\tconst isLoading = ref(false)\n\tconst error = ref<Error | null>(null)\n\tconst resolvedDoctype = ref<Doctype | undefined>()\n\n\t// Workflow readiness computed properties\n\tconst isWorkflowReady = computed(() => {\n\t\tif (!stonecrop.value || !resolvedDoctype.value || !options.recordId || isDraftRecordId(options.recordId)) {\n\t\t\treturn true\n\t\t}\n\t\tconst status = stonecrop.value.isWorkflowReady(resolvedDoctype.value, options.recordId)\n\t\treturn status.ready\n\t})\n\n\tconst blockedLinks = computed(() => {\n\t\tif (!stonecrop.value || !resolvedDoctype.value || !options.recordId || isDraftRecordId(options.recordId)) {\n\t\t\treturn []\n\t\t}\n\t\tconst status = stonecrop.value.isWorkflowReady(resolvedDoctype.value, options.recordId)\n\t\treturn status.blockedLinks ?? []\n\t})\n\n\t// Initialize stonecrop instance synchronously using singleton pattern\n\t// Use injected instance if available, otherwise fall back to the singleton root\n\tconst stonecropInstance = providedStonecrop || Stonecrop._root\n\tif (stonecropInstance) {\n\t\tstonecrop.value = stonecropInstance\n\t}\n\n\t// If doctype is a Doctype instance (not string), set resolved immediately\n\tif (options?.doctype && typeof options.doctype !== 'string') {\n\t\tresolvedDoctype.value = options.doctype\n\t}\n\n\t// Operation log state and methods\n\tconst operations = ref<HSTOperation[]>([])\n\tconst currentIndex = ref(-1)\n\tconst canUndo = computed(() => stonecrop.value?.getOperationLogStore().canUndo ?? false)\n\tconst canRedo = computed(() => stonecrop.value?.getOperationLogStore().canRedo ?? false)\n\tconst undoCount = computed(() => stonecrop.value?.getOperationLogStore().undoCount ?? 0)\n\tconst redoCount = computed(() => stonecrop.value?.getOperationLogStore().redoCount ?? 0)\n\tconst undoRedoState = computed(\n\t\t() =>\n\t\t\tstonecrop.value?.getOperationLogStore().undoRedoState ?? {\n\t\t\t\tcanUndo: false,\n\t\t\t\tcanRedo: false,\n\t\t\t\tundoCount: 0,\n\t\t\t\tredoCount: 0,\n\t\t\t\tcurrentIndex: -1,\n\t\t\t}\n\t)\n\n\t// Operation log methods\n\tconst undo = (hstNode: HSTNode): boolean => {\n\t\treturn stonecrop.value?.getOperationLogStore().undo(hstNode) ?? false\n\t}\n\n\tconst redo = (hstNode: HSTNode): boolean => {\n\t\treturn stonecrop.value?.getOperationLogStore().redo(hstNode) ?? false\n\t}\n\n\tconst startBatch = () => {\n\t\tstonecrop.value?.getOperationLogStore().startBatch()\n\t}\n\n\tconst commitBatch = (description?: string): string | null => {\n\t\treturn stonecrop.value?.getOperationLogStore().commitBatch(description) ?? null\n\t}\n\n\tconst cancelBatch = () => {\n\t\tstonecrop.value?.getOperationLogStore().cancelBatch()\n\t}\n\n\tconst clear = () => {\n\t\tstonecrop.value?.getOperationLogStore().clear()\n\t}\n\n\tconst getOperationsFor = (doctype: string, recordId?: string) => {\n\t\treturn stonecrop.value?.getOperationLogStore().getOperationsFor(doctype, recordId) ?? []\n\t}\n\n\tconst getSnapshot = () => {\n\t\treturn (\n\t\t\tstonecrop.value?.getOperationLogStore().getSnapshot() ?? {\n\t\t\t\toperations: [],\n\t\t\t\tcurrentIndex: -1,\n\t\t\t\ttotalOperations: 0,\n\t\t\t\treversibleOperations: 0,\n\t\t\t\tirreversibleOperations: 0,\n\t\t\t}\n\t\t)\n\t}\n\n\tconst markIrreversible = (operationId: string, reason: string) => {\n\t\tstonecrop.value?.getOperationLogStore().markIrreversible(operationId, reason)\n\t}\n\n\tconst logAction = (\n\t\tdoctype: string,\n\t\tactionName: string,\n\t\trecordIds?: string[],\n\t\tresult: 'success' | 'failure' | 'pending' = 'success',\n\t\terrorMessage?: string\n\t): string => {\n\t\treturn stonecrop.value?.getOperationLogStore().logAction(doctype, actionName, recordIds, result, errorMessage) ?? ''\n\t}\n\n\tconst configure = (config: Partial<OperationLogConfig>) => {\n\t\tstonecrop.value?.getOperationLogStore().configure(config)\n\t}\n\n\t// Wire operation log reactive state synchronously — no lifecycle hook needed.\n\t// storeToRefs and watch are both safe to call in setup() body.\n\tif (registry && stonecrop.value) {\n\t\ttry {\n\t\t\tconst opLogStore = stonecrop.value.getOperationLogStore()\n\t\t\tconst opLogRefs = storeToRefs(opLogStore)\n\t\t\toperations.value = opLogRefs.operations.value\n\t\t\tcurrentIndex.value = opLogRefs.currentIndex.value\n\n\t\t\t// Watch for changes in operation log state\n\t\t\twatch(\n\t\t\t\t() => opLogRefs.operations.value,\n\t\t\t\tnewOps => {\n\t\t\t\t\toperations.value = newOps\n\t\t\t\t}\n\t\t\t)\n\t\t\twatch(\n\t\t\t\t() => opLogRefs.currentIndex.value,\n\t\t\t\tnewIndex => {\n\t\t\t\t\tcurrentIndex.value = newIndex\n\t\t\t\t}\n\t\t\t)\n\t\t} catch {\n\t\t\t// Pinia not available — operation log is optional, silently skip\n\t\t}\n\t}\n\n\t// Synchronous HST initialisation for an explicit Doctype instance.\n\t// When the caller passes a Doctype object (not a slug string), every piece of\n\t// setup that doesn't require network I/O runs here during setup() so that\n\t// hstStore, resolvedSchema, and formData are populated before the first render\n\t// and are immediately available to callers without any await.\n\tif (options.doctype && typeof options.doctype !== 'string' && registry && stonecrop.value) {\n\t\thstStore.value = stonecrop.value.getStore()\n\t\tresolvedSchema.value = registry.resolveSchema(options.doctype)\n\t\tif (!options.recordId || isDraftRecordId(options.recordId)) {\n\t\t\tformData.value = registry.initializeRecord(resolvedSchema.value)\n\t\t}\n\t\tif (hstStore.value) {\n\t\t\tsetupDeepReactivity(options.doctype, options.recordId || 'new', formData, hstStore.value)\n\t\t}\n\t}\n\n\t// onMounted handles only work that is genuinely async: lazy-loading a doctype by slug and\n\t// fetching an existing record from the server. Both require the caller to name a doctype.\n\t//\n\t// Rejected: inferring the doctype from the route when the caller names none. Every output of\n\t// that inference landed in refs the no-argument callers never read — all of them wanted the\n\t// instance, which is resolved synchronously above — so each paid a getMeta plus a getRecord to\n\t// read a value already in hand. It also lowercased the route's record id, which silently missed\n\t// any natural key carrying uppercase.\n\tonMounted(async () => {\n\t\tif (!registry || !stonecrop.value) {\n\t\t\treturn\n\t\t}\n\n\t\t// Handle HST integration if doctype is provided explicitly\n\t\tif (options.doctype) {\n\t\t\tconst recordId = options.recordId\n\n\t\t\tif (typeof options.doctype === 'string') {\n\t\t\t\t// String doctype — resolve lazily, then do full sync-equivalent setup here.\n\t\t\t\tconst doctypeSlug = options.doctype\n\t\t\t\thstStore.value = stonecrop.value.getStore()\n\t\t\t\tisLoading.value = true\n\t\t\t\terror.value = null\n\n\t\t\t\tlet doctype: Doctype | undefined\n\t\t\t\ttry {\n\t\t\t\t\t// Check if already in registry\n\t\t\t\t\tdoctype = registry.getDoctype(doctypeSlug)\n\n\t\t\t\t\tif (!doctype && registry.getMeta) {\n\t\t\t\t\t\t// Lazy-load via getMeta\n\t\t\t\t\t\tconst routeContext: RouteContext = {\n\t\t\t\t\t\t\tpath: `/${doctypeSlug}`,\n\t\t\t\t\t\t\tsegments: [doctypeSlug],\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdoctype = await registry.getMeta(routeContext)\n\t\t\t\t\t\tif (doctype) {\n\t\t\t\t\t\t\tregistry.addDoctype(doctype)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!doctype) {\n\t\t\t\t\t\terror.value = new Error(`Doctype '${doctypeSlug}' not found in registry and getMeta returned no result`)\n\t\t\t\t\t}\n\t\t\t\t} catch (e) {\n\t\t\t\t\terror.value = e instanceof Error ? e : new Error(String(e))\n\t\t\t\t} finally {\n\t\t\t\t\tisLoading.value = false\n\t\t\t\t}\n\n\t\t\t\tresolvedDoctype.value = doctype\n\t\t\t\tif (!doctype) return\n\n\t\t\t\tresolvedSchema.value = registry.resolveSchema(doctype)\n\n\t\t\t\tif (recordId && !isDraftRecordId(recordId)) {\n\t\t\t\t\tconst existingRecord = stonecrop.value.getRecordById(doctype, recordId)\n\t\t\t\t\tif (existingRecord) {\n\t\t\t\t\t\tformData.value = existingRecord.get('') || {}\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait stonecrop.value.getRecord(doctype, recordId)\n\t\t\t\t\t\t\tconst loadedRecord = stonecrop.value.getRecordById(doctype, recordId)\n\t\t\t\t\t\t\tif (loadedRecord) {\n\t\t\t\t\t\t\t\tformData.value = loadedRecord.get('') || {}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tformData.value = registry.initializeRecord(resolvedSchema.value)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tformData.value = registry.initializeRecord(resolvedSchema.value)\n\t\t\t\t}\n\n\t\t\t\tif (hstStore.value) {\n\t\t\t\t\tsetupDeepReactivity(doctype, recordId || 'new', formData, hstStore.value)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Doctype instance — sync init was done during setup().\n\t\t\t\t// Only handle the async path: fetching an existing record from the server.\n\t\t\t\tif (recordId && !isDraftRecordId(recordId)) {\n\t\t\t\t\tconst doctype = options.doctype\n\t\t\t\t\tconst existingRecord = stonecrop.value.getRecordById(doctype, recordId)\n\t\t\t\t\tif (existingRecord) {\n\t\t\t\t\t\tformData.value = existingRecord.get('') || {}\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait stonecrop.value.getRecord(doctype, recordId)\n\t\t\t\t\t\t\tconst loadedRecord = stonecrop.value.getRecordById(doctype, recordId)\n\t\t\t\t\t\t\tif (loadedRecord) {\n\t\t\t\t\t\t\t\tformData.value = loadedRecord.get('') || {}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tformData.value = registry.initializeRecord(resolvedSchema.value)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\n\t// HST integration functions - always created but only populated when HST is available\n\tconst provideHSTPath = (fieldname: string, customRecordId?: string): string => {\n\t\tconst doctype = resolvedDoctype.value\n\t\tif (!doctype) return ''\n\n\t\tconst actualRecordId = customRecordId || options.recordId || 'new'\n\t\treturn `${doctype.slug}.${actualRecordId}.${fieldname}`\n\t}\n\n\tconst handleHSTChange = (changeData: HSTChangeData): void => {\n\t\tconst doctype = resolvedDoctype.value\n\t\tif (!hstStore.value || !stonecrop.value || !doctype) {\n\t\t\treturn\n\t\t}\n\n\t\ttry {\n\t\t\tconst pathParts = changeData.path.split('.')\n\t\t\tif (pathParts.length >= 2) {\n\t\t\t\tconst doctypeSlug = pathParts[0]\n\t\t\t\tconst recordId = pathParts[1]\n\n\t\t\t\tif (!hstStore.value.has(`${doctypeSlug}.${recordId}`)) {\n\t\t\t\t\tstonecrop.value.addRecord(doctype, recordId, { ...formData.value })\n\t\t\t\t}\n\n\t\t\t\tif (pathParts.length > 3) {\n\t\t\t\t\tconst recordPath = `${doctypeSlug}.${recordId}`\n\t\t\t\t\tconst nestedParts = pathParts.slice(2)\n\n\t\t\t\t\tlet currentPath = recordPath\n\t\t\t\t\tfor (let i = 0; i < nestedParts.length - 1; i++) {\n\t\t\t\t\t\tcurrentPath += `.${nestedParts[i]}`\n\n\t\t\t\t\t\tif (!hstStore.value.has(currentPath)) {\n\t\t\t\t\t\t\tconst nextPart = nestedParts[i + 1]\n\t\t\t\t\t\t\tconst isArray = !isNaN(Number(nextPart))\n\t\t\t\t\t\t\thstStore.value.set(currentPath, isArray ? [] : {})\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\thstStore.value.set(changeData.path, changeData.value)\n\n\t\t\tconst fieldParts = changeData.fieldname.split('.')\n\t\t\tconst newFormData = { ...formData.value }\n\n\t\t\tif (fieldParts.length === 1) {\n\t\t\t\tnewFormData[fieldParts[0]] = changeData.value\n\t\t\t} else {\n\t\t\t\tupdateNestedObject(newFormData, fieldParts, changeData.value)\n\t\t\t}\n\n\t\t\tformData.value = newFormData\n\t\t} catch {\n\t\t\t// Silently handle errors\n\t\t}\n\t}\n\n\t// Provide injection tokens if HST will be available\n\tif (options.doctype) {\n\t\tprovide('hstPathProvider', provideHSTPath)\n\t\tprovide('hstChangeHandler', handleHSTChange)\n\t}\n\n\t/**\n\t * Scaffold empty descendant records from defaults for all descendant links.\n\t * Delegates to Stonecrop.initializeNestedData method.\n\t * @param path - The HST path where initialized data should be stored\n\t * @param doctype - The doctype to initialize\n\t */\n\tconst initializeNestedData = (path: string, doctype: Doctype): void => {\n\t\tif (!stonecrop.value) {\n\t\t\tthrow new Error('Stonecrop instance not available')\n\t\t}\n\t\treturn stonecrop.value.initializeNestedData(path, doctype)\n\t}\n\n\t/**\n\t * Fetch a record and its nested data from the server.\n\t * Delegates to Stonecrop.fetchNestedData method.\n\t * @param path - The HST path (e.g., \"recipe.r1\")\n\t * @param doctype - The doctype to fetch\n\t * @param recordId - Record ID to fetch\n\t * @param options - Query options (includeNested to control which links are fetched)\n\t */\n\tconst fetchNestedData = async (\n\t\tpath: string,\n\t\tdoctype: Doctype,\n\t\trecordId: string,\n\t\tfetchOptions?: { includeNested?: boolean | string[] }\n\t): Promise<void> => {\n\t\tif (!stonecrop.value) {\n\t\t\tthrow new Error('Stonecrop instance not available')\n\t\t}\n\t\treturn stonecrop.value.fetchNestedData(path, doctype, recordId, fetchOptions)\n\t}\n\n\t/**\n\t * Collect a record payload with all nested doctype fields from HST\n\t * Delegates to Stonecrop.collectRecordPayload method\n\t * @param doctype - The doctype metadata\n\t * @param recordId - The record ID to collect\n\t * @returns The complete record payload ready for API submission\n\t */\n\tconst collectRecordPayload = (doctype: Doctype, recordId: string): Record<string, any> => {\n\t\tif (!stonecrop.value) {\n\t\t\tthrow new Error('Stonecrop instance not available')\n\t\t}\n\t\treturn stonecrop.value.collectRecordPayload(doctype, recordId)\n\t}\n\n\t/**\n\t * Create a nested context for descendant forms\n\t * @param basePath - The base path for the nested context (e.g., \"customer.123.address\")\n\t * @param _descendantDoctype - The descendant doctype metadata (unused but kept for API consistency)\n\t * @returns Object with scoped provideHSTPath and handleHSTChange\n\t */\n\tconst createNestedContext = (basePath: string, _descendantDoctype: Doctype) => {\n\t\tconst nestedProvideHSTPath = (fieldname: string): string => {\n\t\t\treturn `${basePath}.${fieldname}`\n\t\t}\n\n\t\tconst nestedHandleHSTChange = (changeData: HSTChangeData): void => {\n\t\t\t// Update the path to be relative to the nested base path\n\t\t\tconst nestedPath = changeData.path.startsWith(basePath) ? changeData.path : `${basePath}.${changeData.fieldname}`\n\n\t\t\thandleHSTChange({\n\t\t\t\t...changeData,\n\t\t\t\tpath: nestedPath,\n\t\t\t})\n\t\t}\n\n\t\treturn {\n\t\t\tprovideHSTPath: nestedProvideHSTPath,\n\t\t\thandleHSTChange: nestedHandleHSTChange,\n\t\t}\n\t}\n\n\t// Create operation log API object\n\tconst operationLog: OperationLogAPI = {\n\t\toperations,\n\t\tcurrentIndex,\n\t\tundoRedoState,\n\t\tcanUndo,\n\t\tcanRedo,\n\t\tundoCount,\n\t\tredoCount,\n\t\tundo,\n\t\tredo,\n\t\tstartBatch,\n\t\tcommitBatch,\n\t\tcancelBatch,\n\t\tclear,\n\t\tgetOperationsFor,\n\t\tgetSnapshot,\n\t\tmarkIrreversible,\n\t\tlogAction,\n\t\tconfigure,\n\t}\n\t// Always return HST functions if doctype is provided or will be loaded from router\n\tif (options.doctype) {\n\t\t// Explicit doctype - return HST immediately\n\t\treturn {\n\t\t\tstonecrop,\n\t\t\toperationLog,\n\t\t\tprovideHSTPath,\n\t\t\thandleHSTChange,\n\t\t\thstStore,\n\t\t\tformData,\n\t\t\tresolvedSchema,\n\t\t\tinitializeNestedData,\n\t\t\tfetchNestedData,\n\t\t\tcollectRecordPayload,\n\t\t\tcreateNestedContext,\n\t\t\tisLoading,\n\t\t\terror,\n\t\t\tresolvedDoctype,\n\t\t\tisWorkflowReady,\n\t\t\tblockedLinks,\n\t\t} satisfies HSTStonecropReturn\n\t}\n\n\t// No doctype named: the instance and the operation log are everything this can offer.\n\treturn {\n\t\tstonecrop,\n\t\toperationLog,\n\t}\n}\n\n/**\n * Setup deep reactivity between form data and HST store\n */\nfunction setupDeepReactivity(\n\tdoctype: Doctype,\n\trecordId: string,\n\tformData: Ref<Record<string, any>>,\n\thstStore: HSTNode\n): void {\n\twatch(\n\t\tformData,\n\t\tnewData => {\n\t\t\tconst recordPath = `${doctype.slug}.${recordId}`\n\n\t\t\tObject.keys(newData).forEach(fieldname => {\n\t\t\t\tconst path = `${recordPath}.${fieldname}`\n\t\t\t\ttry {\n\t\t\t\t\thstStore.set(path, newData[fieldname])\n\t\t\t\t} catch {\n\t\t\t\t\t// Silently handle errors\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\t{ deep: true }\n\t)\n}\n\n/**\n * Update nested object with dot-notation path\n */\nfunction updateNestedObject(obj: any, path: string[], value: any): void {\n\tlet current: Record<string, any> = obj\n\n\tfor (let i = 0; i < path.length - 1; i++) {\n\t\tconst key = path[i]\n\n\t\tif (!(key in current) || typeof current[key] !== 'object') {\n\t\t\tcurrent[key] = isNaN(Number(path[i + 1])) ? {} : []\n\t\t}\n\n\t\tcurrent = current[key]\n\t}\n\n\tconst finalKey = path[path.length - 1]\n\tcurrent[finalKey] = value\n}\n","import type { WorkflowMeta } from '@stonecrop/schema'\nimport { useRouter } from 'vue-router'\n\nimport { executeClientHandler } from './client-handler'\nimport { useStonecrop } from './composables/stonecrop'\nimport Doctype from './doctype'\nimport { isDraftRecordId } from './draft'\nimport type {\n\tActionDispatchResult,\n\tActionEventPayload,\n\tActionFailure,\n\tFollowRecordContext,\n\tUseClientActionOptions,\n} from './types/client-action'\n\n/**\n * The identity a server response settled on, or `undefined` when it did not state one.\n *\n * Deliberately stricter than `getRecordId`: that falls back to `id` when the declared key is\n * absent, which here would let a handler returning a partial record (say `{ id, total }` for a\n * natural-keyed doctype) look like a rename and relocate the record to a key the adapter cannot\n * look up. An action whose result carries no identity at all — a `{ state }` outcome — leaves the\n * record exactly where it is.\n */\nfunction settledRecordId(doctype: Doctype, record: Record<string, unknown>): string | undefined {\n\tif (record[doctype.recordIdField] === undefined) return undefined\n\treturn doctype.getRecordId(record)\n}\n\n/**\n * Default failure surface: a blocking alert beats a silent `console.error` for a failed action\n * (e.g. a Save that the server refused), and there is no notification system in the framework to\n * route it into. A host with one passes `onError` and this is never called.\n */\nfunction notifyActionError(failure: ActionFailure): void {\n\tconsole.error('Action failed:', failure.message)\n\tif (typeof window !== 'undefined') window.alert(failure.message)\n}\n\n/**\n * Shared executor for doctype action clicks. A host's Desktop `@action` handler delegates\n * here so every host runs the same logic from one definition:\n *\n * - If the clicked action carries a `clientHandler`, run it. The handler **owns\n * orchestration** — it calls `runAction` itself when it needs the server, navigates via\n * `router`, reads `record`, or queries `graphql`. It supersedes the default dispatch.\n * - Otherwise dispatch the action to its server `handler` (the pre-existing behavior),\n * so actions without a `clientHandler` are unchanged.\n *\n * `runAction` is the only blessed write: it dispatches **and** leaves the store consistent,\n * filing the returned record under the identity the *server* settled on and following the route\n * there when that differs from the one dispatched. For a created record those are never the same,\n * which is what makes hand-rolling this reliably wrong.\n *\n * The store write itself lives one layer down, in {@link Stonecrop.dispatchAction}, so a host that\n * never adopts this composable still cannot file a record under the wrong key. What stays here is\n * only what needs the *dispatched* id: dropping the stale key, and moving the route.\n *\n * Pass `buildArgs` to change the argument envelope your backend receives, `followRecord` to change\n * where a created record sends the user, and `onError` to route failures into your own\n * notification system. Identity resolution and HST keying are deliberately not configurable — see\n * {@link UseClientActionOptions}.\n *\n * @public\n */\nexport function useClientAction(options: UseClientActionOptions = {}) {\n\tconst { stonecrop } = useStonecrop()\n\t// Called during setup so the injection is available; the registry fallback below covers a\n\t// caller outside an injection context, and a host that installed the plugin with `{ router }`.\n\tconst injectedRouter = useRouter()\n\tconst onError = options.onError ?? notifyActionError\n\n\tconst resolveRouter = () => injectedRouter ?? stonecrop.value?.registry.router\n\n\tconst buildArgs =\n\t\toptions.buildArgs ??\n\t\t// Spreading `undefined` in an object literal adds nothing, so `extra` needs no fallback.\n\t\t(({ recordId, isDraft, data, extra }) => [{ ...(isDraft ? {} : { id: recordId }), data, ...extra }])\n\n\tconst followRecord =\n\t\toptions.followRecord ??\n\t\t(async ({ doctype, recordId }: FollowRecordContext) => {\n\t\t\tawait resolveRouter()?.replace(`/${doctype}/${recordId}`)\n\t\t})\n\n\t/**\n\t * Dispatch `action` for the record and reconcile the store and the route with whichever\n\t * identity the result carries.\n\t */\n\tasync function dispatchAndWriteback(\n\t\tdoctypeSlug: string,\n\t\trecordId: string,\n\t\tdata: Record<string, unknown>,\n\t\taction: string,\n\t\textra?: Record<string, unknown>\n\t): Promise<ActionDispatchResult> {\n\t\tconst sc = stonecrop.value\n\t\tif (!sc) return { success: false, data: null, error: 'Stonecrop is not initialized' }\n\n\t\tconst doctype = sc.registry.getDoctype(doctypeSlug)\n\t\tif (!doctype) return { success: false, data: null, error: `Unknown doctype: ${doctypeSlug}` }\n\n\t\t// A draft omits the id, which the write path reads as \"create\". Sending the route segment\n\t\t// instead reaches the same branch by accident — via a lookup for a record named `new`.\n\t\tconst isDraft = isDraftRecordId(recordId)\n\t\tconst result = await sc.dispatchAction(\n\t\t\tdoctype,\n\t\t\taction,\n\t\t\tbuildArgs({ doctype: doctypeSlug, action, recordId, isDraft, data, extra })\n\t\t)\n\n\t\tif (result.success && result.data) {\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the action result payload is an opaque JSON scalar; every adapter returns the record as an object\n\t\t\tconst record = result.data as Record<string, unknown>\n\t\t\tconst settledId = settledRecordId(doctype, record)\n\n\t\t\tif (settledId === undefined) {\n\t\t\t\t// The result states no identity of its own — a `{ state }` outcome. `dispatchAction`\n\t\t\t\t// could not file it, because only this layer knows which record was dispatched. A\n\t\t\t\t// draft has nowhere to put it: filing it under the route segment would leave a\n\t\t\t\t// record named `new` in the list view.\n\t\t\t\tif (!isDraft) sc.addRecord(doctypeSlug, recordId, record)\n\t\t\t\treturn result\n\t\t\t}\n\n\t\t\t// `dispatchAction` has already filed the record under `settledId`. Only the two steps\n\t\t\t// that need the dispatched id are left.\n\t\t\tif (recordId !== settledId) {\n\t\t\t\t// No-op for a draft, which was never in the store — `removeRecord` checks first.\n\t\t\t\tsc.removeRecord(doctypeSlug, recordId)\n\t\t\t\tawait followRecord({ doctype: doctypeSlug, recordId: settledId, previousRecordId: recordId })\n\t\t\t}\n\t\t}\n\t\treturn result\n\t}\n\n\t/**\n\t * Handle a Desktop `@action` event: run the action's `clientHandler` if present,\n\t * else dispatch to the server handler.\n\t */\n\tasync function run(payload: ActionEventPayload): Promise<void> {\n\t\tconst sc = stonecrop.value\n\t\tif (!sc) return\n\n\t\tconst { name, doctype: doctypeSlug, recordId, data } = payload\n\n\t\tconst doctype = sc.registry.getDoctype(doctypeSlug)\n\t\t// `workflow` is a union (XState | WorkflowMeta); only WorkflowMeta carries an\n\t\t// `actions` map with `clientHandler`. An XState workflow has no `actions`, so the\n\t\t// lookup is undefined and we fall through to the server dispatch.\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowing the workflow union to read the optional actions map\n\t\tconst workflow = doctype?.workflow as WorkflowMeta | undefined\n\t\tconst clientHandler = workflow?.actions?.[name]?.clientHandler\n\n\t\ttry {\n\t\t\tif (!clientHandler) {\n\t\t\t\t// No client handler — preserve the existing server-dispatch behavior.\n\t\t\t\tconst result = await dispatchAndWriteback(doctypeSlug, recordId, data, name)\n\t\t\t\tif (!result.success) {\n\t\t\t\t\tonError({\n\t\t\t\t\t\tmessage: result.error ?? `Action \"${name}\" failed`,\n\t\t\t\t\t\taction: name,\n\t\t\t\t\t\tdoctype: doctypeSlug,\n\t\t\t\t\t\trecordId,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Client handler present — it owns orchestration. Assemble the capability map.\n\t\t\t// Prefer the live HST record; fall back to the form snapshot in the payload.\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- HSTNode.get returns any; a record node is always an object of field values\n\t\t\tconst record = (sc.getRecordById(doctypeSlug, recordId)?.get('') as Record<string, unknown> | undefined) ?? data\n\n\t\t\tconst runAction = (action: string, extra?: Record<string, unknown>) =>\n\t\t\t\tdispatchAndWriteback(doctypeSlug, recordId, data, action, extra)\n\n\t\t\t// Read-only GraphQL escape hatch — no mutation is injected (a raw mutation would\n\t\t\t// bypass the dispatch and leave HST stale). `query` is the GraphQL transport's\n\t\t\t// method, not part of the abstract DataClient interface (a non-GraphQL client may\n\t\t\t// not support it), so probe for it structurally and reject if unsupported.\n\t\t\tconst graphql = {\n\t\t\t\tquery<T = unknown>(query: string, variables?: Record<string, unknown>): Promise<T> {\n\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- probing DataClient for the GraphQL transport's `query`, which the abstract interface deliberately does not declare\n\t\t\t\t\tconst client = sc.getClient() as unknown as\n\t\t\t\t\t\t| { query?: <R>(q: string, v?: Record<string, unknown>) => Promise<R> }\n\t\t\t\t\t\t| undefined\n\t\t\t\t\tif (!client?.query) {\n\t\t\t\t\t\treturn Promise.reject(new Error('The configured data client does not support graphql.query'))\n\t\t\t\t\t}\n\t\t\t\t\treturn client.query<T>(query, variables)\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tawait executeClientHandler(clientHandler, { router: resolveRouter(), record, runAction, graphql })\n\t\t} catch (error) {\n\t\t\tonError({\n\t\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t\t\taction: name,\n\t\t\t\tdoctype: doctypeSlug,\n\t\t\t\trecordId,\n\t\t\t\tcause: error,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn { run }\n}\n","import type { FetchStrategy, CustomFetch } from '@stonecrop/schema'\nimport { computed, inject, ref } from 'vue'\n\nimport Doctype from '../doctype'\nimport { Stonecrop } from '../stonecrop'\nimport type { LazyLink } from '../types/composable'\n\n/**\n * Get the lazy link state for a specific link field on a doctype record.\n *\n * This composable provides reactive state for lazy-loaded links:\n * - `loading`: true while fetching\n * - `loaded`: true after successful fetch (permanent until reload)\n * - `error`: error state if any\n * - `reload()`: explicitly trigger a fetch\n * - `data`: computed from HST, or undefined if not loaded\n *\n * The reload() function respects the link's fetch strategy:\n * - `sync`: fetches via GraphQL query through fetchNestedData\n * - `lazy`: fetches via GraphQL query through fetchNestedData\n * - `custom`: invokes the serialized handler function directly\n *\n * @param doctype - The doctype instance\n * @param recordId - The record ID\n * @param linkFieldname - The link fieldname to load\n * @returns LazyLink with loading, loaded, error, reload, and data\n * @public\n */\nexport function useLazyLink(doctype: Doctype, recordId: string, linkFieldname: string): LazyLink {\n\tconst stonecropInstance = inject<Stonecrop>('$stonecrop') || Stonecrop._root\n\n\tif (!stonecropInstance) {\n\t\tthrow new Error('Stonecrop instance not available. Ensure useStonecrop() has been called first.')\n\t}\n\n\tconst loading = ref(false)\n\tconst loaded = ref(false)\n\tconst error = ref<Error | null>(null)\n\n\tconst hstStore = stonecropInstance.getStore()\n\n\t/**\n\t * Build the HST path for a lazy link field\n\t */\n\tconst getLinkPath = (): string => {\n\t\tconst slug = doctype.slug || doctype.doctype\n\t\treturn `${slug}.${recordId}.${linkFieldname}`\n\t}\n\n\t/**\n\t * Get the link declaration from the doctype schema\n\t */\n\tconst getLinkDeclaration = (): FetchStrategy | undefined => {\n\t\treturn doctype.links?.[linkFieldname]?.fetch\n\t}\n\n\t/**\n\t * Invoke a custom fetch handler\n\t * The handler is a serialized function string that we execute via new Function()\n\t */\n\tconst invokeCustomHandler = async (handler: CustomFetch['handler']): Promise<any> => {\n\t\ttry {\n\t\t\t// Create function from serialized string and invoke it\n\t\t\t// The function receives the stonecrop instance and path as parameters\n\t\t\t// oxlint-disable-next-line @typescript-eslint/no-implied-eval\n\t\t\tconst fn = new Function(\n\t\t\t\t'stonecrop',\n\t\t\t\t'path',\n\t\t\t\t'hst',\n\t\t\t\t`\n\t\t\t\treturn (${handler})(stonecrop, path, hst)\n\t\t\t`\n\t\t\t)\n\t\t\treturn await fn(stonecropInstance, getLinkPath(), hstStore)\n\t\t} catch (err) {\n\t\t\tthrow new Error(`Custom handler failed: ${err instanceof Error ? err.message : String(err)}`, { cause: err })\n\t\t}\n\t}\n\n\t/**\n\t * Fetch the link data using the appropriate strategy\n\t */\n\tconst fetchLinkData = async (): Promise<void> => {\n\t\tconst linkFetch = getLinkDeclaration()\n\t\tconst ancestorPath = `${doctype.slug || doctype.doctype}.${recordId}`\n\n\t\tif (linkFetch?.method === 'custom') {\n\t\t\t// Ensure ancestor path exists before invoking custom handler\n\t\t\tif (!hstStore.has(ancestorPath)) {\n\t\t\t\thstStore.set(ancestorPath, {}, 'system')\n\t\t\t}\n\n\t\t\t// Custom handler - invoke directly\n\t\t\tconst result = await invokeCustomHandler(linkFetch.handler)\n\n\t\t\t// Store result in HST at the link path\n\t\t\thstStore.set(getLinkPath(), result, 'system')\n\t\t} else {\n\t\t\t// sync or lazy (both use fetchNestedData but with different includeNested)\n\t\t\t// For lazy links, we still use fetchNestedData but only for this specific link\n\t\t\tawait stonecropInstance.fetchNestedData(ancestorPath, doctype, recordId, { includeNested: [linkFieldname] })\n\t\t}\n\t}\n\n\t/**\n\t * Explicitly reload the lazy link data\n\t */\n\tconst reload = async (): Promise<void> => {\n\t\tif (loading.value) return\n\n\t\tloading.value = true\n\t\terror.value = null\n\n\t\ttry {\n\t\t\tawait fetchLinkData()\n\t\t\tloaded.value = true\n\t\t} catch (err) {\n\t\t\terror.value = err instanceof Error ? err : new Error(String(err))\n\t\t\tthrow err\n\t\t} finally {\n\t\t\tloading.value = false\n\t\t}\n\t}\n\n\t/**\n\t * Computed property that returns the loaded data from HST\n\t */\n\tconst data = computed(() => {\n\t\tif (!loaded.value) return undefined\n\t\treturn hstStore.get(getLinkPath())\n\t})\n\n\treturn {\n\t\t// State\n\t\tloading,\n\t\tloaded,\n\t\terror,\n\n\t\t// Computed\n\t\tdata,\n\n\t\t// Actions\n\t\treload,\n\t}\n}\n","import { useMagicKeys, whenever } from '@vueuse/core'\nimport { storeToRefs } from 'pinia'\nimport { getCurrentInstance, inject } from 'vue'\n\nimport type { HSTNode } from '../types/hst'\nimport { useOperationLogStore } from '../stores/operation-log'\nimport type { OperationLogConfig } from '../types/operation-log'\n\n/**\n * Composable for operation log management\n * Provides easy access to undo/redo functionality and operation history\n *\n * @param config - Optional configuration for the operation log\n * @returns Operation log interface\n *\n * @example\n * ```typescript\n * const { undo, redo, canUndo, canRedo, operations, configure } = useOperationLog()\n *\n * // Configure the log\n * configure({\n * maxOperations: 50,\n * enableCrossTabSync: true,\n * enablePersistence: true\n * })\n *\n * // Undo/redo\n * await undo(hstStore)\n * await redo(hstStore)\n * ```\n *\n * @public\n */\nexport function useOperationLog(config?: Partial<OperationLogConfig>) {\n\t// inject() is only valid inside a component setup() context. When this\n\t// composable is called outside one (e.g. directly in test bodies or plain\n\t// scripts) skip the injection entirely and fall back to the Pinia store.\n\tconst injectedStore = getCurrentInstance()\n\t\t? inject<ReturnType<typeof useOperationLogStore> | undefined>('$operationLogStore', undefined)\n\t\t: undefined\n\tconst store = injectedStore || useOperationLogStore()\n\n\t// Apply configuration if provided\n\tif (config) {\n\t\tstore.configure(config)\n\t}\n\n\t// Extract reactive state\n\tconst { operations, currentIndex, undoRedoState, canUndo, canRedo, undoCount, redoCount } = storeToRefs(store)\n\n\t/**\n\t * Undo the last operation\n\t */\n\tfunction undo(hstStore: HSTNode): boolean {\n\t\treturn store.undo(hstStore)\n\t}\n\n\t/**\n\t * Redo the next operation\n\t */\n\tfunction redo(hstStore: HSTNode): boolean {\n\t\treturn store.redo(hstStore)\n\t}\n\n\t/**\n\t * Start a batch operation\n\t */\n\tfunction startBatch() {\n\t\tstore.startBatch()\n\t}\n\n\t/**\n\t * Commit the current batch\n\t */\n\tfunction commitBatch(description?: string): string | null {\n\t\treturn store.commitBatch(description)\n\t}\n\n\t/**\n\t * Cancel the current batch\n\t */\n\tfunction cancelBatch() {\n\t\tstore.cancelBatch()\n\t}\n\n\t/**\n\t * Clear all operations\n\t */\n\tfunction clear() {\n\t\tstore.clear()\n\t}\n\n\t/**\n\t * Get operations for a specific doctype/record\n\t */\n\tfunction getOperationsFor(doctype: string, recordId?: string) {\n\t\treturn store.getOperationsFor(doctype, recordId)\n\t}\n\n\t/**\n\t * Get a snapshot of the operation log\n\t */\n\tfunction getSnapshot() {\n\t\treturn store.getSnapshot()\n\t}\n\n\t/**\n\t * Mark an operation as irreversible\n\t * @param operationId - The ID of the operation to mark\n\t * @param reason - The reason why the operation is irreversible\n\t */\n\tfunction markIrreversible(operationId: string, reason: string) {\n\t\tstore.markIrreversible(operationId, reason)\n\t}\n\n\t/**\n\t * Log an action execution (stateless actions like print, email, etc.)\n\t * @param doctype - The doctype the action was executed on\n\t * @param actionName - The name of the action that was executed\n\t * @param recordIds - Optional array of record IDs the action was executed on\n\t * @param result - The result of the action execution\n\t * @param error - Optional error message if action failed\n\t * @returns The operation ID\n\t */\n\tfunction logAction(\n\t\tdoctype: string,\n\t\tactionName: string,\n\t\trecordIds?: string[],\n\t\tresult: 'success' | 'failure' | 'pending' = 'success',\n\t\terror?: string\n\t): string {\n\t\treturn store.logAction(doctype, actionName, recordIds, result, error)\n\t}\n\n\t/**\n\t * Update configuration\n\t * @param options - Configuration options to update\n\t */\n\tfunction configure(options: Partial<OperationLogConfig>) {\n\t\tstore.configure(options)\n\t}\n\n\treturn {\n\t\t// State\n\t\toperations,\n\t\tcurrentIndex,\n\t\tundoRedoState,\n\t\tcanUndo,\n\t\tcanRedo,\n\t\tundoCount,\n\t\tredoCount,\n\n\t\t// Methods\n\t\tundo,\n\t\tredo,\n\t\tstartBatch,\n\t\tcommitBatch,\n\t\tcancelBatch,\n\t\tclear,\n\t\tgetOperationsFor,\n\t\tgetSnapshot,\n\t\tmarkIrreversible,\n\t\tlogAction,\n\t\tconfigure,\n\t}\n}\n\n/**\n * Keyboard shortcut handler for undo/redo\n * Automatically binds Ctrl+Z (undo) and Ctrl+Shift+Z/Ctrl+Y (redo) using VueUse\n *\n * @param hstStore - The HST store to operate on\n * @param enabled - Whether shortcuts are enabled (default: true)\n *\n * @example\n * ```typescript\n * import { onMounted } from 'vue'\n *\n * const stonecrop = useStonecrop({ doctype, recordId })\n * useUndoRedoShortcuts(stonecrop.hstStore)\n * ```\n *\n * @public\n */\nexport function useUndoRedoShortcuts(hstStore: HSTNode, enabled = true) {\n\tif (!enabled) return\n\n\tconst { undo, redo, canUndo, canRedo } = useOperationLog()\n\tconst keys = useMagicKeys()\n\n\t// Undo shortcuts: Ctrl+Z or Cmd+Z (Mac)\n\twhenever(keys['Ctrl+Z'], () => {\n\t\tif (canUndo.value) {\n\t\t\tundo(hstStore)\n\t\t}\n\t})\n\n\twhenever(keys['Meta+Z'], () => {\n\t\tif (canUndo.value) {\n\t\t\tundo(hstStore)\n\t\t}\n\t})\n\n\t// Redo shortcuts: Ctrl+Shift+Z, Cmd+Shift+Z (Mac), or Ctrl+Y\n\twhenever(keys['Ctrl+Shift+Z'], () => {\n\t\tif (canRedo.value) {\n\t\t\tredo(hstStore)\n\t\t}\n\t})\n\n\twhenever(keys['Meta+Shift+Z'], () => {\n\t\tif (canRedo.value) {\n\t\t\tredo(hstStore)\n\t\t}\n\t})\n\n\twhenever(keys['Ctrl+Y'], () => {\n\t\tif (canRedo.value) {\n\t\t\tredo(hstStore)\n\t\t}\n\t})\n}\n\n/**\n * Batch operation helper\n * Wraps a function execution in a batch operation\n *\n * @param fn - The function to execute within a batch\n * @param description - Optional description for the batch\n * @returns The batch operation ID\n *\n * @example\n * ```typescript\n * const { withBatch } = useOperationLog()\n *\n * const batchId = await withBatch(() => {\n * hstStore.set('task.123.title', 'New Title')\n * hstStore.set('task.123.status', 'active')\n * hstStore.set('task.123.priority', 'high')\n * }, 'Update task details')\n * ```\n *\n * @public\n */\nexport async function withBatch<T>(fn: () => T | Promise<T>, description?: string): Promise<string | null> {\n\tconst { startBatch, commitBatch, cancelBatch } = useOperationLog()\n\n\tstartBatch()\n\n\ttry {\n\t\tawait fn()\n\t\treturn commitBatch(description)\n\t} catch (error) {\n\t\tcancelBatch()\n\t\tthrow error\n\t}\n}\n","import type { DoctypeField, LinkDeclaration, TriggerDefinition, WorkflowMeta } from '@stonecrop/schema'\nimport { getRecordIdentity, getRecordIdField, isActionAllowedInState, normalizeFieldKind } from '@stonecrop/schema'\nimport { List } from 'immutable'\nimport { Component } from 'vue'\n\nimport type { DoctypeConfig, ImmutableDoctype } from './types/doctype'\n\n/**\n * Doctype runtime class with Immutable.js collections for HST change tracking.\n * @public\n */\nexport default class Doctype {\n\t/**\n\t * The doctype name\n\t * @public\n\t * @readonly\n\t */\n\treadonly doctype: string\n\n\t/**\n\t * Alias for doctype (for DoctypeLike interface compatibility)\n\t * @public\n\t * @readonly\n\t */\n\tget name(): string {\n\t\treturn this.doctype\n\t}\n\n\t/**\n\t * The doctype schema\n\t * @public\n\t * @readonly\n\t */\n\treadonly schema: ImmutableDoctype['schema']\n\n\t/**\n\t * The doctype workflow\n\t * @public\n\t * @readonly\n\t */\n\treadonly workflow: ImmutableDoctype['workflow']\n\n\t/**\n\t * The doctype component\n\t * @public\n\t * @readonly\n\t */\n\treadonly component?: Component\n\n\t/**\n\t * Relationship links to other doctypes\n\t * @public\n\t * @readonly\n\t */\n\treadonly links?: Record<string, LinkDeclaration>\n\n\t/**\n\t * Field on this doctype used when displaying a reference to one of its records.\n\t * @public\n\t * @readonly\n\t */\n\treadonly displayField?: string\n\n\t/**\n\t * Creates a new Doctype instance\n\t * @param doctype - The doctype name\n\t * @param schema - The doctype schema definition\n\t * @param workflow - The doctype workflow configuration (XState machine)\n\t * @param component - Optional Vue component for rendering the doctype\n\t * @param links - Optional relationship links to other doctypes\n\t * @param displayField - Optional field used when displaying references to this doctype\n\t */\n\tconstructor(\n\t\tdoctype: string,\n\t\tschema: ImmutableDoctype['schema'],\n\t\tworkflow: ImmutableDoctype['workflow'],\n\t\tcomponent?: Component,\n\t\tlinks?: Record<string, LinkDeclaration>,\n\t\tdisplayField?: string\n\t) {\n\t\tthis.doctype = doctype\n\t\tthis.schema = schema\n\t\tthis.workflow = workflow\n\t\tthis.component = component\n\t\tthis.links = links\n\t\tthis.displayField = displayField\n\t}\n\n\t/**\n\t * Creates a Doctype instance from a plain configuration object.\n\t * Handles conversion of arrays to Immutable.js collections internally.\n\t *\n\t * This is the recommended way to create a Doctype from API responses\n\t * or configuration files, as it encapsulates the Immutable.js construction\n\t * that the framework uses internally.\n\t *\n\t * @param config - Plain object with doctype configuration (typically from API response)\n\t * @returns A new Doctype instance with Immutable.js collections\n\t *\n\t * @example\n\t * ```ts\n\t * // From an API response\n\t * const response = await client.getMeta({ doctype: 'plan' })\n\t * const doctype = Doctype.fromObject(response)\n\t * registry.addDoctype(doctype)\n\t * ```\n\t *\n\t * @example\n\t * ```ts\n\t * // From a configuration object\n\t * const planDoctype = Doctype.fromObject({\n\t * name: 'Plan',\n\t * fields: [\n\t * { fieldname: 'title', label: 'Title', component: 'ATextInput' },\n\t * { fieldname: 'status', label: 'Status', component: 'ATextInput' },\n\t * ],\n\t * workflow: {\n\t * id: 'plan',\n\t * initial: 'draft',\n\t * states: { draft: {}, submitted: {} }\n\t * }\n\t * })\n\t * ```\n\t *\n\t * @public\n\t */\n\tstatic fromObject(config: DoctypeConfig): Doctype {\n\t\t// Authored JSON may omit the `kind` discriminant; the Zod schema injects it via a\n\t\t// preprocess, but this path bypasses Zod. Normalize here so the registry's\n\t\t// `resolveFields` (which gates link/fieldset handling on `field.kind`) sees the same\n\t\t// shape a parsed doctype would — otherwise links silently fail to expand.\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- normalizeFieldKind only injects the `kind` discriminant; the field shape is otherwise preserved\n\t\tconst fields = config.fields?.map(normalizeFieldKind) as DoctypeField[] | undefined\n\t\tconst schema = fields ? List(fields) : List<DoctypeField>()\n\n\t\treturn new Doctype(config.name, schema, config.workflow, undefined, config.links, config.displayField)\n\t}\n\n\t/**\n\t * Returns the raw authoring schema as a plain array.\n\t * For the resolved schema suitable for AForm, use `registry.resolveSchema(doctype)`.\n\t *\n\t * @returns Array of raw DoctypeField authoring definitions\n\t *\n\t * @example\n\t * ```ts\n\t * const fields = doctype.getSchemaArray()\n\t * // Pass to resolveSchema for AForm-ready output:\n\t * const resolved = registry.resolveSchema(doctype)\n\t * ```\n\t *\n\t * @public\n\t */\n\tgetSchemaArray(): DoctypeField[] {\n\t\tif (!this.schema) return []\n\t\treturn this.schema.toArray()\n\t}\n\n\t/**\n\t * Resolve a record's identity using this doctype's declared `primaryKey`, falling back to `id`.\n\t *\n\t * Lives here rather than at the call site because the doctype owns its schema — and because the\n\t * rule must match the server's, which builds its SQL identity predicate from the same declared\n\t * field via `@stonecrop/schema`'s `getPrimaryKeyField`.\n\t *\n\t * @param record - the record to read the identity from\n\t * @returns the identity as a string, or `undefined` when neither the declared key nor `id` yields one\n\t *\n\t * @public\n\t */\n\tgetRecordId(record: Record<string, unknown>): string | undefined {\n\t\treturn getRecordIdentity(this.getSchemaArray(), record)\n\t}\n\n\t/**\n\t * The field a record of this doctype is identified by: the declared `primaryKey`, or `id`\n\t * when nothing is declared.\n\t *\n\t * The client-side twin of the adapters' `recordLookupField`. Both are the same call to\n\t * `@stonecrop/schema`'s `getRecordIdField`, so the field a caller reads an identity out of is\n\t * the same field the adapter builds its lookup predicate on.\n\t *\n\t * Use this to ask whether a record *states* its own identity. `getRecordId` deliberately\n\t * falls back to `id` when the declared key is missing, which is right for resolving a link\n\t * from a record already in hand and wrong for deciding whether a server response settled on\n\t * a new identity: a response that omits a natural key would resolve through that fallback to\n\t * a surrogate the adapter cannot look up.\n\t *\n\t * @returns The identifying fieldname\n\t *\n\t * @public\n\t */\n\tget recordIdField(): string {\n\t\treturn getRecordIdField(this.getSchemaArray())\n\t}\n\n\t/**\n\t * Returns the transitions available from a given workflow state, derived from the\n\t * doctype's workflow configuration. Supports both XState format and WorkflowMeta format.\n\t *\n\t * @param currentState - The state name to read transitions from\n\t * @returns Array of transition descriptors with `name` and `targetState`\n\t *\n\t * @example\n\t * ```ts\n\t * const transitions = doctype.getAvailableTransitions('draft')\n\t * // [{ name: 'SUBMIT', targetState: 'submitted' }]\n\t * ```\n\t *\n\t * @public\n\t */\n\tgetAvailableTransitions(currentState: string): Array<{ name: string; targetState: string }> {\n\t\tconst workflow = this.workflow\n\t\tif (!workflow) return []\n\n\t\t// Check if this is WorkflowMeta format (states is an array) or XState format (states is an object)\n\t\tif (Array.isArray(workflow.states)) {\n\t\t\t// WorkflowMeta format: validate state exists and filter actions by allowedStates\n\t\t\tconst states = workflow.states\n\t\t\tif (!states.includes(currentState)) return []\n\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Array.isArray(workflow.states) confirms WorkflowMeta format above\n\t\t\tconst actions = (workflow as WorkflowMeta).actions\n\t\t\tif (!actions) return []\n\n\t\t\treturn (\n\t\t\t\tObject.entries(actions)\n\t\t\t\t\t// Exclude stateless Commands — they change no state and are surfaced separately\n\t\t\t\t\t// via getAvailableCommands(). Genuine transitions carry a nextState.\n\t\t\t\t\t.filter(([, actionDef]) => !actionDef.stateless && isActionAllowedInState(actionDef, currentState))\n\t\t\t\t\t.map(([name, actionDef]) => ({\n\t\t\t\t\t\tname,\n\t\t\t\t\t\ttargetState: actionDef.nextState ?? currentState,\n\t\t\t\t\t}))\n\t\t\t)\n\t\t}\n\n\t\t// XState format: use the on property of the state\n\t\tconst states = workflow.states\n\t\tif (!states) return []\n\t\tconst stateConfig = states[currentState]\n\t\tif (!stateConfig?.on) return []\n\t\treturn Object.entries(stateConfig.on).map(([name, target]) => ({\n\t\t\tname,\n\t\t\ttargetState: typeof target === 'string' ? target : 'unknown',\n\t\t}))\n\t}\n\n\t/**\n\t * Returns the stateless **Commands** available in a given workflow state — side-effect\n\t * actions (save/print/email…) that do not change workflow state. Unlike transitions,\n\t * Commands may exist on a workflow that declares no `states` (a commands-only doctype),\n\t * and a Command with no `allowedStates` is available in every state.\n\t *\n\t * Only meaningful for WorkflowMeta format; XState workflows have no Commands.\n\t *\n\t * @param currentState - The record's current state, used to honor a Command's `allowedStates`\n\t * @returns Array of command descriptors with `name`\n\t *\n\t * @example\n\t * ```ts\n\t * const commands = doctype.getAvailableCommands('Draft')\n\t * // [{ name: 'Print' }]\n\t * ```\n\t *\n\t * @public\n\t */\n\tgetAvailableCommands(currentState?: string): Array<{ name: string }> {\n\t\tconst workflow = this.workflow\n\t\tif (!workflow) return []\n\n\t\t// Only WorkflowMeta carries an `actions` map; XState workflows have no Commands.\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- probing the workflow union for the optional WorkflowMeta actions map\n\t\tconst actions = (workflow as WorkflowMeta).actions\n\t\tif (!actions) return []\n\n\t\treturn Object.entries(actions)\n\t\t\t.filter(([, actionDef]) => actionDef.stateless === true && isActionAllowedInState(actionDef, currentState ?? ''))\n\t\t\t.map(([name]) => ({ name }))\n\t}\n\n\t/**\n\t * Returns the field-validation **triggers** declared on this doctype's workflow (advisory,\n\t * client-side). Keyed by trigger name. Returns undefined when the workflow is absent, is an\n\t * XState machine (no triggers), or simply declares none.\n\t *\n\t * @returns The `workflow.triggers` map, or undefined\n\t *\n\t * @example\n\t * ```ts\n\t * const triggers = doctype.getTriggers()\n\t * // { dateOrder: { on: ['start_date', 'end_date'], clientHandler: '…' } }\n\t * ```\n\t *\n\t * @public\n\t */\n\tgetTriggers(): Record<string, TriggerDefinition> | undefined {\n\t\tconst workflow = this.workflow\n\t\tif (!workflow) return undefined\n\n\t\t// Only WorkflowMeta carries a `triggers` map; XState workflows have none.\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- probing the workflow union for the optional WorkflowMeta triggers map\n\t\treturn (workflow as WorkflowMeta).triggers\n\t}\n\n\t/**\n\t * Returns metadata for a specific action, if available.\n\t * Only works with WorkflowMeta format; returns undefined for XState format.\n\t *\n\t * @param actionName - The action name to get metadata for\n\t * @returns Action metadata or undefined\n\t *\n\t * @example\n\t * ```ts\n\t * const actionMeta = doctype.getActionMeta('submit')\n\t * // { label: 'Submit', allowedStates: ['draft'] }\n\t * ```\n\t *\n\t * @public\n\t */\n\tgetActionMeta(actionName: string):\n\t\t| {\n\t\t\t\tlabel: string\n\t\t\t\trequiredFields?: string[]\n\t\t\t\tallowedStates?: string[]\n\t\t }\n\t\t| undefined {\n\t\tconst workflow = this.workflow\n\t\tif (!workflow) return undefined\n\n\t\t// Only WorkflowMeta carries an `actions` map (with labels); XState workflows have none.\n\t\t// Don't require a `states` array — a commands-only doctype has labeled actions but no states.\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- probing the workflow union for the optional WorkflowMeta actions map\n\t\tconst actions = (workflow as WorkflowMeta).actions\n\t\treturn actions?.[actionName]\n\t}\n\n\t/**\n\t * Converts the registered doctype string to a slug (kebab-case). The following conversions are made:\n\t * - It replaces camelCase and PascalCase with kebab-case strings\n\t * - It replaces spaces and underscores with hyphens\n\t * - It converts the string to lowercase\n\t *\n\t * @returns The slugified doctype string\n\t *\n\t * @example\n\t * ```ts\n\t * const doctype = new Doctype('TaskItem', schema, workflow, actions)\n\t * console.log(doctype.slug) // 'task-item'\n\t * ```\n\t *\n\t * @public\n\t */\n\tget slug() {\n\t\treturn this.doctype\n\t\t\t.replace(/([a-z])([A-Z])/g, '$1-$2')\n\t\t\t.replace(/[\\s_]+/g, '-')\n\t\t\t.toLowerCase()\n\t}\n}\n","import type { ResolvedField, ResolvedLink, ResolvedScalar, ResolvedTable, ResolvedFieldset } from '@stonecrop/aform'\nimport { resolvedFieldsToColumns } from '@stonecrop/aform'\nimport type { DoctypeField, LinkDeclaration, TableViewConfig, ValueField } from '@stonecrop/schema'\nimport { componentCategory, componentLinkExpansion, resolveLinkRenderMode } from '@stonecrop/schema'\nimport { Router } from 'vue-router'\n\nimport Doctype from './doctype'\nimport { RouteContext } from './types/registry'\n\n/**\n * Stonecrop Registry class\n * @public\n */\nexport default class Registry {\n\t/**\n\t * The root Registry instance\n\t */\n\tstatic _root: Registry\n\n\t/**\n\t * The name of the Registry instance\n\t *\n\t * @defaultValue 'Registry'\n\t */\n\treadonly name: string = 'Registry'\n\n\t/**\n\t * The registry property contains a collection of doctypes\n\t *\n\t * @defaultValue `{}`\n\t * @see {@link Doctype}\n\t */\n\treadonly registry: Record<string, Doctype> = {}\n\n\t/**\n\t * Reverse index: backlink fieldname → list of \\{ doctype slug, link fieldname \\}.\n\t * Multiple doctypes can declare a link with the same backlink name, so each key\n\t * maps to an array. Built at schema load time for O(1) ancestor lookups.\n\t *\n\t * @defaultValue `new Map()`\n\t * @internal\n\t */\n\tprivate _ancestorIndex: Map<string, Array<{ slug: string; fieldname: string }>> = new Map()\n\n\t/**\n\t * Whether the ancestor index needs rebuilding\n\t *\n\t * @defaultValue `true`\n\t * @internal\n\t */\n\tprivate _ancestorIndexDirty: boolean = true\n\n\t/**\n\t * The Vue router instance\n\t * @see {@link https://router.vuejs.org/}\n\t */\n\treadonly router?: Router\n\n\t/**\n\t * Creates a new Registry instance (singleton pattern)\n\t * @param router - Optional Vue router instance for route management\n\t * @param getMeta - Optional function to fetch doctype metadata from an API\n\t */\n\tconstructor(router?: Router, getMeta?: (routeContext: RouteContext) => Doctype | Promise<Doctype>) {\n\t\tif (Registry._root) {\n\t\t\treturn Registry._root\n\t\t}\n\t\tRegistry._root = this\n\t\tthis.router = router\n\t\tthis.getMeta = getMeta\n\t\treturn this\n\t}\n\n\t/**\n\t * The getMeta function fetches doctype metadata from an API based on route context\n\t * @see {@link Doctype}\n\t */\n\tgetMeta?: (routeContext: RouteContext) => Doctype | Promise<Doctype>\n\n\t/**\n\t * Get doctype metadata\n\t * @param doctype - The doctype to fetch metadata for\n\t * @returns The doctype metadata\n\t * @see {@link Doctype}\n\t */\n\taddDoctype(doctype: Doctype) {\n\t\tif (!(doctype.slug in this.registry)) {\n\t\t\tthis.registry[doctype.slug] = doctype\n\t\t\tthis._ancestorIndexDirty = true\n\t\t}\n\n\t\t// Field triggers are registered imperatively, by the app, via the FieldTriggerEngine's own\n\t\t// `registerDoctypeActions`. A doctype used to be able to declare them too, but that path\n\t\t// could not survive the wire — neither the Zod gate nor the SDL carries such a map — so it\n\t\t// only ever worked for a host bypassing both, and it left two public `runAction` methods\n\t\t// meaning opposite things. Registering here would also overwrite an app's imperative\n\t\t// registration, since `registerDoctypeActions` sets the maps even when handed nothing.\n\n\t\tif (doctype.component && this.router && !this.router.hasRoute(doctype.doctype)) {\n\t\t\tthis.router.addRoute({\n\t\t\t\tpath: `/${doctype.slug}`,\n\t\t\t\tname: doctype.slug,\n\t\t\t\tcomponent: doctype.component,\n\t\t\t})\n\t\t}\n\t}\n\n\t/**\n\t * Resolve a Doctype's authoring schema into a rendered schema array suitable for AForm.\n\t *\n\t * Transforms `DoctypeField[]` (authoring space) → `ResolvedField[]` (rendering space):\n\t * - `kind: 'field'` (not Link) → `ResolvedScalar`\n\t * - `kind: 'field'` (Link, no declaration) → `ResolvedScalar` with `component: 'AFormLink'`\n\t * - `kind: 'field'` (Link, `noneOrMany`/`atLeastOne`) → `ResolvedTable`\n\t * - `kind: 'field'` (Link, `one`/`atMostOne`) → `ResolvedLink`\n\t * - `kind: 'fieldset'` → `ResolvedFieldset` (children resolved recursively)\n\t * - `kind: 'table'` → `ResolvedTable` (columns as `ColumnSchema[]`)\n\t *\n\t * Circular references are protected against via the `visited` set.\n\t *\n\t * @param doctype - The doctype to resolve\n\t * @param visited - Internal — set of already-visited doctype slugs for cycle detection\n\t * @returns A resolved schema array ready for AForm\n\t *\n\t * @public\n\t */\n\tresolveSchema(doctype: Doctype, visited?: Set<string>): ResolvedField[] {\n\t\tconst seen = visited ?? new Set<string>()\n\t\tconst slug = doctype.slug\n\n\t\t// Prevent circular resolution — return all ValueField entries as scalars (link not expanded)\n\t\tif (seen.has(slug)) {\n\t\t\tconst fallback: DoctypeField[] = doctype.schema ? doctype.schema.toArray() : []\n\t\t\treturn fallback\n\t\t\t\t.filter((f): f is ValueField => f.kind === 'field')\n\t\t\t\t.map(({ cardinality: _c, ...rest }): ResolvedScalar => rest)\n\t\t}\n\t\tseen.add(slug)\n\n\t\tconst schemaArray: DoctypeField[] = doctype.schema ? doctype.schema.toArray() : []\n\n\t\t// Map link declarations by fieldname (link.fieldname ?? key)\n\t\tconst linksByFieldname = new Map<string, LinkDeclaration>()\n\t\tif (doctype.links) {\n\t\t\tfor (const [key, link] of Object.entries(doctype.links)) {\n\t\t\t\tlinksByFieldname.set(link.fieldname ?? key, link)\n\t\t\t}\n\t\t}\n\n\t\tconst result = this.resolveFields(schemaArray, linksByFieldname, seen)\n\t\tseen.delete(slug)\n\t\treturn result\n\t}\n\n\t/**\n\t * Recursively resolve a `DoctypeField[]` using the provided link context.\n\t * Called by `resolveSchema` and recursively for fieldset children.\n\t * @internal\n\t */\n\tprivate resolveFields(\n\t\tfields: DoctypeField[],\n\t\tlinks: Map<string, LinkDeclaration>,\n\t\tvisited: Set<string>\n\t): ResolvedField[] {\n\t\tconst resolved: ResolvedField[] = []\n\n\t\tfor (const field of fields) {\n\t\t\t// A field is a link when it carries `doctype` (the marker) or has a LinkDeclaration.\n\t\t\tconst linkDecl = field.kind === 'field' ? links.get(field.fieldname) : undefined\n\t\t\tif (field.kind === 'field' && (linkDecl || field.doctype)) {\n\t\t\t\tconst link = linkDecl\n\t\t\t\t// The declaration's target wins over the field's own `doctype`.\n\t\t\t\tconst linkTarget = link?.target ?? field.doctype\n\n\t\t\t\t// An undeclared link, or a declared one whose component renders an inline picker,\n\t\t\t\t// stays a scalar: the target is not expanded, it only needs the slug for async\n\t\t\t\t// display-text resolution and navigation.\n\t\t\t\tif (!link || resolveLinkRenderMode(link, field.component) === 'inline') {\n\t\t\t\t\tconst { cardinality: _c, ...rest } = field\n\t\t\t\t\tresolved.push({\n\t\t\t\t\t\t...rest,\n\t\t\t\t\t\tcomponent: rest.component || 'AFormLink',\n\t\t\t\t\t\t...(linkTarget !== undefined ? { doctype: linkTarget } : {}),\n\t\t\t\t\t})\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tconst targetDoctype = this.registry[link.target]\n\t\t\t\tif (!targetDoctype) {\n\t\t\t\t\t// Target not registered — copy as scalar\n\t\t\t\t\tconst { cardinality: _c, ...rest } = field\n\t\t\t\t\tresolved.push({ ...rest })\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tconst childSchema = this.resolveSchema(targetDoctype, new Set(visited))\n\t\t\t\tconst { options: _opt, cardinality: _card, kind: _kind, ...fieldRest } = field\n\n\t\t\t\tif (resolveLinkRenderMode(link, field.component) === 'table') {\n\t\t\t\t\tresolved.push(this.buildTableConfig(field, childSchema, link.component))\n\t\t\t\t} else {\n\t\t\t\t\tconst linkEntry: ResolvedLink = {\n\t\t\t\t\t\t...fieldRest,\n\t\t\t\t\t\tkind: 'link',\n\t\t\t\t\t\tlabel: fieldRest.label || field.fieldname,\n\t\t\t\t\t\tcomponent: link.component || fieldRest.component || 'AForm',\n\t\t\t\t\t\tschema: childSchema,\n\t\t\t\t\t}\n\t\t\t\t\tresolved.push(linkEntry)\n\t\t\t\t}\n\t\t\t} else if (field.kind === 'fieldset') {\n\t\t\t\tconst resolvedChildren = this.resolveFields(field.schema, links, visited)\n\t\t\t\tconst { schema: _s, ...fieldRest } = field\n\t\t\t\tconst fieldsetEntry: ResolvedFieldset = {\n\t\t\t\t\t...fieldRest,\n\t\t\t\t\tschema: resolvedChildren,\n\t\t\t\t}\n\t\t\t\tresolved.push(fieldsetEntry)\n\t\t\t} else if (field.kind === 'table') {\n\t\t\t\t// Inline table — columns become ColumnSchema[], add default config\n\t\t\t\tconst { columns, config, ...fieldRest } = field\n\t\t\t\tconst tableEntry: ResolvedTable = {\n\t\t\t\t\t...fieldRest,\n\t\t\t\t\tkind: 'table',\n\t\t\t\t\tcomponent: fieldRest.component || 'ATable',\n\t\t\t\t\tschema: columns,\n\t\t\t\t\tconfig: config ?? { view: 'list' },\n\t\t\t\t}\n\t\t\t\tresolved.push(tableEntry)\n\t\t\t} else {\n\t\t\t\t// Scalar field (kind: 'field', not a link) — strip cardinality.\n\t\t\t\t// A link-rendering component with nothing to point at renders an empty picker (or an\n\t\t\t\t// empty embedded form), which is indistinguishable from \"the record has no value\".\n\t\t\t\t// Link-ness comes from `doctype`/`links`, so this is a field that named a link\n\t\t\t\t// component and forgot the target.\n\t\t\t\tif (field.kind === 'field' && componentLinkExpansion(field.component)) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Stonecrop] Field \"${field.fieldname}\" renders with \"${field.component}\", which is a link component, ` +\n\t\t\t\t\t\t\t`but the field is not a link: it has no \\`doctype\\` and no \\`links\\` declaration. It will render ` +\n\t\t\t\t\t\t\t`as a plain field. Add \\`\"doctype\": \"<doctype-slug>\"\\` to the field definition.`\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tconst { cardinality: _c, ...rest } = field\n\t\t\t\tresolved.push({ ...rest })\n\t\t\t}\n\t\t}\n\n\t\treturn resolved\n\t}\n\n\t/**\n\t * Build a `ResolvedTable` from a resolved Link field with many cardinality.\n\t * Columns come from {@link @stonecrop/aform#resolvedFieldsToColumns}, the shared definition of\n\t * which resolved fields a cell can render.\n\t * @internal\n\t */\n\tprivate buildTableConfig(field: ValueField, childSchema: ResolvedField[], component?: string): ResolvedTable {\n\t\tconst columns = resolvedFieldsToColumns(childSchema)\n\n\t\tconst config: TableViewConfig = (field as ValueField & { config?: TableViewConfig }).config ?? { view: 'list' }\n\t\tconst { options: _opt, cardinality: _card, ...fieldRest } = field\n\n\t\treturn {\n\t\t\t...fieldRest,\n\t\t\tkind: 'table',\n\t\t\tlabel: fieldRest.label || field.fieldname,\n\t\t\tcomponent: component || fieldRest.component || 'ATable',\n\t\t\tschema: columns,\n\t\t\tconfig,\n\t\t}\n\t}\n\n\t/**\n\t * Initialize a new record with default values based on a resolved schema.\n\t * Narrows by `kind` discriminator for precise branch selection.\n\t *\n\t * - `kind: 'table'` or `kind: 'link'` → `[]` or `{}`\n\t * - `kind: 'fieldset'` → recursively initializes children as `{}`\n\t * - `kind: 'field'` → derives the default from the component's category; falls back to `null`\n\t *\n\t * @param schema - The resolved schema array to derive defaults from\n\t * @returns A plain object with default values for each field\n\t * @public\n\t */\n\tinitializeRecord(schema: ResolvedField[]): Record<string, any> {\n\t\tconst record: Record<string, any> = {}\n\n\t\tfor (const field of schema) {\n\t\t\tif (field.kind === 'table') {\n\t\t\t\trecord[field.fieldname] = []\n\t\t\t} else if (field.kind === 'link') {\n\t\t\t\trecord[field.fieldname] = this.initializeRecord(field.schema)\n\t\t\t} else if (field.kind === 'fieldset') {\n\t\t\t\trecord[field.fieldname] = this.initializeRecord(field.schema)\n\t\t\t} else {\n\t\t\t\t// kind: 'field' — the empty default comes from the component's category.\n\t\t\t\tconst fieldDefault = field.default\n\t\t\t\tif (fieldDefault !== undefined) {\n\t\t\t\t\trecord[field.fieldname] = fieldDefault\n\t\t\t\t} else {\n\t\t\t\t\tconst category = componentCategory(field.component)\n\t\t\t\t\tif (category === 'text') {\n\t\t\t\t\t\trecord[field.fieldname] = ''\n\t\t\t\t\t} else if (category === 'number') {\n\t\t\t\t\t\trecord[field.fieldname] = 0\n\t\t\t\t\t} else if (category === 'boolean') {\n\t\t\t\t\t\trecord[field.fieldname] = false\n\t\t\t\t\t} else if (category === 'code' && field.language) {\n\t\t\t\t\t\t// A JSON editor starts from an empty object; any other language from empty source.\n\t\t\t\t\t\trecord[field.fieldname] = field.language === 'json' ? {} : ''\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// date / datetime / select / link / attach — plus two cases with no better answer\n\t\t\t\t\t\t// than \"no value\": an unknown (custom) component, and a code field whose missing\n\t\t\t\t\t\t// `language` doesn't say which kind of empty it wants.\n\t\t\t\t\t\trecord[field.fieldname] = null\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn record\n\t}\n\n\t/**\n\t * Get a registered doctype by slug\n\t * @param slug - The doctype slug to look up\n\t * @returns The Doctype instance if found, or undefined\n\t * @public\n\t */\n\tgetDoctype(slug: string): Doctype | undefined {\n\t\treturn this.registry[slug]\n\t}\n\n\t/**\n\t * Get all links declared on a doctype.\n\t *\n\t * @param doctypeSlug - The doctype slug to get links for\n\t * @returns Array of link declarations with fieldname, or empty array if none\n\t *\n\t * @example\n\t * ```ts\n\t * const links = registry.getDescendantLinks('recipe')\n\t * // [{ fieldname: 'tasks', target: 'recipe-task', cardinality: 'noneOrMany', backlink: 'recipe' }]\n\t * ```\n\t *\n\t * @public\n\t */\n\tgetDescendantLinks(doctypeSlug: string): Array<LinkDeclaration & { fieldname: string }> {\n\t\tconst doctype = this.registry[doctypeSlug]\n\t\tif (!doctype?.links) return []\n\n\t\treturn Object.entries(doctype.links).map(([fieldname, link]) =>\n\t\t\tObject.assign({}, link, {\n\t\t\t\tfieldname,\n\t\t\t})\n\t\t)\n\t}\n\n\t/**\n\t * Get links on other doctypes that target the given doctype.\n\t *\n\t * @param doctypeSlug - The doctype slug to find ancestor links for\n\t * @returns Array of link declarations with fieldname and declaring doctype slug, or empty array\n\t *\n\t * @example\n\t * ```ts\n\t * const ancestors = registry.getAncestorLinks('recipe-task')\n\t * // [{ fieldname: 'tasks', target: 'recipe-task', cardinality: 'noneOrMany', backlink: 'recipe', doctype: 'recipe' }]\n\t * ```\n\t *\n\t * @public\n\t */\n\tgetAncestorLinks(doctypeSlug: string): Array<LinkDeclaration & { fieldname: string; doctype: string }> {\n\t\tthis._ensureAncestorIndex()\n\n\t\tconst results: Array<LinkDeclaration & { fieldname: string; doctype: string }> = []\n\n\t\tfor (const [_backlink, entries] of this._ancestorIndex) {\n\t\t\tfor (const { slug: declaringSlug, fieldname } of entries) {\n\t\t\t\tconst declaringDoctype = this.registry[declaringSlug]\n\t\t\t\tif (!declaringDoctype?.links) continue\n\n\t\t\t\tconst link = declaringDoctype.links[fieldname]\n\t\t\t\tif (link?.target === doctypeSlug) {\n\t\t\t\t\tresults.push({\n\t\t\t\t\t\t...link,\n\t\t\t\t\t\tfieldname,\n\t\t\t\t\t\tdoctype: declaringSlug,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn results\n\t}\n\n\t/**\n\t * Ensure the ancestor index is up to date\n\t * @internal\n\t */\n\tprivate _ensureAncestorIndex(): void {\n\t\tif (!this._ancestorIndexDirty) return\n\t\tthis._ancestorIndexDirty = false\n\t\tthis._ancestorIndex.clear()\n\n\t\tfor (const [slug, doctype] of Object.entries(this.registry)) {\n\t\t\tif (!doctype.links) continue\n\t\t\tfor (const [fieldname, link] of Object.entries(doctype.links)) {\n\t\t\t\tif (link.backlink) {\n\t\t\t\t\tconst existing = this._ancestorIndex.get(link.backlink)\n\t\t\t\t\tif (existing) {\n\t\t\t\t\t\texisting.push({ slug, fieldname })\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis._ancestorIndex.set(link.backlink, [{ slug, fieldname }])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO: should we allow clearing the registry at all?\n\t// clear() {\n\t// \tthis.registry = {}\n\t// \tif (this.router) {\n\t// \t\tconst routes = this.router.getRoutes()\n\t// \t\tfor (const route of routes) {\n\t// \t\t\tif (route.name) {\n\t// \t\t\t\tthis.router.removeRoute(route.name)\n\t// \t\t\t}\n\t// \t\t}\n\t// \t}\n\t// }\n}\n","import { App, type Plugin, nextTick } from 'vue'\nimport type { Pinia } from 'pinia'\n\nimport Registry from '../registry'\nimport { Stonecrop } from '../stonecrop'\nimport type { InstallOptions } from '../types'\nimport { useOperationLogStore } from '../stores/operation-log'\n\n/**\n * Setup auto-initialization for user-defined initialization logic\n * This function handles the post-mount initialization automatically\n */\nasync function setupAutoInitialization(\n\tregistry: Registry,\n\tstonecrop: Stonecrop,\n\tonRouterInitialized: (registry: Registry, stonecrop: Stonecrop) => void | Promise<void>\n) {\n\t// Wait for the next tick to ensure the app is mounted\n\tawait nextTick()\n\n\ttry {\n\t\tawait onRouterInitialized(registry, stonecrop)\n\t} catch {\n\t\t// Silent error handling - application should handle initialization errors\n\t}\n}\n\n/**\n * Stonecrop Vue plugin\n * @param app - The Vue app instance\n * @param options - The plugin options\n * @example\n * ```ts\n * import { createApp } from 'vue'\n * import Stonecrop from '@stonecrop/stonecrop'\n * import { StonecropClient } from '@stonecrop/graphql-client'\n * import router from './router'\n *\n * const client = new StonecropClient({ endpoint: '/graphql' })\n *\n * const app = createApp(App)\n * app.use(Stonecrop, {\n * router,\n * client,\n * getMeta: async (routeContext) => {\n * // routeContext contains: { path, segments }\n * // use the client to fetch doctype meta\n * return client.getMeta({ doctype: routeContext.segments[0] })\n * },\n * autoInitializeRouter: true,\n * onRouterInitialized: async (registry, stonecrop) => {\n * // your custom initialization logic here\n * }\n * })\n * app.mount('#app')\n * ```\n * @public\n */\nconst plugin: Plugin = {\n\tinstall: (app: App, options?: InstallOptions) => {\n\t\t// Check for existing router installation\n\t\tconst existingRouter = app.config.globalProperties.$router\n\t\tconst providedRouter = options?.router\n\t\tconst router = existingRouter || providedRouter\n\t\tif (!existingRouter && providedRouter) {\n\t\t\tapp.use(providedRouter)\n\t\t}\n\n\t\t// Create registry with available router\n\t\tconst registry = new Registry(router, options?.getMeta)\n\t\tapp.provide('$registry', registry)\n\t\tapp.config.globalProperties.$registry = registry\n\n\t\t// Create and provide a global Stonecrop instance\n\t\tconst stonecrop = new Stonecrop(registry)\n\t\tif (options?.client) {\n\t\t\tstonecrop.setClient(options.client)\n\t\t}\n\t\tapp.provide('$stonecrop', stonecrop)\n\t\tapp.config.globalProperties.$stonecrop = stonecrop\n\n\t\t// Initialize operation log store if Pinia is available\n\t\t// This ensures the store is created with the app's Pinia instance\n\t\ttry {\n\t\t\tconst pinia = app.config.globalProperties.$pinia as Pinia | undefined\n\t\t\tif (pinia) {\n\t\t\t\t// Initialize the operation log store with the app's Pinia instance\n\t\t\t\tconst operationLogStore = useOperationLogStore(pinia)\n\n\t\t\t\t// Provide the store so components can access it\n\t\t\t\tapp.provide('$operationLogStore', operationLogStore)\n\t\t\t\tapp.config.globalProperties.$operationLogStore = operationLogStore\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Pinia not available - operation log won't work, but app should still function\n\t\t\tconsole.warn('Pinia not available - operation log features will be disabled:', error)\n\t\t}\n\n\t\t// Register custom components\n\t\tif (options?.components) {\n\t\t\tfor (const [tag, component] of Object.entries(options.components)) {\n\t\t\t\tapp.component(tag, component)\n\t\t\t}\n\t\t}\n\n\t\t// Setup auto-initialization if requested\n\t\tif (options?.autoInitializeRouter && options.onRouterInitialized) {\n\t\t\tvoid setupAutoInitialization(registry, stonecrop, options.onRouterInitialized)\n\t\t}\n\t},\n}\n\nexport default plugin\n","import { defineStore } from 'pinia'\nimport { ref, computed } from 'vue'\n\nimport type { TriggerDefinition } from '@stonecrop/schema'\nimport { executeClientHandler } from '../client-handler'\n\n/**\n * A single validation error contributed by a trigger, displayed on a field.\n * @public\n */\nexport interface ValidationError {\n\t/** The trigger that produced this error — the namespace a re-run clears before repopulating */\n\ttrigger: string\n\t/** The fieldname the error displays on (the `setError` target, not necessarily a fired field) */\n\tfield: string\n\t/** The message to display */\n\tmessage: string\n}\n\n/**\n * Reactive per-field validation error store + the advisory field-validation trigger engine.\n *\n * Holds the errors produced by field-validation triggers (see `TriggerDefinition` in\n * `@stonecrop/schema`) and runs a trigger's `clientHandler` on demand. Errors are **namespaced\n * by trigger**: re-running a trigger clears its own prior contributions before repopulating, so a\n * corrected value clears its stale error without disturbing other triggers.\n *\n * The engine is **advisory** and does **no rollback** — an invalid value stays in the record so the\n * user can fix it; validity is reported separately via `isValid` (read by the save gate) and\n * the per-field messages are surfaced via `errorsByField` / `errorsFor` for display.\n *\n * @public\n */\nexport const useValidationStore = defineStore('stonecrop-validation', () => {\n\tconst errors = ref<ValidationError[]>([])\n\n\t/** True when no field currently carries a validation error. */\n\tconst isValid = computed(() => errors.value.length === 0)\n\n\t/** Errors grouped by field — the shape a renderer consumes (e.g. AForm `:errors`). */\n\tconst errorsByField = computed<Record<string, string[]>>(() => {\n\t\tconst map: Record<string, string[]> = {}\n\t\tfor (const e of errors.value) {\n\t\t\tif (!map[e.field]) map[e.field] = []\n\t\t\tmap[e.field].push(e.message)\n\t\t}\n\t\treturn map\n\t})\n\n\t/** Messages currently displayed on `field`. */\n\tfunction errorsFor(field: string): string[] {\n\t\treturn errors.value.filter(e => e.field === field).map(e => e.message)\n\t}\n\n\t/** Record an error contributed by `trigger`, displayed on `field`. */\n\tfunction setError(trigger: string, field: string, message: string) {\n\t\terrors.value.push({ trigger, field, message })\n\t}\n\n\t/** Remove every error contributed by `trigger` (its namespace). */\n\tfunction clearTrigger(trigger: string) {\n\t\terrors.value = errors.value.filter(e => e.trigger !== trigger)\n\t}\n\n\t/** Remove every validation error. */\n\tfunction clearAll() {\n\t\terrors.value = []\n\t}\n\n\t/**\n\t * Run a single trigger against a read-only snapshot of `record`. Clears the trigger's prior\n\t * errors, then executes its `clientHandler` with `{ record, value, setError }`. Fails **open** —\n\t * a throwing validator warns and records nothing, so a broken validator never blocks the user.\n\t */\n\tasync function runTrigger(name: string, def: TriggerDefinition, record: Record<string, unknown>, value: unknown) {\n\t\tclearTrigger(name)\n\t\t// Shallow-frozen copy: the validator reads siblings but can neither mutate the record nor\n\t\t// reassign fields (advisory reads only) — and mutation can't leak back to the caller.\n\t\tconst frozen = Object.freeze({ ...record })\n\t\tconst boundSetError = (field: string, message: string) => setError(name, field, message)\n\t\ttry {\n\t\t\tawait executeClientHandler(def.clientHandler, { record: frozen, value, setError: boundSetError })\n\t\t} catch (error) {\n\t\t\t// Advisory by design: a broken validator must never block save (a bug in one trigger must\n\t\t\t// not trap the user, especially in production). It fails OPEN — but a throw is an error in\n\t\t\t// the author's code, so surface it loudly (error severity, trigger named) rather than\n\t\t\t// silently: a broken validator that just \"does nothing\" is the real footgun here.\n\t\t\tif (typeof console !== 'undefined') {\n\t\t\t\tconsole.error(\n\t\t\t\t\t`Validation trigger \"${name}\" threw and was ignored (advisory — save is not blocked). ` +\n\t\t\t\t\t\t`Fix its clientHandler:`,\n\t\t\t\t\terror\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Run every trigger whose `on` set includes `changedField`, passing that field's current value.\n\t * Call on the edit path (desktop-driven) so editing either bound field re-validates the pair.\n\t */\n\tasync function validateField(\n\t\ttriggers: Record<string, TriggerDefinition>,\n\t\tchangedField: string,\n\t\trecord: Record<string, unknown>\n\t): Promise<void> {\n\t\tconst runs: Promise<void>[] = []\n\t\tfor (const [name, def] of Object.entries(triggers)) {\n\t\t\tif (def.on.includes(changedField)) {\n\t\t\t\truns.push(runTrigger(name, def, record, record[changedField]))\n\t\t\t}\n\t\t}\n\t\tawait Promise.all(runs)\n\t}\n\n\t/**\n\t * Run **all** triggers (no fired-field filter) — the authoritative client gate at save-attempt,\n\t * covering triggers whose fields were never edited. `value` is undefined (no single changed field).\n\t */\n\tasync function validateRecord(\n\t\ttriggers: Record<string, TriggerDefinition>,\n\t\trecord: Record<string, unknown>\n\t): Promise<void> {\n\t\tawait Promise.all(Object.entries(triggers).map(([name, def]) => runTrigger(name, def, record, undefined)))\n\t}\n\n\treturn {\n\t\terrors,\n\t\tisValid,\n\t\terrorsByField,\n\t\terrorsFor,\n\t\tsetError,\n\t\tclearTrigger,\n\t\tclearAll,\n\t\tvalidateField,\n\t\tvalidateRecord,\n\t}\n})\n","import type Registry from '../registry'\n\n/**\n * Validation severity levels\n * @public\n */\nexport enum ValidationSeverity {\n\t/** Blocking error that prevents save */\n\tERROR = 'error',\n\t/** Advisory warning that allows save */\n\tWARNING = 'warning',\n\t/** Informational message */\n\tINFO = 'info',\n}\n\n/**\n * Validation issue\n * @public\n */\nexport interface ValidationIssue {\n\t/** Severity level */\n\tseverity: ValidationSeverity\n\t/** Validation rule that failed */\n\trule: string\n\t/** Human-readable message */\n\tmessage: string\n\t/** Doctype name */\n\tdoctype?: string\n\t/** Field name if applicable */\n\tfieldname?: string\n\t/** Additional context */\n\tcontext?: Record<string, unknown>\n}\n\n/**\n * Validation result\n * @public\n */\nexport interface ValidationResult {\n\t/** Whether validation passed (no blocking errors) */\n\tvalid: boolean\n\t/** List of validation issues */\n\tissues: ValidationIssue[]\n\t/** Count of errors */\n\terrorCount: number\n\t/** Count of warnings */\n\twarningCount: number\n\t/** Count of info messages */\n\tinfoCount: number\n}\n\n/**\n * Schema validator options\n * @public\n */\nexport interface ValidatorOptions {\n\t/** Registry instance for doctype lookups */\n\tregistry?: Registry\n\t/** Whether to validate Link field targets */\n\tvalidateLinkTargets?: boolean\n\t/** Whether to validate links object (target resolution, backlink consistency, Link field correspondence) */\n\tvalidateLinks?: boolean\n\t/** Whether to validate workflow reachability */\n\tvalidateWorkflows?: boolean\n\t/** Whether to validate action registration */\n\tvalidateActions?: boolean\n\t/** Whether to validate required schema properties */\n\tvalidateRequiredProperties?: boolean\n}\n","/**\n * Schema Validation Utilities\n * Validates Stonecrop schemas for integrity and consistency\n * @packageDocumentation\n */\n\nimport type { DoctypeField } from '@stonecrop/schema'\nimport type { LinkDeclaration } from '@stonecrop/schema'\nimport { componentLinkExpansion } from '@stonecrop/schema'\nimport type { List, Map as ImmutableMap } from 'immutable'\nimport type { AnyStateNodeConfig } from 'xstate'\n\nimport { getGlobalTriggerEngine } from './field-triggers'\nimport type Registry from './registry'\nimport { ValidationSeverity } from './types/schema-validator'\nimport type { ValidationIssue, ValidationResult, ValidatorOptions } from './types/schema-validator'\n\n/**\n * Schema validator class\n * @public\n */\nexport class SchemaValidator {\n\tprivate options: Required<ValidatorOptions>\n\n\t/**\n\t * Creates a new SchemaValidator instance\n\t * @param options - Validator configuration options\n\t */\n\tconstructor(options: ValidatorOptions = {}) {\n\t\tthis.options = {\n\t\t\tregistry: options.registry || null!,\n\t\t\tvalidateLinkTargets: options.validateLinkTargets ?? true,\n\t\t\tvalidateLinks: options.validateLinks ?? true,\n\t\t\tvalidateActions: options.validateActions ?? true,\n\t\t\tvalidateWorkflows: options.validateWorkflows ?? true,\n\t\t\tvalidateRequiredProperties: options.validateRequiredProperties ?? true,\n\t\t}\n\t}\n\n\t/**\n\t * Validates a complete doctype schema\n\t * @param doctype - Doctype name\n\t * @param schema - Schema fields (List or Array)\n\t * @param workflow - Optional workflow configuration\n\t * @param actions - Optional actions map\n\t * @param links - Optional links object\n\t * @returns Validation result\n\t */\n\tvalidate(\n\t\tdoctype: string,\n\t\tschema: List<DoctypeField> | DoctypeField[] | undefined,\n\t\tworkflow?: AnyStateNodeConfig,\n\t\tactions?: ImmutableMap<string, string[]> | Map<string, string[]>,\n\t\tlinks?: Record<string, LinkDeclaration>\n\t): ValidationResult {\n\t\tconst issues: ValidationIssue[] = []\n\n\t\t// Convert schema to array for easier iteration\n\t\tconst schemaArray = schema ? (Array.isArray(schema) ? schema : schema.toArray()) : []\n\n\t\t// Validate required properties\n\t\tif (this.options.validateRequiredProperties) {\n\t\t\tissues.push(...this.validateRequiredProperties(doctype, schemaArray, links))\n\t\t}\n\n\t\t// Validate Link field targets\n\t\tif (this.options.validateLinkTargets && this.options.registry) {\n\t\t\tissues.push(...this.validateLinkFields(doctype, schemaArray, this.options.registry))\n\t\t}\n\n\t\t// Validate links object\n\t\tif (this.options.validateLinks && this.options.registry && links) {\n\t\t\tissues.push(...this.validateLinkDeclarations(doctype, links, schemaArray, this.options.registry))\n\t\t}\n\n\t\t// Validate workflow configuration\n\t\tif (this.options.validateWorkflows && workflow) {\n\t\t\tissues.push(...this.validateWorkflow(doctype, workflow))\n\t\t}\n\n\t\t// Validate action registration\n\t\tif (this.options.validateActions && actions) {\n\t\t\tconst actionsMap = actions instanceof Map ? actions : actions.toObject()\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- toObject() returns plain object; runtime-safe cast for Map<string, string[]>\n\t\t\tissues.push(...this.validateActionRegistration(doctype, actionsMap as Record<string, string[]>))\n\t\t}\n\n\t\t// Calculate counts\n\t\tconst errorCount = issues.filter(i => i.severity === ValidationSeverity.ERROR).length\n\t\tconst warningCount = issues.filter(i => i.severity === ValidationSeverity.WARNING).length\n\t\tconst infoCount = issues.filter(i => i.severity === ValidationSeverity.INFO).length\n\n\t\treturn {\n\t\t\tvalid: errorCount === 0,\n\t\t\tissues,\n\t\t\terrorCount,\n\t\t\twarningCount,\n\t\t\tinfoCount,\n\t\t}\n\t}\n\n\t/**\n\t * Validates that required schema properties are present\n\t * @internal\n\t */\n\tprivate validateRequiredProperties(\n\t\tdoctype: string,\n\t\tschema: DoctypeField[],\n\t\tlinks?: Record<string, LinkDeclaration>\n\t): ValidationIssue[] {\n\t\tconst issues: ValidationIssue[] = []\n\n\t\tfor (const field of schema) {\n\t\t\t// Check for fieldname\n\t\t\tif (!field.fieldname) {\n\t\t\t\tissues.push({\n\t\t\t\t\tseverity: ValidationSeverity.ERROR,\n\t\t\t\t\trule: 'required-fieldname',\n\t\t\t\t\tmessage: 'Field is missing required property: fieldname',\n\t\t\t\t\tdoctype,\n\t\t\t\t\tcontext: { field },\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// A value field renders through its component and has no other rendering axis;\n\t\t\t// fieldset/table have their own structural requirements.\n\t\t\tif (field.kind === 'field' && !field.component) {\n\t\t\t\tissues.push({\n\t\t\t\t\tseverity: ValidationSeverity.ERROR,\n\t\t\t\t\trule: 'required-component',\n\t\t\t\t\tmessage: `Field \"${field.fieldname}\" must have a component property`,\n\t\t\t\t\tdoctype,\n\t\t\t\t\tfieldname: field.fieldname,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// A link component with nothing to point at renders an empty picker, which looks exactly\n\t\t\t// like a record that has no value — so this fails silently at runtime rather than loudly.\n\t\t\t// Link-ness comes from `doctype` or a `links` declaration, so this is a field that named\n\t\t\t// a link component and gave it neither.\n\t\t\tif (\n\t\t\t\tfield.kind === 'field' &&\n\t\t\t\tcomponentLinkExpansion(field.component) &&\n\t\t\t\t!field.doctype &&\n\t\t\t\t!links?.[field.fieldname]\n\t\t\t) {\n\t\t\t\tissues.push({\n\t\t\t\t\tseverity: ValidationSeverity.ERROR,\n\t\t\t\t\trule: 'link-component-without-doctype',\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t`Field \"${field.fieldname}\" renders with \"${field.component}\", which is a link component, ` +\n\t\t\t\t\t\t`but has no \\`doctype\\` to name its target`,\n\t\t\t\t\tdoctype,\n\t\t\t\t\tfieldname: field.fieldname,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// Validate nested schemas recursively (fieldset only; table columns are ColumnSchema not DoctypeField)\n\t\t\tif (field.kind === 'fieldset') {\n\t\t\t\tissues.push(...this.validateRequiredProperties(doctype, field.schema, links))\n\t\t\t}\n\t\t}\n\n\t\treturn issues\n\t}\n\n\t/**\n\t * Validates Link field targets exist in registry\n\t * @internal\n\t */\n\tprivate validateLinkFields(doctype: string, schema: DoctypeField[], registry: Registry): ValidationIssue[] {\n\t\tconst issues: ValidationIssue[] = []\n\n\t\tfor (const field of schema) {\n\t\t\t// `doctype` is both the link marker and its target, and the schema types it as a\n\t\t\t// non-empty string — so there is no \"missing target\" or \"malformed target\" state left\n\t\t\t// to check here. The rules that did (`link-missing-options`, `link-invalid-options`)\n\t\t\t// were removed with the `options`-as-link-target convention; the case they actually\n\t\t\t// guarded — a link component with no target — is now `link-component-without-doctype`,\n\t\t\t// which fires in validateRequiredProperties whether or not a registry is configured.\n\t\t\tif (field.kind === 'field' && field.doctype) {\n\t\t\t\tconst targetDoctype = field.doctype\n\t\t\t\tconst targetMeta = registry.registry[targetDoctype] || registry.registry[targetDoctype.toLowerCase()]\n\n\t\t\t\tif (!targetMeta) {\n\t\t\t\t\tissues.push({\n\t\t\t\t\t\tseverity: ValidationSeverity.ERROR,\n\t\t\t\t\t\trule: 'link-invalid-target',\n\t\t\t\t\t\tmessage: `Link field \"${field.fieldname}\" references non-existent doctype: \"${targetDoctype}\"`,\n\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\tfieldname: field.fieldname,\n\t\t\t\t\t\tcontext: { targetDoctype },\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Recursively check nested fieldset schemas\n\t\t\tif (field.kind === 'fieldset') {\n\t\t\t\tissues.push(...this.validateLinkFields(doctype, field.schema, registry))\n\t\t\t}\n\t\t}\n\n\t\treturn issues\n\t}\n\n\t/**\n\t * Validates link declarations: target resolution, backlink consistency, Link field correspondence\n\t * @internal\n\t */\n\tprivate validateLinkDeclarations(\n\t\tdoctype: string,\n\t\tlinks: Record<string, LinkDeclaration>,\n\t\tschema: DoctypeField[],\n\t\tregistry: Registry\n\t): ValidationIssue[] {\n\t\tconst issues: ValidationIssue[] = []\n\n\t\t// Build a map of link fields by fieldname for quick lookup\n\t\tconst linkFieldsByFieldname = new Map<string, DoctypeField>()\n\t\tfor (const field of schema) {\n\t\t\tif (field.kind === 'field' && field.doctype) {\n\t\t\t\tlinkFieldsByFieldname.set(field.fieldname, field)\n\t\t\t}\n\t\t}\n\n\t\tfor (const [fieldname, link] of Object.entries(links)) {\n\t\t\t// Check target resolves in registry\n\t\t\tconst targetDoctype = registry.registry[link.target]\n\t\t\tif (!targetDoctype) {\n\t\t\t\tissues.push({\n\t\t\t\t\tseverity: ValidationSeverity.ERROR,\n\t\t\t\t\trule: 'link-invalid-target',\n\t\t\t\t\tmessage: `Link \"${fieldname}\" references non-existent doctype: \"${link.target}\"`,\n\t\t\t\t\tdoctype,\n\t\t\t\t\tfieldname,\n\t\t\t\t\tcontext: { target: link.target },\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Warn on self-referential target\n\t\t\tif (link.target === doctype) {\n\t\t\t\tissues.push({\n\t\t\t\t\tseverity: ValidationSeverity.WARNING,\n\t\t\t\t\trule: 'link-self-referential',\n\t\t\t\t\tmessage: `Link \"${fieldname}\" is self-referential (target: \"${link.target}\")`,\n\t\t\t\t\tdoctype,\n\t\t\t\t\tfieldname,\n\t\t\t\t\tcontext: { target: link.target },\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// Check backlink consistency\n\t\t\tif (link.backlink && targetDoctype.links) {\n\t\t\t\tconst reciprocalLink = targetDoctype.links[link.backlink]\n\t\t\t\tif (!reciprocalLink) {\n\t\t\t\t\tissues.push({\n\t\t\t\t\t\tseverity: ValidationSeverity.ERROR,\n\t\t\t\t\t\trule: 'link-backlink-missing',\n\t\t\t\t\t\tmessage: `Backlink \"${link.backlink}\" not found on target doctype \"${link.target}\"`,\n\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\tfieldname,\n\t\t\t\t\t\tcontext: { backlink: link.backlink, target: link.target },\n\t\t\t\t\t})\n\t\t\t\t} else if (reciprocalLink.target !== doctype) {\n\t\t\t\t\tissues.push({\n\t\t\t\t\t\tseverity: ValidationSeverity.WARNING,\n\t\t\t\t\t\trule: 'link-backlink-mismatch',\n\t\t\t\t\t\tmessage: `Backlink \"${link.backlink}\" on \"${link.target}\" points to \"${reciprocalLink.target}\" instead of \"${doctype}\"`,\n\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\tfieldname,\n\t\t\t\t\t\tcontext: { backlink: link.backlink, target: link.target, actualTarget: reciprocalLink.target },\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If Link field exists with same fieldname, verify it has matching target\n\t\t\t// Only check if link has fieldname set (otherwise it's a standalone link without a field)\n\t\t\tif (link.fieldname) {\n\t\t\t\tconst linkField = linkFieldsByFieldname.get(link.fieldname)\n\t\t\t\tif (linkField && linkField.kind === 'field') {\n\t\t\t\t\t// Map membership implies `doctype` is set — that is the map's build condition.\n\t\t\t\t\tconst linkFieldTarget = linkField.doctype\n\t\t\t\t\tif (linkFieldTarget && linkFieldTarget !== link.target) {\n\t\t\t\t\t\tissues.push({\n\t\t\t\t\t\t\tseverity: ValidationSeverity.ERROR,\n\t\t\t\t\t\t\trule: 'link-field-target-mismatch',\n\t\t\t\t\t\t\tmessage: `Link field \"${link.fieldname}\" targets \"${linkFieldTarget}\" but link declaration targets \"${link.target}\"`,\n\t\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\t\tfieldname: link.fieldname,\n\t\t\t\t\t\t\tcontext: { linkFieldTarget, linkTarget: link.target },\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// NOTE: there is deliberately no \"every link field needs a declaration\" rule. A plain foreign\n\t\t// key is a link with no `links` entry — the map is additive, carrying expansion metadata\n\t\t// (backlink/fetch/cardinality), and is not required. Such a rule would contradict\n\t\t// `Registry.resolveFields`, which resolves undeclared links to inline pickers, and would flag\n\t\t// every doctype that mixes an expanded relation with a plain FK (e.g. `country`: a `links`\n\t\t// map for states/languages/subdivisions plus a plain `continent` picker).\n\n\t\treturn issues\n\t}\n\n\t/**\n\t * Validates workflow state machine configuration\n\t * @internal\n\t */\n\tprivate validateWorkflow(doctype: string, workflow: AnyStateNodeConfig): ValidationIssue[] {\n\t\tconst issues: ValidationIssue[] = []\n\n\t\t// Check for initial state\n\t\tif (!workflow.initial && !workflow.type) {\n\t\t\tissues.push({\n\t\t\t\tseverity: ValidationSeverity.WARNING,\n\t\t\t\trule: 'workflow-missing-initial',\n\t\t\t\tmessage: 'Workflow is missing initial state property',\n\t\t\t\tdoctype,\n\t\t\t})\n\t\t}\n\n\t\t// Check for states\n\t\tif (!workflow.states || Object.keys(workflow.states).length === 0) {\n\t\t\tissues.push({\n\t\t\t\tseverity: ValidationSeverity.WARNING,\n\t\t\t\trule: 'workflow-no-states',\n\t\t\t\tmessage: 'Workflow has no states defined',\n\t\t\t\tdoctype,\n\t\t\t})\n\t\t\treturn issues\n\t\t}\n\n\t\t// Validate initial state exists\n\t\tif (workflow.initial && typeof workflow.initial === 'string' && !workflow.states[workflow.initial]) {\n\t\t\tissues.push({\n\t\t\t\tseverity: ValidationSeverity.ERROR,\n\t\t\t\trule: 'workflow-invalid-initial',\n\t\t\t\tmessage: `Workflow initial state \"${workflow.initial}\" does not exist in states`,\n\t\t\t\tdoctype,\n\t\t\t\tcontext: { initialState: workflow.initial },\n\t\t\t})\n\t\t}\n\n\t\t// Check state reachability (simple check - all states should have at least one incoming transition or be initial)\n\t\tconst stateNames = Object.keys(workflow.states)\n\t\tconst reachableStates = new Set<string>()\n\n\t\t// Initial state is always reachable\n\t\tif (workflow.initial && typeof workflow.initial === 'string') {\n\t\t\treachableStates.add(workflow.initial)\n\t\t}\n\n\t\t// Find all target states from transitions\n\t\tfor (const [_stateName, stateConfig] of Object.entries(workflow.states)) {\n\t\t\tconst state = stateConfig as AnyStateNodeConfig\n\t\t\tif (state.on) {\n\t\t\t\tfor (const [_event, transition] of Object.entries(state.on)) {\n\t\t\t\t\tif (typeof transition === 'string') {\n\t\t\t\t\t\treachableStates.add(transition)\n\t\t\t\t\t} else if (transition && typeof transition === 'object') {\n\t\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- 'target' in transition guard confirms property; accessing unknown-typed target safely\n\t\t\t\t\t\tconst target = 'target' in transition ? (transition as { target: unknown }).target : undefined\n\t\t\t\t\t\tif (typeof target === 'string') {\n\t\t\t\t\t\t\treachableStates.add(target)\n\t\t\t\t\t\t} else if (Array.isArray(target)) {\n\t\t\t\t\t\t\ttarget.forEach((t: unknown) => {\n\t\t\t\t\t\t\t\tif (typeof t === 'string') {\n\t\t\t\t\t\t\t\t\treachableStates.add(t)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check for unreachable states\n\t\tfor (const stateName of stateNames) {\n\t\t\tif (!reachableStates.has(stateName)) {\n\t\t\t\tissues.push({\n\t\t\t\t\tseverity: ValidationSeverity.WARNING,\n\t\t\t\t\trule: 'workflow-unreachable-state',\n\t\t\t\t\tmessage: `Workflow state \"${stateName}\" may not be reachable`,\n\t\t\t\t\tdoctype,\n\t\t\t\t\tcontext: { stateName },\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\treturn issues\n\t}\n\n\t/**\n\t * Validates that actions are registered in the FieldTriggerEngine\n\t * @internal\n\t */\n\tprivate validateActionRegistration(doctype: string, actions: Record<string, string[]>): ValidationIssue[] {\n\t\tconst issues: ValidationIssue[] = []\n\t\tconst triggerEngine = getGlobalTriggerEngine()\n\n\t\tfor (const [triggerName, actionNames] of Object.entries(actions)) {\n\t\t\tif (!Array.isArray(actionNames)) {\n\t\t\t\tissues.push({\n\t\t\t\t\tseverity: ValidationSeverity.ERROR,\n\t\t\t\t\trule: 'action-invalid-format',\n\t\t\t\t\tmessage: `Action configuration for \"${triggerName}\" must be an array`,\n\t\t\t\t\tdoctype,\n\t\t\t\t\tcontext: { triggerName, actionNames },\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Check each action name\n\t\t\tfor (const actionName of actionNames) {\n\t\t\t\t// Check if action is registered globally\n\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- introspecting FieldTriggerEngine private fields for validation; no public API for this check\n\t\t\t\tconst engine = triggerEngine as unknown as {\n\t\t\t\t\tglobalActions?: Map<string, unknown>\n\t\t\t\t\tglobalTransitionActions?: Map<string, unknown>\n\t\t\t\t}\n\t\t\t\tconst isRegistered = engine.globalActions?.has(actionName) || engine.globalTransitionActions?.has(actionName)\n\n\t\t\t\tif (!isRegistered) {\n\t\t\t\t\tissues.push({\n\t\t\t\t\t\tseverity: ValidationSeverity.WARNING,\n\t\t\t\t\t\trule: 'action-not-registered',\n\t\t\t\t\t\tmessage: `Action \"${actionName}\" referenced in \"${triggerName}\" is not registered in FieldTriggerEngine`,\n\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\tcontext: { triggerName, actionName },\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn issues\n\t}\n}\n\n/**\n * Creates a validator with the given registry\n * @param registry - Registry instance\n * @param options - Additional validator options\n * @returns SchemaValidator instance\n * @public\n */\nexport function createValidator(registry: Registry, options?: Partial<ValidatorOptions>): SchemaValidator {\n\treturn new SchemaValidator({\n\t\tregistry,\n\t\t...options,\n\t})\n}\n\n/**\n * Quick validation helper\n * @param doctype - Doctype name\n * @param schema - Schema fields\n * @param registry - Registry instance\n * @param workflow - Optional workflow configuration\n * @param actions - Optional actions map\n * @returns Validation result\n * @public\n */\nexport function validateSchema(\n\tdoctype: string,\n\tschema: List<DoctypeField> | DoctypeField[] | undefined,\n\tregistry: Registry,\n\tworkflow?: AnyStateNodeConfig,\n\tactions?: ImmutableMap<string, string[]> | Map<string, string[]>\n): ValidationResult {\n\tconst validator = createValidator(registry)\n\treturn validator.validate(doctype, schema, workflow, actions)\n}\n","export type * from '@stonecrop/aform/types'\nexport type * from '@stonecrop/atable/types'\n\nimport { useClientAction } from './client-action'\nimport { executeClientHandler } from './client-handler'\nimport { useLazyLink } from './composables/lazy-link'\nimport { useStonecrop } from './composables/stonecrop'\nimport { useOperationLog, useUndoRedoShortcuts, withBatch } from './composables/operation-log'\nimport Doctype from './doctype'\nimport { DRAFT_RECORD_ID, isDraftRecordId } from './draft'\nimport {\n\tFieldTriggerEngine,\n\tgetGlobalTriggerEngine,\n\tmarkOperationIrreversible,\n\tregisterGlobalAction,\n\tregisterTransitionAction,\n\tsetFieldRollback,\n\ttriggerTransition,\n} from './field-triggers'\nimport plugin from './plugins'\nimport Registry from './registry'\nimport { Stonecrop } from './stonecrop'\nimport { HST, createHST, type HSTNode } from './stores/hst'\nimport { useOperationLogStore } from './stores/operation-log'\nimport { useValidationStore } from './stores/validation'\nimport { SchemaValidator, createValidator, validateSchema } from './schema-validator'\nimport { ValidationSeverity } from './types/schema-validator'\n\n// Export all types from ./types\nexport type * from './types'\n\n// clientHandler executor types\nexport type { ClientHandlerApi } from './client-handler'\n\n// Field-validation store types\nexport type { ValidationError } from './stores/validation'\n\n// Export enum as value (enums need runtime export, not just type)\nexport { ValidationSeverity }\n\nexport {\n\tDoctype,\n\tRegistry,\n\tStonecrop,\n\t// Unsaved-record identity, shared with the desktop shell\n\tDRAFT_RECORD_ID,\n\tisDraftRecordId,\n\tuseLazyLink,\n\tuseStonecrop,\n\t// clientHandler executor\n\texecuteClientHandler,\n\t// The one blessed write path, shared by every Vue host\n\tuseClientAction,\n\t// HST exports for advanced usage\n\tHST,\n\tcreateHST,\n\tHSTNode,\n\t// Field trigger system exports\n\tFieldTriggerEngine,\n\tgetGlobalTriggerEngine,\n\tregisterGlobalAction,\n\tregisterTransitionAction,\n\tsetFieldRollback,\n\ttriggerTransition,\n\tmarkOperationIrreversible,\n\t// Schema validator exports\n\tSchemaValidator,\n\tcreateValidator,\n\tvalidateSchema,\n\t// Operation log exports\n\tuseOperationLog,\n\tuseOperationLogStore,\n\tuseUndoRedoShortcuts,\n\twithBatch,\n\t// Field-validation store\n\tuseValidationStore,\n\t// Utility functions\n}\n\n// Default export is the Vue plugin\nexport default plugin\n"],"mappings":";;;;;;;;AAkBA,IAAM,gBAAgB,OAAO,eAAe,YAAY,CAAC,CAAC,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgC5D,eAAsB,qBAAqB,MAAc,MAAwB,CAAC,GAAqB;CACtG,MAAM,QAAQ,OAAO,KAAK,GAAG;CAE7B,OAAO,IADQ,cAAc,GAAG,OAAO,IAChC,CAAA,CAAG,GAAG,MAAM,KAAI,SAAQ,IAAI,KAAK,CAAC;AAC1C;;;;;;;;;;;;;;;;;;;;;;;ACjCA,IAAa,kBAAkB;;;;;;;;;;;;;AAc/B,SAAgB,gBAAgB,UAA8C;CAC7E,OAAO,aAAA;AACR;;;;;;ACnBA,SAAS,aAAqB;CAC7B,IAAI,OAAO,WAAW,eAAe,OAAO,YAC3C,OAAO,OAAO,WAAW;CAG1B,OAAO,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,UAAU,GAAG,CAAC;AAClE;AAaA,SAAS,sBAAsB,SAAqD;CACnF,MAAM,aAAwC;EAC7C,MAAM,QAAQ;EACd,UAAU,QAAQ;EAClB,WAAW,QAAQ,UAAU,Y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AAS,SAAS,QAAQ,UAAU,OAAO;AAC7D;;;AC3YA,IAAA,cAAe"}
1
+ {"version":3,"file":"stonecrop.js","names":[],"sources":["../src/client-handler.ts","../src/draft.ts","../src/stores/operation-log.ts","../src/field-triggers.ts","../src/stores/hst.ts","../src/stonecrop.ts","../src/composables/stonecrop.ts","../src/client-action.ts","../src/composables/lazy-link.ts","../src/composables/operation-log.ts","../src/doctype.ts","../src/registry.ts","../src/plugins/index.ts","../src/stores/validation.ts","../src/types/schema-validator.ts","../src/schema-validator.ts","../src/index.ts"],"sourcesContent":["/**\n * clientHandler execution\n * Pure executor for docbuilder-authored client handlers.\n * @packageDocumentation\n */\n\n/**\n * Named capabilities injected into a clientHandler body as function parameters.\n * The caller (the assembly composable) owns what each name resolves to — typically\n * `router`, `record`, `runAction`, and a read-only `graphql`.\n *\n * @public\n */\nexport type ClientHandlerApi = Record<string, unknown>\n\n// AsyncFunction is not a global; reach it via an async function's constructor so authored\n// bodies can use top-level `await` without writing an async wrapper.\n// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- an async function's constructor is always the AsyncFunction constructor\nconst AsyncFunction = Object.getPrototypeOf(async () => {}).constructor as new (\n\t...args: string[]\n) => (...args: unknown[]) => Promise<unknown>\n\n/**\n * Execute a docbuilder-authored `clientHandler` body against an injected API map.\n *\n * `code` is a function *body* (statements), not a full function — authored in the\n * docbuilder code editor and stored on `ActionDefinition.clientHandler`. It is compiled\n * with the AsyncFunction constructor, so `await` works directly. Each key of `api`\n * becomes a parameter name bound to its value, so a handler can reference `router`,\n * `record`, `runAction`, etc. by name.\n *\n * This executor is deliberately concern-free: it performs no routing, dispatch, or HST\n * writes itself — the caller assembles `api`. The injected set is an *intent* contract,\n * not a sandbox (an AsyncFunction body can still reach `fetch`/`window`); enforcement of\n * what a handler may actually do lives server-side, not here.\n *\n * Errors are propagated to the caller as a rejected promise — syntax errors at compile\n * time and thrown errors / rejections at run time — so callers handle both uniformly.\n *\n * @param code - the clientHandler body, e.g. `\"router.push('/users')\"`\n * @param api - named capabilities injected as parameters (default: none)\n * @returns whatever the body returns (typically `void`)\n *\n * @example\n * ```ts\n * await executeClientHandler(\"await runAction('Assign', [record.id])\", { runAction, record })\n * ```\n *\n * @public\n */\nexport async function executeClientHandler(code: string, api: ClientHandlerApi = {}): Promise<unknown> {\n\tconst names = Object.keys(api)\n\tconst fn = new AsyncFunction(...names, code)\n\treturn fn(...names.map(name => api[name]))\n}\n","/**\n * The route identity of a record the user is composing that does not exist on the server yet.\n *\n * Rejected: minting `new-<timestamp>` so a draft had a store key too. Nothing ever created that\n * HST node, so every write to `doctype.<draftId>.<field>` threw on the missing ancestor, and the\n * form's data survived only because Vue cached the empty object the getter returned and the form\n * mutated it in place — any invalidation discarded the edits silently. Seeding the node instead\n * makes the draft a phantom row, because `getRecords` lists every key under the doctype.\n *\n * So a draft is held off-HST by whoever renders the form, and reaches the server as an action\n * carrying no record id, which the write path already reads as \"create\".\n */\n\n/**\n * The record-id segment a draft route carries: `/{doctype}/new`.\n *\n * Route only — never a store key, and never sent: an action dispatched for a draft omits the id\n * rather than sending this.\n *\n * @public\n */\nexport const DRAFT_RECORD_ID = 'new'\n\n/**\n * Whether a record id refers to a record that has not been saved yet.\n *\n * Guard anything that assumes the record exists — fetching it, resolving its links, judging\n * workflow readiness — with this rather than the literal. The shell and this package once spelled\n * the rule differently, which left every guard here dead.\n *\n * @param recordId - The record id to test\n * @returns `true` when the id is the draft segment, `false` for a real identity or no id at all\n *\n * @public\n */\nexport function isDraftRecordId(recordId: string | null | undefined): boolean {\n\treturn recordId === DRAFT_RECORD_ID\n}\n","import { defineStore } from 'pinia'\nimport { ref, computed, watch } from 'vue'\nimport { useLocalStorage } from '@vueuse/core'\n\nimport type { HSTNode } from './hst'\nimport type {\n\tCrossTabMessage,\n\tHSTOperation,\n\tHSTOperationInput,\n\tOperationLogConfig,\n\tOperationLogSnapshot,\n\tOperationSource,\n\tUndoRedoState,\n} from '../types/operation-log'\n\n/**\n * Generate a UUID using crypto API or fallback\n */\nfunction generateId(): string {\n\tif (typeof crypto !== 'undefined' && crypto.randomUUID) {\n\t\treturn crypto.randomUUID()\n\t}\n\t// Fallback for environments without crypto.randomUUID\n\treturn `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`\n}\n\n/**\n * Serialize a message for BroadcastChannel\n * Converts Date objects to ISO strings for structured clone compatibility\n */\ntype SerializedOperation = Omit<HSTOperation, 'timestamp'> & { timestamp: string }\ntype SerializedCrossTabMessage = Omit<CrossTabMessage, 'timestamp' | 'operation' | 'operations'> & {\n\ttimestamp: string\n\toperation?: SerializedOperation\n\toperations?: SerializedOperation[]\n}\n\nfunction serializeForBroadcast(message: CrossTabMessage): SerializedCrossTabMessage {\n\tconst serialized: SerializedCrossTabMessage = {\n\t\ttype: message.type,\n\t\tclientId: message.clientId,\n\t\ttimestamp: message.timestamp.toISOString(),\n\t}\n\n\tif (message.operation) {\n\t\tserialized.operation = {\n\t\t\t...message.operation,\n\t\t\ttimestamp: message.operation.timestamp.toISOString(),\n\t\t}\n\t}\n\n\tif (message.operations) {\n\t\tserialized.operations = message.operations.map(op => ({\n\t\t\t...op,\n\t\t\ttimestamp: op.timestamp.toISOString(),\n\t\t}))\n\t}\n\n\treturn serialized\n}\n\n/**\n * Deserialize a message from BroadcastChannel\n * Converts ISO strings back to Date objects\n */\nfunction deserializeFromBroadcast(serialized: SerializedCrossTabMessage): CrossTabMessage {\n\tconst message: CrossTabMessage = {\n\t\ttype: serialized.type,\n\t\tclientId: serialized.clientId,\n\t\ttimestamp: new Date(serialized.timestamp),\n\t}\n\n\tif (serialized.operation) {\n\t\tmessage.operation = {\n\t\t\t...serialized.operation,\n\t\t\ttimestamp: new Date(serialized.operation.timestamp),\n\t\t}\n\t}\n\n\tif (serialized.operations) {\n\t\tmessage.operations = serialized.operations.map(op => ({\n\t\t\t...op,\n\t\t\ttimestamp: new Date(op.timestamp),\n\t\t}))\n\t}\n\n\treturn message\n}\n\n/**\n * Revert an operation (apply beforeValue)\n */\nfunction revertOperation(operation: HSTOperation, store: HSTNode) {\n\tif ((operation.type === 'set' || operation.type === 'delete') && store && typeof store.set === 'function') {\n\t\tstore.set(operation.path, operation.beforeValue, 'undo')\n\t}\n}\n\n/**\n * Apply an operation (apply afterValue)\n */\nfunction applyOperation(operation: HSTOperation, store: HSTNode) {\n\tif ((operation.type === 'set' || operation.type === 'delete') && store && typeof store.set === 'function') {\n\t\tstore.set(operation.path, operation.afterValue, 'redo')\n\t}\n}\n\n/**\n * Global HST Operation Log Store\n * Tracks all mutations with full metadata for undo/redo, sync, and audit\n *\n * @public\n */\nexport const useOperationLogStore = defineStore('hst-operation-log', () => {\n\t// Configuration\n\tconst config = ref<OperationLogConfig>({\n\t\tmaxOperations: 100,\n\t\tenableCrossTabSync: true,\n\t\tenablePersistence: false,\n\t\tpersistenceKeyPrefix: 'stonecrop-ops',\n\t})\n\n\t// State\n\tconst operations = ref<HSTOperation[]>([])\n\tconst currentIndex = ref(-1) // Points to the last applied operation\n\tconst clientId = ref(generateId())\n\tconst batchMode = ref(false)\n\tconst batchStack = ref<{ id: string; operations: HSTOperation[] }[]>([])\n\n\t// Computed\n\tconst canUndo = computed(() => {\n\t\t// Can undo if there are operations and we're not at the beginning\n\t\tif (currentIndex.value < 0) return false\n\n\t\t// Check if the operation at currentIndex is reversible\n\t\tconst operation = operations.value[currentIndex.value]\n\t\treturn operation?.reversible ?? false\n\t})\n\n\tconst canRedo = computed(() => {\n\t\t// Can redo if there are operations ahead of current index\n\t\treturn currentIndex.value < operations.value.length - 1\n\t})\n\n\tconst undoCount = computed(() => {\n\t\tlet count = 0\n\t\tfor (let i = currentIndex.value; i >= 0; i--) {\n\t\t\tif (operations.value[i]?.reversible) count++\n\t\t\telse break\n\t\t}\n\t\treturn count\n\t})\n\n\tconst redoCount = computed(() => {\n\t\treturn operations.value.length - 1 - currentIndex.value\n\t})\n\n\tconst undoRedoState = computed((): UndoRedoState => ({\n\t\tcanUndo: canUndo.value,\n\t\tcanRedo: canRedo.value,\n\t\tundoCount: undoCount.value,\n\t\tredoCount: redoCount.value,\n\t\tcurrentIndex: currentIndex.value,\n\t}))\n\n\t// Core Methods\n\n\t/**\n\t * Configure the operation log\n\t */\n\tfunction configure(options: Partial<OperationLogConfig>) {\n\t\tconfig.value = { ...config.value, ...options }\n\n\t\t// Set up persistence if enabled\n\t\tif (config.value.enablePersistence) {\n\t\t\tloadFromPersistence()\n\t\t\tsetupPersistenceWatcher()\n\t\t}\n\n\t\t// Set up cross-tab sync if enabled\n\t\tif (config.value.enableCrossTabSync) {\n\t\t\tsetupCrossTabSync()\n\t\t}\n\t}\n\n\t/**\n\t * Add an operation to the log\n\t */\n\tfunction addOperation(operation: HSTOperationInput, source: OperationSource = 'user') {\n\t\tconst fullOperation: HSTOperation = {\n\t\t\t...operation,\n\t\t\tid: generateId(),\n\t\t\ttimestamp: new Date(),\n\t\t\tsource: source,\n\t\t\tuserId: config.value.userId,\n\t\t}\n\n\t\t// Apply filter if configured\n\t\tif (config.value.operationFilter && !config.value.operationFilter(fullOperation)) {\n\t\t\treturn fullOperation.id\n\t\t}\n\n\t\t// If in batch mode, collect operations in current batch\n\t\tif (batchMode.value && batchStack.value.length > 0) {\n\t\t\tbatchStack.value[batchStack.value.length - 1].operations.push(fullOperation)\n\t\t\treturn fullOperation.id\n\t\t}\n\n\t\t// Remove any operations after current index (they become invalid after new operation)\n\t\tif (currentIndex.value < operations.value.length - 1) {\n\t\t\toperations.value = operations.value.slice(0, currentIndex.value + 1)\n\t\t}\n\n\t\t// Add new operation\n\t\toperations.value.push(fullOperation)\n\t\tcurrentIndex.value++\n\n\t\t// Enforce max operations limit\n\t\tif (config.value.maxOperations && operations.value.length > config.value.maxOperations) {\n\t\t\tconst overflow = operations.value.length - config.value.maxOperations\n\t\t\toperations.value = operations.value.slice(overflow)\n\t\t\tcurrentIndex.value -= overflow\n\t\t}\n\n\t\t// Broadcast to other tabs\n\t\tif (config.value.enableCrossTabSync) {\n\t\t\tbroadcastOperation(fullOperation)\n\t\t}\n\n\t\treturn fullOperation.id\n\t}\n\n\t/**\n\t * Start batch mode - collect multiple operations\n\t */\n\tfunction startBatch() {\n\t\tbatchMode.value = true\n\t\tbatchStack.value.push({\n\t\t\tid: generateId(),\n\t\t\toperations: [],\n\t\t})\n\t}\n\n\t/**\n\t * Commit batch - create a single batch operation\n\t */\n\tfunction commitBatch(description?: string): string | null {\n\t\tif (!batchMode.value || batchStack.value.length === 0) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst currentBatchData = batchStack.value.pop()!\n\t\tconst batchOperations = currentBatchData.operations\n\n\t\tif (batchOperations.length === 0) {\n\t\t\t// Empty batch - just pop and continue if there are outer batches\n\t\t\tif (batchStack.value.length === 0) {\n\t\t\t\tbatchMode.value = false\n\t\t\t}\n\t\t\treturn null\n\t\t}\n\n\t\tconst batchId = currentBatchData.id\n\t\tconst allReversible = batchOperations.every(op => op.reversible)\n\n\t\t// Create ancestor batch operation\n\t\tconst batchOperation: HSTOperation = {\n\t\t\tid: batchId,\n\t\t\ttype: 'batch',\n\t\t\tpath: '', // Batch doesn't have a single path\n\t\t\tfieldname: '',\n\t\t\tbeforeValue: null,\n\t\t\tafterValue: null,\n\t\t\tdoctype: batchOperations[0]?.doctype || '',\n\t\t\ttimestamp: new Date(),\n\t\t\tsource: 'user',\n\t\t\treversible: allReversible,\n\t\t\tirreversibleReason: allReversible ? undefined : 'Contains irreversible operations',\n\t\t\tdescendantOperationIds: batchOperations.map(op => op.id),\n\t\t\tmetadata: { description },\n\t\t}\n\n\t\t// Add ancestor operation ID to all descendants\n\t\tbatchOperations.forEach(op => {\n\t\t\top.ancestorOperationId = batchId\n\t\t})\n\n\t\t// If we're inside a ancestor batch, add this batch as a descendant of the ancestor\n\t\tif (batchStack.value.length > 0) {\n\t\t\t// Nested batch - add the batch operation to the ancestor batch\n\t\t\tbatchStack.value[batchStack.value.length - 1].operations.push(batchOperation)\n\t\t} else {\n\t\t\t// Top-level batch - add to the operations log\n\t\t\toperations.value.push(...batchOperations, batchOperation)\n\t\t\tcurrentIndex.value = operations.value.length - 1\n\t\t}\n\n\t\t// Broadcast batch\n\t\tif (config.value.enableCrossTabSync) {\n\t\t\tbroadcastBatch(batchOperations, batchOperation)\n\t\t}\n\n\t\t// If no more batches on stack, exit batch mode\n\t\tif (batchStack.value.length === 0) {\n\t\t\tbatchMode.value = false\n\t\t}\n\n\t\treturn batchId\n\t}\n\n\t/**\n\t * Cancel batch mode without committing\n\t */\n\tfunction cancelBatch() {\n\t\tbatchStack.value = []\n\t\tbatchMode.value = false\n\t}\n\n\t/**\n\t * Undo the last operation\n\t */\n\tfunction undo(store: HSTNode): boolean {\n\t\tif (!canUndo.value) return false\n\n\t\tconst operation = operations.value[currentIndex.value]\n\n\t\tif (!operation.reversible) {\n\t\t\t// Warn about irreversible operation\n\t\t\tif (typeof console !== 'undefined' && operation.irreversibleReason) {\n\t\t\t\tconsole.warn('Cannot undo irreversible operation:', operation.irreversibleReason)\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\n\t\ttry {\n\t\t\t// Handle batch operations\n\t\t\tif (operation.type === 'batch' && operation.descendantOperationIds) {\n\t\t\t\t// Undo all descendant operations in reverse order\n\t\t\t\tfor (let i = operation.descendantOperationIds.length - 1; i >= 0; i--) {\n\t\t\t\t\tconst descendantId = operation.descendantOperationIds[i]\n\t\t\t\t\tconst descendantOp = operations.value.find(op => op.id === descendantId)\n\t\t\t\t\tif (descendantOp) {\n\t\t\t\t\t\trevertOperation(descendantOp, store)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Undo single operation\n\t\t\t\trevertOperation(operation, store)\n\t\t\t}\n\n\t\t\tcurrentIndex.value--\n\n\t\t\t// Broadcast undo to other tabs\n\t\t\tif (config.value.enableCrossTabSync) {\n\t\t\t\tbroadcastUndo(operation)\n\t\t\t}\n\n\t\t\treturn true\n\t\t} catch (error) {\n\t\t\t// Log error in development\n\t\t\tif (typeof console !== 'undefined') {\n\t\t\t\tconsole.error('Undo failed:', error)\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\n\t/**\n\t * Redo the next operation\n\t */\n\tfunction redo(store: HSTNode): boolean {\n\t\tif (!canRedo.value) return false\n\n\t\tconst operation = operations.value[currentIndex.value + 1]\n\n\t\ttry {\n\t\t\t// Handle batch operations\n\t\t\tif (operation.type === 'batch' && operation.descendantOperationIds) {\n\t\t\t\t// Redo all descendant operations in order\n\t\t\t\tfor (const descendantId of operation.descendantOperationIds) {\n\t\t\t\t\tconst descendantOp = operations.value.find(op => op.id === descendantId)\n\t\t\t\t\tif (descendantOp) {\n\t\t\t\t\t\tapplyOperation(descendantOp, store)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Redo single operation\n\t\t\t\tapplyOperation(operation, store)\n\t\t\t}\n\n\t\t\tcurrentIndex.value++\n\n\t\t\t// Broadcast redo to other tabs\n\t\t\tif (config.value.enableCrossTabSync) {\n\t\t\t\tbroadcastRedo(operation)\n\t\t\t}\n\n\t\t\treturn true\n\t\t} catch (error) {\n\t\t\t// Log error in development\n\t\t\tif (typeof console !== 'undefined') {\n\t\t\t\tconsole.error('Redo failed:', error)\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\n\t/**\n\t * Get operation log snapshot for debugging\n\t */\n\tfunction getSnapshot(): OperationLogSnapshot {\n\t\tconst reversibleOps = operations.value.filter(op => op.reversible).length\n\t\tconst timestamps = operations.value.map(op => op.timestamp)\n\n\t\treturn {\n\t\t\toperations: [...operations.value],\n\t\t\tcurrentIndex: currentIndex.value,\n\t\t\ttotalOperations: operations.value.length,\n\t\t\treversibleOperations: reversibleOps,\n\t\t\tirreversibleOperations: operations.value.length - reversibleOps,\n\t\t\toldestOperation: timestamps.length > 0 ? new Date(Math.min(...timestamps.map(t => t.getTime()))) : undefined,\n\t\t\tnewestOperation: timestamps.length > 0 ? new Date(Math.max(...timestamps.map(t => t.getTime()))) : undefined,\n\t\t}\n\t}\n\n\t/**\n\t * Clear all operations\n\t */\n\tfunction clear() {\n\t\toperations.value = []\n\t\tcurrentIndex.value = -1\n\t}\n\n\t/**\n\t * Get operations for a specific doctype and recordId\n\t */\n\tfunction getOperationsFor(doctype: string, recordId?: string): HSTOperation[] {\n\t\treturn operations.value.filter(op => op.doctype === doctype && (recordId === undefined || op.recordId === recordId))\n\t}\n\n\t/**\n\t * Mark an operation as irreversible\n\t * @param operationId - The ID of the operation to mark\n\t * @param reason - The reason why the operation is irreversible\n\t */\n\tfunction markIrreversible(operationId: string, reason: string) {\n\t\tconst operation = operations.value.find(op => op.id === operationId)\n\t\tif (operation) {\n\t\t\toperation.reversible = false\n\t\t\toperation.irreversibleReason = reason\n\t\t}\n\t}\n\n\t/**\n\t * Log an action execution (stateless actions like print, email, etc.)\n\t * These operations are tracked but typically not reversible\n\t * @param doctype - The doctype the action was executed on\n\t * @param actionName - The name of the action that was executed\n\t * @param recordIds - Optional array of record IDs the action was executed on\n\t * @param result - The result of the action execution\n\t * @param error - Optional error message if action failed\n\t * @returns The operation ID\n\t */\n\tfunction logAction(\n\t\tdoctype: string,\n\t\tactionName: string,\n\t\trecordIds?: string[],\n\t\tresult: 'success' | 'failure' | 'pending' = 'success',\n\t\terror?: string\n\t): string {\n\t\tconst operation: HSTOperationInput = {\n\t\t\ttype: 'action',\n\t\t\tpath: recordIds && recordIds.length > 0 ? `${doctype}.${recordIds[0]}` : doctype,\n\t\t\tfieldname: '',\n\t\t\tbeforeValue: null,\n\t\t\tafterValue: null,\n\t\t\tdoctype,\n\t\t\trecordId: recordIds && recordIds.length > 0 ? recordIds[0] : undefined,\n\t\t\treversible: false, // Actions are typically not reversible\n\t\t\tactionName,\n\t\t\tactionRecordIds: recordIds,\n\t\t\tactionResult: result,\n\t\t\tactionError: error,\n\t\t}\n\n\t\treturn addOperation(operation)\n\t}\n\n\t// Cross-tab synchronization\n\tlet broadcastChannel: BroadcastChannel | null = null\n\n\tfunction setupCrossTabSync() {\n\t\tif (typeof window === 'undefined' || !window.BroadcastChannel) return\n\n\t\tbroadcastChannel = new BroadcastChannel('stonecrop-operation-log')\n\n\t\tbroadcastChannel.addEventListener('message', (event: MessageEvent) => {\n\t\t\tconst rawMessage = event.data\n\n\t\t\tif (!rawMessage || typeof rawMessage !== 'object') return\n\n\t\t\tconst message = deserializeFromBroadcast(rawMessage)\n\n\t\t\t// Ignore messages from this tab\n\t\t\tif (message.clientId === clientId.value) return\n\n\t\t\tif (message.type === 'operation' && message.operation) {\n\t\t\t\t// Add operation from another tab\n\t\t\t\toperations.value.push({ ...message.operation, source: 'sync' })\n\t\t\t\tcurrentIndex.value = operations.value.length - 1\n\t\t\t} else if (message.type === 'operation' && message.operations) {\n\t\t\t\t// Add batch operations from another tab\n\t\t\t\toperations.value.push(\n\t\t\t\t\t...message.operations.map((op): HSTOperation => Object.assign({}, op, { source: 'sync' as const }))\n\t\t\t\t)\n\t\t\t\tcurrentIndex.value = operations.value.length - 1\n\t\t\t}\n\t\t})\n\t}\n\n\tfunction broadcastOperation(operation: HSTOperation) {\n\t\tif (!broadcastChannel) return\n\n\t\tconst message: CrossTabMessage = {\n\t\t\ttype: 'operation',\n\t\t\toperation,\n\t\t\tclientId: clientId.value,\n\t\t\ttimestamp: new Date(),\n\t\t}\n\t\t// oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel.postMessage does not accept targetOrigin; rule only applies to window.postMessage\n\t\tbroadcastChannel.postMessage(serializeForBroadcast(message))\n\t}\n\n\tfunction broadcastBatch(descendantOps: HSTOperation[], batchOp: HSTOperation) {\n\t\tif (!broadcastChannel) return\n\n\t\tconst message: CrossTabMessage = {\n\t\t\ttype: 'operation',\n\t\t\toperations: [...descendantOps, batchOp],\n\t\t\tclientId: clientId.value,\n\t\t\ttimestamp: new Date(),\n\t\t}\n\t\t// oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel.postMessage does not accept targetOrigin; rule only applies to window.postMessage\n\t\tbroadcastChannel.postMessage(serializeForBroadcast(message))\n\t}\n\n\tfunction broadcastUndo(operation: HSTOperation) {\n\t\tif (!broadcastChannel) return\n\n\t\tconst message: CrossTabMessage = {\n\t\t\ttype: 'undo',\n\t\t\toperation,\n\t\t\tclientId: clientId.value,\n\t\t\ttimestamp: new Date(),\n\t\t}\n\t\t// oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel.postMessage does not accept targetOrigin; rule only applies to window.postMessage\n\t\tbroadcastChannel.postMessage(serializeForBroadcast(message))\n\t}\n\n\tfunction broadcastRedo(operation: HSTOperation) {\n\t\tif (!broadcastChannel) return\n\n\t\tconst message: CrossTabMessage = {\n\t\t\ttype: 'redo',\n\t\t\toperation,\n\t\t\tclientId: clientId.value,\n\t\t\ttimestamp: new Date(),\n\t\t}\n\t\t// oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel.postMessage does not accept targetOrigin; rule only applies to window.postMessage\n\t\tbroadcastChannel.postMessage(serializeForBroadcast(message))\n\t}\n\n\t// Persistence using VueUse\n\ttype PersistedData = {\n\t\toperations: Array<Omit<HSTOperation, 'timestamp'> & { timestamp: string }>\n\t\tcurrentIndex: number\n\t}\n\n\tconst persistedData = useLocalStorage<PersistedData | null>('stonecrop-operations', null, {\n\t\tserializer: {\n\t\t\tread: (v: string) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst data = JSON.parse(v)\n\t\t\t\t\treturn data\n\t\t\t\t} catch {\n\t\t\t\t\treturn null\n\t\t\t\t}\n\t\t\t},\n\t\t\twrite: (v: PersistedData | null) => {\n\t\t\t\tif (!v) return ''\n\t\t\t\treturn JSON.stringify(v)\n\t\t\t},\n\t\t},\n\t})\n\n\tfunction loadFromPersistence() {\n\t\tif (typeof window === 'undefined') return\n\n\t\ttry {\n\t\t\tconst data = persistedData.value\n\t\t\tif (data && Array.isArray(data.operations)) {\n\t\t\t\toperations.value = data.operations.map(op => ({\n\t\t\t\t\t...op,\n\t\t\t\t\ttimestamp: new Date(op.timestamp),\n\t\t\t\t}))\n\t\t\t\tcurrentIndex.value = data.currentIndex ?? -1\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Log error in development\n\t\t\tif (typeof console !== 'undefined') {\n\t\t\t\tconsole.error('Failed to load operations from persistence:', error)\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction saveToPersistence() {\n\t\tif (typeof window === 'undefined') return\n\n\t\ttry {\n\t\t\tpersistedData.value = {\n\t\t\t\toperations: operations.value.map(op => ({\n\t\t\t\t\t...op,\n\t\t\t\t\ttimestamp: op.timestamp.toISOString(),\n\t\t\t\t})),\n\t\t\t\tcurrentIndex: currentIndex.value,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Log error in development\n\t\t\tif (typeof console !== 'undefined') {\n\t\t\t\tconsole.error('Failed to save operations to persistence:', error)\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction setupPersistenceWatcher() {\n\t\twatch(\n\t\t\t[operations, currentIndex],\n\t\t\t() => {\n\t\t\t\tif (config.value.enablePersistence) {\n\t\t\t\t\tsaveToPersistence()\n\t\t\t\t}\n\t\t\t},\n\t\t\t{ deep: true }\n\t\t)\n\t}\n\n\treturn {\n\t\t// State\n\t\toperations,\n\t\tcurrentIndex,\n\t\tconfig,\n\t\tclientId,\n\t\tundoRedoState,\n\n\t\t// Computed\n\t\tcanUndo,\n\t\tcanRedo,\n\t\tundoCount,\n\t\tredoCount,\n\n\t\t// Methods\n\t\tconfigure,\n\t\taddOperation,\n\t\tstartBatch,\n\t\tcommitBatch,\n\t\tcancelBatch,\n\t\tundo,\n\t\tredo,\n\t\tclear,\n\t\tgetOperationsFor,\n\t\tgetSnapshot,\n\t\tmarkIrreversible,\n\t\tlogAction,\n\t}\n})\n","import type { Map as ImmutableMap } from 'immutable'\nimport { useOperationLogStore } from './stores/operation-log'\nimport type {\n\tFieldAction,\n\tFieldActionFunction,\n\tFieldChangeContext,\n\tFieldTriggerExecutionResult,\n\tFieldTriggerOptions,\n\tActionExecutionResult,\n\tTransitionChangeContext,\n\tTransitionActionFunction,\n\tTransitionExecutionResult,\n} from './types/field-triggers'\n\n/**\n * Field trigger execution engine integrated with Registry\n * Singleton pattern following Registry implementation\n * @public\n */\nexport class FieldTriggerEngine {\n\t/**\n\t * The root FieldTriggerEngine instance\n\t */\n\tstatic _root: FieldTriggerEngine\n\n\tprivate options!: FieldTriggerOptions & { defaultTimeout: number; debug: boolean; enableRollback: boolean }\n\tprivate doctypeActions = new Map<string, Map<string, string[]>>() // doctype -> action/field -> functions\n\tprivate doctypeTransitions = new Map<string, Map<string, string[]>>() // doctype -> transition -> functions\n\tprivate fieldRollbackConfig = new Map<string, Map<string, boolean>>() // doctype -> field -> rollback enabled\n\tprivate globalActions = new Map<string, FieldActionFunction>() // action name -> function\n\tprivate globalTransitionActions = new Map<string, TransitionActionFunction>() // transition action name -> function\n\n\t/**\n\t * Creates a new FieldTriggerEngine instance (singleton pattern)\n\t * @param options - Configuration options for the field trigger engine\n\t */\n\tconstructor(options: FieldTriggerOptions = {}) {\n\t\tif (FieldTriggerEngine._root) {\n\t\t\treturn FieldTriggerEngine._root\n\t\t}\n\t\tFieldTriggerEngine._root = this\n\t\tthis.options = {\n\t\t\tdefaultTimeout: options.defaultTimeout ?? 5000,\n\t\t\tdebug: options.debug ?? false,\n\t\t\tenableRollback: options.enableRollback ?? true,\n\t\t\terrorHandler: options.errorHandler,\n\t\t}\n\t\treturn this\n\t}\n\n\t/**\n\t * Register a global action function\n\t * @param name - The name of the action\n\t * @param fn - The action function\n\t */\n\tregisterAction(name: string, fn: FieldActionFunction): void {\n\t\tthis.globalActions.set(name, fn)\n\t}\n\n\t/**\n\t * Look up a registered action function by name.\n\t * Returns `undefined` if the action has not been registered.\n\t * @param name - The action name\n\t */\n\tgetAction(name: string): FieldActionFunction | undefined {\n\t\treturn this.globalActions.get(name)\n\t}\n\n\t/**\n\t * Register a global XState transition action function\n\t * @param name - The name of the transition action\n\t * @param fn - The transition action function\n\t */\n\tregisterTransitionAction(name: string, fn: TransitionActionFunction): void {\n\t\tthis.globalTransitionActions.set(name, fn)\n\t}\n\n\t/**\n\t * Configure rollback behavior for a specific field trigger\n\t * @param doctype - The doctype name\n\t * @param fieldname - The field name\n\t * @param enableRollback - Whether to enable rollback\n\t */\n\tsetFieldRollback(doctype: string, fieldname: string, enableRollback: boolean): void {\n\t\tif (!this.fieldRollbackConfig.has(doctype)) {\n\t\t\tthis.fieldRollbackConfig.set(doctype, new Map())\n\t\t}\n\t\tthis.fieldRollbackConfig.get(doctype)!.set(fieldname, enableRollback)\n\t}\n\n\t/**\n\t * Get rollback configuration for a specific field trigger\n\t */\n\tprivate getFieldRollback(doctype: string, fieldname: string): boolean | undefined {\n\t\treturn this.fieldRollbackConfig.get(doctype)?.get(fieldname)\n\t}\n\n\t/**\n\t * Register actions from a doctype - both regular actions and field triggers\n\t * Separates XState transitions (uppercase) from field triggers (lowercase)\n\t * @param doctype - The doctype name\n\t * @param actions - The actions to register (supports Immutable Map, Map, or plain object)\n\t */\n\tregisterDoctypeActions(\n\t\tdoctype: string,\n\t\tactions: ImmutableMap<string, string[]> | Map<string, string[]> | Record<string, string[]> | undefined\n\t): void {\n\t\tif (!actions) return\n\n\t\tconst actionMap = new Map<string, string[]>()\n\t\tconst transitionMap = new Map<string, string[]>()\n\n\t\t// Convert from different Map types to regular Map\n\t\t// Check for Immutable.js Map first (has entrySeq method)\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Immutable.js interop: runtime duck-type check follows\n\t\tconst immutableActions = actions as ImmutableMap<string, string[]>\n\t\tif (typeof immutableActions.entrySeq === 'function') {\n\t\t\t// Immutable Map\n\t\t\timmutableActions.entrySeq().forEach(([key, value]: [string, string[]]) => {\n\t\t\t\tthis.categorizeAction(key, value, actionMap, transitionMap)\n\t\t\t})\n\t\t} else if (actions instanceof Map) {\n\t\t\t// Regular Map\n\t\t\tfor (const [key, value] of actions) {\n\t\t\t\tthis.categorizeAction(key, value, actionMap, transitionMap)\n\t\t\t}\n\t\t} else if (actions && typeof actions === 'object') {\n\t\t\t// Plain object\n\t\t\tObject.entries(actions).forEach(([key, value]) => {\n\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Object.entries value type is unknown at runtime; guarded by typeof object check above\n\t\t\t\tthis.categorizeAction(key, value as string[], actionMap, transitionMap)\n\t\t\t})\n\t\t}\n\n\t\t// Always set the maps, even if empty\n\t\tthis.doctypeActions.set(doctype, actionMap)\n\t\tthis.doctypeTransitions.set(doctype, transitionMap)\n\t}\n\n\t/**\n\t * Categorize an action as either a field trigger or XState transition\n\t * Uses uppercase convention: UPPERCASE = transition, lowercase/mixed = field trigger\n\t */\n\tprivate categorizeAction(\n\t\tkey: string,\n\t\tvalue: string[],\n\t\tactionMap: Map<string, string[]>,\n\t\ttransitionMap: Map<string, string[]>\n\t): void {\n\t\t// Check if the key is all uppercase (XState transition convention)\n\t\tif (this.isTransitionKey(key)) {\n\t\t\ttransitionMap.set(key, value)\n\t\t} else {\n\t\t\tactionMap.set(key, value)\n\t\t}\n\t}\n\n\t/**\n\t * Determine if a key represents an XState transition\n\t * Transitions are identified by being all uppercase\n\t */\n\tprivate isTransitionKey(key: string): boolean {\n\t\t// Must be all uppercase letters/numbers/underscores\n\t\treturn /^[A-Z0-9_]+$/.test(key) && key.length > 0\n\t}\n\n\t/**\n\t * Execute field triggers for a changed field\n\t * @param context - The field change context\n\t * @param options - Execution options (timeout and enableRollback)\n\t */\n\tasync executeFieldTriggers(\n\t\tcontext: FieldChangeContext,\n\t\toptions: { timeout?: number; enableRollback?: boolean } = {}\n\t): Promise<FieldTriggerExecutionResult> {\n\t\tconst { doctype, fieldname } = context\n\t\tconst triggers = this.findFieldTriggers(doctype, fieldname)\n\n\t\tif (triggers.length === 0) {\n\t\t\treturn {\n\t\t\t\tpath: context.path,\n\t\t\t\tactionResults: [],\n\t\t\t\ttotalExecutionTime: 0,\n\t\t\t\tallSucceeded: true,\n\t\t\t\tstoppedOnError: false,\n\t\t\t\trolledBack: false,\n\t\t\t}\n\t\t}\n\n\t\tconst startTime = performance.now()\n\t\tconst actionResults: ActionExecutionResult[] = []\n\t\tlet stoppedOnError = false\n\t\tlet rolledBack = false\n\t\tlet snapshot: any = undefined\n\n\t\t// Determine if rollback is enabled (priority: execution option > field config > global setting)\n\t\tconst fieldRollbackConfig = this.getFieldRollback(doctype, fieldname)\n\t\tconst rollbackEnabled = options.enableRollback ?? fieldRollbackConfig ?? this.options.enableRollback\n\n\t\t// Capture snapshot before executing actions if rollback is enabled\n\t\tif (rollbackEnabled && context.store) {\n\t\t\tsnapshot = this.captureSnapshot(context)\n\t\t}\n\n\t\t// Execute actions sequentially — each action may depend on state set by the previous; stop-on-error semantics require sequential execution\n\t\tfor (const actionName of triggers) {\n\t\t\ttry {\n\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- intentionally sequential; actions are order-dependent and stop on first failure\n\t\t\t\tconst actionResult = await this.executeAction(actionName, context, options.timeout)\n\t\t\t\tactionResults.push(actionResult)\n\n\t\t\t\tif (!actionResult.success) {\n\t\t\t\t\tstoppedOnError = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconst actionError = error instanceof Error ? error : new Error(String(error))\n\t\t\t\tconst errorResult: ActionExecutionResult = {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: actionError,\n\t\t\t\t\texecutionTime: 0,\n\t\t\t\t\taction: actionName,\n\t\t\t\t}\n\t\t\t\tactionResults.push(errorResult)\n\t\t\t\tstoppedOnError = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Perform rollback if enabled, errors occurred, and we have a snapshot\n\t\tif (rollbackEnabled && stoppedOnError && snapshot && context.store) {\n\t\t\ttry {\n\t\t\t\tthis.restoreSnapshot(context, snapshot)\n\t\t\t\trolledBack = true\n\t\t\t} catch (rollbackError) {\n\t\t\t\tconsole.error('[FieldTriggers] Rollback failed:', rollbackError)\n\t\t\t}\n\t\t}\n\n\t\tconst totalExecutionTime = performance.now() - startTime\n\n\t\t// Call global error handler if configured and errors occurred\n\t\tconst failedResults = actionResults.filter(r => !r.success && r.error != null)\n\t\tif (failedResults.length > 0 && this.options.errorHandler) {\n\t\t\tfor (const failedResult of failedResults) {\n\t\t\t\ttry {\n\t\t\t\t\tif (failedResult.error) {\n\t\t\t\t\t\tthis.options.errorHandler(failedResult.error, context, failedResult.action)\n\t\t\t\t\t}\n\t\t\t\t} catch (handlerError) {\n\t\t\t\t\tconsole.error('[FieldTriggers] Error in global error handler:', handlerError)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst result: FieldTriggerExecutionResult = {\n\t\t\tpath: context.path,\n\t\t\tactionResults,\n\t\t\ttotalExecutionTime,\n\t\t\tallSucceeded: actionResults.every(r => r.success),\n\t\t\tstoppedOnError,\n\t\t\trolledBack,\n\t\t\tsnapshot: this.options.debug && rollbackEnabled ? snapshot : undefined, // Only include snapshot in debug mode if rollback is enabled\n\t\t}\n\n\t\treturn result\n\t}\n\n\t/**\n\t * Execute XState transition actions\n\t * Similar to field triggers but specifically for FSM state transitions\n\t * @param context - The transition change context\n\t * @param options - Execution options (timeout)\n\t */\n\tasync executeTransitionActions(\n\t\tcontext: TransitionChangeContext,\n\t\toptions: { timeout?: number } = {}\n\t): Promise<TransitionExecutionResult[]> {\n\t\tconst { doctype, transition } = context\n\t\tconst transitionActions = this.findTransitionActions(doctype, transition)\n\n\t\tif (transitionActions.length === 0) {\n\t\t\treturn []\n\t\t}\n\n\t\tconst results: TransitionExecutionResult[] = []\n\n\t\t// Execute transition actions sequentially — transitions are state-machine steps; order and stop-on-error are required\n\t\tfor (const actionName of transitionActions) {\n\t\t\ttry {\n\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- intentionally sequential; transition actions are order-dependent and stop on first failure\n\t\t\t\tconst actionResult = await this.executeTransitionAction(actionName, context, options.timeout)\n\t\t\t\tresults.push(actionResult)\n\n\t\t\t\tif (!actionResult.success) {\n\t\t\t\t\t// Stop on first error for transitions\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconst actionError = error instanceof Error ? error : new Error(String(error))\n\t\t\t\tconst errorResult: TransitionExecutionResult = {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: actionError,\n\t\t\t\t\texecutionTime: 0,\n\t\t\t\t\taction: actionName,\n\t\t\t\t\ttransition,\n\t\t\t\t}\n\t\t\t\tresults.push(errorResult)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Call global error handler if configured and errors occurred\n\t\tconst failedResults = results.filter(r => !r.success)\n\t\tif (failedResults.length > 0 && this.options.errorHandler) {\n\t\t\tfor (const failedResult of failedResults) {\n\t\t\t\ttry {\n\t\t\t\t\t// Call with FieldChangeContext (base context type)\n\t\t\t\t\tif (failedResult.error) {\n\t\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- action result carries string name; FieldAction cast required by errorHandler signature\n\t\t\t\t\t\tthis.options.errorHandler(failedResult.error, context, failedResult.action as unknown as FieldAction)\n\t\t\t\t\t}\n\t\t\t\t} catch (handlerError) {\n\t\t\t\t\tconsole.error('[FieldTriggers] Error in global error handler:', handlerError)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn results\n\t}\n\n\t/**\n\t * Find transition actions for a specific doctype and transition\n\t */\n\tprivate findTransitionActions(doctype: string, transition: string): string[] {\n\t\tconst doctypeTransitions = this.doctypeTransitions.get(doctype)\n\t\tif (!doctypeTransitions) return []\n\n\t\treturn doctypeTransitions.get(transition) || []\n\t}\n\n\t/**\n\t * Execute a single transition action by name\n\t */\n\tprivate async executeTransitionAction(\n\t\tactionName: string,\n\t\tcontext: TransitionChangeContext,\n\t\ttimeout?: number\n\t): Promise<TransitionExecutionResult> {\n\t\tconst startTime = performance.now()\n\t\tconst actionTimeout = timeout ?? this.options.defaultTimeout\n\n\t\ttry {\n\t\t\t// Look up action in transition-specific registry first, then fall back to global\n\t\t\tlet actionFn = this.globalTransitionActions.get(actionName)\n\n\t\t\t// If not found in transition registry, try regular action registry\n\t\t\t// This allows sharing actions between field triggers and transitions\n\t\t\tif (!actionFn) {\n\t\t\t\tconst regularActionFn = this.globalActions.get(actionName)\n\t\t\t\tif (regularActionFn) {\n\t\t\t\t\t// Wrap regular action to accept TransitionChangeContext\n\t\t\t\t\tactionFn = regularActionFn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!actionFn) {\n\t\t\t\tthrow new Error(`Transition action \"${actionName}\" not found in registry`)\n\t\t\t}\n\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- actionFn may be FieldActionFunction set from globalActions fallback; polymorphic function type\n\t\t\tawait this.executeWithTimeout(actionFn as FieldActionFunction, context, actionTimeout)\n\t\t\tconst executionTime = performance.now() - startTime\n\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\texecutionTime,\n\t\t\t\taction: actionName,\n\t\t\t\ttransition: context.transition,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst executionTime = performance.now() - startTime\n\t\t\tconst actionError = error instanceof Error ? error : new Error(String(error))\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: actionError,\n\t\t\t\texecutionTime,\n\t\t\t\taction: actionName,\n\t\t\t\ttransition: context.transition,\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Find field triggers for a specific doctype and field\n\t * Field triggers are identified by keys that look like field paths (contain dots or match field names)\n\t */\n\tprivate findFieldTriggers(doctype: string, fieldname: string): string[] {\n\t\tconst doctypeActions = this.doctypeActions.get(doctype)\n\t\tif (!doctypeActions) return []\n\n\t\tconst triggers: string[] = []\n\n\t\tfor (const [key, actionNames] of doctypeActions) {\n\t\t\t// Check if this key is a field trigger pattern\n\t\t\tif (this.isFieldTriggerKey(key, fieldname)) {\n\t\t\t\ttriggers.push(...actionNames)\n\t\t\t}\n\t\t}\n\n\t\treturn triggers\n\t}\n\n\t/**\n\t * Determine if an action key represents a field trigger\n\t * Field triggers can be:\n\t * - Exact field name match: \"emailAddress\"\n\t * - Wildcard patterns: \"emailAddress.*\", \"*.is_primary\"\n\t * - Nested field paths: \"address.street\", \"contact.email\"\n\t */\n\tprivate isFieldTriggerKey(key: string, fieldname: string): boolean {\n\t\t// Exact match\n\t\tif (key === fieldname) return true\n\n\t\t// Contains dots - likely a field path pattern\n\t\tif (key.includes('.')) {\n\t\t\treturn this.matchFieldPattern(key, fieldname)\n\t\t}\n\n\t\t// Contains wildcards\n\t\tif (key.includes('*')) {\n\t\t\treturn this.matchFieldPattern(key, fieldname)\n\t\t}\n\n\t\treturn false\n\t}\n\n\t/**\n\t * Match a field pattern against a field name\n\t * Supports wildcards (*) for dynamic segments\n\t */\n\tprivate matchFieldPattern(pattern: string, fieldname: string): boolean {\n\t\tconst patternParts = pattern.split('.')\n\t\tconst fieldParts = fieldname.split('.')\n\n\t\tif (patternParts.length !== fieldParts.length) {\n\t\t\treturn false\n\t\t}\n\n\t\tfor (let i = 0; i < patternParts.length; i++) {\n\t\t\tconst patternPart = patternParts[i]\n\t\t\tconst fieldPart = fieldParts[i]\n\n\t\t\tif (patternPart === '*') {\n\t\t\t\t// Wildcard matches any segment\n\t\t\t\tcontinue\n\t\t\t} else if (patternPart !== fieldPart) {\n\t\t\t\t// Exact match required\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t}\n\n\t/**\n\t * Execute a single action by name\n\t */\n\tprivate async executeAction(\n\t\tactionName: string,\n\t\tcontext: FieldChangeContext,\n\t\ttimeout?: number\n\t): Promise<ActionExecutionResult> {\n\t\tconst startTime = performance.now()\n\t\tconst actionTimeout = timeout ?? this.options.defaultTimeout\n\n\t\ttry {\n\t\t\t// Look up action in global registry\n\t\t\tconst actionFn = this.globalActions.get(actionName)\n\t\t\tif (!actionFn) {\n\t\t\t\tthrow new Error(`Action \"${actionName}\" not found in registry`)\n\t\t\t}\n\n\t\t\tawait this.executeWithTimeout(actionFn, context, actionTimeout)\n\t\t\tconst executionTime = performance.now() - startTime\n\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\texecutionTime,\n\t\t\t\taction: actionName,\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst executionTime = performance.now() - startTime\n\t\t\tconst actionError = error instanceof Error ? error : new Error(String(error))\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: actionError,\n\t\t\t\texecutionTime,\n\t\t\t\taction: actionName,\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Execute a function with timeout\n\t */\n\tprivate async executeWithTimeout(\n\t\tfn: FieldActionFunction,\n\t\tcontext: FieldChangeContext,\n\t\ttimeout: number\n\t): Promise<unknown> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timeoutId = setTimeout(() => {\n\t\t\t\treject(new Error(`Action timeout after ${timeout}ms`))\n\t\t\t}, timeout)\n\n\t\t\tPromise.resolve(fn(context))\n\t\t\t\t.then(result => {\n\t\t\t\t\tclearTimeout(timeoutId)\n\t\t\t\t\treturn resolve(result)\n\t\t\t\t})\n\t\t\t\t.catch(error => {\n\t\t\t\t\tclearTimeout(timeoutId)\n\t\t\t\t\treject(error instanceof Error ? error : new Error(String(error)))\n\t\t\t\t})\n\t\t})\n\t}\n\n\t/**\n\t * Capture a snapshot of the record state before executing actions\n\t * This creates a deep copy of the record data for potential rollback\n\t */\n\tprivate captureSnapshot(context: FieldChangeContext): any {\n\t\tif (!context.store || !context.doctype || !context.recordId) {\n\t\t\treturn undefined\n\t\t}\n\n\t\ttry {\n\t\t\t// Get the record path (doctype.recordId)\n\t\t\tconst recordPath = `${context.doctype}.${context.recordId}`\n\n\t\t\t// Get the current record data\n\t\t\tconst recordData = context.store.get(recordPath)\n\n\t\t\tif (!recordData || typeof recordData !== 'object') {\n\t\t\t\treturn undefined\n\t\t\t}\n\n\t\t\t// Create a deep copy to avoid reference issues\n\t\t\treturn JSON.parse(JSON.stringify(recordData))\n\t\t} catch (error) {\n\t\t\tif (this.options.debug) {\n\t\t\t\tconsole.warn('[FieldTriggers] Failed to capture snapshot:', error)\n\t\t\t}\n\t\t\treturn undefined\n\t\t}\n\t}\n\n\t/**\n\t * Restore a previously captured snapshot\n\t * This reverts the record to its state before actions were executed\n\t */\n\tprivate restoreSnapshot(context: FieldChangeContext, snapshot: any): void {\n\t\tif (!context.store || !context.doctype || !context.recordId || !snapshot) {\n\t\t\treturn\n\t\t}\n\n\t\ttry {\n\t\t\t// Get the record path (doctype.recordId)\n\t\t\tconst recordPath = `${context.doctype}.${context.recordId}`\n\n\t\t\t// Restore the entire record from snapshot\n\t\t\tcontext.store.set(recordPath, snapshot)\n\n\t\t\tif (this.options.debug) {\n\t\t\t\t// oxlint-disable-next-line no-console\n\t\t\t\tconsole.log(`[FieldTriggers] Rolled back ${recordPath} to previous state`)\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.error('[FieldTriggers] Failed to restore snapshot:', error)\n\t\t\tthrow error\n\t\t}\n\t}\n}\n\n/**\n * Get or create the global field trigger engine singleton\n * @param options - Optional configuration for the field trigger engine\n * @public\n */\nexport function getGlobalTriggerEngine(options?: FieldTriggerOptions): FieldTriggerEngine {\n\treturn new FieldTriggerEngine(options)\n}\n\n/**\n * Register a global action function that can be used in field triggers\n * @param name - The name of the action to register\n * @param fn - The action function to execute when the trigger fires\n * @public\n */\nexport function registerGlobalAction(name: string, fn: FieldActionFunction): void {\n\tconst engine = getGlobalTriggerEngine()\n\tengine.registerAction(name, fn)\n}\n\n/**\n * Register a global XState transition action function\n * @param name - The name of the transition action to register\n * @param fn - The transition action function to execute\n * @public\n */\nexport function registerTransitionAction(name: string, fn: TransitionActionFunction): void {\n\tconst engine = getGlobalTriggerEngine()\n\tengine.registerTransitionAction(name, fn)\n}\n\n/**\n * Configure rollback behavior for a specific field trigger\n * @param doctype - The doctype name\n * @param fieldname - The field name\n * @param enableRollback - Whether to enable automatic rollback for this field\n * @public\n */\nexport function setFieldRollback(doctype: string, fieldname: string, enableRollback: boolean): void {\n\tconst engine = getGlobalTriggerEngine()\n\tengine.setFieldRollback(doctype, fieldname, enableRollback)\n}\n\n/**\n * Manually trigger an XState transition for a specific doctype/record\n * This can be called directly when you need to execute transition actions programmatically\n * @param doctype - The doctype name\n * @param transition - The XState transition name to trigger\n * @param options - Optional configuration for the transition\n * @public\n */\nexport async function triggerTransition(\n\tdoctype: string,\n\ttransition: string,\n\toptions?: {\n\t\trecordId?: string\n\t\tcurrentState?: string\n\t\ttargetState?: string\n\t\tfsmContext?: Record<string, any>\n\t\tpath?: string\n\t}\n): Promise<any> {\n\tconst engine = getGlobalTriggerEngine()\n\n\tconst context: TransitionChangeContext = {\n\t\tpath: options?.path || (options?.recordId ? `${doctype}.${options.recordId}` : doctype),\n\t\tfieldname: '',\n\t\tbeforeValue: undefined,\n\t\tafterValue: undefined,\n\t\toperation: 'set',\n\t\tdoctype,\n\t\trecordId: options?.recordId,\n\t\ttimestamp: new Date(),\n\t\ttransition,\n\t\tcurrentState: options?.currentState,\n\t\ttargetState: options?.targetState,\n\t\tfsmContext: options?.fsmContext,\n\t}\n\n\treturn await engine.executeTransitionActions(context)\n}\n\n/**\n * Mark a specific operation as irreversible.\n * Used to prevent undo of critical operations like publishing or deletion.\n * @param operationId - The ID of the operation to mark as irreversible\n * @param reason - Human-readable reason why the operation cannot be undone\n * @public\n */\nexport function markOperationIrreversible(operationId: string | undefined, reason: string): void {\n\tif (!operationId) return\n\n\ttry {\n\t\tconst store = useOperationLogStore()\n\t\tstore.markIrreversible(operationId, reason)\n\t} catch {\n\t\t// Operation log is optional\n\t}\n}\n","import { getGlobalTriggerEngine } from '../field-triggers'\nimport { useOperationLogStore } from './operation-log'\nimport type { FieldChangeContext, TransitionChangeContext } from '../types/field-triggers'\nimport type { HSTNode } from '../types/hst'\n\n/**\n * Get the operation log store if available\n */\nfunction getOperationLogStore() {\n\ttry {\n\t\treturn useOperationLogStore()\n\t} catch {\n\t\t// Operation log is optional\n\t\treturn null\n\t}\n}\n\n// Type definitions for global Registry\ninterface RegistryGlobal {\n\tRegistry?: {\n\t\t_root?: {\n\t\t\tregistry: Record<string, any>\n\t\t}\n\t}\n}\n\n// Interface for Immutable-like objects\ninterface ImmutableLike {\n\tget(key: string): any\n\tset(key: string, value: any): ImmutableLike\n\thas(key: string): boolean\n\tsize?: number\n\t__ownerID?: any\n\t_map?: any\n\t_list?: any\n\t_origin?: any\n\t_capacity?: any\n\t_defaultValues?: any\n\t_tail?: any\n\t_root?: any\n}\n\n// Interface for Vue reactive objects\ninterface VueReactive {\n\t__v_isReactive: boolean\n\t[key: string]: any\n}\n\n// Interface for Pinia stores\ninterface PiniaStore {\n\t$state?: Record<string, any>\n\t$patch?: (partial: Record<string, any>) => void\n\t$id?: string\n\t[key: string]: any\n}\n\n// Extend global interfaces\ndeclare global {\n\tinterface Window extends RegistryGlobal {}\n\tconst global: RegistryGlobal | undefined\n}\n\n/**\n * Global HST Manager (Singleton)\n * Manages hierarchical state trees and provides access to the global registry.\n *\n * @public\n */\nclass HST {\n\tprivate static instance: HST\n\n\t/**\n\t * Gets the singleton instance of HST\n\t * @returns The HST singleton instance\n\t */\n\tstatic getInstance(): HST {\n\t\tif (!HST.instance) {\n\t\t\tHST.instance = new HST()\n\t\t}\n\t\treturn HST.instance\n\t}\n\n\t/**\n\t * Gets the global registry instance\n\t * @returns The global registry object or undefined if not found\n\t */\n\tgetRegistry(): any {\n\t\t// In test environment, try different ways to access Registry\n\t\t// First, try the global Registry if it exists\n\t\tif (typeof globalThis !== 'undefined') {\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Window interface extended with RegistryGlobal in declare global above; no other way to access globalThis properties\n\t\t\tconst globalRegistry = (globalThis as unknown as RegistryGlobal).Registry?._root\n\t\t\tif (globalRegistry) {\n\t\t\t\treturn globalRegistry\n\t\t\t}\n\t\t}\n\n\t\t// Try to access through window (browser environment)\n\t\tif (typeof window !== 'undefined') {\n\t\t\tconst windowRegistry = window.Registry?._root\n\t\t\tif (windowRegistry) {\n\t\t\t\treturn windowRegistry\n\t\t\t}\n\t\t}\n\n\t\t// Try to access through global (Node environment)\n\t\tif (typeof global !== 'undefined' && global) {\n\t\t\tconst nodeRegistry = global.Registry?._root\n\t\t\tif (nodeRegistry) {\n\t\t\t\treturn nodeRegistry\n\t\t\t}\n\t\t}\n\n\t\t// If we can't find it globally, it might not be set up\n\t\t// This is expected in test environments where Registry is created locally\n\t\treturn undefined\n\t}\n\n\t/**\n\t * Helper method to get doctype metadata from the registry\n\t * @param doctype - The name of the doctype to retrieve metadata for\n\t * @returns The doctype metadata object or undefined if not found\n\t */\n\tgetDoctypeMeta(doctype: string) {\n\t\tconst registry = this.getRegistry()\n\t\tif (registry && typeof registry === 'object' && 'registry' in registry) {\n\t\t\treturn registry.registry[doctype]\n\t\t}\n\t\treturn undefined\n\t}\n}\n\n// Enhanced HST Proxy with tree navigation\nclass HSTProxy implements HSTNode {\n\tprivate target: any\n\tprivate ancestorPath: string\n\tprivate rootNode: HSTNode | null\n\tprivate doctype: string\n\tprivate hst: HST\n\n\tconstructor(target: any, doctype: string, ancestorPath = '', rootNode: HSTNode | null = null) {\n\t\tthis.target = target\n\t\tthis.ancestorPath = ancestorPath\n\t\tthis.rootNode = rootNode || this\n\t\tthis.doctype = doctype\n\t\tthis.hst = HST.getInstance()\n\n\t\treturn new Proxy(this, {\n\t\t\tget(hst, prop) {\n\t\t\t\t// Return HST methods directly\n\t\t\t\tif (prop in hst) return Reflect.get(hst, prop)\n\n\t\t\t\t// Handle property access - return tree nodes for navigation\n\t\t\t\tconst path = String(prop)\n\t\t\t\treturn hst.getNode(path)\n\t\t\t},\n\n\t\t\tset(hst, prop, value) {\n\t\t\t\tconst path = String(prop)\n\t\t\t\thst.set(path, value)\n\t\t\t\treturn true\n\t\t\t},\n\t\t})\n\t}\n\n\tget(path: string): any {\n\t\treturn this.resolveValue(path)\n\t}\n\n\t// Method to get a tree-wrapped node for navigation\n\tgetNode(path: string): HSTNode {\n\t\tconst fullPath = this.resolvePath(path)\n\t\tconst value = this.resolveValue(path)\n\n\t\t// Determine the correct doctype for this node based on the path\n\t\tconst pathSegments = fullPath.split('.')\n\t\tlet nodeDoctype = this.doctype\n\n\t\t// If we're at the root level and this is a StonecropStore, use the first path segment as the doctype\n\t\tif (this.doctype === 'StonecropStore' && pathSegments.length >= 1) {\n\t\t\tnodeDoctype = pathSegments[0]\n\t\t}\n\n\t\t// Always wrap in HSTProxy for tree navigation\n\t\tif (typeof value === 'object' && value !== null && !this.isPrimitive(value)) {\n\t\t\treturn new HSTProxy(value, nodeDoctype, fullPath, this.rootNode)\n\t\t}\n\n\t\t// For primitives, return a minimal wrapper that throws on tree operations\n\t\treturn new HSTProxy(value, nodeDoctype, fullPath, this.rootNode)\n\t}\n\n\tset(path: string, value: any, source: 'user' | 'system' | 'sync' | 'undo' | 'redo' = 'user'): void {\n\t\t// Get current value for change context\n\t\tconst fullPath = this.resolvePath(path)\n\t\tif (fullPath === undefined) {\n\t\t\tconsole.warn('HST.set: resolved path is undefined, skipping operation')\n\t\t\treturn\n\t\t}\n\t\tconst beforeValue = this.has(path) ? this.get(path) : undefined\n\n\t\t// Log operation if not from undo/redo and store is available\n\t\tif (source !== 'undo' && source !== 'redo') {\n\t\t\tconst logStore = getOperationLogStore()\n\t\t\tif (logStore && typeof logStore.addOperation === 'function') {\n\t\t\t\tconst pathSegments = fullPath.split('.')\n\t\t\t\tconst doctype = this.doctype === 'StonecropStore' && pathSegments.length >= 1 ? pathSegments[0] : this.doctype\n\t\t\t\tconst recordId = pathSegments.length >= 2 ? pathSegments[1] : undefined\n\t\t\t\tconst fieldname = pathSegments.slice(2).join('.') || pathSegments[pathSegments.length - 1]\n\n\t\t\t\t// Detect if this is a DELETE operation (setting to undefined when a value existed)\n\t\t\t\tconst isDelete = value === undefined && beforeValue !== undefined\n\t\t\t\tconst operationType: 'set' | 'delete' = isDelete ? 'delete' : 'set'\n\n\t\t\t\tlogStore.addOperation(\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: operationType,\n\t\t\t\t\t\tpath: fullPath,\n\t\t\t\t\t\tfieldname,\n\t\t\t\t\t\tbeforeValue,\n\t\t\t\t\t\tafterValue: value,\n\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\trecordId,\n\t\t\t\t\t\treversible: true, // Default to reversible, can be changed by field triggers\n\t\t\t\t\t},\n\t\t\t\t\tsource\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// Update the value\n\t\tthis.updateValue(path, value)\n\n\t\t// Trigger field actions asynchronously (don't block the set operation)\n\t\tvoid this.triggerFieldActions(fullPath, beforeValue, value)\n\t}\n\n\thas(path: string): boolean {\n\t\ttry {\n\t\t\t// Handle empty path case\n\t\t\tif (path === '') {\n\t\t\t\treturn true // empty path refers to the root object\n\t\t\t}\n\n\t\t\tconst segments = this.parsePath(path)\n\t\t\tlet current = this.target\n\n\t\t\tfor (let i = 0; i < segments.length; i++) {\n\t\t\t\tconst segment = segments[i]\n\n\t\t\t\tif (current === null || current === undefined) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\n\t\t\t\t// Check if this is the last segment\n\t\t\t\tif (i === segments.length - 1) {\n\t\t\t\t\t// For the final property, check if it exists\n\t\t\t\t\tif (this.isImmutable(current)) {\n\t\t\t\t\t\treturn current.has(segment)\n\t\t\t\t\t} else if (this.isPiniaStore(current)) {\n\t\t\t\t\t\treturn (current.$state && segment in current.$state) || segment in current\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn segment in current\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Navigate to the next level\n\t\t\t\tcurrent = this.getProperty(current, segment)\n\t\t\t}\n\n\t\t\treturn false\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Tree navigation methods\n\tgetAncestor(): HSTNode | null {\n\t\tif (!this.ancestorPath) return null\n\n\t\tconst ancestorSegments = this.ancestorPath.split('.').slice(0, -1)\n\t\tconst ancestorPath = ancestorSegments.join('.')\n\n\t\tif (ancestorPath === '') {\n\t\t\treturn this.rootNode\n\t\t}\n\n\t\t// Return a wrapped node, not raw data\n\t\treturn this.rootNode!.getNode(ancestorPath)\n\t}\n\n\tgetRoot(): HSTNode {\n\t\treturn this.rootNode!\n\t}\n\n\tgetPath(): string {\n\t\treturn this.ancestorPath\n\t}\n\n\tgetDepth(): number {\n\t\treturn this.ancestorPath ? this.ancestorPath.split('.').length : 0\n\t}\n\n\tgetBreadcrumbs(): string[] {\n\t\treturn this.ancestorPath ? this.ancestorPath.split('.') : []\n\t}\n\n\t/**\n\t * Trigger an XState transition with optional context data\n\t */\n\tasync triggerTransition(\n\t\ttransition: string,\n\t\tcontext?: { currentState?: string; targetState?: string; fsmContext?: Record<string, any> }\n\t): Promise<any> {\n\t\tconst triggerEngine = getGlobalTriggerEngine()\n\n\t\t// Determine doctype and recordId from the current path\n\t\tconst pathSegments = this.ancestorPath.split('.')\n\t\tlet doctype = this.doctype\n\t\tlet recordId: string | undefined\n\n\t\t// If we're at the root level and this is a StonecropStore, use the first path segment as the doctype\n\t\tif (this.doctype === 'StonecropStore' && pathSegments.length >= 1) {\n\t\t\tdoctype = pathSegments[0]\n\t\t}\n\n\t\t// Extract recordId from path if it follows the expected pattern\n\t\tif (pathSegments.length >= 2) {\n\t\t\trecordId = pathSegments[1]\n\t\t}\n\n\t\t// Build transition context\n\t\tconst transitionContext: TransitionChangeContext = {\n\t\t\tpath: this.ancestorPath,\n\t\t\tfieldname: '', // No specific field for transitions\n\t\t\tbeforeValue: undefined,\n\t\t\tafterValue: undefined,\n\t\t\toperation: 'set',\n\t\t\tdoctype,\n\t\t\trecordId,\n\t\t\ttimestamp: new Date(),\n\t\t\tstore: this.rootNode || undefined,\n\t\t\ttransition,\n\t\t\tcurrentState: context?.currentState,\n\t\t\ttargetState: context?.targetState,\n\t\t\tfsmContext: context?.fsmContext,\n\t\t}\n\n\t\t// Log FSM transition operation\n\t\tconst logStore = getOperationLogStore()\n\t\tif (logStore && typeof logStore.addOperation === 'function') {\n\t\t\tlogStore.addOperation(\n\t\t\t\t{\n\t\t\t\t\ttype: 'transition' as const,\n\t\t\t\t\tpath: this.ancestorPath,\n\t\t\t\t\tfieldname: transition,\n\t\t\t\t\tbeforeValue: context?.currentState,\n\t\t\t\t\tafterValue: context?.targetState,\n\t\t\t\t\tdoctype,\n\t\t\t\t\trecordId,\n\t\t\t\t\treversible: false, // FSM transitions are generally not reversible\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\ttransition,\n\t\t\t\t\t\tcurrentState: context?.currentState,\n\t\t\t\t\t\ttargetState: context?.targetState,\n\t\t\t\t\t\tfsmContext: context?.fsmContext,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t'user'\n\t\t\t)\n\t\t}\n\n\t\t// Execute transition actions\n\t\treturn await triggerEngine.executeTransitionActions(transitionContext)\n\t}\n\n\t// Private helper methods\n\tprivate resolvePath(path: string): string {\n\t\tif (path === '') return this.ancestorPath ?? ''\n\t\treturn this.ancestorPath ? `${this.ancestorPath}.${path}` : path\n\t}\n\n\tprivate resolveValue(path: string): any {\n\t\t// Handle empty path - return the target object\n\t\tif (path === '') {\n\t\t\treturn this.target\n\t\t}\n\n\t\tconst segments = this.parsePath(path)\n\t\tlet current = this.target\n\n\t\tfor (const segment of segments) {\n\t\t\tif (current === null || current === undefined) {\n\t\t\t\treturn undefined\n\t\t\t}\n\n\t\t\tcurrent = this.getProperty(current, segment)\n\t\t}\n\n\t\treturn current\n\t}\n\n\tprivate updateValue(path: string, value: any): void {\n\t\t// Handle empty path case - should throw error\n\t\tif (path === '') {\n\t\t\tthrow new Error('Cannot set value on empty path')\n\t\t}\n\n\t\tconst segments = this.parsePath(path)\n\t\tconst lastSegment = segments.pop()!\n\t\tlet current = this.target\n\n\t\t// Navigate to ancestor object\n\t\tfor (const segment of segments) {\n\t\t\tcurrent = this.getProperty(current, segment)\n\t\t\tif (current === null || current === undefined) {\n\t\t\t\tthrow new Error(`Cannot set property on null/undefined path: ${path}`)\n\t\t\t}\n\t\t}\n\n\t\t// Set the final property\n\t\tthis.setProperty(current, lastSegment, value)\n\t}\n\n\tprivate getProperty(obj: any, key: string): any {\n\t\t// Immutable objects\n\t\tif (this.isImmutable(obj)) {\n\t\t\treturn obj.get(key)\n\t\t}\n\n\t\t// Vue reactive object\n\t\tif (this.isVueReactive(obj)) {\n\t\t\treturn obj[key]\n\t\t}\n\n\t\t// Pinia store\n\t\tif (this.isPiniaStore(obj)) {\n\t\t\treturn obj.$state?.[key] ?? obj[key]\n\t\t}\n\n\t\t// Plain object\n\t\treturn obj[key]\n\t}\n\n\tprivate setProperty(obj: any, key: string, value: any): void {\n\t\t// Immutable objects\n\t\tif (this.isImmutable(obj)) {\n\t\t\tthrow new Error('Cannot directly mutate immutable objects. Use immutable update methods instead.')\n\t\t}\n\n\t\t// Pinia store\n\t\tif (this.isPiniaStore(obj)) {\n\t\t\tif (obj.$patch) {\n\t\t\t\tobj.$patch({ [key]: value })\n\t\t\t} else {\n\t\t\t\tobj[key] = value\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// Vue reactive or plain object\n\t\tobj[key] = value\n\t}\n\n\tprivate async triggerFieldActions(fullPath: string, beforeValue: any, afterValue: any): Promise<void> {\n\t\ttry {\n\t\t\t// Guard against undefined or null fullPath\n\t\t\tif (!fullPath || typeof fullPath !== 'string') {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Skip triggering when the value did not actually change\n\t\t\tif (Object.is(beforeValue, afterValue)) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst pathSegments = fullPath.split('.')\n\n\t\t\t// Only trigger field actions for actual field changes (at least 3 levels deep: doctype.recordId.fieldname)\n\t\t\t// Skip triggering for doctype-level or record-level changes\n\t\t\tif (pathSegments.length < 3) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst triggerEngine = getGlobalTriggerEngine()\n\t\t\tconst fieldname = pathSegments.slice(2).join('.') || pathSegments[pathSegments.length - 1]\n\n\t\t\t// Determine the correct doctype for this path using the same logic as getNode()\n\t\t\t// The path should be in format: \"doctype.recordId.fieldname\"\n\t\t\tlet doctype = this.doctype\n\n\t\t\t// If we're at the root level and this is a StonecropStore, use the first path segment as the doctype\n\t\t\tif (this.doctype === 'StonecropStore' && pathSegments.length >= 1) {\n\t\t\t\tdoctype = pathSegments[0]\n\t\t\t}\n\n\t\t\tlet recordId: string | undefined\n\n\t\t\t// Extract recordId from path if it follows the expected pattern\n\t\t\tif (pathSegments.length >= 2) {\n\t\t\t\trecordId = pathSegments[1]\n\t\t\t}\n\n\t\t\tconst context: FieldChangeContext = {\n\t\t\t\tpath: fullPath,\n\t\t\t\tfieldname,\n\t\t\t\tbeforeValue,\n\t\t\t\tafterValue,\n\t\t\t\toperation: 'set',\n\t\t\t\tdoctype,\n\t\t\t\trecordId,\n\t\t\t\ttimestamp: new Date(),\n\t\t\t\tstore: this.rootNode || undefined, // Pass the root store for snapshot/rollback capabilities\n\t\t\t}\n\n\t\t\tawait triggerEngine.executeFieldTriggers(context)\n\t\t} catch (error) {\n\t\t\t// Silently handle trigger errors to not break the main flow\n\t\t\t// In production, you might want to log this error\n\t\t\tif (error instanceof Error) {\n\t\t\t\tconsole.warn('Field trigger error:', error.message)\n\t\t\t\t// Optional: emit an event or call error handler\n\t\t\t}\n\t\t}\n\t}\n\tprivate isVueReactive(obj: any): obj is VueReactive {\n\t\treturn obj && typeof obj === 'object' && '__v_isReactive' in obj && obj.__v_isReactive === true\n\t}\n\n\tprivate isPiniaStore(obj: any): obj is PiniaStore {\n\t\treturn obj && typeof obj === 'object' && ('$state' in obj || '$patch' in obj || '$id' in obj)\n\t}\n\n\tprivate isImmutable(obj: any): obj is ImmutableLike {\n\t\tif (!obj || typeof obj !== 'object') {\n\t\t\treturn false\n\t\t}\n\n\t\tconst hasGetMethod = 'get' in obj && typeof obj.get === 'function'\n\t\tconst hasSetMethod = 'set' in obj && typeof obj.set === 'function'\n\t\tconst hasHasMethod = 'has' in obj && typeof obj.has === 'function'\n\n\t\tconst hasImmutableMarkers =\n\t\t\t'__ownerID' in obj ||\n\t\t\t'_map' in obj ||\n\t\t\t'_list' in obj ||\n\t\t\t'_origin' in obj ||\n\t\t\t'_capacity' in obj ||\n\t\t\t'_defaultValues' in obj ||\n\t\t\t'_tail' in obj ||\n\t\t\t'_root' in obj ||\n\t\t\t('size' in obj && hasGetMethod && hasSetMethod)\n\n\t\tlet constructorName: string | undefined\n\t\ttry {\n\t\t\tif ('constructor' in obj && obj.constructor && typeof obj.constructor === 'object' && 'name' in obj.constructor) {\n\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- obj.constructor.name accessed after 'name' in check; obj is any throughout this method\n\t\t\t\tconst nameValue = (obj.constructor as { name: unknown }).name\n\t\t\t\tconstructorName = typeof nameValue === 'string' ? nameValue : undefined\n\t\t\t}\n\t\t} catch {\n\t\t\tconstructorName = undefined\n\t\t}\n\n\t\tconst isImmutableConstructor =\n\t\t\tconstructorName &&\n\t\t\t(constructorName.includes('Map') ||\n\t\t\t\tconstructorName.includes('List') ||\n\t\t\t\tconstructorName.includes('Set') ||\n\t\t\t\tconstructorName.includes('Stack') ||\n\t\t\t\tconstructorName.includes('Seq')) &&\n\t\t\t(hasGetMethod || hasSetMethod)\n\n\t\treturn Boolean(\n\t\t\t(hasGetMethod && hasSetMethod && hasHasMethod && hasImmutableMarkers) ||\n\t\t\t(hasGetMethod && hasSetMethod && isImmutableConstructor)\n\t\t)\n\t}\n\n\tprivate isPrimitive(value: any): boolean {\n\t\t// Don't wrap primitive values, functions, or null/undefined\n\t\treturn (\n\t\t\tvalue === null ||\n\t\t\tvalue === undefined ||\n\t\t\ttypeof value === 'string' ||\n\t\t\ttypeof value === 'number' ||\n\t\t\ttypeof value === 'boolean' ||\n\t\t\ttypeof value === 'function' ||\n\t\t\ttypeof value === 'symbol' ||\n\t\t\ttypeof value === 'bigint'\n\t\t)\n\t}\n\n\t/**\n\t * Parse a path string into segments, handling both dot notation and array bracket notation\n\t * @param path - The path string to parse (e.g., \"order.456.line_items[0].product\")\n\t * @returns Array of path segments (e.g., ['order', '456', 'line_items', '0', 'product'])\n\t */\n\tprivate parsePath(path: string): string[] {\n\t\tif (!path) return []\n\n\t\t// Replace array bracket notation with dot notation\n\t\t// items[0] → items.0\n\t\t// items[0][1] → items.0.1\n\t\tconst normalizedPath = path.replace(/\\[(\\d+)\\]/g, '.$1')\n\n\t\treturn normalizedPath.split('.').filter(segment => segment.length > 0)\n\t}\n}\n\n/**\n * Factory function for HST creation\n * Creates a new HSTNode proxy for hierarchical state tree navigation.\n *\n * @param target - The target object to wrap with HST functionality\n * @param doctype - The document type identifier\n * @returns A new HSTNode proxy instance\n *\n * @public\n */\nfunction createHST(target: any, doctype: string): HSTNode {\n\treturn new HSTProxy(target, doctype, '', null)\n}\n\n// Export everything\nexport { HSTProxy, HST, createHST, type HSTNode }\n","import type { DataClient, GetRecordOptions, GetRecordsOptions, GetRecordsResult } from '@stonecrop/schema'\nimport { reactive } from 'vue'\n\nimport Doctype from './doctype'\nimport { isDraftRecordId } from './draft'\nimport Registry from './registry'\nimport { createHST, type HSTNode } from './stores/hst'\nimport { useOperationLogStore } from './stores/operation-log'\nimport type { OperationLogConfig } from './types/operation-log'\nimport type { RouteContext } from './types/registry'\nimport type { PageInfo, StonecropOptions } from './types/stonecrop'\n\n/**\n * Main Stonecrop class with HST integration and built-in Operation Log\n * @public\n */\nexport class Stonecrop {\n\t/**\n\t * Singleton instance of Stonecrop. Only one Stonecrop instance can exist\n\t * per application, ensuring consistent HST state and registry access.\n\t * Subsequent constructor calls return this instance instead of creating new ones.\n\t * @internal\n\t */\n\tstatic _root: Stonecrop\n\n\t/** The HST store instance for reactive state management */\n\tprivate hstStore!: HSTNode\n\tprivate _operationLogStore?: ReturnType<typeof useOperationLogStore>\n\tprivate _operationLogConfig?: Partial<OperationLogConfig>\n\tprivate _client?: DataClient\n\n\t/**\n\t * Per-doctype page info from the last list read, keyed by slug. Reactive so views tracking\n\t * it update on fetch. Deliberately not in HST — see {@link Stonecrop.getRecords}.\n\t */\n\tprivate pageInfo: Record<string, PageInfo> = reactive({})\n\n\t/** The registry instance containing all doctype definitions */\n\treadonly registry!: Registry\n\n\t/**\n\t * Creates a new Stonecrop instance with HST integration (singleton pattern)\n\t * @param registry - The Registry instance containing doctype definitions\n\t * @param operationLogConfig - Optional configuration for the operation log\n\t * @param options - Options including the data client (can be set later via setClient)\n\t */\n\tconstructor(registry: Registry, operationLogConfig?: Partial<OperationLogConfig>, options?: StonecropOptions) {\n\t\tif (Stonecrop._root) {\n\t\t\treturn Stonecrop._root\n\t\t}\n\t\tStonecrop._root = this\n\n\t\tthis.registry = registry\n\n\t\t// Store config for lazy initialization\n\t\tthis._operationLogConfig = operationLogConfig\n\n\t\t// Store data client (can be set later via setClient)\n\t\tthis._client = options?.client\n\n\t\t// Initialize HST store with auto-sync to Registry\n\t\tthis.initializeHSTStore()\n\t\tthis.setupRegistrySync()\n\t\treturn this\n\t}\n\n\t/**\n\t * Set the data client for fetching doctype metadata and records.\n\t * Use this for deferred configuration in Nuxt/Vue plugin setups.\n\t *\n\t * @param client - DataClient implementation (e.g., StonecropClient from \\@stonecrop/graphql-client)\n\t *\n\t * @example\n\t * ```ts\n\t * const { setClient } = useStonecropRegistry()\n\t * const client = new StonecropClient({ endpoint: '/graphql' })\n\t * setClient(client)\n\t * ```\n\t */\n\tsetClient(client: DataClient): void {\n\t\tthis._client = client\n\t}\n\n\t/**\n\t * Get the current data client\n\t * @returns The DataClient instance or undefined if not set\n\t */\n\tgetClient(): DataClient | undefined {\n\t\treturn this._client\n\t}\n\n\t/**\n\t * Get the operation log store (lazy initialization)\n\t * @internal\n\t */\n\tgetOperationLogStore() {\n\t\tif (!this._operationLogStore) {\n\t\t\tthis._operationLogStore = useOperationLogStore()\n\t\t\tif (this._operationLogConfig) {\n\t\t\t\tthis._operationLogStore.configure(this._operationLogConfig)\n\t\t\t}\n\t\t}\n\t\treturn this._operationLogStore\n\t}\n\n\t/**\n\t * Initialize the HST store structure\n\t */\n\tprivate initializeHSTStore(): void {\n\t\tconst initialStoreStructure: Record<string, any> = {}\n\n\t\t// Auto-populate from existing Registry doctypes\n\t\tObject.keys(this.registry.registry).forEach(doctypeSlug => {\n\t\t\tinitialStoreStructure[doctypeSlug] = {}\n\t\t})\n\n\t\t// Wrap the store in Vue's reactive() for automatic change detection\n\t\t// This enables Vue computed properties to track HST store changes\n\t\tthis.hstStore = createHST(reactive(initialStoreStructure), 'StonecropStore')\n\t}\n\n\t/**\n\t * Setup automatic sync with Registry when doctypes are added\n\t */\n\tprivate setupRegistrySync(): void {\n\t\t// Extend Registry.addDoctype to auto-create HST store sections\n\t\tconst originalAddDoctype = this.registry.addDoctype.bind(this.registry)\n\n\t\tthis.registry.addDoctype = (doctype: Doctype) => {\n\t\t\t// Call original method\n\t\t\toriginalAddDoctype(doctype)\n\n\t\t\t// Auto-create HST store section for new doctype\n\t\t\tif (!this.hstStore.has(doctype.slug)) {\n\t\t\t\tthis.hstStore.set(doctype.slug, {})\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Get records hash for a doctype\n\t * @param doctype - The doctype to get records for\n\t * @returns HST node containing records hash\n\t */\n\trecords(doctype: string | Doctype): HSTNode {\n\t\tconst slug = typeof doctype === 'string' ? doctype : doctype.slug\n\t\tthis.ensureDoctypeExists(slug)\n\t\treturn this.hstStore.getNode(slug)\n\t}\n\n\t/**\n\t * Add a record to the store\n\t * @param doctype - The doctype\n\t * @param recordId - The record ID\n\t * @param recordData - The record data\n\t */\n\taddRecord(doctype: string | Doctype, recordId: string, recordData: any): void {\n\t\tconst slug = typeof doctype === 'string' ? doctype : doctype.slug\n\n\t\tthis.ensureDoctypeExists(slug)\n\n\t\t// Store raw record data - let HST handle wrapping with proper hierarchy\n\t\tthis.hstStore.set(`${slug}.${recordId}`, recordData)\n\t}\n\n\t/**\n\t * Get a specific record\n\t * @param doctype - The doctype\n\t * @param recordId - The record ID\n\t * @returns HST node for the record or undefined\n\t */\n\tgetRecordById(doctype: string | Doctype, recordId: string): HSTNode | undefined {\n\t\tconst slug = typeof doctype === 'string' ? doctype : doctype.slug\n\t\tthis.ensureDoctypeExists(slug)\n\n\t\t// First check if the record exists\n\t\tconst recordExists = this.hstStore.has(`${slug}.${recordId}`)\n\t\tif (!recordExists) {\n\t\t\treturn undefined\n\t\t}\n\n\t\t// Check if the actual value is undefined (i.e., record was removed)\n\t\tconst recordValue = this.hstStore.get(`${slug}.${recordId}`)\n\t\tif (recordValue === undefined) {\n\t\t\treturn undefined\n\t\t}\n\n\t\t// Use getNode to get the properly wrapped HST node with correct ancestor relationships\n\t\treturn this.hstStore.getNode(`${slug}.${recordId}`)\n\t}\n\n\t/**\n\t * Remove a record from the store\n\t * @param doctype - The doctype\n\t * @param recordId - The record ID\n\t */\n\tremoveRecord(doctype: string | Doctype, recordId: string): void {\n\t\tconst slug = typeof doctype === 'string' ? doctype : doctype.slug\n\t\tthis.ensureDoctypeExists(slug)\n\n\t\t// Remove the specific record directly by setting to undefined\n\t\tif (this.hstStore.has(`${slug}.${recordId}`)) {\n\t\t\tthis.hstStore.set(`${slug}.${recordId}`, undefined)\n\t\t}\n\t}\n\n\t/**\n\t * Get all record IDs for a doctype\n\t * @param doctype - The doctype\n\t * @returns Array of record IDs\n\t */\n\tgetRecordIds(doctype: string | Doctype): string[] {\n\t\tconst slug = typeof doctype === 'string' ? doctype : doctype.slug\n\t\tthis.ensureDoctypeExists(slug)\n\n\t\tconst doctypeNode = this.hstStore.get(slug)\n\t\tif (!doctypeNode || typeof doctypeNode !== 'object') {\n\t\t\treturn []\n\t\t}\n\n\t\treturn Object.keys(doctypeNode).filter(key => doctypeNode[key] !== undefined)\n\t}\n\n\t/**\n\t * Clear all records for a doctype\n\t * @param doctype - The doctype\n\t */\n\tclearRecords(doctype: string | Doctype): void {\n\t\tconst slug = typeof doctype === 'string' ? doctype : doctype.slug\n\t\tthis.ensureDoctypeExists(slug)\n\n\t\t// Get all record IDs and remove them\n\t\tconst recordIds = this.getRecordIds(slug)\n\t\trecordIds.forEach(recordId => {\n\t\t\tthis.hstStore.set(`${slug}.${recordId}`, undefined)\n\t\t})\n\t}\n\n\t/**\n\t * Setup method for doctype initialization\n\t * @param doctype - The doctype to setup\n\t */\n\tsetup(doctype: Doctype): void {\n\t\t// Ensure doctype exists in store\n\t\tthis.ensureDoctypeExists(doctype.slug)\n\t}\n\n\t/**\n\t * Get the effective blockWorkflows value for a link.\n\t * Returns true if blockWorkflows is explicitly true, or if it's absent and fetch method is 'sync'.\n\t * @param link - The link declaration\n\t * @returns Whether workflows should be blocked until this link is loaded\n\t */\n\tprivate getEffectiveBlockWorkflows(link: { blockWorkflows?: boolean; fetch?: { method?: string } }): boolean {\n\t\tif (link.blockWorkflows !== undefined) {\n\t\t\treturn link.blockWorkflows\n\t\t}\n\t\t// TODO: For custom fetch handlers, this returns false (not blocking), but the custom handler\n\t\t// may still be invoked by useLazyLink. Future: custom handlers should be able to declare they\n\t\t// satisfy blockWorkflows, or validation should reject custom + blockWorkflows: true.\n\t\treturn link.fetch?.method === 'sync'\n\t}\n\n\t/**\n\t * Check if workflow actions are ready to run (all required link data is loaded).\n\t * A link's data is considered loaded if it exists in HST at `slug.recordId.linkname`.\n\t * @param doctype - The doctype to check\n\t * @param recordId - The record ID\n\t * @returns Object with `ready: true` if all blocked links are loaded, or `ready: false` with `blockedLinks` array\n\t */\n\tisWorkflowReady(doctype: Doctype, recordId: string): { ready: boolean; blockedLinks?: string[] } {\n\t\t// New records don't block workflows - they haven't been saved yet\n\t\tif (isDraftRecordId(recordId)) {\n\t\t\treturn { ready: true }\n\t\t}\n\n\t\tconst links = this.registry.getDescendantLinks(doctype.slug)\n\t\tconst blockedLinks: string[] = []\n\n\t\tfor (const link of links) {\n\t\t\tif (this.getEffectiveBlockWorkflows(link)) {\n\t\t\t\tconst linkPath = `${doctype.slug}.${recordId}.${link.fieldname}`\n\t\t\t\tif (!this.hstStore.has(linkPath)) {\n\t\t\t\t\tblockedLinks.push(link.fieldname)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (blockedLinks.length > 0) {\n\t\t\treturn { ready: false, blockedLinks }\n\t\t}\n\t\treturn { ready: true }\n\t}\n\n\t/**\n\t * Fetch a doctype's records from the server and store them in HST.\n\t *\n\t * This is the one read path for a list. Every caller shares its keying rule, so a row is\n\t * always stored under the identity its Edit link will later ask for.\n\t *\n\t * Deliberately unguarded, unlike {@link Stonecrop.getRecord}: a list is a view of data that\n\t * changes, so revisiting one must re-read it rather than serve whatever HST happens to hold.\n\t *\n\t * `options` is forwarded to the client untouched — no row limit is invented here, because\n\t * nothing on this side of the wire knows what is safe for an arbitrary backend. A caller that\n\t * passes none gets whatever the server considers a reasonable page.\n\t *\n\t * `options.offset === 0` (or omitted) replaces the doctype's HST records; `offset > 0` appends.\n\t *\n\t * @param doctype - The doctype\n\t * @param options - Query options (filters, orderBy, limit, offset), forwarded to the client\n\t * @throws Error if no data client has been configured\n\t * @public\n\t */\n\tasync getRecords(doctype: Doctype, options?: GetRecordsOptions): Promise<GetRecordsResult> {\n\t\tif (!this._client) {\n\t\t\tthrow new Error(\n\t\t\t\t'No data client configured. Call setClient() with a DataClient implementation ' +\n\t\t\t\t\t'(e.g., StonecropClient from @stonecrop/graphql-client) before fetching records.'\n\t\t\t)\n\t\t}\n\n\t\tconst result = await this._client.getRecords(doctype, options)\n\t\tconst records = result.data\n\t\tconst offset = options?.offset ?? 0\n\n\t\t// Page info is kept beside HST, not in it. `getRecordIds` reads the raw keys under a\n\t\t// doctype node, so anything filed there becomes a phantom record — the same hazard that\n\t\t// ruled out seeding a draft node.\n\t\tconst pageEntry: PageInfo = {\n\t\t\thasMore: result.hasMore,\n\t\t\toffset,\n\t\t\tlimit: records.length,\n\t\t}\n\t\tif (result.count != null) {\n\t\t\tpageEntry.count = result.count\n\t\t}\n\t\tthis.pageInfo[doctype.slug] = pageEntry\n\n\t\t// offset === 0 replaces the doctype's HST records; offset > 0 appends. A failed fetch\n\t\t// must not clear — that happens only after a successful response lands above.\n\t\tif (offset === 0) {\n\t\t\tthis.clearRecords(doctype)\n\t\t}\n\n\t\t// Key each record by its declared primary key, falling back to `id`. This used to read\n\t\t// `record.id` only, which silently dropped every row of a natural-keyed doctype (no `id`\n\t\t// column at all) — the records never entered HST, so the list rendered empty and no\n\t\t// downstream id-resolution could recover them.\n\t\trecords.forEach(record => {\n\t\t\tconst recordId = doctype.getRecordId(record)\n\t\t\tif (recordId !== undefined) {\n\t\t\t\tthis.addRecord(doctype, recordId, record)\n\t\t\t}\n\t\t})\n\n\t\treturn result\n\t}\n\n\t/**\n\t * What the last {@link Stonecrop.getRecords} for this doctype returned about the wider set.\n\t *\n\t * Answers the question HST cannot: HST holds what was fetched, so counting its keys reports\n\t * how much has been seen, never how much exists. Reactive, so a view reading it re-renders\n\t * when a fetch lands.\n\t *\n\t * @param doctype - The doctype slug string or Doctype object\n\t * @returns Page info, or undefined if this doctype's records have not been fetched\n\t * @public\n\t */\n\tgetPageInfo(doctype: string | Doctype): PageInfo | undefined {\n\t\tconst slug = typeof doctype === 'string' ? doctype : doctype.slug\n\t\treturn this.pageInfo[slug]\n\t}\n\n\t/**\n\t * Fetch a single record from the server and store it in HST.\n\t *\n\t * This is the one read path for a record, and it owns the whole job: deciding whether a fetch\n\t * is warranted, performing it, and writing the result back under the doctype's declared\n\t * identity. Callers ask for a record and get one; they do not re-derive when to ask.\n\t *\n\t * Two cases return without touching the network, because in both the answer is already known:\n\t * a draft does not exist on the server yet, and a record already in HST has been read.\n\t * Refetching the latter would also discard unsaved edits sitting in the store.\n\t *\n\t * @param doctype - The doctype slug string or Doctype object\n\t * @param recordId - The record ID\n\t * @param options - Query options (includeNested, maxDepth), forwarded to the client\n\t * @throws Error if no data client has been configured\n\t * @throws Error if a slug string is given and no matching doctype is found in the registry\n\t * @public\n\t */\n\tasync getRecord(doctype: string | Doctype, recordId: string, options?: GetRecordOptions): Promise<void> {\n\t\tif (!this._client) {\n\t\t\tthrow new Error(\n\t\t\t\t'No data client configured. Call setClient() with a DataClient implementation ' +\n\t\t\t\t\t'(e.g., StonecropClient from @stonecrop/graphql-client) before fetching records.'\n\t\t\t)\n\t\t}\n\n\t\tconst resolved = typeof doctype === 'string' ? this.registry.getDoctype(doctype) : doctype\n\t\tif (!resolved) {\n\t\t\tthrow new Error(`Doctype not found: ${typeof doctype === 'string' ? doctype : doctype.slug}`)\n\t\t}\n\n\t\t// An unsaved draft has no server record, so a fetch could only ever miss. This guard used\n\t\t// to live in every host, which is how the private draft-id scheme leaked into all of them.\n\t\tif (isDraftRecordId(recordId)) {\n\t\t\treturn\n\t\t}\n\n\t\tif (this.getRecordById(resolved.slug, recordId)) {\n\t\t\treturn\n\t\t}\n\n\t\tconst result = await this._client.getRecord(resolved, recordId, options)\n\n\t\tif (result?.record) {\n\t\t\tthis.addRecord(resolved, recordId, result.record)\n\t\t}\n\t}\n\n\t/**\n\t * Dispatch an action to the server via the configured data client, and file the record it\n\t * returns into HST under the identity the *server* settled on.\n\t *\n\t * The write is the point. For a created record the settled identity is never the one that was\n\t * dispatched, so a caller that stores the result under the id it sent files the record under a\n\t * key nothing can fetch and leaves the next save creating a second one. Every host that\n\t * hand-rolled this got it wrong the same way, so it stops being the caller's job — this is the\n\t * write-side twin of {@link Stonecrop.getRecords}, which keys reads by the same rule.\n\t *\n\t * Two things are deliberately NOT done here, because both need the id that was dispatched and\n\t * that lives inside `args` — an opaque array whose shape is a convention between a host's\n\t * client and its server handlers, not something this layer may parse. Dropping the stale key\n\t * and moving the route therefore stay with `useClientAction`, which knows both ids.\n\t *\n\t * A result that states no identity of its own — a `{ state: 'APPROVED' }` outcome — is left\n\t * alone rather than guessed at, for the same reason `settledRecordId` is strict: a partial\n\t * record must not be able to look like a rename.\n\t *\n\t * @param doctype - The doctype\n\t * @param action - Action name to execute (e.g., 'SUBMIT', 'APPROVE', 'save')\n\t * @param args - Action arguments (typically record ID and/or form data)\n\t * @returns Action result with success status, response data, and any error\n\t * @throws Error if no data client has been configured\n\t */\n\tasync dispatchAction(\n\t\tdoctype: Doctype,\n\t\taction: string,\n\t\targs?: unknown[]\n\t): Promise<{ success: boolean; data: unknown; error: string | null }> {\n\t\tif (!this._client) {\n\t\t\tthrow new Error(\n\t\t\t\t'No data client configured. Call setClient() with a DataClient implementation ' +\n\t\t\t\t\t'(e.g., StonecropClient from @stonecrop/graphql-client) before dispatching actions.'\n\t\t\t)\n\t\t}\n\n\t\tconst result = await this._client.runAction(doctype, action, args)\n\n\t\tif (result.success && result.data && typeof result.data === 'object' && !Array.isArray(result.data)) {\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the guard above confirms a non-null, non-array object; the action result payload is an opaque JSON scalar\n\t\t\tconst record = result.data as Record<string, unknown>\n\t\t\t// Require the declared key to be *present* before trusting `getRecordId`, which falls\n\t\t\t// back to `id`. Without that, a handler returning `{ id, total }` for a natural-keyed\n\t\t\t// doctype would relocate the record to a key the adapter cannot look up.\n\t\t\tif (record[doctype.recordIdField] !== undefined) {\n\t\t\t\tconst settledId = doctype.getRecordId(record)\n\t\t\t\tif (settledId !== undefined) {\n\t\t\t\t\tthis.addRecord(doctype, settledId, record)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result\n\t}\n\n\t/**\n\t * Ensure doctype section exists in HST store\n\t * @param slug - The doctype slug\n\t */\n\tprivate ensureDoctypeExists(slug: string): void {\n\t\tif (!this.hstStore.has(slug)) {\n\t\t\tthis.hstStore.set(slug, {})\n\t\t}\n\t}\n\n\t/**\n\t * Get doctype metadata from the registry\n\t * @param context - The route context\n\t * @returns The doctype metadata\n\t */\n\tasync getMeta(context: RouteContext): Promise<any> {\n\t\tif (!this.registry.getMeta) {\n\t\t\tthrow new Error('No getMeta function provided to Registry')\n\t\t}\n\t\treturn await this.registry.getMeta(context)\n\t}\n\n\t/**\n\t * Get the root HST store node for advanced usage\n\t * @returns Root HST node\n\t */\n\tgetStore(): HSTNode {\n\t\treturn this.hstStore\n\t}\n\n\t/**\n\t * Determine the current workflow state for a record.\n\t *\n\t * Reads the record's `status` field from the HST store. If the field is absent or\n\t * empty the doctype's declared `workflow.initial` state is used as the fallback,\n\t * giving callers a reliable state name without having to duplicate that logic.\n\t *\n\t * @param doctype - The doctype slug or Doctype instance\n\t * @param recordId - The record identifier\n\t * @returns The current state name, or an empty string if the doctype has no workflow\n\t *\n\t * @public\n\t */\n\tgetRecordState(doctype: string | Doctype, recordId: string): string {\n\t\tconst slug = typeof doctype === 'string' ? doctype : doctype.slug\n\t\tconst meta = this.registry.getDoctype(slug)\n\t\tif (!meta?.workflow) return ''\n\n\t\tconst record = this.getRecordById(slug, recordId)\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- HSTNode.get returns any; status is always string in workflow records\n\t\tconst status = record?.get('status') as string | undefined\n\n\t\t// Handle both XState format and WorkflowMeta format\n\t\tconst workflow = meta.workflow\n\t\tlet initialState: string\n\n\t\tif (Array.isArray(workflow.states)) {\n\t\t\t// WorkflowMeta format: states is a string array\n\t\t\tinitialState = workflow.states[0] ?? ''\n\t\t} else {\n\t\t\t// XState format: states is an object, use initial or first key\n\t\t\t// oxlint-disable typescript/no-unsafe-type-assertion -- XState MachineConfig has `initial` but type union doesn't expose it; runtime-guarded by typeof check\n\t\t\tinitialState =\n\t\t\t\ttypeof (workflow as { initial?: unknown }).initial === 'string'\n\t\t\t\t\t? (workflow as { initial: string }).initial\n\t\t\t\t\t: (Object.keys(workflow.states ?? {})[0] ?? '')\n\t\t\t// oxlint-enable typescript/no-unsafe-type-assertion\n\t\t}\n\n\t\treturn status || initialState\n\t}\n\n\t/**\n\t * Collect a record payload with all nested doctype fields from HST\n\t * @param doctype - The doctype metadata\n\t * @param recordId - The record ID to collect\n\t * @returns The complete record payload ready for API submission\n\t * @public\n\t */\n\tcollectRecordPayload(doctype: Doctype, recordId: string): Record<string, any> {\n\t\tconst recordPath = `${doctype.slug}.${recordId}`\n\t\tconst recordData = this.hstStore.get(recordPath) || {}\n\n\t\tconst payload: Record<string, any> = { ...recordData }\n\n\t\t// Collect nested data from links\n\t\tif (doctype.links) {\n\t\t\tfor (const [fieldname, link] of Object.entries(doctype.links)) {\n\t\t\t\tconst fieldPath = `${recordPath}.${fieldname}`\n\t\t\t\tconst isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne'\n\n\t\t\t\tif (isMany) {\n\t\t\t\t\tconst arrayData = this.hstStore.get(fieldPath)\n\t\t\t\t\tif (Array.isArray(arrayData)) {\n\t\t\t\t\t\tpayload[fieldname] = arrayData\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst targetDoctype = this.registry.getDoctype(link.target)\n\t\t\t\t\tif (targetDoctype?.links) {\n\t\t\t\t\t\tpayload[fieldname] = this.collectNestedData(fieldPath, targetDoctype)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpayload[fieldname] = this.hstStore.get(fieldPath) || {}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// The store's shape, inline links included. Reducing them to what a column takes is the\n\t\t// adapter's job at dispatch — storage is behind the API.\n\t\treturn payload\n\t}\n\n\t/**\n\t * Scaffold empty descendant records from defaults for all descendant links.\n\t *\n\t * Initializes all scalar and link fields at their HST paths with default values.\n\t * For new records, call this after setting up the doctype to ensure all paths exist.\n\t *\n\t * @param path - HST path (e.g., \"customer.new\")\n\t * @param doctype - The doctype to initialize\n\t * @public\n\t */\n\tinitializeNestedData(path: string, doctype: Doctype): void {\n\t\tconst slug = doctype.slug\n\t\tthis.ensureDoctypeExists(slug)\n\n\t\t// Resolve schema and initialize with defaults\n\t\tconst resolvedSchema = this.registry.resolveSchema(doctype)\n\t\tconst record = this.registry.initializeRecord(resolvedSchema)\n\n\t\t// Ensure the ancestor path exists in HST before setting descendant fields\n\t\tconst existingData = this.hstStore.get(path)\n\t\tif (!existingData) {\n\t\t\tthis.hstStore.set(path, {}, 'system')\n\t\t}\n\n\t\t// Store each field at its own HST path\n\t\tfor (const [key, value] of Object.entries(record)) {\n\t\t\tthis.hstStore.set(`${path}.${key}`, value, 'system')\n\t\t}\n\t}\n\n\t/**\n\t * Fetch a record and its nested data from the server.\n\t *\n\t * Calls `_client.getRecord()` with nested sub-selections and stores each scalar field at its own HST path\n\t * (`slug.recordId.fieldname`), descendants at the link-level path (`slug.recordId.linkname`).\n\t *\n\t * @param path - HST path (e.g., \"recipe.r1\")\n\t * @param doctype - The doctype to fetch\n\t * @param recordId - Record ID to fetch\n\t * @param options - Query options (includeNested to control which links are fetched)\n\t * @throws Error with code `\"CLIENT_REQUIRED\"` if no data client is configured\n\t * @throws Error with code `\"RECORD_NOT_FOUND\"` if the server returns null\n\t * @public\n\t */\n\tasync fetchNestedData(\n\t\tpath: string,\n\t\tdoctype: Doctype,\n\t\trecordId: string,\n\t\toptions?: { includeNested?: boolean | string[] }\n\t): Promise<void> {\n\t\tif (!this._client) {\n\t\t\tthrow createCodedError(\n\t\t\t\t'No data client configured. Call setClient() with a DataClient implementation ' +\n\t\t\t\t\t'(e.g., StonecropClient from @stonecrop/graphql-client) before fetching records.',\n\t\t\t\t'CLIENT_REQUIRED'\n\t\t\t)\n\t\t}\n\n\t\tconst result = await this._client.getRecord({ name: doctype.doctype }, recordId, {\n\t\t\tincludeNested: options?.includeNested ?? true,\n\t\t})\n\n\t\tif (!result?.record) {\n\t\t\tthrow createCodedError(`Record not found: ${doctype.doctype} ${recordId}`, 'RECORD_NOT_FOUND')\n\t\t}\n\n\t\t// Store each scalar field at its own HST path, descendants at link-level path\n\t\tconst slug = doctype.slug\n\t\tthis.ensureDoctypeExists(slug)\n\n\t\t// Ensure the ancestor path exists in HST before setting descendant fields\n\t\tconst existingData = this.hstStore.get(`${slug}.${recordId}`)\n\t\tif (!existingData) {\n\t\t\tthis.hstStore.set(`${slug}.${recordId}`, {}, 'system')\n\t\t}\n\n\t\tfor (const [key, value] of Object.entries(result.record)) {\n\t\t\tthis.hstStore.set(`${slug}.${recordId}.${key}`, value, 'system')\n\t\t}\n\t}\n\n\t/**\n\t * Recursively collect nested data from HST\n\t * @param basePath - The base path in HST (e.g., \"customer.123.address\")\n\t * @param doctype - The doctype whose links drive the recursive traversal\n\t * @returns The collected data object\n\t */\n\tprivate collectNestedData(basePath: string, doctype: Doctype): Record<string, any> {\n\t\tconst data = this.hstStore.get(basePath) || {}\n\t\tconst payload: Record<string, any> = { ...data }\n\n\t\tif (!doctype.links) return payload\n\n\t\tfor (const [fieldname, link] of Object.entries(doctype.links)) {\n\t\t\tconst fieldPath = `${basePath}.${fieldname}`\n\t\t\tconst isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne'\n\n\t\t\tif (isMany) {\n\t\t\t\tconst arrayData = this.hstStore.get(fieldPath)\n\t\t\t\tif (Array.isArray(arrayData)) {\n\t\t\t\t\tpayload[fieldname] = arrayData\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst targetDoctype = this.registry.getDoctype(link.target)\n\t\t\t\tif (targetDoctype?.links) {\n\t\t\t\t\tpayload[fieldname] = this.collectNestedData(fieldPath, targetDoctype)\n\t\t\t\t} else {\n\t\t\t\t\tpayload[fieldname] = this.hstStore.get(fieldPath) || {}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn payload\n\t}\n}\n\n/**\n * Create an Error with a `code` property for programmatic error handling.\n * @internal\n */\ninterface CodedError extends Error {\n\tcode: string\n}\n\nfunction createCodedError(message: string, code: string): CodedError {\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- extending Error with code property; CodedError cast is the standard pattern for typed error objects\n\tconst error = new Error(message) as CodedError\n\terror.code = code\n\treturn error\n}\n","import { type ResolvedField } from '@stonecrop/aform'\nimport { storeToRefs } from 'pinia'\nimport { inject, onMounted, Ref, ref, watch, provide, computed } from 'vue'\n\nimport Doctype from '../doctype'\nimport { isDraftRecordId } from '../draft'\nimport Registry from '../registry'\nimport { Stonecrop } from '../stonecrop'\nimport type { HSTNode } from '../types/hst'\nimport type { BaseStonecropReturn, HSTStonecropReturn, HSTChangeData, OperationLogAPI } from '../types/composable'\nimport type { HSTOperation, OperationLogConfig } from '../types/operation-log'\nimport type { RouteContext } from '../types/registry'\n\n/**\n * Unified Stonecrop composable - handles both general operations and HST reactive integration.\n *\n * Called with no doctype, it returns the Stonecrop instance and the operation log, and touches\n * the network not at all. Name a doctype to get the HST surface.\n *\n * @returns The Stonecrop instance and the operation log\n * @public\n */\nexport function useStonecrop(): BaseStonecropReturn\n/**\n * Unified Stonecrop composable with HST integration for a specific doctype and record.\n *\n * When a `Doctype` instance is passed, all synchronous initialisation (`hstStore`,\n * `resolvedSchema`, `formData`, `handleHSTChange`, operation-log wiring) is performed\n * during `setup()` — before the first render and without awaiting any lifecycle hook.\n * Callers can read `hstStore.value`, `resolvedSchema.value`, and `formData.value`\n * immediately after calling this composable; no `nextTick`, `flushPromises`, or\n * `setTimeout` is required.\n *\n * The only async work in `onMounted` is fetching an existing record from the server when\n * `recordId` is not a draft, and lazy-loading a doctype by slug string. Both need a doctype\n * named here — nothing is inferred from the route.\n *\n * @param options - Configuration with doctype (string slug or Doctype instance) and optional recordId\n * @returns Stonecrop instance with full HST integration utilities\n * @public\n */\nexport function useStonecrop(options: {\n\tregistry?: Registry\n\tdoctype: Doctype | string\n\trecordId?: string\n}): HSTStonecropReturn\n/**\n * @public\n */\nexport function useStonecrop(options?: {\n\tregistry?: Registry\n\tdoctype?: Doctype | string\n\trecordId?: string\n}): BaseStonecropReturn | HSTStonecropReturn {\n\tif (!options) options = {}\n\n\tconst registry = options.registry || inject<Registry>('$registry')\n\tconst providedStonecrop = inject<Stonecrop>('$stonecrop')\n\tconst stonecrop = ref<Stonecrop | undefined>()\n\tconst hstStore = ref<HSTNode>()\n\tconst formData = ref<Record<string, any>>({})\n\n\t// Resolved schema with nested Doctype fields expanded\n\tconst resolvedSchema = ref<ResolvedField[]>([])\n\n\t// Loading state for lazy-loaded doctypes\n\tconst isLoading = ref(false)\n\tconst error = ref<Error | null>(null)\n\tconst resolvedDoctype = ref<Doctype | undefined>()\n\n\t// Workflow readiness computed properties\n\tconst isWorkflowReady = computed(() => {\n\t\tif (!stonecrop.value || !resolvedDoctype.value || !options.recordId || isDraftRecordId(options.recordId)) {\n\t\t\treturn true\n\t\t}\n\t\tconst status = stonecrop.value.isWorkflowReady(resolvedDoctype.value, options.recordId)\n\t\treturn status.ready\n\t})\n\n\tconst blockedLinks = computed(() => {\n\t\tif (!stonecrop.value || !resolvedDoctype.value || !options.recordId || isDraftRecordId(options.recordId)) {\n\t\t\treturn []\n\t\t}\n\t\tconst status = stonecrop.value.isWorkflowReady(resolvedDoctype.value, options.recordId)\n\t\treturn status.blockedLinks ?? []\n\t})\n\n\t// Initialize stonecrop instance synchronously using singleton pattern\n\t// Use injected instance if available, otherwise fall back to the singleton root\n\tconst stonecropInstance = providedStonecrop || Stonecrop._root\n\tif (stonecropInstance) {\n\t\tstonecrop.value = stonecropInstance\n\t}\n\n\t// If doctype is a Doctype instance (not string), set resolved immediately\n\tif (options?.doctype && typeof options.doctype !== 'string') {\n\t\tresolvedDoctype.value = options.doctype\n\t}\n\n\t// Operation log state and methods\n\tconst operations = ref<HSTOperation[]>([])\n\tconst currentIndex = ref(-1)\n\tconst canUndo = computed(() => stonecrop.value?.getOperationLogStore().canUndo ?? false)\n\tconst canRedo = computed(() => stonecrop.value?.getOperationLogStore().canRedo ?? false)\n\tconst undoCount = computed(() => stonecrop.value?.getOperationLogStore().undoCount ?? 0)\n\tconst redoCount = computed(() => stonecrop.value?.getOperationLogStore().redoCount ?? 0)\n\tconst undoRedoState = computed(\n\t\t() =>\n\t\t\tstonecrop.value?.getOperationLogStore().undoRedoState ?? {\n\t\t\t\tcanUndo: false,\n\t\t\t\tcanRedo: false,\n\t\t\t\tundoCount: 0,\n\t\t\t\tredoCount: 0,\n\t\t\t\tcurrentIndex: -1,\n\t\t\t}\n\t)\n\n\t// Operation log methods\n\tconst undo = (hstNode: HSTNode): boolean => {\n\t\treturn stonecrop.value?.getOperationLogStore().undo(hstNode) ?? false\n\t}\n\n\tconst redo = (hstNode: HSTNode): boolean => {\n\t\treturn stonecrop.value?.getOperationLogStore().redo(hstNode) ?? false\n\t}\n\n\tconst startBatch = () => {\n\t\tstonecrop.value?.getOperationLogStore().startBatch()\n\t}\n\n\tconst commitBatch = (description?: string): string | null => {\n\t\treturn stonecrop.value?.getOperationLogStore().commitBatch(description) ?? null\n\t}\n\n\tconst cancelBatch = () => {\n\t\tstonecrop.value?.getOperationLogStore().cancelBatch()\n\t}\n\n\tconst clear = () => {\n\t\tstonecrop.value?.getOperationLogStore().clear()\n\t}\n\n\tconst getOperationsFor = (doctype: string, recordId?: string) => {\n\t\treturn stonecrop.value?.getOperationLogStore().getOperationsFor(doctype, recordId) ?? []\n\t}\n\n\tconst getSnapshot = () => {\n\t\treturn (\n\t\t\tstonecrop.value?.getOperationLogStore().getSnapshot() ?? {\n\t\t\t\toperations: [],\n\t\t\t\tcurrentIndex: -1,\n\t\t\t\ttotalOperations: 0,\n\t\t\t\treversibleOperations: 0,\n\t\t\t\tirreversibleOperations: 0,\n\t\t\t}\n\t\t)\n\t}\n\n\tconst markIrreversible = (operationId: string, reason: string) => {\n\t\tstonecrop.value?.getOperationLogStore().markIrreversible(operationId, reason)\n\t}\n\n\tconst logAction = (\n\t\tdoctype: string,\n\t\tactionName: string,\n\t\trecordIds?: string[],\n\t\tresult: 'success' | 'failure' | 'pending' = 'success',\n\t\terrorMessage?: string\n\t): string => {\n\t\treturn stonecrop.value?.getOperationLogStore().logAction(doctype, actionName, recordIds, result, errorMessage) ?? ''\n\t}\n\n\tconst configure = (config: Partial<OperationLogConfig>) => {\n\t\tstonecrop.value?.getOperationLogStore().configure(config)\n\t}\n\n\t// Wire operation log reactive state synchronously — no lifecycle hook needed.\n\t// storeToRefs and watch are both safe to call in setup() body.\n\tif (registry && stonecrop.value) {\n\t\ttry {\n\t\t\tconst opLogStore = stonecrop.value.getOperationLogStore()\n\t\t\tconst opLogRefs = storeToRefs(opLogStore)\n\t\t\toperations.value = opLogRefs.operations.value\n\t\t\tcurrentIndex.value = opLogRefs.currentIndex.value\n\n\t\t\t// Watch for changes in operation log state\n\t\t\twatch(\n\t\t\t\t() => opLogRefs.operations.value,\n\t\t\t\tnewOps => {\n\t\t\t\t\toperations.value = newOps\n\t\t\t\t}\n\t\t\t)\n\t\t\twatch(\n\t\t\t\t() => opLogRefs.currentIndex.value,\n\t\t\t\tnewIndex => {\n\t\t\t\t\tcurrentIndex.value = newIndex\n\t\t\t\t}\n\t\t\t)\n\t\t} catch {\n\t\t\t// Pinia not available — operation log is optional, silently skip\n\t\t}\n\t}\n\n\t// Synchronous HST initialisation for an explicit Doctype instance.\n\t// When the caller passes a Doctype object (not a slug string), every piece of\n\t// setup that doesn't require network I/O runs here during setup() so that\n\t// hstStore, resolvedSchema, and formData are populated before the first render\n\t// and are immediately available to callers without any await.\n\tif (options.doctype && typeof options.doctype !== 'string' && registry && stonecrop.value) {\n\t\thstStore.value = stonecrop.value.getStore()\n\t\tresolvedSchema.value = registry.resolveSchema(options.doctype)\n\t\tif (!options.recordId || isDraftRecordId(options.recordId)) {\n\t\t\tformData.value = registry.initializeRecord(resolvedSchema.value)\n\t\t}\n\t\tif (hstStore.value) {\n\t\t\tsetupDeepReactivity(options.doctype, options.recordId || 'new', formData, hstStore.value)\n\t\t}\n\t}\n\n\t// onMounted handles only work that is genuinely async: lazy-loading a doctype by slug and\n\t// fetching an existing record from the server. Both require the caller to name a doctype.\n\t//\n\t// Rejected: inferring the doctype from the route when the caller names none. Every output of\n\t// that inference landed in refs the no-argument callers never read — all of them wanted the\n\t// instance, which is resolved synchronously above — so each paid a getMeta plus a getRecord to\n\t// read a value already in hand. It also lowercased the route's record id, which silently missed\n\t// any natural key carrying uppercase.\n\tonMounted(async () => {\n\t\tif (!registry || !stonecrop.value) {\n\t\t\treturn\n\t\t}\n\n\t\t// Handle HST integration if doctype is provided explicitly\n\t\tif (options.doctype) {\n\t\t\tconst recordId = options.recordId\n\n\t\t\tif (typeof options.doctype === 'string') {\n\t\t\t\t// String doctype — resolve lazily, then do full sync-equivalent setup here.\n\t\t\t\tconst doctypeSlug = options.doctype\n\t\t\t\thstStore.value = stonecrop.value.getStore()\n\t\t\t\tisLoading.value = true\n\t\t\t\terror.value = null\n\n\t\t\t\tlet doctype: Doctype | undefined\n\t\t\t\ttry {\n\t\t\t\t\t// Check if already in registry\n\t\t\t\t\tdoctype = registry.getDoctype(doctypeSlug)\n\n\t\t\t\t\tif (!doctype && registry.getMeta) {\n\t\t\t\t\t\t// Lazy-load via getMeta\n\t\t\t\t\t\tconst routeContext: RouteContext = {\n\t\t\t\t\t\t\tpath: `/${doctypeSlug}`,\n\t\t\t\t\t\t\tsegments: [doctypeSlug],\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdoctype = await registry.getMeta(routeContext)\n\t\t\t\t\t\tif (doctype) {\n\t\t\t\t\t\t\tregistry.addDoctype(doctype)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!doctype) {\n\t\t\t\t\t\terror.value = new Error(`Doctype '${doctypeSlug}' not found in registry and getMeta returned no result`)\n\t\t\t\t\t}\n\t\t\t\t} catch (e) {\n\t\t\t\t\terror.value = e instanceof Error ? e : new Error(String(e))\n\t\t\t\t} finally {\n\t\t\t\t\tisLoading.value = false\n\t\t\t\t}\n\n\t\t\t\tresolvedDoctype.value = doctype\n\t\t\t\tif (!doctype) return\n\n\t\t\t\tresolvedSchema.value = registry.resolveSchema(doctype)\n\n\t\t\t\tif (recordId && !isDraftRecordId(recordId)) {\n\t\t\t\t\tconst existingRecord = stonecrop.value.getRecordById(doctype, recordId)\n\t\t\t\t\tif (existingRecord) {\n\t\t\t\t\t\tformData.value = existingRecord.get('') || {}\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait stonecrop.value.getRecord(doctype, recordId)\n\t\t\t\t\t\t\tconst loadedRecord = stonecrop.value.getRecordById(doctype, recordId)\n\t\t\t\t\t\t\tif (loadedRecord) {\n\t\t\t\t\t\t\t\tformData.value = loadedRecord.get('') || {}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tformData.value = registry.initializeRecord(resolvedSchema.value)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tformData.value = registry.initializeRecord(resolvedSchema.value)\n\t\t\t\t}\n\n\t\t\t\tif (hstStore.value) {\n\t\t\t\t\tsetupDeepReactivity(doctype, recordId || 'new', formData, hstStore.value)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Doctype instance — sync init was done during setup().\n\t\t\t\t// Only handle the async path: fetching an existing record from the server.\n\t\t\t\tif (recordId && !isDraftRecordId(recordId)) {\n\t\t\t\t\tconst doctype = options.doctype\n\t\t\t\t\tconst existingRecord = stonecrop.value.getRecordById(doctype, recordId)\n\t\t\t\t\tif (existingRecord) {\n\t\t\t\t\t\tformData.value = existingRecord.get('') || {}\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait stonecrop.value.getRecord(doctype, recordId)\n\t\t\t\t\t\t\tconst loadedRecord = stonecrop.value.getRecordById(doctype, recordId)\n\t\t\t\t\t\t\tif (loadedRecord) {\n\t\t\t\t\t\t\t\tformData.value = loadedRecord.get('') || {}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tformData.value = registry.initializeRecord(resolvedSchema.value)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\n\t// HST integration functions - always created but only populated when HST is available\n\tconst provideHSTPath = (fieldname: string, customRecordId?: string): string => {\n\t\tconst doctype = resolvedDoctype.value\n\t\tif (!doctype) return ''\n\n\t\tconst actualRecordId = customRecordId || options.recordId || 'new'\n\t\treturn `${doctype.slug}.${actualRecordId}.${fieldname}`\n\t}\n\n\tconst handleHSTChange = (changeData: HSTChangeData): void => {\n\t\tconst doctype = resolvedDoctype.value\n\t\tif (!hstStore.value || !stonecrop.value || !doctype) {\n\t\t\treturn\n\t\t}\n\n\t\ttry {\n\t\t\tconst pathParts = changeData.path.split('.')\n\t\t\tif (pathParts.length >= 2) {\n\t\t\t\tconst doctypeSlug = pathParts[0]\n\t\t\t\tconst recordId = pathParts[1]\n\n\t\t\t\tif (!hstStore.value.has(`${doctypeSlug}.${recordId}`)) {\n\t\t\t\t\tstonecrop.value.addRecord(doctype, recordId, { ...formData.value })\n\t\t\t\t}\n\n\t\t\t\tif (pathParts.length > 3) {\n\t\t\t\t\tconst recordPath = `${doctypeSlug}.${recordId}`\n\t\t\t\t\tconst nestedParts = pathParts.slice(2)\n\n\t\t\t\t\tlet currentPath = recordPath\n\t\t\t\t\tfor (let i = 0; i < nestedParts.length - 1; i++) {\n\t\t\t\t\t\tcurrentPath += `.${nestedParts[i]}`\n\n\t\t\t\t\t\tif (!hstStore.value.has(currentPath)) {\n\t\t\t\t\t\t\tconst nextPart = nestedParts[i + 1]\n\t\t\t\t\t\t\tconst isArray = !isNaN(Number(nextPart))\n\t\t\t\t\t\t\thstStore.value.set(currentPath, isArray ? [] : {})\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\thstStore.value.set(changeData.path, changeData.value)\n\n\t\t\tconst fieldParts = changeData.fieldname.split('.')\n\t\t\tconst newFormData = { ...formData.value }\n\n\t\t\tif (fieldParts.length === 1) {\n\t\t\t\tnewFormData[fieldParts[0]] = changeData.value\n\t\t\t} else {\n\t\t\t\tupdateNestedObject(newFormData, fieldParts, changeData.value)\n\t\t\t}\n\n\t\t\tformData.value = newFormData\n\t\t} catch {\n\t\t\t// Silently handle errors\n\t\t}\n\t}\n\n\t// Provide injection tokens if HST will be available\n\tif (options.doctype) {\n\t\tprovide('hstPathProvider', provideHSTPath)\n\t\tprovide('hstChangeHandler', handleHSTChange)\n\t}\n\n\t/**\n\t * Scaffold empty descendant records from defaults for all descendant links.\n\t * Delegates to Stonecrop.initializeNestedData method.\n\t * @param path - The HST path where initialized data should be stored\n\t * @param doctype - The doctype to initialize\n\t */\n\tconst initializeNestedData = (path: string, doctype: Doctype): void => {\n\t\tif (!stonecrop.value) {\n\t\t\tthrow new Error('Stonecrop instance not available')\n\t\t}\n\t\treturn stonecrop.value.initializeNestedData(path, doctype)\n\t}\n\n\t/**\n\t * Fetch a record and its nested data from the server.\n\t * Delegates to Stonecrop.fetchNestedData method.\n\t * @param path - The HST path (e.g., \"recipe.r1\")\n\t * @param doctype - The doctype to fetch\n\t * @param recordId - Record ID to fetch\n\t * @param options - Query options (includeNested to control which links are fetched)\n\t */\n\tconst fetchNestedData = async (\n\t\tpath: string,\n\t\tdoctype: Doctype,\n\t\trecordId: string,\n\t\tfetchOptions?: { includeNested?: boolean | string[] }\n\t): Promise<void> => {\n\t\tif (!stonecrop.value) {\n\t\t\tthrow new Error('Stonecrop instance not available')\n\t\t}\n\t\treturn stonecrop.value.fetchNestedData(path, doctype, recordId, fetchOptions)\n\t}\n\n\t/**\n\t * Collect a record payload with all nested doctype fields from HST\n\t * Delegates to Stonecrop.collectRecordPayload method\n\t * @param doctype - The doctype metadata\n\t * @param recordId - The record ID to collect\n\t * @returns The complete record payload ready for API submission\n\t */\n\tconst collectRecordPayload = (doctype: Doctype, recordId: string): Record<string, any> => {\n\t\tif (!stonecrop.value) {\n\t\t\tthrow new Error('Stonecrop instance not available')\n\t\t}\n\t\treturn stonecrop.value.collectRecordPayload(doctype, recordId)\n\t}\n\n\t/**\n\t * Create a nested context for descendant forms\n\t * @param basePath - The base path for the nested context (e.g., \"customer.123.address\")\n\t * @param _descendantDoctype - The descendant doctype metadata (unused but kept for API consistency)\n\t * @returns Object with scoped provideHSTPath and handleHSTChange\n\t */\n\tconst createNestedContext = (basePath: string, _descendantDoctype: Doctype) => {\n\t\tconst nestedProvideHSTPath = (fieldname: string): string => {\n\t\t\treturn `${basePath}.${fieldname}`\n\t\t}\n\n\t\tconst nestedHandleHSTChange = (changeData: HSTChangeData): void => {\n\t\t\t// Update the path to be relative to the nested base path\n\t\t\tconst nestedPath = changeData.path.startsWith(basePath) ? changeData.path : `${basePath}.${changeData.fieldname}`\n\n\t\t\thandleHSTChange({\n\t\t\t\t...changeData,\n\t\t\t\tpath: nestedPath,\n\t\t\t})\n\t\t}\n\n\t\treturn {\n\t\t\tprovideHSTPath: nestedProvideHSTPath,\n\t\t\thandleHSTChange: nestedHandleHSTChange,\n\t\t}\n\t}\n\n\t// Create operation log API object\n\tconst operationLog: OperationLogAPI = {\n\t\toperations,\n\t\tcurrentIndex,\n\t\tundoRedoState,\n\t\tcanUndo,\n\t\tcanRedo,\n\t\tundoCount,\n\t\tredoCount,\n\t\tundo,\n\t\tredo,\n\t\tstartBatch,\n\t\tcommitBatch,\n\t\tcancelBatch,\n\t\tclear,\n\t\tgetOperationsFor,\n\t\tgetSnapshot,\n\t\tmarkIrreversible,\n\t\tlogAction,\n\t\tconfigure,\n\t}\n\t// Always return HST functions if doctype is provided or will be loaded from router\n\tif (options.doctype) {\n\t\t// Explicit doctype - return HST immediately\n\t\treturn {\n\t\t\tstonecrop,\n\t\t\toperationLog,\n\t\t\tprovideHSTPath,\n\t\t\thandleHSTChange,\n\t\t\thstStore,\n\t\t\tformData,\n\t\t\tresolvedSchema,\n\t\t\tinitializeNestedData,\n\t\t\tfetchNestedData,\n\t\t\tcollectRecordPayload,\n\t\t\tcreateNestedContext,\n\t\t\tisLoading,\n\t\t\terror,\n\t\t\tresolvedDoctype,\n\t\t\tisWorkflowReady,\n\t\t\tblockedLinks,\n\t\t} satisfies HSTStonecropReturn\n\t}\n\n\t// No doctype named: the instance and the operation log are everything this can offer.\n\treturn {\n\t\tstonecrop,\n\t\toperationLog,\n\t}\n}\n\n/**\n * Setup deep reactivity between form data and HST store\n */\nfunction setupDeepReactivity(\n\tdoctype: Doctype,\n\trecordId: string,\n\tformData: Ref<Record<string, any>>,\n\thstStore: HSTNode\n): void {\n\twatch(\n\t\tformData,\n\t\tnewData => {\n\t\t\tconst recordPath = `${doctype.slug}.${recordId}`\n\n\t\t\tObject.keys(newData).forEach(fieldname => {\n\t\t\t\tconst path = `${recordPath}.${fieldname}`\n\t\t\t\ttry {\n\t\t\t\t\thstStore.set(path, newData[fieldname])\n\t\t\t\t} catch {\n\t\t\t\t\t// Silently handle errors\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\t{ deep: true }\n\t)\n}\n\n/**\n * Update nested object with dot-notation path\n */\nfunction updateNestedObject(obj: any, path: string[], value: any): void {\n\tlet current: Record<string, any> = obj\n\n\tfor (let i = 0; i < path.length - 1; i++) {\n\t\tconst key = path[i]\n\n\t\tif (!(key in current) || typeof current[key] !== 'object') {\n\t\t\tcurrent[key] = isNaN(Number(path[i + 1])) ? {} : []\n\t\t}\n\n\t\tcurrent = current[key]\n\t}\n\n\tconst finalKey = path[path.length - 1]\n\tcurrent[finalKey] = value\n}\n","import type { WorkflowMeta } from '@stonecrop/schema'\nimport { useRouter } from 'vue-router'\n\nimport { executeClientHandler } from './client-handler'\nimport { useStonecrop } from './composables/stonecrop'\nimport Doctype from './doctype'\nimport { isDraftRecordId } from './draft'\nimport type {\n\tActionDispatchResult,\n\tActionEventPayload,\n\tActionFailure,\n\tFollowRecordContext,\n\tUseClientActionOptions,\n} from './types/client-action'\n\n/**\n * The identity a server response settled on, or `undefined` when it did not state one.\n *\n * Deliberately stricter than `getRecordId`: that falls back to `id` when the declared key is\n * absent, which here would let a handler returning a partial record (say `{ id, total }` for a\n * natural-keyed doctype) look like a rename and relocate the record to a key the adapter cannot\n * look up. An action whose result carries no identity at all — a `{ state }` outcome — leaves the\n * record exactly where it is.\n */\nfunction settledRecordId(doctype: Doctype, record: Record<string, unknown>): string | undefined {\n\tif (record[doctype.recordIdField] === undefined) return undefined\n\treturn doctype.getRecordId(record)\n}\n\n/**\n * Default failure surface: a blocking alert beats a silent `console.error` for a failed action\n * (e.g. a Save that the server refused), and there is no notification system in the framework to\n * route it into. A host with one passes `onError` and this is never called.\n */\nfunction notifyActionError(failure: ActionFailure): void {\n\tconsole.error('Action failed:', failure.message)\n\tif (typeof window !== 'undefined') window.alert(failure.message)\n}\n\n/**\n * Shared executor for doctype action clicks. A host's Desktop `@action` handler delegates\n * here so every host runs the same logic from one definition:\n *\n * - If the clicked action carries a `clientHandler`, run it. The handler **owns\n * orchestration** — it calls `runAction` itself when it needs the server, navigates via\n * `router`, reads `record`, or queries `graphql`. It supersedes the default dispatch.\n * - Otherwise dispatch the action to its server `handler` (the pre-existing behavior),\n * so actions without a `clientHandler` are unchanged.\n *\n * `runAction` is the only blessed write: it dispatches **and** leaves the store consistent,\n * filing the returned record under the identity the *server* settled on and following the route\n * there when that differs from the one dispatched. For a created record those are never the same,\n * which is what makes hand-rolling this reliably wrong.\n *\n * The store write itself lives one layer down, in {@link Stonecrop.dispatchAction}, so a host that\n * never adopts this composable still cannot file a record under the wrong key. What stays here is\n * only what needs the *dispatched* id: dropping the stale key, and moving the route.\n *\n * Pass `buildArgs` to change the argument envelope your backend receives, `followRecord` to change\n * where a created record sends the user, and `onError` to route failures into your own\n * notification system. Identity resolution and HST keying are deliberately not configurable — see\n * {@link UseClientActionOptions}.\n *\n * @public\n */\nexport function useClientAction(options: UseClientActionOptions = {}) {\n\tconst { stonecrop } = useStonecrop()\n\t// Called during setup so the injection is available; the registry fallback below covers a\n\t// caller outside an injection context, and a host that installed the plugin with `{ router }`.\n\tconst injectedRouter = useRouter()\n\tconst onError = options.onError ?? notifyActionError\n\n\tconst resolveRouter = () => injectedRouter ?? stonecrop.value?.registry.router\n\n\tconst buildArgs =\n\t\toptions.buildArgs ??\n\t\t// Spreading `undefined` in an object literal adds nothing, so `extra` needs no fallback.\n\t\t(({ recordId, isDraft, data, extra }) => [{ ...(isDraft ? {} : { id: recordId }), data, ...extra }])\n\n\tconst followRecord =\n\t\toptions.followRecord ??\n\t\t(async ({ doctype, recordId }: FollowRecordContext) => {\n\t\t\tawait resolveRouter()?.replace(`/${doctype}/${recordId}`)\n\t\t})\n\n\t/**\n\t * Dispatch `action` for the record and reconcile the store and the route with whichever\n\t * identity the result carries.\n\t */\n\tasync function dispatchAndWriteback(\n\t\tdoctypeSlug: string,\n\t\trecordId: string,\n\t\tdata: Record<string, unknown>,\n\t\taction: string,\n\t\textra?: Record<string, unknown>\n\t): Promise<ActionDispatchResult> {\n\t\tconst sc = stonecrop.value\n\t\tif (!sc) return { success: false, data: null, error: 'Stonecrop is not initialized' }\n\n\t\tconst doctype = sc.registry.getDoctype(doctypeSlug)\n\t\tif (!doctype) return { success: false, data: null, error: `Unknown doctype: ${doctypeSlug}` }\n\n\t\t// A draft omits the id, which the write path reads as \"create\". Sending the route segment\n\t\t// instead reaches the same branch by accident — via a lookup for a record named `new`.\n\t\tconst isDraft = isDraftRecordId(recordId)\n\t\tconst result = await sc.dispatchAction(\n\t\t\tdoctype,\n\t\t\taction,\n\t\t\tbuildArgs({ doctype: doctypeSlug, action, recordId, isDraft, data, extra })\n\t\t)\n\n\t\tif (result.success && result.data) {\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the action result payload is an opaque JSON scalar; every adapter returns the record as an object\n\t\t\tconst record = result.data as Record<string, unknown>\n\t\t\tconst settledId = settledRecordId(doctype, record)\n\n\t\t\tif (settledId === undefined) {\n\t\t\t\t// The result states no identity of its own — a `{ state }` outcome. `dispatchAction`\n\t\t\t\t// could not file it, because only this layer knows which record was dispatched. A\n\t\t\t\t// draft has nowhere to put it: filing it under the route segment would leave a\n\t\t\t\t// record named `new` in the list view.\n\t\t\t\tif (!isDraft) sc.addRecord(doctypeSlug, recordId, record)\n\t\t\t\treturn result\n\t\t\t}\n\n\t\t\t// `dispatchAction` has already filed the record under `settledId`. Only the two steps\n\t\t\t// that need the dispatched id are left.\n\t\t\tif (recordId !== settledId) {\n\t\t\t\t// No-op for a draft, which was never in the store — `removeRecord` checks first.\n\t\t\t\tsc.removeRecord(doctypeSlug, recordId)\n\t\t\t\tawait followRecord({ doctype: doctypeSlug, recordId: settledId, previousRecordId: recordId })\n\t\t\t}\n\t\t}\n\t\treturn result\n\t}\n\n\t/**\n\t * Handle a Desktop `@action` event: run the action's `clientHandler` if present,\n\t * else dispatch to the server handler.\n\t */\n\tasync function run(payload: ActionEventPayload): Promise<void> {\n\t\tconst sc = stonecrop.value\n\t\tif (!sc) return\n\n\t\tconst { name, doctype: doctypeSlug, recordId, data } = payload\n\n\t\tconst doctype = sc.registry.getDoctype(doctypeSlug)\n\t\t// `workflow` is a union (XState | WorkflowMeta); only WorkflowMeta carries an\n\t\t// `actions` map with `clientHandler`. An XState workflow has no `actions`, so the\n\t\t// lookup is undefined and we fall through to the server dispatch.\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowing the workflow union to read the optional actions map\n\t\tconst workflow = doctype?.workflow as WorkflowMeta | undefined\n\t\tconst clientHandler = workflow?.actions?.[name]?.clientHandler\n\n\t\ttry {\n\t\t\tif (!clientHandler) {\n\t\t\t\t// No client handler — preserve the existing server-dispatch behavior.\n\t\t\t\tconst result = await dispatchAndWriteback(doctypeSlug, recordId, data, name)\n\t\t\t\tif (!result.success) {\n\t\t\t\t\tonError({\n\t\t\t\t\t\tmessage: result.error ?? `Action \"${name}\" failed`,\n\t\t\t\t\t\taction: name,\n\t\t\t\t\t\tdoctype: doctypeSlug,\n\t\t\t\t\t\trecordId,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Client handler present — it owns orchestration. Assemble the capability map.\n\t\t\t// Prefer the live HST record; fall back to the form snapshot in the payload.\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- HSTNode.get returns any; a record node is always an object of field values\n\t\t\tconst record = (sc.getRecordById(doctypeSlug, recordId)?.get('') as Record<string, unknown> | undefined) ?? data\n\n\t\t\tconst runAction = (action: string, extra?: Record<string, unknown>) =>\n\t\t\t\tdispatchAndWriteback(doctypeSlug, recordId, data, action, extra)\n\n\t\t\t// Read-only GraphQL escape hatch — no mutation is injected (a raw mutation would\n\t\t\t// bypass the dispatch and leave HST stale). `query` is the GraphQL transport's\n\t\t\t// method, not part of the abstract DataClient interface (a non-GraphQL client may\n\t\t\t// not support it), so probe for it structurally and reject if unsupported.\n\t\t\tconst graphql = {\n\t\t\t\tquery<T = unknown>(query: string, variables?: Record<string, unknown>): Promise<T> {\n\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- probing DataClient for the GraphQL transport's `query`, which the abstract interface deliberately does not declare\n\t\t\t\t\tconst client = sc.getClient() as unknown as\n\t\t\t\t\t\t| { query?: <R>(q: string, v?: Record<string, unknown>) => Promise<R> }\n\t\t\t\t\t\t| undefined\n\t\t\t\t\tif (!client?.query) {\n\t\t\t\t\t\treturn Promise.reject(new Error('The configured data client does not support graphql.query'))\n\t\t\t\t\t}\n\t\t\t\t\treturn client.query<T>(query, variables)\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tawait executeClientHandler(clientHandler, { router: resolveRouter(), record, runAction, graphql })\n\t\t} catch (error) {\n\t\t\tonError({\n\t\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t\t\taction: name,\n\t\t\t\tdoctype: doctypeSlug,\n\t\t\t\trecordId,\n\t\t\t\tcause: error,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn { run }\n}\n","import type { FetchStrategy, CustomFetch } from '@stonecrop/schema'\nimport { computed, inject, ref } from 'vue'\n\nimport Doctype from '../doctype'\nimport { Stonecrop } from '../stonecrop'\nimport type { LazyLink } from '../types/composable'\n\n/**\n * Get the lazy link state for a specific link field on a doctype record.\n *\n * This composable provides reactive state for lazy-loaded links:\n * - `loading`: true while fetching\n * - `loaded`: true after successful fetch (permanent until reload)\n * - `error`: error state if any\n * - `reload()`: explicitly trigger a fetch\n * - `data`: computed from HST, or undefined if not loaded\n *\n * The reload() function respects the link's fetch strategy:\n * - `sync`: fetches via GraphQL query through fetchNestedData\n * - `lazy`: fetches via GraphQL query through fetchNestedData\n * - `custom`: invokes the serialized handler function directly\n *\n * @param doctype - The doctype instance\n * @param recordId - The record ID\n * @param linkFieldname - The link fieldname to load\n * @returns LazyLink with loading, loaded, error, reload, and data\n * @public\n */\nexport function useLazyLink(doctype: Doctype, recordId: string, linkFieldname: string): LazyLink {\n\tconst stonecropInstance = inject<Stonecrop>('$stonecrop') || Stonecrop._root\n\n\tif (!stonecropInstance) {\n\t\tthrow new Error('Stonecrop instance not available. Ensure useStonecrop() has been called first.')\n\t}\n\n\tconst loading = ref(false)\n\tconst loaded = ref(false)\n\tconst error = ref<Error | null>(null)\n\n\tconst hstStore = stonecropInstance.getStore()\n\n\t/**\n\t * Build the HST path for a lazy link field\n\t */\n\tconst getLinkPath = (): string => {\n\t\tconst slug = doctype.slug || doctype.doctype\n\t\treturn `${slug}.${recordId}.${linkFieldname}`\n\t}\n\n\t/**\n\t * Get the link declaration from the doctype schema\n\t */\n\tconst getLinkDeclaration = (): FetchStrategy | undefined => {\n\t\treturn doctype.links?.[linkFieldname]?.fetch\n\t}\n\n\t/**\n\t * Invoke a custom fetch handler\n\t * The handler is a serialized function string that we execute via new Function()\n\t */\n\tconst invokeCustomHandler = async (handler: CustomFetch['handler']): Promise<any> => {\n\t\ttry {\n\t\t\t// Create function from serialized string and invoke it\n\t\t\t// The function receives the stonecrop instance and path as parameters\n\t\t\t// oxlint-disable-next-line @typescript-eslint/no-implied-eval\n\t\t\tconst fn = new Function(\n\t\t\t\t'stonecrop',\n\t\t\t\t'path',\n\t\t\t\t'hst',\n\t\t\t\t`\n\t\t\t\treturn (${handler})(stonecrop, path, hst)\n\t\t\t`\n\t\t\t)\n\t\t\treturn await fn(stonecropInstance, getLinkPath(), hstStore)\n\t\t} catch (err) {\n\t\t\tthrow new Error(`Custom handler failed: ${err instanceof Error ? err.message : String(err)}`, { cause: err })\n\t\t}\n\t}\n\n\t/**\n\t * Fetch the link data using the appropriate strategy\n\t */\n\tconst fetchLinkData = async (): Promise<void> => {\n\t\tconst linkFetch = getLinkDeclaration()\n\t\tconst ancestorPath = `${doctype.slug || doctype.doctype}.${recordId}`\n\n\t\tif (linkFetch?.method === 'custom') {\n\t\t\t// Ensure ancestor path exists before invoking custom handler\n\t\t\tif (!hstStore.has(ancestorPath)) {\n\t\t\t\thstStore.set(ancestorPath, {}, 'system')\n\t\t\t}\n\n\t\t\t// Custom handler - invoke directly\n\t\t\tconst result = await invokeCustomHandler(linkFetch.handler)\n\n\t\t\t// Store result in HST at the link path\n\t\t\thstStore.set(getLinkPath(), result, 'system')\n\t\t} else {\n\t\t\t// sync or lazy (both use fetchNestedData but with different includeNested)\n\t\t\t// For lazy links, we still use fetchNestedData but only for this specific link\n\t\t\tawait stonecropInstance.fetchNestedData(ancestorPath, doctype, recordId, { includeNested: [linkFieldname] })\n\t\t}\n\t}\n\n\t/**\n\t * Explicitly reload the lazy link data\n\t */\n\tconst reload = async (): Promise<void> => {\n\t\tif (loading.value) return\n\n\t\tloading.value = true\n\t\terror.value = null\n\n\t\ttry {\n\t\t\tawait fetchLinkData()\n\t\t\tloaded.value = true\n\t\t} catch (err) {\n\t\t\terror.value = err instanceof Error ? err : new Error(String(err))\n\t\t\tthrow err\n\t\t} finally {\n\t\t\tloading.value = false\n\t\t}\n\t}\n\n\t/**\n\t * Computed property that returns the loaded data from HST\n\t */\n\tconst data = computed(() => {\n\t\tif (!loaded.value) return undefined\n\t\treturn hstStore.get(getLinkPath())\n\t})\n\n\treturn {\n\t\t// State\n\t\tloading,\n\t\tloaded,\n\t\terror,\n\n\t\t// Computed\n\t\tdata,\n\n\t\t// Actions\n\t\treload,\n\t}\n}\n","import { useMagicKeys, whenever } from '@vueuse/core'\nimport { storeToRefs } from 'pinia'\nimport { getCurrentInstance, inject } from 'vue'\n\nimport type { HSTNode } from '../types/hst'\nimport { useOperationLogStore } from '../stores/operation-log'\nimport type { OperationLogConfig } from '../types/operation-log'\n\n/**\n * Composable for operation log management\n * Provides easy access to undo/redo functionality and operation history\n *\n * @param config - Optional configuration for the operation log\n * @returns Operation log interface\n *\n * @example\n * ```typescript\n * const { undo, redo, canUndo, canRedo, operations, configure } = useOperationLog()\n *\n * // Configure the log\n * configure({\n * maxOperations: 50,\n * enableCrossTabSync: true,\n * enablePersistence: true\n * })\n *\n * // Undo/redo\n * await undo(hstStore)\n * await redo(hstStore)\n * ```\n *\n * @public\n */\nexport function useOperationLog(config?: Partial<OperationLogConfig>) {\n\t// inject() is only valid inside a component setup() context. When this\n\t// composable is called outside one (e.g. directly in test bodies or plain\n\t// scripts) skip the injection entirely and fall back to the Pinia store.\n\tconst injectedStore = getCurrentInstance()\n\t\t? inject<ReturnType<typeof useOperationLogStore> | undefined>('$operationLogStore', undefined)\n\t\t: undefined\n\tconst store = injectedStore || useOperationLogStore()\n\n\t// Apply configuration if provided\n\tif (config) {\n\t\tstore.configure(config)\n\t}\n\n\t// Extract reactive state\n\tconst { operations, currentIndex, undoRedoState, canUndo, canRedo, undoCount, redoCount } = storeToRefs(store)\n\n\t/**\n\t * Undo the last operation\n\t */\n\tfunction undo(hstStore: HSTNode): boolean {\n\t\treturn store.undo(hstStore)\n\t}\n\n\t/**\n\t * Redo the next operation\n\t */\n\tfunction redo(hstStore: HSTNode): boolean {\n\t\treturn store.redo(hstStore)\n\t}\n\n\t/**\n\t * Start a batch operation\n\t */\n\tfunction startBatch() {\n\t\tstore.startBatch()\n\t}\n\n\t/**\n\t * Commit the current batch\n\t */\n\tfunction commitBatch(description?: string): string | null {\n\t\treturn store.commitBatch(description)\n\t}\n\n\t/**\n\t * Cancel the current batch\n\t */\n\tfunction cancelBatch() {\n\t\tstore.cancelBatch()\n\t}\n\n\t/**\n\t * Clear all operations\n\t */\n\tfunction clear() {\n\t\tstore.clear()\n\t}\n\n\t/**\n\t * Get operations for a specific doctype/record\n\t */\n\tfunction getOperationsFor(doctype: string, recordId?: string) {\n\t\treturn store.getOperationsFor(doctype, recordId)\n\t}\n\n\t/**\n\t * Get a snapshot of the operation log\n\t */\n\tfunction getSnapshot() {\n\t\treturn store.getSnapshot()\n\t}\n\n\t/**\n\t * Mark an operation as irreversible\n\t * @param operationId - The ID of the operation to mark\n\t * @param reason - The reason why the operation is irreversible\n\t */\n\tfunction markIrreversible(operationId: string, reason: string) {\n\t\tstore.markIrreversible(operationId, reason)\n\t}\n\n\t/**\n\t * Log an action execution (stateless actions like print, email, etc.)\n\t * @param doctype - The doctype the action was executed on\n\t * @param actionName - The name of the action that was executed\n\t * @param recordIds - Optional array of record IDs the action was executed on\n\t * @param result - The result of the action execution\n\t * @param error - Optional error message if action failed\n\t * @returns The operation ID\n\t */\n\tfunction logAction(\n\t\tdoctype: string,\n\t\tactionName: string,\n\t\trecordIds?: string[],\n\t\tresult: 'success' | 'failure' | 'pending' = 'success',\n\t\terror?: string\n\t): string {\n\t\treturn store.logAction(doctype, actionName, recordIds, result, error)\n\t}\n\n\t/**\n\t * Update configuration\n\t * @param options - Configuration options to update\n\t */\n\tfunction configure(options: Partial<OperationLogConfig>) {\n\t\tstore.configure(options)\n\t}\n\n\treturn {\n\t\t// State\n\t\toperations,\n\t\tcurrentIndex,\n\t\tundoRedoState,\n\t\tcanUndo,\n\t\tcanRedo,\n\t\tundoCount,\n\t\tredoCount,\n\n\t\t// Methods\n\t\tundo,\n\t\tredo,\n\t\tstartBatch,\n\t\tcommitBatch,\n\t\tcancelBatch,\n\t\tclear,\n\t\tgetOperationsFor,\n\t\tgetSnapshot,\n\t\tmarkIrreversible,\n\t\tlogAction,\n\t\tconfigure,\n\t}\n}\n\n/**\n * Keyboard shortcut handler for undo/redo\n * Automatically binds Ctrl+Z (undo) and Ctrl+Shift+Z/Ctrl+Y (redo) using VueUse\n *\n * @param hstStore - The HST store to operate on\n * @param enabled - Whether shortcuts are enabled (default: true)\n *\n * @example\n * ```typescript\n * import { onMounted } from 'vue'\n *\n * const stonecrop = useStonecrop({ doctype, recordId })\n * useUndoRedoShortcuts(stonecrop.hstStore)\n * ```\n *\n * @public\n */\nexport function useUndoRedoShortcuts(hstStore: HSTNode, enabled = true) {\n\tif (!enabled) return\n\n\tconst { undo, redo, canUndo, canRedo } = useOperationLog()\n\tconst keys = useMagicKeys()\n\n\t// Undo shortcuts: Ctrl+Z or Cmd+Z (Mac)\n\twhenever(keys['Ctrl+Z'], () => {\n\t\tif (canUndo.value) {\n\t\t\tundo(hstStore)\n\t\t}\n\t})\n\n\twhenever(keys['Meta+Z'], () => {\n\t\tif (canUndo.value) {\n\t\t\tundo(hstStore)\n\t\t}\n\t})\n\n\t// Redo shortcuts: Ctrl+Shift+Z, Cmd+Shift+Z (Mac), or Ctrl+Y\n\twhenever(keys['Ctrl+Shift+Z'], () => {\n\t\tif (canRedo.value) {\n\t\t\tredo(hstStore)\n\t\t}\n\t})\n\n\twhenever(keys['Meta+Shift+Z'], () => {\n\t\tif (canRedo.value) {\n\t\t\tredo(hstStore)\n\t\t}\n\t})\n\n\twhenever(keys['Ctrl+Y'], () => {\n\t\tif (canRedo.value) {\n\t\t\tredo(hstStore)\n\t\t}\n\t})\n}\n\n/**\n * Batch operation helper\n * Wraps a function execution in a batch operation\n *\n * @param fn - The function to execute within a batch\n * @param description - Optional description for the batch\n * @returns The batch operation ID\n *\n * @example\n * ```typescript\n * const { withBatch } = useOperationLog()\n *\n * const batchId = await withBatch(() => {\n * hstStore.set('task.123.title', 'New Title')\n * hstStore.set('task.123.status', 'active')\n * hstStore.set('task.123.priority', 'high')\n * }, 'Update task details')\n * ```\n *\n * @public\n */\nexport async function withBatch<T>(fn: () => T | Promise<T>, description?: string): Promise<string | null> {\n\tconst { startBatch, commitBatch, cancelBatch } = useOperationLog()\n\n\tstartBatch()\n\n\ttry {\n\t\tawait fn()\n\t\treturn commitBatch(description)\n\t} catch (error) {\n\t\tcancelBatch()\n\t\tthrow error\n\t}\n}\n","import type { DoctypeField, LinkDeclaration, TriggerDefinition, WorkflowMeta } from '@stonecrop/schema'\nimport { getRecordIdentity, getRecordIdField, isActionAllowedInState, normalizeFieldKind } from '@stonecrop/schema'\nimport { List } from 'immutable'\nimport { Component } from 'vue'\n\nimport type { DoctypeConfig, ImmutableDoctype } from './types/doctype'\n\n/**\n * Doctype runtime class with Immutable.js collections for HST change tracking.\n * @public\n */\nexport default class Doctype {\n\t/**\n\t * The doctype name\n\t * @public\n\t * @readonly\n\t */\n\treadonly doctype: string\n\n\t/**\n\t * Alias for doctype (for DoctypeLike interface compatibility)\n\t * @public\n\t * @readonly\n\t */\n\tget name(): string {\n\t\treturn this.doctype\n\t}\n\n\t/**\n\t * The doctype schema\n\t * @public\n\t * @readonly\n\t */\n\treadonly schema: ImmutableDoctype['schema']\n\n\t/**\n\t * The doctype workflow\n\t * @public\n\t * @readonly\n\t */\n\treadonly workflow: ImmutableDoctype['workflow']\n\n\t/**\n\t * The doctype component\n\t * @public\n\t * @readonly\n\t */\n\treadonly component?: Component\n\n\t/**\n\t * Relationship links to other doctypes\n\t * @public\n\t * @readonly\n\t */\n\treadonly links?: Record<string, LinkDeclaration>\n\n\t/**\n\t * Field on this doctype used when displaying a reference to one of its records.\n\t * @public\n\t * @readonly\n\t */\n\treadonly displayField?: string\n\n\t/**\n\t * Creates a new Doctype instance\n\t * @param doctype - The doctype name\n\t * @param schema - The doctype schema definition\n\t * @param workflow - The doctype workflow configuration (XState machine)\n\t * @param component - Optional Vue component for rendering the doctype\n\t * @param links - Optional relationship links to other doctypes\n\t * @param displayField - Optional field used when displaying references to this doctype\n\t */\n\tconstructor(\n\t\tdoctype: string,\n\t\tschema: ImmutableDoctype['schema'],\n\t\tworkflow: ImmutableDoctype['workflow'],\n\t\tcomponent?: Component,\n\t\tlinks?: Record<string, LinkDeclaration>,\n\t\tdisplayField?: string\n\t) {\n\t\tthis.doctype = doctype\n\t\tthis.schema = schema\n\t\tthis.workflow = workflow\n\t\tthis.component = component\n\t\tthis.links = links\n\t\tthis.displayField = displayField\n\t}\n\n\t/**\n\t * Creates a Doctype instance from a plain configuration object.\n\t * Handles conversion of arrays to Immutable.js collections internally.\n\t *\n\t * This is the recommended way to create a Doctype from API responses\n\t * or configuration files, as it encapsulates the Immutable.js construction\n\t * that the framework uses internally.\n\t *\n\t * @param config - Plain object with doctype configuration (typically from API response)\n\t * @returns A new Doctype instance with Immutable.js collections\n\t *\n\t * @example\n\t * ```ts\n\t * // From an API response\n\t * const response = await client.getMeta({ doctype: 'plan' })\n\t * const doctype = Doctype.fromObject(response)\n\t * registry.addDoctype(doctype)\n\t * ```\n\t *\n\t * @example\n\t * ```ts\n\t * // From a configuration object\n\t * const planDoctype = Doctype.fromObject({\n\t * name: 'Plan',\n\t * fields: [\n\t * { fieldname: 'title', label: 'Title', component: 'ATextInput' },\n\t * { fieldname: 'status', label: 'Status', component: 'ATextInput' },\n\t * ],\n\t * workflow: {\n\t * id: 'plan',\n\t * initial: 'draft',\n\t * states: { draft: {}, submitted: {} }\n\t * }\n\t * })\n\t * ```\n\t *\n\t * @public\n\t */\n\tstatic fromObject(config: DoctypeConfig): Doctype {\n\t\t// Authored JSON may omit the `kind` discriminant; the Zod schema injects it via a\n\t\t// preprocess, but this path bypasses Zod. Normalize here so the registry's\n\t\t// `resolveFields` (which gates link/fieldset handling on `field.kind`) sees the same\n\t\t// shape a parsed doctype would — otherwise links silently fail to expand.\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- normalizeFieldKind only injects the `kind` discriminant; the field shape is otherwise preserved\n\t\tconst fields = config.fields?.map(normalizeFieldKind) as DoctypeField[] | undefined\n\t\tconst schema = fields ? List(fields) : List<DoctypeField>()\n\n\t\treturn new Doctype(config.name, schema, config.workflow, undefined, config.links, config.displayField)\n\t}\n\n\t/**\n\t * Returns the raw authoring schema as a plain array.\n\t * For the resolved schema suitable for AForm, use `registry.resolveSchema(doctype)`.\n\t *\n\t * @returns Array of raw DoctypeField authoring definitions\n\t *\n\t * @example\n\t * ```ts\n\t * const fields = doctype.getSchemaArray()\n\t * // Pass to resolveSchema for AForm-ready output:\n\t * const resolved = registry.resolveSchema(doctype)\n\t * ```\n\t *\n\t * @public\n\t */\n\tgetSchemaArray(): DoctypeField[] {\n\t\tif (!this.schema) return []\n\t\treturn this.schema.toArray()\n\t}\n\n\t/**\n\t * Resolve a record's identity using this doctype's declared `primaryKey`, falling back to `id`.\n\t *\n\t * Lives here rather than at the call site because the doctype owns its schema — and because the\n\t * rule must match the server's, which builds its SQL identity predicate from the same declared\n\t * field via `@stonecrop/schema`'s `getPrimaryKeyField`.\n\t *\n\t * @param record - the record to read the identity from\n\t * @returns the identity as a string, or `undefined` when neither the declared key nor `id` yields one\n\t *\n\t * @public\n\t */\n\tgetRecordId(record: Record<string, unknown>): string | undefined {\n\t\treturn getRecordIdentity(this.getSchemaArray(), record)\n\t}\n\n\t/**\n\t * The field a record of this doctype is identified by: the declared `primaryKey`, or `id`\n\t * when nothing is declared.\n\t *\n\t * The client-side twin of the adapters' `recordLookupField`. Both are the same call to\n\t * `@stonecrop/schema`'s `getRecordIdField`, so the field a caller reads an identity out of is\n\t * the same field the adapter builds its lookup predicate on.\n\t *\n\t * Use this to ask whether a record *states* its own identity. `getRecordId` deliberately\n\t * falls back to `id` when the declared key is missing, which is right for resolving a link\n\t * from a record already in hand and wrong for deciding whether a server response settled on\n\t * a new identity: a response that omits a natural key would resolve through that fallback to\n\t * a surrogate the adapter cannot look up.\n\t *\n\t * @returns The identifying fieldname\n\t *\n\t * @public\n\t */\n\tget recordIdField(): string {\n\t\treturn getRecordIdField(this.getSchemaArray())\n\t}\n\n\t/**\n\t * Returns the transitions available from a given workflow state, derived from the\n\t * doctype's workflow configuration. Supports both XState format and WorkflowMeta format.\n\t *\n\t * @param currentState - The state name to read transitions from\n\t * @returns Array of transition descriptors with `name` and `targetState`\n\t *\n\t * @example\n\t * ```ts\n\t * const transitions = doctype.getAvailableTransitions('draft')\n\t * // [{ name: 'SUBMIT', targetState: 'submitted' }]\n\t * ```\n\t *\n\t * @public\n\t */\n\tgetAvailableTransitions(currentState: string): Array<{ name: string; targetState: string }> {\n\t\tconst workflow = this.workflow\n\t\tif (!workflow) return []\n\n\t\t// Check if this is WorkflowMeta format (states is an array) or XState format (states is an object)\n\t\tif (Array.isArray(workflow.states)) {\n\t\t\t// WorkflowMeta format: validate state exists and filter actions by allowedStates\n\t\t\tconst states = workflow.states\n\t\t\tif (!states.includes(currentState)) return []\n\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Array.isArray(workflow.states) confirms WorkflowMeta format above\n\t\t\tconst actions = (workflow as WorkflowMeta).actions\n\t\t\tif (!actions) return []\n\n\t\t\treturn (\n\t\t\t\tObject.entries(actions)\n\t\t\t\t\t// Exclude stateless Commands — they change no state and are surfaced separately\n\t\t\t\t\t// via getAvailableCommands(). Genuine transitions carry a nextState.\n\t\t\t\t\t.filter(([, actionDef]) => !actionDef.stateless && isActionAllowedInState(actionDef, currentState))\n\t\t\t\t\t.map(([name, actionDef]) => ({\n\t\t\t\t\t\tname,\n\t\t\t\t\t\ttargetState: actionDef.nextState ?? currentState,\n\t\t\t\t\t}))\n\t\t\t)\n\t\t}\n\n\t\t// XState format: use the on property of the state\n\t\tconst states = workflow.states\n\t\tif (!states) return []\n\t\tconst stateConfig = states[currentState]\n\t\tif (!stateConfig?.on) return []\n\t\treturn Object.entries(stateConfig.on).map(([name, target]) => ({\n\t\t\tname,\n\t\t\ttargetState: typeof target === 'string' ? target : 'unknown',\n\t\t}))\n\t}\n\n\t/**\n\t * Returns the stateless **Commands** available in a given workflow state — side-effect\n\t * actions (save/print/email…) that do not change workflow state. Unlike transitions,\n\t * Commands may exist on a workflow that declares no `states` (a commands-only doctype),\n\t * and a Command with no `allowedStates` is available in every state.\n\t *\n\t * Only meaningful for WorkflowMeta format; XState workflows have no Commands.\n\t *\n\t * @param currentState - The record's current state, used to honor a Command's `allowedStates`\n\t * @returns Array of command descriptors with `name`\n\t *\n\t * @example\n\t * ```ts\n\t * const commands = doctype.getAvailableCommands('Draft')\n\t * // [{ name: 'Print' }]\n\t * ```\n\t *\n\t * @public\n\t */\n\tgetAvailableCommands(currentState?: string): Array<{ name: string }> {\n\t\tconst workflow = this.workflow\n\t\tif (!workflow) return []\n\n\t\t// Only WorkflowMeta carries an `actions` map; XState workflows have no Commands.\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- probing the workflow union for the optional WorkflowMeta actions map\n\t\tconst actions = (workflow as WorkflowMeta).actions\n\t\tif (!actions) return []\n\n\t\treturn Object.entries(actions)\n\t\t\t.filter(([, actionDef]) => actionDef.stateless === true && isActionAllowedInState(actionDef, currentState ?? ''))\n\t\t\t.map(([name]) => ({ name }))\n\t}\n\n\t/**\n\t * Returns the field-validation **triggers** declared on this doctype's workflow (advisory,\n\t * client-side). Keyed by trigger name. Returns undefined when the workflow is absent, is an\n\t * XState machine (no triggers), or simply declares none.\n\t *\n\t * @returns The `workflow.triggers` map, or undefined\n\t *\n\t * @example\n\t * ```ts\n\t * const triggers = doctype.getTriggers()\n\t * // { dateOrder: { on: ['start_date', 'end_date'], clientHandler: '…' } }\n\t * ```\n\t *\n\t * @public\n\t */\n\tgetTriggers(): Record<string, TriggerDefinition> | undefined {\n\t\tconst workflow = this.workflow\n\t\tif (!workflow) return undefined\n\n\t\t// Only WorkflowMeta carries a `triggers` map; XState workflows have none.\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- probing the workflow union for the optional WorkflowMeta triggers map\n\t\treturn (workflow as WorkflowMeta).triggers\n\t}\n\n\t/**\n\t * Returns metadata for a specific action, if available.\n\t * Only works with WorkflowMeta format; returns undefined for XState format.\n\t *\n\t * @param actionName - The action name to get metadata for\n\t * @returns Action metadata or undefined\n\t *\n\t * @example\n\t * ```ts\n\t * const actionMeta = doctype.getActionMeta('submit')\n\t * // { label: 'Submit', allowedStates: ['draft'] }\n\t * ```\n\t *\n\t * @public\n\t */\n\tgetActionMeta(actionName: string):\n\t\t| {\n\t\t\t\tlabel: string\n\t\t\t\trequiredFields?: string[]\n\t\t\t\tallowedStates?: string[]\n\t\t }\n\t\t| undefined {\n\t\tconst workflow = this.workflow\n\t\tif (!workflow) return undefined\n\n\t\t// Only WorkflowMeta carries an `actions` map (with labels); XState workflows have none.\n\t\t// Don't require a `states` array — a commands-only doctype has labeled actions but no states.\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- probing the workflow union for the optional WorkflowMeta actions map\n\t\tconst actions = (workflow as WorkflowMeta).actions\n\t\treturn actions?.[actionName]\n\t}\n\n\t/**\n\t * Converts the registered doctype string to a slug (kebab-case). The following conversions are made:\n\t * - It replaces camelCase and PascalCase with kebab-case strings\n\t * - It replaces spaces and underscores with hyphens\n\t * - It converts the string to lowercase\n\t *\n\t * @returns The slugified doctype string\n\t *\n\t * @example\n\t * ```ts\n\t * const doctype = new Doctype('TaskItem', schema, workflow, actions)\n\t * console.log(doctype.slug) // 'task-item'\n\t * ```\n\t *\n\t * @public\n\t */\n\tget slug() {\n\t\treturn this.doctype\n\t\t\t.replace(/([a-z])([A-Z])/g, '$1-$2')\n\t\t\t.replace(/[\\s_]+/g, '-')\n\t\t\t.toLowerCase()\n\t}\n}\n","import type { ResolvedField, ResolvedLink, ResolvedScalar, ResolvedTable, ResolvedFieldset } from '@stonecrop/aform'\nimport { resolvedFieldsToColumns } from '@stonecrop/aform'\nimport type { DoctypeField, LinkDeclaration, TableViewConfig, ValueField } from '@stonecrop/schema'\nimport { componentCategory, componentLinkExpansion, resolveLinkRenderMode } from '@stonecrop/schema'\nimport { Router } from 'vue-router'\n\nimport Doctype from './doctype'\nimport { RouteContext } from './types/registry'\n\n/**\n * Stonecrop Registry class\n * @public\n */\nexport default class Registry {\n\t/**\n\t * The root Registry instance\n\t */\n\tstatic _root: Registry\n\n\t/**\n\t * The name of the Registry instance\n\t *\n\t * @defaultValue 'Registry'\n\t */\n\treadonly name: string = 'Registry'\n\n\t/**\n\t * The registry property contains a collection of doctypes\n\t *\n\t * @defaultValue `{}`\n\t * @see {@link Doctype}\n\t */\n\treadonly registry: Record<string, Doctype> = {}\n\n\t/**\n\t * Reverse index: backlink fieldname → list of \\{ doctype slug, link fieldname \\}.\n\t * Multiple doctypes can declare a link with the same backlink name, so each key\n\t * maps to an array. Built at schema load time for O(1) ancestor lookups.\n\t *\n\t * @defaultValue `new Map()`\n\t * @internal\n\t */\n\tprivate _ancestorIndex: Map<string, Array<{ slug: string; fieldname: string }>> = new Map()\n\n\t/**\n\t * Whether the ancestor index needs rebuilding\n\t *\n\t * @defaultValue `true`\n\t * @internal\n\t */\n\tprivate _ancestorIndexDirty: boolean = true\n\n\t/**\n\t * The Vue router instance\n\t * @see {@link https://router.vuejs.org/}\n\t */\n\treadonly router?: Router\n\n\t/**\n\t * Creates a new Registry instance (singleton pattern)\n\t * @param router - Optional Vue router instance for route management\n\t * @param getMeta - Optional function to fetch doctype metadata from an API\n\t */\n\tconstructor(router?: Router, getMeta?: (routeContext: RouteContext) => Doctype | Promise<Doctype>) {\n\t\tif (Registry._root) {\n\t\t\treturn Registry._root\n\t\t}\n\t\tRegistry._root = this\n\t\tthis.router = router\n\t\tthis.getMeta = getMeta\n\t\treturn this\n\t}\n\n\t/**\n\t * The getMeta function fetches doctype metadata from an API based on route context\n\t * @see {@link Doctype}\n\t */\n\tgetMeta?: (routeContext: RouteContext) => Doctype | Promise<Doctype>\n\n\t/**\n\t * Get doctype metadata\n\t * @param doctype - The doctype to fetch metadata for\n\t * @returns The doctype metadata\n\t * @see {@link Doctype}\n\t */\n\taddDoctype(doctype: Doctype) {\n\t\tif (!(doctype.slug in this.registry)) {\n\t\t\tthis.registry[doctype.slug] = doctype\n\t\t\tthis._ancestorIndexDirty = true\n\t\t}\n\n\t\t// Field triggers are registered imperatively, by the app, via the FieldTriggerEngine's own\n\t\t// `registerDoctypeActions`. A doctype used to be able to declare them too, but that path\n\t\t// could not survive the wire — neither the Zod gate nor the SDL carries such a map — so it\n\t\t// only ever worked for a host bypassing both, and it left two public `runAction` methods\n\t\t// meaning opposite things. Registering here would also overwrite an app's imperative\n\t\t// registration, since `registerDoctypeActions` sets the maps even when handed nothing.\n\n\t\tif (doctype.component && this.router && !this.router.hasRoute(doctype.doctype)) {\n\t\t\tthis.router.addRoute({\n\t\t\t\tpath: `/${doctype.slug}`,\n\t\t\t\tname: doctype.slug,\n\t\t\t\tcomponent: doctype.component,\n\t\t\t})\n\t\t}\n\t}\n\n\t/**\n\t * Resolve a Doctype's authoring schema into a rendered schema array suitable for AForm.\n\t *\n\t * Transforms `DoctypeField[]` (authoring space) → `ResolvedField[]` (rendering space):\n\t * - `kind: 'field'` (not Link) → `ResolvedScalar`\n\t * - `kind: 'field'` (Link, no declaration) → `ResolvedScalar` with `component: 'AFormLink'`\n\t * - `kind: 'field'` (Link, `noneOrMany`/`atLeastOne`) → `ResolvedTable`\n\t * - `kind: 'field'` (Link, `one`/`atMostOne`) → `ResolvedLink`\n\t * - `kind: 'fieldset'` → `ResolvedFieldset` (children resolved recursively)\n\t * - `kind: 'table'` → `ResolvedTable` (columns as `ColumnSchema[]`)\n\t *\n\t * Circular references are protected against via the `visited` set.\n\t *\n\t * @param doctype - The doctype to resolve\n\t * @param visited - Internal — set of already-visited doctype slugs for cycle detection\n\t * @returns A resolved schema array ready for AForm\n\t *\n\t * @public\n\t */\n\tresolveSchema(doctype: Doctype, visited?: Set<string>): ResolvedField[] {\n\t\tconst seen = visited ?? new Set<string>()\n\t\tconst slug = doctype.slug\n\n\t\t// Prevent circular resolution — return all ValueField entries as scalars (link not expanded)\n\t\tif (seen.has(slug)) {\n\t\t\tconst fallback: DoctypeField[] = doctype.schema ? doctype.schema.toArray() : []\n\t\t\treturn fallback\n\t\t\t\t.filter((f): f is ValueField => f.kind === 'field')\n\t\t\t\t.map(({ cardinality: _c, ...rest }): ResolvedScalar => rest)\n\t\t}\n\t\tseen.add(slug)\n\n\t\tconst schemaArray: DoctypeField[] = doctype.schema ? doctype.schema.toArray() : []\n\n\t\t// Map link declarations by fieldname (link.fieldname ?? key)\n\t\tconst linksByFieldname = new Map<string, LinkDeclaration>()\n\t\tif (doctype.links) {\n\t\t\tfor (const [key, link] of Object.entries(doctype.links)) {\n\t\t\t\tlinksByFieldname.set(link.fieldname ?? key, link)\n\t\t\t}\n\t\t}\n\n\t\tconst result = this.resolveFields(schemaArray, linksByFieldname, seen)\n\t\tseen.delete(slug)\n\t\treturn result\n\t}\n\n\t/**\n\t * Recursively resolve a `DoctypeField[]` using the provided link context.\n\t * Called by `resolveSchema` and recursively for fieldset children.\n\t * @internal\n\t */\n\tprivate resolveFields(\n\t\tfields: DoctypeField[],\n\t\tlinks: Map<string, LinkDeclaration>,\n\t\tvisited: Set<string>\n\t): ResolvedField[] {\n\t\tconst resolved: ResolvedField[] = []\n\n\t\tfor (const field of fields) {\n\t\t\t// A field is a link when it carries `doctype` (the marker) or has a LinkDeclaration.\n\t\t\tconst linkDecl = field.kind === 'field' ? links.get(field.fieldname) : undefined\n\t\t\tif (field.kind === 'field' && (linkDecl || field.doctype)) {\n\t\t\t\tconst link = linkDecl\n\t\t\t\t// The declaration's target wins over the field's own `doctype`.\n\t\t\t\tconst linkTarget = link?.target ?? field.doctype\n\n\t\t\t\t// An undeclared link, or a declared one whose component renders an inline picker,\n\t\t\t\t// stays a scalar: the target is not expanded, it only needs the slug for async\n\t\t\t\t// display-text resolution and navigation.\n\t\t\t\tif (!link || resolveLinkRenderMode(link, field.component) === 'inline') {\n\t\t\t\t\tconst { cardinality: _c, ...rest } = field\n\t\t\t\t\tresolved.push({\n\t\t\t\t\t\t...rest,\n\t\t\t\t\t\tcomponent: rest.component || 'AFormLink',\n\t\t\t\t\t\t...(linkTarget !== undefined ? { doctype: linkTarget } : {}),\n\t\t\t\t\t})\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tconst targetDoctype = this.registry[link.target]\n\t\t\t\tif (!targetDoctype) {\n\t\t\t\t\t// Target not registered — copy as scalar\n\t\t\t\t\tconst { cardinality: _c, ...rest } = field\n\t\t\t\t\tresolved.push({ ...rest })\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tconst childSchema = this.resolveSchema(targetDoctype, new Set(visited))\n\t\t\t\tconst { options: _opt, cardinality: _card, kind: _kind, ...fieldRest } = field\n\n\t\t\t\tif (resolveLinkRenderMode(link, field.component) === 'table') {\n\t\t\t\t\tresolved.push(this.buildTableConfig(field, childSchema, link.component))\n\t\t\t\t} else {\n\t\t\t\t\tconst linkEntry: ResolvedLink = {\n\t\t\t\t\t\t...fieldRest,\n\t\t\t\t\t\tkind: 'link',\n\t\t\t\t\t\tlabel: fieldRest.label || field.fieldname,\n\t\t\t\t\t\tcomponent: link.component || fieldRest.component || 'AForm',\n\t\t\t\t\t\tschema: childSchema,\n\t\t\t\t\t}\n\t\t\t\t\tresolved.push(linkEntry)\n\t\t\t\t}\n\t\t\t} else if (field.kind === 'fieldset') {\n\t\t\t\tconst resolvedChildren = this.resolveFields(field.schema, links, visited)\n\t\t\t\tconst { schema: _s, ...fieldRest } = field\n\t\t\t\tconst fieldsetEntry: ResolvedFieldset = {\n\t\t\t\t\t...fieldRest,\n\t\t\t\t\tschema: resolvedChildren,\n\t\t\t\t}\n\t\t\t\tresolved.push(fieldsetEntry)\n\t\t\t} else if (field.kind === 'table') {\n\t\t\t\t// Inline table — columns become ColumnSchema[], add default config\n\t\t\t\tconst { columns, config, ...fieldRest } = field\n\t\t\t\tconst tableEntry: ResolvedTable = {\n\t\t\t\t\t...fieldRest,\n\t\t\t\t\tkind: 'table',\n\t\t\t\t\tcomponent: fieldRest.component || 'ATable',\n\t\t\t\t\tschema: columns,\n\t\t\t\t\tconfig: config ?? { view: 'list' },\n\t\t\t\t}\n\t\t\t\tresolved.push(tableEntry)\n\t\t\t} else {\n\t\t\t\t// Scalar field (kind: 'field', not a link) — strip cardinality.\n\t\t\t\t// A link-rendering component with nothing to point at renders an empty picker (or an\n\t\t\t\t// empty embedded form), which is indistinguishable from \"the record has no value\".\n\t\t\t\t// Link-ness comes from `doctype`/`links`, so this is a field that named a link\n\t\t\t\t// component and forgot the target.\n\t\t\t\tif (field.kind === 'field' && componentLinkExpansion(field.component)) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Stonecrop] Field \"${field.fieldname}\" renders with \"${field.component}\", which is a link component, ` +\n\t\t\t\t\t\t\t`but the field is not a link: it has no \\`doctype\\` and no \\`links\\` declaration. It will render ` +\n\t\t\t\t\t\t\t`as a plain field. Add \\`\"doctype\": \"<doctype-slug>\"\\` to the field definition.`\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tconst { cardinality: _c, ...rest } = field\n\t\t\t\tresolved.push({ ...rest })\n\t\t\t}\n\t\t}\n\n\t\treturn resolved\n\t}\n\n\t/**\n\t * Build a `ResolvedTable` from a resolved Link field with many cardinality.\n\t * Columns come from {@link @stonecrop/aform#resolvedFieldsToColumns}, the shared definition of\n\t * which resolved fields a cell can render.\n\t * @internal\n\t */\n\tprivate buildTableConfig(field: ValueField, childSchema: ResolvedField[], component?: string): ResolvedTable {\n\t\tconst columns = resolvedFieldsToColumns(childSchema)\n\n\t\tconst config: TableViewConfig = field.config\n\t\t\t? { fullWidth: true, ...field.config }\n\t\t\t: { view: 'list', fullWidth: true }\n\t\tconst { options: _opt, cardinality: _card, ...fieldRest } = field\n\n\t\treturn {\n\t\t\t...fieldRest,\n\t\t\tkind: 'table',\n\t\t\tlabel: fieldRest.label || field.fieldname,\n\t\t\tcomponent: component || fieldRest.component || 'ATable',\n\t\t\tschema: columns,\n\t\t\tconfig,\n\t\t}\n\t}\n\n\t/**\n\t * Initialize a new record with default values based on a resolved schema.\n\t * Narrows by `kind` discriminator for precise branch selection.\n\t *\n\t * - `kind: 'table'` or `kind: 'link'` → `[]` or `{}`\n\t * - `kind: 'fieldset'` → recursively initializes children as `{}`\n\t * - `kind: 'field'` → derives the default from the component's category; falls back to `null`\n\t *\n\t * @param schema - The resolved schema array to derive defaults from\n\t * @returns A plain object with default values for each field\n\t * @public\n\t */\n\tinitializeRecord(schema: ResolvedField[]): Record<string, any> {\n\t\tconst record: Record<string, any> = {}\n\n\t\tfor (const field of schema) {\n\t\t\tif (field.kind === 'table') {\n\t\t\t\trecord[field.fieldname] = []\n\t\t\t} else if (field.kind === 'link') {\n\t\t\t\trecord[field.fieldname] = this.initializeRecord(field.schema)\n\t\t\t} else if (field.kind === 'fieldset') {\n\t\t\t\trecord[field.fieldname] = this.initializeRecord(field.schema)\n\t\t\t} else {\n\t\t\t\t// kind: 'field' — the empty default comes from the component's category.\n\t\t\t\tconst fieldDefault = field.default\n\t\t\t\tif (fieldDefault !== undefined) {\n\t\t\t\t\trecord[field.fieldname] = fieldDefault\n\t\t\t\t} else {\n\t\t\t\t\tconst category = componentCategory(field.component)\n\t\t\t\t\tif (category === 'text') {\n\t\t\t\t\t\trecord[field.fieldname] = ''\n\t\t\t\t\t} else if (category === 'number') {\n\t\t\t\t\t\trecord[field.fieldname] = 0\n\t\t\t\t\t} else if (category === 'boolean') {\n\t\t\t\t\t\trecord[field.fieldname] = false\n\t\t\t\t\t} else if (category === 'code' && field.language) {\n\t\t\t\t\t\t// A JSON editor starts from an empty object; any other language from empty source.\n\t\t\t\t\t\trecord[field.fieldname] = field.language === 'json' ? {} : ''\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// date / datetime / select / link / attach — plus two cases with no better answer\n\t\t\t\t\t\t// than \"no value\": an unknown (custom) component, and a code field whose missing\n\t\t\t\t\t\t// `language` doesn't say which kind of empty it wants.\n\t\t\t\t\t\trecord[field.fieldname] = null\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn record\n\t}\n\n\t/**\n\t * Get a registered doctype by slug\n\t * @param slug - The doctype slug to look up\n\t * @returns The Doctype instance if found, or undefined\n\t * @public\n\t */\n\tgetDoctype(slug: string): Doctype | undefined {\n\t\treturn this.registry[slug]\n\t}\n\n\t/**\n\t * Get all links declared on a doctype.\n\t *\n\t * @param doctypeSlug - The doctype slug to get links for\n\t * @returns Array of link declarations with fieldname, or empty array if none\n\t *\n\t * @example\n\t * ```ts\n\t * const links = registry.getDescendantLinks('recipe')\n\t * // [{ fieldname: 'tasks', target: 'recipe-task', cardinality: 'noneOrMany', backlink: 'recipe' }]\n\t * ```\n\t *\n\t * @public\n\t */\n\tgetDescendantLinks(doctypeSlug: string): Array<LinkDeclaration & { fieldname: string }> {\n\t\tconst doctype = this.registry[doctypeSlug]\n\t\tif (!doctype?.links) return []\n\n\t\treturn Object.entries(doctype.links).map(([fieldname, link]) =>\n\t\t\tObject.assign({}, link, {\n\t\t\t\tfieldname,\n\t\t\t})\n\t\t)\n\t}\n\n\t/**\n\t * Get links on other doctypes that target the given doctype.\n\t *\n\t * @param doctypeSlug - The doctype slug to find ancestor links for\n\t * @returns Array of link declarations with fieldname and declaring doctype slug, or empty array\n\t *\n\t * @example\n\t * ```ts\n\t * const ancestors = registry.getAncestorLinks('recipe-task')\n\t * // [{ fieldname: 'tasks', target: 'recipe-task', cardinality: 'noneOrMany', backlink: 'recipe', doctype: 'recipe' }]\n\t * ```\n\t *\n\t * @public\n\t */\n\tgetAncestorLinks(doctypeSlug: string): Array<LinkDeclaration & { fieldname: string; doctype: string }> {\n\t\tthis._ensureAncestorIndex()\n\n\t\tconst results: Array<LinkDeclaration & { fieldname: string; doctype: string }> = []\n\n\t\tfor (const [_backlink, entries] of this._ancestorIndex) {\n\t\t\tfor (const { slug: declaringSlug, fieldname } of entries) {\n\t\t\t\tconst declaringDoctype = this.registry[declaringSlug]\n\t\t\t\tif (!declaringDoctype?.links) continue\n\n\t\t\t\tconst link = declaringDoctype.links[fieldname]\n\t\t\t\tif (link?.target === doctypeSlug) {\n\t\t\t\t\tresults.push({\n\t\t\t\t\t\t...link,\n\t\t\t\t\t\tfieldname,\n\t\t\t\t\t\tdoctype: declaringSlug,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn results\n\t}\n\n\t/**\n\t * Ensure the ancestor index is up to date\n\t * @internal\n\t */\n\tprivate _ensureAncestorIndex(): void {\n\t\tif (!this._ancestorIndexDirty) return\n\t\tthis._ancestorIndexDirty = false\n\t\tthis._ancestorIndex.clear()\n\n\t\tfor (const [slug, doctype] of Object.entries(this.registry)) {\n\t\t\tif (!doctype.links) continue\n\t\t\tfor (const [fieldname, link] of Object.entries(doctype.links)) {\n\t\t\t\tif (link.backlink) {\n\t\t\t\t\tconst existing = this._ancestorIndex.get(link.backlink)\n\t\t\t\t\tif (existing) {\n\t\t\t\t\t\texisting.push({ slug, fieldname })\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis._ancestorIndex.set(link.backlink, [{ slug, fieldname }])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO: should we allow clearing the registry at all?\n\t// clear() {\n\t// \tthis.registry = {}\n\t// \tif (this.router) {\n\t// \t\tconst routes = this.router.getRoutes()\n\t// \t\tfor (const route of routes) {\n\t// \t\t\tif (route.name) {\n\t// \t\t\t\tthis.router.removeRoute(route.name)\n\t// \t\t\t}\n\t// \t\t}\n\t// \t}\n\t// }\n}\n","import { App, type Plugin, nextTick } from 'vue'\nimport type { Pinia } from 'pinia'\n\nimport Registry from '../registry'\nimport { Stonecrop } from '../stonecrop'\nimport type { InstallOptions } from '../types'\nimport { useOperationLogStore } from '../stores/operation-log'\n\n/**\n * Setup auto-initialization for user-defined initialization logic\n * This function handles the post-mount initialization automatically\n */\nasync function setupAutoInitialization(\n\tregistry: Registry,\n\tstonecrop: Stonecrop,\n\tonRouterInitialized: (registry: Registry, stonecrop: Stonecrop) => void | Promise<void>\n) {\n\t// Wait for the next tick to ensure the app is mounted\n\tawait nextTick()\n\n\ttry {\n\t\tawait onRouterInitialized(registry, stonecrop)\n\t} catch {\n\t\t// Silent error handling - application should handle initialization errors\n\t}\n}\n\n/**\n * Stonecrop Vue plugin\n * @param app - The Vue app instance\n * @param options - The plugin options\n * @example\n * ```ts\n * import { createApp } from 'vue'\n * import Stonecrop from '@stonecrop/stonecrop'\n * import { StonecropClient } from '@stonecrop/graphql-client'\n * import router from './router'\n *\n * const client = new StonecropClient({ endpoint: '/graphql' })\n *\n * const app = createApp(App)\n * app.use(Stonecrop, {\n * router,\n * client,\n * getMeta: async (routeContext) => {\n * // routeContext contains: { path, segments }\n * // use the client to fetch doctype meta\n * return client.getMeta({ doctype: routeContext.segments[0] })\n * },\n * autoInitializeRouter: true,\n * onRouterInitialized: async (registry, stonecrop) => {\n * // your custom initialization logic here\n * }\n * })\n * app.mount('#app')\n * ```\n * @public\n */\nconst plugin: Plugin = {\n\tinstall: (app: App, options?: InstallOptions) => {\n\t\t// Check for existing router installation\n\t\tconst existingRouter = app.config.globalProperties.$router\n\t\tconst providedRouter = options?.router\n\t\tconst router = existingRouter || providedRouter\n\t\tif (!existingRouter && providedRouter) {\n\t\t\tapp.use(providedRouter)\n\t\t}\n\n\t\t// Create registry with available router\n\t\tconst registry = new Registry(router, options?.getMeta)\n\t\tapp.provide('$registry', registry)\n\t\tapp.config.globalProperties.$registry = registry\n\n\t\t// Create and provide a global Stonecrop instance\n\t\tconst stonecrop = new Stonecrop(registry)\n\t\tif (options?.client) {\n\t\t\tstonecrop.setClient(options.client)\n\t\t}\n\t\tapp.provide('$stonecrop', stonecrop)\n\t\tapp.config.globalProperties.$stonecrop = stonecrop\n\n\t\t// Initialize operation log store if Pinia is available\n\t\t// This ensures the store is created with the app's Pinia instance\n\t\ttry {\n\t\t\tconst pinia = app.config.globalProperties.$pinia as Pinia | undefined\n\t\t\tif (pinia) {\n\t\t\t\t// Initialize the operation log store with the app's Pinia instance\n\t\t\t\tconst operationLogStore = useOperationLogStore(pinia)\n\n\t\t\t\t// Provide the store so components can access it\n\t\t\t\tapp.provide('$operationLogStore', operationLogStore)\n\t\t\t\tapp.config.globalProperties.$operationLogStore = operationLogStore\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Pinia not available - operation log won't work, but app should still function\n\t\t\tconsole.warn('Pinia not available - operation log features will be disabled:', error)\n\t\t}\n\n\t\t// Register custom components\n\t\tif (options?.components) {\n\t\t\tfor (const [tag, component] of Object.entries(options.components)) {\n\t\t\t\tapp.component(tag, component)\n\t\t\t}\n\t\t}\n\n\t\t// Setup auto-initialization if requested\n\t\tif (options?.autoInitializeRouter && options.onRouterInitialized) {\n\t\t\tvoid setupAutoInitialization(registry, stonecrop, options.onRouterInitialized)\n\t\t}\n\t},\n}\n\nexport default plugin\n","import { defineStore } from 'pinia'\nimport { ref, computed } from 'vue'\n\nimport type { TriggerDefinition } from '@stonecrop/schema'\nimport { executeClientHandler } from '../client-handler'\n\n/**\n * A single validation error contributed by a trigger, displayed on a field.\n * @public\n */\nexport interface ValidationError {\n\t/** The trigger that produced this error — the namespace a re-run clears before repopulating */\n\ttrigger: string\n\t/** The fieldname the error displays on (the `setError` target, not necessarily a fired field) */\n\tfield: string\n\t/** The message to display */\n\tmessage: string\n}\n\n/**\n * Reactive per-field validation error store + the advisory field-validation trigger engine.\n *\n * Holds the errors produced by field-validation triggers (see `TriggerDefinition` in\n * `@stonecrop/schema`) and runs a trigger's `clientHandler` on demand. Errors are **namespaced\n * by trigger**: re-running a trigger clears its own prior contributions before repopulating, so a\n * corrected value clears its stale error without disturbing other triggers.\n *\n * The engine is **advisory** and does **no rollback** — an invalid value stays in the record so the\n * user can fix it; validity is reported separately via `isValid` (read by the save gate) and\n * the per-field messages are surfaced via `errorsByField` / `errorsFor` for display.\n *\n * @public\n */\nexport const useValidationStore = defineStore('stonecrop-validation', () => {\n\tconst errors = ref<ValidationError[]>([])\n\n\t/** True when no field currently carries a validation error. */\n\tconst isValid = computed(() => errors.value.length === 0)\n\n\t/** Errors grouped by field — the shape a renderer consumes (e.g. AForm `:errors`). */\n\tconst errorsByField = computed<Record<string, string[]>>(() => {\n\t\tconst map: Record<string, string[]> = {}\n\t\tfor (const e of errors.value) {\n\t\t\tif (!map[e.field]) map[e.field] = []\n\t\t\tmap[e.field].push(e.message)\n\t\t}\n\t\treturn map\n\t})\n\n\t/** Messages currently displayed on `field`. */\n\tfunction errorsFor(field: string): string[] {\n\t\treturn errors.value.filter(e => e.field === field).map(e => e.message)\n\t}\n\n\t/** Record an error contributed by `trigger`, displayed on `field`. */\n\tfunction setError(trigger: string, field: string, message: string) {\n\t\terrors.value.push({ trigger, field, message })\n\t}\n\n\t/** Remove every error contributed by `trigger` (its namespace). */\n\tfunction clearTrigger(trigger: string) {\n\t\terrors.value = errors.value.filter(e => e.trigger !== trigger)\n\t}\n\n\t/** Remove every validation error. */\n\tfunction clearAll() {\n\t\terrors.value = []\n\t}\n\n\t/**\n\t * Run a single trigger against a read-only snapshot of `record`. Clears the trigger's prior\n\t * errors, then executes its `clientHandler` with `{ record, value, setError }`. Fails **open** —\n\t * a throwing validator warns and records nothing, so a broken validator never blocks the user.\n\t */\n\tasync function runTrigger(name: string, def: TriggerDefinition, record: Record<string, unknown>, value: unknown) {\n\t\tclearTrigger(name)\n\t\t// Shallow-frozen copy: the validator reads siblings but can neither mutate the record nor\n\t\t// reassign fields (advisory reads only) — and mutation can't leak back to the caller.\n\t\tconst frozen = Object.freeze({ ...record })\n\t\tconst boundSetError = (field: string, message: string) => setError(name, field, message)\n\t\ttry {\n\t\t\tawait executeClientHandler(def.clientHandler, { record: frozen, value, setError: boundSetError })\n\t\t} catch (error) {\n\t\t\t// Advisory by design: a broken validator must never block save (a bug in one trigger must\n\t\t\t// not trap the user, especially in production). It fails OPEN — but a throw is an error in\n\t\t\t// the author's code, so surface it loudly (error severity, trigger named) rather than\n\t\t\t// silently: a broken validator that just \"does nothing\" is the real footgun here.\n\t\t\tif (typeof console !== 'undefined') {\n\t\t\t\tconsole.error(\n\t\t\t\t\t`Validation trigger \"${name}\" threw and was ignored (advisory — save is not blocked). ` +\n\t\t\t\t\t\t`Fix its clientHandler:`,\n\t\t\t\t\terror\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Run every trigger whose `on` set includes `changedField`, passing that field's current value.\n\t * Call on the edit path (desktop-driven) so editing either bound field re-validates the pair.\n\t */\n\tasync function validateField(\n\t\ttriggers: Record<string, TriggerDefinition>,\n\t\tchangedField: string,\n\t\trecord: Record<string, unknown>\n\t): Promise<void> {\n\t\tconst runs: Promise<void>[] = []\n\t\tfor (const [name, def] of Object.entries(triggers)) {\n\t\t\tif (def.on.includes(changedField)) {\n\t\t\t\truns.push(runTrigger(name, def, record, record[changedField]))\n\t\t\t}\n\t\t}\n\t\tawait Promise.all(runs)\n\t}\n\n\t/**\n\t * Run **all** triggers (no fired-field filter) — the authoritative client gate at save-attempt,\n\t * covering triggers whose fields were never edited. `value` is undefined (no single changed field).\n\t */\n\tasync function validateRecord(\n\t\ttriggers: Record<string, TriggerDefinition>,\n\t\trecord: Record<string, unknown>\n\t): Promise<void> {\n\t\tawait Promise.all(Object.entries(triggers).map(([name, def]) => runTrigger(name, def, record, undefined)))\n\t}\n\n\treturn {\n\t\terrors,\n\t\tisValid,\n\t\terrorsByField,\n\t\terrorsFor,\n\t\tsetError,\n\t\tclearTrigger,\n\t\tclearAll,\n\t\tvalidateField,\n\t\tvalidateRecord,\n\t}\n})\n","import type Registry from '../registry'\n\n/**\n * Validation severity levels\n * @public\n */\nexport enum ValidationSeverity {\n\t/** Blocking error that prevents save */\n\tERROR = 'error',\n\t/** Advisory warning that allows save */\n\tWARNING = 'warning',\n\t/** Informational message */\n\tINFO = 'info',\n}\n\n/**\n * Validation issue\n * @public\n */\nexport interface ValidationIssue {\n\t/** Severity level */\n\tseverity: ValidationSeverity\n\t/** Validation rule that failed */\n\trule: string\n\t/** Human-readable message */\n\tmessage: string\n\t/** Doctype name */\n\tdoctype?: string\n\t/** Field name if applicable */\n\tfieldname?: string\n\t/** Additional context */\n\tcontext?: Record<string, unknown>\n}\n\n/**\n * Validation result\n * @public\n */\nexport interface ValidationResult {\n\t/** Whether validation passed (no blocking errors) */\n\tvalid: boolean\n\t/** List of validation issues */\n\tissues: ValidationIssue[]\n\t/** Count of errors */\n\terrorCount: number\n\t/** Count of warnings */\n\twarningCount: number\n\t/** Count of info messages */\n\tinfoCount: number\n}\n\n/**\n * Schema validator options\n * @public\n */\nexport interface ValidatorOptions {\n\t/** Registry instance for doctype lookups */\n\tregistry?: Registry\n\t/** Whether to validate Link field targets */\n\tvalidateLinkTargets?: boolean\n\t/** Whether to validate links object (target resolution, backlink consistency, Link field correspondence) */\n\tvalidateLinks?: boolean\n\t/** Whether to validate workflow reachability */\n\tvalidateWorkflows?: boolean\n\t/** Whether to validate action registration */\n\tvalidateActions?: boolean\n\t/** Whether to validate required schema properties */\n\tvalidateRequiredProperties?: boolean\n}\n","/**\n * Schema Validation Utilities\n * Validates Stonecrop schemas for integrity and consistency\n * @packageDocumentation\n */\n\nimport type { DoctypeField } from '@stonecrop/schema'\nimport type { LinkDeclaration } from '@stonecrop/schema'\nimport { componentLinkExpansion } from '@stonecrop/schema'\nimport type { List, Map as ImmutableMap } from 'immutable'\nimport type { AnyStateNodeConfig } from 'xstate'\n\nimport { getGlobalTriggerEngine } from './field-triggers'\nimport type Registry from './registry'\nimport { ValidationSeverity } from './types/schema-validator'\nimport type { ValidationIssue, ValidationResult, ValidatorOptions } from './types/schema-validator'\n\n/**\n * Schema validator class\n * @public\n */\nexport class SchemaValidator {\n\tprivate options: Required<ValidatorOptions>\n\n\t/**\n\t * Creates a new SchemaValidator instance\n\t * @param options - Validator configuration options\n\t */\n\tconstructor(options: ValidatorOptions = {}) {\n\t\tthis.options = {\n\t\t\tregistry: options.registry || null!,\n\t\t\tvalidateLinkTargets: options.validateLinkTargets ?? true,\n\t\t\tvalidateLinks: options.validateLinks ?? true,\n\t\t\tvalidateActions: options.validateActions ?? true,\n\t\t\tvalidateWorkflows: options.validateWorkflows ?? true,\n\t\t\tvalidateRequiredProperties: options.validateRequiredProperties ?? true,\n\t\t}\n\t}\n\n\t/**\n\t * Validates a complete doctype schema\n\t * @param doctype - Doctype name\n\t * @param schema - Schema fields (List or Array)\n\t * @param workflow - Optional workflow configuration\n\t * @param actions - Optional actions map\n\t * @param links - Optional links object\n\t * @returns Validation result\n\t */\n\tvalidate(\n\t\tdoctype: string,\n\t\tschema: List<DoctypeField> | DoctypeField[] | undefined,\n\t\tworkflow?: AnyStateNodeConfig,\n\t\tactions?: ImmutableMap<string, string[]> | Map<string, string[]>,\n\t\tlinks?: Record<string, LinkDeclaration>\n\t): ValidationResult {\n\t\tconst issues: ValidationIssue[] = []\n\n\t\t// Convert schema to array for easier iteration\n\t\tconst schemaArray = schema ? (Array.isArray(schema) ? schema : schema.toArray()) : []\n\n\t\t// Validate required properties\n\t\tif (this.options.validateRequiredProperties) {\n\t\t\tissues.push(...this.validateRequiredProperties(doctype, schemaArray, links))\n\t\t}\n\n\t\t// Validate Link field targets\n\t\tif (this.options.validateLinkTargets && this.options.registry) {\n\t\t\tissues.push(...this.validateLinkFields(doctype, schemaArray, this.options.registry))\n\t\t}\n\n\t\t// Validate links object\n\t\tif (this.options.validateLinks && this.options.registry && links) {\n\t\t\tissues.push(...this.validateLinkDeclarations(doctype, links, schemaArray, this.options.registry))\n\t\t}\n\n\t\t// Validate workflow configuration\n\t\tif (this.options.validateWorkflows && workflow) {\n\t\t\tissues.push(...this.validateWorkflow(doctype, workflow))\n\t\t}\n\n\t\t// Validate action registration\n\t\tif (this.options.validateActions && actions) {\n\t\t\tconst actionsMap = actions instanceof Map ? actions : actions.toObject()\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- toObject() returns plain object; runtime-safe cast for Map<string, string[]>\n\t\t\tissues.push(...this.validateActionRegistration(doctype, actionsMap as Record<string, string[]>))\n\t\t}\n\n\t\t// Calculate counts\n\t\tconst errorCount = issues.filter(i => i.severity === ValidationSeverity.ERROR).length\n\t\tconst warningCount = issues.filter(i => i.severity === ValidationSeverity.WARNING).length\n\t\tconst infoCount = issues.filter(i => i.severity === ValidationSeverity.INFO).length\n\n\t\treturn {\n\t\t\tvalid: errorCount === 0,\n\t\t\tissues,\n\t\t\terrorCount,\n\t\t\twarningCount,\n\t\t\tinfoCount,\n\t\t}\n\t}\n\n\t/**\n\t * Validates that required schema properties are present\n\t * @internal\n\t */\n\tprivate validateRequiredProperties(\n\t\tdoctype: string,\n\t\tschema: DoctypeField[],\n\t\tlinks?: Record<string, LinkDeclaration>\n\t): ValidationIssue[] {\n\t\tconst issues: ValidationIssue[] = []\n\n\t\tfor (const field of schema) {\n\t\t\t// Check for fieldname\n\t\t\tif (!field.fieldname) {\n\t\t\t\tissues.push({\n\t\t\t\t\tseverity: ValidationSeverity.ERROR,\n\t\t\t\t\trule: 'required-fieldname',\n\t\t\t\t\tmessage: 'Field is missing required property: fieldname',\n\t\t\t\t\tdoctype,\n\t\t\t\t\tcontext: { field },\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// A value field renders through its component and has no other rendering axis;\n\t\t\t// fieldset/table have their own structural requirements.\n\t\t\tif (field.kind === 'field' && !field.component) {\n\t\t\t\tissues.push({\n\t\t\t\t\tseverity: ValidationSeverity.ERROR,\n\t\t\t\t\trule: 'required-component',\n\t\t\t\t\tmessage: `Field \"${field.fieldname}\" must have a component property`,\n\t\t\t\t\tdoctype,\n\t\t\t\t\tfieldname: field.fieldname,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// A link component with nothing to point at renders an empty picker, which looks exactly\n\t\t\t// like a record that has no value — so this fails silently at runtime rather than loudly.\n\t\t\t// Link-ness comes from `doctype` or a `links` declaration, so this is a field that named\n\t\t\t// a link component and gave it neither.\n\t\t\tif (\n\t\t\t\tfield.kind === 'field' &&\n\t\t\t\tcomponentLinkExpansion(field.component) &&\n\t\t\t\t!field.doctype &&\n\t\t\t\t!links?.[field.fieldname]\n\t\t\t) {\n\t\t\t\tissues.push({\n\t\t\t\t\tseverity: ValidationSeverity.ERROR,\n\t\t\t\t\trule: 'link-component-without-doctype',\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t`Field \"${field.fieldname}\" renders with \"${field.component}\", which is a link component, ` +\n\t\t\t\t\t\t`but has no \\`doctype\\` to name its target`,\n\t\t\t\t\tdoctype,\n\t\t\t\t\tfieldname: field.fieldname,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// Validate nested schemas recursively (fieldset only; table columns are ColumnSchema not DoctypeField)\n\t\t\tif (field.kind === 'fieldset') {\n\t\t\t\tissues.push(...this.validateRequiredProperties(doctype, field.schema, links))\n\t\t\t}\n\t\t}\n\n\t\treturn issues\n\t}\n\n\t/**\n\t * Validates Link field targets exist in registry\n\t * @internal\n\t */\n\tprivate validateLinkFields(doctype: string, schema: DoctypeField[], registry: Registry): ValidationIssue[] {\n\t\tconst issues: ValidationIssue[] = []\n\n\t\tfor (const field of schema) {\n\t\t\t// `doctype` is both the link marker and its target, and the schema types it as a\n\t\t\t// non-empty string — so there is no \"missing target\" or \"malformed target\" state left\n\t\t\t// to check here. The rules that did (`link-missing-options`, `link-invalid-options`)\n\t\t\t// were removed with the `options`-as-link-target convention; the case they actually\n\t\t\t// guarded — a link component with no target — is now `link-component-without-doctype`,\n\t\t\t// which fires in validateRequiredProperties whether or not a registry is configured.\n\t\t\tif (field.kind === 'field' && field.doctype) {\n\t\t\t\tconst targetDoctype = field.doctype\n\t\t\t\tconst targetMeta = registry.registry[targetDoctype] || registry.registry[targetDoctype.toLowerCase()]\n\n\t\t\t\tif (!targetMeta) {\n\t\t\t\t\tissues.push({\n\t\t\t\t\t\tseverity: ValidationSeverity.ERROR,\n\t\t\t\t\t\trule: 'link-invalid-target',\n\t\t\t\t\t\tmessage: `Link field \"${field.fieldname}\" references non-existent doctype: \"${targetDoctype}\"`,\n\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\tfieldname: field.fieldname,\n\t\t\t\t\t\tcontext: { targetDoctype },\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Recursively check nested fieldset schemas\n\t\t\tif (field.kind === 'fieldset') {\n\t\t\t\tissues.push(...this.validateLinkFields(doctype, field.schema, registry))\n\t\t\t}\n\t\t}\n\n\t\treturn issues\n\t}\n\n\t/**\n\t * Validates link declarations: target resolution, backlink consistency, Link field correspondence\n\t * @internal\n\t */\n\tprivate validateLinkDeclarations(\n\t\tdoctype: string,\n\t\tlinks: Record<string, LinkDeclaration>,\n\t\tschema: DoctypeField[],\n\t\tregistry: Registry\n\t): ValidationIssue[] {\n\t\tconst issues: ValidationIssue[] = []\n\n\t\t// Build a map of link fields by fieldname for quick lookup\n\t\tconst linkFieldsByFieldname = new Map<string, DoctypeField>()\n\t\tfor (const field of schema) {\n\t\t\tif (field.kind === 'field' && field.doctype) {\n\t\t\t\tlinkFieldsByFieldname.set(field.fieldname, field)\n\t\t\t}\n\t\t}\n\n\t\tfor (const [fieldname, link] of Object.entries(links)) {\n\t\t\t// Check target resolves in registry\n\t\t\tconst targetDoctype = registry.registry[link.target]\n\t\t\tif (!targetDoctype) {\n\t\t\t\tissues.push({\n\t\t\t\t\tseverity: ValidationSeverity.ERROR,\n\t\t\t\t\trule: 'link-invalid-target',\n\t\t\t\t\tmessage: `Link \"${fieldname}\" references non-existent doctype: \"${link.target}\"`,\n\t\t\t\t\tdoctype,\n\t\t\t\t\tfieldname,\n\t\t\t\t\tcontext: { target: link.target },\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Warn on self-referential target\n\t\t\tif (link.target === doctype) {\n\t\t\t\tissues.push({\n\t\t\t\t\tseverity: ValidationSeverity.WARNING,\n\t\t\t\t\trule: 'link-self-referential',\n\t\t\t\t\tmessage: `Link \"${fieldname}\" is self-referential (target: \"${link.target}\")`,\n\t\t\t\t\tdoctype,\n\t\t\t\t\tfieldname,\n\t\t\t\t\tcontext: { target: link.target },\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// Check backlink consistency\n\t\t\tif (link.backlink && targetDoctype.links) {\n\t\t\t\tconst reciprocalLink = targetDoctype.links[link.backlink]\n\t\t\t\tif (!reciprocalLink) {\n\t\t\t\t\tissues.push({\n\t\t\t\t\t\tseverity: ValidationSeverity.ERROR,\n\t\t\t\t\t\trule: 'link-backlink-missing',\n\t\t\t\t\t\tmessage: `Backlink \"${link.backlink}\" not found on target doctype \"${link.target}\"`,\n\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\tfieldname,\n\t\t\t\t\t\tcontext: { backlink: link.backlink, target: link.target },\n\t\t\t\t\t})\n\t\t\t\t} else if (reciprocalLink.target !== doctype) {\n\t\t\t\t\tissues.push({\n\t\t\t\t\t\tseverity: ValidationSeverity.WARNING,\n\t\t\t\t\t\trule: 'link-backlink-mismatch',\n\t\t\t\t\t\tmessage: `Backlink \"${link.backlink}\" on \"${link.target}\" points to \"${reciprocalLink.target}\" instead of \"${doctype}\"`,\n\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\tfieldname,\n\t\t\t\t\t\tcontext: { backlink: link.backlink, target: link.target, actualTarget: reciprocalLink.target },\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If Link field exists with same fieldname, verify it has matching target\n\t\t\t// Only check if link has fieldname set (otherwise it's a standalone link without a field)\n\t\t\tif (link.fieldname) {\n\t\t\t\tconst linkField = linkFieldsByFieldname.get(link.fieldname)\n\t\t\t\tif (linkField && linkField.kind === 'field') {\n\t\t\t\t\t// Map membership implies `doctype` is set — that is the map's build condition.\n\t\t\t\t\tconst linkFieldTarget = linkField.doctype\n\t\t\t\t\tif (linkFieldTarget && linkFieldTarget !== link.target) {\n\t\t\t\t\t\tissues.push({\n\t\t\t\t\t\t\tseverity: ValidationSeverity.ERROR,\n\t\t\t\t\t\t\trule: 'link-field-target-mismatch',\n\t\t\t\t\t\t\tmessage: `Link field \"${link.fieldname}\" targets \"${linkFieldTarget}\" but link declaration targets \"${link.target}\"`,\n\t\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\t\tfieldname: link.fieldname,\n\t\t\t\t\t\t\tcontext: { linkFieldTarget, linkTarget: link.target },\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// NOTE: there is deliberately no \"every link field needs a declaration\" rule. A plain foreign\n\t\t// key is a link with no `links` entry — the map is additive, carrying expansion metadata\n\t\t// (backlink/fetch/cardinality), and is not required. Such a rule would contradict\n\t\t// `Registry.resolveFields`, which resolves undeclared links to inline pickers, and would flag\n\t\t// every doctype that mixes an expanded relation with a plain FK (e.g. `country`: a `links`\n\t\t// map for states/languages/subdivisions plus a plain `continent` picker).\n\n\t\treturn issues\n\t}\n\n\t/**\n\t * Validates workflow state machine configuration\n\t * @internal\n\t */\n\tprivate validateWorkflow(doctype: string, workflow: AnyStateNodeConfig): ValidationIssue[] {\n\t\tconst issues: ValidationIssue[] = []\n\n\t\t// Check for initial state\n\t\tif (!workflow.initial && !workflow.type) {\n\t\t\tissues.push({\n\t\t\t\tseverity: ValidationSeverity.WARNING,\n\t\t\t\trule: 'workflow-missing-initial',\n\t\t\t\tmessage: 'Workflow is missing initial state property',\n\t\t\t\tdoctype,\n\t\t\t})\n\t\t}\n\n\t\t// Check for states\n\t\tif (!workflow.states || Object.keys(workflow.states).length === 0) {\n\t\t\tissues.push({\n\t\t\t\tseverity: ValidationSeverity.WARNING,\n\t\t\t\trule: 'workflow-no-states',\n\t\t\t\tmessage: 'Workflow has no states defined',\n\t\t\t\tdoctype,\n\t\t\t})\n\t\t\treturn issues\n\t\t}\n\n\t\t// Validate initial state exists\n\t\tif (workflow.initial && typeof workflow.initial === 'string' && !workflow.states[workflow.initial]) {\n\t\t\tissues.push({\n\t\t\t\tseverity: ValidationSeverity.ERROR,\n\t\t\t\trule: 'workflow-invalid-initial',\n\t\t\t\tmessage: `Workflow initial state \"${workflow.initial}\" does not exist in states`,\n\t\t\t\tdoctype,\n\t\t\t\tcontext: { initialState: workflow.initial },\n\t\t\t})\n\t\t}\n\n\t\t// Check state reachability (simple check - all states should have at least one incoming transition or be initial)\n\t\tconst stateNames = Object.keys(workflow.states)\n\t\tconst reachableStates = new Set<string>()\n\n\t\t// Initial state is always reachable\n\t\tif (workflow.initial && typeof workflow.initial === 'string') {\n\t\t\treachableStates.add(workflow.initial)\n\t\t}\n\n\t\t// Find all target states from transitions\n\t\tfor (const [_stateName, stateConfig] of Object.entries(workflow.states)) {\n\t\t\tconst state = stateConfig as AnyStateNodeConfig\n\t\t\tif (state.on) {\n\t\t\t\tfor (const [_event, transition] of Object.entries(state.on)) {\n\t\t\t\t\tif (typeof transition === 'string') {\n\t\t\t\t\t\treachableStates.add(transition)\n\t\t\t\t\t} else if (transition && typeof transition === 'object') {\n\t\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- 'target' in transition guard confirms property; accessing unknown-typed target safely\n\t\t\t\t\t\tconst target = 'target' in transition ? (transition as { target: unknown }).target : undefined\n\t\t\t\t\t\tif (typeof target === 'string') {\n\t\t\t\t\t\t\treachableStates.add(target)\n\t\t\t\t\t\t} else if (Array.isArray(target)) {\n\t\t\t\t\t\t\ttarget.forEach((t: unknown) => {\n\t\t\t\t\t\t\t\tif (typeof t === 'string') {\n\t\t\t\t\t\t\t\t\treachableStates.add(t)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check for unreachable states\n\t\tfor (const stateName of stateNames) {\n\t\t\tif (!reachableStates.has(stateName)) {\n\t\t\t\tissues.push({\n\t\t\t\t\tseverity: ValidationSeverity.WARNING,\n\t\t\t\t\trule: 'workflow-unreachable-state',\n\t\t\t\t\tmessage: `Workflow state \"${stateName}\" may not be reachable`,\n\t\t\t\t\tdoctype,\n\t\t\t\t\tcontext: { stateName },\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\treturn issues\n\t}\n\n\t/**\n\t * Validates that actions are registered in the FieldTriggerEngine\n\t * @internal\n\t */\n\tprivate validateActionRegistration(doctype: string, actions: Record<string, string[]>): ValidationIssue[] {\n\t\tconst issues: ValidationIssue[] = []\n\t\tconst triggerEngine = getGlobalTriggerEngine()\n\n\t\tfor (const [triggerName, actionNames] of Object.entries(actions)) {\n\t\t\tif (!Array.isArray(actionNames)) {\n\t\t\t\tissues.push({\n\t\t\t\t\tseverity: ValidationSeverity.ERROR,\n\t\t\t\t\trule: 'action-invalid-format',\n\t\t\t\t\tmessage: `Action configuration for \"${triggerName}\" must be an array`,\n\t\t\t\t\tdoctype,\n\t\t\t\t\tcontext: { triggerName, actionNames },\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Check each action name\n\t\t\tfor (const actionName of actionNames) {\n\t\t\t\t// Check if action is registered globally\n\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- introspecting FieldTriggerEngine private fields for validation; no public API for this check\n\t\t\t\tconst engine = triggerEngine as unknown as {\n\t\t\t\t\tglobalActions?: Map<string, unknown>\n\t\t\t\t\tglobalTransitionActions?: Map<string, unknown>\n\t\t\t\t}\n\t\t\t\tconst isRegistered = engine.globalActions?.has(actionName) || engine.globalTransitionActions?.has(actionName)\n\n\t\t\t\tif (!isRegistered) {\n\t\t\t\t\tissues.push({\n\t\t\t\t\t\tseverity: ValidationSeverity.WARNING,\n\t\t\t\t\t\trule: 'action-not-registered',\n\t\t\t\t\t\tmessage: `Action \"${actionName}\" referenced in \"${triggerName}\" is not registered in FieldTriggerEngine`,\n\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\tcontext: { triggerName, actionName },\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn issues\n\t}\n}\n\n/**\n * Creates a validator with the given registry\n * @param registry - Registry instance\n * @param options - Additional validator options\n * @returns SchemaValidator instance\n * @public\n */\nexport function createValidator(registry: Registry, options?: Partial<ValidatorOptions>): SchemaValidator {\n\treturn new SchemaValidator({\n\t\tregistry,\n\t\t...options,\n\t})\n}\n\n/**\n * Quick validation helper\n * @param doctype - Doctype name\n * @param schema - Schema fields\n * @param registry - Registry instance\n * @param workflow - Optional workflow configuration\n * @param actions - Optional actions map\n * @returns Validation result\n * @public\n */\nexport function validateSchema(\n\tdoctype: string,\n\tschema: List<DoctypeField> | DoctypeField[] | undefined,\n\tregistry: Registry,\n\tworkflow?: AnyStateNodeConfig,\n\tactions?: ImmutableMap<string, string[]> | Map<string, string[]>\n): ValidationResult {\n\tconst validator = createValidator(registry)\n\treturn validator.validate(doctype, schema, workflow, actions)\n}\n","export type * from '@stonecrop/aform/types'\nexport type * from '@stonecrop/atable/types'\n\nimport { useClientAction } from './client-action'\nimport { executeClientHandler } from './client-handler'\nimport { useLazyLink } from './composables/lazy-link'\nimport { useStonecrop } from './composables/stonecrop'\nimport { useOperationLog, useUndoRedoShortcuts, withBatch } from './composables/operation-log'\nimport Doctype from './doctype'\nimport { DRAFT_RECORD_ID, isDraftRecordId } from './draft'\nimport {\n\tFieldTriggerEngine,\n\tgetGlobalTriggerEngine,\n\tmarkOperationIrreversible,\n\tregisterGlobalAction,\n\tregisterTransitionAction,\n\tsetFieldRollback,\n\ttriggerTransition,\n} from './field-triggers'\nimport plugin from './plugins'\nimport Registry from './registry'\nimport { Stonecrop } from './stonecrop'\nimport { HST, createHST, type HSTNode } from './stores/hst'\nimport { useOperationLogStore } from './stores/operation-log'\nimport { useValidationStore } from './stores/validation'\nimport { SchemaValidator, createValidator, validateSchema } from './schema-validator'\nimport { ValidationSeverity } from './types/schema-validator'\n\n// Export all types from ./types\nexport type * from './types'\n\n// clientHandler executor types\nexport type { ClientHandlerApi } from './client-handler'\n\n// Field-validation store types\nexport type { ValidationError } from './stores/validation'\n\n// Export enum as value (enums need runtime export, not just type)\nexport { ValidationSeverity }\n\nexport {\n\tDoctype,\n\tRegistry,\n\tStonecrop,\n\t// Unsaved-record identity, shared with the desktop shell\n\tDRAFT_RECORD_ID,\n\tisDraftRecordId,\n\tuseLazyLink,\n\tuseStonecrop,\n\t// clientHandler executor\n\texecuteClientHandler,\n\t// The one blessed write path, shared by every Vue host\n\tuseClientAction,\n\t// HST exports for advanced usage\n\tHST,\n\tcreateHST,\n\tHSTNode,\n\t// Field trigger system exports\n\tFieldTriggerEngine,\n\tgetGlobalTriggerEngine,\n\tregisterGlobalAction,\n\tregisterTransitionAction,\n\tsetFieldRollback,\n\ttriggerTransition,\n\tmarkOperationIrreversible,\n\t// Schema validator exports\n\tSchemaValidator,\n\tcreateValidator,\n\tvalidateSchema,\n\t// Operation log exports\n\tuseOperationLog,\n\tuseOperationLogStore,\n\tuseUndoRedoShortcuts,\n\twithBatch,\n\t// Field-validation store\n\tuseValidationStore,\n\t// Utility functions\n}\n\n// Default export is the Vue plugin\nexport default plugin\n"],"mappings":";;;;;;;;AAkBA,IAAM,gBAAgB,OAAO,eAAe,YAAY,CAAC,CAAC,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgC5D,eAAsB,qBAAqB,MAAc,MAAwB,CAAC,GAAqB;CACtG,MAAM,QAAQ,OAAO,KAAK,GAAG;CAE7B,OAAO,IADQ,cAAc,GAAG,OAAO,IAChC,CAAA,CAAG,GAAG,MAAM,KAAI,SAAQ,IAAI,KAAK,CAAC;AAC1C;;;;;;;;;;;;;;;;;;;;;;;ACjCA,IAAa,kBAAkB;;;;;;;;;;;;;AAc/B,SAAgB,gBAAgB,UAA8C;CAC7E,OAAO,aAAA;AACR;;;;;;ACnBA,SAAS,aAAqB;CAC7B,IAAI,OAAO,WAAW,eAAe,OAAO,YAC3C,OAAO,OAAO,WAAW;CAG1B,OAAO,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,UAAU,GAAG,CAAC;AAClE;AAaA,SAAS,sBAAsB,SAAqD;CACnF,MAAM,aAAwC;EAC7C,MAAM,QAAQ;EACd,UAAU,QAAQ;EAClB,WAAW,QAAQ,UAAU,YAAY;CAC1C;CAEA,IAAI,QAAQ,WACX,WAAW,YAA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