@case-framework/survey-core 0.7.0 → 0.9.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":"editor.mjs","names":[],"sources":["../src/editor/item-copy-paste.ts","../src/editor/undo-redo.ts","../src/editor/survey-editor.ts"],"sourcesContent":["import { Survey } from \"../survey/survey\";\nimport { SurveyItemCore } from \"../survey/items\";\nimport { GroupItemCore } from \"../survey/registry/built-in-items\";\nimport { ReservedSurveyItemTypes } from \"../survey/items/types\";\nimport { SurveyItemTranslations, JsonComponentContent } from \"../survey/utils\";\nimport { RawSurveyItem } from \"../survey/items/survey-item-json\";\nimport { Target } from \"./types\";\nimport { generateId } from \"../utils\";\n\n// Serialized translation data format for clipboard\nexport type SerializedTranslations = {\n [locale: string]: JsonComponentContent;\n};\n\n// Clipboard data structure for copy-paste functionality\nexport interface SurveyItemClipboardData {\n type: \"survey-item\";\n version: string;\n items: Array<{\n itemId: string;\n itemData: RawSurveyItem;\n }>;\n translations: { [itemId: string]: SerializedTranslations };\n rootItemId: string; // The id of the main item being copied\n timestamp: number;\n}\n\nexport class ItemCopyPaste {\n private survey: Survey;\n\n constructor(survey: Survey) {\n this.survey = survey;\n }\n\n /**\n * Copy a survey item and all its data to clipboard format\n * When copying a group, automatically includes all items in the subtree\n * @param itemId - The id of the item to copy\n * @returns Clipboard data that can be serialized to JSON for clipboard\n */\n copyItem(itemId: string): SurveyItemClipboardData {\n const item = this.survey.surveyItems.get(itemId);\n if (!item) {\n throw new Error(`Item with id '${itemId}' not found`);\n }\n\n // Collect all items to copy (including subtree for groups)\n const itemsToCopy = this.collectItemsForCopy(itemId);\n\n // Create items array with their data\n const items = itemsToCopy.map((id) => {\n const item = this.survey.surveyItems.get(id);\n if (!item) throw new Error(`Item with id '${id}' not found during copy`);\n return { itemId: id, itemData: item.rawItem };\n });\n\n // Collect translations for all items\n const translations: { [itemId: string]: SerializedTranslations } = {};\n itemsToCopy.forEach((id) => {\n try {\n const itemTranslations = this.survey.getItemTranslations(id);\n if (itemTranslations?.locales?.length) {\n const serializedTranslations: SerializedTranslations = {};\n itemTranslations.locales.forEach((locale) => {\n const localeContent = itemTranslations.getAllForLocale(locale);\n if (localeContent) {\n serializedTranslations[locale] = localeContent;\n }\n });\n translations[id] = serializedTranslations;\n } else {\n translations[id] = {};\n }\n } catch {\n translations[id] = {};\n }\n });\n\n // Create clipboard data\n const clipboardData: SurveyItemClipboardData = {\n type: \"survey-item\",\n version: \"1.0.0\",\n items: items,\n translations: translations,\n rootItemId: itemId,\n timestamp: Date.now(),\n };\n\n return clipboardData;\n }\n\n /**\n * Collect all items that should be copied, including subtree for groups\n * @param itemId - The root item id\n * @returns Array of item keys to copy\n */\n private collectItemsForCopy(itemId: string): string[] {\n const itemsToCopy: string[] = [itemId];\n const item = this.survey.surveyItems.get(itemId);\n\n if (!item) {\n return [];\n }\n\n // If this is a group item, collect all child items recursively\n if (item instanceof GroupItemCore) {\n const childIds = item.items;\n if (childIds.length > 0) {\n childIds.forEach((childId) => {\n const childItems = this.collectItemsForCopy(childId);\n itemsToCopy.push(...childItems);\n });\n }\n }\n\n return itemsToCopy;\n }\n\n /**\n * Add an item to its parent group.\n * Ensures key uniqueness among siblings.\n * @param target - Target location information\n * @param item - The item to add (may have key adjusted for uniqueness)\n */\n private addItemToParentGroup(target: Target, item: SurveyItemCore): void {\n const parentGroup = this.survey.surveyItems.get(target.parentId);\n\n if (!parentGroup) {\n throw new Error(`Parent item with id '${target.parentId}' not found`);\n }\n\n if (!(parentGroup instanceof GroupItemCore)) {\n throw new Error(`Parent item '${target.parentId}' is not a group item`);\n }\n\n const siblingIds = parentGroup.items;\n const siblings = siblingIds\n .map((id) => this.survey.surveyItems.get(id))\n .filter((s): s is SurveyItemCore => s !== undefined);\n const siblingKeys = new Set(siblings.map((s) => s.key));\n\n let uniqueKey = item.key;\n if (siblingKeys.has(uniqueKey)) {\n let counter = 1;\n const originalKey = item.key;\n while (siblingKeys.has(uniqueKey)) {\n uniqueKey = originalKey + `_${counter}`;\n counter++;\n }\n if (uniqueKey !== item.key) {\n const updatedRawItem = { ...item.rawItem, key: uniqueKey };\n const newItem = this.survey.createItemFromRaw(updatedRawItem);\n this.survey.surveyItems.delete(item.id);\n this.survey.surveyItems.set(newItem.id, newItem);\n item = newItem;\n }\n }\n\n const insertIndex =\n target.index !== undefined\n ? Math.min(target.index, parentGroup.items.length)\n : parentGroup.items.length;\n\n parentGroup.addChild(item.id, insertIndex);\n }\n\n /**\n * Paste a survey item from clipboard data to a target location\n * Handles multiple items and subtrees from the clipboard data\n * @param clipboardData - The clipboard data containing the item(s) to paste\n * @param target - Target location where to paste the item\n * @returns The id of the pasted root item\n */\n pasteItem(clipboardData: SurveyItemClipboardData, target: Target): string {\n // Validate clipboard data\n if (!ItemCopyPaste.isValidClipboardData(clipboardData)) {\n throw new Error(\"Invalid clipboard data format\");\n }\n\n // Create id mapping for all items in the subtree\n const idMapping: { [oldId: string]: string } = {};\n clipboardData.items.forEach(({ itemId }) => {\n idMapping[itemId] = generateId();\n });\n\n // Create all items with updated ids\n clipboardData.items.forEach(({ itemId, itemData }) => {\n const newId = idMapping[itemId];\n if (newId) {\n const updatedItemData = this.updateItemIdsInData(itemData, idMapping);\n updatedItemData.id = newId;\n\n const newItem = this.survey.createItemFromRaw(updatedItemData);\n this.survey.surveyItems.set(newItem.id, newItem);\n\n if (itemId === clipboardData.rootItemId) {\n this.addItemToParentGroup(target, newItem);\n }\n }\n });\n\n // Update translations with new IDs\n const updatedTranslations = this.updateTranslations(clipboardData.translations, idMapping);\n Object.keys(updatedTranslations).forEach((itemId) => {\n // Convert serialized translations back to SurveyItemTranslations instance\n const itemTranslations = new SurveyItemTranslations();\n const serializedData = updatedTranslations[itemId];\n Object.keys(serializedData).forEach((locale) => {\n itemTranslations.setAllForLocale(locale, serializedData[locale]);\n });\n this.survey.translations.setItemTranslations(itemId, itemTranslations);\n });\n\n return idMapping[clipboardData.rootItemId];\n }\n\n // PRIVATE HELPER METHODS\n /**\n * Update all item ids in the raw item data recursively\n */\n private updateItemIdsInData(\n itemData: RawSurveyItem,\n idMapping: { [oldId: string]: string },\n ): RawSurveyItem {\n const updatedData = JSON.parse(JSON.stringify(itemData));\n\n if (updatedData.itemType === ReservedSurveyItemTypes.Group && updatedData.config) {\n const config = updatedData.config as { items?: string[] };\n if (config.items) {\n config.items = config.items.map((childId: string) => idMapping[childId] ?? childId);\n }\n }\n\n this.updateExpressionsInItemData(updatedData, idMapping);\n return updatedData;\n }\n\n /**\n * Update expressions in item data that reference the old ids\n */\n private updateExpressionsInItemData(\n itemData: RawSurveyItem,\n idMapping: { [oldId: string]: string },\n ): void {\n // Update display conditions\n if (itemData.displayConditions?.root) {\n this.updateExpressionReferences(itemData.displayConditions.root, idMapping);\n }\n if (itemData.displayConditions?.components) {\n Object.values(itemData.displayConditions.components).forEach((expr) => {\n if (expr) this.updateExpressionReferences(expr, idMapping);\n });\n }\n\n // Update disabled conditions\n if (itemData.disabledConditions?.components) {\n Object.values(itemData.disabledConditions.components).forEach((expr) => {\n if (expr) this.updateExpressionReferences(expr, idMapping);\n });\n }\n\n // Update validations\n if (itemData.validations) {\n Object.values(itemData.validations).forEach((expr) => {\n if (expr) this.updateExpressionReferences(expr, idMapping);\n });\n }\n\n if (itemData.prefills) {\n itemData.prefills.forEach((prefill) => {\n if (prefill.when) {\n this.updateExpressionReferences(prefill.when, idMapping);\n }\n\n if (prefill.source.type === \"expression\") {\n this.updateExpressionReferences(prefill.source.expression, idMapping);\n }\n\n if (prefill.source.type === \"previousResponse\") {\n prefill.source.ref.itemId =\n idMapping[prefill.source.ref.itemId] ?? prefill.source.ref.itemId;\n }\n });\n }\n }\n\n /**\n * Update references in a single expression (recursive)\n */\n private updateExpressionReferences(\n expression: unknown,\n idMapping: { [oldId: string]: string },\n ): void {\n if (!expression || typeof expression !== \"object\") {\n return;\n }\n\n const expr = expression as Record<string, unknown>;\n if (Array.isArray(expr.data)) {\n expr.data.forEach((arg: unknown) => {\n if (arg && typeof arg === \"object\" && arg !== null && \"str\" in arg) {\n const argObj = arg as { str?: string };\n if (\n typeof argObj.str === \"string\" &&\n Object.prototype.hasOwnProperty.call(idMapping, argObj.str)\n ) {\n argObj.str = idMapping[argObj.str];\n }\n this.updateExpressionReferences(arg, idMapping);\n }\n });\n }\n\n Object.keys(expr).forEach((key) => {\n const val = expr[key];\n if (val && typeof val === \"object\") {\n this.updateExpressionReferences(val, idMapping);\n }\n });\n }\n\n /**\n * Update translation keys for the pasted item\n */\n private updateTranslations(\n translations: { [itemId: string]: SerializedTranslations },\n idMapping: { [oldId: string]: string },\n ): { [itemId: string]: SerializedTranslations } {\n const newTranslations: { [itemId: string]: SerializedTranslations } = {};\n\n // Update ids for all items in the translation data\n Object.keys(translations).forEach((itemId) => {\n const itemTranslations = translations[itemId];\n\n // Determine the new key for this item (update the key mapping)\n const newItemId = idMapping[itemId];\n\n // Copy the serialized translations as-is (content is preserved, only keys change)\n newTranslations[newItemId] = itemTranslations;\n });\n\n return newTranslations;\n }\n\n /**\n * Validate clipboard data format\n */\n static isValidClipboardData(data: unknown): data is SurveyItemClipboardData {\n if (typeof data !== \"object\" || data === null || data === undefined) return false;\n const clipboardData = data as SurveyItemClipboardData;\n\n if (\n clipboardData.rootItemId === undefined ||\n typeof clipboardData.rootItemId !== \"string\" ||\n !Array.isArray(clipboardData.items) ||\n clipboardData.items.length === 0 ||\n typeof clipboardData.translations !== \"object\" ||\n clipboardData.translations === null ||\n Array.isArray(clipboardData.translations)\n ) {\n return false;\n }\n\n return (\n clipboardData.type === \"survey-item\" &&\n clipboardData.version === \"1.0.0\" &&\n clipboardData.items.every(\n (item) =>\n typeof item === \"object\" &&\n item !== null &&\n typeof item.itemId === \"string\" &&\n item.itemId.length > 0 &&\n typeof item.itemData === \"object\" &&\n item.itemData !== null &&\n !Array.isArray(item.itemData) &&\n typeof item.itemData.itemType === \"string\",\n ) &&\n clipboardData.items.some((item) => item.itemId === clipboardData.rootItemId)\n );\n }\n}\n","import { RawSurvey, RawSurveyAsset } from \"../survey/survey-file-schema\";\nimport { structuredCloneMethod } from \"../utils\";\n\nexport interface UndoRedoConfig {\n maxTotalMemoryMB: number;\n minHistorySize: number;\n maxHistorySize: number;\n}\n\nexport const CommitSource = {\n USER: \"user\",\n SYSTEM: \"system\",\n ASSISTANT: \"assistant\",\n} as const;\nexport type CommitSource = (typeof CommitSource)[keyof typeof CommitSource];\n\nexport interface CommitMeta {\n label: string;\n source?: CommitSource;\n}\n\nexport interface AssetPatch {\n assetId: string;\n prev?: RawSurveyAsset;\n next?: RawSurveyAsset;\n}\n\ninterface BaseHistoryEntry {\n timestamp: number;\n meta: CommitMeta;\n memorySize: number;\n}\n\ninterface SurveySnapshotHistoryEntry extends BaseHistoryEntry {\n kind: \"survey-snapshot\";\n survey: RawSurvey;\n}\n\ninterface AssetChangeHistoryEntry extends BaseHistoryEntry {\n kind: \"asset-change\";\n changes: AssetPatch[];\n}\n\ntype HistoryEntry = SurveySnapshotHistoryEntry | AssetChangeHistoryEntry;\ntype PendingHistoryEntry =\n | Omit<SurveySnapshotHistoryEntry, \"timestamp\" | \"memorySize\">\n | Omit<AssetChangeHistoryEntry, \"timestamp\" | \"memorySize\">;\n\nexport interface SurveyEditorHistoryCommit {\n index: number;\n kind: HistoryEntry[\"kind\"];\n meta: CommitMeta;\n timestamp: number;\n memorySize: number;\n isCurrent: boolean;\n}\n\ntype SerializedHistoryEntry =\n | SurveySnapshotHistoryEntry\n | AssetChangeHistoryEntry\n | (BaseHistoryEntry & { survey: RawSurvey });\n\n// Memory calculation utilities\nclass MemoryCalculator {\n private static encoder = new TextEncoder();\n\n static calculateSize(obj: object): number {\n const jsonString = JSON.stringify(obj);\n return this.encoder.encode(jsonString).length;\n }\n\n static formatBytes(bytes: number): string {\n const units = [\"B\", \"KB\", \"MB\", \"GB\"];\n let size = bytes;\n let unitIndex = 0;\n\n while (size >= 1024 && unitIndex < units.length - 1) {\n size /= 1024;\n unitIndex++;\n }\n\n return `${size.toFixed(1)} ${units[unitIndex]}`;\n }\n}\n\nfunction cloneAssets(\n assets?: Record<string, RawSurveyAsset>,\n): Record<string, RawSurveyAsset> | undefined {\n if (!assets || Object.keys(assets).length === 0) {\n return undefined;\n }\n return structuredCloneMethod(assets);\n}\n\nfunction normalizeHistoryEntry(entry: SerializedHistoryEntry): HistoryEntry {\n if (\"kind\" in entry) {\n if (entry.kind === \"survey-snapshot\") {\n return {\n kind: \"survey-snapshot\",\n survey: structuredCloneMethod(entry.survey),\n timestamp: entry.timestamp,\n meta: entry.meta,\n memorySize: entry.memorySize,\n };\n }\n\n return {\n kind: \"asset-change\",\n changes: structuredCloneMethod(entry.changes),\n timestamp: entry.timestamp,\n meta: entry.meta,\n memorySize: entry.memorySize,\n };\n }\n\n return {\n kind: \"survey-snapshot\",\n survey: structuredCloneMethod(entry.survey),\n timestamp: entry.timestamp,\n meta: entry.meta,\n memorySize: entry.memorySize,\n };\n}\n\nexport class SurveyEditorUndoRedo {\n private history: HistoryEntry[] = [];\n private currentIndex: number = -1;\n private _config: UndoRedoConfig;\n private _initialAssets?: Record<string, RawSurveyAsset>;\n\n constructor(\n initialSurvey: RawSurvey,\n config: Partial<UndoRedoConfig> = {},\n meta: CommitMeta = { label: \"Initial state\", source: CommitSource.SYSTEM },\n initialAssets?: Record<string, RawSurveyAsset>,\n ) {\n this._config = {\n maxTotalMemoryMB: 50,\n minHistorySize: 10,\n maxHistorySize: 200,\n ...config,\n };\n this._initialAssets = cloneAssets(initialAssets);\n\n this.saveSnapshot(initialSurvey, meta);\n }\n\n private saveEntry(entry: PendingHistoryEntry): void {\n const payload =\n entry.kind === \"survey-snapshot\"\n ? { kind: entry.kind, survey: entry.survey }\n : { kind: entry.kind, changes: entry.changes };\n\n const memorySize = MemoryCalculator.calculateSize(payload);\n\n // Remove any history after current index\n this.history = this.history.slice(0, this.currentIndex + 1);\n\n this.history.push({\n ...structuredCloneMethod(entry),\n timestamp: Date.now(),\n memorySize,\n } as HistoryEntry);\n\n this.currentIndex++;\n\n // Clean up history based on memory usage\n this.cleanupHistory();\n }\n\n private saveSnapshot(survey: RawSurvey, meta: CommitMeta): void {\n this.saveEntry({\n kind: \"survey-snapshot\",\n survey: structuredCloneMethod(survey),\n meta,\n });\n }\n\n private getBaseAssetsSize(): number {\n return this._initialAssets ? MemoryCalculator.calculateSize(this._initialAssets) : 0;\n }\n\n private cleanupHistory(): void {\n const maxMemoryBytes = this._config.maxTotalMemoryMB * 1024 * 1024;\n\n // Remove oldest states while preserving minimum.\n while (\n this.history.length > this._config.minHistorySize &&\n (this.getTotalMemoryUsage() > maxMemoryBytes ||\n this.history.length > this._config.maxHistorySize)\n ) {\n if (this.dropOldestState() <= 0) {\n break;\n }\n }\n }\n\n private dropOldestState(): number {\n if (this.history.length <= 1) {\n return 0;\n }\n\n const nextStateIndex = 1;\n const nextStateSurvey = this.getStateAtIndex(nextStateIndex);\n const nextStateAssets = this.getAssetsAtIndex(nextStateIndex);\n const nextEntry = this.history[nextStateIndex];\n\n const newFirstEntry: SurveySnapshotHistoryEntry = {\n kind: \"survey-snapshot\",\n survey: nextStateSurvey,\n meta: nextEntry.meta,\n timestamp: nextEntry.timestamp,\n memorySize: MemoryCalculator.calculateSize({\n kind: \"survey-snapshot\",\n survey: nextStateSurvey,\n }),\n };\n\n const removedBytes = this.history[0].memorySize;\n\n this._initialAssets = cloneAssets(nextStateAssets);\n this.history = [newFirstEntry, ...this.history.slice(nextStateIndex + 1)];\n this.currentIndex--;\n\n return removedBytes;\n }\n\n private getTotalMemoryUsage(): number {\n return (\n this.getBaseAssetsSize() + this.history.reduce((total, entry) => total + entry.memorySize, 0)\n );\n }\n\n private getStateAtIndex(index: number): RawSurvey {\n if (index < 0 || index >= this.history.length) {\n throw new Error(\"Invalid history state\");\n }\n\n for (let i = index; i >= 0; i--) {\n const entry = this.history[i];\n if (entry.kind === \"survey-snapshot\") {\n return structuredCloneMethod(entry.survey);\n }\n }\n\n throw new Error(\"Invalid history state\");\n }\n\n private applyAssetPatch(\n assets: Record<string, RawSurveyAsset>,\n patch: AssetPatch,\n ): Record<string, RawSurveyAsset> {\n const nextAssets = structuredCloneMethod(assets);\n if (patch.next) {\n nextAssets[patch.assetId] = structuredCloneMethod(patch.next);\n } else {\n delete nextAssets[patch.assetId];\n }\n return nextAssets;\n }\n\n private getAssetsAtIndex(index: number): Record<string, RawSurveyAsset> | undefined {\n if (index < 0 || index >= this.history.length) {\n throw new Error(\"Invalid history state\");\n }\n\n let assets = cloneAssets(this._initialAssets) ?? {};\n\n for (let i = 1; i <= index; i++) {\n const entry = this.history[i];\n if (entry.kind !== \"asset-change\") {\n continue;\n }\n\n for (const patch of entry.changes) {\n assets = this.applyAssetPatch(assets, patch);\n }\n }\n\n return Object.keys(assets).length > 0 ? assets : undefined;\n }\n\n // Commit a change to history\n commit(survey: RawSurvey, meta: CommitMeta): void {\n this.saveSnapshot(survey, meta);\n }\n\n commitAssetChange(changes: AssetPatch[], meta: CommitMeta): void {\n if (changes.length === 0) {\n return;\n }\n\n this.saveEntry({\n kind: \"asset-change\",\n changes: structuredCloneMethod(changes),\n meta,\n });\n }\n\n // Get current committed state\n getCurrentState(): RawSurvey {\n if (this.currentIndex < 0 || this.currentIndex >= this.history.length) {\n throw new Error(\"Invalid history state\");\n }\n return this.getStateAtIndex(this.currentIndex);\n }\n\n getCurrentAssets(): Record<string, RawSurveyAsset> | undefined {\n if (this.currentIndex < 0 || this.currentIndex >= this.history.length) {\n throw new Error(\"Invalid history state\");\n }\n return this.getAssetsAtIndex(this.currentIndex);\n }\n\n undo(): RawSurvey | null {\n if (!this.canUndo()) return null;\n\n this.currentIndex--;\n return this.getCurrentState();\n }\n\n redo(): RawSurvey | null {\n if (!this.canRedo()) return null;\n\n this.currentIndex++;\n return this.getCurrentState();\n }\n\n canUndo(): boolean {\n return this.currentIndex > 0;\n }\n\n canRedo(): boolean {\n return this.currentIndex < this.history.length - 1;\n }\n\n getUndoMeta(): CommitMeta | null {\n if (!this.canUndo()) return null;\n return this.history[this.currentIndex].meta;\n }\n\n getRedoMeta(): CommitMeta | null {\n if (!this.canRedo()) return null;\n return this.history[this.currentIndex + 1].meta;\n }\n\n getMemoryUsage(): { totalMB: number; entries: number } {\n return {\n totalMB: this.getTotalMemoryUsage() / (1024 * 1024),\n entries: this.history.length,\n };\n }\n\n getConfig(): UndoRedoConfig {\n return { ...this._config };\n }\n\n /**\n * Get the full history list with metadata\n */\n getHistory(): Array<{\n index: number;\n kind: HistoryEntry[\"kind\"];\n meta: CommitMeta;\n timestamp: number;\n memorySize: number;\n isCurrent: boolean;\n }> {\n return this.history.map((entry, index) => ({\n index,\n kind: entry.kind,\n meta: entry.meta,\n timestamp: entry.timestamp,\n memorySize: entry.memorySize,\n isCurrent: index === this.currentIndex,\n }));\n }\n\n /**\n * Get committed history entries after the initial state up to the current index.\n *\n * Redo-only future entries are intentionally omitted so the returned list describes the active\n * change chain from the initial state to the current editor state.\n */\n getCommitsSinceInitial(): SurveyEditorHistoryCommit[] {\n return this.history.slice(1, this.currentIndex + 1).map((entry, offset) => {\n const index = offset + 1;\n return {\n index,\n kind: entry.kind,\n meta: entry.meta,\n timestamp: entry.timestamp,\n memorySize: entry.memorySize,\n isCurrent: index === this.currentIndex,\n };\n });\n }\n\n /**\n * Get the current index in the history\n */\n getCurrentIndex(): number {\n return this.currentIndex;\n }\n\n /**\n * Get the total number of history entries\n */\n getHistoryLength(): number {\n return this.history.length;\n }\n\n /**\n * Jump to a specific index in the history (can go forward or backward)\n * @param targetIndex The index to jump to\n * @returns The survey state at the target index, or null if invalid\n */\n jumpToIndex(targetIndex: number): RawSurvey | null {\n if (\n targetIndex < 0 ||\n targetIndex >= this.history.length ||\n targetIndex === this.currentIndex\n ) {\n return null;\n }\n\n this.currentIndex = targetIndex;\n return this.getCurrentState();\n }\n\n /**\n * Check if we can jump to a specific index\n */\n canJumpToIndex(targetIndex: number): boolean {\n return (\n targetIndex >= 0 && targetIndex < this.history.length && targetIndex !== this.currentIndex\n );\n }\n\n /**\n * Serialize the undo/redo state to JSON\n * @returns A JSON-serializable object containing the complete state\n */\n serialize(): {\n history: Array<HistoryEntry>;\n currentIndex: number;\n config: UndoRedoConfig;\n initialAssets?: Record<string, RawSurveyAsset>;\n } {\n return {\n history: this.history.map((entry) => {\n if (entry.kind === \"survey-snapshot\") {\n return {\n kind: \"survey-snapshot\",\n survey: entry.survey,\n timestamp: entry.timestamp,\n meta: entry.meta,\n memorySize: entry.memorySize,\n };\n }\n\n return {\n kind: \"asset-change\",\n changes: entry.changes,\n timestamp: entry.timestamp,\n meta: entry.meta,\n memorySize: entry.memorySize,\n };\n }),\n currentIndex: this.currentIndex,\n config: { ...this._config },\n initialAssets: cloneAssets(this._initialAssets),\n };\n }\n\n /**\n * Create a new SurveyEditorUndoRedo instance from JSON data\n * @param jsonData The serialized undo/redo state\n * @returns A new SurveyEditorUndoRedo instance with the restored state\n */\n static deserialize(\n jsonData: {\n history: Array<SerializedHistoryEntry>;\n currentIndex: number;\n config: UndoRedoConfig;\n initialAssets?: Record<string, RawSurveyAsset>;\n },\n initialAssetsOverride?: Record<string, RawSurveyAsset>,\n ): SurveyEditorUndoRedo {\n if (!jsonData.history || !Array.isArray(jsonData.history) || jsonData.history.length === 0) {\n throw new Error(\"Invalid object: history must be an array and must not be empty\");\n }\n\n if (\n typeof jsonData.currentIndex !== \"number\" ||\n jsonData.currentIndex < 0 ||\n jsonData.currentIndex >= jsonData.history.length\n ) {\n throw new Error(\n \"Invalid object: currentIndex must be a valid index within the history array\",\n );\n }\n\n if (!jsonData.config) {\n throw new Error(\"Invalid object: config is required\");\n }\n\n const normalizedHistory = jsonData.history.map(normalizeHistoryEntry);\n\n // Create a new instance with the first survey and config\n const firstEntry = normalizedHistory[0];\n const firstSurvey =\n firstEntry.kind === \"survey-snapshot\"\n ? firstEntry.survey\n : (() => {\n throw new Error(\n \"Invalid object: first history entry must resolve to a survey snapshot\",\n );\n })();\n\n const instance = new SurveyEditorUndoRedo(\n firstSurvey,\n jsonData.config,\n firstEntry.meta,\n initialAssetsOverride ?? jsonData.initialAssets,\n );\n\n // Clear the default initial state and restore the full history\n instance.history = normalizedHistory;\n instance.currentIndex = jsonData.currentIndex;\n instance._initialAssets = cloneAssets(initialAssetsOverride ?? jsonData.initialAssets);\n\n return instance;\n }\n}\n","import { Survey } from \"../survey/survey\";\nimport { CommitMeta, CommitSource, SurveyEditorUndoRedo, type UndoRedoConfig } from \"./undo-redo\";\nimport {\n SurveyItemTranslations,\n SurveyCardContent,\n NavigationContent,\n Content,\n} from \"../survey/utils\";\nimport { RawSurvey, RawSurveyAsset } from \"../survey/survey-file-schema\";\nimport { ItemCopyPaste, SurveyItemClipboardData } from \"./item-copy-paste\";\nimport { Target } from \"./types\";\nimport { SurveyItemCore, RawSurveyItem } from \"../survey/items\";\nimport { GroupItemCore } from \"../survey/registry/built-in-items\";\nimport type { ItemTypeRegistry } from \"../survey/registry/item-registry\";\nimport type { TemplateValueDefinition } from \"../expressions/template-value\";\nimport { structuredCloneMethod } from \"../utils\";\n\n// Interface for serializing SurveyEditor state\nexport interface SerializedSurveyEditor {\n version: string;\n survey: RawSurvey;\n undoRedo: ReturnType<SurveyEditorUndoRedo[\"serialize\"]>;\n hasUncommittedChanges: boolean;\n}\n\nexport interface SurveyEditorConfig extends Partial<UndoRedoConfig> {\n /** Plugin registry for deserializing survey state during undo/redo. Required when survey contains custom item types. */\n pluginRegistry?: ItemTypeRegistry;\n}\n\nfunction stripAssetsFromSurveySnapshot(survey: RawSurvey): RawSurvey {\n const snapshot = structuredCloneMethod(survey);\n delete snapshot.assets;\n return snapshot;\n}\n\nfunction mergeSurveySnapshotWithAssets(\n snapshot: RawSurvey,\n assets?: RawSurvey[\"assets\"],\n): RawSurvey {\n const merged = structuredCloneMethod(snapshot);\n\n if (assets && Object.keys(assets).length > 0) {\n merged.assets = structuredCloneMethod(assets);\n } else {\n delete merged.assets;\n }\n\n return merged;\n}\n\nexport class SurveyEditor {\n private _survey: Survey;\n private _undoRedo: SurveyEditorUndoRedo;\n private _hasUncommittedChanges: boolean = false;\n private _pluginRegistry?: ItemTypeRegistry;\n\n constructor(survey: Survey, config: SurveyEditorConfig = {}, meta?: CommitMeta) {\n this._survey = survey;\n const { pluginRegistry, ...undoRedoConfig } = config;\n this._pluginRegistry = pluginRegistry;\n const serialized = survey.serialize();\n this._undoRedo = new SurveyEditorUndoRedo(\n stripAssetsFromSurveySnapshot(serialized),\n undoRedoConfig,\n meta,\n serialized.assets,\n );\n }\n\n /** Returns an immutable copy of the current survey state. */\n get survey(): Survey {\n const serialized = this._survey.serialize();\n const registry = this._pluginRegistry ?? this._survey.getPluginRegistry();\n return Survey.fromJson(serialized, registry);\n }\n\n get hasUncommittedChanges(): boolean {\n return this._hasUncommittedChanges;\n }\n\n // Expose the undo-redo instance directly\n get undoRedo(): SurveyEditorUndoRedo {\n return this._undoRedo;\n }\n\n // Commit current changes to undo/redo history\n commit(meta: CommitMeta): void {\n if (!this._hasUncommittedChanges) {\n return;\n }\n\n this._undoRedo.commit(stripAssetsFromSurveySnapshot(this._survey.serialize()), meta);\n this._hasUncommittedChanges = false;\n }\n\n private restoreHistoryState(snapshot: RawSurvey, assets?: RawSurvey[\"assets\"]): void {\n this._survey = Survey.fromJson(\n mergeSurveySnapshotWithAssets(snapshot, assets),\n this._pluginRegistry,\n );\n }\n\n commitIfNeeded(): void {\n if (this._hasUncommittedChanges) {\n this.commit({\n label: \"Latest content changes\",\n source: CommitSource.SYSTEM,\n });\n }\n }\n\n // Undo to previous state\n undo(): boolean {\n if (this._hasUncommittedChanges) {\n // If there are uncommitted changes, revert to last committed state\n this.restoreHistoryState(this._undoRedo.getCurrentState(), this._undoRedo.getCurrentAssets());\n this._hasUncommittedChanges = false;\n return true;\n } else {\n // Normal undo operation\n const previousState = this._undoRedo.undo();\n if (previousState) {\n this.restoreHistoryState(previousState, this._undoRedo.getCurrentAssets());\n this._hasUncommittedChanges = false;\n return true;\n }\n return false;\n }\n }\n\n // Redo to next state\n redo(): boolean {\n if (this._hasUncommittedChanges) {\n // Cannot redo when there are uncommitted changes\n return false;\n }\n\n const nextState = this._undoRedo.redo();\n if (nextState) {\n this.restoreHistoryState(nextState, this._undoRedo.getCurrentAssets());\n this._hasUncommittedChanges = false;\n return true;\n }\n return false;\n }\n\n // Enhanced undo/redo methods that use the exposed instance\n /**\n * Jump to a specific index in the history (can go forward or backward)\n */\n jumpToIndex(targetIndex: number): boolean {\n if (this._hasUncommittedChanges) {\n // Cannot jump to specific index with uncommitted changes\n return false;\n }\n\n const targetState = this._undoRedo.jumpToIndex(targetIndex);\n if (targetState) {\n this.restoreHistoryState(targetState, this._undoRedo.getCurrentAssets());\n this._hasUncommittedChanges = false;\n return true;\n }\n return false;\n }\n\n canUndo(): boolean {\n return this._hasUncommittedChanges || this._undoRedo.canUndo();\n }\n\n canRedo(): boolean {\n return !this._hasUncommittedChanges && this._undoRedo.canRedo();\n }\n\n getUndoMeta(): CommitMeta | null {\n if (this._hasUncommittedChanges) {\n return {\n label: \"Latest content changes\",\n source: CommitSource.SYSTEM,\n };\n }\n return this._undoRedo.getUndoMeta();\n }\n\n getRedoMeta(): CommitMeta | null {\n if (this._hasUncommittedChanges) {\n return null;\n }\n return this._undoRedo.getRedoMeta();\n }\n\n // Get memory usage statistics\n getMemoryUsage(): { totalMB: number; entries: number } {\n return this._undoRedo.getMemoryUsage();\n }\n\n // Get undo/redo configuration\n getUndoRedoConfig(): UndoRedoConfig {\n return this._undoRedo.getConfig();\n }\n\n /**\n * Get committed changes after the initial editor state up to the current undo/redo position.\n */\n getCommitsSinceInitial() {\n return this._undoRedo.getCommitsSinceInitial();\n }\n\n /**\n * Serialize the SurveyEditor state to JSON\n * @returns A JSON-serializable object containing the complete editor state\n */\n toJson(): SerializedSurveyEditor {\n return {\n version: \"1.0.0\",\n survey: this._survey.serialize(),\n undoRedo: this._undoRedo.serialize(),\n hasUncommittedChanges: this._hasUncommittedChanges,\n };\n }\n\n /**\n * Create a new SurveyEditor instance from JSON data\n * @param jsonData The serialized editor state\n * @param pluginRegistry Optional plugin registry for deserializing survey state (required when survey contains custom item types)\n * @returns A new SurveyEditor instance with the restored state\n */\n static fromJson(\n jsonData: SerializedSurveyEditor,\n pluginRegistry?: ItemTypeRegistry,\n ): SurveyEditor {\n if (!jsonData.survey) {\n throw new Error(\"Invalid object: survey is required\");\n }\n\n if (!jsonData.undoRedo) {\n throw new Error(\"Invalid object: undoRedo is required\");\n }\n\n if (typeof jsonData.hasUncommittedChanges !== \"boolean\") {\n throw new Error(\"Invalid object: hasUncommittedChanges must be a boolean\");\n }\n\n // Validate version (for future compatibility)\n if (jsonData.version && !jsonData.version.startsWith(\"1.\")) {\n console.warn(\n `Warning: Loading SurveyEditor with version ${jsonData.version}, current version is 1.0.0`,\n );\n }\n\n // Create survey from JSON\n const survey = Survey.fromJson(jsonData.survey, pluginRegistry);\n\n // Create a new editor instance\n const editor = new SurveyEditor(survey, { pluginRegistry });\n\n // Restore undo/redo state\n editor._undoRedo = SurveyEditorUndoRedo.deserialize(\n {\n ...jsonData.undoRedo,\n history: jsonData.undoRedo.history.map((entry) =>\n \"survey\" in entry\n ? {\n ...entry,\n survey: stripAssetsFromSurveySnapshot(entry.survey),\n }\n : entry,\n ),\n },\n jsonData.survey.assets,\n );\n\n // Infer whether the live survey contains uncommitted survey changes by comparing\n // the current survey content to the current history entry, ignoring assets.\n editor._hasUncommittedChanges =\n JSON.stringify(stripAssetsFromSurveySnapshot(jsonData.survey)) !==\n JSON.stringify(editor._undoRedo.getCurrentState());\n\n return editor;\n }\n\n private markAsModified(): void {\n this._hasUncommittedChanges = true;\n }\n\n private createEditorTimestamp(): string {\n return new Date().toISOString();\n }\n\n private touchItemModifiedMetadata(\n itemId: string,\n timestamp = this.createEditorTimestamp(),\n ): void {\n const item = this._survey.surveyItems.get(itemId);\n if (!item) {\n return;\n }\n\n item.setModifiedAt(timestamp);\n }\n\n addItem(target: Target, item: SurveyItemCore, content?: SurveyItemTranslations): void {\n if (this._survey.surveyItems.has(item.id)) {\n throw new Error(`Item with id '${item.id}' already exists in the survey`);\n }\n\n // Mark as modified (uncommitted change)\n this.markAsModified();\n const timestamp = this.createEditorTimestamp();\n\n // Find the parent group item\n let parentGroup: GroupItemCore;\n\n if (!target) {\n // If no target provided, add to root\n\n const rootItem = this._survey.rootItem;\n if (!rootItem) {\n throw new Error(\"No root group found in survey\");\n }\n if (!(rootItem instanceof GroupItemCore)) {\n throw new Error(\"Root item is not a group item\");\n }\n parentGroup = rootItem;\n } else {\n // Find the target parent group\n const targetItem = this._survey.surveyItems.get(target.parentId);\n\n if (!targetItem) {\n throw new Error(`Parent item with id '${target.parentId}' not found`);\n }\n\n if (!(targetItem instanceof GroupItemCore)) {\n throw new Error(\n `Parent item '${target.parentId}' is not a group item (${targetItem.type})`,\n );\n }\n\n parentGroup = targetItem;\n }\n\n if (parentGroup.hasChild(item.id)) {\n throw new Error(`Item ${item.id} already in this group`);\n }\n\n // ensure that item's key not already used within the group\n const siblings = Array.from(this._survey.surveyItems.values()).filter((sItem) =>\n parentGroup.items?.includes(sItem.id),\n );\n let counter = 1;\n const originalKey = item.key;\n let uniqueKey = originalKey;\n while (siblings.some((sibling) => sibling.key === uniqueKey)) {\n uniqueKey = `${originalKey}_${counter}`;\n counter++;\n }\n\n // Determine insertion index\n let insertIndex: number;\n if (target?.index !== undefined) {\n // Insert at specified index, or at end if index is larger than array length\n insertIndex = Math.min(target.index, parentGroup.items.length);\n } else {\n // Insert at the end\n insertIndex = parentGroup.items.length;\n }\n\n item.updateRawItem({\n ...item.rawItem,\n key: uniqueKey,\n });\n item.setCreatedAt(timestamp);\n item.setModifiedAt(timestamp);\n\n // Add the item to the survey items collection\n this._survey.surveyItems.set(item.id, item);\n\n // Add the item to the parent group (uses addChild for proper persistence)\n parentGroup.addChild(item.id, insertIndex);\n this.touchItemModifiedMetadata(parentGroup.id, timestamp);\n\n // Update translations in the survey\n if (content) {\n this._survey.translations.setItemTranslations(item.id, content);\n }\n }\n\n // Remove an item from the survey\n removeItem(itemId: string, nested: boolean = false): boolean {\n this.markAsModified();\n const timestamp = this.createEditorTimestamp();\n const item = this._survey.surveyItems.get(itemId);\n if (!item) {\n return false;\n }\n\n // Find parent group and remove from its items array\n const parentItem = this._survey.getParentItem(itemId);\n if (!parentItem) {\n throw new Error(`Item with id '${itemId}' is the root item`);\n }\n\n if (item instanceof GroupItemCore) {\n for (const childId of item.getChildrenIds()) {\n this.removeItem(childId, true);\n }\n }\n\n // Remove from survey items\n this._survey.surveyItems.delete(itemId);\n\n // Remove translations\n this._survey.translations?.onItemDeleted(itemId);\n\n if (!nested) {\n parentItem.removeChild(itemId);\n this.touchItemModifiedMetadata(parentItem.id, timestamp);\n }\n return true;\n }\n\n // Move an item to a different position\n moveItem(itemId: string, newTarget: Target): boolean {\n this.markAsModified();\n const timestamp = this.createEditorTimestamp();\n // Check if item exists\n const item = this._survey.surveyItems.get(itemId);\n if (!item) {\n throw new Error(`Item with id '${itemId}' not found`);\n }\n\n // Check if new target exists and is a group\n const targetItem = this._survey.surveyItems.get(newTarget.parentId);\n if (!targetItem) {\n throw new Error(`Target parent with id '${newTarget.parentId}' not found`);\n }\n\n if (!(targetItem instanceof GroupItemCore)) {\n throw new Error(\n `Target parent '${newTarget.parentId}' is not a group item (${targetItem.type})`,\n );\n }\n\n // Check if new target is not a child of the current item (prevent circular reference)\n if (this._survey.isDescendantOf(newTarget.parentId, itemId)) {\n throw new Error(`Cannot move item '${itemId}' to its descendant '${newTarget.parentId}'`);\n }\n\n // If the item is already in the target parent\n const currentParentItem = this._survey.getParentItem(itemId);\n if (currentParentItem?.id === newTarget.parentId) {\n throw new Error(`Item '${itemId}' is already in the target parent '${newTarget.parentId}'`);\n }\n\n // Remove item from current parent's items array\n if (currentParentItem) {\n const currentParentGroup = currentParentItem as GroupItemCore;\n currentParentGroup.removeChild(itemId);\n this.touchItemModifiedMetadata(currentParentGroup.id, timestamp);\n }\n\n // Add item to new parent's items array\n const targetGroup = targetItem as GroupItemCore;\n\n // ensure that item's key not already used within the group\n const siblings = Array.from(this._survey.surveyItems.values()).filter((sItem) =>\n targetGroup.hasChild(sItem.id),\n );\n let counter = 1;\n let uniqueKey = item.key;\n while (siblings.some((sibling) => sibling.key === uniqueKey)) {\n uniqueKey = `${item.key}_${counter}`;\n counter++;\n }\n if (uniqueKey !== item.key) {\n item.updateRawItem({\n ...item.rawItem,\n key: uniqueKey,\n });\n }\n\n const insertIndex =\n newTarget.index !== undefined\n ? Math.min(newTarget.index, targetGroup.items.length)\n : targetGroup.items.length;\n\n targetGroup.addChild(itemId, insertIndex);\n this.touchItemModifiedMetadata(targetGroup.id, timestamp);\n this.touchItemModifiedMetadata(itemId, timestamp);\n\n return true;\n }\n\n /** Move several independent item subtrees as one ordered block. */\n moveItems(itemIds: readonly string[], newTarget: Target): boolean {\n const requestedIds = [...new Set(itemIds)];\n const selectedIds = requestedIds.filter(\n (itemId) =>\n !requestedIds.some(\n (candidateId) =>\n candidateId !== itemId && this._survey.isDescendantOf(itemId, candidateId),\n ),\n );\n if (selectedIds.length === 0) return false;\n\n const targetGroup = this._survey.surveyItems.get(newTarget.parentId);\n if (!(targetGroup instanceof GroupItemCore)) {\n throw new Error(`Target parent '${newTarget.parentId}' is not a group item`);\n }\n\n const entries = selectedIds.map((itemId) => {\n const item = this._survey.surveyItems.get(itemId);\n const parent = this._survey.getParentItem(itemId);\n if (!item || !(parent instanceof GroupItemCore)) {\n throw new Error(`Item '${itemId}' cannot be moved`);\n }\n if (\n itemId === newTarget.parentId ||\n this._survey.isDescendantOf(newTarget.parentId, itemId)\n ) {\n throw new Error(`Cannot move item '${itemId}' into its own subtree`);\n }\n return { item, parent, index: parent.items.indexOf(itemId) };\n });\n\n // Preserve the survey's structural order, regardless of click order.\n const order = new Map<string, number>();\n let orderIndex = 0;\n const visit = (group: GroupItemCore) => {\n for (const childId of group.items) {\n order.set(childId, orderIndex++);\n const child = this._survey.surveyItems.get(childId);\n if (child instanceof GroupItemCore) visit(child);\n }\n };\n const root = this._survey.rootItem;\n if (root) visit(root);\n entries.sort((a, b) => (order.get(a.item.id) ?? 0) - (order.get(b.item.id) ?? 0));\n\n const selectedSet = new Set(entries.map(({ item }) => item.id));\n const requestedIndex = newTarget.index ?? targetGroup.items.length;\n const removedBeforeTarget = targetGroup.items\n .slice(0, requestedIndex)\n .filter((id) => selectedSet.has(id)).length;\n const insertionIndex = Math.max(0, requestedIndex - removedBeforeTarget);\n const timestamp = this.createEditorTimestamp();\n\n this.markAsModified();\n for (const { item, parent } of entries) {\n parent.removeChild(item.id);\n this.touchItemModifiedMetadata(parent.id, timestamp);\n }\n\n const siblingKeys = new Set(\n targetGroup.items\n .map((id) => this._survey.surveyItems.get(id)?.key)\n .filter((key): key is string => Boolean(key)),\n );\n entries.forEach(({ item }, offset) => {\n const originalKey = item.key;\n let uniqueKey = originalKey;\n let counter = 1;\n while (siblingKeys.has(uniqueKey)) uniqueKey = `${originalKey}_${counter++}`;\n if (uniqueKey !== item.key) item.updateRawItem({ ...item.rawItem, key: uniqueKey });\n siblingKeys.add(uniqueKey);\n targetGroup.addChild(item.id, insertionIndex + offset);\n this.touchItemModifiedMetadata(item.id, timestamp);\n });\n this.touchItemModifiedMetadata(targetGroup.id, timestamp);\n return true;\n }\n\n /**\n * Get a deep copy of an item's raw data.\n * The returned object is independent of the survey—mutating it will not affect the survey.\n * Use this when you need to edit an item in a form or pass it to updateItem after modifications.\n *\n * @param itemId - The ID of the item to copy\n * @returns A deep copy of the item's RawSurveyItem data\n * @throws Error if the item is not found\n */\n getItemDataCopy(itemId: string): RawSurveyItem {\n const item = this._survey.surveyItems.get(itemId);\n if (!item) {\n throw new Error(`Item with id '${itemId}' not found`);\n }\n return JSON.parse(JSON.stringify(item.rawItem)) as RawSurveyItem;\n }\n\n /**\n * Update an item's data in the survey.\n * Can update common attributes (displayConditions, disabledConditions, validations, etc.)\n * as well as type-specific config.\n *\n * Use getItemDataCopy to obtain an editable copy, modify it, then pass it here.\n * Alternatively, pass a Partial to merge specific fields (top-level keys only;\n * e.g. config replaces the entire config object).\n *\n * @param itemId - The ID of the item to update (must match data.id if provided)\n * @param rawItemData - Full RawSurveyItem or Partial to merge. The id cannot be changed.\n */\n updateItem(itemId: string, rawItemData: RawSurveyItem | Partial<RawSurveyItem>): void {\n const existingItem = this._survey.surveyItems.get(itemId);\n if (!existingItem) {\n throw new Error(`Item with id '${itemId}' not found`);\n }\n\n if (\"id\" in rawItemData && rawItemData.id !== undefined && rawItemData.id !== itemId) {\n throw new Error(`Cannot change item id from '${itemId}' to '${rawItemData.id}'`);\n }\n\n const currentRaw = existingItem.rawItem;\n const merged: RawSurveyItem = {\n ...currentRaw,\n ...rawItemData,\n id: itemId, // Ensure id is never changed\n };\n\n // Reject key change if it would collide with a sibling\n const newKey = merged.key ?? existingItem.key;\n const parentGroup = this._survey.getParentItem(itemId);\n if (parentGroup) {\n const siblingWithSameKey = (parentGroup.items ?? [])\n .filter((id) => id !== itemId)\n .map((id) => this._survey.surveyItems.get(id))\n .find((s) => s !== undefined && s.key === newKey);\n if (siblingWithSameKey) {\n throw new Error(\n `Key '${newKey}' is already in use by sibling item '${siblingWithSameKey.id}'`,\n );\n }\n }\n\n const newItem = this._survey.createItemFromRaw({\n ...merged,\n editorMetadata: existingItem.rawItem.editorMetadata,\n });\n newItem.setModifiedAt(this.createEditorTimestamp());\n this._survey.surveyItems.set(itemId, newItem);\n this.markAsModified();\n }\n\n // TODO: add also to update component translations (updating part of the item)\n // Update item translations\n updateItemTranslations(itemId: string, updatedContent?: SurveyItemTranslations): boolean {\n const item = this._survey.surveyItems.get(itemId);\n if (!item) {\n return false;\n }\n\n this.markAsModified();\n item.setModifiedAt(this.createEditorTimestamp());\n this._survey.translations.setItemTranslations(itemId, updatedContent);\n\n return true;\n }\n\n /**\n * Update survey-level translations that are not tied to specific items.\n * Use these for survey card, navigation, validation messages, etc.\n */\n updateSurveyTranslations(updates: {\n surveyCard?: { locale: string; content?: SurveyCardContent };\n navigation?: { locale: string; content?: NavigationContent };\n validationMessages?: { locale: string; content?: { invalidResponse?: Content } };\n }): void {\n this.markAsModified();\n if (updates.surveyCard) {\n this._survey.translations.setSurveyCardContent(\n updates.surveyCard.locale,\n updates.surveyCard.content,\n );\n }\n if (updates.navigation) {\n this._survey.translations.setNavigationContent(\n updates.navigation.locale,\n updates.navigation.content,\n );\n }\n if (updates.validationMessages) {\n this._survey.translations.setValidationMessages(\n updates.validationMessages.locale,\n updates.validationMessages.content,\n );\n }\n }\n\n /** Add an empty survey locale so it can be authored before translated content exists. */\n addLocale(locale: string): boolean {\n const added = this._survey.translations.addLocale(locale);\n if (added) {\n this.markAsModified();\n }\n return added;\n }\n\n /** Remove a locale and every survey- and item-level translation stored for it. */\n removeLocale(locale: string): boolean {\n if (!this._survey.locales.includes(locale)) {\n return false;\n }\n\n this._survey.translations.removeLocale(locale);\n this.markAsModified();\n return true;\n }\n\n /**\n * Get maxItemsPerPage immutably (returns a copy).\n */\n getMaxItemsPerPage(): { large: number; small: number } | undefined {\n const val = this._survey.maxItemsPerPage;\n return val ? { ...val } : undefined;\n }\n\n /**\n * Update maxItemsPerPage.\n */\n updateMaxItemsPerPage(value: { large: number; small: number } | undefined): void {\n this.markAsModified();\n this._survey.maxItemsPerPage = value ? { ...value } : undefined;\n }\n\n /**\n * Get metadata immutably (returns a copy).\n */\n getMetadata(): { [key: string]: string } | undefined {\n const val = this._survey.metadata;\n return val ? { ...val } : undefined;\n }\n\n /**\n * Update metadata.\n */\n updateMetadata(metadata: { [key: string]: string } | undefined): void {\n this.markAsModified();\n this._survey.metadata = metadata ? { ...metadata } : undefined;\n }\n\n /**\n * Get a template value immutably (returns a deep copy).\n */\n getTemplateValue(key: string): TemplateValueDefinition | undefined {\n const val = this._survey.getTemplateValue(key);\n return val ? structuredCloneMethod(val) : undefined;\n }\n\n /**\n * Get all template values immutably (returns a new Map with deep-copied values).\n */\n getTemplateValues(): Map<string, TemplateValueDefinition> {\n const keys = this._survey.getTemplateValueKeys();\n const result = new Map<string, TemplateValueDefinition>();\n for (const key of keys) {\n const val = this._survey.getTemplateValue(key);\n if (val) {\n result.set(key, structuredCloneMethod(val));\n }\n }\n return result;\n }\n\n /**\n * Add or replace a template value.\n */\n setTemplateValue(key: string, templateValue: TemplateValueDefinition): void {\n this.markAsModified();\n this._survey.setTemplateValue(key, structuredCloneMethod(templateValue));\n }\n\n /**\n * Remove a template value.\n */\n removeTemplateValue(key: string): void {\n this.markAsModified();\n this._survey.deleteTemplateValue(key);\n }\n\n /**\n * Get a survey asset immutably.\n */\n getAsset(assetId: string): RawSurveyAsset | undefined {\n const asset = this._survey.getAsset(assetId);\n return asset ? structuredCloneMethod(asset) : undefined;\n }\n\n /**\n * Get all survey assets immutably.\n */\n getAssets(): Map<string, RawSurveyAsset> {\n return this._survey.getAssets();\n }\n\n /**\n * Add or replace a survey asset.\n */\n setAsset(assetId: string, asset: RawSurveyAsset): void {\n const previousAsset = this._survey.getAsset(assetId);\n this._survey.setAsset(assetId, structuredCloneMethod(asset));\n this._undoRedo.commitAssetChange(\n [\n {\n assetId,\n prev: previousAsset,\n next: structuredCloneMethod(asset),\n },\n ],\n {\n label: `Update asset: ${assetId}`,\n source: CommitSource.USER,\n },\n );\n }\n\n /**\n * Remove a survey asset.\n */\n removeAsset(assetId: string): void {\n const previousAsset = this._survey.getAsset(assetId);\n if (!previousAsset) {\n return;\n }\n this._survey.deleteAsset(assetId);\n this._undoRedo.commitAssetChange(\n [\n {\n assetId,\n prev: previousAsset,\n },\n ],\n {\n label: `Remove asset: ${assetId}`,\n source: CommitSource.USER,\n },\n );\n }\n\n /**\n * Copy a survey item and all its data to clipboard format\n * @param itemId - The ID of the item to copy\n * @returns Clipboard data that can be serialized to JSON for clipboard\n */\n copyItem(itemId: string): SurveyItemClipboardData {\n const copyPaste = new ItemCopyPaste(this._survey);\n return copyPaste.copyItem(itemId);\n }\n\n /**\n * Paste a survey item from clipboard data to a target location\n * @param clipboardData - The clipboard data containing the item to paste\n * @param target - Target location where to paste the item\n * @returns The ID of the pasted item\n */\n pasteItem(clipboardData: SurveyItemClipboardData, target: Target): string {\n this.markAsModified();\n const timestamp = this.createEditorTimestamp();\n const itemIdsBeforePaste = new Set(this._survey.surveyItems.keys());\n const copyPaste = new ItemCopyPaste(this._survey);\n const newItemId = copyPaste.pasteItem(clipboardData, target);\n const pastedItemIds = Array.from(this._survey.surveyItems.keys()).filter(\n (itemId) => !itemIdsBeforePaste.has(itemId),\n );\n\n for (const itemId of pastedItemIds) {\n const item = this._survey.surveyItems.get(itemId);\n if (item) {\n item.setCreatedAt(timestamp);\n item.setModifiedAt(timestamp);\n }\n }\n this.touchItemModifiedMetadata(target.parentId, timestamp);\n\n return newItemId;\n }\n}\n"],"mappings":";;AA2BA,IAAa,gBAAb,MAAa,cAAc;CACzB;CAEA,YAAY,QAAgB;AAC1B,OAAK,SAAS;;;;;;;;CAShB,SAAS,QAAyC;AAEhD,MAAI,CADS,KAAK,OAAO,YAAY,IAAI,OAChC,CACP,OAAM,IAAI,MAAM,iBAAiB,OAAO,aAAa;EAIvD,MAAM,cAAc,KAAK,oBAAoB,OAAO;EAGpD,MAAM,QAAQ,YAAY,KAAK,OAAO;GACpC,MAAM,OAAO,KAAK,OAAO,YAAY,IAAI,GAAG;AAC5C,OAAI,CAAC,KAAM,OAAM,IAAI,MAAM,iBAAiB,GAAG,yBAAyB;AACxE,UAAO;IAAE,QAAQ;IAAI,UAAU,KAAK;IAAS;IAC7C;EAGF,MAAM,eAA6D,EAAE;AACrE,cAAY,SAAS,OAAO;AAC1B,OAAI;IACF,MAAM,mBAAmB,KAAK,OAAO,oBAAoB,GAAG;AAC5D,QAAI,kBAAkB,SAAS,QAAQ;KACrC,MAAM,yBAAiD,EAAE;AACzD,sBAAiB,QAAQ,SAAS,WAAW;MAC3C,MAAM,gBAAgB,iBAAiB,gBAAgB,OAAO;AAC9D,UAAI,cACF,wBAAuB,UAAU;OAEnC;AACF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;GACA,MAAM;GACN,MAAM,sBAAsB,MAAM;GACnC,CACF,EACD;GACE,OAAO,iBAAiB;GACxB,QAAQ,aAAa;GACtB,CACF;;;;;CAMH,YAAY,SAAuB;EACjC,MAAM,gBAAgB,KAAK,QAAQ,SAAS,QAAQ;AACpD,MAAI,CAAC,cACH;AAEF,OAAK,QAAQ,YAAY,QAAQ;AACjC,OAAK,UAAU,kBACb,CACE;GACE;GACA,MAAM;GACP,CACF,EACD;GACE,OAAO,iBAAiB;GACxB,QAAQ,aAAa;GACtB,CACF;;;;;;;CAQH,SAAS,QAAyC;AAEhD,SAAO,IADe,cAAc,KAAK,QACzB,CAAC,SAAS,OAAO;;;;;;;;CASnC,UAAU,eAAwC,QAAwB;AACxE,OAAK,gBAAgB;EACrB,MAAM,YAAY,KAAK,uBAAuB;EAC9C,MAAM,qBAAqB,IAAI,IAAI,KAAK,QAAQ,YAAY,MAAM,CAAC;EAEnE,MAAM,YAAY,IADI,cAAc,KAAK,QACd,CAAC,UAAU,eAAe,OAAO;EAC5D,MAAM,gBAAgB,MAAM,KAAK,KAAK,QAAQ,YAAY,MAAM,CAAC,CAAC,QAC/D,WAAW,CAAC,mBAAmB,IAAI,OAAO,CAC5C;AAED,OAAK,MAAM,UAAU,eAAe;GAClC,MAAM,OAAO,KAAK,QAAQ,YAAY,IAAI,OAAO;AACjD,OAAI,MAAM;AACR,SAAK,aAAa,UAAU;AAC5B,SAAK,cAAc,UAAU;;;AAGjC,OAAK,0BAA0B,OAAO,UAAU,UAAU;AAE1D,SAAO"}
1
+ {"version":3,"file":"editor.mjs","names":[],"sources":["../src/editor/undo-redo.ts","../src/editor/response-naming.ts","../src/editor/item-copy-paste.ts","../src/editor/session-schema.ts","../src/editor/survey-editor.ts"],"sourcesContent":["import type { CompositionSurvey as RawSurvey } from \"../survey/composition/registry\";\ntype RawSurveyAsset = NonNullable<RawSurvey[\"assets\"]>[string];\nimport { generateId, structuredCloneMethod } from \"../utils\";\nimport { setOwnValue } from \"../schema/string-record\";\n\nexport interface UndoRedoConfig {\n maxTotalMemoryMB: number;\n minHistorySize: number;\n maxHistorySize: number;\n}\n\nexport const CommitSource = {\n USER: \"user\",\n SYSTEM: \"system\",\n ASSISTANT: \"assistant\",\n} as const;\nexport type CommitSource = (typeof CommitSource)[keyof typeof CommitSource];\n\nexport interface CommitMeta {\n label: string;\n source?: CommitSource;\n}\n\nexport interface AssetPatch {\n assetId: string;\n prev?: RawSurveyAsset;\n next?: RawSurveyAsset;\n}\n\ninterface BaseHistoryEntry {\n id?: string;\n timestamp: number;\n meta: CommitMeta;\n memorySize: number;\n}\n\ninterface SurveySnapshotHistoryEntry extends BaseHistoryEntry {\n kind: \"survey-snapshot\";\n survey: RawSurvey;\n changes?: AssetPatch[];\n}\n\ninterface AssetChangeHistoryEntry extends BaseHistoryEntry {\n kind: \"asset-change\";\n changes: AssetPatch[];\n}\n\ntype HistoryEntry = SurveySnapshotHistoryEntry | AssetChangeHistoryEntry;\ntype PendingHistoryEntry =\n | Omit<SurveySnapshotHistoryEntry, \"timestamp\" | \"memorySize\">\n | Omit<AssetChangeHistoryEntry, \"timestamp\" | \"memorySize\">;\n\nexport interface SurveyEditorHistoryCommit {\n index: number;\n kind: HistoryEntry[\"kind\"];\n meta: CommitMeta;\n timestamp: number;\n memorySize: number;\n isCurrent: boolean;\n}\n\ntype SerializedHistoryEntry = HistoryEntry;\n\n// Memory calculation utilities\nclass MemoryCalculator {\n private static encoder = new TextEncoder();\n\n static calculateSize(obj: object): number {\n const jsonString = JSON.stringify(obj);\n return this.encoder.encode(jsonString).length;\n }\n\n static formatBytes(bytes: number): string {\n const units = [\"B\", \"KB\", \"MB\", \"GB\"];\n let size = bytes;\n let unitIndex = 0;\n\n while (size >= 1024 && unitIndex < units.length - 1) {\n size /= 1024;\n unitIndex++;\n }\n\n return `${size.toFixed(1)} ${units[unitIndex]}`;\n }\n}\n\nfunction cloneAssets(\n assets?: Record<string, RawSurveyAsset>,\n): Record<string, RawSurveyAsset> | undefined {\n if (!assets || Object.keys(assets).length === 0) {\n return undefined;\n }\n return structuredCloneMethod(assets);\n}\n\nfunction normalizeHistoryEntry(entry: SerializedHistoryEntry): HistoryEntry {\n if (entry.kind !== \"survey-snapshot\" && entry.kind !== \"asset-change\")\n throw new Error(\"Unsupported history entry kind\");\n return { ...structuredCloneMethod(entry), id: entry.id ?? generateId() };\n}\n\nexport class SurveyEditorUndoRedo {\n private history: HistoryEntry[] = [];\n private currentIndex: number = -1;\n private _config: UndoRedoConfig;\n private baseAssetSize?: number;\n private _initialAssets?: Record<string, RawSurveyAsset>;\n\n constructor(\n initialSurvey: RawSurvey,\n config: Partial<UndoRedoConfig> = {},\n meta: CommitMeta = { label: \"Initial state\", source: CommitSource.SYSTEM },\n initialAssets?: Record<string, RawSurveyAsset>,\n ) {\n this._config = {\n maxTotalMemoryMB: 50,\n minHistorySize: 10,\n maxHistorySize: 200,\n ...config,\n };\n this._initialAssets = cloneAssets(initialAssets);\n\n this.saveSnapshot(initialSurvey, meta);\n }\n\n private saveEntry(entry: PendingHistoryEntry): void {\n const payload =\n entry.kind === \"survey-snapshot\"\n ? { kind: entry.kind, survey: entry.survey, changes: entry.changes }\n : { kind: entry.kind, changes: entry.changes };\n\n const memorySize = MemoryCalculator.calculateSize(payload);\n\n // Remove any history after current index\n this.history = this.history.slice(0, this.currentIndex + 1);\n\n this.history.push({\n ...structuredCloneMethod(entry),\n id: generateId(),\n timestamp: Date.now(),\n memorySize,\n } as HistoryEntry);\n\n this.currentIndex++;\n\n // Clean up history based on memory usage\n this.cleanupHistory();\n }\n\n private saveSnapshot(survey: RawSurvey, meta: CommitMeta): void {\n this.saveEntry({\n kind: \"survey-snapshot\",\n survey,\n meta,\n });\n }\n\n private getBaseAssetsSize(): number {\n return (this.baseAssetSize ??= this._initialAssets\n ? MemoryCalculator.calculateSize(this._initialAssets)\n : 0);\n }\n\n private cleanupHistory(): void {\n const maxMemoryBytes = this._config.maxTotalMemoryMB * 1024 * 1024;\n\n // Remove oldest states while preserving minimum.\n while (\n this.history.length > this._config.minHistorySize &&\n (this.getTotalMemoryUsage() > maxMemoryBytes ||\n this.history.length > this._config.maxHistorySize)\n ) {\n if (this.dropOldestState() <= 0) {\n break;\n }\n }\n }\n\n private dropOldestState(): number {\n if (this.history.length <= 1) {\n return 0;\n }\n\n const nextStateIndex = 1;\n const nextStateSurvey = this.getStateAtIndex(nextStateIndex);\n const nextStateAssets = this.getAssetsAtIndex(nextStateIndex);\n const nextEntry = this.history[nextStateIndex];\n\n const newFirstEntry: SurveySnapshotHistoryEntry = {\n kind: \"survey-snapshot\",\n id: nextEntry.id,\n survey: nextStateSurvey,\n meta: nextEntry.meta,\n timestamp: nextEntry.timestamp,\n memorySize: MemoryCalculator.calculateSize({\n kind: \"survey-snapshot\",\n survey: nextStateSurvey,\n }),\n };\n\n const removedBytes = this.history[0].memorySize;\n\n this._initialAssets = nextStateAssets;\n this.baseAssetSize = undefined;\n this.history = [newFirstEntry, ...this.history.slice(nextStateIndex + 1)];\n this.currentIndex--;\n\n return removedBytes;\n }\n\n private getTotalMemoryUsage(): number {\n return (\n this.getBaseAssetsSize() + this.history.reduce((total, entry) => total + entry.memorySize, 0)\n );\n }\n\n private getStateAtIndex(index: number): RawSurvey {\n if (index < 0 || index >= this.history.length) {\n throw new Error(\"Invalid history state\");\n }\n\n for (let i = index; i >= 0; i--) {\n const entry = this.history[i];\n if (entry.kind === \"survey-snapshot\") {\n return structuredCloneMethod(entry.survey);\n }\n }\n\n throw new Error(\"Invalid history state\");\n }\n\n private applyAssetPatch(\n assets: Record<string, RawSurveyAsset>,\n patch: AssetPatch,\n ): Record<string, RawSurveyAsset> {\n const nextAssets = assets;\n if (patch.next) {\n setOwnValue(nextAssets, patch.assetId, structuredCloneMethod(patch.next));\n } else {\n delete nextAssets[patch.assetId];\n }\n return nextAssets;\n }\n\n private getAssetsAtIndex(index: number): Record<string, RawSurveyAsset> | undefined {\n if (index < 0 || index >= this.history.length) {\n throw new Error(\"Invalid history state\");\n }\n\n let assets = cloneAssets(this._initialAssets) ?? {};\n\n for (let i = 1; i <= index; i++) {\n const entry = this.history[i];\n for (const patch of entry.changes ?? []) {\n assets = this.applyAssetPatch(assets, patch);\n }\n }\n\n return Object.keys(assets).length > 0 ? assets : undefined;\n }\n\n getEntryId(index: number): string | undefined {\n return this.history[index]?.id;\n }\n\n findEntryIndex(id: string): number {\n return this.history.findIndex((entry) => entry.id === id);\n }\n\n // Commit a change to history\n commit(survey: RawSurvey, meta: CommitMeta, changes?: AssetPatch[]): void {\n this.saveEntry({\n kind: \"survey-snapshot\",\n survey,\n meta,\n ...(changes?.length ? { changes } : {}),\n });\n }\n\n commitAssetChange(changes: AssetPatch[], meta: CommitMeta): void {\n if (changes.length === 0) {\n return;\n }\n\n this.saveEntry({\n kind: \"asset-change\",\n changes: structuredCloneMethod(changes),\n meta,\n });\n }\n\n // Get current committed state\n getCurrentState(): RawSurvey {\n if (this.currentIndex < 0 || this.currentIndex >= this.history.length) {\n throw new Error(\"Invalid history state\");\n }\n return this.getStateAtIndex(this.currentIndex);\n }\n\n getCurrentAssets(): Record<string, RawSurveyAsset> | undefined {\n if (this.currentIndex < 0 || this.currentIndex >= this.history.length) {\n throw new Error(\"Invalid history state\");\n }\n return this.getAssetsAtIndex(this.currentIndex);\n }\n\n undo(): RawSurvey | null {\n if (!this.canUndo()) return null;\n\n this.currentIndex--;\n return this.getCurrentState();\n }\n\n redo(): RawSurvey | null {\n if (!this.canRedo()) return null;\n\n this.currentIndex++;\n return this.getCurrentState();\n }\n\n canUndo(): boolean {\n return this.currentIndex > 0;\n }\n\n canRedo(): boolean {\n return this.currentIndex < this.history.length - 1;\n }\n\n getUndoMeta(): CommitMeta | null {\n if (!this.canUndo()) return null;\n return this.history[this.currentIndex].meta;\n }\n\n getRedoMeta(): CommitMeta | null {\n if (!this.canRedo()) return null;\n return this.history[this.currentIndex + 1].meta;\n }\n\n getMemoryUsage(): { totalMB: number; entries: number } {\n return {\n totalMB: this.getTotalMemoryUsage() / (1024 * 1024),\n entries: this.history.length,\n };\n }\n\n getConfig(): UndoRedoConfig {\n return { ...this._config };\n }\n\n /**\n * Get the full history list with metadata\n */\n getHistory(): Array<{\n index: number;\n kind: HistoryEntry[\"kind\"];\n meta: CommitMeta;\n timestamp: number;\n memorySize: number;\n isCurrent: boolean;\n }> {\n return this.history.map((entry, index) => ({\n index,\n kind: entry.kind,\n meta: entry.meta,\n id: entry.id ?? generateId(),\n timestamp: entry.timestamp,\n memorySize: entry.memorySize,\n isCurrent: index === this.currentIndex,\n }));\n }\n\n /**\n * Get committed history entries after the initial state up to the current index.\n *\n * Redo-only future entries are intentionally omitted so the returned list describes the active\n * change chain from the initial state to the current editor state.\n */\n getCommitsSinceInitial(): SurveyEditorHistoryCommit[] {\n return this.history.slice(1, this.currentIndex + 1).map((entry, offset) => {\n const index = offset + 1;\n return {\n index,\n kind: entry.kind,\n meta: entry.meta,\n id: entry.id ?? generateId(),\n timestamp: entry.timestamp,\n memorySize: entry.memorySize,\n isCurrent: index === this.currentIndex,\n };\n });\n }\n\n /**\n * Get the current index in the history\n */\n getCurrentIndex(): number {\n return this.currentIndex;\n }\n\n /**\n * Get the total number of history entries\n */\n getHistoryLength(): number {\n return this.history.length;\n }\n\n /**\n * Jump to a specific index in the history (can go forward or backward)\n * @param targetIndex The index to jump to\n * @returns The survey state at the target index, or null if invalid\n */\n jumpToIndex(targetIndex: number): RawSurvey | null {\n if (\n targetIndex < 0 ||\n targetIndex >= this.history.length ||\n targetIndex === this.currentIndex\n ) {\n return null;\n }\n\n this.currentIndex = targetIndex;\n return this.getCurrentState();\n }\n\n /**\n * Check if we can jump to a specific index\n */\n canJumpToIndex(targetIndex: number): boolean {\n return (\n targetIndex >= 0 && targetIndex < this.history.length && targetIndex !== this.currentIndex\n );\n }\n\n /**\n * Serialize the undo/redo state to JSON\n * @returns A JSON-serializable object containing the complete state\n */\n serialize(): {\n history: Array<HistoryEntry>;\n currentIndex: number;\n config: UndoRedoConfig;\n initialAssets?: Record<string, RawSurveyAsset>;\n } {\n return {\n history: this.history.map((entry) => {\n if (entry.kind === \"survey-snapshot\") {\n return {\n kind: \"survey-snapshot\",\n survey: entry.survey,\n changes: entry.changes,\n id: entry.id ?? generateId(),\n timestamp: entry.timestamp,\n meta: entry.meta,\n memorySize: entry.memorySize,\n };\n }\n\n return {\n kind: \"asset-change\",\n changes: entry.changes,\n id: entry.id ?? generateId(),\n timestamp: entry.timestamp,\n meta: entry.meta,\n memorySize: entry.memorySize,\n };\n }),\n currentIndex: this.currentIndex,\n config: { ...this._config },\n initialAssets: cloneAssets(this._initialAssets),\n };\n }\n\n /**\n * Create a new SurveyEditorUndoRedo instance from JSON data\n * @param jsonData The serialized undo/redo state\n * @returns A new SurveyEditorUndoRedo instance with the restored state\n */\n static deserialize(\n jsonData: {\n history: Array<SerializedHistoryEntry>;\n currentIndex: number;\n config: UndoRedoConfig;\n initialAssets?: Record<string, RawSurveyAsset>;\n },\n initialAssetsOverride?: Record<string, RawSurveyAsset>,\n ): SurveyEditorUndoRedo {\n if (!jsonData.history || !Array.isArray(jsonData.history) || jsonData.history.length === 0) {\n throw new Error(\"Invalid object: history must be an array and must not be empty\");\n }\n\n if (\n typeof jsonData.currentIndex !== \"number\" ||\n jsonData.currentIndex < 0 ||\n jsonData.currentIndex >= jsonData.history.length\n ) {\n throw new Error(\n \"Invalid object: currentIndex must be a valid index within the history array\",\n );\n }\n\n if (!jsonData.config) {\n throw new Error(\"Invalid object: config is required\");\n }\n\n const normalizedHistory = jsonData.history.map(normalizeHistoryEntry);\n\n // Create a new instance with the first survey and config\n const firstEntry = normalizedHistory[0];\n const firstSurvey =\n firstEntry.kind === \"survey-snapshot\"\n ? firstEntry.survey\n : (() => {\n throw new Error(\n \"Invalid object: first history entry must resolve to a survey snapshot\",\n );\n })();\n\n const instance = new SurveyEditorUndoRedo(\n firstSurvey,\n jsonData.config,\n firstEntry.meta,\n initialAssetsOverride ?? jsonData.initialAssets,\n );\n\n // Clear the default initial state and restore the full history\n instance.history = normalizedHistory;\n instance.currentIndex = jsonData.currentIndex;\n instance._initialAssets = cloneAssets(initialAssetsOverride ?? jsonData.initialAssets);\n\n return instance;\n }\n}\n","import type { z } from \"zod\";\nimport { transformAnnotated } from \"../schema/annotations\";\nimport type { ElementRegistry } from \"../survey/composition/registry\";\nimport { allocateResponseVariableName } from \"../survey/responses/variable-naming\";\nimport {\n getDefaultProjectionIssues,\n localizedExportSlots,\n projectSlot,\n} from \"../response-exporter/projection\";\nimport { Survey } from \"../survey/composition/document\";\nimport {\n isValidResponseVariableName,\n type ReadonlyResponseSlotDefinition,\n} from \"../survey/responses\";\nimport { ownValue, setOwnValue } from \"../schema/string-record\";\n\nexport interface ResponseNameChange {\n slotId: string;\n itemId: string;\n before: string;\n after: string;\n}\nexport type ResponseNamingEdit =\n | { slotId: string; variableName: string }\n | {\n elementId: string;\n prefix?: string;\n rows?: Record<string, string>;\n columns?: Record<string, string>;\n };\n\nfunction readPath(input: unknown, path: readonly (string | number)[]): unknown {\n let value = input;\n for (const key of path) {\n if (Array.isArray(value) && typeof key === \"number\") value = value[key];\n else if (\n value !== null &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n Object.hasOwn(value, key)\n )\n value = Reflect.get(value, key);\n else throw new Error(\"Response naming declaration does not match its config\");\n }\n return value;\n}\nfunction writePath(input: unknown, path: readonly (string | number)[], value: unknown): void {\n if (!path.length) throw new Error(\"Invalid response naming path\");\n const parent = readPath(input, path.slice(0, -1));\n if (!parent || typeof parent !== \"object\")\n throw new Error(\"Response naming declaration does not match its config\");\n const key = path.at(-1)!;\n if (Array.isArray(parent) && typeof key === \"number\") parent[key] = value;\n else setOwnValue(parent as Record<string, unknown>, String(key), value);\n}\nconst assertName = (name: string) => {\n if (!isValidResponseVariableName(name))\n throw new Error(\n `Invalid variable name \"${name}\". Use lowercase snake_case, starting with a letter, at most 32 characters.`,\n );\n};\n\n/** Detached, validated preview; applying it uses the editor's ordinary mutation/history path. */\nfunction previewNaming(survey: Survey, edits: readonly ResponseNamingEdit[]) {\n const registry = survey.slots;\n const raw = structuredClone(survey.serialize());\n const config = (slot: ReadonlyResponseSlotDefinition) =>\n readPath(raw, [...survey.elements.get(slot.elementId)!.path, \"config\"]);\n for (const edit of edits) {\n if (\"slotId\" in edit) {\n const slot = registry.get(edit.slotId);\n if (!slot) throw new Error(`Unknown response variable \"${edit.slotId}\"`);\n if (slot.naming?.kind === \"matrix\")\n throw new Error(\n \"Matrix cell names are derived; edit the matrix prefix or row/column coding names\",\n );\n if (!slot.naming)\n throw new Error(`The input owning \"${edit.slotId}\" does not expose a naming mutation`);\n assertName(edit.variableName);\n writePath(config(slot), slot.naming.path, edit.variableName);\n } else {\n const slots = registry.definitions.filter(\n (slot) => slot.elementId === edit.elementId && slot.naming?.kind === \"matrix\",\n );\n if (!slots.length) throw new Error(`Unknown matrix element \"${edit.elementId}\"`);\n for (const [ids, kind] of [\n [edit.rows, \"row\"],\n [edit.columns, \"column\"],\n ] as const) {\n for (const [id, name] of Object.entries(ids ?? {})) {\n assertName(name);\n const slot = slots.find((slot) =>\n kind === \"row\" ? slot.rowId === id : slot.columnId === id,\n );\n const naming = slot?.naming;\n const path =\n naming?.kind === \"matrix\"\n ? kind === \"row\"\n ? naming.rowPath\n : naming.columnPath\n : undefined;\n if (!slot || !path) throw new Error(`Unknown matrix ${kind} \"${id}\"`);\n writePath(config(slot), path, name);\n }\n }\n if (edit.prefix !== undefined) {\n assertName(edit.prefix);\n const slot = slots[0],\n naming = slot.naming;\n if (naming?.kind === \"matrix\") writePath(config(slot), naming.prefixPath, edit.prefix);\n }\n }\n }\n const next = Survey.parse(raw, survey.registry, { admission: \"draft\" });\n const nextRegistry = next.slots;\n const beforeIssues = new Set(registry.diagnostics.map((issue) => JSON.stringify(issue)));\n const issues = nextRegistry.diagnostics.filter(\n (issue) => !beforeIssues.has(JSON.stringify(issue)),\n );\n if (issues.length) throw new Error(issues.map((issue) => issue.message).join(\"\\n\"));\n const changes: ResponseNameChange[] = nextRegistry.definitions.flatMap((slot) => {\n const before = registry.get(slot.slotId)!.variableName;\n return before === slot.variableName\n ? []\n : [{ slotId: slot.slotId, itemId: slot.itemId, before, after: slot.variableName }];\n });\n return { survey: next.serialize(), changes };\n}\n\nfunction assertProjectionChanges(before: Survey, after: Survey): void {\n const existing = new Set(getDefaultProjectionIssues(before));\n const introduced = getDefaultProjectionIssues(after).filter((issue) => !existing.has(issue));\n if (introduced.length) throw new Error(introduced.join(\"\\n\"));\n}\n\nexport function previewResponseNaming(survey: Survey, edits: readonly ResponseNamingEdit[]) {\n const preview = previewNaming(survey, edits);\n assertProjectionChanges(\n survey,\n Survey.parse(preview.survey, survey.registry, { admission: \"draft\" }),\n );\n return preview;\n}\n\nexport interface ResponseSettingsEdit {\n slotId: string;\n optionCodes?: Record<string, string>;\n exportSettings?: import(\"../response-exporter/types\").SlotTransformConfig;\n}\n\n/** Naming, categorical codes, and formats share one detached, atomic preview. */\nexport function previewResponseSettings(\n survey: Survey,\n naming: readonly ResponseNamingEdit[],\n settings: readonly ResponseSettingsEdit[],\n) {\n const preview = previewNaming(survey, naming);\n const raw = preview.survey;\n const registry = survey.slots;\n const codeWrites = new Map<string, { code: string; slotId: string }>();\n for (const edit of settings) {\n const slot = registry.get(edit.slotId);\n if (!slot) throw new Error(`Unknown response variable \"${edit.slotId}\"`);\n const path = survey.elements.get(slot.elementId)!.path;\n const element = survey.registry.elementSchema.parse(readPath(raw, path));\n for (const [id, code] of Object.entries(edit.optionCodes ?? {})) {\n const path = ownValue(slot.optionCodePaths, id);\n if (!path) throw new Error(`Option \"${id}\" does not expose an export-code mutation`);\n if (!code.trim()) throw new Error(\"Option export codes cannot be empty\");\n const target = JSON.stringify([slot.elementId, path]);\n const previous = codeWrites.get(target);\n if (previous && previous.code !== code)\n throw new Error(\n `Conflicting export codes for shared option \"${id}\" on variables \"${registry.get(previous.slotId)!.variableName}\" and \"${slot.variableName}\". Supply one code for this shared option.`,\n );\n codeWrites.set(target, { code, slotId: slot.slotId });\n writePath(element.config, path, code);\n }\n if (edit.exportSettings)\n element.exportSettings = {\n ...element.exportSettings,\n [slot.slotId]: structuredClone(edit.exportSettings),\n };\n writePath(raw, path, element);\n }\n const next = Survey.parse(raw, survey.registry, { admission: \"draft\" });\n // Validate only affected variables so another unfinished input cannot block this edit.\n for (const slot of localizedExportSlots(next).filter((slot) =>\n settings.some((edit) => edit.slotId === slot.slotId),\n )) {\n projectSlot(slot, { mode: \"default\", ...slot.exportSettings });\n }\n assertProjectionChanges(survey, next);\n return { ...preview, survey: next.serialize() };\n}\n\n/** Allocate names using declared mutation locations, including every nested element. */\nexport function allocateCopiedResponseNames<S extends z.ZodType>(\n schema: S,\n input: z.output<S>,\n registry: ElementRegistry,\n occupied: ReadonlySet<string>,\n): z.output<S> {\n const used = new Set(occupied);\n return transformAnnotated(schema, input, ({ annotation, value }) => {\n if (\n annotation.kind !== \"owner\" ||\n !value ||\n typeof value !== \"object\" ||\n !(\"kind\" in value) ||\n value.kind !== \"element\"\n )\n return value;\n const node = registry.elementSchema.parse(value);\n const definition = registry.get(node.elementType);\n const paths = new Map<\n string,\n { path: (string | number)[]; base: string; slots: Set<string>; maxLength: number }\n >();\n for (const slot of definition.inspect(node).slots) {\n const naming = slot.naming;\n if (!naming) {\n if (used.has(slot.variableName))\n throw new Error(\n `Cannot copy variable '${slot.variableName}': element '${node.elementType}' must declare a naming location to resolve the duplicate name`,\n );\n used.add(slot.variableName);\n continue;\n }\n const path = [\"config\", ...(naming.kind === \"variable\" ? naming.path : naming.prefixPath)];\n const base = readPath(node, path);\n if (typeof base !== \"string\") throw new Error(\"Invalid response naming location\");\n const key = JSON.stringify(path);\n const group = paths.get(key) ?? { path, base, slots: new Set<string>(), maxLength: 32 };\n group.slots.add(slot.slotId);\n group.maxLength = Math.min(group.maxLength, 32 - (slot.variableName.length - base.length));\n paths.set(key, group);\n }\n for (const { path, base, slots, maxLength } of paths.values()) {\n let candidate = base,\n attempts = 0;\n const names = () =>\n definition\n .inspect(node)\n .slots.filter((slot) => slots.has(slot.slotId))\n .map((slot) => slot.variableName);\n while (names().some((name) => used.has(name))) {\n if (++attempts > used.size + 1)\n throw new Error(\n `Element '${node.elementType}' does not honor its declared naming location`,\n );\n const before = names();\n candidate = allocateResponseVariableName(candidate, new Set([candidate]), maxLength);\n writePath(node, path, candidate);\n if (before.every((name, index) => name === names()[index]))\n throw new Error(\n `Element '${node.elementType}' does not honor its declared naming location`,\n );\n }\n names().forEach((name) => used.add(name));\n }\n return node;\n });\n}\n","import { z } from \"zod\";\nimport { inspectAnnotated, referenceId, remapAnnotated } from \"../schema/annotations\";\nimport { Survey, checkDocumentBudget } from \"../survey/composition/document\";\nimport type { CompositionSurvey, ElementRegistry, FlowItem } from \"../survey/composition/registry\";\nimport { generateId } from \"../utils\";\nimport { allocateCopiedResponseNames } from \"./response-naming\";\nimport { ownValue } from \"../schema/string-record\";\n\nexport interface SurveyItemClipboardData {\n type: \"survey-item\";\n version: 2;\n rootItemId: string;\n surveyItems: FlowItem[];\n translations?: CompositionSurvey[\"translations\"];\n assets?: CompositionSurvey[\"assets\"];\n}\n\n/** Only the current format is accepted. Parsing is repeated at the paste boundary. */\nexport function createItemClipboardSchema(\n registry: ElementRegistry,\n): z.ZodType<SurveyItemClipboardData> {\n const shape = registry.surveySchema.shape;\n return z\n .strictObject({\n type: z.literal(\"survey-item\"),\n version: z.literal(2),\n rootItemId: referenceId(\"item\"),\n surveyItems: shape.surveyItems,\n translations: shape.translations,\n assets: shape.assets,\n })\n .superRefine((payload, ctx) => {\n const items = new Map(payload.surveyItems.map((item) => [item.id, item]));\n const visited = new Set<string>();\n const visit = (id: string) => {\n if (visited.has(id)) {\n ctx.addIssue({ code: \"custom\", message: \"Clipboard flow must be a tree\" });\n return;\n }\n visited.add(id);\n const item = items.get(id);\n if (!item) {\n ctx.addIssue({\n code: \"custom\",\n message: \"Clipboard flow cannot reference an external child\",\n });\n return;\n }\n if (item.itemType === \"group\") {\n if (item.config.isRoot)\n ctx.addIssue({ code: \"custom\", message: \"A root group cannot be pasted\" });\n item.config.items.forEach(visit);\n }\n };\n visit(payload.rootItemId);\n if (items.size !== payload.surveyItems.length || visited.size !== items.size)\n ctx.addIssue({\n code: \"custom\",\n message: \"Clipboard contains duplicate or disconnected flow items\",\n });\n });\n}\n\nexport function copySurveyItem(survey: Survey, itemId: string): SurveyItemClipboardData {\n if (!survey.getItem(itemId)) throw new Error(`Unknown item '${itemId}'`);\n const items = survey.data.surveyItems.filter((item) => survey.isDescendantOf(item.id, itemId));\n const itemIds = new Set(items.map((item) => item.id));\n const owners = new Set(\n [...survey.owners.values()]\n .filter((owner) => itemIds.has(owner.itemId))\n .map((owner) => owner.id),\n );\n const payload: SurveyItemClipboardData = {\n type: \"survey-item\",\n version: 2,\n rootItemId: itemId,\n surveyItems: structuredClone(items).map((item) =>\n item.itemType === \"group\" && item.config.isRoot\n ? { ...item, config: { ...item.config, isRoot: false } }\n : item,\n ),\n translations: Object.fromEntries(\n Object.entries(survey.data.translations ?? {}).flatMap(([locale, translation]) => {\n const content = Object.fromEntries(\n Object.entries(translation.content).filter(\n ([id, roles]) => owners.has(id) && Object.keys(roles).length > 0,\n ),\n );\n return Object.keys(content).length ? [[locale, { content }]] : [];\n }),\n ),\n };\n const schema = createItemClipboardSchema(survey.registry);\n const assetIds = new Set(\n inspectAnnotated(schema, payload).flatMap(({ annotation, value }) =>\n annotation.kind === \"reference\" && annotation.target === \"asset\" && typeof value === \"string\"\n ? [value]\n : [],\n ),\n );\n payload.assets = Object.fromEntries(\n [...assetIds].map((id) => [id, ownValue(survey.data.assets, id)!]),\n );\n return schema.parse(payload);\n}\n\n/** Prepare a detached payload; the editor publishes it only after whole-document validation. */\nexport function prepareItemPaste(survey: Survey, input: unknown): SurveyItemClipboardData {\n checkDocumentBudget(input);\n const schema = createItemClipboardSchema(survey.registry);\n const payload = schema.parse(input);\n const ids = new Map<string, string>();\n for (const { annotation, value } of inspectAnnotated(schema, payload)) {\n if (annotation.kind !== \"identity\" || typeof value !== \"string\") continue;\n if (ids.has(value)) throw new Error(`Duplicate clipboard identity '${value}'`);\n // Reuse an identical image asset; conflicting bytes must never replace the destination's asset.\n const reuse =\n annotation.identity === \"asset\" &&\n JSON.stringify(ownValue(survey.data.assets, value)) ===\n JSON.stringify(ownValue(payload.assets, value));\n ids.set(value, reuse ? value : generateId());\n }\n return allocateCopiedResponseNames(\n schema,\n remapAnnotated(schema, payload, ids),\n survey.registry,\n new Set(survey.slots.definitions.map((slot) => slot.variableName)),\n );\n}\n","import { stringRecord } from \"../schema/string-record\";\nimport { z } from \"zod\";\nimport type {\n CompositionSurvey,\n ElementRegistry,\n RawSurveyAsset,\n} from \"../survey/composition/registry\";\nimport { CommitSource } from \"./undo-redo\";\nimport { answerTypeReservationsSchema } from \"../schema/answer-types\";\nimport type { SerializedSurveyEditor } from \"./survey-editor\";\n\n/** The saved editor session is separate from both survey definitions and participant resume state. */\nexport function createEditorSessionSchema(\n registry: ElementRegistry,\n): z.ZodType<SerializedSurveyEditor> {\n // Named, schema-inferred payload boundaries keep emitted declarations bounded.\n const survey: z.ZodType<CompositionSurvey> = registry.surveySchema;\n const asset: z.ZodType<RawSurveyAsset, RawSurveyAsset> =\n registry.surveySchema.shape.assets.unwrap().valueType;\n const assets = stringRecord(z.string().min(1), asset);\n const patch = z.strictObject({\n assetId: z.string().min(1),\n prev: asset.optional(),\n next: asset.optional(),\n });\n const entry = {\n id: z.string().min(1).optional(),\n timestamp: z.number().finite(),\n memorySize: z.number().nonnegative().finite(),\n meta: z.strictObject({ label: z.string(), source: z.enum(CommitSource).optional() }),\n };\n return z.strictObject({\n version: z.literal(2),\n survey,\n hasUncommittedChanges: z.boolean(),\n answerTypes: answerTypeReservationsSchema,\n undoRedo: z\n .strictObject({\n history: z\n .array(\n z.discriminatedUnion(\"kind\", [\n z.strictObject({\n ...entry,\n kind: z.literal(\"survey-snapshot\"),\n survey,\n changes: z.array(patch).optional(),\n }),\n z.strictObject({\n ...entry,\n kind: z.literal(\"asset-change\"),\n changes: z.array(patch),\n }),\n ]),\n )\n .min(1),\n currentIndex: z.number().int().nonnegative(),\n initialAssets: assets.optional(),\n config: z.strictObject({\n maxTotalMemoryMB: z.number().positive().finite(),\n minHistorySize: z.number().int().nonnegative(),\n maxHistorySize: z.number().int().positive(),\n }),\n })\n .superRefine((value, context) => {\n if (value.currentIndex >= value.history.length)\n context.addIssue({\n code: \"custom\",\n path: [\"currentIndex\"],\n message: \"History index is outside the stored history\",\n });\n if (value.history[0]?.kind !== \"survey-snapshot\")\n context.addIssue({\n code: \"custom\",\n path: [\"history\", 0],\n message: \"History must start with a survey snapshot\",\n });\n }),\n });\n}\n","import { expressionSchema } from \"../expressions/schema\";\nimport { transformExpression } from \"../expressions/tree\";\nimport { copySurveyItem, prepareItemPaste } from \"./item-copy-paste\";\nimport { Survey, DefinitionError, type DefinitionDiagnostic } from \"../survey/composition/document\";\nimport { createEditorSessionSchema } from \"./session-schema\";\nimport {\n allocateCopiedResponseNames,\n previewResponseSettings,\n type ResponseNamingEdit,\n type ResponseSettingsEdit,\n} from \"./response-naming\";\nimport type { Target } from \"./types\";\nimport type {\n CompositionSurvey,\n ElementRegistry,\n RawSurveyAsset,\n RuntimeElement,\n FlowItem,\n SurveyCardContent,\n NavigationContent,\n TemplateValueDefinition,\n} from \"../survey/composition/registry\";\nimport { SurveyStateGraph } from \"../engine/survey-state-graph\";\nimport { getDefaultProjectionDiagnostics } from \"../response-exporter/projection\";\nimport { generateId } from \"../utils\";\nimport { ownValue, setOwnValue } from \"../schema/string-record\";\nimport type { ValueType } from \"../survey/responses/value-types\";\nimport { answerTypeReservationsSchema, type AnswerTypeReservations } from \"../schema/answer-types\";\nimport {\n inspectAnnotated,\n contentOwnerIds,\n remapAnnotated,\n annotatedReferences,\n transformAnnotated,\n} from \"../schema/annotations\";\nimport type { Content } from \"../survey/utils/content\";\nimport { readLocalizationContent, type LocalizationRef } from \"../survey/utils/localization\";\nimport {\n SurveyEditorUndoRedo,\n CommitSource,\n type CommitMeta,\n type UndoRedoConfig,\n type AssetPatch,\n} from \"./undo-redo\";\n\ntype Path = readonly (string | number)[];\nconst record = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\nfunction at(input: unknown, path: Path): unknown {\n let value = input;\n for (const part of path) {\n if (Array.isArray(value) && typeof part === \"number\") value = value[part];\n else if (record(value)) value = ownValue(value, String(part));\n else throw new Error(`Invalid derived location ${JSON.stringify(path)}`);\n }\n return value;\n}\nfunction arrayAt(input: unknown, path: Path): unknown[] {\n const value = at(input, path);\n if (!Array.isArray(value)) throw new Error(\"Expected array at derived location\");\n return value;\n}\nfunction setAt(input: unknown, path: Path, value: unknown) {\n const parent = at(input, path.slice(0, -1)),\n part = path.at(-1);\n if (Array.isArray(parent) && typeof part === \"number\") parent[part] = value;\n else if (record(parent) && typeof part === \"string\") setOwnValue(parent, part, value);\n else throw new Error(\"Invalid mutation location\");\n}\nconst inside = (ancestor: Path, path: Path) =>\n ancestor.length <= path.length && ancestor.every((part, i) => path[i] === part);\n\nexport interface SerializedSurveyEditor {\n version: 2;\n survey: CompositionSurvey;\n undoRedo: ReturnType<SurveyEditorUndoRedo[\"serialize\"]>;\n hasUncommittedChanges: boolean;\n /** Includes deleted answers and discarded history branches; never part of the survey format. */\n answerTypes: AnswerTypeReservations;\n}\n\nexport interface SurveyEditorOptions extends Partial<UndoRedoConfig> {\n /** Seed detached validation with the owning editor session's published answer types. */\n answerTypes?: AnswerTypeReservations;\n}\n\nfunction stripAssets(survey: CompositionSurvey): CompositionSurvey {\n const { assets: _assets, ...snapshot } = survey;\n return snapshot;\n}\n/** Compare persisted JSON semantics without depending on object property insertion order. */\nfunction equal(left: unknown, right: unknown): boolean {\n if (left === right) return true;\n if (Array.isArray(left) || Array.isArray(right))\n return (\n Array.isArray(left) &&\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((value, index) => equal(value, right[index]))\n );\n if (!record(left) || !record(right)) return false;\n const keys = Object.keys(left).filter((key) => left[key] !== undefined);\n return (\n keys.length === Object.keys(right).filter((key) => right[key] !== undefined).length &&\n keys.every((key) => Object.hasOwn(right, key) && equal(left[key], right[key]))\n );\n}\n\n/** Element mutations may edit their owned wording, never another owner's content or survey UI. */\nfunction assertElementTranslationScope(\n before: CompositionSurvey[\"translations\"],\n after: CompositionSurvey[\"translations\"],\n owners: ReadonlySet<string>,\n) {\n const surfaces = (\n translation: NonNullable<CompositionSurvey[\"translations\"]>[string] | undefined,\n ) => Object.fromEntries(Object.entries(translation ?? {}).filter(([key]) => key !== \"content\"));\n for (const locale of new Set([...Object.keys(before ?? {}), ...Object.keys(after ?? {})])) {\n const previous = ownValue(before, locale),\n next = ownValue(after, locale);\n if (!previous || !next || !equal(surfaces(previous), surfaces(next)))\n throw new Error(\n `Element edits cannot change survey-level translations or add/remove locale '${locale}'`,\n );\n for (const owner of new Set([\n ...Object.keys(previous?.content ?? {}),\n ...Object.keys(next?.content ?? {}),\n ]))\n if (\n !owners.has(owner) &&\n !equal(ownValue(previous?.content, owner), ownValue(next?.content, owner))\n )\n throw new Error(\n `Element edits cannot change content owned by '${owner}' in locale '${locale}'`,\n );\n }\n}\n\n/** Derive modification ownership from the committed revision, including nested localized content. */\nfunction timestampEditedItems(before: CompositionSurvey, after: Survey): Survey {\n const previous = new Map(before.surveyItems.map((item) => [item.id, item]));\n const positions = (items: readonly FlowItem[]) =>\n new Map(\n items.flatMap((item) =>\n item.itemType === \"group\"\n ? item.config.items.map((id, index) => [id, [item.id, index]] as const)\n : [],\n ),\n );\n const previousPositions = positions(before.surveyItems);\n const nextPositions = positions(after.data.surveyItems);\n const changed = new Set<string>();\n for (const item of after.data.surveyItems) {\n if (\n !equal(previous.get(item.id), item) ||\n !equal(previousPositions.get(item.id), nextPositions.get(item.id))\n )\n changed.add(item.id);\n }\n for (const locale of new Set([...Object.keys(before.translations ?? {}), ...after.locales])) {\n const oldContent = ownValue(before.translations, locale)?.content ?? {};\n const newContent = ownValue(after.data.translations, locale)?.content ?? {};\n for (const id of new Set([...Object.keys(oldContent), ...Object.keys(newContent)])) {\n if (equal(ownValue(oldContent, id), ownValue(newContent, id))) continue;\n const owner = after.owners.get(id);\n if (owner) changed.add(owner.itemId);\n }\n }\n const timestamp = new Date().toISOString();\n return after.withItemEditorMetadata(\n new Map(\n [...changed].map((id) => {\n const original = previous.get(id);\n return [\n id,\n {\n createdAt: original ? (original.editorMetadata?.createdAt ?? timestamp) : timestamp,\n updatedAt: timestamp,\n },\n ];\n }),\n ),\n );\n}\n\n/** A surviving answer identity cannot acquire a different wire value type. */\nexport function getAnswerTypeChangeDiagnostics(\n before: Survey,\n after: Survey,\n): DefinitionDiagnostic[] {\n if (before.slots === after.slots) return [];\n return answerTypeDiagnostics(after, (id) => before.slots.get(id)?.valueType);\n}\nfunction answerTypeDiagnostics(\n after: Survey,\n previousType: (id: string) => ValueType | undefined,\n): DefinitionDiagnostic[] {\n return after.slots.definitions.flatMap((slot) => {\n const previous = previousType(slot.slotId);\n return previous && previous !== slot.valueType\n ? [\n {\n code: \"answer-type-change\",\n severity: \"error\" as const,\n path:\n after.identities.get(slot.slotId)?.path ?? after.elements.get(slot.elementId)!.path,\n message: `Answer '${slot.variableName}' (${slot.slotId}) cannot change from ${previous} to ${slot.valueType} while keeping its ID. Allocate a new answer ID and explicitly repair its references, prefills and export settings in the same transaction.`,\n },\n ]\n : [];\n });\n}\nfunction assertStableAnswerTypes(before: Survey, after: Survey) {\n const diagnostics = getAnswerTypeChangeDiagnostics(before, after);\n if (diagnostics.length) throw new DefinitionError(diagnostics);\n}\n\n/** All human and assistant operations publish through this transaction/history owner. */\nexport class SurveyEditor {\n private current: Survey;\n private answerTypes = new Map<string, ValueType>();\n private rememberedSlots?: Survey[\"slots\"];\n private _history: SurveyEditorUndoRedo;\n private listeners = new Set<() => void>();\n private mutationEpoch = 0;\n private fieldWriteDepth = 0;\n private actionDepth = 0;\n private actionMeta?: CommitMeta;\n private pendingSurvey = false;\n private pendingAssets: AssetPatch[] = [];\n private pendingMeta?: CommitMeta;\n\n constructor(survey: Survey, options: SurveyEditorOptions = {}, meta?: CommitMeta) {\n const { answerTypes, ...config } = options;\n this.answerTypes = new Map(answerTypeReservationsSchema.parse(answerTypes ?? []));\n const diagnostics = answerTypeDiagnostics(survey, (id) => this.answerTypes.get(id));\n if (diagnostics.length) throw new DefinitionError(diagnostics);\n this.current = survey;\n this.rememberAnswerTypes(survey);\n const serialized = survey.serialize();\n this._history = new SurveyEditorUndoRedo(\n stripAssets(serialized),\n config,\n meta,\n serialized.assets,\n );\n }\n get survey() {\n return this.current;\n }\n get history() {\n return this._history;\n }\n getAnswerTypes(): AnswerTypeReservations {\n return [...this.answerTypes];\n }\n get hasUncommittedChanges() {\n return this.pendingSurvey || this.pendingAssets.length > 0;\n }\n get hasCommittedChanges() {\n return this.history.getCurrentIndex() > 0;\n }\n subscribe(listener: () => void) {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n private notify() {\n this.listeners.forEach((listener) => listener());\n }\n private rememberAnswerTypes(survey: Survey) {\n if (this.rememberedSlots === survey.slots) return;\n for (const slot of survey.slots.definitions) this.answerTypes.set(slot.slotId, slot.valueType);\n this.rememberedSlots = survey.slots;\n }\n private publish(next: Survey) {\n this.current = next;\n if (this.actionDepth) return;\n // Only published revisions reserve identities. Rolled-back compound actions do not.\n this.rememberAnswerTypes(next);\n this.mutationEpoch++;\n this.notify();\n }\n\n private trackPending(next: Survey, meta?: CommitMeta) {\n this.pendingSurvey = !equal(stripAssets(next.data), this.history.getCurrentState());\n const previous = this.history.getCurrentAssets() ?? {},\n assets = next.data.assets ?? {};\n this.pendingAssets = [...new Set([...Object.keys(previous), ...Object.keys(assets)])]\n .filter((id) => !equal(ownValue(previous, id), ownValue(assets, id)))\n .map((assetId) => ({\n assetId,\n prev: ownValue(previous, assetId),\n next: ownValue(assets, assetId),\n }));\n this.pendingMeta ??= meta;\n }\n private accept(next: Survey, meta: CommitMeta, staged = false) {\n if (equal(next.data, this.current.data)) return;\n assertStableAnswerTypes(this.current, next);\n if (this.current.slots !== next.slots) {\n const diagnostics = answerTypeDiagnostics(next, (id) => this.answerTypes.get(id));\n if (diagnostics.length) throw new DefinitionError(diagnostics);\n const existing = new Set(\n getDefaultProjectionDiagnostics(this.current).flatMap((issue) =>\n issue.code === \"duplicate-header\" ? [issue.header] : [],\n ),\n );\n const introduced = getDefaultProjectionDiagnostics(next).filter(\n (issue) => issue.code === \"duplicate-header\" && !existing.has(issue.header),\n );\n if (introduced.length) throw new Error(introduced.map((issue) => issue.message).join(\"\\n\"));\n }\n if (!this.fieldWriteDepth && !this.actionDepth && !staged) {\n const pending = this.current;\n this.commitIfNeeded();\n if (this.current !== pending) {\n // `next` was prepared from the live draft. Carry forward timestamps from the\n // field just committed without making that field part of this new edit again.\n const metadata = new Map<string, NonNullable<FlowItem[\"editorMetadata\"]>>();\n for (const item of next.data.surveyItems) {\n const before = pending.getItem(item.id)?.editorMetadata;\n const committed = this.current.getItem(item.id)?.editorMetadata;\n if (committed && equal(item.editorMetadata, before) && !equal(before, committed))\n metadata.set(item.id, committed);\n }\n next = next.withItemEditorMetadata(metadata);\n }\n }\n const baseline = this.current;\n const pending = {\n survey: this.pendingSurvey,\n assets: this.pendingAssets,\n meta: this.pendingMeta,\n };\n try {\n this.trackPending(next, meta);\n // Focused writes stay live without consuming history.\n this.current = next;\n if (!this.fieldWriteDepth && !this.actionDepth && !staged) this.recordCommit(meta);\n } catch (error) {\n this.current = baseline;\n this.pendingSurvey = pending.survey;\n this.pendingAssets = pending.assets;\n this.pendingMeta = pending.meta;\n throw error;\n }\n this.publish(this.current);\n }\n transact(meta: CommitMeta, operation: (draft: CompositionSurvey) => void): void {\n const draft = this.current.serialize();\n const hadLocales = this.current.locales.length > 0;\n operation(draft);\n // The first language added becomes the default; later additions never change it.\n const first = Object.keys(draft.translations ?? {})[0];\n if (!hadLocales && first !== undefined) draft.defaultLocale ??= first;\n const next = Survey.parse(draft, this.current.registry, { admission: \"draft\" });\n new SurveyStateGraph(next, { admission: \"draft\" });\n this.accept(next, meta);\n }\n /** Synchronous compound UI action: validated writes, one publication/history entry, rollback on failure. */\n runAction<T>(operation: () => T): T {\n if (!this.actionDepth) this.commitIfNeeded();\n const baseline = this.current;\n const pending = {\n survey: this.pendingSurvey,\n assets: this.pendingAssets,\n meta: this.pendingMeta,\n actionMeta: this.actionMeta,\n };\n this.actionDepth++;\n let result: T;\n try {\n result = operation();\n if (result && typeof result === \"object\" && \"then\" in result)\n throw new Error(\"Editor actions must be synchronous\");\n // A compound action must not bypass the invariant by temporarily deleting a slot.\n assertStableAnswerTypes(baseline, this.current);\n } catch (error) {\n this.current = baseline;\n this.pendingSurvey = pending.survey;\n this.pendingAssets = pending.assets;\n this.pendingMeta = pending.meta;\n this.actionMeta = pending.actionMeta;\n throw error;\n } finally {\n this.actionDepth--;\n }\n if (!this.actionDepth) {\n const meta = this.actionMeta ?? this.pendingMeta ?? { label: \"Edit survey\" };\n this.actionMeta = undefined;\n const changed = !equal(baseline.data, this.current.data);\n if (!changed) {\n this.current = baseline;\n this.pendingSurvey = pending.survey;\n this.pendingAssets = pending.assets;\n this.pendingMeta = pending.meta;\n }\n if (changed) {\n try {\n this.recordCommit(meta);\n } catch (error) {\n this.current = baseline;\n this.pendingSurvey = pending.survey;\n this.pendingAssets = pending.assets;\n this.pendingMeta = pending.meta;\n this.actionMeta = pending.actionMeta;\n throw error;\n }\n this.publish(this.current);\n }\n }\n return result;\n }\n getLocalizedContent(ref: LocalizationRef, locale: string) {\n return readLocalizationContent(this.current, ref, locale);\n }\n setLocalizedContent(\n ref: LocalizationRef,\n locale: string,\n content: Content | undefined,\n meta: CommitMeta = { label: \"Edit translated content\" },\n ) {\n let next = this.current.withLocalizationContent(ref, locale, content);\n // As in `transact`, text in a survey without languages makes its language the default.\n if (\n !this.current.locales.length &&\n next.locales.length &&\n next.data.defaultLocale === undefined\n )\n next = next.withDefaultLocale(next.locales[0]);\n this.accept(next, meta);\n }\n\n /** Reuses the editor's field session boundary; no separate editable survey or history. */\n beginFieldEdit(itemId?: string): {\n run: <T>(write: () => T) => T;\n reconcile: (restoreValue?: () => void) => boolean;\n } {\n if (this.hasUncommittedChanges || this.actionDepth)\n throw new Error(\"Finish pending changes before editing a field\");\n if (itemId && !this.current.data.surveyItems.some((item) => item.id === itemId))\n throw new Error(`Unknown item '${itemId}'`);\n let expectedEpoch = this.mutationEpoch;\n const history = this.history,\n index = history.getCurrentIndex();\n const owns = () =>\n this.mutationEpoch === expectedEpoch &&\n this.history === history &&\n history.getCurrentIndex() === index;\n const run = <T>(write: () => T): T => {\n if (!owns()) throw new Error(\"Field edit was superseded by another action\");\n this.fieldWriteDepth++;\n try {\n return write();\n } finally {\n this.fieldWriteDepth--;\n expectedEpoch = this.mutationEpoch;\n }\n };\n return {\n run,\n reconcile: (restoreValue) => {\n if (!owns()) return false;\n if (restoreValue) run(restoreValue);\n // The guard proves no other action owns changes since the committed revision.\n // Restore it exactly, including locale shape, without discarding the redo branch.\n this.restoreHistoryState(history.getCurrentState());\n expectedEpoch = this.mutationEpoch;\n return true;\n },\n };\n }\n private recordCommit(meta: CommitMeta): boolean {\n if (!this.hasUncommittedChanges) return false;\n if (this.pendingSurvey) {\n const stamped = timestampEditedItems(this.history.getCurrentState(), this.current);\n this.history.commit(stripAssets(stamped.serialize()), meta, this.pendingAssets);\n this.current = stamped;\n } else this.history.commitAssetChange(this.pendingAssets, meta);\n this.pendingSurvey = false;\n this.pendingAssets = [];\n this.pendingMeta = undefined;\n this.mutationEpoch++;\n return true;\n }\n commit(meta: CommitMeta): void {\n if (this.actionDepth) {\n this.actionMeta = meta;\n return;\n }\n if (this.recordCommit(meta)) this.notify();\n }\n commitIfNeeded() {\n this.commit(\n this.pendingMeta ?? { label: \"Latest content changes\", source: CommitSource.SYSTEM },\n );\n }\n private restoreHistoryState(snapshot: CompositionSurvey) {\n const assets = this.history.getCurrentAssets();\n const next = Survey.parse(\n { ...snapshot, ...(assets ? { assets } : {}) },\n this.current.registry,\n {\n previous: this.current,\n admission: \"draft\",\n },\n );\n this.pendingSurvey = false;\n this.pendingAssets = [];\n this.pendingMeta = undefined;\n this.publish(next);\n }\n undo(): boolean {\n if (this.actionDepth) throw new Error(\"History navigation cannot run inside an edit action\");\n if (this.hasUncommittedChanges) {\n this.restoreHistoryState(this.history.getCurrentState());\n return true;\n }\n const value = this.history.undo();\n if (!value) return false;\n this.restoreHistoryState(value);\n return true;\n }\n redo(): boolean {\n if (this.actionDepth) throw new Error(\"History navigation cannot run inside an edit action\");\n if (this.hasUncommittedChanges) return false;\n const value = this.history.redo();\n if (!value) return false;\n this.restoreHistoryState(value);\n return true;\n }\n jumpToIndex(index: number): boolean {\n if (this.actionDepth) throw new Error(\"History navigation cannot run inside an edit action\");\n if (this.hasUncommittedChanges) return false;\n const value = this.history.jumpToIndex(index);\n if (!value) return false;\n this.restoreHistoryState(value);\n return true;\n }\n canUndo() {\n return this.hasUncommittedChanges || this.history.canUndo();\n }\n canRedo() {\n return !this.hasUncommittedChanges && this.history.canRedo();\n }\n getUndoMeta() {\n return this.hasUncommittedChanges ? (this.pendingMeta ?? null) : this.history.getUndoMeta();\n }\n getRedoMeta() {\n return this.hasUncommittedChanges ? null : this.history.getRedoMeta();\n }\n getMemoryUsage() {\n return this.history.getMemoryUsage();\n }\n getUndoRedoConfig() {\n return this.history.getConfig();\n }\n getCommitsSinceInitial() {\n return this.history.getCommitsSinceInitial();\n }\n toJson(): SerializedSurveyEditor {\n return {\n version: 2,\n survey: this.current.serialize(),\n undoRedo: structuredClone(this.history.serialize()),\n hasUncommittedChanges: this.hasUncommittedChanges,\n answerTypes: this.getAnswerTypes(),\n };\n }\n static fromJson(input: unknown, registry: ElementRegistry): SurveyEditor {\n const data = createEditorSessionSchema(registry).parse(input);\n const answerTypes = new Map(data.answerTypes);\n const checkAnswerTypes = (survey: Survey) => {\n const diagnostics = answerTypeDiagnostics(survey, (id) => answerTypes.get(id));\n if (diagnostics.length) throw new DefinitionError(diagnostics);\n for (const slot of survey.slots.definitions)\n if (!answerTypes.has(slot.slotId))\n throw new Error(`Stored answer type is missing for '${slot.slotId}'`);\n };\n let historySurvey: CompositionSurvey | undefined;\n let previous: Survey | undefined;\n let currentHistoryRevision: Survey | undefined;\n const assets = structuredClone(data.undoRedo.initialAssets ?? {});\n for (const [index, entry] of data.undoRedo.history.entries()) {\n for (const patch of entry.changes ?? []) {\n if (!equal(ownValue(assets, patch.assetId), patch.prev))\n throw new Error(`Inconsistent asset history for '${patch.assetId}'`);\n if (patch.next) setOwnValue(assets, patch.assetId, patch.next);\n else delete assets[patch.assetId];\n }\n if (entry.kind === \"survey-snapshot\") {\n if (entry.survey.assets !== undefined)\n throw new Error(\"History snapshots must use the shared asset history\");\n historySurvey = entry.survey;\n }\n if (!historySurvey) throw new Error(\"History requires an initial survey snapshot\");\n // Undo and redo must never resurrect an invalid definition or a retired item type.\n const snapshot = Survey.parse(\n { ...historySurvey, ...(Object.keys(assets).length ? { assets } : {}) },\n registry,\n { previous, admission: \"draft\" },\n );\n if (snapshot.slots !== previous?.slots)\n new SurveyStateGraph(snapshot, { admission: \"draft\" });\n checkAnswerTypes(snapshot);\n previous = snapshot;\n if (index === data.undoRedo.currentIndex) currentHistoryRevision = snapshot;\n }\n const editor = new SurveyEditor(\n Survey.parse(data.survey, registry, {\n previous: currentHistoryRevision,\n admission: \"draft\",\n }),\n );\n if (editor.survey.slots !== currentHistoryRevision?.slots)\n new SurveyStateGraph(editor.survey, { admission: \"draft\" });\n checkAnswerTypes(editor.survey);\n editor.answerTypes = answerTypes;\n editor._history = SurveyEditorUndoRedo.deserialize(data.undoRedo);\n editor.trackPending(editor.current);\n if (editor.hasUncommittedChanges !== data.hasUncommittedChanges)\n throw new Error(\"Stored pending-edit state does not match the current history revision\");\n return editor;\n }\n getAsset(id: string): RawSurveyAsset | undefined {\n return structuredClone(ownValue(this.current.data.assets, id));\n }\n getAssets(): Map<string, RawSurveyAsset> {\n return new Map(Object.entries(structuredClone(this.current.data.assets ?? {})));\n }\n addItem(\n target: Target,\n item: FlowItem,\n content?: { locale: string; content: Record<string, Record<string, Content>> },\n ) {\n this.insertItemTree(target, item.id, [item], content);\n }\n /** Validate a preset's entire flow subtree together, including forward references. */\n insertItemTree(\n target: Target,\n rootItemId: string,\n items: readonly FlowItem[],\n content?: { locale: string; content: Record<string, Record<string, Content>> },\n meta: CommitMeta = { label: \"Add item\" },\n ) {\n if (!items.some((item) => item.id === rootItemId)) throw new Error(\"Preset root is missing\");\n const byId = new Map(items.map((item) => [item.id, item]));\n if (byId.size !== items.length) throw new Error(\"Duplicate preset item identity\");\n const visited = new Set<string>();\n const pending = [rootItemId];\n while (pending.length) {\n const id = pending.pop()!;\n const item = byId.get(id);\n if (!item || visited.has(id)) throw new Error(\"Preset must be a self-contained flow tree\");\n visited.add(id);\n if (item.itemType === \"group\") pending.push(...item.config.items);\n }\n if (visited.size !== items.length) throw new Error(\"Preset contains disconnected items\");\n this.transact(meta, (draft) => {\n const parent = draft.surveyItems.find((candidate) => candidate.id === target.parentId);\n if (parent?.itemType !== \"group\") throw new Error(\"Item target must be a group\");\n if (target.index !== undefined && (!Number.isInteger(target.index) || target.index < 0))\n throw new Error(\"Invalid item insertion index\");\n parent.config.items.splice(\n Math.min(target.index ?? parent.config.items.length, parent.config.items.length),\n 0,\n rootItemId,\n );\n draft.surveyItems.push(...structuredClone(items));\n if (content) {\n draft.translations ??= {};\n const translation = ownValue(draft.translations, content.locale) ?? { content: {} };\n setOwnValue(draft.translations, content.locale, translation);\n for (const [owner, roles] of Object.entries(content.content)) {\n if (this.current.owners.has(owner))\n throw new Error(`Initial localized owner '${owner}' already exists`);\n setOwnValue(translation.content, owner, structuredClone(roles));\n }\n }\n });\n }\n getItemDataCopy(itemId: string): FlowItem {\n const item = this.current.getItem(itemId);\n if (!item) throw new Error(`Unknown item '${itemId}'`);\n return structuredClone(item);\n }\n updateItem(itemId: string, update: Partial<FlowItem>, meta: CommitMeta = { label: \"Edit item\" }) {\n const existing = this.current.getItem(itemId);\n if (!existing) throw new Error(`Unknown item '${itemId}'`);\n if (update.id !== undefined && update.id !== itemId)\n throw new Error(\"Updating an item cannot change its identity\");\n this.transact(meta, (draft) => {\n const index = draft.surveyItems.findIndex((item) => item.id === itemId);\n // Validate the merged discriminated node through the canonical document schema.\n const next = { ...existing, ...update, id: itemId };\n setAt(draft, [\"surveyItems\", index], next);\n });\n }\n /** Repair answer reads only; state targets and previous-survey prefill references are distinct. */\n rewriteAnswerReferences(replacements: Readonly<Record<string, string>>): number {\n let changed = 0;\n const raw = transformAnnotated(\n this.current.registry.surveySchema,\n this.current.data,\n ({ annotation, value }) => {\n if (annotation.kind !== \"expression\") return value;\n return transformExpression(expressionSchema.parse(value), {\n const: (node) => node,\n function: (node) => node,\n contextVariable: (node) => node,\n ownerState: (node) => node,\n responseVariable: (node) => {\n const slotId = ownValue(replacements, node.variableRef.slotId);\n if (!slotId || slotId === node.variableRef.slotId) return node;\n changed++;\n return { ...node, variableRef: { ...node.variableRef, slotId } };\n },\n });\n },\n );\n if (changed) {\n const next = Survey.parse(raw, this.current.registry, { admission: \"draft\" });\n new SurveyStateGraph(next, { admission: \"draft\" });\n this.accept(next, { label: \"Repair answer references\" });\n }\n return changed;\n }\n renameResponseVariables(edits: readonly ResponseNamingEdit[]) {\n return this.updateResponseSettings(edits, []);\n }\n updateResponseSettings(\n naming: readonly ResponseNamingEdit[],\n settings: readonly ResponseSettingsEdit[],\n ) {\n const preview = previewResponseSettings(this.current, naming, settings);\n const next = Survey.parse(preview.survey, this.current.registry, { admission: \"draft\" });\n new SurveyStateGraph(next, { admission: \"draft\" });\n this.accept(next, { label: \"Edit response variables\" });\n return preview.changes;\n }\n addLocale(locale: string): boolean {\n if (!locale.trim()) throw new Error(\"A locale is required\");\n if (Object.hasOwn(this.current.data.translations ?? {}, locale)) return false;\n this.transact({ label: `Add language: ${locale}` }, (draft) => {\n draft.translations ??= {};\n setOwnValue(draft.translations, locale, { content: {} });\n });\n return true;\n }\n removeLocale(locale: string): boolean {\n if (!Object.hasOwn(this.current.data.translations ?? {}, locale)) return false;\n this.transact({ label: `Remove language: ${locale}` }, (draft) => {\n delete draft.translations?.[locale];\n if (draft.defaultLocale === locale) {\n const next = Object.keys(draft.translations ?? {})[0];\n if (next === undefined) delete draft.defaultLocale;\n else draft.defaultLocale = next;\n }\n });\n return true;\n }\n /** Sets the source language that exports and hosts fall back to. */\n setDefaultLocale(locale: string): boolean {\n if (!Object.hasOwn(this.current.data.translations ?? {}, locale))\n throw new Error(`Unknown locale '${locale}'`);\n if (this.current.data.defaultLocale === locale) return false;\n this.transact({ label: `Set default language: ${locale}` }, (draft) => {\n draft.defaultLocale = locale;\n });\n return true;\n }\n updateSurveyTranslations(updates: {\n surveyCard?: { locale: string; content?: SurveyCardContent };\n navigation?: { locale: string; content?: NavigationContent };\n validationMessages?: { locale: string; content?: { invalidResponse?: Content } };\n }) {\n this.transact({ label: \"Edit survey wording\" }, (draft) => {\n const apply = (\n surface: \"surveyCardContent\" | \"navigationContent\" | \"validationMessages\",\n update?: { locale: string; content?: Record<string, Content | undefined> },\n ) => {\n if (!update) return;\n if (!update.locale.trim()) throw new Error(\"A locale is required\");\n const existing = ownValue(draft.translations, update.locale);\n if (update.content === undefined && existing?.[surface] === undefined) return;\n draft.translations ??= {};\n const translation = existing ?? { content: {} };\n setOwnValue(draft.translations, update.locale, translation);\n if (update.content === undefined) delete translation[surface];\n else translation[surface] = structuredClone(update.content);\n };\n apply(\"surveyCardContent\", updates.surveyCard);\n apply(\"navigationContent\", updates.navigation);\n apply(\"validationMessages\", updates.validationMessages);\n });\n }\n getMaxItemsPerPage() {\n return structuredClone(this.current.data.maxItemsPerPage);\n }\n updateMaxItemsPerPage(value: CompositionSurvey[\"maxItemsPerPage\"]) {\n this.transact({ label: \"Change page size\" }, (draft) => {\n if (value === undefined) delete draft.maxItemsPerPage;\n else draft.maxItemsPerPage = structuredClone(value);\n });\n }\n getMetadata() {\n return structuredClone(this.current.data.metadata);\n }\n updateMetadata(metadata: CompositionSurvey[\"metadata\"]) {\n this.transact({ label: \"Edit survey metadata\" }, (draft) => {\n if (metadata === undefined) delete draft.metadata;\n else draft.metadata = structuredClone(metadata);\n });\n }\n getTemplateValue(key: string) {\n return structuredClone(this.current.getTemplateValue(key));\n }\n getTemplateValues(): Map<string, TemplateValueDefinition> {\n return new Map(Object.entries(structuredClone(this.current.data.templateValues ?? {})));\n }\n setTemplateValue(key: string, value: TemplateValueDefinition) {\n this.transact({ label: `Edit template: ${key}` }, (draft) => {\n draft.templateValues ??= {};\n setOwnValue(draft.templateValues, key, structuredClone(value));\n });\n }\n removeTemplateValue(key: string) {\n this.transact({ label: `Remove template: ${key}` }, (draft) => {\n delete draft.templateValues?.[key];\n });\n }\n stageAsset(id: string, asset?: RawSurveyAsset) {\n const draft = this.current.serialize();\n draft.assets ??= {};\n if (asset) setOwnValue(draft.assets, id, asset);\n else {\n delete draft.assets[id];\n if (!Object.keys(draft.assets).length) delete draft.assets;\n }\n this.accept(\n Survey.parse(draft, this.current.registry, { admission: \"draft\" }),\n { label: `Update asset: ${id}` },\n true,\n );\n }\n setAsset(id: string, asset: RawSurveyAsset) {\n this.transact({ label: `Update asset: ${id}`, source: CommitSource.USER }, (draft) => {\n draft.assets ??= {};\n setOwnValue(draft.assets, id, asset);\n });\n }\n removeAsset(id: string) {\n this.transact({ label: `Remove asset: ${id}`, source: CommitSource.USER }, (draft) => {\n if (draft.assets) {\n delete draft.assets[id];\n if (!Object.keys(draft.assets).length) delete draft.assets;\n }\n });\n }\n\n /** Shared insertion used by the survey catalog and a layout's element catalog. */\n insertElement(\n input: unknown,\n target?:\n | { layoutId: string; index?: number }\n | { bodyOwnerId: string; index?: number }\n | Target,\n meta: CommitMeta = { label: \"Add element\" },\n initialContent?: { locale: string; content: Record<string, Record<string, Content>> },\n ): { itemId: string; elementId: string } {\n const element = this.current.registry.elementSchema.parse(input);\n const layoutTarget = target && \"layoutId\" in target ? target : undefined;\n const bodyTarget = target && \"bodyOwnerId\" in target ? target : undefined;\n const body = bodyTarget ? this.current.bodies.get(bodyTarget.bodyOwnerId) : undefined;\n if (bodyTarget && !body) throw new Error(`Unknown body owner '${bodyTarget.bodyOwnerId}'`);\n const flowTarget = target && \"parentId\" in target ? target : { parentId: this.current.rootId };\n if (target?.index !== undefined && (!Number.isInteger(target.index) || target.index < 0))\n throw new Error(\"An insertion index must be a nonnegative integer\");\n if (\n !layoutTarget &&\n !bodyTarget &&\n this.current.getItem(flowTarget.parentId)?.itemType !== \"group\"\n )\n throw new Error(`Target parent '${flowTarget.parentId}' is not a group item`);\n const itemId = layoutTarget\n ? this.containingItem(layoutTarget.layoutId)\n : bodyTarget\n ? this.containingItem(bodyTarget.bodyOwnerId)\n : generateId();\n this.transact(meta, (draft) => {\n if (initialContent) {\n draft.translations ??= {};\n const translation = ownValue(draft.translations, initialContent.locale) ?? { content: {} };\n setOwnValue(draft.translations, initialContent.locale, translation);\n for (const [owner, roles] of Object.entries(initialContent.content)) {\n if (this.current.owners.has(owner))\n throw new Error(`Initial localized owner '${owner}' already exists`);\n setOwnValue(translation.content, owner, structuredClone(roles));\n }\n }\n if (layoutTarget) {\n const path = this.identityPath(layoutTarget.layoutId, \"layout\");\n const elements = arrayAt(draft, [...path, \"elements\"]);\n elements.splice(layoutTarget.index ?? elements.length, 0, element);\n } else if (body && bodyTarget) {\n const blocks = arrayAt(draft, [...body.path, \"blocks\"]);\n blocks.splice(bodyTarget.index ?? blocks.length, 0, {\n id: generateId(),\n kind: \"layout\",\n layout: { mode: \"automatic\", maxColumns: 1 },\n elements: [element],\n });\n } else {\n draft.surveyItems.push({\n id: itemId,\n itemType: \"content\",\n config: {\n body: {\n blocks: [\n {\n id: generateId(),\n kind: \"layout\",\n layout: { mode: \"automatic\", maxColumns: 1 },\n elements: [element],\n },\n ],\n },\n },\n });\n const parent = draft.surveyItems.find((item) => item.id === flowTarget.parentId);\n if (parent?.itemType !== \"group\") throw new Error(\"Insertion requires a flow group\");\n parent.config.items.splice(flowTarget.index ?? parent.config.items.length, 0, itemId);\n }\n });\n return { itemId, elementId: element.id };\n }\n\n moveItem(itemId: string, target: Target, meta: CommitMeta = { label: \"Move item\" }): boolean {\n return this.moveItems([itemId], target, meta);\n }\n\n /** Retain the outline's ordered-block move semantics, publishing one validated revision. */\n moveItems(\n itemIds: readonly string[],\n target: Target,\n meta: CommitMeta = { label: \"Move items\" },\n ): boolean {\n const survey = this.current;\n const requested = [...new Set(itemIds)];\n if (!requested.length) return false;\n // Validate the entire request before collapsing nested selections or changing any state.\n for (const id of requested) {\n if (!survey.getItem(id)) throw new Error(`Item with id '${id}' not found`);\n if (id === survey.rootId) throw new Error(\"The root group cannot be moved\");\n }\n const destination = survey.getItem(target.parentId);\n if (!destination) throw new Error(`Target parent with id '${target.parentId}' not found`);\n if (destination.itemType !== \"group\")\n throw new Error(`Target parent '${target.parentId}' is not a group item`);\n const selected = requested.filter(\n (id) => !requested.some((other) => other !== id && survey.isDescendantOf(id, other)),\n );\n for (const id of selected)\n if (survey.isDescendantOf(destination.id, id))\n throw new Error(`Cannot move item '${id}' into its own subtree`);\n if (target.index !== undefined && (!Number.isInteger(target.index) || target.index < 0))\n throw new Error(\"An insertion index must be a nonnegative integer\");\n\n // Preserve structural order rather than click order or the flat storage-array order.\n const selectedSet = new Set(selected);\n const ordered: string[] = [];\n const visit = (id: string) => {\n if (selectedSet.has(id)) ordered.push(id);\n const item = survey.getItem(id);\n if (item?.itemType === \"group\") item.config.items.forEach(visit);\n };\n visit(survey.rootId);\n const requestedIndex = Math.min(\n target.index ?? destination.config.items.length,\n destination.config.items.length,\n );\n const removedBefore = destination.config.items\n .slice(0, requestedIndex)\n .filter((id) => selectedSet.has(id)).length;\n const parents = new Set(selected.map((id) => survey.getParentItem(id)!.id));\n parents.add(destination.id);\n const lists = new Map<string, string[]>();\n for (const id of parents) {\n const group = survey.getItem(id);\n if (group?.itemType !== \"group\") throw new Error(`Unknown parent group '${id}'`);\n lists.set(\n id,\n group.config.items.filter((child) => !selectedSet.has(child)),\n );\n }\n lists.get(destination.id)!.splice(requestedIndex - removedBefore, 0, ...ordered);\n const changed = [...lists].some(([id, children]) => {\n const group = survey.getItem(id);\n return group?.itemType === \"group\" && !equal(group.config.items, children);\n });\n if (!changed) return false;\n this.transact(meta, (draft) => {\n for (const item of draft.surveyItems) {\n const children = lists.get(item.id);\n if (item.itemType === \"group\" && children) item.config.items = children;\n }\n });\n return true;\n }\n\n private identityPath(id: string, kind?: string): Path {\n const declaration = this.current.identities.get(id);\n if (!declaration || (kind && declaration.kind !== kind))\n throw new Error(`Unknown ${kind ?? \"identity\"} '${id}'`);\n return declaration.path.slice(0, -1);\n }\n private containingItem(id: string): string {\n const declaration = this.current.identities.get(id);\n const owner = declaration?.ownerId ? this.current.owners.get(declaration.ownerId) : undefined;\n if (!owner) throw new Error(`No containing item for '${id}'`);\n return owner.itemId;\n }\n\n /** Edit wording only for this element and its added/removed descendants, in existing locales. */\n updateElement(\n elementId: string,\n update: (\n element: RuntimeElement,\n translations: NonNullable<CompositionSurvey[\"translations\"]>,\n ) => void,\n meta: CommitMeta = { label: \"Edit element\" },\n /** Renew structural owners without rebinding answers to a different value type. */\n renewOwnerIds: ReadonlyMap<string, string> = new Map(),\n ) {\n const path = this.identityPath(elementId, \"element\");\n this.transact(meta, (draft) => {\n const schema = this.current.registry.elementSchema;\n const element = schema.parse(at(draft, path));\n const before = contentOwnerIds(schema, element);\n const elementType = element.elementType;\n const translations = draft.translations ?? {};\n update(element, translations);\n if (Object.keys(translations).length || draft.translations) draft.translations = translations;\n if (element.id !== elementId || element.elementType !== elementType)\n throw new Error(\"Element identity and type cannot change during a settings update\");\n const next = schema.parse(element);\n const remaining = contentOwnerIds(schema, next);\n assertElementTranslationScope(\n this.current.data.translations,\n draft.translations,\n new Set([...before, ...remaining]),\n );\n // Removing owned rules/options also removes their wording, atomically in every locale.\n // Other authored references remain intact and must pass ordinary integrity validation.\n for (const translation of Object.values(draft.translations ?? {}))\n for (const ownerId of before)\n if (!remaining.has(ownerId)) delete translation.content[ownerId];\n setAt(draft, path, next);\n for (const from of renewOwnerIds.keys())\n if (from === elementId || !before.has(from) || !remaining.has(from))\n throw new Error(\n `Cannot renew '${from}': it must be a surviving owner inside the element`,\n );\n if (renewOwnerIds.size) {\n // An owner may also declare an answer. Keep slot references on the retired ID;\n // only structural identity, owned wording and disabled-state references follow it.\n // Update descendants before renaming record keys, including values whose\n // annotation shares the key's path. Otherwise a later visit uses a stale path.\n const visits = inspectAnnotated(this.current.registry.surveySchema, draft).sort(\n (a, b) => b.path.length - a.path.length || Number(a.key) - Number(b.key),\n );\n for (const visit of visits) {\n if (visit.annotation.kind === \"expression\") {\n setAt(\n draft,\n visit.path,\n transformExpression(expressionSchema.parse(visit.value), {\n const: (node) => node,\n function: (node) => node,\n contextVariable: (node) => node,\n responseVariable: (node) => node,\n ownerState: (node) => ({\n ...node,\n targetRef: {\n ownerId: renewOwnerIds.get(node.targetRef.ownerId) ?? node.targetRef.ownerId,\n },\n }),\n }),\n );\n }\n if (\n (visit.annotation.kind !== \"identity\" &&\n !(\n visit.annotation.kind === \"reference\" &&\n !visit.annotation.external &&\n (visit.annotation.target === \"owner\" || visit.annotation.target === \"state\")\n )) ||\n typeof visit.value !== \"string\"\n )\n continue;\n const to = renewOwnerIds.get(visit.value);\n if (!to) continue;\n if (visit.key) {\n const parent = at(draft, visit.path.slice(0, -1));\n if (!record(parent) || Object.hasOwn(parent, to))\n throw new Error(`Cannot move owned content to '${to}'`);\n setOwnValue(parent, to, ownValue(parent, visit.value));\n delete parent[visit.value];\n } else setAt(draft, visit.path, to);\n }\n }\n });\n }\n\n addLayout(bodyOwnerId: string) {\n const body = this.current.bodies.get(bodyOwnerId);\n if (!body) throw new Error(`Unknown body owner '${bodyOwnerId}'`);\n const id = generateId();\n this.transact({ label: \"Add layout\" }, (draft) => {\n arrayAt(draft, [...body.path, \"blocks\"]).push({\n id,\n kind: \"layout\",\n layout: { mode: \"automatic\", maxColumns: 2 },\n elements: [],\n });\n });\n return id;\n }\n\n addSection(bodyOwnerId: string) {\n const body = this.current.bodies.get(bodyOwnerId);\n if (!body) throw new Error(`Unknown body owner '${bodyOwnerId}'`);\n const id = generateId();\n this.transact({ label: \"Add section\" }, (draft) => {\n arrayAt(draft, [...body.path, \"blocks\"]).push({\n id,\n kind: \"section\",\n body: {\n blocks: [\n {\n id: generateId(),\n kind: \"layout\",\n layout: { mode: \"automatic\", maxColumns: 1 },\n elements: [],\n },\n ],\n },\n });\n });\n return id;\n }\n\n updateLayout(\n layoutId: string,\n layout: import(\"../survey/composition/schema\").LayoutGroup<RuntimeElement>[\"layout\"],\n ) {\n this.transact({ label: \"Change columns\" }, (draft) =>\n setAt(draft, [...this.identityPath(layoutId, \"layout\"), \"layout\"], layout),\n );\n }\n\n private removalScope(ids: readonly string[]) {\n const paths: Path[] = [];\n for (const id of new Set(ids)) {\n if (id === this.current.rootId) throw new Error(\"The root group cannot be removed\");\n const declaration = this.current.identities.get(id);\n if (!declaration || ![\"element\", \"layout\", \"section\", \"item\"].includes(declaration.kind))\n throw new Error(\"Only structural nodes can be removed directly\");\n if (declaration.kind === \"item\") {\n for (const item of this.current.data.surveyItems)\n if (this.current.isDescendantOf(item.id, id)) paths.push(this.identityPath(item.id));\n } else paths.push(this.identityPath(id));\n }\n const roots = paths.filter(\n (path, index) =>\n !paths.some(\n (other, otherIndex) =>\n otherIndex !== index &&\n inside(other, path) &&\n (other.length < path.length || otherIndex < index),\n ),\n );\n const includes = (path: Path) => roots.some((root) => inside(root, path));\n const owned = new Set(\n [...this.current.identities.values()]\n .filter((entry) => includes(entry.path))\n .map((entry) => entry.id),\n );\n return { roots, owned, includes };\n }\n\n /** Includes whole flow subtrees; deletion never silently rewrites an authored rule. */\n deletionImpact(id: string | readonly string[]) {\n const { owned, includes } = this.removalScope(typeof id === \"string\" ? [id] : id);\n return annotatedReferences(\n inspectAnnotated(this.current.registry.surveySchema, this.current.data),\n ).filter(\n (ref) =>\n owned.has(ref.id) &&\n !includes(ref.path) &&\n ref.path[0] !== \"translations\" &&\n !(ref.target === \"item\" && ref.path[0] === \"surveyItems\" && ref.path.includes(\"items\")),\n );\n }\n\n remove(id: string) {\n return this.removeNodes([id]);\n }\n removeItem(itemId: string): boolean {\n if (!this.current.getItem(itemId)) return false;\n return this.removeItems([itemId]);\n }\n removeItems(itemIds: readonly string[]): boolean {\n if (itemIds.some((id) => !this.current.getItem(id)))\n throw new Error(\"Unknown flow item in removal request\");\n return this.removeNodes(itemIds);\n }\n private removeNodes(ids: readonly string[]): boolean {\n if (!ids.length) return false;\n const { roots, owned } = this.removalScope(ids);\n // Dependents remain as dangling references (draft diagnostics) until the author repairs them.\n // Callers confirm with `deletionImpact` first; the assistant refuses to leave them behind.\n // Descending positions keep all derived paths valid while removing several subtrees.\n roots.sort((left, right) => {\n for (let i = 0; i < Math.min(left.length, right.length); i++) {\n const a = left[i],\n b = right[i];\n if (a !== b)\n return typeof a === \"number\" && typeof b === \"number\"\n ? b - a\n : String(b).localeCompare(String(a));\n }\n return right.length - left.length;\n });\n this.transact({ label: \"Remove content\" }, (draft) => {\n for (const path of roots) {\n const index = path.at(-1);\n if (typeof index !== \"number\")\n throw new Error(\"Structural content must belong to an ordered list\");\n arrayAt(draft, path.slice(0, -1)).splice(index, 1);\n }\n for (const item of draft.surveyItems)\n if (item.itemType === \"group\")\n item.config.items = item.config.items.filter((child) => !owned.has(child));\n for (const translation of Object.values(draft.translations ?? {}))\n for (const owner of owned) delete translation.content[owner];\n });\n return true;\n }\n\n /** index is the final position after removal, as reported by composition sortables. */\n moveElement(\n elementId: string,\n layoutId: string,\n index?: number,\n ruleTransfer: \"reject\" | \"move-with-targets\" = \"reject\",\n ) {\n this.moveCompositionContent(\n elementId,\n this.identityPath(elementId, \"element\"),\n [...this.identityPath(layoutId, \"layout\"), \"elements\"],\n layoutId,\n index,\n ruleTransfer,\n );\n }\n\n /** Reorders/moves vertical blocks; index is the final position after removal. */\n moveBlock(\n blockId: string,\n bodyOwnerId: string,\n index?: number,\n ruleTransfer: \"reject\" | \"move-with-targets\" = \"reject\",\n ) {\n const identity = this.current.identities.get(blockId);\n if (!identity || (identity.kind !== \"layout\" && identity.kind !== \"section\"))\n throw new Error(\"Only layouts and sections can move between bodies\");\n const body = this.current.bodies.get(bodyOwnerId);\n if (!body) throw new Error(`Unknown body owner '${bodyOwnerId}'`);\n this.moveCompositionContent(\n blockId,\n this.identityPath(blockId),\n [...body.path, \"blocks\"],\n bodyOwnerId,\n index,\n ruleTransfer,\n );\n }\n\n private moveCompositionContent(\n elementId: string,\n source: Path,\n destination: Path,\n targetOwnerId: string,\n index: number | undefined,\n ruleTransfer: \"reject\" | \"move-with-targets\",\n ) {\n if (inside(source, destination)) throw new Error(\"Content cannot move into its own descendant\");\n const fromItem = this.containingItem(elementId),\n toItem = this.containingItem(targetOwnerId);\n const ownedSlots = new Set(\n this.current.slots.definitions\n .filter((slot) => {\n const owner = this.current.owners.get(slot.elementId);\n return owner && inside(source, owner.path);\n })\n .map((slot) => slot.slotId),\n );\n this.transact({ label: \"Move content\" }, (draft) => {\n const elements = arrayAt(draft, destination);\n if (index !== undefined && (!Number.isInteger(index) || index < 0 || index > elements.length))\n throw new Error(\"Invalid content insertion index\");\n const parent = arrayAt(draft, source.slice(0, -1));\n const position = source.at(-1);\n if (typeof position !== \"number\") throw new Error(\"Content must belong to an ordered list\");\n if (fromItem !== toItem) {\n const oldItem = draft.surveyItems.find((item) => item.id === fromItem),\n newItem = draft.surveyItems.find((item) => item.id === toItem);\n if (oldItem?.itemType !== \"content\" || newItem?.itemType !== \"content\")\n throw new Error(\"Invalid content-item move\");\n const affected =\n oldItem.config.validationRules?.filter((rule) =>\n rule.targets.some((id) => ownedSlots.has(id)),\n ) ?? [];\n if (\n affected.length &&\n (ruleTransfer !== \"move-with-targets\" ||\n affected.some((rule) => rule.targets.some((id) => !ownedSlots.has(id))))\n )\n throw new Error(\n \"This move changes validation-rule ownership. Move all targets with explicit ruleTransfer or repair the rules first.\",\n );\n if (affected.length) {\n oldItem.config.validationRules = oldItem.config.validationRules?.filter(\n (rule) => !affected.includes(rule),\n );\n newItem.config.validationRules = [...(newItem.config.validationRules ?? []), ...affected];\n }\n }\n const [element] = parent.splice(position, 1);\n elements.splice(index ?? elements.length, 0, element);\n });\n }\n\n /** Move selected roots into a new group under the first root's parent, as in the outline UI. */\n groupItems(\n itemIds: readonly string[],\n meta: CommitMeta = { label: \"Group selected items\" },\n ): string {\n const requested = new Set(itemIds);\n if (\n !requested.size ||\n requested.has(this.current.rootId) ||\n [...requested].some((id) => !this.current.getItem(id))\n )\n throw new Error(\"Select existing non-root items to group\");\n const roots = this.current.itemOutline\n .map((entry) => entry.itemId)\n .filter(\n (id) =>\n requested.has(id) &&\n ![...requested].some((other) => other !== id && this.current.isDescendantOf(id, other)),\n );\n const parent = this.current.getParentItem(roots[0])!;\n const id = generateId();\n this.transact(meta, (draft) => {\n const destination = draft.surveyItems.find((item) => item.id === parent.id);\n if (destination?.itemType !== \"group\") throw new Error(\"Grouping requires a flow parent\");\n const index = destination.config.items.indexOf(roots[0]);\n destination.config.items.splice(index, 0, id);\n for (const item of draft.surveyItems)\n if (item.itemType === \"group\")\n item.config.items = item.config.items.filter((child) => !roots.includes(child));\n draft.surveyItems.push({\n id,\n itemType: \"group\",\n config: { items: roots },\n });\n });\n return id;\n }\n\n copyItem(itemId: string) {\n return copySurveyItem(this.current, itemId);\n }\n pasteItem(input: unknown, target: Target): string {\n const parent = this.current.getItem(target.parentId);\n if (parent?.itemType !== \"group\") throw new Error(\"Paste target must be a group\");\n if (target.index !== undefined && (!Number.isInteger(target.index) || target.index < 0))\n throw new Error(\"Invalid paste index\");\n const payload = prepareItemPaste(this.current, input);\n this.transact({ label: \"Paste item\" }, (draft) => {\n const group = draft.surveyItems.find((item) => item.id === target.parentId);\n if (group?.itemType !== \"group\") throw new Error(\"Paste target must be a group\");\n group.config.items.splice(\n Math.min(target.index ?? group.config.items.length, group.config.items.length),\n 0,\n payload.rootItemId,\n );\n draft.surveyItems.push(...payload.surveyItems);\n for (const [locale, translation] of Object.entries(payload.translations ?? {})) {\n // Clipboard envelopes may contain languages with no copied wording.\n if (!Object.values(translation.content).some((roles) => Object.keys(roles).length))\n continue;\n draft.translations ??= {};\n const destination = ownValue(draft.translations, locale) ?? { content: {} };\n setOwnValue(draft.translations, locale, destination);\n for (const [ownerId, roles] of Object.entries(translation.content))\n setOwnValue(destination.content, ownerId, roles);\n }\n if (Object.keys(payload.assets ?? {}).length)\n draft.assets = { ...draft.assets, ...payload.assets };\n });\n return payload.rootItemId;\n }\n\n copyElement(elementId: string, layoutId: string) {\n const sourcePath = this.identityPath(elementId, \"element\");\n const source = this.current.elements.get(elementId)!;\n const ids = new Map(\n [...this.current.identities.values()]\n .filter((declaration) => inside(sourcePath, declaration.path))\n .map((declaration) => [declaration.id, generateId()]),\n );\n const copy = allocateCopiedResponseNames(\n this.current.registry.elementSchema,\n remapAnnotated(this.current.registry.elementSchema, source.node, ids),\n this.current.registry,\n new Set(this.current.slots.definitions.map((slot) => slot.variableName)),\n );\n this.transact({ label: \"Copy element\" }, (draft) => {\n arrayAt(draft, [...this.identityPath(layoutId, \"layout\"), \"elements\"]).push(copy);\n for (const translation of Object.values(draft.translations ?? {}))\n for (const [oldId, newId] of ids) {\n const content = ownValue(translation.content, oldId);\n if (content) setOwnValue(translation.content, newId, structuredClone(content));\n }\n });\n return copy.id;\n }\n}\n"],"mappings":";;;;;;AAWA,MAAa,eAAe;CAC1B,MAAM;CACN,QAAQ;CACR,WAAW;AACb;AAiDA,IAAM,mBAAN,MAAuB;CACrB,OAAe,UAAU,IAAI,YAAY;CAEzC,OAAO,cAAc,KAAqB;EACxC,MAAM,aAAa,KAAK,UAAU,GAAG;EACrC,OAAO,KAAK,QAAQ,OAAO,UAAU,CAAC,CAAC;CACzC;CAEA,OAAO,YAAY,OAAuB;EACxC,MAAM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