@case-framework/survey-assistant 0.3.0 → 0.5.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.
Files changed (79) hide show
  1. package/README.md +20 -4
  2. package/dist/capabilities-default.d.mts +1 -1
  3. package/dist/capabilities-default.mjs +1 -1
  4. package/dist/{constants-DrGZXtQf.d.mts → constants-DbrJxxOh.d.mts} +5 -2
  5. package/dist/constants-DbrJxxOh.d.mts.map +1 -0
  6. package/dist/{controller-proxy-DmBdzqKs.d.mts → controller-proxy-BdKF2yrq.d.mts} +2 -2
  7. package/dist/{controller-proxy-DmBdzqKs.d.mts.map → controller-proxy-BdKF2yrq.d.mts.map} +1 -1
  8. package/dist/{controller-proxy-CpkQRezb.mjs → controller-proxy-jWIPOZAv.mjs} +17 -8
  9. package/dist/controller-proxy-jWIPOZAv.mjs.map +1 -0
  10. package/dist/{engine-CWTuN3o2.mjs → engine-DcSdLRle.mjs} +172 -12
  11. package/dist/engine-DcSdLRle.mjs.map +1 -0
  12. package/dist/engine.d.mts +2 -2
  13. package/dist/engine.mjs +3 -3
  14. package/dist/{form-authoring-DCd9XfXf.mjs → form-authoring-BQh40yDb.mjs} +2 -2
  15. package/dist/{form-authoring-DCd9XfXf.mjs.map → form-authoring-BQh40yDb.mjs.map} +1 -1
  16. package/dist/{index-D4OitUg4.d.mts → index-BApnIiCI.d.mts} +7 -4
  17. package/dist/index-BApnIiCI.d.mts.map +1 -0
  18. package/dist/{index-Bo4dHAo8.d.mts → index-Da_Hb9-1.d.mts} +28 -4
  19. package/dist/index-Da_Hb9-1.d.mts.map +1 -0
  20. package/dist/{index-DZk20e3k.d.mts → index-DhNQKOwr.d.mts} +9 -5
  21. package/dist/index-DhNQKOwr.d.mts.map +1 -0
  22. package/dist/{index-Dxgg0-D_.d.mts → index-dV6df0W3.d.mts} +11 -5
  23. package/dist/index-dV6df0W3.d.mts.map +1 -0
  24. package/dist/{memory-thread-repository-acbz6HZJ.mjs → memory-thread-repository-CvYZwni6.mjs} +87 -28
  25. package/dist/memory-thread-repository-CvYZwni6.mjs.map +1 -0
  26. package/dist/{protocol-DATvkr1S.mjs → protocol-DJUP4gc0.mjs} +10 -4
  27. package/dist/protocol-DJUP4gc0.mjs.map +1 -0
  28. package/dist/protocol.d.mts +1 -1
  29. package/dist/protocol.mjs +1 -1
  30. package/dist/{react-Br5YE8H-.mjs → react-CY6N7lVi.mjs} +25 -5
  31. package/dist/react-CY6N7lVi.mjs.map +1 -0
  32. package/dist/react-integration.d.mts +1 -1
  33. package/dist/react-integration.mjs +1 -1
  34. package/dist/react.d.mts +2 -2
  35. package/dist/react.mjs +2 -2
  36. package/dist/{request-context-BEjnaaFr.mjs → request-context-D1sC54ZA.mjs} +3 -3
  37. package/dist/request-context-D1sC54ZA.mjs.map +1 -0
  38. package/dist/server-agent.d.mts +8 -6
  39. package/dist/server-agent.d.mts.map +1 -1
  40. package/dist/server-agent.mjs +4 -3
  41. package/dist/server-agent.mjs.map +1 -1
  42. package/dist/server-runtime.d.mts +354 -7
  43. package/dist/server-runtime.d.mts.map +1 -1
  44. package/dist/server-runtime.mjs +361 -24
  45. package/dist/server-runtime.mjs.map +1 -1
  46. package/dist/server-tasks.d.mts +1 -1
  47. package/dist/server-tasks.mjs +5 -4
  48. package/dist/server-tasks.mjs.map +1 -1
  49. package/dist/server-tools.d.mts +1 -1
  50. package/dist/server-tools.mjs +1 -1
  51. package/dist/server.d.mts +7 -7
  52. package/dist/server.d.mts.map +1 -1
  53. package/dist/server.mjs +2 -2
  54. package/dist/storage-postgres.mjs +3 -0
  55. package/dist/storage-postgres.mjs.map +1 -1
  56. package/dist/{tasks-DQgL449A.d.mts → tasks-CCtxjhwh.d.mts} +3 -3
  57. package/dist/{tasks-DQgL449A.d.mts.map → tasks-CCtxjhwh.d.mts.map} +1 -1
  58. package/dist/{thread-handlers-CeYl45xG.d.mts → thread-handlers-Bt9cDo-F.d.mts} +21 -6
  59. package/dist/{thread-handlers-CeYl45xG.d.mts.map → thread-handlers-Bt9cDo-F.d.mts.map} +1 -1
  60. package/dist/{tools-Dg9HZrYU.mjs → tools-3tq-XqI0.mjs} +31 -6
  61. package/dist/{tools-Dg9HZrYU.mjs.map → tools-3tq-XqI0.mjs.map} +1 -1
  62. package/dist/ui.css +1 -1
  63. package/dist/ui.d.mts +3 -3
  64. package/dist/ui.d.mts.map +1 -1
  65. package/dist/ui.mjs +438 -140
  66. package/dist/ui.mjs.map +1 -1
  67. package/docs/integration.md +113 -58
  68. package/package.json +3 -3
  69. package/dist/constants-DrGZXtQf.d.mts.map +0 -1
  70. package/dist/controller-proxy-CpkQRezb.mjs.map +0 -1
  71. package/dist/engine-CWTuN3o2.mjs.map +0 -1
  72. package/dist/index-Bo4dHAo8.d.mts.map +0 -1
  73. package/dist/index-D4OitUg4.d.mts.map +0 -1
  74. package/dist/index-DZk20e3k.d.mts.map +0 -1
  75. package/dist/index-Dxgg0-D_.d.mts.map +0 -1
  76. package/dist/memory-thread-repository-acbz6HZJ.mjs.map +0 -1
  77. package/dist/protocol-DATvkr1S.mjs.map +0 -1
  78. package/dist/react-Br5YE8H-.mjs.map +0 -1
  79. package/dist/request-context-BEjnaaFr.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"engine-CWTuN3o2.mjs","names":["isRecord","asString","asArray","createIssue","isRecord","getRawSurvey","createIssue","isRecord","isRecord","isRecord","rawItem","isRecord","#candidates","#context","#assertOpen","#draftOperations","#latestChangeSetId","#unresolvedCandidates","#final"],"sources":["../src/engine/context.ts","../src/engine/expression-validation.ts","../src/engine/inspection.ts","../src/engine/expression-mutations.ts","../src/engine/normalization.ts","../src/engine/operations.ts","../src/engine/audit.ts","../src/engine/turn-survey-draft.ts","../src/engine/task-context.ts","../src/engine/task-result-cache.ts"],"sourcesContent":["import {\n SurveyTranslations,\n ValueReferenceMethod,\n ValueType,\n getContentPlainText,\n type Content,\n type RawSurvey,\n type RawSurveyItem,\n} from \"@case-framework/survey-core\";\nimport type {\n SurveyAssistantCapabilityManifest,\n SurveyDocumentSnapshot,\n SurveyDocumentVersion,\n} from \"../protocol\";\nimport { buildCapabilityDigest, hashString, stableStringify } from \"../protocol/digest\";\nimport {\n assertSurveyAssistantCapabilities,\n type SurveyAssistantCapabilitySet,\n} from \"./capabilities\";\n\nexport type SurveyAssistantResponseSlotTypes = Record<string, ValueType | undefined>;\n\nexport interface SurveyAssistantInspectionOutlineNode {\n itemId: string;\n parentId?: string;\n depth: number;\n itemType: string;\n key: string;\n fullKey: string;\n itemLabel?: string;\n childCount: number;\n}\n\nexport interface SurveyAssistantInspectionFocus {\n focusItemId: string;\n parentItemId?: string;\n pathItemIds: string[];\n siblingItemIds: string[];\n childItemIds: string[];\n}\n\nexport interface SurveyAssistantInspectionItemNode {\n itemId: string;\n itemType: string;\n itemKey: string;\n fullKey: string;\n itemLabel?: string;\n siblingKeys: string[];\n translations: Array<{ locale: string; contentKey: string; text: string }>;\n descendants: SurveyAssistantInspectionItemNode[];\n}\n\nexport interface SurveyAssistantInspectionKeyEntry {\n itemId: string;\n itemType: string;\n key: string;\n fullKey: string;\n itemLabel?: string;\n path: string[];\n}\n\n/** Deterministic, request-local lookup data derived from the canonical document. */\nexport interface SurveyAssistantInspectionIndex {\n surveyKey?: string;\n locales: string[];\n /** All survey items except the structural root group. */\n itemCount: number;\n outline: SurveyAssistantInspectionOutlineNode[];\n focus?: SurveyAssistantInspectionFocus;\n focusItem?: SurveyAssistantInspectionItemNode;\n keyIndex: SurveyAssistantInspectionKeyEntry[];\n responseSlots: string[];\n focusItemTreeTruncated: boolean;\n}\n\n/** Request-local derived state built from one authoritative survey document. */\nexport interface SurveyAssistantEngineContext {\n document: SurveyDocumentSnapshot;\n version: SurveyDocumentVersion;\n survey: RawSurvey;\n ui: SurveyDocumentSnapshot[\"ui\"];\n capabilities: SurveyAssistantCapabilityManifest;\n responseSlotTypes: SurveyAssistantResponseSlotTypes;\n inspection: SurveyAssistantInspectionIndex;\n trustedCapabilities?: SurveyAssistantCapabilitySet;\n}\n\nexport interface CreateSurveyAssistantEngineContextOptions {\n focusItemId?: string;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst asString = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n\nconst asArray = (value: unknown): unknown[] => (Array.isArray(value) ? value : []);\n\nconst getChildIds = (item: RawSurveyItem): string[] => {\n const config = isRecord(item.config) ? item.config : undefined;\n return asArray(config?.items).filter((entry): entry is string => typeof entry === \"string\");\n};\n\nconst getFieldValueType = (field: Record<string, unknown>): ValueType => {\n switch (field.type) {\n case \"number\":\n case \"slider\":\n return ValueType.number;\n case \"datepicker\":\n return ValueType.date;\n case \"switch\":\n return ValueType.boolean;\n default:\n return ValueType.string;\n }\n};\n\nconst addResponseSlot = (\n lookup: SurveyAssistantResponseSlotTypes,\n itemId: string,\n slotId: string,\n valueType: ValueType,\n) => {\n lookup[`${itemId}...${ValueReferenceMethod.get}...${slotId}`] = valueType;\n lookup[`${itemId}...${ValueReferenceMethod.isDefined}...${slotId}`] = ValueType.boolean;\n};\n\nconst addFormResponseSlots = ({\n config,\n itemId,\n lookup,\n slotPrefix,\n}: {\n config: unknown;\n itemId: string;\n lookup: SurveyAssistantResponseSlotTypes;\n slotPrefix?: string;\n}) => {\n if (!isRecord(config)) return;\n for (const group of asArray(config.fieldGroups).filter(isRecord)) {\n for (const field of asArray(group.fields).filter(isRecord)) {\n const key = asString(field.key);\n if (!key) continue;\n addResponseSlot(\n lookup,\n itemId,\n slotPrefix ? `${slotPrefix}.${key}` : key,\n getFieldValueType(field),\n );\n }\n }\n};\n\nexport const deriveResponseSlotTypes = (\n survey: RawSurvey,\n trustedCapabilities?: SurveyAssistantCapabilitySet,\n): SurveyAssistantResponseSlotTypes => {\n const lookup: SurveyAssistantResponseSlotTypes = {};\n for (const item of survey.surveyItems) {\n const deriveResponseSlots = trustedCapabilities?.byItemType.get(\n item.itemType,\n )?.deriveResponseSlots;\n if (deriveResponseSlots) {\n for (const [slotId, valueType] of Object.entries(deriveResponseSlots(item))) {\n addResponseSlot(lookup, item.id, slotId, valueType);\n }\n continue;\n }\n\n // Pure snapshot callers do not have trusted executable adapters, so derive\n // the built-in response slots without registry code.\n if (item.itemType === \"choiceItem\") {\n const config = isRecord(item.config) ? item.config : {};\n const slotId = asString(config.id) ?? item.id;\n addResponseSlot(\n lookup,\n item.id,\n slotId,\n config.maxSelection === 1 ? ValueType.reference : ValueType.referenceArray,\n );\n for (const option of asArray(config.options).filter(isRecord)) {\n const optionId = asString(option.id);\n if (optionId && option.embeddedForm) {\n addFormResponseSlots({\n config: option.embeddedForm,\n itemId: item.id,\n lookup,\n slotPrefix: `embedded.${optionId}`,\n });\n }\n }\n } else if (item.itemType === \"formItem\") {\n addFormResponseSlots({ config: item.config, itemId: item.id, lookup });\n }\n }\n return lookup;\n};\n\nconst buildDerivedContext = (\n snapshot: SurveyDocumentSnapshot,\n trustedCapabilities?: SurveyAssistantCapabilitySet,\n requestedFocusItemId?: string,\n) => {\n const rawItems = snapshot.survey.surveyItems;\n const itemsById = new Map(rawItems.map((item) => [item.id, item]));\n const parentById = new Map<string, string>();\n for (const item of rawItems) {\n for (const childId of getChildIds(item)) {\n if (itemsById.has(childId) && !parentById.has(childId)) parentById.set(childId, item.id);\n }\n }\n\n const fullKeyCache = new Map<string, string>();\n const getFullKey = (itemId: string, stack = new Set<string>()): string => {\n const cached = fullKeyCache.get(itemId);\n if (cached) return cached;\n const item = itemsById.get(itemId);\n if (!item) return itemId;\n if (stack.has(itemId)) return item.key;\n const parentId = parentById.get(itemId);\n if (!parentId) return item.key;\n stack.add(itemId);\n const fullKey = `${getFullKey(parentId, stack)}.${item.key}`;\n stack.delete(itemId);\n fullKeyCache.set(itemId, fullKey);\n return fullKey;\n };\n\n const outline: SurveyAssistantInspectionOutlineNode[] = [];\n const visited = new Set<string>();\n const visit = (itemId: string, depth: number) => {\n if (visited.has(itemId)) return;\n const item = itemsById.get(itemId);\n if (!item) return;\n visited.add(itemId);\n outline.push({\n itemId,\n parentId: parentById.get(itemId),\n depth,\n itemType: item.itemType,\n key: item.key,\n fullKey: getFullKey(itemId),\n itemLabel: item.metadata?.itemLabel,\n childCount: getChildIds(item).length,\n });\n for (const childId of getChildIds(item)) visit(childId, depth + 1);\n };\n\n const explicitRoot = rawItems.find(\n (item) => isRecord(item.config) && item.config.isRoot === true,\n );\n if (explicitRoot) visit(explicitRoot.id, 0);\n for (const item of [...rawItems].sort((left, right) => left.id.localeCompare(right.id))) {\n if (!visited.has(item.id)) visit(item.id, 0);\n }\n\n const keyIndex: SurveyAssistantInspectionKeyEntry[] = outline.map((node) => ({\n itemId: node.itemId,\n itemType: node.itemType,\n key: node.key,\n fullKey: node.fullKey,\n itemLabel: node.itemLabel,\n path: node.fullKey.split(\".\"),\n }));\n\n const translations = new SurveyTranslations(snapshot.survey.translations);\n const buildFocusNode = (\n itemId: string,\n budget: { remaining: number },\n ): SurveyAssistantInspectionItemNode => {\n const item = itemsById.get(itemId)!;\n budget.remaining -= 1;\n const itemTranslations = translations.getItemTranslations(itemId);\n const translationSnippets = (itemTranslations?.locales ?? []).flatMap((locale) =>\n Object.entries(itemTranslations?.getAllForLocale(locale) ?? {})\n .slice(0, 8)\n .map(([contentKey, content]) => ({\n locale,\n contentKey,\n text: getContentPlainText(content as Content).slice(0, 120),\n })),\n );\n return {\n itemId,\n itemType: item.itemType,\n itemKey: item.key,\n fullKey: getFullKey(itemId),\n itemLabel: item.metadata?.itemLabel,\n siblingKeys: rawItems\n .filter(\n (candidate) =>\n candidate.id !== itemId && parentById.get(candidate.id) === parentById.get(itemId),\n )\n .map((candidate) => candidate.key),\n translations: translationSnippets,\n descendants: getChildIds(item)\n .filter((childId) => itemsById.has(childId) && budget.remaining > 0)\n .map((childId) => buildFocusNode(childId, budget)),\n };\n };\n\n const focusItemId = requestedFocusItemId ?? snapshot.ui.focusItemId ?? snapshot.ui.selectedItemId;\n let focus: SurveyAssistantInspectionFocus | undefined;\n let focusItem: SurveyAssistantInspectionItemNode | undefined;\n let focusItemTreeTruncated = false;\n if (focusItemId && itemsById.has(focusItemId)) {\n const pathItemIds: string[] = [];\n let currentId: string | undefined = focusItemId;\n const pathSeen = new Set<string>();\n while (currentId && !pathSeen.has(currentId)) {\n pathSeen.add(currentId);\n pathItemIds.unshift(currentId);\n currentId = parentById.get(currentId);\n }\n const parentItemId = parentById.get(focusItemId);\n focus = {\n focusItemId,\n parentItemId,\n pathItemIds,\n siblingItemIds: rawItems\n .filter(\n (candidate) =>\n candidate.id !== focusItemId && parentById.get(candidate.id) === parentItemId,\n )\n .map((candidate) => candidate.id),\n childItemIds: getChildIds(itemsById.get(focusItemId)!),\n };\n const budget = { remaining: 120 };\n focusItem = buildFocusNode(focusItemId, budget);\n focusItemTreeTruncated = budget.remaining === 0;\n }\n\n const responseSlotTypes = deriveResponseSlotTypes(snapshot.survey, trustedCapabilities);\n const locales = [\n snapshot.ui.selectedLocale,\n ...Object.keys(snapshot.survey.translations ?? {}).filter(\n (locale) => locale !== snapshot.ui.selectedLocale,\n ),\n ].filter((locale, index, values) => locale.length > 0 && values.indexOf(locale) === index);\n\n const inspection: SurveyAssistantInspectionIndex = {\n surveyKey: explicitRoot?.key,\n locales,\n itemCount: rawItems.filter((item) => item.id !== explicitRoot?.id).length,\n outline,\n focus,\n focusItem,\n keyIndex,\n responseSlots: Object.keys(responseSlotTypes),\n focusItemTreeTruncated,\n };\n\n return { inspection, responseSlotTypes };\n};\n\nexport const createSurveyAssistantEngineContext = (\n document: SurveyDocumentSnapshot,\n trustedCapabilities?: SurveyAssistantCapabilitySet,\n options?: CreateSurveyAssistantEngineContextOptions,\n): SurveyAssistantEngineContext => {\n assertSurveyAssistantCapabilities({\n manifest: document.capabilities,\n trustedCapabilities,\n versionDigest: document.version.capabilityDigest,\n });\n const { inspection, responseSlotTypes } = buildDerivedContext(\n document,\n trustedCapabilities,\n options?.focusItemId,\n );\n return {\n document,\n version: document.version,\n survey: document.survey,\n ui: document.ui,\n capabilities: document.capabilities,\n responseSlotTypes,\n inspection,\n trustedCapabilities,\n };\n};\n","import {\n Expression,\n ExpressionType,\n FunctionExpressionNames,\n ValueType,\n type JsonExpression,\n} from \"@case-framework/survey-core\";\nimport type { SurveyValidationIssue } from \"../protocol\";\n\nexport type ResponseSlotTypeLookup = Record<string, ValueType | undefined>;\n\ntype IssueInput = Omit<SurveyValidationIssue, \"severity\"> & {\n severity?: SurveyValidationIssue[\"severity\"];\n};\n\nconst createIssue = ({ severity = \"error\", ...input }: IssueInput): SurveyValidationIssue => ({\n severity,\n ...input,\n});\n\nconst formatValueType = (valueType: ValueType | undefined) => valueType ?? \"unknown\";\n\nconst addFunctionSignatureIssue = ({\n issues,\n message,\n operationIndex,\n scope,\n}: {\n issues: SurveyValidationIssue[];\n message: string;\n operationIndex: number;\n scope: string;\n}) => {\n issues.push(\n createIssue({\n code: \"expression-function-signature-mismatch\",\n message: `${scope} has an invalid function expression: ${message}`,\n operationIndex,\n }),\n );\n};\n\nconst validateArgumentCount = ({\n actual,\n expected,\n functionName,\n issues,\n operationIndex,\n scope,\n}: {\n actual: number;\n expected: number;\n functionName: FunctionExpressionNames;\n issues: SurveyValidationIssue[];\n operationIndex: number;\n scope: string;\n}) => {\n if (actual === expected) {\n return;\n }\n\n addFunctionSignatureIssue({\n issues,\n operationIndex,\n scope,\n message: `${functionName} expects ${expected} argument${expected === 1 ? \"\" : \"s\"}, got ${actual}.`,\n });\n};\n\nexport const inferExpressionReturnType = (\n expression: JsonExpression | undefined,\n responseSlotTypes: ResponseSlotTypeLookup,\n): ValueType | undefined => {\n if (!expression) {\n return undefined;\n }\n\n if (expression.type === ExpressionType.Const) {\n return expression.value?.type;\n }\n\n if (expression.type === ExpressionType.ResponseVariable) {\n return responseSlotTypes[expression.variableRef];\n }\n\n if (expression.type === ExpressionType.ContextVariable) {\n if (expression.contextType === \"locale\") {\n return ValueType.string;\n }\n return expression.asType;\n }\n\n switch (expression.functionName) {\n case FunctionExpressionNames.and:\n case FunctionExpressionNames.or:\n case FunctionExpressionNames.not:\n case FunctionExpressionNames.eq:\n case FunctionExpressionNames.gt:\n case FunctionExpressionNames.gte:\n case FunctionExpressionNames.lt:\n case FunctionExpressionNames.lte:\n case FunctionExpressionNames.in_range:\n case FunctionExpressionNames.list_contains:\n case FunctionExpressionNames.str_eq:\n case FunctionExpressionNames.date_eq:\n return ValueType.boolean;\n case FunctionExpressionNames.sum:\n case FunctionExpressionNames.min:\n case FunctionExpressionNames.max:\n return ValueType.number;\n }\n};\n\nconst validateExpressionFunctionSignatures = ({\n expression,\n issues,\n operationIndex,\n responseSlotTypes,\n scope,\n}: {\n expression: JsonExpression | undefined;\n issues: SurveyValidationIssue[];\n operationIndex: number;\n responseSlotTypes: ResponseSlotTypeLookup;\n scope: string;\n}) => {\n if (!expression || expression.type !== ExpressionType.Function) {\n return;\n }\n\n expression.arguments.forEach((argument, argumentIndex) => {\n validateExpressionFunctionSignatures({\n expression: argument,\n issues,\n operationIndex,\n responseSlotTypes,\n scope: `${scope} argument ${argumentIndex + 1}`,\n });\n });\n\n const argumentTypes = expression.arguments.map((argument) =>\n inferExpressionReturnType(argument, responseSlotTypes),\n );\n\n const requireBooleanArguments = () => {\n argumentTypes.forEach((argumentType, argumentIndex) => {\n if (argumentType && argumentType !== ValueType.boolean) {\n addFunctionSignatureIssue({\n issues,\n operationIndex,\n scope,\n message: `${expression.functionName} argument ${\n argumentIndex + 1\n } must be boolean, got ${formatValueType(argumentType)}.`,\n });\n }\n });\n };\n\n const requireNumericArguments = () => {\n argumentTypes.forEach((argumentType, argumentIndex) => {\n if (argumentType && argumentType !== ValueType.number) {\n addFunctionSignatureIssue({\n issues,\n operationIndex,\n scope,\n message: `${expression.functionName} argument ${\n argumentIndex + 1\n } must be number, got ${formatValueType(argumentType)}.`,\n });\n }\n });\n };\n\n const requireSameKnownType = () => {\n if (argumentTypes.length < 2 || !argumentTypes[0] || !argumentTypes[1]) {\n return;\n }\n\n if (argumentTypes[0] !== argumentTypes[1]) {\n addFunctionSignatureIssue({\n issues,\n operationIndex,\n scope,\n message: `${expression.functionName} arguments must have the same type, got ${formatValueType(\n argumentTypes[0],\n )} and ${formatValueType(argumentTypes[1])}.`,\n });\n }\n };\n\n switch (expression.functionName) {\n case FunctionExpressionNames.and:\n case FunctionExpressionNames.or:\n requireBooleanArguments();\n break;\n case FunctionExpressionNames.not:\n validateArgumentCount({\n actual: expression.arguments.length,\n expected: 1,\n functionName: expression.functionName,\n issues,\n operationIndex,\n scope,\n });\n requireBooleanArguments();\n break;\n case FunctionExpressionNames.str_eq:\n validateArgumentCount({\n actual: expression.arguments.length,\n expected: 2,\n functionName: expression.functionName,\n issues,\n operationIndex,\n scope,\n });\n argumentTypes.forEach((argumentType, argumentIndex) => {\n if (argumentType && argumentType !== ValueType.string) {\n addFunctionSignatureIssue({\n issues,\n operationIndex,\n scope,\n message: `str_eq argument ${argumentIndex + 1} must be string, got ${formatValueType(\n argumentType,\n )}.`,\n });\n }\n });\n break;\n case FunctionExpressionNames.date_eq:\n validateArgumentCount({\n actual: expression.arguments.length,\n expected: 2,\n functionName: expression.functionName,\n issues,\n operationIndex,\n scope,\n });\n argumentTypes.forEach((argumentType, argumentIndex) => {\n if (argumentType && argumentType !== ValueType.date) {\n addFunctionSignatureIssue({\n issues,\n operationIndex,\n scope,\n message: `date_eq argument ${argumentIndex + 1} must be date, got ${formatValueType(\n argumentType,\n )}.`,\n });\n }\n });\n break;\n case FunctionExpressionNames.eq:\n case FunctionExpressionNames.gt:\n case FunctionExpressionNames.gte:\n case FunctionExpressionNames.lt:\n case FunctionExpressionNames.lte:\n validateArgumentCount({\n actual: expression.arguments.length,\n expected: 2,\n functionName: expression.functionName,\n issues,\n operationIndex,\n scope,\n });\n requireSameKnownType();\n break;\n case FunctionExpressionNames.in_range:\n validateArgumentCount({\n actual: expression.arguments.length,\n expected: 4,\n functionName: expression.functionName,\n issues,\n operationIndex,\n scope,\n });\n argumentTypes.slice(0, 3).forEach((argumentType, argumentIndex) => {\n if (argumentType && argumentType !== ValueType.number) {\n addFunctionSignatureIssue({\n issues,\n operationIndex,\n scope,\n message: `in_range argument ${argumentIndex + 1} must be number, got ${formatValueType(\n argumentType,\n )}.`,\n });\n }\n });\n if (argumentTypes[3] && argumentTypes[3] !== ValueType.boolean) {\n addFunctionSignatureIssue({\n issues,\n operationIndex,\n scope,\n message: `in_range argument 4 must be boolean, got ${formatValueType(argumentTypes[3])}.`,\n });\n }\n break;\n case FunctionExpressionNames.sum:\n case FunctionExpressionNames.min:\n case FunctionExpressionNames.max:\n if (expression.arguments.length < 1) {\n addFunctionSignatureIssue({\n issues,\n operationIndex,\n scope,\n message: `${expression.functionName} expects at least 1 argument, got 0.`,\n });\n }\n requireNumericArguments();\n break;\n case FunctionExpressionNames.list_contains: {\n validateArgumentCount({\n actual: expression.arguments.length,\n expected: 2,\n functionName: expression.functionName,\n issues,\n operationIndex,\n scope,\n });\n const listType = argumentTypes[0];\n const itemType = argumentTypes[1];\n if (listType && listType !== ValueType.stringArray && listType !== ValueType.referenceArray) {\n addFunctionSignatureIssue({\n issues,\n operationIndex,\n scope,\n message: `list_contains argument 1 must be string[] or reference[], got ${formatValueType(\n listType,\n )}. Use eq for single-choice reference responses.`,\n });\n }\n if (listType === ValueType.stringArray && itemType && itemType !== ValueType.string) {\n addFunctionSignatureIssue({\n issues,\n operationIndex,\n scope,\n message: `list_contains with string[] needs a string item, got ${formatValueType(\n itemType,\n )}.`,\n });\n }\n if (listType === ValueType.referenceArray && itemType && itemType !== ValueType.reference) {\n addFunctionSignatureIssue({\n issues,\n operationIndex,\n scope,\n message: `list_contains with reference[] needs a reference item, got ${formatValueType(\n itemType,\n )}.`,\n });\n }\n break;\n }\n }\n};\n\nexport const validateExpression = ({\n expression,\n expectedReturnType,\n issues,\n operationIndex,\n responseSlotTypes,\n scope,\n}: {\n expression: JsonExpression | undefined;\n expectedReturnType?: ValueType;\n issues: SurveyValidationIssue[];\n operationIndex: number;\n responseSlotTypes: ResponseSlotTypeLookup;\n scope: string;\n}) => {\n if (!expression) {\n issues.push(\n createIssue({\n code: \"missing-expression\",\n message: `${scope} needs an expression.`,\n operationIndex,\n }),\n );\n return;\n }\n\n let parsed: Expression | undefined;\n try {\n parsed = Expression.deserialize(expression);\n } catch (error) {\n issues.push(\n createIssue({\n code: \"invalid-expression\",\n message: `${scope} contains invalid expression JSON: ${\n error instanceof Error ? error.message : String(error)\n }`,\n operationIndex,\n }),\n );\n return;\n }\n\n for (const ref of parsed?.responseVariableRefs ?? []) {\n if (!(ref.toString() in responseSlotTypes)) {\n issues.push(\n createIssue({\n code: \"unknown-response-ref\",\n message: `${scope} references unknown response slot \"${ref.toString()}\". Inspect response slots before using it.`,\n operationIndex,\n }),\n );\n }\n }\n\n validateExpressionFunctionSignatures({\n expression,\n issues,\n operationIndex,\n responseSlotTypes,\n scope,\n });\n\n const inferred = inferExpressionReturnType(expression, responseSlotTypes);\n if (expectedReturnType && inferred && inferred !== expectedReturnType) {\n issues.push(\n createIssue({\n code: \"expression-return-type-mismatch\",\n message: `${scope} must return ${expectedReturnType}, but this expression appears to return ${inferred}.`,\n operationIndex,\n }),\n );\n }\n};\n","import {\n SurveyTranslations,\n getContentPlainText,\n type Content,\n type RawSurvey,\n type RawSurveyItem,\n} from \"@case-framework/survey-core\";\nimport type { SurveyAssistantEngineContext } from \"./context\";\nimport { getFormAuthoringMode, isValidSimpleFormConfig } from \"./form-authoring\";\nimport { z } from \"zod\";\n\nexport const DEFAULT_LIMIT = 12;\nexport const MAX_LIMIT = 50;\n\nexport const itemSummarySchema = z.object({\n itemId: z.string(),\n itemType: z.string(),\n key: z.string(),\n fullKey: z.string(),\n itemLabel: z.string().optional(),\n parentId: z.string().optional(),\n depth: z.number().int().nonnegative().optional(),\n childCount: z.number().int().nonnegative().optional(),\n path: z.array(z.string()).optional(),\n siblingKeys: z.array(z.string()).optional(),\n});\n\nexport type ItemSummary = z.infer<typeof itemSummarySchema>;\n\nexport const translationEntrySchema = z.object({\n locale: z.string(),\n contentKey: z.string(),\n text: z.string(),\n});\n\nexport type TranslationEntry = z.infer<typeof translationEntrySchema>;\n\nexport const choiceOptionDetailsSchema = z.object({\n position: z.number().int().positive().describe(\"One-based position in the stored option order.\"),\n id: z.string(),\n key: z.string().optional(),\n labelContentKey: z.string(),\n hasDisplayCondition: z.boolean().optional(),\n embeddedFormItemId: z.string().optional(),\n embeddedFormFieldGroupCount: z.number().int().nonnegative().optional(),\n embeddedFormAuthoringMode: z.enum([\"simple\", \"custom\"]).optional(),\n embeddedFormSimpleModeValid: z.boolean().optional(),\n embeddedFormTranslationPrefix: z.string().optional(),\n embeddedFormResponseSlotPrefix: z.string().optional(),\n});\n\nexport const formSelectOptionDetailsSchema = z.object({\n position: z\n .number()\n .int()\n .positive()\n .describe(\"One-based position in the stored select-option order.\"),\n id: z.string(),\n value: z.string().optional(),\n labelContentKey: z.string(),\n});\n\nexport const formFieldGroupLayoutSchema = z.object({\n base: z.number().int().positive(),\n xs: z.number().int().positive(),\n sm: z.number().int().positive(),\n md: z.number().int().positive(),\n xl: z.number().int().positive(),\n});\n\nexport const formFieldDetailsSchema = z.object({\n position: z\n .number()\n .int()\n .positive()\n .describe(\"One-based position in this field group's stored field order.\"),\n id: z.string(),\n key: z.string(),\n type: z.string(),\n responseSlotId: z.string(),\n labelContentKey: z.string(),\n descriptionContentKey: z.string(),\n errorContentKey: z.string(),\n placeholderContentKey: z.string().optional(),\n unitContentKey: z.string().optional(),\n checkedLabelContentKey: z.string().optional(),\n uncheckedLabelContentKey: z.string().optional(),\n required: z.boolean().optional(),\n controllerType: z.string().optional(),\n validationTypes: z.array(z.string()).optional(),\n validationMessageContentKeys: z.array(z.string()).optional(),\n selectOptions: z.array(formSelectOptionDetailsSchema).optional(),\n});\n\nexport const formFieldGroupDetailsSchema = z.object({\n position: z\n .number()\n .int()\n .positive()\n .describe(\"One-based position in the form's stored field-group order.\"),\n id: z.string(),\n titleContentKey: z.string(),\n descriptionContentKey: z.string(),\n hasDisplayCondition: z.boolean().optional(),\n layout: formFieldGroupLayoutSchema,\n fieldCount: z.number().int().nonnegative(),\n fields: z.array(formFieldDetailsSchema),\n});\n\nexport const itemConfigDetailsSchema = z.object({\n kind: z.enum([\"choice\", \"form\", \"generic\"]),\n summary: z.array(z.string()),\n authoringMode: z.enum([\"simple\", \"custom\"]).optional(),\n simpleModeValid: z.boolean().optional(),\n mainResponseSlotId: z.string().optional(),\n choiceOptions: z.array(choiceOptionDetailsSchema).optional(),\n formFieldGroups: z.array(formFieldGroupDetailsSchema).optional(),\n listOrdering: z\n .record(z.string(), z.string())\n .optional()\n .describe(\"Meaning of each list in these config details.\"),\n});\n\nexport type ChoiceOptionDetails = z.infer<typeof choiceOptionDetailsSchema>;\nexport type FormFieldDetails = z.infer<typeof formFieldDetailsSchema>;\nexport type FormFieldGroupDetails = z.infer<typeof formFieldGroupDetailsSchema>;\nexport type ItemConfigDetails = z.infer<typeof itemConfigDetailsSchema>;\n\nexport type SurveyInspectionIndex = SurveyAssistantEngineContext[\"inspection\"];\nexport type SurveyOutlineNode = SurveyInspectionIndex[\"outline\"][number];\nexport type SurveyKeyIndexEntry = SurveyInspectionIndex[\"keyIndex\"][number];\nexport type SurveyFocusItemNode = NonNullable<SurveyInspectionIndex[\"focusItem\"]>;\n\nexport const normalizeText = (value: string | undefined) => value?.trim().toLowerCase() ?? \"\";\n\nexport const clampLimit = (limit: number | undefined) =>\n Math.min(MAX_LIMIT, Math.max(1, limit ?? DEFAULT_LIMIT));\n\nexport const parseCursor = (cursor: string | undefined): number => {\n if (!cursor) {\n return 0;\n }\n\n const parsed = Number.parseInt(cursor, 10);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;\n};\n\nexport const unique = <T>(values: T[]): T[] => Array.from(new Set(values));\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst asString = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n\nconst asBoolean = (value: unknown): boolean | undefined =>\n typeof value === \"boolean\" ? value : undefined;\n\nconst asArray = (value: unknown): unknown[] => (Array.isArray(value) ? value : []);\n\nconst createContentKey = (...segments: string[]) => segments.filter(Boolean).join(\".\");\n\nconst getChoiceOptionLabelContentKey = (optionId: string) =>\n createContentKey(\"options\", optionId, \"label\");\n\nconst getChoiceEmbeddedFormTranslationPrefix = (optionId: string) =>\n createContentKey(\"embeddedForms\", optionId);\n\nconst getChoiceEmbeddedFormResponseSlotPrefix = (optionId: string) =>\n createContentKey(\"embedded\", optionId);\n\nconst withFormTranslationNamespace = (contentKey: string, translationNamespace?: string) =>\n translationNamespace ? createContentKey(translationNamespace, contentKey) : contentKey;\n\nconst getFormFieldGroupContentKey = (\n groupId: string,\n contentKey: \"title\" | \"description\",\n translationNamespace?: string,\n) =>\n withFormTranslationNamespace(\n createContentKey(\"fieldGroups\", groupId, contentKey),\n translationNamespace,\n );\n\nconst getFormFieldContentKey = (\n fieldId: string,\n contentKey: string,\n translationNamespace?: string,\n) =>\n withFormTranslationNamespace(\n createContentKey(\"fields\", fieldId, contentKey),\n translationNamespace,\n );\n\nconst getFormFieldOptionLabelContentKey = (\n fieldId: string,\n optionId: string,\n translationNamespace?: string,\n) =>\n withFormTranslationNamespace(\n createContentKey(\"fields\", fieldId, \"options\", optionId, \"label\"),\n translationNamespace,\n );\n\nconst getFormFieldResponseSlotId = (fieldKey: string, responseSlotPrefix?: string) =>\n responseSlotPrefix ? createContentKey(responseSlotPrefix, fieldKey) : fieldKey;\n\nconst getRoundedPositiveInt = (value: unknown, fallback = 1) => {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return fallback;\n }\n\n return Math.max(1, Math.round(value));\n};\n\nexport const sliceWithCursor = <T>(values: T[], input: { cursor?: string; limit?: number }) => {\n const offset = parseCursor(input.cursor);\n const limit = clampLimit(input.limit);\n const nextOffset = offset + limit;\n const items = values.slice(offset, nextOffset);\n\n return {\n items,\n nextCursor: nextOffset < values.length ? String(nextOffset) : undefined,\n truncated: nextOffset < values.length,\n };\n};\n\nexport const mapOutlineById = (snapshot: SurveyAssistantEngineContext) =>\n new Map(snapshot.inspection.outline.map((item) => [item.itemId, item]));\n\nexport const mapKeyIndexById = (snapshot: SurveyAssistantEngineContext) =>\n new Map(snapshot.inspection.keyIndex.map((item) => [item.itemId, item]));\n\n/** The full-survey key index, regardless of the (possibly focus-scoped) outline. */\nexport const getKeyIndexEntries = (snapshot: SurveyAssistantEngineContext): SurveyKeyIndexEntry[] =>\n snapshot.inspection.keyIndex;\n\nexport const getRawSurvey = (snapshot: SurveyAssistantEngineContext): Partial<RawSurvey> =>\n snapshot.survey as Partial<RawSurvey>;\n\nexport const getRawSurveyItems = (snapshot: SurveyAssistantEngineContext): RawSurveyItem[] => {\n const rawItems = getRawSurvey(snapshot).surveyItems;\n return Array.isArray(rawItems) ? rawItems : [];\n};\n\nexport const mapRawItemsById = (snapshot: SurveyAssistantEngineContext) =>\n new Map(getRawSurveyItems(snapshot).map((item) => [item.id, item]));\n\nexport const buildSurveyTranslations = (snapshot: SurveyAssistantEngineContext) =>\n new SurveyTranslations(getRawSurvey(snapshot).translations);\n\nexport const summarizeRawItem = (item: RawSurveyItem): ItemSummary => ({\n itemId: item.id,\n itemType: item.itemType,\n key: item.key,\n fullKey: item.key,\n itemLabel: item.metadata?.itemLabel,\n});\n\nexport const buildItemTranslationEntries = (\n snapshot: SurveyAssistantEngineContext,\n itemId: string,\n input: { locales?: string[]; textLimit?: number },\n): TranslationEntry[] => {\n const translations = buildSurveyTranslations(snapshot);\n const itemTranslations = translations.getItemTranslations(itemId);\n\n if (!itemTranslations) {\n return [];\n }\n\n const localeFilter = input.locales?.length ? new Set(input.locales) : undefined;\n const textLimit = input.textLimit ?? 400;\n const entries: TranslationEntry[] = [];\n\n for (const locale of itemTranslations.locales) {\n if (localeFilter && !localeFilter.has(locale)) {\n continue;\n }\n\n const localeContent = itemTranslations.getAllForLocale(locale);\n if (!localeContent) {\n continue;\n }\n\n for (const [contentKey, content] of Object.entries(localeContent)) {\n const text = getContentPlainText(content as Content).trim();\n if (!text) {\n continue;\n }\n\n entries.push({\n locale,\n contentKey,\n text: text.length > textLimit ? `${text.slice(0, textLimit)}...` : text,\n });\n }\n }\n\n return entries;\n};\n\nexport const summarizeOutlineNode = (node: SurveyOutlineNode): ItemSummary => ({\n itemId: node.itemId,\n itemType: node.itemType,\n key: node.key,\n fullKey: node.fullKey,\n itemLabel: node.itemLabel,\n parentId: node.parentId,\n depth: node.depth,\n childCount: node.childCount,\n});\n\nexport const summarizeKeyIndexEntry = (\n entry: SurveyKeyIndexEntry,\n outlineById: Map<string, SurveyOutlineNode>,\n): ItemSummary => {\n const outlineNode = outlineById.get(entry.itemId);\n\n return {\n itemId: entry.itemId,\n itemType: entry.itemType,\n key: entry.key,\n fullKey: entry.fullKey,\n itemLabel: entry.itemLabel,\n parentId: outlineNode?.parentId,\n depth: outlineNode?.depth,\n childCount: outlineNode?.childCount,\n path: entry.path,\n };\n};\n\nconst getParentFullKey = (fullKey: string): string | undefined => {\n const segments = fullKey.split(\".\");\n if (segments.length <= 1) {\n return undefined;\n }\n\n return segments.slice(0, -1).join(\".\");\n};\n\nexport const summarizeKeyIndexEntries = (\n entries: SurveyKeyIndexEntry[],\n outlineById: Map<string, SurveyOutlineNode>,\n): ItemSummary[] => {\n const byFullKey = new Map(entries.map((entry) => [entry.fullKey, entry]));\n const childCountByFullKey = new Map<string, number>();\n\n for (const entry of entries) {\n const parentFullKey = getParentFullKey(entry.fullKey);\n if (!parentFullKey) {\n continue;\n }\n\n childCountByFullKey.set(parentFullKey, (childCountByFullKey.get(parentFullKey) ?? 0) + 1);\n }\n\n return entries.map((entry) => {\n const outlineNode = outlineById.get(entry.itemId);\n const parentFullKey = getParentFullKey(entry.fullKey);\n const parentEntry = parentFullKey ? byFullKey.get(parentFullKey) : undefined;\n\n return {\n itemId: entry.itemId,\n itemType: entry.itemType,\n key: entry.key,\n fullKey: entry.fullKey,\n itemLabel: entry.itemLabel,\n parentId: outlineNode?.parentId ?? parentEntry?.itemId,\n depth: outlineNode?.depth ?? Math.max(0, entry.fullKey.split(\".\").length - 1),\n childCount: outlineNode?.childCount ?? childCountByFullKey.get(entry.fullKey) ?? 0,\n path: entry.path,\n };\n });\n};\n\nconst buildChoiceConfigDetails = (rawItem: RawSurveyItem): ItemConfigDetails | undefined => {\n const config = isRecord(rawItem.config) ? rawItem.config : undefined;\n const rawOptions = asArray(config?.options);\n const mainResponseSlotId = asString(config?.id) ?? rawItem.id;\n\n if (rawItem.itemType !== \"choiceItem\" && rawOptions.length === 0) {\n return undefined;\n }\n\n const choiceOptions: ChoiceOptionDetails[] = rawOptions\n .map((option, index): ChoiceOptionDetails | undefined => {\n if (!isRecord(option)) {\n return undefined;\n }\n const id = asString(option.id);\n if (!id) {\n return undefined;\n }\n\n const embeddedForm = isRecord(option.embeddedForm) ? option.embeddedForm : undefined;\n const embeddedFormFieldGroups = asArray(embeddedForm?.fieldGroups);\n const details: ChoiceOptionDetails = {\n position: index + 1,\n id,\n labelContentKey: getChoiceOptionLabelContentKey(id),\n };\n\n const key = asString(option.key);\n if (key) {\n details.key = key;\n }\n\n const hasDisplayCondition = asBoolean(option.hasDisplayCondition);\n if (hasDisplayCondition !== undefined) {\n details.hasDisplayCondition = hasDisplayCondition;\n }\n\n const embeddedFormItemId = asString(option.embeddedFormItemId);\n if (embeddedFormItemId) {\n details.embeddedFormItemId = embeddedFormItemId;\n }\n\n if (embeddedFormFieldGroups.length > 0) {\n details.embeddedFormFieldGroupCount = embeddedFormFieldGroups.length;\n details.embeddedFormAuthoringMode = getFormAuthoringMode(embeddedForm);\n details.embeddedFormSimpleModeValid = isValidSimpleFormConfig(embeddedForm);\n details.embeddedFormTranslationPrefix = getChoiceEmbeddedFormTranslationPrefix(id);\n details.embeddedFormResponseSlotPrefix = getChoiceEmbeddedFormResponseSlotPrefix(id);\n }\n\n return details;\n })\n .filter((option): option is ChoiceOptionDetails => Boolean(option));\n\n const maxSelection =\n config?.maxSelection === null\n ? \"unlimited\"\n : typeof config?.maxSelection === \"number\"\n ? String(config.maxSelection)\n : \"default\";\n const summary = [\n `choice item config: ${choiceOptions.length} option(s)`,\n `maxSelection=${maxSelection}`,\n `shuffleOptions=${config?.shuffleOptions === true ? \"true\" : \"false\"}`,\n `responseSlot=${mainResponseSlotId}`,\n ];\n\n return {\n kind: \"choice\",\n summary,\n mainResponseSlotId,\n choiceOptions,\n listOrdering: {\n choiceOptions:\n config?.shuffleOptions === true\n ? \"Stored configured order; positions are one-based. Respondents see a shuffled order, so this is not a stable respondent-visible order.\"\n : \"Stored configured order; positions are one-based and match respondent-visible order.\",\n },\n };\n};\n\nconst buildFormFieldDetails = (\n field: Record<string, unknown>,\n position: number,\n translationNamespace?: string,\n responseSlotPrefix?: string,\n): FormFieldDetails | undefined => {\n const id = asString(field.id);\n const key = asString(field.key);\n const type = asString(field.type);\n\n if (!id || !key || !type) {\n return undefined;\n }\n\n const controller = isRecord(field.controller) ? field.controller : undefined;\n const controllerType = asString(controller?.type);\n const validations = asArray(field.validations).filter(isRecord);\n const validationMessageContentKeys = validations\n .map((validation) => asString(validation.id))\n .filter((validationId): validationId is string => Boolean(validationId))\n .map((validationId) =>\n getFormFieldContentKey(\n id,\n createContentKey(\"validations\", validationId, \"message\"),\n translationNamespace,\n ),\n );\n const selectOptions =\n controllerType === \"select\"\n ? asArray(controller?.options)\n .map((option, index): z.infer<typeof formSelectOptionDetailsSchema> | undefined => {\n if (!isRecord(option)) {\n return undefined;\n }\n const optionId = asString(option.id);\n if (!optionId) {\n return undefined;\n }\n\n const details: z.infer<typeof formSelectOptionDetailsSchema> = {\n position: index + 1,\n id: optionId,\n labelContentKey: getFormFieldOptionLabelContentKey(\n id,\n optionId,\n translationNamespace,\n ),\n };\n\n const value = asString(option.value);\n if (value) {\n details.value = value;\n }\n\n return details;\n })\n .filter((option): option is z.infer<typeof formSelectOptionDetailsSchema> =>\n Boolean(option),\n )\n : undefined;\n\n return {\n position,\n id,\n key,\n type,\n responseSlotId: getFormFieldResponseSlotId(key, responseSlotPrefix),\n labelContentKey: getFormFieldContentKey(id, \"label\", translationNamespace),\n descriptionContentKey: getFormFieldContentKey(id, \"description\", translationNamespace),\n errorContentKey: getFormFieldContentKey(id, \"error\", translationNamespace),\n placeholderContentKey:\n type === \"input\" ||\n type === \"textarea\" ||\n type === \"number\" ||\n type === \"datepicker\" ||\n type === \"select\"\n ? getFormFieldContentKey(id, \"placeholder\", translationNamespace)\n : undefined,\n unitContentKey:\n type === \"number\" ? getFormFieldContentKey(id, \"unit\", translationNamespace) : undefined,\n checkedLabelContentKey:\n type === \"switch\"\n ? getFormFieldContentKey(id, \"checkedLabel\", translationNamespace)\n : undefined,\n uncheckedLabelContentKey:\n type === \"switch\"\n ? getFormFieldContentKey(id, \"uncheckedLabel\", translationNamespace)\n : undefined,\n required: asBoolean(field.required),\n controllerType,\n validationTypes: validations\n .map((validation) => asString(validation.type))\n .filter((type): type is string => Boolean(type)),\n validationMessageContentKeys:\n validationMessageContentKeys.length > 0 ? validationMessageContentKeys : undefined,\n selectOptions,\n };\n};\n\nconst buildFormConfigDetails = (\n rawItem: RawSurveyItem,\n configOverride?: unknown,\n translationNamespace?: string,\n responseSlotPrefix?: string,\n): ItemConfigDetails | undefined => {\n const configCandidate = configOverride ?? rawItem.config;\n const config = isRecord(configCandidate) ? configCandidate : undefined;\n const rawGroups = asArray(config?.fieldGroups);\n\n if (rawItem.itemType !== \"formItem\" && rawGroups.length === 0) {\n return undefined;\n }\n\n const formFieldGroups: FormFieldGroupDetails[] = rawGroups\n .map((group, groupIndex): FormFieldGroupDetails | undefined => {\n if (!isRecord(group)) {\n return undefined;\n }\n const id = asString(group.id);\n if (!id) {\n return undefined;\n }\n\n const fields = asArray(group.fields)\n .map((field, fieldIndex) =>\n isRecord(field)\n ? buildFormFieldDetails(field, fieldIndex + 1, translationNamespace, responseSlotPrefix)\n : undefined,\n )\n .filter((field): field is FormFieldDetails => Boolean(field));\n\n const layout = isRecord(group.layout) ? group.layout : undefined;\n\n return {\n position: groupIndex + 1,\n id,\n titleContentKey: getFormFieldGroupContentKey(id, \"title\", translationNamespace),\n descriptionContentKey: getFormFieldGroupContentKey(id, \"description\", translationNamespace),\n hasDisplayCondition: asBoolean(group.hasDisplayCondition),\n layout: {\n base: getRoundedPositiveInt(layout?.base ?? layout?.xs ?? layout?.sm),\n xs: getRoundedPositiveInt(layout?.xs ?? layout?.sm),\n sm: getRoundedPositiveInt(layout?.sm),\n md: getRoundedPositiveInt(layout?.md ?? layout?.lg),\n xl: getRoundedPositiveInt(layout?.xl ?? layout?.lg),\n },\n fieldCount: fields.length,\n fields,\n };\n })\n .filter((group): group is FormFieldGroupDetails => Boolean(group));\n\n const fieldCount = formFieldGroups.reduce((sum, group) => sum + group.fieldCount, 0);\n const authoringMode = getFormAuthoringMode(config);\n const simpleModeValid = isValidSimpleFormConfig(config);\n\n return {\n kind: \"form\",\n summary: [\n `form item config: authoringMode=${authoringMode}, ${formFieldGroups.length} group(s), ${fieldCount} field(s)${simpleModeValid ? \"\" : \"; malformed simple mode should be treated as custom\"}`,\n ],\n authoringMode,\n simpleModeValid,\n formFieldGroups,\n listOrdering: {\n formFieldGroups: \"Stored configured order; positions are one-based.\",\n \"formFieldGroups[].fields\":\n \"Stored configured order within each field group; positions are one-based.\",\n \"formFieldGroups[].fields[].selectOptions\":\n \"Stored configured order within each select field; positions are one-based.\",\n },\n };\n};\n\nexport const buildItemConfigDetails = (rawItem: RawSurveyItem): ItemConfigDetails | undefined => {\n const choiceDetails = buildChoiceConfigDetails(rawItem);\n if (choiceDetails) {\n return choiceDetails;\n }\n\n const formDetails = buildFormConfigDetails(rawItem);\n if (formDetails) {\n return formDetails;\n }\n\n if (!isRecord(rawItem.config)) {\n return undefined;\n }\n\n const configKeys = Object.keys(rawItem.config);\n return {\n kind: \"generic\",\n summary: [\n configKeys.length > 0\n ? `generic config keys: ${configKeys.join(\", \")}`\n : \"generic config has no enumerable keys\",\n ],\n };\n};\n\nexport const buildEmbeddedFormDetails = (\n choiceOption: ChoiceOptionDetails,\n embeddedForm: unknown,\n): ItemConfigDetails | undefined => {\n if (!isRecord(embeddedForm)) {\n return undefined;\n }\n\n const syntheticRawItem: RawSurveyItem = {\n id: choiceOption.embeddedFormItemId ?? choiceOption.id,\n key: choiceOption.key ?? choiceOption.id,\n itemType: \"formItem\",\n config: embeddedForm,\n };\n\n return buildFormConfigDetails(\n syntheticRawItem,\n embeddedForm,\n getChoiceEmbeddedFormTranslationPrefix(choiceOption.id),\n getChoiceEmbeddedFormResponseSlotPrefix(choiceOption.id),\n );\n};\n\nexport const buildConfigSearchText = (rawItem: RawSurveyItem): string[] => {\n const details = buildItemConfigDetails(rawItem);\n if (!details) {\n return [];\n }\n\n const values = [...details.summary];\n\n for (const option of details.choiceOptions ?? []) {\n values.push(\n option.id,\n option.key ?? \"\",\n option.labelContentKey,\n option.embeddedFormItemId ?? \"\",\n option.embeddedFormTranslationPrefix ?? \"\",\n option.embeddedFormResponseSlotPrefix ?? \"\",\n );\n }\n\n for (const group of details.formFieldGroups ?? []) {\n values.push(\n group.id,\n group.titleContentKey,\n group.descriptionContentKey,\n String(group.layout.base),\n String(group.layout.xs),\n String(group.layout.sm),\n String(group.layout.md),\n String(group.layout.xl),\n group.hasDisplayCondition === true ? \"hasDisplayCondition\" : \"\",\n );\n for (const field of group.fields) {\n values.push(\n field.id,\n field.key,\n field.type,\n field.responseSlotId,\n field.labelContentKey,\n field.descriptionContentKey,\n field.errorContentKey,\n field.placeholderContentKey ?? \"\",\n field.unitContentKey ?? \"\",\n field.checkedLabelContentKey ?? \"\",\n field.uncheckedLabelContentKey ?? \"\",\n field.controllerType ?? \"\",\n ...(field.validationTypes ?? []),\n ...(field.validationMessageContentKeys ?? []),\n );\n for (const option of field.selectOptions ?? []) {\n values.push(option.id, option.value ?? \"\", option.labelContentKey);\n }\n }\n }\n\n return values.filter((value) => value.trim().length > 0);\n};\n\nexport const summarizeFocusItemNode = (\n node: SurveyFocusItemNode,\n outlineById: Map<string, SurveyOutlineNode>,\n): ItemSummary => {\n const outlineNode = outlineById.get(node.itemId);\n\n return {\n itemId: node.itemId,\n itemType: node.itemType,\n key: node.itemKey,\n fullKey: node.fullKey,\n itemLabel: node.itemLabel,\n parentId: outlineNode?.parentId,\n depth: outlineNode?.depth,\n childCount: outlineNode?.childCount ?? node.descendants.length,\n siblingKeys: node.siblingKeys,\n };\n};\n\nexport const summarizeItemById = (\n itemId: string,\n indexById: Map<string, SurveyKeyIndexEntry>,\n outlineById: Map<string, SurveyOutlineNode>,\n): ItemSummary | undefined => {\n const outlineNode = outlineById.get(itemId);\n if (outlineNode) {\n return summarizeOutlineNode(outlineNode);\n }\n\n const indexEntry = indexById.get(itemId);\n if (indexEntry) {\n return summarizeKeyIndexEntry(indexEntry, outlineById);\n }\n\n return undefined;\n};\n\n/**\n * Resolve an item by internal itemId, or fall back to matching on `key` /\n * `fullKey`. Model-facing text (outline rows, fullKey paths) only ever shows\n * key/fullKey, not the internal itemId, so models often pass a key like\n * \"info_1\" where an itemId is expected — this keeps that usage working.\n */\nexport const resolveItemSummary = (\n identifier: string,\n indexById: Map<string, SurveyKeyIndexEntry>,\n outlineById: Map<string, SurveyOutlineNode>,\n): ItemSummary | undefined => {\n const direct = summarizeItemById(identifier, indexById, outlineById);\n if (direct) {\n return direct;\n }\n\n const normalized = identifier.trim().toLowerCase();\n if (!normalized) {\n return undefined;\n }\n\n for (const entry of indexById.values()) {\n if (entry.key.toLowerCase() === normalized || entry.fullKey.toLowerCase() === normalized) {\n return summarizeKeyIndexEntry(entry, outlineById);\n }\n }\n\n for (const node of outlineById.values()) {\n if (node.key.toLowerCase() === normalized || node.fullKey.toLowerCase() === normalized) {\n return summarizeOutlineNode(node);\n }\n }\n\n return undefined;\n};\n\nexport const itemMatchesQuery = (item: ItemSummary, query: string) => {\n const haystack = [\n item.itemId,\n item.itemType,\n item.key,\n item.fullKey,\n item.itemLabel,\n ...(item.path ?? []),\n ...(item.siblingKeys ?? []),\n ]\n .filter(Boolean)\n .join(\" \")\n .toLowerCase();\n\n return haystack.includes(query);\n};\n\n/**\n * Direct children of `parentFullKey` derived from the full-survey key index.\n * This works for any item, selected or not.\n */\nexport const findDirectChildrenByFullKey = (\n entries: SurveyKeyIndexEntry[],\n outlineById: Map<string, SurveyOutlineNode>,\n parentFullKey: string,\n): ItemSummary[] => {\n const prefix = `${parentFullKey}.`;\n return entries\n .filter(\n (entry) =>\n entry.fullKey.startsWith(prefix) && !entry.fullKey.slice(prefix.length).includes(\".\"),\n )\n .map((entry) => summarizeKeyIndexEntry(entry, outlineById));\n};\n","import type { SurveyValidationIssue } from \"../protocol\";\nimport {\n ExpressionType,\n FunctionExpressionNames,\n ValueType,\n type JsonExpression,\n type JsonPatchOperation,\n type JsonValue,\n type RawSurvey,\n type ResponseValue,\n} from \"@case-framework/survey-core\";\nimport type { SurveyAssistantEngineContext as SurveyAssistantSnapshot } from \"./context\";\nimport { z } from \"zod\";\nimport { validateExpression, type ResponseSlotTypeLookup } from \"./expression-validation\";\nimport { getKeyIndexEntries, getRawSurveyItems } from \"./inspection\";\n\nconst jsonValueSchema: z.ZodType<unknown> = z.lazy(() =>\n z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.array(jsonValueSchema),\n z.record(z.string(), jsonValueSchema),\n ]),\n);\n\nconst responseValueSchema: z.ZodType<ResponseValue> = z\n .object({\n type: z.enum([\n ValueType.string,\n ValueType.duration,\n ValueType.reference,\n ValueType.number,\n ValueType.boolean,\n ValueType.date,\n ValueType.stringArray,\n ValueType.durationArray,\n ValueType.referenceArray,\n ValueType.numberArray,\n ValueType.dateArray,\n ]),\n value: jsonValueSchema.optional(),\n unit: z.string().optional(),\n precision: z.string().optional(),\n })\n .passthrough() as z.ZodType<ResponseValue>;\n\nexport const expressionSchema: z.ZodType<JsonExpression> = z.lazy(() =>\n z.discriminatedUnion(\"type\", [\n z.object({\n type: z.literal(ExpressionType.Const),\n value: responseValueSchema.optional(),\n editorConfig: z.record(z.string(), jsonValueSchema).optional(),\n }),\n z.object({\n type: z.literal(ExpressionType.ResponseVariable),\n variableRef: z.string().min(1),\n editorConfig: z.record(z.string(), jsonValueSchema).optional(),\n }),\n z.object({\n type: z.literal(ExpressionType.ContextVariable),\n contextType: z.enum([\"locale\", \"participantFlag\", \"customValue\", \"customExpression\"]),\n key: expressionSchema.optional(),\n arguments: z.array(expressionSchema.optional()).optional(),\n asType: z\n .enum([\n ValueType.string,\n ValueType.duration,\n ValueType.reference,\n ValueType.number,\n ValueType.boolean,\n ValueType.date,\n ValueType.stringArray,\n ValueType.durationArray,\n ValueType.referenceArray,\n ValueType.numberArray,\n ValueType.dateArray,\n ])\n .optional(),\n editorConfig: z.record(z.string(), jsonValueSchema).optional(),\n }),\n z.object({\n type: z.literal(ExpressionType.Function),\n functionName: z.nativeEnum(FunctionExpressionNames),\n arguments: z.array(expressionSchema.optional()),\n editorConfig: z.record(z.string(), jsonValueSchema).optional(),\n }),\n ]),\n) as z.ZodType<JsonExpression>;\n\nconst prefillTargetSchema = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"itemResponse\") }),\n z.object({ type: z.literal(\"field\"), fieldId: z.string().min(1).max(240) }),\n z.object({\n type: z.literal(\"embeddedField\"),\n optionId: z.string().min(1).max(240),\n fieldId: z.string().min(1).max(240),\n }),\n]);\n\nconst prefillSourceSchema = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"static\"), value: responseValueSchema }),\n z.object({ type: z.literal(\"expression\"), expression: expressionSchema }),\n z.object({ type: z.literal(\"templateValue\"), key: z.string().min(1).max(240) }),\n z.object({\n type: z.literal(\"previousResponse\"),\n ref: z.object({\n surveyKey: z.string().min(1).max(240).optional(),\n itemId: z.string().min(1).max(240),\n target: prefillTargetSchema.optional(),\n }),\n ifUnsupported: z.literal(\"skip\").optional(),\n }),\n]);\n\nconst prefillSchema = z.object({\n id: z.string().min(1).max(240),\n target: prefillTargetSchema,\n when: expressionSchema.optional(),\n apply: z.literal(\"ifEmpty\").optional(),\n source: prefillSourceSchema,\n});\n\nconst valueTypeSchema = z.enum([\n ValueType.string,\n ValueType.duration,\n ValueType.reference,\n ValueType.number,\n ValueType.boolean,\n ValueType.date,\n ValueType.stringArray,\n ValueType.durationArray,\n ValueType.referenceArray,\n ValueType.numberArray,\n ValueType.dateArray,\n]);\n\nconst templateValueSchema = z.object({\n type: z.enum([\"default\", \"date2string\"]),\n returnType: valueTypeSchema,\n expression: expressionSchema.optional(),\n dateFormat: z.string().min(1).max(120).optional(),\n});\n\nexport const expressionMutationSchema = z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"set-item-display-condition\"),\n itemId: z.string().min(1).max(240),\n expression: expressionSchema,\n }),\n z.object({\n kind: z.literal(\"clear-item-display-condition\"),\n itemId: z.string().min(1).max(240),\n }),\n z.object({\n kind: z.literal(\"set-component-display-condition\"),\n itemId: z.string().min(1).max(240),\n componentId: z.string().min(1).max(240),\n expression: expressionSchema,\n }),\n z.object({\n kind: z.literal(\"clear-component-display-condition\"),\n itemId: z.string().min(1).max(240),\n componentId: z.string().min(1).max(240),\n }),\n z.object({\n kind: z.literal(\"set-component-disabled-condition\"),\n itemId: z.string().min(1).max(240),\n componentId: z.string().min(1).max(240),\n expression: expressionSchema,\n }),\n z.object({\n kind: z.literal(\"clear-component-disabled-condition\"),\n itemId: z.string().min(1).max(240),\n componentId: z.string().min(1).max(240),\n }),\n z.object({\n kind: z.literal(\"set-validation-expression\"),\n itemId: z.string().min(1).max(240),\n validationKey: z.string().min(1).max(240),\n expression: expressionSchema,\n }),\n z.object({\n kind: z.literal(\"clear-validation-expression\"),\n itemId: z.string().min(1).max(240),\n validationKey: z.string().min(1).max(240),\n }),\n z.object({\n kind: z.literal(\"set-prefill\"),\n itemId: z.string().min(1).max(240),\n prefill: prefillSchema,\n }),\n z.object({\n kind: z.literal(\"clear-prefill\"),\n itemId: z.string().min(1).max(240),\n prefillId: z.string().min(1).max(240),\n }),\n z.object({\n kind: z.literal(\"set-template-value\"),\n templateKey: z.string().min(1).max(240),\n templateValue: templateValueSchema,\n }),\n z.object({\n kind: z.literal(\"clear-template-value\"),\n templateKey: z.string().min(1).max(240),\n }),\n]);\n\nexport type ExpressionMutation = z.infer<typeof expressionMutationSchema>;\n\ntype IssueInput = Omit<SurveyValidationIssue, \"severity\"> & {\n severity?: SurveyValidationIssue[\"severity\"];\n};\n\nconst createIssue = ({ severity = \"error\", ...input }: IssueInput): SurveyValidationIssue => ({\n severity,\n ...input,\n});\n\nconst pointerEscape = (segment: string) => segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst getRawSurvey = (snapshot: SurveyAssistantSnapshot): RawSurvey => snapshot.survey as RawSurvey;\n\nconst toJsonValue = (value: unknown): JsonValue => value as JsonValue;\n\nconst buildResponseSlotTypes = (snapshot: SurveyAssistantSnapshot): ResponseSlotTypeLookup =>\n snapshot.responseSlotTypes;\n\nconst resolveItemId = (\n snapshot: SurveyAssistantSnapshot,\n itemRef: string,\n): { itemId?: string; issue?: SurveyValidationIssue } => {\n const rawItems = getRawSurveyItems(snapshot);\n const byId = new Map(rawItems.map((item) => [item.id, item]));\n if (byId.has(itemRef)) {\n return { itemId: itemRef };\n }\n\n const keyIndexMatch = getKeyIndexEntries(snapshot).find(\n (entry) => entry.itemId === itemRef || entry.key === itemRef || entry.fullKey === itemRef,\n );\n if (keyIndexMatch) {\n return { itemId: keyIndexMatch.itemId };\n }\n\n const rawKeyMatch = rawItems.find((item) => item.key === itemRef);\n if (rawKeyMatch) {\n return { itemId: rawKeyMatch.id };\n }\n\n return {\n issue: createIssue({\n code: \"item-not-found\",\n message: `Could not resolve item \"${itemRef}\". Inspect current context or item details first.`,\n itemId: itemRef,\n }),\n };\n};\n\nconst getRawItemLocation = (\n snapshot: SurveyAssistantSnapshot,\n itemRef: string,\n): {\n itemId?: string;\n rawIndex?: number;\n rawItem?: Record<string, unknown>;\n issue?: SurveyValidationIssue;\n} => {\n const resolved = resolveItemId(snapshot, itemRef);\n if (resolved.issue || !resolved.itemId) {\n return { issue: resolved.issue };\n }\n\n const rawItems = getRawSurveyItems(snapshot);\n const rawIndex = rawItems.findIndex((item) => item.id === resolved.itemId);\n if (rawIndex < 0) {\n return {\n issue: createIssue({\n code: \"item-not-found\",\n message: `Item \"${resolved.itemId}\" is not present in raw survey items.`,\n itemId: resolved.itemId,\n }),\n };\n }\n\n return {\n itemId: resolved.itemId,\n rawIndex,\n rawItem: rawItems[rawIndex] as unknown as Record<string, unknown>,\n };\n};\n\nconst addOrReplacePropertyPatch = ({\n patches,\n parentPath,\n parentValue,\n property,\n value,\n}: {\n patches: JsonPatchOperation[];\n parentPath: string;\n parentValue: unknown;\n property: string;\n value: JsonValue;\n}) => {\n const exists =\n isRecord(parentValue) && Object.prototype.hasOwnProperty.call(parentValue, property);\n patches.push({\n op: exists ? \"replace\" : \"add\",\n path: `${parentPath}/${pointerEscape(property)}`,\n value,\n });\n};\n\nconst removePropertyPatch = ({\n issues,\n operationIndex,\n patches,\n parentPath,\n parentValue,\n property,\n scope,\n}: {\n issues: SurveyValidationIssue[];\n operationIndex: number;\n patches: JsonPatchOperation[];\n parentPath: string;\n parentValue: unknown;\n property: string;\n scope: string;\n}) => {\n const exists =\n isRecord(parentValue) && Object.prototype.hasOwnProperty.call(parentValue, property);\n if (!exists) {\n issues.push(\n createIssue({\n severity: \"warning\",\n code: \"expression-location-already-empty\",\n message: `${scope} is already empty.`,\n operationIndex,\n }),\n );\n return;\n }\n\n patches.push({\n op: \"remove\",\n path: `${parentPath}/${pointerEscape(property)}`,\n });\n};\n\nconst addNestedConditionPatch = ({\n branch,\n expression,\n patches,\n rawIndex,\n rawItem,\n componentId,\n}: {\n branch: \"displayConditions\" | \"disabledConditions\";\n expression: JsonExpression;\n patches: JsonPatchOperation[];\n rawIndex: number;\n rawItem: Record<string, unknown>;\n componentId?: string;\n}) => {\n const basePath = `/surveyItems/${rawIndex}/${branch}`;\n const currentBranch = rawItem[branch];\n\n if (branch === \"displayConditions\" && !componentId) {\n if (!isRecord(currentBranch)) {\n patches.push({ op: \"add\", path: basePath, value: toJsonValue({ root: expression }) });\n return;\n }\n addOrReplacePropertyPatch({\n patches,\n parentPath: basePath,\n parentValue: currentBranch,\n property: \"root\",\n value: toJsonValue(expression),\n });\n return;\n }\n\n if (!componentId) {\n return;\n }\n\n if (!isRecord(currentBranch)) {\n patches.push({\n op: \"add\",\n path: basePath,\n value: toJsonValue({ components: { [componentId]: expression } }),\n });\n return;\n }\n\n if (!isRecord(currentBranch.components)) {\n patches.push({\n op: \"add\",\n path: `${basePath}/components`,\n value: toJsonValue({ [componentId]: expression }),\n });\n return;\n }\n\n addOrReplacePropertyPatch({\n patches,\n parentPath: `${basePath}/components`,\n parentValue: currentBranch.components,\n property: componentId,\n value: toJsonValue(expression),\n });\n};\n\nconst removeNestedConditionPatch = ({\n branch,\n componentId,\n issues,\n operationIndex,\n patches,\n rawIndex,\n rawItem,\n scope,\n}: {\n branch: \"displayConditions\" | \"disabledConditions\";\n componentId?: string;\n issues: SurveyValidationIssue[];\n operationIndex: number;\n patches: JsonPatchOperation[];\n rawIndex: number;\n rawItem: Record<string, unknown>;\n scope: string;\n}) => {\n const currentBranch = rawItem[branch];\n const basePath = `/surveyItems/${rawIndex}/${branch}`;\n if (!isRecord(currentBranch)) {\n issues.push(\n createIssue({\n severity: \"warning\",\n code: \"expression-location-already-empty\",\n message: `${scope} is already empty.`,\n operationIndex,\n }),\n );\n return;\n }\n\n if (branch === \"displayConditions\" && !componentId) {\n removePropertyPatch({\n issues,\n operationIndex,\n patches,\n parentPath: basePath,\n parentValue: currentBranch,\n property: \"root\",\n scope,\n });\n return;\n }\n\n removePropertyPatch({\n issues,\n operationIndex,\n patches,\n parentPath: `${basePath}/components`,\n parentValue: currentBranch.components,\n property: componentId ?? \"\",\n scope,\n });\n};\n\nexport const buildExpressionMutationPatches = ({\n mutation,\n operationIndex,\n issues,\n patches,\n responseSlotTypes,\n snapshot,\n}: {\n mutation: ExpressionMutation;\n operationIndex: number;\n issues: SurveyValidationIssue[];\n patches: JsonPatchOperation[];\n responseSlotTypes: ResponseSlotTypeLookup;\n snapshot: SurveyAssistantSnapshot;\n}) => {\n if (mutation.kind === \"set-template-value\" || mutation.kind === \"clear-template-value\") {\n const templateValues = getRawSurvey(snapshot).templateValues;\n const basePath = \"/templateValues\";\n\n if (mutation.kind === \"clear-template-value\") {\n removePropertyPatch({\n issues,\n operationIndex,\n patches,\n parentPath: basePath,\n parentValue: templateValues,\n property: mutation.templateKey,\n scope: `template value ${mutation.templateKey}`,\n });\n return;\n }\n\n if (mutation.templateValue.expression) {\n validateExpression({\n expression: mutation.templateValue.expression,\n expectedReturnType: mutation.templateValue.returnType,\n issues,\n operationIndex,\n responseSlotTypes,\n scope: `template value ${mutation.templateKey}`,\n });\n }\n if (mutation.templateValue.type === \"date2string\" && !mutation.templateValue.dateFormat) {\n issues.push(\n createIssue({\n code: \"missing-date-format\",\n message: `Template value \"${mutation.templateKey}\" uses date2string and needs dateFormat.`,\n operationIndex,\n }),\n );\n }\n\n if (!isRecord(templateValues)) {\n patches.push({\n op: \"add\",\n path: basePath,\n value: toJsonValue({ [mutation.templateKey]: mutation.templateValue }),\n });\n return;\n }\n\n addOrReplacePropertyPatch({\n patches,\n parentPath: basePath,\n parentValue: templateValues,\n property: mutation.templateKey,\n value: toJsonValue(mutation.templateValue),\n });\n return;\n }\n\n const location = getRawItemLocation(snapshot, mutation.itemId);\n if (location.issue || location.rawIndex === undefined || !location.rawItem) {\n issues.push(\n location.issue ?? createIssue({ code: \"item-not-found\", message: \"Item not found.\" }),\n );\n return;\n }\n\n const { rawIndex, rawItem } = location;\n const itemPath = `/surveyItems/${rawIndex}`;\n\n switch (mutation.kind) {\n case \"set-item-display-condition\":\n validateExpression({\n expression: mutation.expression,\n expectedReturnType: ValueType.boolean,\n issues,\n operationIndex,\n responseSlotTypes,\n scope: `display condition for ${location.itemId}`,\n });\n addNestedConditionPatch({\n branch: \"displayConditions\",\n expression: mutation.expression,\n patches,\n rawIndex,\n rawItem,\n });\n break;\n case \"clear-item-display-condition\":\n removeNestedConditionPatch({\n branch: \"displayConditions\",\n issues,\n operationIndex,\n patches,\n rawIndex,\n rawItem,\n scope: `display condition for ${location.itemId}`,\n });\n break;\n case \"set-component-display-condition\":\n validateExpression({\n expression: mutation.expression,\n expectedReturnType: ValueType.boolean,\n issues,\n operationIndex,\n responseSlotTypes,\n scope: `display condition for ${location.itemId}.${mutation.componentId}`,\n });\n addNestedConditionPatch({\n branch: \"displayConditions\",\n componentId: mutation.componentId,\n expression: mutation.expression,\n patches,\n rawIndex,\n rawItem,\n });\n break;\n case \"clear-component-display-condition\":\n removeNestedConditionPatch({\n branch: \"displayConditions\",\n componentId: mutation.componentId,\n issues,\n operationIndex,\n patches,\n rawIndex,\n rawItem,\n scope: `display condition for ${location.itemId}.${mutation.componentId}`,\n });\n break;\n case \"set-component-disabled-condition\":\n validateExpression({\n expression: mutation.expression,\n expectedReturnType: ValueType.boolean,\n issues,\n operationIndex,\n responseSlotTypes,\n scope: `disabled condition for ${location.itemId}.${mutation.componentId}`,\n });\n addNestedConditionPatch({\n branch: \"disabledConditions\",\n componentId: mutation.componentId,\n expression: mutation.expression,\n patches,\n rawIndex,\n rawItem,\n });\n break;\n case \"clear-component-disabled-condition\":\n removeNestedConditionPatch({\n branch: \"disabledConditions\",\n componentId: mutation.componentId,\n issues,\n operationIndex,\n patches,\n rawIndex,\n rawItem,\n scope: `disabled condition for ${location.itemId}.${mutation.componentId}`,\n });\n break;\n case \"set-validation-expression\":\n validateExpression({\n expression: mutation.expression,\n expectedReturnType: ValueType.boolean,\n issues,\n operationIndex,\n responseSlotTypes,\n scope: `validation ${mutation.validationKey} for ${location.itemId}`,\n });\n if (!isRecord(rawItem.validations)) {\n patches.push({\n op: \"add\",\n path: `${itemPath}/validations`,\n value: toJsonValue({ [mutation.validationKey]: mutation.expression }),\n });\n } else {\n addOrReplacePropertyPatch({\n patches,\n parentPath: `${itemPath}/validations`,\n parentValue: rawItem.validations,\n property: mutation.validationKey,\n value: toJsonValue(mutation.expression),\n });\n }\n break;\n case \"clear-validation-expression\":\n removePropertyPatch({\n issues,\n operationIndex,\n patches,\n parentPath: `${itemPath}/validations`,\n parentValue: rawItem.validations,\n property: mutation.validationKey,\n scope: `validation ${mutation.validationKey} for ${location.itemId}`,\n });\n break;\n case \"set-prefill\": {\n validateExpression({\n expression: mutation.prefill.when,\n expectedReturnType: mutation.prefill.when ? ValueType.boolean : undefined,\n issues,\n operationIndex,\n responseSlotTypes,\n scope: `prefill ${mutation.prefill.id} condition for ${location.itemId}`,\n });\n if (mutation.prefill.source.type === \"expression\") {\n validateExpression({\n expression: mutation.prefill.source.expression,\n issues,\n operationIndex,\n responseSlotTypes,\n scope: `prefill ${mutation.prefill.id} source expression for ${location.itemId}`,\n });\n }\n const prefills = Array.isArray(rawItem.prefills) ? rawItem.prefills : undefined;\n const existingIndex = prefills?.findIndex(\n (prefill) => isRecord(prefill) && prefill.id === mutation.prefill.id,\n );\n if (!prefills) {\n patches.push({\n op: \"add\",\n path: `${itemPath}/prefills`,\n value: toJsonValue([mutation.prefill]),\n });\n } else if (existingIndex !== undefined && existingIndex >= 0) {\n patches.push({\n op: \"replace\",\n path: `${itemPath}/prefills/${existingIndex}`,\n value: toJsonValue(mutation.prefill),\n });\n } else {\n patches.push({\n op: \"add\",\n path: `${itemPath}/prefills/-`,\n value: toJsonValue(mutation.prefill),\n });\n }\n break;\n }\n case \"clear-prefill\": {\n const prefills = Array.isArray(rawItem.prefills) ? rawItem.prefills : [];\n const existingIndex = prefills.findIndex(\n (prefill) => isRecord(prefill) && prefill.id === mutation.prefillId,\n );\n if (existingIndex < 0) {\n issues.push(\n createIssue({\n severity: \"warning\",\n code: \"expression-location-already-empty\",\n message: `Prefill \"${mutation.prefillId}\" is not present on ${location.itemId}.`,\n operationIndex,\n }),\n );\n return;\n }\n patches.push({ op: \"remove\", path: `${itemPath}/prefills/${existingIndex}` });\n break;\n }\n }\n};\n","import { ContentType } from \"@case-framework/survey-core\";\n\ntype LooseRecord = Record<string, unknown>;\ntype LooseTranslation = {\n locale: string;\n contentKey: string;\n plainText?: string;\n content?: unknown;\n};\n\ntype RichTextStyle = {\n weight?: \"strong\" | \"normal\";\n italic?: \"italic\" | \"normal\";\n underline?: \"underline\" | \"none\";\n color?: \"primary\" | \"accent\" | \"default\";\n};\ntype RichTextTextInline = { type: \"text\"; text: string; style?: RichTextStyle };\ntype RichTextLineBreakInline = { type: \"lineBreak\" };\ntype RichTextLinkInline = {\n type: \"link\";\n href: string;\n children: Array<RichTextTextInline | RichTextLineBreakInline>;\n};\ntype RichTextInline = RichTextTextInline | RichTextLineBreakInline | RichTextLinkInline;\ntype RichTextParagraphBlock = { type: \"paragraph\"; children: RichTextInline[] };\ntype RichTextBlock =\n | RichTextParagraphBlock\n | { type: \"heading\"; level: number; children: RichTextInline[] }\n | { type: \"bulletList\"; items: Array<{ type: \"listItem\"; children: RichTextParagraphBlock[] }> }\n | {\n type: \"infoBox\";\n tone: \"info\" | \"warning\";\n title?: RichTextInline[];\n collapsible: boolean;\n defaultOpen: boolean;\n children: RichTextParagraphBlock[];\n }\n | { type: \"separator\" };\n\nconst isRecord = (value: unknown): value is LooseRecord =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst getString = (value: unknown) => (typeof value === \"string\" ? value.trim() : undefined);\n\nconst normalizeChoiceMaxSelection = (config: LooseRecord) => {\n if (config.maxSelection === null) {\n return null;\n }\n\n if (typeof config.maxSelection === \"number\") {\n return config.maxSelection;\n }\n\n if (typeof config.maxSelection === \"string\") {\n const normalized = config.maxSelection.trim().toLowerCase();\n if (\n normalized === \"multiple\" ||\n normalized === \"multi\" ||\n normalized === \"unlimited\" ||\n normalized === \"none\"\n ) {\n return null;\n }\n\n if (/^[1-9]\\d*$/.test(normalized)) {\n return Number.parseInt(normalized, 10);\n }\n\n return config.maxSelection;\n }\n\n const mode =\n getString(config.mode)?.toLowerCase() ??\n getString(config.selectionType)?.toLowerCase() ??\n getString(config.selectionMode)?.toLowerCase();\n if (\n mode === \"multiple\" ||\n mode === \"multi\" ||\n mode === \"multi-select\" ||\n mode === \"multiselect\" ||\n mode === \"checkbox\" ||\n mode === \"checkboxes\"\n ) {\n return null;\n }\n\n return 1;\n};\n\nconst normalizeLayout = (value: unknown) => {\n const baseLayout = { base: 1, xs: 1, sm: 1, md: 1, xl: 1 };\n if (!isRecord(value)) {\n return baseLayout;\n }\n\n const normalized: Record<keyof typeof baseLayout, unknown> = { ...baseLayout };\n for (const key of Object.keys(normalized) as Array<keyof typeof normalized>) {\n if (value[key] !== undefined) {\n normalized[key] = value[key];\n }\n }\n return normalized;\n};\n\nconst normalizeKey = (value: string) =>\n value\n .trim()\n .replace(/[.\\s]+/g, \"_\")\n .replace(/[^A-Za-z0-9_-]+/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\nconst textInline = (text: string, style?: RichTextStyle): RichTextTextInline => ({\n type: \"text\",\n text,\n ...(style ? { style } : {}),\n});\n\nconst paragraphBlock = (text: string, style?: RichTextStyle): RichTextParagraphBlock => ({\n type: \"paragraph\",\n children: [textInline(text, style)],\n});\n\nconst getBlockText = (block: LooseRecord) =>\n getString(block.text) ?? getString(block.content) ?? getString(block.label);\n\nconst normalizeAssistantHeadingLevel = (level: number) =>\n Math.min(2, Math.max(1, Math.round(level)));\n\nconst normalizeRichTextStyle = (value: LooseRecord): RichTextStyle | undefined => {\n const rawStyle = isRecord(value.style) ? value.style : {};\n const style: RichTextStyle = {};\n const weight = rawStyle.weight ?? value.weight;\n const italic = rawStyle.italic ?? value.italic;\n const underline = rawStyle.underline ?? value.underline;\n const color = rawStyle.color ?? value.color;\n\n if (value.strong === true || value.bold === true || weight === \"strong\" || weight === \"bold\") {\n style.weight = \"strong\";\n } else if (weight === \"normal\") {\n style.weight = \"normal\";\n }\n\n if (value.italic === true || italic === \"italic\") {\n style.italic = \"italic\";\n } else if (italic === \"normal\") {\n style.italic = \"normal\";\n }\n\n if (value.underline === true || underline === \"underline\") {\n style.underline = \"underline\";\n } else if (underline === \"none\") {\n style.underline = \"none\";\n }\n\n if (color === \"primary\" || color === \"accent\" || color === \"default\") {\n style.color = color;\n }\n\n return Object.keys(style).length > 0 ? style : undefined;\n};\n\nconst normalizeRichTextInline = (\n value: unknown,\n allowLink = true,\n): RichTextTextInline | RichTextLineBreakInline | RichTextLinkInline | undefined => {\n if (typeof value === \"string\") {\n return textInline(value);\n }\n\n if (!isRecord(value)) {\n return undefined;\n }\n\n const type = getString(value.type)?.toLowerCase();\n if (type === \"linebreak\" || type === \"line-break\" || type === \"break\") {\n return { type: \"lineBreak\" };\n }\n\n if (type === \"link\" && allowLink) {\n const href = getString(value.href) ?? getString(value.url);\n if (!href) {\n return undefined;\n }\n\n const childValues = Array.isArray(value.children)\n ? value.children\n : [getString(value.text) ?? getString(value.label) ?? href];\n const children = childValues\n .map((child) => normalizeRichTextInline(child, false))\n .filter(\n (child): child is RichTextTextInline | RichTextLineBreakInline =>\n child !== undefined && child.type !== \"link\",\n );\n\n return { type: \"link\", href, children };\n }\n\n const text = getBlockText(value);\n return text === undefined ? undefined : textInline(text, normalizeRichTextStyle(value));\n};\n\nconst normalizeRichTextChildren = (value: LooseRecord) => {\n if (!Array.isArray(value.children)) {\n return undefined;\n }\n\n const children = value.children\n .map((child) => normalizeRichTextInline(child))\n .filter((child): child is RichTextInline => Boolean(child));\n return children.length > 0 ? children : undefined;\n};\n\nconst normalizeRichTextBlock = (value: unknown): RichTextBlock | undefined => {\n if (typeof value === \"string\") {\n return paragraphBlock(value);\n }\n\n if (!isRecord(value)) {\n return undefined;\n }\n\n const type = getString(value.type)?.toLowerCase();\n const text = getBlockText(value);\n const style = normalizeRichTextStyle(value);\n const children = normalizeRichTextChildren(value);\n\n if (type === \"heading\" || /^h[1-6]$/.test(type ?? \"\")) {\n const rawLevel = typeof value.level === \"number\" ? value.level : type === \"h1\" ? 1 : 2;\n return {\n type: \"heading\",\n level: normalizeAssistantHeadingLevel(rawLevel),\n children: children ?? [textInline(text ?? \"\", style)],\n };\n }\n\n if (type === \"bulletlist\" || type === \"bullet-list\" || type === \"list\" || type === \"bullets\") {\n const items = Array.isArray(value.items) ? value.items : [];\n return {\n type: \"bulletList\",\n items: items\n .map((item) => {\n const itemText =\n typeof item === \"string\" ? item : isRecord(item) ? getBlockText(item) : undefined;\n return itemText\n ? { type: \"listItem\" as const, children: [paragraphBlock(itemText)] }\n : undefined;\n })\n .filter((item): item is { type: \"listItem\"; children: RichTextParagraphBlock[] } =>\n Boolean(item),\n ),\n };\n }\n\n if (type === \"infobox\" || type === \"info-box\" || type === \"note\" || type === \"footnote\") {\n return {\n type: \"infoBox\",\n tone: value.tone === \"warning\" ? \"warning\" : \"info\",\n title: getString(value.title) ? [textInline(getString(value.title) ?? \"\")] : undefined,\n collapsible: value.collapsible === true,\n defaultOpen: value.defaultOpen !== false,\n children: [paragraphBlock(text ?? \"\")],\n };\n }\n\n if (type === \"separator\" || type === \"divider\" || type === \"rule\") {\n return { type: \"separator\" };\n }\n\n if (type === \"paragraph\" || text) {\n return children ? { type: \"paragraph\", children } : paragraphBlock(text ?? \"\", style);\n }\n\n return undefined;\n};\n\nconst normalizeRichTextContent = (value: unknown): unknown => {\n if (!isRecord(value)) {\n return value;\n }\n\n if (value.type === ContentType.richText && isRecord(value.doc) && value.version === 1) {\n return value;\n }\n\n const candidateBlocks = Array.isArray(value.richTextBlocks)\n ? value.richTextBlocks\n : Array.isArray(value.blocks)\n ? value.blocks\n : undefined;\n if (!candidateBlocks) {\n return value;\n }\n\n const blocks = candidateBlocks\n .map(normalizeRichTextBlock)\n .filter((block): block is RichTextBlock => Boolean(block));\n\n return {\n type: ContentType.richText,\n version: 1,\n doc: {\n type: \"doc\",\n blocks,\n },\n };\n};\n\nconst normalizeLooseTranslationRecord = (value: LooseRecord): LooseTranslation | undefined => {\n const locale = getString(value.locale);\n const contentKey = getString(value.contentKey);\n if (!locale || !contentKey) {\n return undefined;\n }\n\n const content = normalizeRichTextContent(\n value.content ??\n (Array.isArray(value.blocks) || Array.isArray(value.richTextBlocks) ? value : undefined),\n );\n const plainText = typeof value.plainText === \"string\" ? value.plainText : undefined;\n\n if (isRecord(content) && content.type) {\n return { locale, contentKey, content };\n }\n\n if (plainText !== undefined) {\n return { locale, contentKey, plainText };\n }\n\n const shorthandText = getString(value.text) ?? getString(value.label);\n return shorthandText ? { locale, contentKey, plainText: shorthandText } : undefined;\n};\n\nconst toTranslation = (\n locale: string,\n contentKey: string,\n value: unknown,\n): LooseTranslation | undefined => {\n if (typeof value === \"string\") {\n return { locale, contentKey, plainText: value };\n }\n\n if (!isRecord(value)) {\n return undefined;\n }\n\n const normalizedContent = normalizeRichTextContent(value);\n if (\n isRecord(normalizedContent) &&\n normalizedContent.type === ContentType.richText &&\n isRecord(normalizedContent.doc) &&\n normalizedContent.version === 1\n ) {\n return { locale, contentKey, content: normalizedContent };\n }\n\n if (\n (value.type === ContentType.md || value.type === ContentType.plain) &&\n typeof value.content === \"string\"\n ) {\n return { locale, contentKey, content: value };\n }\n\n if (value.type === ContentType.richText && isRecord(value.doc) && value.version === 1) {\n return { locale, contentKey, content: value };\n }\n\n const shorthandText = getString(value.text) ?? getString(value.content) ?? getString(value.label);\n return shorthandText ? { locale, contentKey, plainText: shorthandText } : undefined;\n};\n\nconst upsertLooseTranslation = (\n translations: LooseTranslation[],\n next: LooseTranslation | undefined,\n) => {\n if (!next) return;\n\n const existingIndex = translations.findIndex(\n (translation) =>\n translation.locale === next.locale && translation.contentKey === next.contentKey,\n );\n if (existingIndex >= 0) {\n translations[existingIndex] = next;\n return;\n }\n\n translations.push(next);\n};\n\nconst flattenLooseItemTranslations = (value: unknown): LooseTranslation[] => {\n if (Array.isArray(value)) {\n return value\n .filter(isRecord)\n .map(normalizeLooseTranslationRecord)\n .filter((translation): translation is LooseTranslation => Boolean(translation));\n }\n\n if (!isRecord(value)) {\n return [];\n }\n\n const translations: LooseTranslation[] = [];\n\n for (const [locale, localeValue] of Object.entries(value)) {\n if (!isRecord(localeValue)) continue;\n\n const appendContentMap = (contentMap: LooseRecord) => {\n for (const [contentKey, contentValue] of Object.entries(contentMap)) {\n if (contentKey === \"options\" && isRecord(contentValue)) {\n for (const [optionId, optionLabel] of Object.entries(contentValue)) {\n upsertLooseTranslation(\n translations,\n toTranslation(locale, `options.${optionId}.label`, optionLabel),\n );\n }\n continue;\n }\n\n if (contentKey === \"fieldGroups\" && Array.isArray(contentValue)) {\n for (const group of contentValue) {\n if (!isRecord(group)) continue;\n const groupId = getString(group.id) ?? getString(group.groupId);\n if (!groupId) continue;\n upsertLooseTranslation(\n translations,\n toTranslation(locale, `fieldGroups.${groupId}.title`, group.title),\n );\n upsertLooseTranslation(\n translations,\n toTranslation(locale, `fieldGroups.${groupId}.description`, group.description),\n );\n }\n continue;\n }\n\n upsertLooseTranslation(translations, toTranslation(locale, contentKey, contentValue));\n }\n };\n\n if (isRecord(localeValue.itemTranslations)) {\n for (const itemTranslation of Object.values(localeValue.itemTranslations)) {\n if (isRecord(itemTranslation)) {\n appendContentMap(itemTranslation);\n }\n }\n continue;\n }\n\n appendContentMap(localeValue);\n }\n\n return translations;\n};\n\nconst appendParenthetical = (text: string, note: string | undefined) => {\n if (!note) {\n return text;\n }\n\n if (text.toLowerCase().includes(note.toLowerCase())) {\n return text;\n }\n\n return `${text} (${note})`;\n};\n\nconst appendMarker = (text: string, marker: string | undefined) => {\n if (!marker || text.endsWith(marker)) {\n return text;\n }\n\n return `${text}${marker}`;\n};\n\nconst getOptionNote = (option: LooseRecord): string | undefined =>\n getString(option.note) ??\n getString(option.description) ??\n getString(option.helpText) ??\n getString(option.instruction);\n\nconst getFootnoteMarker = (option: LooseRecord): string | undefined =>\n getString(option.footnoteMarker) ?? getString(option.marker);\n\nconst getOptionTranslationLabel = (option: LooseRecord): string | undefined => {\n const directLabel = getString(option.label) ?? getString(option.text) ?? getString(option.title);\n if (directLabel) {\n return appendMarker(\n appendParenthetical(directLabel, getOptionNote(option)),\n getFootnoteMarker(option),\n );\n }\n\n if (!isRecord(option.translations)) {\n return undefined;\n }\n\n for (const localeValue of Object.values(option.translations)) {\n if (!isRecord(localeValue)) continue;\n const translatedLabel = getString(localeValue.label) ?? getString(localeValue.text);\n if (translatedLabel) {\n const translatedNote =\n getString(localeValue.note) ??\n getString(localeValue.description) ??\n getString(localeValue.helpText) ??\n getString(localeValue.instruction);\n const translatedMarker =\n getString(localeValue.footnoteMarker) ?? getString(localeValue.marker);\n return appendMarker(appendParenthetical(translatedLabel, translatedNote), translatedMarker);\n }\n }\n\n return undefined;\n};\n\nconst getSelectOptionTranslationLabel = (option: LooseRecord): string | undefined =>\n getString(option.label) ??\n getString(option.text) ??\n getString(option.title) ??\n getString(option.name);\n\nconst normalizeSelectControllerOptions = ({\n controller,\n fieldId,\n translations,\n}: {\n controller: LooseRecord;\n fieldId: string;\n translations: Array<{ contentKey: string; plainText: string }>;\n}) => {\n if (controller.type !== \"select\" || !Array.isArray(controller.options)) {\n return controller;\n }\n\n return {\n ...controller,\n options: controller.options.map((option, index) => {\n if (!isRecord(option)) {\n return option;\n }\n\n const optionLabel = getSelectOptionTranslationLabel(option);\n const rawOptionId =\n getString(option.id) ??\n getString(option.optionId) ??\n getString(option.value) ??\n (optionLabel ? normalizeKey(optionLabel) : undefined) ??\n `option_${index + 1}`;\n const optionId = normalizeKey(rawOptionId) || `option_${index + 1}`;\n const value = getString(option.value) ?? optionId;\n\n if (optionLabel) {\n translations.push({\n contentKey: `fields.${fieldId}.options.${optionId}.label`,\n plainText: optionLabel,\n });\n }\n\n return {\n ...option,\n id: optionId,\n value,\n };\n }),\n };\n};\n\nconst appendOptionTranslationLabels = (\n translations: LooseTranslation[],\n option: LooseRecord,\n optionId: string | undefined,\n) => {\n if (!optionId || !isRecord(option.translations)) {\n return;\n }\n\n for (const [locale, localeValue] of Object.entries(option.translations)) {\n if (!isRecord(localeValue)) continue;\n upsertLooseTranslation(\n translations,\n toTranslation(locale, `options.${optionId}.label`, localeValue.label ?? localeValue.text),\n );\n }\n};\n\nconst normalizeLooseField = (\n field: unknown,\n): { field?: LooseRecord; translations: Array<{ contentKey: string; plainText: string }> } => {\n if (!isRecord(field)) {\n return { translations: [] };\n }\n\n const rawId = getString(field.id) ?? getString(field.fieldId) ?? getString(field.key);\n const id = rawId ? normalizeKey(rawId) : undefined;\n if (!id) {\n return { translations: [] };\n }\n\n const rawType = getString(field.type) ?? getString(field.controlType) ?? \"input\";\n const type =\n rawType === \"text\" || rawType === \"email\"\n ? \"input\"\n : rawType === \"date\"\n ? \"datepicker\"\n : rawType === \"checkbox\"\n ? \"switch\"\n : rawType;\n const controller = (() => {\n switch (type) {\n case \"textarea\":\n return { type: \"textarea\", rows: 3 };\n case \"number\":\n return { type: \"number\", step: 1 };\n case \"datepicker\":\n return { type: \"datepicker\", mode: \"year-month-day\" };\n case \"switch\":\n return { type: \"switch\", defaultChecked: false };\n case \"select\":\n return { type: \"select\", options: [] };\n case \"slider\":\n return {\n type: \"slider\",\n min: 0,\n max: 100,\n step: 1,\n defaultValue: 50,\n showValue: true,\n };\n default:\n return { type: \"input\", inputMode: rawType === \"email\" ? \"email\" : \"text\" };\n }\n })();\n\n const translations: Array<{ contentKey: string; plainText: string }> = [];\n const label = getString(field.label);\n if (label) {\n translations.push({ contentKey: `fields.${id}.label`, plainText: label });\n }\n const placeholder = getString(field.placeholder);\n if (placeholder) {\n translations.push({ contentKey: `fields.${id}.placeholder`, plainText: placeholder });\n }\n const description = getString(field.description);\n if (description) {\n translations.push({ contentKey: `fields.${id}.description`, plainText: description });\n }\n const unit = getString(field.unit);\n if (unit) {\n translations.push({ contentKey: `fields.${id}.unit`, plainText: unit });\n }\n\n return {\n field: {\n id,\n key: getString(field.key) ?? id,\n type,\n required: field.required === true,\n controller: normalizeSelectControllerOptions({\n controller: isRecord(field.controller) ? field.controller : controller,\n fieldId: id,\n translations,\n }),\n validations:\n Array.isArray(field.validations) && field.validations.length > 0\n ? field.validations\n : rawType === \"email\"\n ? [{ id: \"email\", type: \"email\" }]\n : [],\n },\n translations,\n };\n};\n\nconst normalizeFormFieldGroupSelectOptions = (\n fieldGroups: unknown,\n): { fieldGroups: unknown; translations: Array<{ contentKey: string; plainText: string }> } => {\n if (!Array.isArray(fieldGroups)) {\n return { fieldGroups, translations: [] };\n }\n\n const translations: Array<{ contentKey: string; plainText: string }> = [];\n const normalizedFieldGroups = fieldGroups.map((group) => {\n if (!isRecord(group) || !Array.isArray(group.fields)) {\n return group;\n }\n\n return {\n ...group,\n fields: group.fields.map((field) => {\n if (!isRecord(field)) {\n return field;\n }\n\n const fieldId = getString(field.id) ?? getString(field.fieldId) ?? getString(field.key);\n const controller = isRecord(field.controller) ? field.controller : undefined;\n if (!fieldId || !controller || controller.type !== \"select\") {\n return field;\n }\n\n return {\n ...field,\n controller: normalizeSelectControllerOptions({\n controller,\n fieldId,\n translations,\n }),\n };\n }),\n };\n });\n\n return { fieldGroups: normalizedFieldGroups, translations };\n};\n\nconst normalizeLooseCreateOperation = (operation: unknown, defaultLocale: string) => {\n if (!isRecord(operation) || !isRecord(operation.item)) {\n return operation;\n }\n\n const operationKind = getString(operation.kind) ?? getString(operation.op);\n if (operationKind !== \"create-item\") {\n return operation;\n }\n\n const item = { ...operation.item };\n const translations = [\n ...flattenLooseItemTranslations(operation.translations),\n ...flattenLooseItemTranslations(item.translations),\n ];\n\n if (!getString(item.id)) {\n const itemId = getString(item.key) ?? getString(item.label);\n if (itemId) {\n item.id = normalizeKey(itemId);\n }\n }\n\n if (!isRecord(item.config) && isRecord(operation.config)) {\n item.config = operation.config;\n }\n\n if (item.itemType === \"choiceItem\") {\n const rawConfig = isRecord(item.config) ? item.config : {};\n const choiceConfig = isRecord(item.choiceConfig) ? item.choiceConfig : {};\n const looseOptions = Array.isArray(item.options) ? item.options : undefined;\n const config: LooseRecord = {\n ...choiceConfig,\n ...rawConfig,\n ...(!Array.isArray(rawConfig.options) && looseOptions ? { options: looseOptions } : {}),\n };\n config.id = getString(config.id) ?? getString(item.id) ?? getString(item.key);\n config.maxSelection = normalizeChoiceMaxSelection(config);\n config.shuffleOptions = config.shuffleOptions === true;\n if (Array.isArray(config.options)) {\n config.options = config.options.map((option) => {\n if (!isRecord(option)) return option;\n const optionLabel = getOptionTranslationLabel(option);\n const optionId =\n getString(option.id) ??\n getString(option.optionId) ??\n getString(option.value) ??\n (optionLabel ? normalizeKey(optionLabel) : undefined);\n appendOptionTranslationLabels(translations, option, optionId);\n return {\n ...option,\n id: optionId,\n key: getString(option.key) ?? getString(option.value) ?? getString(option.optionId),\n label: optionLabel,\n };\n });\n }\n item.config = config;\n delete item.choiceConfig;\n delete item.options;\n }\n\n if (item.itemType === \"formItem\" && isRecord(item.config)) {\n const config = { ...item.config };\n config.id = getString(config.id) ?? getString(item.id) ?? getString(item.key);\n const looseFields = Array.isArray(config.fields) ? config.fields : [];\n const fieldTranslations: Array<{ contentKey: string; plainText: string }> = [];\n const normalizedLooseFields = looseFields\n .map((field) => {\n const normalized = normalizeLooseField(field);\n fieldTranslations.push(...normalized.translations);\n return normalized.field;\n })\n .filter((field): field is LooseRecord => Boolean(field));\n\n if (Array.isArray(config.fieldGroups)) {\n config.fieldGroups = config.fieldGroups.map((group, index) => {\n if (!isRecord(group)) return group;\n return {\n ...group,\n id: getString(group.id) ?? getString(group.groupId) ?? `group_${index + 1}`,\n layout: normalizeLayout(group.layout),\n fields:\n Array.isArray(group.fields) && group.fields.length > 0\n ? group.fields\n : index === 0\n ? normalizedLooseFields\n : [],\n };\n });\n } else if (normalizedLooseFields.length > 0) {\n config.fieldGroups = [\n {\n id: \"main\",\n layout: { base: 1, xs: 1, sm: 1, md: 1, xl: 1 },\n fields: normalizedLooseFields,\n },\n ];\n }\n delete config.fields;\n\n const normalizedSelectOptions = normalizeFormFieldGroupSelectOptions(config.fieldGroups);\n config.fieldGroups = normalizedSelectOptions.fieldGroups;\n fieldTranslations.push(...normalizedSelectOptions.translations);\n\n for (const translation of fieldTranslations) {\n upsertLooseTranslation(translations, {\n locale: defaultLocale,\n contentKey: translation.contentKey,\n plainText: translation.plainText,\n });\n }\n\n item.config = config;\n }\n\n delete item.translations;\n\n return {\n ...operation,\n kind: \"create-item\",\n item,\n ...(translations.length > 0 ? { translations } : {}),\n };\n};\n\n/**\n * Accepts common model-authored shorthand and converts it to the strict\n * assistant operation shape before validation. This keeps the public tool\n * compact while making it tolerant of predictable schema-near authoring\n * mistakes: nested raw translation maps, sibling config objects, choice\n * optionId aliases, and flat form fields.\n */\nexport const normalizeSurveyChangeOperations = (operations: unknown[], defaultLocale: string) =>\n operations.map((operation) => normalizeLooseCreateOperation(operation, defaultLocale));\n","import type {\n SurveyChangeSet,\n SurveyDocumentVersion,\n SurveyOperation,\n SurveyValidationIssue,\n SurveyValidationResult,\n SurveyDocumentSnapshot,\n} from \"../protocol\";\nimport { rawSurveyDocumentSchema, SURVEY_ASSISTANT_PROTOCOL_VERSION } from \"../protocol\";\nimport {\n ContentType,\n JsonPatchError,\n SurveyItemTranslations,\n SurveyTranslations,\n applyJsonPatch,\n generateId,\n getContentPlainText,\n isContentEmpty,\n parseJsonPointer,\n ReservedSurveyItemTypes,\n ValueType,\n structuredCloneMethod,\n type Content,\n type JsonExpression,\n type RawSurvey,\n type RawSurveyItem,\n} from \"@case-framework/survey-core\";\nimport type { SurveyAssistantEngineContext } from \"./context\";\nimport { createSurveyAssistantEngineContext, deriveResponseSlotTypes } from \"./context\";\nimport {\n getRawSurveyItems,\n mapKeyIndexById,\n mapOutlineById,\n mapRawItemsById,\n resolveItemSummary,\n} from \"./inspection\";\nimport { validateExpression, type ResponseSlotTypeLookup } from \"./expression-validation\";\nimport {\n isCompatibleSimpleFieldUpsert,\n normalizeFormAuthoringConfig,\n transitionFormAuthoringMode,\n} from \"./form-authoring\";\n\nconst ITEM_KEY_PATTERN = /^[A-Za-z0-9_-]+$/;\nexport const MAX_SURVEY_ASSISTANT_OPERATIONS_PER_PROPOSAL = 200;\nexport const MAX_SURVEY_ASSISTANT_OPERATIONS_PER_TURN_DRAFT = 1_000;\nconst CHOICE_ITEM_TYPE = \"choiceItem\";\nconst FORM_ITEM_TYPE = \"formItem\";\nconst CHOICE_OPTION_LABEL_CONTENT_KEY_PATTERN = /^options\\.([^.]+)\\.label$/;\nconst MAX_VALIDATION_DIAGNOSTIC_VALUES = 12;\n\nconst formatBoundedDiagnosticValues = (\n values: readonly string[],\n limit = MAX_VALIDATION_DIAGNOSTIC_VALUES,\n) => {\n const shown = values.slice(0, limit);\n const suffix =\n shown.length < values.length\n ? `, … (${shown.length}/${values.length} shown in operation order)`\n : \"\";\n return `${shown.join(\", \")}${suffix}`;\n};\n\ntype IssueInput = Omit<SurveyValidationIssue, \"severity\"> & {\n severity?: SurveyValidationIssue[\"severity\"];\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst getTrimmedString = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n\nconst getFirstStringProperty = (\n record: Record<string, unknown>,\n keys: string[],\n): string | undefined => {\n for (const key of keys) {\n const value = getTrimmedString(record[key]);\n if (value) {\n return value;\n }\n }\n\n return undefined;\n};\n\nconst isContent = (value: unknown): value is Content => {\n if (!isRecord(value)) {\n return false;\n }\n\n if (\n (value.type === ContentType.md || value.type === ContentType.plain) &&\n typeof value.content === \"string\"\n ) {\n return true;\n }\n\n return (\n value.type === ContentType.richText &&\n value.version === 1 &&\n isRecord(value.doc) &&\n value.doc.type === \"doc\" &&\n Array.isArray(value.doc.blocks)\n );\n};\n\nconst cloneContent = (content: Content): Content => structuredCloneMethod(content);\n\nconst getTranslationPlainText = ({\n content,\n plainText,\n}: {\n content?: Content;\n plainText?: string;\n}) => {\n if (content) {\n return getContentPlainText(content).trim();\n }\n\n return (plainText ?? \"\").trim();\n};\n\nconst isTranslationContentEmpty = ({\n content,\n plainText,\n}: {\n content?: Content;\n plainText?: string;\n}) => (content ? isContentEmpty(content) : (plainText ?? \"\").trim().length === 0);\n\nconst getCreateItemNestedTranslations = (\n item: Extract<SurveyOperation, { kind: \"create-item\" }>[\"item\"],\n): NonNullable<Extract<SurveyOperation, { kind: \"create-item\" }>[\"translations\"]> => {\n const rawItem = item as Record<string, unknown>;\n const rawTranslations = rawItem.translations;\n\n if (!Array.isArray(rawTranslations)) {\n return [];\n }\n\n return rawTranslations\n .filter(isRecord)\n .map((translation) => {\n const locale = getTrimmedString(translation.locale);\n const contentKey = getTrimmedString(translation.contentKey);\n const content = isContent(translation.content)\n ? cloneContent(translation.content)\n : undefined;\n const plainText =\n typeof translation.plainText === \"string\" ? translation.plainText : undefined;\n\n if (!locale || !contentKey || (!content && plainText === undefined)) {\n return undefined;\n }\n\n return {\n locale,\n contentKey,\n ...(plainText !== undefined ? { plainText } : {}),\n ...(content ? { content } : {}),\n };\n })\n .filter(\n (\n translation,\n ): translation is NonNullable<\n Extract<SurveyOperation, { kind: \"create-item\" }>[\"translations\"]\n >[number] => Boolean(translation),\n );\n};\n\nconst getGroupChildren = (item: RawSurveyItem | undefined): string[] => {\n const config = isRecord(item?.config) ? item.config : undefined;\n const items = config?.items;\n\n if (!Array.isArray(items)) {\n return [];\n }\n\n return items.filter((entry): entry is string => typeof entry === \"string\");\n};\n\nconst isRootItem = (item: RawSurveyItem | undefined) => {\n const config = isRecord(item?.config) ? item.config : undefined;\n return config?.isRoot === true;\n};\n\nconst isSurveyJsonPatchOperation = (\n operation: SurveyOperation,\n): operation is Extract<SurveyOperation, { kind: \"survey-json-patch\" }> =>\n operation.kind === \"survey-json-patch\";\n\nconst getPatchTouchedPaths = (operation: Extract<SurveyOperation, { kind: \"survey-json-patch\" }>) =>\n operation.patches.flatMap((patch) => (\"from\" in patch ? [patch.path, patch.from] : [patch.path]));\n\nconst touchesSurveySchemaPath = (path: string) => {\n const segments = parseJsonPointer(path);\n return segments[0] === \"$schema\";\n};\n\nconst isTranslationContainerMutation = (patch: { op: string }) => patch.op !== \"test\";\n\nconst validateTranslationPatchSafety = ({\n operation,\n survey,\n}: {\n operation: Extract<SurveyOperation, { kind: \"survey-json-patch\" }>;\n survey: RawSurvey;\n}) => {\n const issues: SurveyValidationIssue[] = [];\n const operationId = getOperationId(operation);\n const translations = survey.translations ?? {};\n\n for (const [patchIndex, patch] of operation.patches.entries()) {\n const paths = patch.op === \"move\" ? [patch.path, patch.from] : [patch.path];\n for (const path of paths) {\n let segments: string[];\n try {\n segments = parseJsonPointer(path);\n } catch {\n continue;\n }\n\n if (segments[0] !== \"translations\" || !isTranslationContainerMutation(patch)) {\n continue;\n }\n\n if (segments.length === 1) {\n issues.push(\n createIssue({\n code: \"unsafe-translation-root-patch\",\n message:\n \"Raw patches cannot replace or remove the complete translations map. Patch a specific locale/content leaf or use typed translation operations.\",\n operationIndex: patchIndex,\n operationId,\n }),\n );\n continue;\n }\n\n const locale = segments[1];\n const localeTranslations = translations[locale];\n if (segments.length === 2 && localeTranslations !== undefined) {\n issues.push(\n createIssue({\n code: \"unsafe-locale-translation-patch\",\n message: `Raw patch ${patchIndex} would replace or remove the existing ${locale} locale branch and discard sibling translations. Patch a leaf under /translations/${locale}/itemTranslations/<itemId>/... instead.`,\n operationIndex: patchIndex,\n operationId,\n }),\n );\n continue;\n }\n\n if (\n segments[2] === \"itemTranslations\" &&\n segments.length === 4 &&\n localeTranslations?.itemTranslations?.[segments[3]] !== undefined\n ) {\n issues.push(\n createIssue({\n code: \"unsafe-item-translation-patch\",\n message: `Raw patch ${patchIndex} would replace or remove all existing translations for item \"${segments[3]}\" in locale ${locale}. Patch the individual content key instead, or use update-item-translation.`,\n operationIndex: patchIndex,\n operationId,\n itemId: segments[3],\n }),\n );\n }\n }\n }\n\n return issues;\n};\n\nconst validateTranslationBranchShapes = ({\n operation,\n survey,\n}: {\n operation: Extract<SurveyOperation, { kind: \"survey-json-patch\" }>;\n survey: RawSurvey;\n}) => {\n const issues: SurveyValidationIssue[] = [];\n const operationId = getOperationId(operation);\n\n for (const [locale, localeTranslations] of Object.entries(survey.translations ?? {})) {\n if (!isRecord(localeTranslations)) {\n issues.push(\n createIssue({\n code: \"invalid-locale-translation-shape\",\n message: `Locale \"${locale}\" must be a translation object, not an array or primitive value.`,\n operationIndex: 0,\n operationId,\n }),\n );\n continue;\n }\n\n if (\n localeTranslations.itemTranslations !== undefined &&\n !isRecord(localeTranslations.itemTranslations)\n ) {\n issues.push(\n createIssue({\n code: \"invalid-item-translations-shape\",\n message: `Locale \"${locale}\" itemTranslations must be an object keyed by item id.`,\n operationIndex: 0,\n operationId,\n }),\n );\n }\n }\n\n return issues;\n};\n\nconst getRawItemsFromSurvey = (survey: RawSurvey): RawSurveyItem[] =>\n Array.isArray(survey.surveyItems) ? survey.surveyItems : [];\n\ninterface RequiredLocalizedContent {\n itemId: string;\n contentKey: string;\n}\n\nconst FORM_LAYOUT_BREAKPOINTS = [\"base\", \"xs\", \"sm\", \"md\", \"xl\"] as const;\n\ninterface InvalidFormLayout {\n itemId: string;\n path: string;\n value: unknown;\n}\n\nconst collectInvalidFieldGroupLayouts = ({\n fieldGroups,\n itemId,\n prefix,\n invalid,\n}: {\n fieldGroups: unknown;\n itemId: string;\n prefix: string;\n invalid: Map<string, InvalidFormLayout>;\n}) => {\n if (!Array.isArray(fieldGroups)) {\n return;\n }\n\n for (const [groupIndex, group] of fieldGroups.entries()) {\n if (!isRecord(group) || !isRecord(group.layout)) {\n continue;\n }\n\n const groupId = getTrimmedString(group.id) ?? String(groupIndex);\n for (const breakpoint of FORM_LAYOUT_BREAKPOINTS) {\n const value = group.layout[breakpoint];\n if (\n value !== undefined &&\n (typeof value !== \"number\" || !Number.isInteger(value) || value < 1 || value > 4)\n ) {\n const path = `${prefix}.${groupId}.layout.${breakpoint}`;\n invalid.set(`${itemId}\\u0000${path}`, { itemId, path, value });\n }\n }\n }\n};\n\nconst collectInvalidSurveyFormLayouts = (survey: RawSurvey) => {\n const invalid = new Map<string, InvalidFormLayout>();\n\n for (const item of survey.surveyItems) {\n const config = isRecord(item.config) ? item.config : undefined;\n if (item.itemType === FORM_ITEM_TYPE) {\n collectInvalidFieldGroupLayouts({\n fieldGroups: config?.fieldGroups,\n itemId: item.id,\n prefix: \"fieldGroups\",\n invalid,\n });\n continue;\n }\n\n if (item.itemType !== CHOICE_ITEM_TYPE || !Array.isArray(config?.options)) {\n continue;\n }\n\n for (const option of config.options) {\n if (!isRecord(option) || !isRecord(option.embeddedForm)) {\n continue;\n }\n const optionId = getTrimmedString(option.id);\n if (optionId) {\n collectInvalidFieldGroupLayouts({\n fieldGroups: option.embeddedForm.fieldGroups,\n itemId: item.id,\n prefix: `embeddedForms.${optionId}.fieldGroups`,\n invalid,\n });\n }\n }\n }\n\n return invalid;\n};\n\nconst addRequiredLocalizedContent = (\n required: Map<string, RequiredLocalizedContent>,\n itemId: string,\n contentKey: string,\n) => {\n required.set(`${itemId}\\u0000${contentKey}`, { itemId, contentKey });\n};\n\nconst collectFieldLocalizedContent = ({\n fieldGroups,\n itemId,\n prefix,\n required,\n}: {\n fieldGroups: unknown;\n itemId: string;\n prefix: string;\n required: Map<string, RequiredLocalizedContent>;\n}) => {\n if (!Array.isArray(fieldGroups)) {\n return;\n }\n\n for (const group of fieldGroups) {\n if (!isRecord(group) || !Array.isArray(group.fields)) {\n continue;\n }\n\n for (const field of group.fields) {\n if (!isRecord(field)) {\n continue;\n }\n\n const fieldId = getTrimmedString(field.id);\n if (!fieldId) {\n continue;\n }\n\n addRequiredLocalizedContent(required, itemId, `${prefix}.${fieldId}.label`);\n\n const controller = isRecord(field.controller) ? field.controller : undefined;\n if (field.type !== \"select\" || controller?.type !== \"select\") {\n continue;\n }\n\n for (const option of Array.isArray(controller.options) ? controller.options : []) {\n const optionId = isRecord(option) ? getTrimmedString(option.id) : undefined;\n if (optionId) {\n addRequiredLocalizedContent(\n required,\n itemId,\n `${prefix}.${fieldId}.options.${optionId}.label`,\n );\n }\n }\n }\n }\n};\n\nconst collectRequiredLocalizedContent = (\n survey: RawSurvey,\n snapshot: SurveyAssistantEngineContext,\n) => {\n const required = new Map<string, RequiredLocalizedContent>();\n const manifestByItemType = new Map(\n snapshot.capabilities.itemTypes.map((entry) => [entry.itemType, entry]),\n );\n\n for (const item of survey.surveyItems) {\n const manifest = manifestByItemType.get(item.itemType);\n for (const surface of manifest?.contentSurfaces ?? []) {\n if (surface.requiredOnCreate && !surface.pattern) {\n addRequiredLocalizedContent(required, item.id, surface.key);\n }\n }\n\n const config = isRecord(item.config) ? item.config : undefined;\n if (item.itemType === FORM_ITEM_TYPE) {\n collectFieldLocalizedContent({\n fieldGroups: config?.fieldGroups,\n itemId: item.id,\n prefix: \"fields\",\n required,\n });\n continue;\n }\n\n if (item.itemType !== CHOICE_ITEM_TYPE || !Array.isArray(config?.options)) {\n continue;\n }\n\n for (const option of config.options) {\n if (!isRecord(option)) {\n continue;\n }\n\n const optionId = getTrimmedString(option.id);\n if (!optionId) {\n continue;\n }\n\n addRequiredLocalizedContent(required, item.id, `options.${optionId}.label`);\n if (isRecord(option.embeddedForm)) {\n collectFieldLocalizedContent({\n fieldGroups: option.embeddedForm.fieldGroups,\n itemId: item.id,\n prefix: `embeddedForms.${optionId}.fields`,\n required,\n });\n }\n }\n }\n\n return required;\n};\n\nconst hasNonEmptySurveyTranslation = (\n survey: RawSurvey,\n { itemId, contentKey }: RequiredLocalizedContent,\n) =>\n Object.values(survey.translations ?? {}).some((localeTranslations) => {\n const content = localeTranslations?.itemTranslations?.[itemId]?.[contentKey];\n return isContent(content) && !isContentEmpty(content);\n });\n\nconst validateNewRawPatchLocalizedContent = ({\n operation,\n originalSurvey,\n patchedSurvey,\n snapshot,\n}: {\n operation: Extract<SurveyOperation, { kind: \"survey-json-patch\" }>;\n originalSurvey: RawSurvey;\n patchedSurvey: RawSurvey;\n snapshot: SurveyAssistantEngineContext;\n}) => {\n const existingRequired = collectRequiredLocalizedContent(originalSurvey, snapshot);\n const existingMissing = new Set(\n Array.from(existingRequired)\n .filter(([, binding]) => !hasNonEmptySurveyTranslation(originalSurvey, binding))\n .map(([identity]) => identity),\n );\n const missing = Array.from(collectRequiredLocalizedContent(patchedSurvey, snapshot))\n .filter(([identity, binding]) => {\n if (hasNonEmptySurveyTranslation(patchedSurvey, binding)) {\n return false;\n }\n return !existingMissing.has(identity);\n })\n .map(([, binding]) => binding);\n\n if (missing.length === 0) {\n return [];\n }\n\n const missingPaths = missing.map(\n ({ itemId, contentKey }) => `/translations/<locale>/itemTranslations/${itemId}/${contentKey}`,\n );\n\n return [\n createIssue({\n code: \"missing-raw-patch-localized-content\",\n message:\n \"The raw patch introduces respondent-visible content without its required translation. \" +\n `Add non-empty Content values in the same patches array for: ${formatBoundedDiagnosticValues(missingPaths)}. ` +\n \"Content keys use config ids exactly and are case-sensitive; for embedded fields, \" +\n \"embeddedForms.<optionId> uses the choice option's id, not its key or embeddedForm id.\",\n operationIndex: 0,\n operationId: getOperationId(operation),\n itemId: missing[0]?.itemId,\n }),\n ];\n};\n\nconst validateNewRawPatchFormLayouts = ({\n operation,\n originalSurvey,\n patchedSurvey,\n}: {\n operation: Extract<SurveyOperation, { kind: \"survey-json-patch\" }>;\n originalSurvey: RawSurvey;\n patchedSurvey: RawSurvey;\n}) => {\n const existingInvalid = collectInvalidSurveyFormLayouts(originalSurvey);\n const introducedInvalid = Array.from(collectInvalidSurveyFormLayouts(patchedSurvey))\n .filter(([identity, entry]) => {\n const existing = existingInvalid.get(identity);\n return !existing || !Object.is(existing.value, entry.value);\n })\n .map(([, entry]) => entry);\n\n if (introducedInvalid.length === 0) {\n return [];\n }\n\n return [\n createIssue({\n code: \"invalid-form-layout-columns\",\n message:\n \"Form layout values are responsive column counts from 1 to 4, not field spans. \" +\n `Use 1 for a lone full-width field. Invalid values: ${introducedInvalid\n .map(({ path, value }) => `${path}=${JSON.stringify(value)}`)\n .join(\", \")}.`,\n operationIndex: 0,\n operationId: getOperationId(operation),\n itemId: introducedInvalid[0]?.itemId,\n }),\n ];\n};\n\nconst createStructureIssue = ({\n code,\n message,\n operationId,\n itemId,\n}: {\n code: string;\n message: string;\n operationId?: string;\n itemId?: string;\n}): SurveyValidationIssue =>\n createIssue({\n code,\n message,\n operationIndex: 0,\n operationId,\n itemId,\n });\n\nconst buildResponseSlotTypesForDraft = ({\n currentItem,\n rawItemsById,\n snapshot,\n}: {\n currentItem?: RawSurveyItem;\n rawItemsById: Map<string, RawSurveyItem>;\n snapshot: SurveyAssistantEngineContext;\n}): ResponseSlotTypeLookup => {\n const draftItems = Array.from(rawItemsById.values());\n if (currentItem) {\n const existingIndex = draftItems.findIndex((item) => item.id === currentItem.id);\n if (existingIndex >= 0) {\n draftItems[existingIndex] = currentItem;\n } else {\n draftItems.push(currentItem);\n }\n }\n\n return deriveResponseSlotTypes({\n ...(snapshot.survey as RawSurvey),\n surveyItems: draftItems,\n });\n};\n\nconst isJsonExpression = (value: unknown): value is JsonExpression =>\n isRecord(value) && typeof value.type === \"string\";\n\nconst validateCreateItemExpressions = ({\n issues,\n item,\n operationId,\n operationIndex,\n responseSlotTypes,\n}: {\n issues: SurveyValidationIssue[];\n item: RawSurveyItem;\n operationId: string | undefined;\n operationIndex: number;\n responseSlotTypes: ResponseSlotTypeLookup;\n}) => {\n const addExpressionValidation = (\n expression: unknown,\n scope: string,\n expectedReturnType?: ValueType,\n ) => {\n if (!isJsonExpression(expression)) {\n issues.push(\n createIssue({\n code: \"invalid-expression\",\n message: `${scope} must be a CASE expression JSON object.`,\n operationIndex,\n operationId,\n itemId: item.id,\n }),\n );\n return;\n }\n\n const beforeCount = issues.length;\n validateExpression({\n expression,\n expectedReturnType,\n issues,\n operationIndex,\n responseSlotTypes,\n scope,\n });\n for (const issue of issues.slice(beforeCount)) {\n issue.operationId = issue.operationId ?? operationId;\n issue.itemId = issue.itemId ?? item.id;\n }\n };\n\n const displayConditions = isRecord(item.displayConditions) ? item.displayConditions : undefined;\n if (displayConditions?.root !== undefined) {\n addExpressionValidation(\n displayConditions.root,\n `display condition for new item ${item.id}`,\n ValueType.boolean,\n );\n }\n const displayComponents = isRecord(displayConditions?.components)\n ? displayConditions.components\n : undefined;\n for (const [componentId, expression] of Object.entries(displayComponents ?? {})) {\n addExpressionValidation(\n expression,\n `display condition for new item ${item.id}.${componentId}`,\n ValueType.boolean,\n );\n }\n\n const disabledConditions = isRecord(item.disabledConditions)\n ? item.disabledConditions\n : undefined;\n const disabledComponents = isRecord(disabledConditions?.components)\n ? disabledConditions.components\n : undefined;\n for (const [componentId, expression] of Object.entries(disabledComponents ?? {})) {\n addExpressionValidation(\n expression,\n `disabled condition for new item ${item.id}.${componentId}`,\n ValueType.boolean,\n );\n }\n\n const validations = isRecord(item.validations) ? item.validations : undefined;\n for (const [validationKey, expression] of Object.entries(validations ?? {})) {\n addExpressionValidation(\n expression,\n `validation ${validationKey} for new item ${item.id}`,\n ValueType.boolean,\n );\n }\n\n const prefills = Array.isArray(item.prefills) ? item.prefills : [];\n for (const prefill of prefills) {\n if (!isRecord(prefill)) {\n continue;\n }\n const prefillId = getTrimmedString(prefill.id) ?? \"unnamed\";\n if (prefill.when !== undefined) {\n addExpressionValidation(\n prefill.when,\n `prefill ${prefillId} condition for new item ${item.id}`,\n ValueType.boolean,\n );\n }\n const source = isRecord(prefill.source) ? prefill.source : undefined;\n if (source?.type === \"expression\") {\n addExpressionValidation(\n source.expression,\n `prefill ${prefillId} source expression for new item ${item.id}`,\n );\n }\n }\n};\n\nconst validateSurveyTreeStructure = (\n survey: RawSurvey,\n operationId: string | undefined,\n availableItemTypes: Set<string>,\n): SurveyValidationIssue[] => {\n const issues: SurveyValidationIssue[] = [];\n\n if (!isRecord(survey)) {\n return [\n createStructureIssue({\n code: \"patched-survey-not-object\",\n message: \"The patched survey must be a JSON object.\",\n operationId,\n }),\n ];\n }\n\n if (typeof survey.$schema !== \"string\" || survey.$schema.trim().length === 0) {\n issues.push(\n createStructureIssue({\n code: \"missing-survey-schema\",\n message: \"The patched survey must keep a non-empty $schema value.\",\n operationId,\n }),\n );\n }\n\n if (!Array.isArray(survey.surveyItems) || survey.surveyItems.length === 0) {\n issues.push(\n createStructureIssue({\n code: \"missing-survey-items\",\n message: \"The patched survey must contain at least one survey item.\",\n operationId,\n }),\n );\n return issues;\n }\n\n const itemsById = new Map<string, RawSurveyItem>();\n const rootItems: RawSurveyItem[] = [];\n\n for (const [itemIndex, item] of survey.surveyItems.entries()) {\n if (!isRecord(item)) {\n issues.push(\n createStructureIssue({\n code: \"invalid-survey-item\",\n message: `Survey item at index ${itemIndex} must be an object.`,\n operationId,\n }),\n );\n continue;\n }\n\n const itemId = getTrimmedString(item.id);\n const itemKey = getTrimmedString(item.key);\n const itemType = getTrimmedString(item.itemType);\n\n if (!itemId || !itemKey || !itemType) {\n issues.push(\n createStructureIssue({\n code: \"invalid-survey-item-identity\",\n message: `Survey item at index ${itemIndex} must have non-empty id, key, and itemType fields.`,\n operationId,\n itemId,\n }),\n );\n continue;\n }\n\n if (!availableItemTypes.has(itemType)) {\n issues.push(\n createStructureIssue({\n code: \"unknown-item-type\",\n message: `Item \"${itemId}\" uses item type \"${itemType}\", which is not available in the current editor registry.`,\n operationId,\n itemId,\n }),\n );\n }\n\n if (!ITEM_KEY_PATTERN.test(itemKey)) {\n issues.push(\n createStructureIssue({\n code: \"invalid-item-key\",\n message: `Item \"${itemId}\" has an invalid key. Keys must contain only letters, numbers, underscores, or hyphens.`,\n operationId,\n itemId,\n }),\n );\n }\n\n if (itemsById.has(itemId)) {\n issues.push(\n createStructureIssue({\n code: \"duplicate-item-id\",\n message: `The patched survey contains duplicate item id \"${itemId}\".`,\n operationId,\n itemId,\n }),\n );\n continue;\n }\n\n const rawItem = item as RawSurveyItem;\n itemsById.set(itemId, rawItem);\n if (isRootItem(rawItem)) {\n rootItems.push(rawItem);\n }\n }\n\n if (rootItems.length !== 1) {\n issues.push(\n createStructureIssue({\n code: \"invalid-root-count\",\n message:\n rootItems.length === 0\n ? \"The patched survey must contain one root group item.\"\n : \"The patched survey cannot contain more than one root group item.\",\n operationId,\n }),\n );\n } else if (rootItems[0].itemType !== ReservedSurveyItemTypes.Group) {\n issues.push(\n createStructureIssue({\n code: \"root-not-group\",\n message: \"The root item must be a group item.\",\n operationId,\n itemId: rootItems[0].id,\n }),\n );\n }\n\n const parentByChildId = new Map<string, string>();\n\n for (const item of itemsById.values()) {\n const config = isRecord(item.config) ? item.config : undefined;\n const childRefs = config?.items;\n\n if (childRefs === undefined) {\n continue;\n }\n\n if (item.itemType !== ReservedSurveyItemTypes.Group || !Array.isArray(childRefs)) {\n issues.push(\n createStructureIssue({\n code: \"invalid-group-items\",\n message: `Item \"${item.id}\" has an items array but is not a valid group item.`,\n operationId,\n itemId: item.id,\n }),\n );\n continue;\n }\n\n const seenChildRefs = new Set<string>();\n for (const childId of childRefs) {\n if (typeof childId !== \"string\" || childId.trim().length === 0) {\n issues.push(\n createStructureIssue({\n code: \"invalid-child-reference\",\n message: `Group item \"${item.id}\" contains an invalid child reference.`,\n operationId,\n itemId: item.id,\n }),\n );\n continue;\n }\n\n if (childId === item.id) {\n issues.push(\n createStructureIssue({\n code: \"self-child-reference\",\n message: `Group item \"${item.id}\" cannot include itself as a child.`,\n operationId,\n itemId: item.id,\n }),\n );\n }\n\n if (seenChildRefs.has(childId)) {\n issues.push(\n createStructureIssue({\n code: \"duplicate-child-reference\",\n message: `Group item \"${item.id}\" lists child \"${childId}\" more than once.`,\n operationId,\n itemId: item.id,\n }),\n );\n }\n seenChildRefs.add(childId);\n\n if (!itemsById.has(childId)) {\n issues.push(\n createStructureIssue({\n code: \"missing-child-item\",\n message: `Group item \"${item.id}\" references missing child item \"${childId}\".`,\n operationId,\n itemId: item.id,\n }),\n );\n continue;\n }\n\n const existingParentId = parentByChildId.get(childId);\n if (existingParentId && existingParentId !== item.id) {\n issues.push(\n createStructureIssue({\n code: \"multiple-child-parents\",\n message: `Child item \"${childId}\" is listed under both \"${existingParentId}\" and \"${item.id}\".`,\n operationId,\n itemId: childId,\n }),\n );\n }\n parentByChildId.set(childId, item.id);\n }\n }\n\n for (const item of itemsById.values()) {\n if (isRootItem(item)) {\n continue;\n }\n\n if (!parentByChildId.has(item.id)) {\n issues.push(\n createStructureIssue({\n code: \"orphan-survey-item\",\n message: `Item \"${item.id}\" is not reachable from any group parent.`,\n operationId,\n itemId: item.id,\n }),\n );\n }\n }\n\n for (const item of itemsById.values()) {\n const siblingKeys = new Map<string, string>();\n for (const childId of getGroupChildren(item)) {\n const child = itemsById.get(childId);\n if (!child) {\n continue;\n }\n\n const conflictingChildId = siblingKeys.get(child.key);\n if (conflictingChildId) {\n issues.push(\n createStructureIssue({\n code: \"duplicate-sibling-key\",\n message: `Siblings \"${conflictingChildId}\" and \"${childId}\" both use key \"${child.key}\".`,\n operationId,\n itemId: childId,\n }),\n );\n }\n siblingKeys.set(child.key, childId);\n }\n }\n\n const rootItem = rootItems[0];\n if (rootItem) {\n const visiting = new Set<string>();\n const visited = new Set<string>();\n\n const visit = (itemId: string, path: string[]) => {\n if (visiting.has(itemId)) {\n issues.push(\n createStructureIssue({\n code: \"survey-item-cycle\",\n message: `The patched survey contains a cycle through item \"${itemId}\" (${path.join(\" -> \")} -> ${itemId}).`,\n operationId,\n itemId,\n }),\n );\n return;\n }\n\n if (visited.has(itemId)) {\n return;\n }\n\n visiting.add(itemId);\n const item = itemsById.get(itemId);\n for (const childId of getGroupChildren(item)) {\n visit(childId, [...path, itemId]);\n }\n visiting.delete(itemId);\n visited.add(itemId);\n };\n\n visit(rootItem.id, []);\n }\n\n return issues;\n};\n\nconst validateSurveyJsonPatchOperation = ({\n operation,\n snapshot,\n}: {\n operation: Extract<SurveyOperation, { kind: \"survey-json-patch\" }>;\n snapshot: SurveyAssistantEngineContext;\n}): SurveyValidationResult => {\n const operationId = getOperationId(operation);\n const issues: SurveyValidationIssue[] = [];\n const warnings: SurveyValidationIssue[] = [];\n\n issues.push(\n ...validateTranslationPatchSafety({\n operation,\n survey: snapshot.survey as RawSurvey,\n }),\n );\n\n for (const path of getPatchTouchedPaths(operation)) {\n try {\n if (touchesSurveySchemaPath(path)) {\n issues.push(\n createIssue({\n code: \"cannot-edit-survey-schema\",\n message: \"Assistant raw patches cannot modify the survey $schema field.\",\n operationIndex: 0,\n operationId,\n }),\n );\n }\n } catch (error) {\n issues.push(\n createIssue({\n code: \"invalid-json-pointer\",\n message:\n error instanceof Error\n ? error.message\n : `Invalid JSON Pointer path \"${path}\" in raw survey patch.`,\n operationIndex: 0,\n operationId,\n }),\n );\n }\n }\n\n if (issues.length > 0) {\n return {\n valid: false,\n issues,\n warnings,\n normalizedOperations: [operation],\n };\n }\n\n let patchedSurvey: RawSurvey;\n try {\n patchedSurvey = applyJsonPatch<RawSurvey>(snapshot.survey, operation.patches);\n } catch (error) {\n const patchError = error instanceof JsonPatchError ? error : undefined;\n return {\n valid: false,\n issues: [\n createIssue({\n code: patchError?.code ?? \"json-patch-failed\",\n message:\n error instanceof Error\n ? error.message\n : \"The raw survey JSON Patch could not be applied.\",\n operationIndex: patchError?.operationIndex ?? 0,\n operationId,\n }),\n ],\n warnings,\n normalizedOperations: [operation],\n };\n }\n\n const existingItemIds = new Set(snapshot.survey.surveyItems.map((item) => item.id));\n const manifestByItemType = new Map(\n snapshot.capabilities.itemTypes.map((entry) => [entry.itemType, entry]),\n );\n for (const item of patchedSurvey.surveyItems) {\n if (existingItemIds.has(item.id)) {\n continue;\n }\n\n const capability = manifestByItemType.get(item.itemType);\n if (capability?.create !== \"deterministic\") {\n issues.push(\n createIssue({\n code: \"item-type-not-deterministically-creatable\",\n message: capability\n ? `Item type \"${item.itemType}\" requires an interactive editor flow and cannot be created through a raw patch.`\n : `Item type \"${item.itemType}\" is not available in the current assistant capability set.`,\n operationIndex: 0,\n operationId,\n itemId: item.id,\n }),\n );\n }\n }\n\n for (const item of patchedSurvey.surveyItems) {\n const capability = snapshot.trustedCapabilities?.byItemType.get(item.itemType);\n for (const issue of capability?.validateItem?.(item) ?? []) {\n const normalizedIssue = {\n ...issue,\n operationIndex: issue.operationIndex ?? 0,\n operationId: issue.operationId ?? operationId,\n itemId: issue.itemId ?? item.id,\n };\n (normalizedIssue.severity === \"warning\" ? warnings : issues).push(normalizedIssue);\n }\n }\n\n issues.push(\n ...validateTranslationBranchShapes({ operation, survey: patchedSurvey }),\n ...validateNewRawPatchLocalizedContent({\n operation,\n originalSurvey: snapshot.survey,\n patchedSurvey,\n snapshot,\n }),\n ...validateNewRawPatchFormLayouts({\n operation,\n originalSurvey: snapshot.survey,\n patchedSurvey,\n }),\n ...validateSurveyTreeStructure(\n patchedSurvey,\n operationId,\n new Set(snapshot.capabilities.itemTypes.map((entry) => entry.itemType)),\n ),\n );\n\n const documentResult = rawSurveyDocumentSchema.safeParse(patchedSurvey);\n if (!documentResult.success) {\n const firstIssue = documentResult.error.issues[0];\n const path = firstIssue?.path.length ? ` at /${firstIssue.path.join(\"/\")}` : \"\";\n issues.push(\n createIssue({\n code: \"invalid-survey-document\",\n message: `The raw patch would produce an invalid survey document${path}: ${firstIssue?.message ?? \"schema validation failed\"}.`,\n operationIndex: 0,\n operationId,\n }),\n );\n }\n\n if (getRawItemsFromSurvey(patchedSurvey).length !== getRawSurveyItems(snapshot).length) {\n warnings.push(\n createIssue({\n severity: \"warning\",\n code: \"raw-patch-changed-item-count\",\n message:\n \"The raw survey patch changes the number of survey items. Confirm that added or removed ids are reflected in the parent group items array and translations.\",\n operationIndex: 0,\n operationId,\n }),\n );\n }\n\n return {\n valid: issues.length === 0,\n issues,\n warnings,\n normalizedOperations: [operation],\n };\n};\n\nconst buildParentByChildId = (rawItems: RawSurveyItem[]) => {\n const parentByChildId = new Map<string, string>();\n\n for (const item of rawItems) {\n for (const childId of getGroupChildren(item)) {\n parentByChildId.set(childId, item.id);\n }\n }\n\n return parentByChildId;\n};\n\nconst collectDescendantIds = (\n itemId: string,\n rawItemsById: Map<string, RawSurveyItem>,\n descendants = new Set<string>(),\n) => {\n const item = rawItemsById.get(itemId);\n\n for (const childId of getGroupChildren(item)) {\n if (descendants.has(childId)) {\n continue;\n }\n descendants.add(childId);\n collectDescendantIds(childId, rawItemsById, descendants);\n }\n\n return descendants;\n};\n\nconst normalizeSummary = (summary: string) => {\n const trimmed = summary.trim();\n return trimmed.length > 0 ? trimmed : \"Prepared survey change\";\n};\n\nconst createIssue = ({ severity = \"error\", ...input }: IssueInput): SurveyValidationIssue => ({\n severity,\n ...input,\n});\n\nconst getOperationId = (operation: SurveyOperation) => operation.id;\n\nconst isSurveyLevelOperation = (\n operation: SurveyOperation,\n): operation is Extract<\n SurveyOperation,\n {\n kind:\n | \"update-survey-metadata\"\n | \"update-survey-pagination\"\n | \"update-survey-translation\"\n | \"add-survey-locale\"\n | \"remove-survey-locale\"\n | \"set-image-asset\"\n | \"update-image-asset-metadata\"\n | \"remove-image-asset\";\n }\n> =>\n [\n \"update-survey-metadata\",\n \"update-survey-pagination\",\n \"update-survey-translation\",\n \"add-survey-locale\",\n \"remove-survey-locale\",\n \"set-image-asset\",\n \"update-image-asset-metadata\",\n \"remove-image-asset\",\n ].includes(operation.kind);\n\nconst getOperationTarget = (operation: Exclude<SurveyOperation, { kind: \"survey-json-patch\" }>) => {\n switch (operation.kind) {\n case \"create-item\":\n return operation.target.parentItemId;\n case \"upsert-form-field-group\":\n case \"remove-form-field-group\":\n case \"reorder-form-field-groups\":\n case \"upsert-form-field\":\n case \"remove-form-field\":\n case \"move-form-field\":\n return operation.target.itemId;\n case \"reorder-items\":\n return operation.parentItemId;\n case \"update-survey-metadata\":\n case \"update-survey-pagination\":\n case \"update-survey-translation\":\n case \"add-survey-locale\":\n case \"remove-survey-locale\":\n case \"set-image-asset\":\n case \"update-image-asset-metadata\":\n case \"remove-image-asset\":\n return \"\";\n default:\n return operation.itemId;\n }\n};\n\ntype ItemTypeManifestEntry = SurveyAssistantEngineContext[\"capabilities\"][\"itemTypes\"][number];\ntype ChoiceOptionRecord = Record<string, unknown> & { id: string; key?: string };\n\nconst createChoiceOptionLabelContentKey = (optionId: string) => `options.${optionId}.label`;\n\nconst KNOWN_CHOICE_OPTION_INPUT_KEYS = new Set([\n \"id\",\n \"optionId\",\n \"label\",\n \"text\",\n \"title\",\n \"name\",\n \"value\",\n \"key\",\n \"hasDisplayCondition\",\n \"embeddedFormItemId\",\n \"embeddedForm\",\n]);\n\nconst getUnrecognizedChoiceOptionKeys = (option: Record<string, unknown>): string[] =>\n Object.keys(option).filter((key) => !KNOWN_CHOICE_OPTION_INPUT_KEYS.has(key));\n\nconst normalizeChoiceOptionId = (value: string): string =>\n value\n .trim()\n .replace(/[.\\s]+/g, \"_\")\n .replace(/[^A-Za-z0-9_-]+/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\nconst normalizeChoiceOptionKey = (value: string): string =>\n value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/_+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\nconst getNextChoiceOptionKey = (usedKeys: Set<string>) => {\n const usedNumbers = new Set(\n Array.from(usedKeys)\n .map((key) => normalizeChoiceOptionKey(key).match(/^opt_(\\d+)$/)?.[1])\n .filter((value): value is string => value !== undefined)\n .map((value) => Number.parseInt(value, 10))\n .filter((value) => Number.isFinite(value)),\n );\n\n let nextNumber = 1;\n while (usedNumbers.has(nextNumber)) {\n nextNumber += 1;\n }\n\n return `opt_${nextNumber}`;\n};\n\nconst ensureUniqueId = (candidate: string | undefined, usedIds: Set<string>) => {\n const normalizedCandidate = candidate ? normalizeChoiceOptionId(candidate) : \"\";\n const baseId = normalizedCandidate || generateId();\n\n if (!usedIds.has(baseId)) {\n usedIds.add(baseId);\n return baseId;\n }\n\n let suffix = 2;\n while (usedIds.has(`${baseId}_${suffix}`)) {\n suffix += 1;\n }\n\n const uniqueId = `${baseId}_${suffix}`;\n usedIds.add(uniqueId);\n return uniqueId;\n};\n\nconst ensureUniqueChoiceOptionKey = (candidate: string | undefined, usedKeys: Set<string>) => {\n const normalizedUsedKeys = new Set(\n Array.from(usedKeys)\n .map((key) => normalizeChoiceOptionKey(key))\n .filter((key) => key.length > 0),\n );\n const normalizedCandidate = candidate ? normalizeChoiceOptionKey(candidate) : \"\";\n const baseKey = normalizedCandidate || getNextChoiceOptionKey(usedKeys);\n\n if (!usedKeys.has(baseKey) && !normalizedUsedKeys.has(baseKey)) {\n usedKeys.add(baseKey);\n return baseKey;\n }\n\n let suffix = 2;\n while (usedKeys.has(`${baseKey}_${suffix}`) || normalizedUsedKeys.has(`${baseKey}_${suffix}`)) {\n suffix += 1;\n }\n\n const uniqueKey = `${baseKey}_${suffix}`;\n usedKeys.add(uniqueKey);\n return uniqueKey;\n};\n\nconst getChoiceOptionsFromRawItem = (rawItem: RawSurveyItem): ChoiceOptionRecord[] => {\n const config = isRecord(rawItem.config) ? rawItem.config : undefined;\n const rawOptions = config?.options;\n\n if (!Array.isArray(rawOptions)) {\n return [];\n }\n\n return rawOptions\n .filter(isRecord)\n .map((option): ChoiceOptionRecord | undefined => {\n const optionId = getTrimmedString(option.id);\n if (!optionId) {\n return undefined;\n }\n\n const optionKey = getTrimmedString(option.key);\n return {\n ...option,\n id: optionId,\n ...(optionKey ? { key: optionKey } : {}),\n };\n })\n .filter((option): option is ChoiceOptionRecord => Boolean(option));\n};\n\nconst withChoiceOptionsOnRawItem = (\n rawItem: RawSurveyItem,\n options: ChoiceOptionRecord[],\n): RawSurveyItem => {\n const config = isRecord(rawItem.config) ? rawItem.config : {};\n\n return {\n ...rawItem,\n config: {\n id: rawItem.id,\n maxSelection: 1,\n shuffleOptions: false,\n ...config,\n options,\n },\n };\n};\n\ntype FormFieldGroupRecord = Record<string, unknown> & {\n id: string;\n fields: Record<string, unknown>[];\n};\n\nconst normalizeFormFieldGroupRecord = (value: unknown): FormFieldGroupRecord | undefined => {\n if (!isRecord(value)) return undefined;\n const id = getTrimmedString(value.id);\n if (!id) return undefined;\n return {\n ...value,\n id,\n layout: isRecord(value.layout) ? value.layout : { base: 1, xs: 1, sm: 1, md: 1, xl: 1 },\n fields: Array.isArray(value.fields) ? value.fields.filter(isRecord) : [],\n };\n};\n\nconst getFormFieldGroupsFromConfig = (config: unknown): FormFieldGroupRecord[] => {\n if (!isRecord(config) || !Array.isArray(config.fieldGroups)) return [];\n return config.fieldGroups\n .map(normalizeFormFieldGroupRecord)\n .filter((group): group is FormFieldGroupRecord => Boolean(group));\n};\n\nconst getFormFieldGroupsForTarget = (\n rawItem: RawSurveyItem,\n optionId?: string,\n): FormFieldGroupRecord[] | undefined => {\n if (!optionId) {\n return rawItem.itemType === FORM_ITEM_TYPE\n ? getFormFieldGroupsFromConfig(rawItem.config)\n : undefined;\n }\n if (rawItem.itemType !== CHOICE_ITEM_TYPE) return undefined;\n const option = getChoiceOptionsFromRawItem(rawItem).find(\n (candidate) => candidate.id === optionId,\n );\n return option ? getFormFieldGroupsFromConfig(option.embeddedForm) : undefined;\n};\n\nconst getFormConfigForTarget = (\n rawItem: RawSurveyItem,\n optionId?: string,\n): Record<string, unknown> | undefined => {\n if (!optionId) {\n return rawItem.itemType === FORM_ITEM_TYPE && isRecord(rawItem.config)\n ? rawItem.config\n : undefined;\n }\n if (rawItem.itemType !== CHOICE_ITEM_TYPE) return undefined;\n const option = getChoiceOptionsFromRawItem(rawItem).find(\n (candidate) => candidate.id === optionId,\n );\n return option && isRecord(option.embeddedForm) ? option.embeddedForm : undefined;\n};\n\nconst withFormFieldGroupsForTarget = (\n rawItem: RawSurveyItem,\n fieldGroups: FormFieldGroupRecord[],\n optionId?: string,\n preserveSimpleMode = false,\n): RawSurveyItem | undefined => {\n if (!optionId) {\n if (rawItem.itemType !== FORM_ITEM_TYPE) return undefined;\n const config = isRecord(rawItem.config) ? rawItem.config : {};\n return {\n ...rawItem,\n config: transitionFormAuthoringMode({\n config: { id: rawItem.id, ...config },\n fieldGroups,\n preserveSimpleMode,\n }),\n };\n }\n if (rawItem.itemType !== CHOICE_ITEM_TYPE) return undefined;\n const options = getChoiceOptionsFromRawItem(rawItem);\n const optionIndex = options.findIndex((candidate) => candidate.id === optionId);\n if (optionIndex < 0) return undefined;\n const option = options[optionIndex];\n const embeddedForm = isRecord(option.embeddedForm) ? option.embeddedForm : {};\n options[optionIndex] = {\n ...option,\n embeddedForm: transitionFormAuthoringMode({\n config: { id: optionId, ...embeddedForm },\n fieldGroups,\n preserveSimpleMode,\n }),\n };\n return withChoiceOptionsOnRawItem(rawItem, options);\n};\n\nconst normalizeFormTranslationKey = (contentKey: string, optionId?: string) =>\n optionId && !contentKey.startsWith(`embeddedForms.${optionId}.`)\n ? `embeddedForms.${optionId}.${contentKey}`\n : contentKey;\n\nconst normalizeFormOperationTranslations = <\n T extends { translations?: Array<{ contentKey: string }> },\n>(\n operation: T,\n optionId?: string,\n): T => ({\n ...operation,\n translations: operation.translations?.map((translation) => ({\n ...translation,\n contentKey: normalizeFormTranslationKey(translation.contentKey.trim(), optionId),\n })),\n});\n\nconst normalizeEmbeddedFormAuthoringMode = <\n T extends { form: Record<string, unknown> & { id: string; fieldGroups: unknown[] } },\n>(\n operation: T,\n): T => ({\n ...operation,\n form: (normalizeFormAuthoringConfig(operation.form) ?? operation.form) as T[\"form\"],\n});\n\nconst getItemTranslationText = ({\n contentKey,\n itemId,\n locale,\n snapshot,\n}: {\n contentKey: string;\n itemId: string;\n locale: string;\n snapshot: SurveyAssistantEngineContext;\n}) => {\n const translations = new SurveyTranslations((snapshot.survey as RawSurvey).translations);\n const content = translations.getItemTranslations(itemId)?.getContent(locale, contentKey) as\n | Content\n | undefined;\n\n return content ? getContentPlainText(content).trim() : undefined;\n};\n\nconst resolveChoiceOption = ({\n itemId,\n locale,\n optionRef,\n options,\n snapshot,\n}: {\n itemId: string;\n locale: string;\n optionRef: string;\n options: ChoiceOptionRecord[];\n snapshot: SurveyAssistantEngineContext;\n}) => {\n const normalizedRef = optionRef.trim();\n const normalizedSearchText = normalizedRef.toLowerCase();\n\n for (const option of options) {\n if (option.id === normalizedRef || option.key === normalizedRef) {\n return option;\n }\n }\n\n const labelMatches = options.filter((option) => {\n const label = getItemTranslationText({\n contentKey: createChoiceOptionLabelContentKey(option.id),\n itemId,\n locale,\n snapshot,\n });\n\n return label?.toLowerCase() === normalizedSearchText;\n });\n\n return labelMatches.length === 1 ? labelMatches[0] : undefined;\n};\n\nconst createChoiceOptionsConflictIssue = ({\n code,\n itemId,\n message,\n operationId,\n operationIndex,\n}: {\n code: string;\n itemId: string;\n message: string;\n operationId: string | undefined;\n operationIndex: number;\n}) =>\n createIssue({\n code,\n itemId,\n message,\n operationId,\n operationIndex,\n });\n\nconst upsertCreateItemTranslation = (\n translations: NonNullable<Extract<SurveyOperation, { kind: \"create-item\" }>[\"translations\"]>,\n nextTranslation: NonNullable<\n Extract<SurveyOperation, { kind: \"create-item\" }>[\"translations\"]\n >[number],\n) => {\n const existingIndex = translations.findIndex(\n (translation) =>\n translation.locale === nextTranslation.locale &&\n translation.contentKey === nextTranslation.contentKey,\n );\n\n if (existingIndex >= 0) {\n translations[existingIndex] = nextTranslation;\n return;\n }\n\n translations.push(nextTranslation);\n};\n\nconst normalizeChoiceOptionInput = ({\n defaultLocale,\n option,\n usedIds,\n}: {\n defaultLocale: string;\n option: unknown;\n usedIds: Set<string>;\n}):\n | {\n labelTranslation?: {\n locale: string;\n contentKey: string;\n plainText: string;\n };\n option: Record<string, unknown>;\n unrecognizedKeys?: string[];\n }\n | undefined => {\n if (typeof option === \"string\") {\n const label = option.trim();\n if (!label) {\n return undefined;\n }\n\n const optionId = ensureUniqueId(label, usedIds);\n const optionKey = normalizeChoiceOptionKey(label);\n\n return {\n labelTranslation: {\n locale: defaultLocale,\n contentKey: createChoiceOptionLabelContentKey(optionId),\n plainText: label,\n },\n option: {\n id: optionId,\n ...(optionKey ? { key: optionKey } : {}),\n },\n };\n }\n\n if (!isRecord(option)) {\n return undefined;\n }\n\n const label = getFirstStringProperty(option, [\"label\", \"text\", \"title\", \"name\"]);\n const idCandidate =\n getFirstStringProperty(option, [\"id\", \"optionId\"]) ??\n getFirstStringProperty(option, [\"value\", \"key\"]) ??\n label;\n const optionId = ensureUniqueId(idCandidate, usedIds);\n const keyCandidate = getFirstStringProperty(option, [\"key\", \"value\"]) ?? label;\n const optionKey = keyCandidate ? normalizeChoiceOptionKey(keyCandidate) : undefined;\n const embeddedFormItemId = getTrimmedString(option.embeddedFormItemId);\n const unrecognizedKeys = getUnrecognizedChoiceOptionKeys(option);\n\n return {\n labelTranslation: label\n ? {\n locale: defaultLocale,\n contentKey: createChoiceOptionLabelContentKey(optionId),\n plainText: label,\n }\n : undefined,\n option: {\n id: optionId,\n ...(optionKey ? { key: optionKey } : {}),\n ...(option.hasDisplayCondition === true ? { hasDisplayCondition: true } : {}),\n ...(embeddedFormItemId ? { embeddedFormItemId } : {}),\n ...(isRecord(option.embeddedForm) ? { embeddedForm: option.embeddedForm } : {}),\n },\n ...(unrecognizedKeys.length > 0 ? { unrecognizedKeys } : {}),\n };\n};\n\nconst normalizeContentKeyForItemType = (\n contentKey: string,\n registryEntry: ItemTypeManifestEntry | undefined,\n) => {\n const normalizedContentKey = contentKey.trim();\n const contentSurfaces = registryEntry?.contentSurfaces;\n if (!contentSurfaces) {\n return normalizedContentKey;\n }\n\n const normalizedLowerCase = normalizedContentKey.toLowerCase();\n for (const surface of contentSurfaces) {\n if (surface.aliases?.some((alias) => alias.toLowerCase() === normalizedLowerCase)) {\n return surface.key;\n }\n }\n\n return (\n contentSurfaces.find((surface) => surface.key.toLowerCase() === normalizedLowerCase)?.key ??\n normalizedContentKey\n );\n};\n\nconst normalizeCreateItemTranslationContentKeys = (\n operation: Extract<SurveyOperation, { kind: \"create-item\" }>,\n registryEntry: ItemTypeManifestEntry | undefined,\n): Extract<SurveyOperation, { kind: \"create-item\" }> => ({\n ...operation,\n translations: operation.translations?.map((translation) => ({\n ...translation,\n contentKey: normalizeContentKeyForItemType(translation.contentKey, registryEntry),\n })),\n});\n\nconst normalizeChoiceItemCreateOperation = (\n operation: Extract<SurveyOperation, { kind: \"create-item\" }>,\n defaultLocale: string,\n): {\n operation: Extract<SurveyOperation, { kind: \"create-item\" }>;\n optionWarnings: { optionId: string; unrecognizedKeys: string[] }[];\n} => {\n if (operation.item.itemType !== CHOICE_ITEM_TYPE) {\n return { operation, optionWarnings: [] };\n }\n\n const config = isRecord(operation.item.config) ? operation.item.config : {};\n const rawOptions = Array.isArray(config.options) ? config.options : [];\n const usedIds = new Set<string>();\n const normalizedOptions: Record<string, unknown>[] = [];\n const translations = [...(operation.translations ?? [])];\n const optionWarnings: { optionId: string; unrecognizedKeys: string[] }[] = [];\n\n for (const option of rawOptions) {\n const normalized = normalizeChoiceOptionInput({\n defaultLocale,\n option,\n usedIds,\n });\n\n if (!normalized) {\n continue;\n }\n\n normalizedOptions.push(normalized.option);\n if (normalized.labelTranslation) {\n upsertCreateItemTranslation(translations, normalized.labelTranslation);\n }\n if (normalized.unrecognizedKeys?.length) {\n optionWarnings.push({\n optionId: normalized.option.id as string,\n unrecognizedKeys: normalized.unrecognizedKeys,\n });\n }\n }\n\n for (const translation of translations) {\n const optionId = translation.contentKey.match(CHOICE_OPTION_LABEL_CONTENT_KEY_PATTERN)?.[1];\n const labelText = getTranslationPlainText(translation);\n if (!optionId || usedIds.has(optionId) || !labelText) {\n continue;\n }\n\n usedIds.add(optionId);\n normalizedOptions.push({\n id: optionId,\n key: normalizeChoiceOptionKey(labelText),\n });\n }\n\n return {\n operation: {\n ...operation,\n item: {\n ...operation.item,\n config: {\n ...config,\n options: normalizedOptions,\n },\n },\n translations,\n },\n optionWarnings,\n };\n};\n\nconst hasRequiredCreateContent = (\n operation: Extract<SurveyOperation, { kind: \"create-item\" }>,\n registryEntry: ItemTypeManifestEntry | undefined,\n) => {\n const requiredContentSurfaces =\n registryEntry?.contentSurfaces.filter((surface) => surface.requiredOnCreate) ?? [];\n if (requiredContentSurfaces.length === 0) {\n return true;\n }\n\n return requiredContentSurfaces.every((surface) =>\n (operation.translations ?? []).some(\n (translation) =>\n translation.contentKey === surface.key && !isTranslationContentEmpty(translation),\n ),\n );\n};\n\nconst getChoiceCreateOptionIds = (operation: Extract<SurveyOperation, { kind: \"create-item\" }>) => {\n if (operation.item.itemType !== CHOICE_ITEM_TYPE || !isRecord(operation.item.config)) {\n return [];\n }\n\n const options = operation.item.config.options;\n if (!Array.isArray(options)) {\n return [];\n }\n\n return options\n .map((option) => (isRecord(option) ? getTrimmedString(option.id) : undefined))\n .filter((optionId): optionId is string => Boolean(optionId));\n};\n\nconst getChoiceCreateContentIssue = ({\n operation,\n operationId,\n operationIndex,\n itemId,\n}: {\n operation: Extract<SurveyOperation, { kind: \"create-item\" }>;\n operationId: string | undefined;\n operationIndex: number;\n itemId: string;\n}): SurveyValidationIssue | undefined => {\n if (operation.item.itemType !== CHOICE_ITEM_TYPE) {\n return undefined;\n }\n\n const optionIds = getChoiceCreateOptionIds(operation);\n if (optionIds.length === 0) {\n return createIssue({\n code: \"missing-choice-options\",\n message:\n 'New choice items need response options. Add item.config.options entries with labels, for example { \"label\": \"Fuji\" }.',\n operationIndex,\n operationId,\n itemId,\n });\n }\n\n const missingLabelOptionIds = optionIds.filter(\n (optionId) =>\n !(operation.translations ?? []).some(\n (translation) =>\n translation.contentKey === createChoiceOptionLabelContentKey(optionId) &&\n getTranslationPlainText(translation).length > 0,\n ),\n );\n\n if (missingLabelOptionIds.length === 0) {\n return undefined;\n }\n\n return createIssue({\n code: \"missing-choice-option-labels\",\n message: `New choice item options need visible labels. Missing labels for option id(s): ${formatBoundedDiagnosticValues(missingLabelOptionIds)}.`,\n operationIndex,\n operationId,\n itemId,\n });\n};\n\nconst getRawFieldIds = (fieldGroups: unknown): string[] => {\n if (!Array.isArray(fieldGroups)) {\n return [];\n }\n\n const fieldIds: string[] = [];\n for (const group of fieldGroups) {\n if (!isRecord(group) || !Array.isArray(group.fields)) {\n continue;\n }\n\n for (const field of group.fields) {\n const fieldId = isRecord(field) ? getTrimmedString(field.id) : undefined;\n if (fieldId) {\n fieldIds.push(fieldId);\n }\n }\n }\n\n return fieldIds;\n};\n\nconst getRawFields = (fieldGroups: unknown): Record<string, unknown>[] => {\n if (!Array.isArray(fieldGroups)) {\n return [];\n }\n\n const fields: Record<string, unknown>[] = [];\n for (const group of fieldGroups) {\n if (!isRecord(group) || !Array.isArray(group.fields)) {\n continue;\n }\n\n for (const field of group.fields) {\n if (isRecord(field)) {\n fields.push(field);\n }\n }\n }\n\n return fields;\n};\n\ntype FormOperationTranslation = {\n contentKey: string;\n content?: Content;\n plainText?: string;\n};\n\nconst getRequiredFormContentKeys = ({\n fieldGroups,\n prefix,\n}: {\n fieldGroups: unknown;\n prefix: string;\n}) => {\n const required = new Set<string>();\n\n for (const field of getRawFields(fieldGroups)) {\n const fieldId = getTrimmedString(field.id);\n if (!fieldId) {\n continue;\n }\n\n required.add(`${prefix}.${fieldId}.label`);\n const controller = isRecord(field.controller) ? field.controller : undefined;\n if (field.type !== \"select\" || controller?.type !== \"select\") {\n continue;\n }\n\n for (const option of Array.isArray(controller.options) ? controller.options : []) {\n const optionId = isRecord(option) ? getTrimmedString(option.id) : undefined;\n if (optionId) {\n required.add(`${prefix}.${fieldId}.options.${optionId}.label`);\n }\n }\n }\n\n return Array.from(required);\n};\n\nconst getMissingFormOperationContentKeys = ({\n fieldGroups,\n itemId,\n prefix,\n snapshot,\n translations,\n}: {\n fieldGroups: unknown;\n itemId: string;\n prefix: string;\n snapshot: SurveyAssistantEngineContext;\n translations: FormOperationTranslation[] | undefined;\n}) =>\n getRequiredFormContentKeys({ fieldGroups, prefix }).filter((contentKey) => {\n if (\n translations?.some(\n (translation) =>\n translation.contentKey === contentKey && getTranslationPlainText(translation).length > 0,\n )\n ) {\n return false;\n }\n\n return !hasNonEmptySurveyTranslation(snapshot.survey, { itemId, contentKey });\n });\n\nconst getInvalidFormLayoutIssue = ({\n fieldGroups,\n itemId,\n operationId,\n operationIndex,\n prefix,\n}: {\n fieldGroups: unknown;\n itemId: string;\n operationId: string | undefined;\n operationIndex: number;\n prefix: string;\n}): SurveyValidationIssue | undefined => {\n const invalid = new Map<string, InvalidFormLayout>();\n collectInvalidFieldGroupLayouts({ fieldGroups, itemId, prefix, invalid });\n const entries = Array.from(invalid.values());\n if (entries.length === 0) {\n return undefined;\n }\n\n return createIssue({\n code: \"invalid-form-layout-columns\",\n message:\n \"Form layout values are responsive column counts from 1 to 4, not field spans. \" +\n `Use 1 for a lone full-width field. Invalid values: ${entries\n .map(({ path, value }) => `${path}=${JSON.stringify(value)}`)\n .join(\", \")}.`,\n operationIndex,\n operationId,\n itemId,\n });\n};\n\nconst getFormOperationContentIssue = ({\n fieldGroups,\n itemId,\n operationId,\n operationIndex,\n prefix,\n snapshot,\n translations,\n}: {\n fieldGroups: unknown;\n itemId: string;\n operationId: string | undefined;\n operationIndex: number;\n prefix: string;\n snapshot: SurveyAssistantEngineContext;\n translations: FormOperationTranslation[] | undefined;\n}): SurveyValidationIssue | undefined => {\n const missingContentKeys = getMissingFormOperationContentKeys({\n fieldGroups,\n itemId,\n prefix,\n snapshot,\n translations,\n });\n if (missingContentKeys.length === 0) {\n return undefined;\n }\n\n return createIssue({\n code: \"missing-form-field-content\",\n message:\n \"Introduced form fields and select options need visible labels. Add non-empty translations for: \" +\n formatBoundedDiagnosticValues(missingContentKeys) +\n \".\",\n operationIndex,\n operationId,\n itemId,\n });\n};\n\nconst getMissingSelectOptionLabelContentKeys = ({\n fieldGroups,\n prefix,\n translations,\n}: {\n fieldGroups: unknown;\n prefix: string;\n translations: Extract<SurveyOperation, { kind: \"create-item\" }>[\"translations\"];\n}): string[] => {\n const missingContentKeys: string[] = [];\n\n for (const field of getRawFields(fieldGroups)) {\n const fieldId = getTrimmedString(field.id);\n const controller = isRecord(field.controller) ? field.controller : undefined;\n if (!fieldId || field.type !== \"select\" || controller?.type !== \"select\") {\n continue;\n }\n\n const options = Array.isArray(controller.options) ? controller.options : [];\n for (const option of options) {\n const optionId = isRecord(option) ? getTrimmedString(option.id) : undefined;\n if (!optionId) {\n continue;\n }\n\n const contentKey = `${prefix}.${fieldId}.options.${optionId}.label`;\n if (!hasNonEmptyCreateTranslation(translations, contentKey)) {\n missingContentKeys.push(contentKey);\n }\n }\n }\n\n return missingContentKeys;\n};\n\n/**\n * A `fieldGroups` array only counts as \"usable\" if at least one group actually\n * carries a non-empty `fields` array. An empty/missing `fieldGroups` (or one\n * full of empty groups) renders nothing, even though it looks superficially\n * valid.\n */\nconst hasUsableFieldGroups = (fieldGroups: unknown): boolean => {\n if (!Array.isArray(fieldGroups) || fieldGroups.length === 0) {\n return false;\n }\n\n return fieldGroups.some(\n (group) => isRecord(group) && Array.isArray(group.fields) && group.fields.length > 0,\n );\n};\n\n/**\n * Shallow recursive search (bounded depth) for a stray `fields` array anywhere\n * inside a malformed form/embeddedForm record, so the validation message can\n * point at exactly where the model misplaced it (e.g. wrapped it in a spurious\n * `itemType`/`config` envelope instead of putting `fieldGroups` at the top\n * level of the record).\n */\nconst findNestedFieldsArrayPath = (\n value: unknown,\n path: string,\n depth: number,\n): string | undefined => {\n if (depth > 3 || !isRecord(value)) {\n return undefined;\n }\n\n if (Array.isArray(value.fields) && value.fields.length > 0) {\n return path ? `${path}.fields` : \"fields\";\n }\n\n for (const [key, nested] of Object.entries(value)) {\n if (key === \"fields\" || !isRecord(nested)) {\n continue;\n }\n\n const nestedPath = path ? `${path}.${key}` : key;\n const found = findNestedFieldsArrayPath(nested, nestedPath, depth + 1);\n if (found) {\n return found;\n }\n }\n\n return undefined;\n};\n\n/**\n * Detects any shape where a form's fields are not usable because they are not\n * nested inside a `fieldGroups` array directly on this record — including the\n * near-miss of a top-level `fields` array, AND shapes that wrap everything in\n * a spurious envelope like `{ \"itemType\": \"formItem\", \"config\": { \"fields\": [...] } }`\n * (a real model failure mode: it invents an `itemType`/`config` wrapper around\n * the embedded form instead of using the flat `{ \"id\", \"fieldGroups\" }` shape).\n * Since `fieldGroups` is not schema-validated (config is `z.unknown()`), any of\n * these mistakes is otherwise silently dropped and results in no visible fields.\n */\nconst getMissingFieldGroupsWrapperHint = (record: Record<string, unknown>): string | undefined => {\n if (hasUsableFieldGroups(record.fieldGroups)) {\n return undefined;\n }\n\n const nestedFieldsPath = findNestedFieldsArrayPath(record, \"\", 0);\n if (nestedFieldsPath) {\n return (\n `found a \"${nestedFieldsPath}\" array, but fields must be nested inside a top-level ` +\n `\"fieldGroups\" array on this exact object, for example { \"id\": \"...\", \"fieldGroups\": ` +\n `[{ \"id\": \"main\", \"fields\": [...] }] } — do NOT wrap this in an \"itemType\"/\"config\" ` +\n `envelope; the shape is flat`\n );\n }\n\n return (\n 'no \"fieldGroups\" array with any fields was found; the shape must be ' +\n '{ \"id\": \"...\", \"fieldGroups\": [{ \"id\": \"main\", \"fields\": [...] }] }'\n );\n};\n\nconst hasNonEmptyCreateTranslation = (\n translations: Extract<SurveyOperation, { kind: \"create-item\" }>[\"translations\"],\n contentKey: string,\n) =>\n (translations ?? []).some(\n (translation) =>\n translation.contentKey === contentKey && getTranslationPlainText(translation).length > 0,\n );\n\nconst getFormCreateFieldLabelIssue = ({\n operation,\n operationId,\n operationIndex,\n itemId,\n}: {\n operation: Extract<SurveyOperation, { kind: \"create-item\" }>;\n operationId: string | undefined;\n operationIndex: number;\n itemId: string;\n}): SurveyValidationIssue | undefined => {\n if (operation.item.itemType !== FORM_ITEM_TYPE || !isRecord(operation.item.config)) {\n return undefined;\n }\n\n const isExplicitBlankCustomForm =\n operation.item.config.authoringMode === \"custom\" &&\n Array.isArray(operation.item.config.fieldGroups) &&\n operation.item.config.fieldGroups.length === 1 &&\n isRecord(operation.item.config.fieldGroups[0]) &&\n Array.isArray(operation.item.config.fieldGroups[0].fields) &&\n operation.item.config.fieldGroups[0].fields.length === 0;\n if (isExplicitBlankCustomForm) {\n return undefined;\n }\n\n const wrapperHint = getMissingFieldGroupsWrapperHint(operation.item.config);\n if (wrapperHint) {\n return createIssue({\n code: \"missing-field-groups-wrapper\",\n message: `New form item has no usable fields: ${wrapperHint}.`,\n operationIndex,\n operationId,\n itemId,\n });\n }\n\n const missingLabelFieldIds = getRawFieldIds(operation.item.config.fieldGroups).filter(\n (fieldId) => !hasNonEmptyCreateTranslation(operation.translations, `fields.${fieldId}.label`),\n );\n\n const missingSelectOptionLabelContentKeys = getMissingSelectOptionLabelContentKeys({\n fieldGroups: operation.item.config.fieldGroups,\n prefix: \"fields\",\n translations: operation.translations,\n });\n\n if (missingSelectOptionLabelContentKeys.length > 0) {\n return createIssue({\n code: \"missing-form-select-option-labels\",\n message:\n `New form item select options need visible labels. Add translations for: ` +\n formatBoundedDiagnosticValues(missingSelectOptionLabelContentKeys) +\n \".\",\n operationIndex,\n operationId,\n itemId,\n });\n }\n\n if (missingLabelFieldIds.length === 0) {\n return undefined;\n }\n\n return createIssue({\n code: \"missing-form-field-labels\",\n message: `New form item fields need visible labels. Add a translation with contentKey \"fields.<fieldId>.label\" for field id(s): ${formatBoundedDiagnosticValues(missingLabelFieldIds)}.`,\n operationIndex,\n operationId,\n itemId,\n });\n};\n\nconst getChoiceEmbeddedFormFieldLabelIssue = ({\n operation,\n operationId,\n operationIndex,\n itemId,\n}: {\n operation: Extract<SurveyOperation, { kind: \"create-item\" }>;\n operationId: string | undefined;\n operationIndex: number;\n itemId: string;\n}): SurveyValidationIssue | undefined => {\n if (operation.item.itemType !== CHOICE_ITEM_TYPE || !isRecord(operation.item.config)) {\n return undefined;\n }\n\n const options = operation.item.config.options;\n if (!Array.isArray(options)) {\n return undefined;\n }\n\n const missingLabelContentKeys: string[] = [];\n for (const option of options) {\n if (!isRecord(option) || !isRecord(option.embeddedForm)) {\n continue;\n }\n\n const optionId = getTrimmedString(option.id);\n if (!optionId) {\n continue;\n }\n\n const wrapperHint = getMissingFieldGroupsWrapperHint(option.embeddedForm);\n if (wrapperHint) {\n return createIssue({\n code: \"missing-field-groups-wrapper\",\n message: `Embedded form on option \"${optionId}\" has no usable fields: ${wrapperHint}.`,\n operationIndex,\n operationId,\n itemId,\n });\n }\n\n for (const fieldId of getRawFieldIds(option.embeddedForm.fieldGroups)) {\n const contentKey = `embeddedForms.${optionId}.fields.${fieldId}.label`;\n if (!hasNonEmptyCreateTranslation(operation.translations, contentKey)) {\n missingLabelContentKeys.push(contentKey);\n }\n }\n\n missingLabelContentKeys.push(\n ...getMissingSelectOptionLabelContentKeys({\n fieldGroups: option.embeddedForm.fieldGroups,\n prefix: `embeddedForms.${optionId}.fields`,\n translations: operation.translations,\n }),\n );\n }\n\n if (missingLabelContentKeys.length === 0) {\n return undefined;\n }\n\n return createIssue({\n code: \"missing-embedded-form-field-labels\",\n message: `New embedded form fields and select options need visible labels, otherwise respondents only see raw keys. Add translations for: ${formatBoundedDiagnosticValues(missingLabelContentKeys)}.`,\n operationIndex,\n operationId,\n itemId,\n });\n};\n\nconst getCreateFormLayoutIssue = ({\n operation,\n operationId,\n operationIndex,\n itemId,\n}: {\n operation: Extract<SurveyOperation, { kind: \"create-item\" }>;\n operationId: string | undefined;\n operationIndex: number;\n itemId: string;\n}): SurveyValidationIssue | undefined => {\n if (!isRecord(operation.item.config)) {\n return undefined;\n }\n\n if (operation.item.itemType === FORM_ITEM_TYPE) {\n return getInvalidFormLayoutIssue({\n fieldGroups: operation.item.config.fieldGroups,\n itemId,\n operationId,\n operationIndex,\n prefix: \"fieldGroups\",\n });\n }\n\n if (\n operation.item.itemType !== CHOICE_ITEM_TYPE ||\n !Array.isArray(operation.item.config.options)\n ) {\n return undefined;\n }\n\n for (const option of operation.item.config.options) {\n if (!isRecord(option) || !isRecord(option.embeddedForm)) {\n continue;\n }\n const optionId = getTrimmedString(option.id);\n if (!optionId) {\n continue;\n }\n const issue = getInvalidFormLayoutIssue({\n fieldGroups: option.embeddedForm.fieldGroups,\n itemId,\n operationId,\n operationIndex,\n prefix: `embeddedForms.${optionId}.fieldGroups`,\n });\n if (issue) {\n return issue;\n }\n }\n\n return undefined;\n};\n\nconst resolveRawItemByIdentifier = ({\n identifier,\n indexById,\n outlineById,\n rawItemsById,\n}: {\n identifier: string;\n indexById: ReturnType<typeof mapKeyIndexById>;\n outlineById: ReturnType<typeof mapOutlineById>;\n rawItemsById: Map<string, RawSurveyItem>;\n}): { itemId: string; rawItem: RawSurveyItem } | undefined => {\n const direct = rawItemsById.get(identifier);\n if (direct) {\n return { itemId: identifier, rawItem: direct };\n }\n\n const resolved = resolveItemSummary(identifier, indexById, outlineById);\n if (!resolved) {\n return undefined;\n }\n\n const rawItem = rawItemsById.get(resolved.itemId);\n return rawItem ? { itemId: resolved.itemId, rawItem } : undefined;\n};\n\nconst resolveCreateParentByIdentifier = ({\n identifier,\n indexById,\n outlineById,\n rawItemsById,\n}: {\n identifier: string;\n indexById: ReturnType<typeof mapKeyIndexById>;\n outlineById: ReturnType<typeof mapOutlineById>;\n rawItemsById: Map<string, RawSurveyItem>;\n}): { itemId: string; rawItem: RawSurveyItem } | undefined => {\n if (identifier.trim().length > 0) {\n return resolveRawItemByIdentifier({\n identifier,\n indexById,\n outlineById,\n rawItemsById,\n });\n }\n\n const rootItems = Array.from(rawItemsById.entries()).filter(\n ([, rawItem]) => rawItem.itemType === ReservedSurveyItemTypes.Group && isRootItem(rawItem),\n );\n\n if (rootItems.length !== 1) {\n return undefined;\n }\n\n const [itemId, rawItem] = rootItems[0];\n return { itemId, rawItem };\n};\n\nconst normalizeOperation = (\n operation: SurveyOperation,\n resolvedItemId: string,\n): SurveyOperation => {\n switch (operation.kind) {\n case \"create-item\": {\n const nestedTranslations = getCreateItemNestedTranslations(operation.item);\n const topLevelTranslations = operation.translations ?? [];\n const translations =\n topLevelTranslations.length > 0 ? topLevelTranslations : nestedTranslations;\n const item = { ...(operation.item as Record<string, unknown>) };\n delete item.translations;\n\n return {\n ...operation,\n target: {\n ...operation.target,\n parentItemId: operation.target.parentItemId.trim(),\n },\n item: {\n ...item,\n id: operation.item.id?.trim(),\n key: operation.item.key.trim(),\n itemType: operation.item.itemType.trim(),\n },\n translations: translations.map((translation) => ({\n ...translation,\n locale: translation.locale.trim(),\n contentKey: translation.contentKey.trim(),\n })),\n };\n }\n case \"update-item-key\":\n return {\n ...operation,\n itemId: resolvedItemId,\n key: operation.key.trim(),\n };\n case \"update-item-label\":\n return {\n ...operation,\n itemId: resolvedItemId,\n itemLabel: operation.itemLabel.trim(),\n };\n case \"update-item-color\":\n return {\n ...operation,\n itemId: resolvedItemId,\n };\n case \"update-item-translation\":\n return {\n ...operation,\n itemId: resolvedItemId,\n locale: operation.locale.trim(),\n contentKey: operation.contentKey.trim(),\n };\n case \"update-placed-image\":\n return {\n ...operation,\n itemId: resolvedItemId,\n locale: operation.locale.trim(),\n contentKey: operation.contentKey.trim(),\n expectedAssetId: operation.expectedAssetId?.trim(),\n changes: {\n ...operation.changes,\n source:\n operation.changes.source?.type === \"asset\"\n ? { type: \"asset\", assetId: operation.changes.source.assetId.trim() }\n : operation.changes.source?.type === \"external\"\n ? { type: \"external\", url: operation.changes.source.url.trim() }\n : undefined,\n },\n };\n case \"patch-item-config\":\n return {\n ...operation,\n itemId: resolvedItemId,\n };\n case \"upsert-form-field-group\":\n case \"remove-form-field-group\":\n case \"reorder-form-field-groups\":\n case \"upsert-form-field\":\n case \"remove-form-field\":\n case \"move-form-field\":\n return {\n ...operation,\n target: {\n ...operation.target,\n itemId: resolvedItemId,\n optionId: operation.target.optionId?.trim(),\n },\n };\n case \"set-embedded-form\":\n case \"remove-embedded-form\":\n return {\n ...operation,\n itemId: resolvedItemId,\n optionId: operation.optionId.trim(),\n };\n case \"add-choice-option\":\n return {\n ...operation,\n itemId: resolvedItemId,\n locale: operation.locale?.trim(),\n option: {\n ...operation.option,\n id: operation.option.id?.trim(),\n key: operation.option.key?.trim(),\n label: operation.option.label.trim(),\n },\n };\n case \"update-choice-option-label\":\n return {\n ...operation,\n itemId: resolvedItemId,\n optionId: operation.optionId.trim(),\n locale: operation.locale?.trim(),\n label: operation.label.trim(),\n };\n case \"remove-choice-option\":\n return {\n ...operation,\n itemId: resolvedItemId,\n optionId: operation.optionId.trim(),\n };\n case \"reorder-choice-options\":\n return {\n ...operation,\n itemId: resolvedItemId,\n optionIds: operation.optionIds.map((optionId) => optionId.trim()),\n };\n case \"remove-item\":\n return {\n ...operation,\n itemId: resolvedItemId,\n includeChildren: operation.includeChildren ?? false,\n };\n case \"move-item\":\n return {\n ...operation,\n itemId: resolvedItemId,\n target: {\n ...operation.target,\n parentItemId: operation.target.parentItemId.trim(),\n },\n };\n case \"reorder-items\":\n return {\n ...operation,\n parentItemId: resolvedItemId,\n itemIds: operation.itemIds.map((itemId) => itemId.trim()),\n };\n case \"update-survey-metadata\":\n case \"update-survey-pagination\":\n case \"set-image-asset\":\n case \"update-image-asset-metadata\":\n case \"remove-image-asset\":\n return operation;\n case \"update-survey-translation\":\n return {\n ...operation,\n locale: operation.locale.trim(),\n contentKey: operation.contentKey.trim(),\n };\n case \"add-survey-locale\":\n case \"remove-survey-locale\":\n return { ...operation, locale: operation.locale.trim() };\n case \"survey-json-patch\":\n return operation;\n }\n};\n\nconst createEmptyValidationResult = (\n issue: SurveyValidationIssue,\n operations: SurveyOperation[],\n): SurveyValidationResult => ({\n valid: false,\n issues: [issue],\n warnings: [],\n normalizedOperations: operations,\n});\n\nconst getSiblingKeyConflict = ({\n createdKeysByParentId,\n deletedItemIds,\n itemId,\n key,\n parentByChildId,\n plannedKeys,\n rawItemsById,\n}: {\n createdKeysByParentId: Map<string, Map<string, string>>;\n deletedItemIds: Set<string>;\n itemId: string;\n key: string;\n parentByChildId: Map<string, string>;\n plannedKeys: Map<string, string>;\n rawItemsById: Map<string, RawSurveyItem>;\n}) => {\n const parentId = parentByChildId.get(itemId);\n if (!parentId) {\n return undefined;\n }\n\n const createdKeys = createdKeysByParentId.get(parentId);\n for (const [createdItemId, createdKey] of createdKeys ?? []) {\n if (createdItemId !== itemId && createdKey === key) {\n return createdItemId;\n }\n }\n\n for (const siblingId of getGroupChildren(rawItemsById.get(parentId))) {\n if (siblingId === itemId || deletedItemIds.has(siblingId)) {\n continue;\n }\n\n const siblingKey = plannedKeys.get(siblingId) ?? rawItemsById.get(siblingId)?.key;\n if (siblingKey === key) {\n return siblingId;\n }\n }\n\n return undefined;\n};\n\nconst getKeyConflictInParent = ({\n createdKeysByParentId,\n deletedItemIds,\n key,\n parentId,\n rawItemsById,\n}: {\n createdKeysByParentId: Map<string, Map<string, string>>;\n deletedItemIds: Set<string>;\n key: string;\n parentId: string;\n rawItemsById: Map<string, RawSurveyItem>;\n}) => {\n const createdKeys = createdKeysByParentId.get(parentId);\n for (const [createdItemId, createdKey] of createdKeys ?? []) {\n if (createdKey === key) {\n return createdItemId;\n }\n }\n\n for (const siblingId of getGroupChildren(rawItemsById.get(parentId))) {\n if (deletedItemIds.has(siblingId)) {\n continue;\n }\n\n if (rawItemsById.get(siblingId)?.key === key) {\n return siblingId;\n }\n }\n\n return undefined;\n};\n\nconst getPlannedCreateCountForParent = (\n parentId: string,\n createdKeysByParentId: Map<string, Map<string, string>>,\n) => createdKeysByParentId.get(parentId)?.size ?? 0;\n\nconst getDeletedAncestor = (\n itemId: string,\n parentByChildId: Map<string, string>,\n deletedItemIds: Set<string>,\n) => {\n let currentParentId = parentByChildId.get(itemId);\n\n while (currentParentId) {\n if (deletedItemIds.has(currentParentId)) {\n return currentParentId;\n }\n currentParentId = parentByChildId.get(currentParentId);\n }\n\n return undefined;\n};\n\nexport const buildSurveyDocumentVersion = (\n snapshot: SurveyAssistantEngineContext | SurveyDocumentSnapshot,\n): SurveyDocumentVersion => ({ ...snapshot.version });\n\nconst resolveEngineContext = (\n snapshot: SurveyAssistantEngineContext | SurveyDocumentSnapshot,\n): SurveyAssistantEngineContext =>\n \"document\" in snapshot ? snapshot : createSurveyAssistantEngineContext(snapshot);\n\nexport const validateSurveyOperations = ({\n maxOperations = MAX_SURVEY_ASSISTANT_OPERATIONS_PER_PROPOSAL,\n operations,\n snapshot: snapshotInput,\n}: {\n maxOperations?: number;\n operations: SurveyOperation[];\n snapshot: SurveyAssistantEngineContext | SurveyDocumentSnapshot | undefined;\n}): SurveyValidationResult => {\n if (!snapshotInput) {\n return createEmptyValidationResult(\n createIssue({\n code: \"missing-snapshot\",\n message: \"No live editor snapshot was provided for this assistant turn.\",\n }),\n operations,\n );\n }\n\n const snapshot = resolveEngineContext(snapshotInput);\n\n if (operations.length === 0) {\n return createEmptyValidationResult(\n createIssue({\n code: \"empty-operations\",\n message: \"No survey change operations were provided.\",\n }),\n operations,\n );\n }\n\n if (operations.length > maxOperations) {\n return createEmptyValidationResult(\n createIssue({\n code: \"too-many-operations\",\n message: `At most ${maxOperations} operations can be validated in this change set.`,\n }),\n operations,\n );\n }\n\n const surveyJsonPatchOperations = operations.filter(isSurveyJsonPatchOperation);\n if (surveyJsonPatchOperations.length > 0) {\n if (operations.length > 1 || surveyJsonPatchOperations.length > 1) {\n return createEmptyValidationResult(\n createIssue({\n code: \"raw-patch-must-be-single-operation\",\n message:\n \"A survey-json-patch operation must be the only operation in a proposal. Put all raw edits in that operation's patches array.\",\n operationIndex: operations.findIndex(isSurveyJsonPatchOperation),\n operationId: surveyJsonPatchOperations[0]?.id,\n }),\n operations,\n );\n }\n\n return validateSurveyJsonPatchOperation({\n operation: surveyJsonPatchOperations[0],\n snapshot,\n });\n }\n\n const rawItems = getRawSurveyItems(snapshot);\n const rawItemsById = mapRawItemsById(snapshot);\n const parentByChildId = buildParentByChildId(rawItems);\n const outlineById = mapOutlineById(snapshot);\n const indexById = mapKeyIndexById(snapshot);\n const itemTypeManifestByType = new Map(\n snapshot.capabilities.itemTypes.map((entry) => [entry.itemType, entry]),\n );\n const deterministicCreateItemTypes = new Set(\n snapshot.capabilities.itemTypes\n .filter((entry) => entry.create === \"deterministic\")\n .map((entry) => entry.itemType),\n );\n const issues: SurveyValidationIssue[] = [];\n const warnings: SurveyValidationIssue[] = [];\n const normalizedOperations: SurveyOperation[] = [];\n const createdKeysByParentId = new Map<string, Map<string, string>>();\n const plannedKeys = new Map<string, string>();\n const deletedItemIds = new Set<string>();\n const plannedLocales = new Set(snapshot.inspection.locales);\n const introducedLocaleWarnings = new Set<string>();\n\n const addIntroducedLocaleWarning = ({\n itemId,\n locale,\n operationId,\n operationIndex,\n }: {\n itemId?: string;\n locale: string;\n operationId?: string;\n operationIndex: number;\n }) => {\n if (plannedLocales.has(locale)) {\n return;\n }\n plannedLocales.add(locale);\n\n const warningKey = `${operationIndex}:${itemId ?? \"\"}:${locale}`;\n if (introducedLocaleWarnings.has(warningKey)) {\n return;\n }\n introducedLocaleWarnings.add(warningKey);\n\n warnings.push(\n createIssue({\n severity: \"warning\",\n code: \"introduced-locale\",\n message: `Locale \"${locale}\" is not currently present and will be introduced by this translation change.`,\n operationIndex,\n operationId,\n itemId,\n }),\n );\n };\n\n operations.forEach((operation, operationIndex) => {\n const operationId = getOperationId(operation);\n\n if (operation.kind === \"create-item\") {\n const baseNormalized = normalizeOperation(operation, \"\") as Extract<\n SurveyOperation,\n { kind: \"create-item\" }\n >;\n const registryEntry = itemTypeManifestByType.get(baseNormalized.item.itemType);\n const { operation: normalized, optionWarnings } = normalizeChoiceItemCreateOperation(\n normalizeCreateItemTranslationContentKeys(baseNormalized, registryEntry),\n snapshot.ui.selectedLocale,\n );\n\n for (const optionWarning of optionWarnings) {\n issues.push(\n createIssue({\n code: \"unrecognized-choice-option-keys\",\n message:\n `Option \"${optionWarning.optionId}\" has unrecognized field(s): ` +\n `${optionWarning.unrecognizedKeys.join(\", \")}. Recognized option fields are ` +\n `id, key, label, hasDisplayCondition, embeddedFormItemId, and embeddedForm ` +\n `(singular). Put respondent labels in translations at options.<optionId>.label; ` +\n `do not use provider-specific option metadata.`,\n operationIndex,\n operationId,\n }),\n );\n }\n\n const parent = resolveCreateParentByIdentifier({\n identifier: normalized.target.parentItemId,\n indexById,\n outlineById,\n rawItemsById,\n });\n\n if (!parent) {\n issues.push(\n createIssue({\n code: \"target-parent-not-found\",\n message:\n normalized.target.parentItemId.length > 0\n ? `No parent group matching \"${normalized.target.parentItemId}\" was found.`\n : \"No root group parent could be inferred for this create-item operation.\",\n operationIndex,\n operationId,\n }),\n );\n return;\n }\n\n if (parent.rawItem.itemType !== ReservedSurveyItemTypes.Group) {\n issues.push(\n createIssue({\n code: \"target-parent-not-group\",\n message: `The target parent \"${parent.itemId}\" is not a group item.`,\n operationIndex,\n operationId,\n itemId: parent.itemId,\n }),\n );\n return;\n }\n\n const deletedParentAncestorId = getDeletedAncestor(\n parent.itemId,\n parentByChildId,\n deletedItemIds,\n );\n if (deletedItemIds.has(parent.itemId) || deletedParentAncestorId) {\n issues.push(\n createIssue({\n code: \"target-parent-already-removed\",\n message: \"The target parent is removed earlier in this proposal.\",\n operationIndex,\n operationId,\n itemId: parent.itemId,\n }),\n );\n return;\n }\n\n const itemId =\n normalized.item.id && normalized.item.id.length > 0 ? normalized.item.id : generateId();\n if (rawItemsById.has(itemId)) {\n issues.push(\n createIssue({\n code: \"duplicate-item-id\",\n message: `The new item id \"${itemId}\" already exists in the survey or this proposal.`,\n operationIndex,\n operationId,\n itemId,\n }),\n );\n return;\n }\n\n if (!ITEM_KEY_PATTERN.test(normalized.item.key)) {\n issues.push(\n createIssue({\n code: \"invalid-item-key\",\n message: \"Item keys must contain only letters, numbers, underscores, or hyphens.\",\n operationIndex,\n operationId,\n itemId,\n }),\n );\n return;\n }\n\n if (\n normalized.item.itemType === \"root\" ||\n (isRecord(normalized.item.config) && normalized.item.config.isRoot === true)\n ) {\n issues.push(\n createIssue({\n code: \"cannot-create-root\",\n message: \"The assistant cannot create a second survey root item.\",\n operationIndex,\n operationId,\n itemId,\n }),\n );\n return;\n }\n\n if (\n normalized.item.itemType === ReservedSurveyItemTypes.Group &&\n getGroupChildren(normalized.item as RawSurveyItem).length > 0\n ) {\n issues.push(\n createIssue({\n code: \"create-group-with-children\",\n message:\n \"Create group items without embedded child ids; create children as separate operations.\",\n operationIndex,\n operationId,\n itemId,\n }),\n );\n return;\n }\n\n const conflictId = getKeyConflictInParent({\n createdKeysByParentId,\n deletedItemIds,\n key: normalized.item.key,\n parentId: parent.itemId,\n rawItemsById,\n });\n\n if (conflictId) {\n issues.push(\n createIssue({\n code: \"duplicate-sibling-key\",\n message: `The key \"${normalized.item.key}\" is already used by sibling item \"${conflictId}\".`,\n operationIndex,\n operationId,\n itemId,\n }),\n );\n return;\n }\n\n if (normalized.target.index !== undefined) {\n const maximumUsefulIndex =\n getGroupChildren(parent.rawItem).length +\n getPlannedCreateCountForParent(parent.itemId, createdKeysByParentId);\n if (normalized.target.index > maximumUsefulIndex) {\n warnings.push(\n createIssue({\n severity: \"warning\",\n code: \"target-index-after-end\",\n message: `The target index is after the end of the parent group and will be clamped by the editor apply path.`,\n operationIndex,\n operationId,\n itemId,\n }),\n );\n }\n }\n\n if (!deterministicCreateItemTypes.has(normalized.item.itemType)) {\n issues.push(\n createIssue({\n code: \"item-type-not-deterministically-creatable\",\n message: registryEntry\n ? registryEntry.create === \"interactive-only\"\n ? `Item type \"${normalized.item.itemType}\" requires an interactive editor flow and cannot be created silently.`\n : `Item type \"${normalized.item.itemType}\" is available in the editor registry but does not support deterministic creation.`\n : `Item type \"${normalized.item.itemType}\" is not available in the current editor registry.`,\n operationIndex,\n operationId,\n itemId,\n }),\n );\n }\n\n if (!hasRequiredCreateContent(normalized, registryEntry)) {\n issues.push(\n createIssue({\n code: \"missing-create-content\",\n message: registryEntry?.contentSurfaces.find((surface) => surface.requiredOnCreate)?.key\n ? `New \"${normalized.item.itemType}\" items need visible content. Add a translation for \"${registryEntry.contentSurfaces.find((surface) => surface.requiredOnCreate)?.key}\".`\n : `New \"${normalized.item.itemType}\" items need visible content.`,\n operationIndex,\n operationId,\n itemId,\n }),\n );\n }\n\n const choiceContentIssue = getChoiceCreateContentIssue({\n operation: normalized,\n operationId,\n operationIndex,\n itemId,\n });\n if (choiceContentIssue) {\n issues.push(choiceContentIssue);\n }\n\n const embeddedFormFieldLabelIssue = getChoiceEmbeddedFormFieldLabelIssue({\n operation: normalized,\n operationId,\n operationIndex,\n itemId,\n });\n if (embeddedFormFieldLabelIssue) {\n issues.push(embeddedFormFieldLabelIssue);\n }\n\n const formFieldLabelIssue = getFormCreateFieldLabelIssue({\n operation: normalized,\n operationId,\n operationIndex,\n itemId,\n });\n if (formFieldLabelIssue) {\n issues.push(formFieldLabelIssue);\n }\n\n const formLayoutIssue = getCreateFormLayoutIssue({\n operation: normalized,\n operationId,\n operationIndex,\n itemId,\n });\n if (formLayoutIssue) {\n issues.push(formLayoutIssue);\n }\n\n for (const translation of normalized.translations ?? []) {\n addIntroducedLocaleWarning({\n locale: translation.locale,\n operationIndex,\n operationId,\n itemId,\n });\n\n if (translation.contentKey.includes(\"..\")) {\n issues.push(\n createIssue({\n code: \"invalid-content-key\",\n message: \"Translation content keys cannot contain empty path segments.\",\n operationIndex,\n operationId,\n itemId,\n }),\n );\n }\n }\n\n let normalizedItem: RawSurveyItem = {\n ...normalized.item,\n id: itemId,\n };\n const trustedCapability = snapshot.trustedCapabilities?.byItemType.get(\n normalizedItem.itemType,\n );\n if (trustedCapability?.normalizeCreate) {\n normalizedItem = trustedCapability.normalizeCreate(normalizedItem);\n }\n if (\n normalizedItem.id !== itemId ||\n normalizedItem.itemType !== normalized.item.itemType ||\n normalizedItem.key !== normalized.item.key\n ) {\n issues.push(\n createIssue({\n code: \"invalid-capability-normalization\",\n message:\n \"The trusted item capability changed the new item's identity during normalization.\",\n operationIndex,\n operationId,\n itemId,\n }),\n );\n }\n for (const issue of trustedCapability?.validateItem?.(normalizedItem) ?? []) {\n const normalizedIssue = {\n ...issue,\n operationIndex: issue.operationIndex ?? operationIndex,\n operationId: issue.operationId ?? operationId,\n itemId: issue.itemId ?? itemId,\n };\n (normalizedIssue.severity === \"warning\" ? warnings : issues).push(normalizedIssue);\n }\n validateCreateItemExpressions({\n issues,\n item: normalizedItem,\n operationId,\n operationIndex,\n responseSlotTypes: buildResponseSlotTypesForDraft({\n currentItem: normalizedItem,\n rawItemsById,\n snapshot,\n }),\n });\n\n if (issues.some((issue) => issue.operationIndex === operationIndex)) {\n return;\n }\n\n const createdKeys = createdKeysByParentId.get(parent.itemId) ?? new Map<string, string>();\n createdKeys.set(itemId, normalizedItem.key);\n createdKeysByParentId.set(parent.itemId, createdKeys);\n rawItemsById.set(itemId, normalizedItem);\n parentByChildId.set(itemId, parent.itemId);\n normalizedOperations.push({\n ...normalized,\n target: {\n ...normalized.target,\n parentItemId: parent.itemId,\n },\n item: normalizedItem,\n });\n return;\n }\n\n if (operation.kind === \"survey-json-patch\") {\n return;\n }\n\n if (isSurveyLevelOperation(operation)) {\n const normalized = normalizeOperation(operation, \"\");\n switch (normalized.kind) {\n case \"update-survey-metadata\":\n if (Object.keys(normalized.values).length === 0) {\n issues.push(\n createIssue({\n code: \"empty-survey-metadata-update\",\n message: \"Provide at least one survey metadata key to set or remove.\",\n operationIndex,\n operationId,\n }),\n );\n return;\n }\n break;\n case \"update-survey-translation\":\n addIntroducedLocaleWarning({\n locale: normalized.locale,\n operationIndex,\n operationId,\n });\n if (normalized.contentKey.includes(\"..\")) {\n issues.push(\n createIssue({\n code: \"invalid-content-key\",\n message: \"Translation content keys cannot contain empty path segments.\",\n operationIndex,\n operationId,\n }),\n );\n return;\n }\n break;\n case \"add-survey-locale\":\n if (normalized.locale.length === 0) {\n issues.push(\n createIssue({\n code: \"invalid-survey-locale\",\n message: \"Survey locale cannot be blank.\",\n operationIndex,\n operationId,\n }),\n );\n return;\n }\n if (plannedLocales.has(normalized.locale)) {\n issues.push(\n createIssue({\n code: \"survey-locale-already-exists\",\n message: `Locale \"${normalized.locale}\" is already present in the survey.`,\n operationIndex,\n operationId,\n }),\n );\n return;\n }\n plannedLocales.add(normalized.locale);\n warnings.push(\n createIssue({\n severity: \"warning\",\n code: \"empty-locale-registration\",\n message: `This operation only registers an empty \"${normalized.locale}\" locale. It does not complete a request to localize or translate existing respondent-facing content; continue with real translation operations unless the user explicitly requested an empty registration.`,\n operationIndex,\n operationId,\n }),\n );\n break;\n case \"remove-survey-locale\":\n if (!plannedLocales.has(normalized.locale)) {\n issues.push(\n createIssue({\n code: \"survey-locale-not-found\",\n message: `Locale \"${normalized.locale}\" is not present in the survey.`,\n operationIndex,\n operationId,\n }),\n );\n return;\n }\n plannedLocales.delete(normalized.locale);\n break;\n case \"update-image-asset-metadata\":\n case \"remove-image-asset\":\n if (!snapshot.survey.assets?.[normalized.assetId]) {\n issues.push(\n createIssue({\n code: \"image-asset-not-found\",\n message: `Image asset \"${normalized.assetId}\" was not found.`,\n operationIndex,\n operationId,\n }),\n );\n return;\n }\n break;\n case \"set-image-asset\":\n case \"update-survey-pagination\":\n break;\n }\n normalizedOperations.push(normalized);\n return;\n }\n\n const item = resolveRawItemByIdentifier({\n identifier: getOperationTarget(operation),\n indexById,\n outlineById,\n rawItemsById,\n });\n\n if (!item) {\n issues.push(\n createIssue({\n code: \"item-not-found\",\n message: `No survey item matching \"${getOperationTarget(operation)}\" was found.`,\n operationIndex,\n operationId,\n }),\n );\n return;\n }\n\n const deletedAncestorId = getDeletedAncestor(item.itemId, parentByChildId, deletedItemIds);\n if (deletedItemIds.has(item.itemId) || deletedAncestorId) {\n issues.push(\n createIssue({\n code: \"target-already-removed\",\n message: `The operation targets an item that is already removed earlier in this proposal.`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n return;\n }\n\n const { rawItem } = item;\n const rawNormalized = normalizeOperation(operation, item.itemId);\n const normalized =\n rawNormalized.kind === \"update-item-translation\" ||\n rawNormalized.kind === \"update-placed-image\"\n ? {\n ...rawNormalized,\n contentKey: normalizeContentKeyForItemType(\n rawNormalized.contentKey,\n itemTypeManifestByType.get(rawItem.itemType),\n ),\n }\n : rawNormalized.kind === \"upsert-form-field-group\" ||\n rawNormalized.kind === \"upsert-form-field\"\n ? normalizeFormOperationTranslations(rawNormalized, rawNormalized.target.optionId)\n : rawNormalized.kind === \"set-embedded-form\"\n ? normalizeEmbeddedFormAuthoringMode(\n normalizeFormOperationTranslations(rawNormalized, rawNormalized.optionId),\n )\n : rawNormalized;\n\n const itemCapability = itemTypeManifestByType.get(rawItem.itemType);\n if (!itemCapability?.supportedOperations.includes(normalized.kind)) {\n issues.push(\n createIssue({\n code: \"operation-not-supported-for-item-type\",\n message: `Item type \"${rawItem.itemType}\" does not support operation \"${normalized.kind}\".`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n return;\n }\n\n const trustedCapability = snapshot.trustedCapabilities?.byItemType.get(rawItem.itemType);\n if (trustedCapability?.supportsOperation && !trustedCapability.supportsOperation(normalized)) {\n issues.push(\n createIssue({\n code: \"operation-rejected-by-item-capability\",\n message: `The trusted capability for \"${rawItem.itemType}\" rejected operation \"${normalized.kind}\".`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n return;\n }\n\n switch (normalized.kind) {\n case \"update-item-key\": {\n if (!ITEM_KEY_PATTERN.test(normalized.key)) {\n issues.push(\n createIssue({\n code: \"invalid-item-key\",\n message: \"Item keys must contain only letters, numbers, underscores, or hyphens.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n const conflictId = getSiblingKeyConflict({\n createdKeysByParentId,\n deletedItemIds,\n itemId: item.itemId,\n key: normalized.key,\n parentByChildId,\n plannedKeys,\n rawItemsById,\n });\n\n if (conflictId) {\n issues.push(\n createIssue({\n code: \"duplicate-sibling-key\",\n message: `The key \"${normalized.key}\" is already used by sibling item \"${conflictId}\".`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n if (rawItem.key === normalized.key) {\n warnings.push(\n createIssue({\n severity: \"warning\",\n code: \"no-key-change\",\n message: `The item already has the key \"${normalized.key}\".`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n }\n\n plannedKeys.set(item.itemId, normalized.key);\n normalizedOperations.push(normalized);\n break;\n }\n case \"update-item-label\": {\n if ((rawItem.metadata?.itemLabel ?? \"\") === normalized.itemLabel) {\n warnings.push(\n createIssue({\n severity: \"warning\",\n code: \"no-label-change\",\n message: \"The item already has that editor label.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n }\n normalizedOperations.push(normalized);\n break;\n }\n case \"update-item-color\": {\n if (rawItem.metadata?.editorItemColor === normalized.color) {\n warnings.push(\n createIssue({\n severity: \"warning\",\n code: \"no-color-change\",\n message: \"The item already has that editor color.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n }\n normalizedOperations.push(normalized);\n break;\n }\n case \"update-item-translation\": {\n addIntroducedLocaleWarning({\n locale: normalized.locale,\n operationIndex,\n operationId,\n itemId: item.itemId,\n });\n\n if (normalized.contentKey.includes(\"..\")) {\n issues.push(\n createIssue({\n code: \"invalid-content-key\",\n message: \"Translation content keys cannot contain empty path segments.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n normalizedOperations.push(normalized);\n break;\n }\n case \"update-placed-image\": {\n const translations = new SurveyTranslations((snapshot.survey as RawSurvey).translations);\n const content = translations\n .getItemTranslations(item.itemId)\n ?.getContent(normalized.locale, normalized.contentKey);\n\n if (content?.type !== ContentType.richText) {\n issues.push(\n createIssue({\n code: \"placed-image-content-not-rich-text\",\n message: `Content \"${normalized.locale}:${normalized.contentKey}\" is not rich text and has no placed image to update.`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n const imageBlocks = content.doc.blocks.filter((block) => block.type === \"image\");\n const image = imageBlocks[normalized.imageIndex];\n if (!image) {\n issues.push(\n createIssue({\n code: \"placed-image-not-found\",\n message: `No image exists at imageIndex ${normalized.imageIndex} in \"${normalized.locale}:${normalized.contentKey}\". The content contains ${imageBlocks.length} image block${imageBlocks.length === 1 ? \"\" : \"s\"}.`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n if (\n normalized.expectedAssetId &&\n (image.source.type !== \"asset\" || image.source.assetId !== normalized.expectedAssetId)\n ) {\n issues.push(\n createIssue({\n code: \"placed-image-asset-mismatch\",\n message: `The selected image no longer references expected asset \"${normalized.expectedAssetId}\". Inspect the item again before changing it.`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n normalizedOperations.push(normalized);\n break;\n }\n case \"patch-item-config\": {\n let nextConfig: RawSurveyItem[\"config\"];\n try {\n nextConfig = applyJsonPatch(rawItem.config ?? {}, normalized.patches);\n } catch (error) {\n const patchError = error instanceof JsonPatchError ? error : undefined;\n issues.push(\n createIssue({\n code: patchError?.code ?? \"item-config-patch-failed\",\n message:\n error instanceof Error\n ? error.message\n : \"The item config JSON Patch could not be applied.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n const nextItem: RawSurveyItem = { ...rawItem, config: nextConfig };\n const capabilityIssues = trustedCapability?.validateItem?.(nextItem) ?? [];\n for (const issue of capabilityIssues) {\n const normalizedIssue = {\n ...issue,\n operationIndex: issue.operationIndex ?? operationIndex,\n operationId: issue.operationId ?? operationId,\n itemId: issue.itemId ?? item.itemId,\n };\n (normalizedIssue.severity === \"warning\" ? warnings : issues).push(normalizedIssue);\n }\n if (issues.some((issue) => issue.operationIndex === operationIndex)) {\n break;\n }\n\n rawItemsById.set(item.itemId, nextItem);\n normalizedOperations.push(normalized);\n break;\n }\n case \"upsert-form-field-group\": {\n const groups = getFormFieldGroupsForTarget(rawItem, normalized.target.optionId);\n if (!groups) {\n issues.push(\n createIssue({\n code: \"form-target-not-found\",\n message: normalized.target.optionId\n ? `No inline embedded form was found on choice option \"${normalized.target.optionId}\".`\n : \"Form operations require a formItem target.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n const layoutIssue = getInvalidFormLayoutIssue({\n fieldGroups: [normalized.group],\n itemId: item.itemId,\n operationId,\n operationIndex,\n prefix: normalized.target.optionId\n ? `embeddedForms.${normalized.target.optionId}.fieldGroups`\n : \"fieldGroups\",\n });\n const contentIssue = Array.isArray(normalized.group.fields)\n ? getFormOperationContentIssue({\n fieldGroups: [normalized.group],\n itemId: item.itemId,\n operationId,\n operationIndex,\n prefix: normalized.target.optionId\n ? `embeddedForms.${normalized.target.optionId}.fields`\n : \"fields\",\n snapshot,\n translations: normalized.translations,\n })\n : undefined;\n if (layoutIssue || contentIssue) {\n if (layoutIssue) issues.push(layoutIssue);\n if (contentIssue) issues.push(contentIssue);\n break;\n }\n const existingIndex = groups.findIndex((group) => group.id === normalized.group.id);\n const existing = existingIndex >= 0 ? groups[existingIndex] : undefined;\n const nextGroup = normalizeFormFieldGroupRecord({\n ...existing,\n ...normalized.group,\n fields: Array.isArray(normalized.group.fields)\n ? normalized.group.fields\n : (existing?.fields ?? []),\n });\n if (!nextGroup) break;\n const nextGroups = [...groups];\n if (existingIndex >= 0) {\n nextGroups[existingIndex] = nextGroup;\n } else {\n const insertIndex = Math.min(normalized.index ?? nextGroups.length, nextGroups.length);\n nextGroups.splice(insertIndex, 0, nextGroup);\n }\n const nextItem = withFormFieldGroupsForTarget(\n rawItem,\n nextGroups,\n normalized.target.optionId,\n );\n if (!nextItem) break;\n for (const translation of normalized.translations ?? []) {\n addIntroducedLocaleWarning({\n locale: translation.locale,\n operationIndex,\n operationId,\n itemId: item.itemId,\n });\n }\n rawItemsById.set(item.itemId, nextItem);\n normalizedOperations.push(normalized);\n break;\n }\n case \"remove-form-field-group\": {\n const groups = getFormFieldGroupsForTarget(rawItem, normalized.target.optionId);\n const groupIndex = groups?.findIndex((group) => group.id === normalized.groupId) ?? -1;\n if (!groups || groupIndex < 0) {\n issues.push(\n createIssue({\n code: \"form-field-group-not-found\",\n message: `Form field group \"${normalized.groupId}\" was not found.`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n const nextItem = withFormFieldGroupsForTarget(\n rawItem,\n groups.filter((_, index) => index !== groupIndex),\n normalized.target.optionId,\n );\n if (nextItem) rawItemsById.set(item.itemId, nextItem);\n normalizedOperations.push(normalized);\n break;\n }\n case \"reorder-form-field-groups\": {\n const groups = getFormFieldGroupsForTarget(rawItem, normalized.target.optionId);\n const groupIds = groups?.map((group) => group.id) ?? [];\n if (\n !groups ||\n normalized.groupIds.length !== groupIds.length ||\n new Set(normalized.groupIds).size !== groupIds.length ||\n normalized.groupIds.some((groupId) => !groupIds.includes(groupId))\n ) {\n issues.push(\n createIssue({\n code: \"incomplete-form-field-group-order\",\n message: \"Reordering form groups requires every existing group id exactly once.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n const byId = new Map(groups.map((group) => [group.id, group]));\n const nextItem = withFormFieldGroupsForTarget(\n rawItem,\n normalized.groupIds.map((groupId) => byId.get(groupId)!),\n normalized.target.optionId,\n );\n if (nextItem) rawItemsById.set(item.itemId, nextItem);\n normalizedOperations.push(normalized);\n break;\n }\n case \"upsert-form-field\": {\n const groups = getFormFieldGroupsForTarget(rawItem, normalized.target.optionId);\n const groupIndex = groups?.findIndex((group) => group.id === normalized.groupId) ?? -1;\n if (!groups || groupIndex < 0) {\n issues.push(\n createIssue({\n code: \"form-field-group-not-found\",\n message: `Form field group \"${normalized.groupId}\" was not found.`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n const contentIssue = getFormOperationContentIssue({\n fieldGroups: [{ fields: [normalized.field] }],\n itemId: item.itemId,\n operationId,\n operationIndex,\n prefix: normalized.target.optionId\n ? `embeddedForms.${normalized.target.optionId}.fields`\n : \"fields\",\n snapshot,\n translations: normalized.translations,\n });\n if (contentIssue) {\n issues.push(contentIssue);\n break;\n }\n const duplicateKey = groups\n .flatMap((group) => group.fields)\n .find((field) => field.id !== normalized.field.id && field.key === normalized.field.key);\n if (duplicateKey) {\n issues.push(\n createIssue({\n code: \"duplicate-form-field-key\",\n message: `Form field key \"${normalized.field.key}\" is already in use.`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n const nextGroups = groups.map((group) => ({ ...group, fields: [...group.fields] }));\n let existingField: Record<string, unknown> | undefined;\n for (const group of nextGroups) {\n const existingIndex = group.fields.findIndex((field) => field.id === normalized.field.id);\n if (existingIndex >= 0) {\n existingField = group.fields[existingIndex];\n group.fields.splice(existingIndex, 1);\n }\n }\n const targetFields = nextGroups[groupIndex].fields;\n const insertIndex = Math.min(normalized.index ?? targetFields.length, targetFields.length);\n targetFields.splice(insertIndex, 0, { ...existingField, ...normalized.field });\n const nextItem = withFormFieldGroupsForTarget(\n rawItem,\n nextGroups,\n normalized.target.optionId,\n isCompatibleSimpleFieldUpsert({\n config: getFormConfigForTarget(rawItem, normalized.target.optionId),\n groupId: normalized.groupId,\n field: normalized.field,\n index: normalized.index,\n }),\n );\n if (nextItem) rawItemsById.set(item.itemId, nextItem);\n for (const translation of normalized.translations ?? []) {\n addIntroducedLocaleWarning({\n locale: translation.locale,\n operationIndex,\n operationId,\n itemId: item.itemId,\n });\n }\n normalizedOperations.push(normalized);\n break;\n }\n case \"remove-form-field\":\n case \"move-form-field\": {\n const groups = getFormFieldGroupsForTarget(rawItem, normalized.target.optionId);\n if (!groups) {\n issues.push(\n createIssue({\n code: \"form-target-not-found\",\n message: \"The requested form or embedded form was not found.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n const nextGroups = groups.map((group) => ({ ...group, fields: [...group.fields] }));\n let foundField: Record<string, unknown> | undefined;\n for (const group of nextGroups) {\n const fieldIndex = group.fields.findIndex((field) => field.id === normalized.fieldId);\n if (fieldIndex >= 0) {\n [foundField] = group.fields.splice(fieldIndex, 1);\n break;\n }\n }\n if (!foundField) {\n issues.push(\n createIssue({\n code: \"form-field-not-found\",\n message: `Form field \"${normalized.fieldId}\" was not found.`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n if (normalized.kind === \"move-form-field\") {\n const targetGroup = nextGroups.find((group) => group.id === normalized.targetGroupId);\n if (!targetGroup) {\n issues.push(\n createIssue({\n code: \"form-field-group-not-found\",\n message: `Target form field group \"${normalized.targetGroupId}\" was not found.`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n targetGroup.fields.splice(\n Math.min(normalized.index ?? targetGroup.fields.length, targetGroup.fields.length),\n 0,\n foundField,\n );\n }\n const nextItem = withFormFieldGroupsForTarget(\n rawItem,\n nextGroups,\n normalized.target.optionId,\n );\n if (nextItem) rawItemsById.set(item.itemId, nextItem);\n normalizedOperations.push(normalized);\n break;\n }\n case \"set-embedded-form\":\n case \"remove-embedded-form\": {\n if (rawItem.itemType !== CHOICE_ITEM_TYPE) {\n issues.push(\n createIssue({\n code: \"not-choice-item\",\n message: \"Embedded forms can only target choiceItem options.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n const options = getChoiceOptionsFromRawItem(rawItem);\n const optionIndex = options.findIndex((option) => option.id === normalized.optionId);\n if (optionIndex < 0) {\n issues.push(\n createIssue({\n code: \"choice-option-not-found\",\n message: `Choice option \"${normalized.optionId}\" was not found.`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n options[optionIndex] = { ...options[optionIndex] };\n if (normalized.kind === \"set-embedded-form\") {\n const layoutIssue = getInvalidFormLayoutIssue({\n fieldGroups: normalized.form.fieldGroups,\n itemId: item.itemId,\n operationId,\n operationIndex,\n prefix: `embeddedForms.${normalized.optionId}.fieldGroups`,\n });\n const contentIssue = getFormOperationContentIssue({\n fieldGroups: normalized.form.fieldGroups,\n itemId: item.itemId,\n operationId,\n operationIndex,\n prefix: `embeddedForms.${normalized.optionId}.fields`,\n snapshot,\n translations: normalized.translations,\n });\n if (layoutIssue || contentIssue) {\n if (layoutIssue) issues.push(layoutIssue);\n if (contentIssue) issues.push(contentIssue);\n break;\n }\n options[optionIndex].embeddedForm = normalized.form;\n for (const translation of normalized.translations ?? []) {\n addIntroducedLocaleWarning({\n locale: translation.locale,\n operationIndex,\n operationId,\n itemId: item.itemId,\n });\n }\n } else {\n delete options[optionIndex].embeddedForm;\n delete options[optionIndex].embeddedFormItemId;\n }\n rawItemsById.set(item.itemId, withChoiceOptionsOnRawItem(rawItem, options));\n normalizedOperations.push(normalized);\n break;\n }\n case \"add-choice-option\": {\n const locale = normalized.locale ?? snapshot.ui.selectedLocale;\n if (rawItem.itemType !== CHOICE_ITEM_TYPE) {\n issues.push(\n createIssue({\n code: \"not-choice-item\",\n message: \"Choice option operations can only target choiceItem items.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n addIntroducedLocaleWarning({\n locale,\n operationIndex,\n operationId,\n itemId: item.itemId,\n });\n\n if (!normalized.option.label.trim()) {\n issues.push(\n createIssue({\n code: \"missing-choice-option-label\",\n message: \"A new choice option needs a non-empty respondent-visible label.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n const options = getChoiceOptionsFromRawItem(rawItem);\n const usedIds = new Set(options.map((option) => option.id));\n const usedKeys = new Set(\n options.map((option) => option.key).filter((key): key is string => Boolean(key)),\n );\n const optionId = ensureUniqueId(normalized.option.id ?? normalized.option.label, usedIds);\n const optionKey = ensureUniqueChoiceOptionKey(\n normalized.option.key ?? normalized.option.label,\n usedKeys,\n );\n const nextOption: ChoiceOptionRecord = {\n id: optionId,\n key: optionKey,\n };\n const insertIndex =\n normalized.index === undefined\n ? options.length\n : Math.min(options.length, Math.max(0, normalized.index));\n const nextOptions = [...options];\n nextOptions.splice(insertIndex, 0, nextOption);\n\n if (normalized.index !== undefined && normalized.index > options.length) {\n warnings.push(\n createIssue({\n severity: \"warning\",\n code: \"option-index-after-end\",\n message: \"The option index is after the end of the option list and will be clamped.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n }\n\n rawItemsById.set(item.itemId, withChoiceOptionsOnRawItem(rawItem, nextOptions));\n normalizedOperations.push({\n ...normalized,\n locale,\n index: insertIndex,\n option: {\n id: optionId,\n key: optionKey,\n label: normalized.option.label,\n },\n });\n break;\n }\n case \"update-choice-option-label\": {\n const locale = normalized.locale ?? snapshot.ui.selectedLocale;\n if (rawItem.itemType !== CHOICE_ITEM_TYPE) {\n issues.push(\n createIssue({\n code: \"not-choice-item\",\n message: \"Choice option operations can only target choiceItem items.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n addIntroducedLocaleWarning({\n locale,\n operationIndex,\n operationId,\n itemId: item.itemId,\n });\n\n const option = resolveChoiceOption({\n itemId: item.itemId,\n locale,\n optionRef: normalized.optionId,\n options: getChoiceOptionsFromRawItem(rawItem),\n snapshot,\n });\n\n if (!option) {\n issues.push(\n createChoiceOptionsConflictIssue({\n code: \"choice-option-not-found\",\n message: `No option matching \"${normalized.optionId}\" was found on this choice item.`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n const currentLabel = getItemTranslationText({\n contentKey: createChoiceOptionLabelContentKey(option.id),\n itemId: item.itemId,\n locale,\n snapshot,\n });\n if (currentLabel === normalized.label) {\n warnings.push(\n createIssue({\n severity: \"warning\",\n code: \"no-choice-option-label-change\",\n message: \"The option already has that label.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n }\n\n normalizedOperations.push({\n ...normalized,\n locale,\n optionId: option.id,\n });\n break;\n }\n case \"remove-choice-option\": {\n if (rawItem.itemType !== CHOICE_ITEM_TYPE) {\n issues.push(\n createIssue({\n code: \"not-choice-item\",\n message: \"Choice option operations can only target choiceItem items.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n const options = getChoiceOptionsFromRawItem(rawItem);\n const option = resolveChoiceOption({\n itemId: item.itemId,\n locale: snapshot.ui.selectedLocale,\n optionRef: normalized.optionId,\n options,\n snapshot,\n });\n\n if (!option) {\n issues.push(\n createChoiceOptionsConflictIssue({\n code: \"choice-option-not-found\",\n message: `No option matching \"${normalized.optionId}\" was found on this choice item.`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n rawItemsById.set(\n item.itemId,\n withChoiceOptionsOnRawItem(\n rawItem,\n options.filter((candidate) => candidate.id !== option.id),\n ),\n );\n normalizedOperations.push({\n ...normalized,\n optionId: option.id,\n });\n break;\n }\n case \"reorder-choice-options\": {\n if (rawItem.itemType !== CHOICE_ITEM_TYPE) {\n issues.push(\n createIssue({\n code: \"not-choice-item\",\n message: \"Choice option operations can only target choiceItem items.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n const options = getChoiceOptionsFromRawItem(rawItem);\n const resolvedOptions = normalized.optionIds.map((optionRef) =>\n resolveChoiceOption({\n itemId: item.itemId,\n locale: snapshot.ui.selectedLocale,\n optionRef,\n options,\n snapshot,\n }),\n );\n\n const missingIndex = resolvedOptions.findIndex((option) => !option);\n if (missingIndex >= 0) {\n issues.push(\n createChoiceOptionsConflictIssue({\n code: \"choice-option-not-found\",\n message: `No option matching \"${normalized.optionIds[missingIndex]}\" was found on this choice item.`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n const resolvedOptionIds = resolvedOptions.map((option) => option!.id);\n const uniqueResolvedOptionIds = new Set(resolvedOptionIds);\n if (uniqueResolvedOptionIds.size !== resolvedOptionIds.length) {\n issues.push(\n createChoiceOptionsConflictIssue({\n code: \"duplicate-choice-option-order-entry\",\n message: \"The option order contains the same option more than once.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n const existingOptionIds = new Set(options.map((option) => option.id));\n if (\n resolvedOptionIds.length !== options.length ||\n resolvedOptionIds.some((optionId) => !existingOptionIds.has(optionId))\n ) {\n issues.push(\n createChoiceOptionsConflictIssue({\n code: \"incomplete-choice-option-order\",\n message:\n \"Reordering options requires a complete order containing every existing option exactly once.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n const optionsById = new Map(options.map((option) => [option.id, option]));\n rawItemsById.set(\n item.itemId,\n withChoiceOptionsOnRawItem(\n rawItem,\n resolvedOptionIds.map((optionId) => optionsById.get(optionId)!),\n ),\n );\n normalizedOperations.push({\n ...normalized,\n optionIds: resolvedOptionIds,\n });\n break;\n }\n case \"move-item\": {\n if (isRootItem(rawItem)) {\n issues.push(\n createIssue({\n code: \"cannot-move-root\",\n message: \"The survey root item cannot be moved.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n const parent = resolveCreateParentByIdentifier({\n identifier: normalized.target.parentItemId,\n indexById,\n outlineById,\n rawItemsById,\n });\n if (!parent || parent.rawItem.itemType !== ReservedSurveyItemTypes.Group) {\n issues.push(\n createIssue({\n code: \"target-parent-not-group\",\n message: `Move target \"${normalized.target.parentItemId}\" is not an existing group.`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n if (\n item.itemId === parent.itemId ||\n collectDescendantIds(item.itemId, rawItemsById).has(parent.itemId)\n ) {\n issues.push(\n createIssue({\n code: \"move-would-create-cycle\",\n message: \"An item cannot be moved into itself or one of its descendants.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n const previousParentId = parentByChildId.get(item.itemId);\n if (previousParentId === parent.itemId) {\n issues.push(\n createIssue({\n code: \"item-already-in-target-parent\",\n message:\n \"The item is already in the target parent. Omit an unchanged placement or use reorder-items with the parent's complete child order.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n if (previousParentId) {\n const previousParent = rawItemsById.get(previousParentId);\n if (previousParent) {\n rawItemsById.set(previousParentId, {\n ...previousParent,\n config: {\n ...(isRecord(previousParent.config) ? previousParent.config : {}),\n items: getGroupChildren(previousParent).filter(\n (childId) => childId !== item.itemId,\n ),\n },\n });\n }\n }\n const nextChildren = getGroupChildren(parent.rawItem).filter(\n (childId) => childId !== item.itemId,\n );\n nextChildren.splice(\n Math.min(normalized.target.index ?? nextChildren.length, nextChildren.length),\n 0,\n item.itemId,\n );\n rawItemsById.set(parent.itemId, {\n ...parent.rawItem,\n config: {\n ...(isRecord(parent.rawItem.config) ? parent.rawItem.config : {}),\n items: nextChildren,\n },\n });\n parentByChildId.set(item.itemId, parent.itemId);\n normalizedOperations.push({\n ...normalized,\n target: { ...normalized.target, parentItemId: parent.itemId },\n });\n break;\n }\n case \"reorder-items\": {\n if (rawItem.itemType !== ReservedSurveyItemTypes.Group) {\n issues.push(\n createIssue({\n code: \"target-parent-not-group\",\n message: \"Only group children can be reordered.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n const currentChildren = getGroupChildren(rawItem);\n const resolvedChildren = normalized.itemIds.map((itemRef) =>\n resolveRawItemByIdentifier({\n identifier: itemRef,\n indexById,\n outlineById,\n rawItemsById,\n }),\n );\n const resolvedIds = resolvedChildren.map((child) => child?.itemId);\n if (\n resolvedIds.some((childId) => !childId) ||\n resolvedIds.length !== currentChildren.length ||\n new Set(resolvedIds).size !== currentChildren.length ||\n resolvedIds.some((childId) => !currentChildren.includes(childId!))\n ) {\n issues.push(\n createIssue({\n code: \"incomplete-item-order\",\n message:\n \"Reordering group children requires every existing direct child exactly once.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n rawItemsById.set(item.itemId, {\n ...rawItem,\n config: {\n ...(isRecord(rawItem.config) ? rawItem.config : {}),\n items: resolvedIds as string[],\n },\n });\n normalizedOperations.push({ ...normalized, itemIds: resolvedIds as string[] });\n break;\n }\n case \"remove-item\": {\n if (isRootItem(rawItem)) {\n issues.push(\n createIssue({\n code: \"cannot-remove-root\",\n message: \"The survey root item cannot be removed.\",\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n const descendantIds = collectDescendantIds(item.itemId, rawItemsById);\n if (descendantIds.size > 0 && !normalized.includeChildren) {\n issues.push(\n createIssue({\n code: \"remove-would-delete-children\",\n message: `Removing this item would also remove ${descendantIds.size} child item(s). Set includeChildren to true if that is intended.`,\n operationIndex,\n operationId,\n itemId: item.itemId,\n }),\n );\n break;\n }\n\n deletedItemIds.add(item.itemId);\n for (const descendantId of descendantIds) {\n deletedItemIds.add(descendantId);\n }\n normalizedOperations.push(normalized);\n break;\n }\n }\n });\n\n return {\n valid: issues.length === 0,\n issues,\n warnings,\n normalizedOperations,\n };\n};\n\nconst buildDraftContent = ({\n content,\n plainText,\n}: {\n content?: Content;\n plainText?: string;\n}): Content =>\n content\n ? structuredCloneMethod(content)\n : {\n type: ContentType.md,\n content: plainText ?? \"\",\n };\n\nconst updateDraftItemTranslations = ({\n itemId,\n survey,\n translations,\n}: {\n itemId: string;\n survey: RawSurvey;\n translations?: Array<{\n locale: string;\n contentKey: string;\n content?: Content;\n plainText?: string;\n }>;\n}) => {\n if (!translations?.length) return;\n const surveyTranslations = new SurveyTranslations(survey.translations);\n const itemTranslations =\n surveyTranslations.getItemTranslations(itemId)?.clone() ?? new SurveyItemTranslations();\n for (const translation of translations) {\n itemTranslations.setContent(\n translation.locale,\n translation.contentKey,\n buildDraftContent(translation),\n );\n }\n surveyTranslations.setItemTranslations(itemId, itemTranslations);\n survey.translations = surveyTranslations.serialize();\n};\n\nconst removeDraftTranslationPrefix = ({\n itemId,\n prefix,\n survey,\n}: {\n itemId: string;\n prefix: string;\n survey: RawSurvey;\n}) => {\n const surveyTranslations = new SurveyTranslations(survey.translations);\n const itemTranslations = surveyTranslations.getItemTranslations(itemId)?.clone();\n if (!itemTranslations) return;\n itemTranslations.removeContentKeysWithPrefix(prefix);\n surveyTranslations.setItemTranslations(itemId, itemTranslations.compact());\n survey.translations = surveyTranslations.serialize();\n};\n\n/**\n * Applies already-normalized, validated operations to a request-local raw\n * survey. This is simulation only; the editor remains the final mutation and\n * undo/redo owner.\n */\nexport const applyValidatedSurveyOperationsToDraft = ({\n operations,\n survey: inputSurvey,\n}: {\n operations: SurveyOperation[];\n survey: RawSurvey;\n}): RawSurvey => {\n let survey = structuredCloneMethod(inputSurvey);\n\n const getItem = (itemId: string) => {\n const item = survey.surveyItems.find((candidate) => candidate.id === itemId);\n if (!item) throw new Error(`Draft item \"${itemId}\" was not found.`);\n return item;\n };\n const replaceItem = (item: RawSurveyItem) => {\n const index = survey.surveyItems.findIndex((candidate) => candidate.id === item.id);\n if (index < 0) throw new Error(`Draft item \"${item.id}\" was not found.`);\n survey.surveyItems[index] = item;\n };\n\n for (const operation of operations) {\n if (operation.kind === \"survey-json-patch\") {\n survey = applyJsonPatch(survey, operation.patches);\n continue;\n }\n\n switch (operation.kind) {\n case \"create-item\": {\n const item = structuredCloneMethod(operation.item) as RawSurveyItem;\n survey.surveyItems.push(item);\n const parent = getItem(operation.target.parentItemId);\n const children = getGroupChildren(parent);\n children.splice(\n Math.min(operation.target.index ?? children.length, children.length),\n 0,\n item.id,\n );\n replaceItem({\n ...parent,\n config: {\n ...(isRecord(parent.config) ? parent.config : {}),\n items: children,\n },\n });\n updateDraftItemTranslations({\n itemId: item.id,\n survey,\n translations: operation.translations,\n });\n break;\n }\n case \"update-item-key\":\n replaceItem({ ...getItem(operation.itemId), key: operation.key });\n break;\n case \"update-item-label\": {\n const item = getItem(operation.itemId);\n const metadata = { ...(item.metadata ?? {}) };\n if (operation.itemLabel) metadata.itemLabel = operation.itemLabel;\n else delete metadata.itemLabel;\n replaceItem({\n ...item,\n metadata: Object.keys(metadata).length ? metadata : undefined,\n });\n break;\n }\n case \"update-item-color\": {\n const item = getItem(operation.itemId);\n replaceItem({\n ...item,\n metadata: { ...(item.metadata ?? {}), editorItemColor: operation.color },\n });\n break;\n }\n case \"update-item-translation\":\n updateDraftItemTranslations({\n itemId: operation.itemId,\n survey,\n translations: [operation],\n });\n break;\n case \"update-placed-image\": {\n const surveyTranslations = new SurveyTranslations(survey.translations);\n const itemTranslations =\n surveyTranslations.getItemTranslations(operation.itemId)?.clone() ??\n new SurveyItemTranslations();\n const content = itemTranslations.getContent(operation.locale, operation.contentKey);\n if (content?.type !== ContentType.richText) {\n throw new Error(\"Draft image placement is not rich text.\");\n }\n let imageIndex = -1;\n const blocks = content.doc.blocks.map((block) => {\n if (block.type !== \"image\") return block;\n imageIndex += 1;\n if (imageIndex !== operation.imageIndex) return block;\n const next = structuredCloneMethod(block);\n const changes = operation.changes;\n if (changes.source !== undefined) next.source = changes.source;\n if (changes.alt !== undefined) {\n if (changes.alt === null) delete next.alt;\n else next.alt = changes.alt;\n }\n if (changes.caption !== undefined) {\n if (changes.caption === null || changes.caption.length === 0) delete next.caption;\n else {\n next.caption = [\n {\n type: \"paragraph\",\n children: [{ type: \"text\", text: changes.caption }],\n },\n ];\n }\n }\n const size = { ...(next.size ?? {}) };\n for (const key of [\"width\", \"height\", \"maxWidth\", \"maxHeight\"] as const) {\n const value = changes[key];\n if (value === null) delete size[key];\n else if (value !== undefined) size[key] = value;\n }\n if (Object.keys(size).length) next.size = size;\n else delete next.size;\n if (changes.alignment === null) delete next.alignment;\n else if (changes.alignment !== undefined) next.alignment = changes.alignment;\n return next;\n });\n itemTranslations.setContent(operation.locale, operation.contentKey, {\n ...content,\n doc: { ...content.doc, blocks },\n });\n surveyTranslations.setItemTranslations(operation.itemId, itemTranslations);\n survey.translations = surveyTranslations.serialize();\n break;\n }\n case \"patch-item-config\": {\n const item = getItem(operation.itemId);\n replaceItem({\n ...item,\n config: applyJsonPatch(item.config ?? {}, operation.patches),\n });\n break;\n }\n case \"add-choice-option\": {\n const item = getItem(operation.itemId);\n const options = getChoiceOptionsFromRawItem(item);\n options.splice(operation.index ?? options.length, 0, {\n id: operation.option.id!,\n ...(operation.option.key ? { key: operation.option.key } : {}),\n });\n replaceItem(withChoiceOptionsOnRawItem(item, options));\n updateDraftItemTranslations({\n itemId: item.id,\n survey,\n translations: [\n {\n locale: operation.locale ?? \"en\",\n contentKey: createChoiceOptionLabelContentKey(operation.option.id!),\n plainText: operation.option.label,\n },\n ],\n });\n break;\n }\n case \"update-choice-option-label\":\n updateDraftItemTranslations({\n itemId: operation.itemId,\n survey,\n translations: [\n {\n locale: operation.locale ?? \"en\",\n contentKey: createChoiceOptionLabelContentKey(operation.optionId),\n plainText: operation.label,\n },\n ],\n });\n break;\n case \"remove-choice-option\": {\n const item = getItem(operation.itemId);\n replaceItem(\n withChoiceOptionsOnRawItem(\n item,\n getChoiceOptionsFromRawItem(item).filter((option) => option.id !== operation.optionId),\n ),\n );\n removeDraftTranslationPrefix({\n itemId: item.id,\n prefix: `options.${operation.optionId}`,\n survey,\n });\n removeDraftTranslationPrefix({\n itemId: item.id,\n prefix: `embeddedForms.${operation.optionId}`,\n survey,\n });\n break;\n }\n case \"reorder-choice-options\": {\n const item = getItem(operation.itemId);\n const options = new Map(\n getChoiceOptionsFromRawItem(item).map((option) => [option.id, option]),\n );\n replaceItem(\n withChoiceOptionsOnRawItem(\n item,\n operation.optionIds.map((optionId) => options.get(optionId)!),\n ),\n );\n break;\n }\n case \"set-embedded-form\":\n case \"remove-embedded-form\": {\n const item = getItem(operation.itemId);\n const options = getChoiceOptionsFromRawItem(item);\n const optionIndex = options.findIndex((option) => option.id === operation.optionId);\n const option = { ...options[optionIndex] };\n if (operation.kind === \"set-embedded-form\") option.embeddedForm = operation.form;\n else {\n delete option.embeddedForm;\n delete option.embeddedFormItemId;\n }\n options[optionIndex] = option;\n replaceItem(withChoiceOptionsOnRawItem(item, options));\n if (operation.kind === \"set-embedded-form\") {\n updateDraftItemTranslations({\n itemId: item.id,\n survey,\n translations: operation.translations,\n });\n } else {\n removeDraftTranslationPrefix({\n itemId: item.id,\n prefix: `embeddedForms.${operation.optionId}`,\n survey,\n });\n }\n break;\n }\n case \"upsert-form-field-group\":\n case \"remove-form-field-group\":\n case \"reorder-form-field-groups\":\n case \"upsert-form-field\":\n case \"remove-form-field\":\n case \"move-form-field\": {\n const item = getItem(operation.target.itemId);\n let groups = getFormFieldGroupsForTarget(item, operation.target.optionId) ?? [];\n groups = groups.map((group) => ({ ...group, fields: [...group.fields] }));\n if (operation.kind === \"upsert-form-field-group\") {\n const index = groups.findIndex((group) => group.id === operation.group.id);\n const group = normalizeFormFieldGroupRecord({\n ...(index >= 0 ? groups[index] : {}),\n ...operation.group,\n })!;\n if (index >= 0) groups[index] = group;\n else groups.splice(operation.index ?? groups.length, 0, group);\n updateDraftItemTranslations({\n itemId: item.id,\n survey,\n translations: operation.translations,\n });\n } else if (operation.kind === \"remove-form-field-group\") {\n groups = groups.filter((group) => group.id !== operation.groupId);\n removeDraftTranslationPrefix({\n itemId: item.id,\n prefix: `${operation.target.optionId ? `embeddedForms.${operation.target.optionId}.` : \"\"}fieldGroups.${operation.groupId}`,\n survey,\n });\n } else if (operation.kind === \"reorder-form-field-groups\") {\n const byId = new Map(groups.map((group) => [group.id, group]));\n groups = operation.groupIds.map((groupId) => byId.get(groupId)!);\n } else if (operation.kind === \"upsert-form-field\") {\n let field: Record<string, unknown> | undefined;\n for (const group of groups) {\n const index = group.fields.findIndex(\n (candidate) => candidate.id === operation.field.id,\n );\n if (index >= 0) [field] = group.fields.splice(index, 1);\n }\n const group = groups.find((candidate) => candidate.id === operation.groupId)!;\n group.fields.splice(operation.index ?? group.fields.length, 0, {\n ...field,\n ...operation.field,\n });\n updateDraftItemTranslations({\n itemId: item.id,\n survey,\n translations: operation.translations,\n });\n } else {\n let field: Record<string, unknown> | undefined;\n for (const group of groups) {\n const index = group.fields.findIndex((candidate) => candidate.id === operation.fieldId);\n if (index >= 0) [field] = group.fields.splice(index, 1);\n }\n if (operation.kind === \"move-form-field\") {\n const group = groups.find((candidate) => candidate.id === operation.targetGroupId)!;\n group.fields.splice(operation.index ?? group.fields.length, 0, field!);\n } else {\n removeDraftTranslationPrefix({\n itemId: item.id,\n prefix: `${operation.target.optionId ? `embeddedForms.${operation.target.optionId}.` : \"\"}fields.${operation.fieldId}`,\n survey,\n });\n }\n }\n replaceItem(\n withFormFieldGroupsForTarget(\n item,\n groups,\n operation.target.optionId,\n operation.kind === \"upsert-form-field\" &&\n isCompatibleSimpleFieldUpsert({\n config: getFormConfigForTarget(item, operation.target.optionId),\n groupId: operation.groupId,\n field: operation.field,\n index: operation.index,\n }),\n )!,\n );\n break;\n }\n case \"remove-item\": {\n const removeIds = collectDescendantIds(\n operation.itemId,\n new Map(survey.surveyItems.map((item) => [item.id, item])),\n );\n removeIds.add(operation.itemId);\n survey.surveyItems = survey.surveyItems\n .filter((item) => !removeIds.has(item.id))\n .map((item) => ({\n ...item,\n config: isRecord(item.config)\n ? {\n ...item.config,\n items: getGroupChildren(item).filter((id) => !removeIds.has(id)),\n }\n : item.config,\n }));\n const translations = new SurveyTranslations(survey.translations);\n for (const itemId of removeIds) translations.setItemTranslations(itemId, undefined);\n survey.translations = translations.serialize();\n break;\n }\n case \"move-item\": {\n const itemId = operation.itemId;\n for (const item of survey.surveyItems) {\n const children = getGroupChildren(item);\n if (!children.includes(itemId)) continue;\n replaceItem({\n ...item,\n config: {\n ...(isRecord(item.config) ? item.config : {}),\n items: children.filter((id) => id !== itemId),\n },\n });\n }\n const parent = getItem(operation.target.parentItemId);\n const children = getGroupChildren(parent);\n children.splice(operation.target.index ?? children.length, 0, itemId);\n replaceItem({\n ...parent,\n config: { ...(isRecord(parent.config) ? parent.config : {}), items: children },\n });\n break;\n }\n case \"reorder-items\": {\n const parent = getItem(operation.parentItemId);\n replaceItem({\n ...parent,\n config: {\n ...(isRecord(parent.config) ? parent.config : {}),\n items: operation.itemIds,\n },\n });\n break;\n }\n case \"update-survey-metadata\": {\n const metadata = { ...(survey.metadata ?? {}) };\n for (const [key, value] of Object.entries(operation.values)) {\n if (value === null) delete metadata[key];\n else metadata[key] = value;\n }\n survey.metadata = Object.keys(metadata).length ? metadata : undefined;\n break;\n }\n case \"update-survey-pagination\":\n survey.maxItemsPerPage = operation.value ?? undefined;\n break;\n case \"update-survey-translation\": {\n const locale = survey.translations?.[operation.locale] ?? {};\n const surface = {\n ...(locale[operation.surface] ?? {}),\n } as Record<string, Content>;\n surface[operation.contentKey] = buildDraftContent(operation);\n survey.translations = {\n ...(survey.translations ?? {}),\n [operation.locale]: { ...locale, [operation.surface]: surface },\n };\n break;\n }\n case \"add-survey-locale\":\n survey.translations = {\n ...(survey.translations ?? {}),\n [operation.locale]: {},\n };\n break;\n case \"remove-survey-locale\": {\n const translations = { ...(survey.translations ?? {}) };\n delete translations[operation.locale];\n survey.translations = Object.keys(translations).length ? translations : undefined;\n break;\n }\n case \"set-image-asset\":\n survey.assets = { ...(survey.assets ?? {}), [operation.assetId]: operation.asset };\n break;\n case \"update-image-asset-metadata\": {\n const asset = survey.assets?.[operation.assetId]!;\n const metadata = { ...(asset.metadata ?? {}) };\n for (const [key, value] of Object.entries(operation.metadata)) {\n if (value === null) delete metadata[key as keyof typeof metadata];\n else if (value !== undefined) Object.assign(metadata, { [key]: value });\n }\n survey.assets = {\n ...(survey.assets ?? {}),\n [operation.assetId]: {\n ...asset,\n metadata: Object.keys(metadata).length ? metadata : undefined,\n },\n };\n break;\n }\n case \"remove-image-asset\": {\n const assets = { ...(survey.assets ?? {}) };\n delete assets[operation.assetId];\n survey.assets = Object.keys(assets).length ? assets : undefined;\n break;\n }\n }\n }\n\n return rawSurveyDocumentSchema.parse(survey);\n};\n\nexport const createSurveyChangeSet = ({\n maxOperations,\n operations,\n snapshot,\n summary,\n turnId,\n}: {\n maxOperations?: number;\n operations: SurveyOperation[];\n snapshot: SurveyAssistantEngineContext | SurveyDocumentSnapshot | undefined;\n summary: string;\n turnId: string;\n}): SurveyChangeSet => {\n const validation = validateSurveyOperations({ maxOperations, operations, snapshot });\n\n return {\n protocolVersion: SURVEY_ASSISTANT_PROTOCOL_VERSION,\n id: globalThis.crypto.randomUUID(),\n turnId,\n status: validation.valid ? \"validated\" : \"rejected\",\n summary: normalizeSummary(summary),\n operations: validation.normalizedOperations,\n precondition: snapshot ? buildSurveyDocumentVersion(snapshot) : undefined,\n validation,\n createdAt: new Date().toISOString(),\n };\n};\n","import { getContentPlainText, type RawSurveyItem } from \"@case-framework/survey-core\";\nimport type { SurveyAssistantEngineContext } from \"./context\";\n\nexport type SurveyAuditSeverity = \"error\" | \"warning\" | \"info\";\nexport type SurveyAuditCategory =\n | \"structure\"\n | \"content\"\n | \"localization\"\n | \"logic\"\n | \"responses\"\n | \"assets\"\n | \"quality\";\n\nexport interface SurveyAuditFinding {\n code: string;\n severity: SurveyAuditSeverity;\n category: SurveyAuditCategory;\n message: string;\n itemId?: string;\n locale?: string;\n contentKey?: string;\n suggestion?: string;\n}\n\nexport interface SurveyQualityReviewPrinciple {\n id: string;\n title: string;\n prompt: string;\n}\n\nexport interface SurveyAuditReport {\n summary: Record<SurveyAuditSeverity, number> & { total: number };\n findingCount: number;\n truncated: boolean;\n metrics: {\n itemCount: number;\n localeCount: number;\n responseSlotCount: number;\n assetCount: number;\n itemTypes: Record<string, number>;\n };\n findings: SurveyAuditFinding[];\n qualityReviewPrinciples: SurveyQualityReviewPrinciple[];\n note: string;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\nconst records = (value: unknown) => (Array.isArray(value) ? value.filter(isRecord) : []);\nconst strings = (value: unknown) =>\n Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === \"string\") : [];\n\nconst QUALITY_PRINCIPLES: SurveyQualityReviewPrinciple[] = [\n { id: \"purpose-alignment\", title: \"Purpose and construct alignment\", prompt: \"Does every question serve a stated objective, and does it measure the intended construct?\" },\n { id: \"cognitive-burden\", title: \"Respondent burden\", prompt: \"Is the survey as short and cognitively simple as its purpose allows?\" },\n { id: \"question-wording\", title: \"Clear, neutral wording\", prompt: \"Are questions specific, neutral, answerable, and limited to one idea without assumptions or double negatives?\" },\n { id: \"recall\", title: \"Recall and reference periods\", prompt: \"Are recall periods explicit, realistic, and consistent with what respondents can remember?\" },\n { id: \"response-options\", title: \"Response option quality\", prompt: \"Are options mutually exclusive, collectively sufficient, balanced, ordered, and consistently scaled?\" },\n { id: \"flow\", title: \"Flow and completeness\", prompt: \"Does the order move logically from easy/general to specific, with needed instructions and no important objective omitted?\" },\n { id: \"routing\", title: \"Requiredness and routing\", prompt: \"Do required fields, branching, validation, and not-applicable paths avoid forcing inaccurate answers?\" },\n { id: \"sensitivity\", title: \"Sensitivity and ethics\", prompt: \"Are sensitive questions justified, respectfully phrased, appropriately optional, and paired with privacy context where needed?\" },\n { id: \"accessibility\", title: \"Accessibility and inclusion\", prompt: \"Is language plain and inclusive, and are content, controls, and images understandable without avoidable barriers?\" },\n { id: \"localization\", title: \"Cross-language equivalence\", prompt: \"Do translations preserve meaning and cultural relevance rather than merely matching words?\" },\n { id: \"testing\", title: \"Testing and validation\", prompt: \"Has the instrument been cognitively tested, piloted, and checked for reliability or validity where the intended use requires it?\" },\n];\n\nconst translationText = (\n context: SurveyAssistantEngineContext,\n locale: string,\n itemId: string,\n contentKey: string,\n) => {\n const localeTranslations = isRecord(context.survey.translations?.[locale])\n ? context.survey.translations?.[locale]\n : undefined;\n const itemTranslations = isRecord(localeTranslations?.itemTranslations)\n ? localeTranslations.itemTranslations\n : undefined;\n const itemContent = isRecord(itemTranslations?.[itemId]) ? itemTranslations[itemId] : undefined;\n const content = itemContent?.[contentKey];\n return content ? getContentPlainText(content as never).trim() : \"\";\n};\n\nconst getGroups = (item: RawSurveyItem, optionId?: string) => {\n const config = isRecord(item.config) ? item.config : {};\n if (!optionId) return records(config.fieldGroups);\n const option = records(config.options).find((entry) => entry.id === optionId);\n return records(isRecord(option?.embeddedForm) ? option.embeddedForm.fieldGroups : undefined);\n};\n\nexport const auditSurvey = (\n context: SurveyAssistantEngineContext,\n options: { sourceLocale?: string; targetLocales?: string[]; maxFindings?: number } = {},\n): SurveyAuditReport => {\n const findings: SurveyAuditFinding[] = [];\n const add = (finding: SurveyAuditFinding) => findings.push(finding);\n const items = context.survey.surveyItems;\n const itemsById = new Map<string, RawSurveyItem>();\n const parentById = new Map<string, string>();\n const itemTypes: Record<string, number> = {};\n\n for (const item of items) {\n itemTypes[item.itemType] = (itemTypes[item.itemType] ?? 0) + 1;\n if (itemsById.has(item.id)) add({ code: \"duplicate-item-id\", severity: \"error\", category: \"structure\", itemId: item.id, message: `Item id \"${item.id}\" is duplicated.` });\n itemsById.set(item.id, item);\n }\n\n for (const parent of items) {\n const seenChildren = new Set<string>();\n for (const childId of strings(isRecord(parent.config) ? parent.config.items : undefined)) {\n if (seenChildren.has(childId)) add({ code: \"duplicate-child-reference\", severity: \"error\", category: \"structure\", itemId: parent.id, message: `Child \"${childId}\" is listed more than once.` });\n seenChildren.add(childId);\n if (!itemsById.has(childId)) add({ code: \"missing-child\", severity: \"error\", category: \"structure\", itemId: parent.id, message: `Referenced child \"${childId}\" does not exist.` });\n else if (parentById.has(childId)) add({ code: \"multiple-parents\", severity: \"error\", category: \"structure\", itemId: childId, message: `Item is referenced by multiple parents.` });\n else parentById.set(childId, parent.id);\n }\n }\n\n const roots = items.filter((item) => !parentById.has(item.id));\n if (roots.length !== 1) add({ code: \"root-count\", severity: \"error\", category: \"structure\", message: `Expected one survey root but found ${roots.length}.` });\n\n for (const parent of items) {\n const siblingKeys = new Map<string, string>();\n for (const childId of strings(isRecord(parent.config) ? parent.config.items : undefined)) {\n const child = itemsById.get(childId);\n if (!child) continue;\n const existing = siblingKeys.get(child.key);\n if (existing) add({ code: \"duplicate-sibling-key\", severity: \"error\", category: \"structure\", itemId: child.id, message: `Key \"${child.key}\" duplicates sibling \"${existing}\".` });\n siblingKeys.set(child.key, child.id);\n }\n }\n\n const locales = context.inspection.locales;\n const sourceLocale = options.sourceLocale ?? context.ui.selectedLocale ?? locales[0];\n const targetLocales = options.targetLocales ?? locales.filter((locale) => locale !== sourceLocale);\n const manifests = new Map(context.capabilities.itemTypes.map((entry) => [entry.itemType, entry]));\n\n for (const item of items) {\n const manifest = manifests.get(item.itemType);\n if (!manifest) {\n add({ code: \"unsupported-item-type\", severity: \"warning\", category: \"structure\", itemId: item.id, message: `Item type \"${item.itemType}\" is not advertised by the active editor.` });\n continue;\n }\n for (const surface of manifest.contentSurfaces.filter((entry) => entry.requiredOnCreate && !entry.pattern)) {\n if (!translationText(context, sourceLocale, item.id, surface.key)) add({ code: \"missing-primary-content\", severity: \"warning\", category: \"content\", itemId: item.id, locale: sourceLocale, contentKey: surface.key, message: `Required respondent content \"${surface.key}\" is empty in ${sourceLocale}.` });\n }\n const sourceContent = isRecord(context.survey.translations?.[sourceLocale]?.itemTranslations?.[item.id])\n ? context.survey.translations?.[sourceLocale]?.itemTranslations?.[item.id]\n : {};\n for (const [contentKey, content] of Object.entries(sourceContent ?? {})) {\n if (!getContentPlainText(content).trim()) continue;\n for (const locale of targetLocales) {\n if (!translationText(context, locale, item.id, contentKey)) add({ code: \"missing-translation\", severity: \"warning\", category: \"localization\", itemId: item.id, locale, contentKey, message: `Content \"${contentKey}\" has source text but no ${locale} translation.` });\n }\n }\n\n const config = isRecord(item.config) ? item.config : {};\n if (item.itemType === \"choiceItem\") {\n const optionsList = records(config.options);\n if (optionsList.length === 0) add({ code: \"choice-without-options\", severity: \"error\", category: \"content\", itemId: item.id, message: \"Choice item has no options.\" });\n for (const option of optionsList) {\n if (typeof option.id === \"string\" && !translationText(context, sourceLocale, item.id, `options.${option.id}.label`)) add({ code: \"missing-option-label\", severity: \"warning\", category: \"content\", itemId: item.id, locale: sourceLocale, contentKey: `options.${option.id}.label`, message: `Choice option \"${option.id}\" has no visible label.` });\n if (typeof option.id === \"string\" && option.embeddedForm) {\n for (const group of getGroups(item, option.id)) {\n for (const field of records(group.fields)) {\n if (typeof field.id === \"string\" && !translationText(context, sourceLocale, item.id, `embeddedForms.${option.id}.fields.${field.id}.label`)) add({ code: \"missing-field-label\", severity: \"warning\", category: \"content\", itemId: item.id, locale: sourceLocale, contentKey: `embeddedForms.${option.id}.fields.${field.id}.label`, message: `Embedded field \"${field.id}\" has no visible label.` });\n }\n }\n }\n }\n }\n if (item.itemType === \"formItem\") {\n const groups = getGroups(item);\n if (groups.length === 0) add({ code: \"form-without-groups\", severity: \"error\", category: \"content\", itemId: item.id, message: \"Form item has no field groups.\" });\n for (const group of groups) for (const field of records(group.fields)) {\n if (typeof field.id === \"string\" && !translationText(context, sourceLocale, item.id, `fields.${field.id}.label`)) add({ code: \"missing-field-label\", severity: \"warning\", category: \"content\", itemId: item.id, locale: sourceLocale, contentKey: `fields.${field.id}.label`, message: `Form field \"${field.id}\" has no visible label.` });\n }\n }\n }\n\n const assets = context.survey.assets ?? {};\n for (const [assetId, asset] of Object.entries(assets)) {\n const metadata = isRecord(asset.metadata) ? asset.metadata : {};\n if (asset.kind === \"image\" && typeof metadata.alt !== \"string\") add({ code: \"missing-image-alt\", severity: \"warning\", category: \"assets\", message: `Image asset \"${assetId}\" has no alternative text.`, suggestion: \"Add concise alt text, or an empty alt value when the image is purely decorative.\" });\n }\n\n const limited = findings.slice(0, options.maxFindings ?? 200);\n const summary = findings.reduce<Record<SurveyAuditSeverity, number> & { total: number }>((acc, entry) => {\n acc[entry.severity] += 1;\n acc.total += 1;\n return acc;\n }, { error: 0, warning: 0, info: 0, total: 0 });\n\n return {\n summary,\n findingCount: findings.length,\n truncated: limited.length < findings.length,\n metrics: { itemCount: context.inspection.itemCount, localeCount: locales.length, responseSlotCount: context.inspection.responseSlots.length, assetCount: Object.keys(assets).length, itemTypes },\n findings: limited,\n qualityReviewPrinciples: QUALITY_PRINCIPLES,\n note: \"Technical findings are deterministic. Quality principles are a structured review rubric; apply them with human/model judgment and domain context, and do not present them as psychometric validation.\",\n };\n};\n","import {\n SURVEY_ASSISTANT_PROTOCOL_VERSION,\n surveyChangeSetSchema,\n surveyAssistantTurnFinalSchema,\n type SurveyAssistantTurnFinal,\n type SurveyChangeSet,\n type SurveyDocumentSnapshot,\n type SurveyOperation,\n} from \"../protocol\";\nimport { SurveyTranslations, getContentPlainText, type Content } from \"@case-framework/survey-core\";\nimport {\n MAX_SURVEY_ASSISTANT_OPERATIONS_PER_TURN_DRAFT,\n applyValidatedSurveyOperationsToDraft,\n createSurveyChangeSet,\n} from \"./operations\";\nimport { auditSurvey, type SurveyAuditFinding } from \"./audit\";\nimport { createSurveyAssistantEngineContext, type SurveyAssistantEngineContext } from \"./context\";\n\nconst createId = () => globalThis.crypto.randomUUID();\n\nconst operationTargets = (operation: SurveyOperation): string[] => {\n switch (operation.kind) {\n case \"create-item\":\n return [`item:${operation.item.id}`];\n case \"update-item-key\":\n case \"update-item-label\":\n case \"update-item-color\":\n case \"update-item-translation\":\n case \"update-placed-image\":\n case \"patch-item-config\":\n case \"add-choice-option\":\n case \"update-choice-option-label\":\n case \"remove-choice-option\":\n case \"reorder-choice-options\":\n case \"set-embedded-form\":\n case \"remove-embedded-form\":\n case \"remove-item\":\n case \"move-item\":\n return [`item:${operation.itemId}`];\n case \"upsert-form-field-group\":\n case \"remove-form-field-group\":\n case \"reorder-form-field-groups\":\n case \"upsert-form-field\":\n case \"remove-form-field\":\n case \"move-form-field\":\n return [`item:${operation.target.itemId}`];\n case \"reorder-items\":\n return [`item:${operation.parentItemId}`];\n case \"set-image-asset\":\n case \"update-image-asset-metadata\":\n case \"remove-image-asset\":\n return [`asset:${operation.assetId}`];\n case \"update-survey-metadata\":\n case \"update-survey-pagination\":\n case \"update-survey-translation\":\n case \"add-survey-locale\":\n case \"remove-survey-locale\":\n return [\"survey\"];\n case \"survey-json-patch\":\n return operation.patches.map((patch) => `path:${patch.path}`);\n }\n};\n\nconst collectOperationTargets = (operations: SurveyOperation[]) =>\n new Set(operations.flatMap(operationTargets));\n\nconst MAX_POST_CHANGE_TARGETS = 16;\nconst MAX_POST_CHANGE_ITEMS = 6;\nconst MAX_POST_CHANGE_TRANSLATIONS = 12;\nconst MAX_POST_CHANGE_RESPONSE_SLOTS = 12;\nconst MAX_POST_CHANGE_TEXT_CHARS = 100;\nconst MAX_VERIFICATION_AUDIT_FINDINGS = 8;\nconst MAX_VERIFICATION_MESSAGE_CHARS = 240;\nconst SUBSTANTIAL_CHANGE_ITEM_COUNT = 6;\nconst SUBSTANTIAL_CHANGE_OPERATION_COUNT = 12;\n\nconst createPostChangeProjection = (\n context: SurveyAssistantEngineContext,\n targets: Set<string>,\n): NonNullable<SurveyChangeSet[\"postChange\"]> => {\n // Set preserves first occurrence across the requested operations, so bounded\n // previews follow the model's mutation order instead of sorting opaque ids.\n const allTargets = [...targets];\n const requestedItemIds = allTargets\n .filter((target) => target.startsWith(\"item:\"))\n .map((target) => target.slice(\"item:\".length));\n const itemEntries = requestedItemIds\n .map((itemId) => context.inspection.keyIndex.find((entry) => entry.itemId === itemId))\n .filter((entry) => entry !== undefined);\n const surveyTranslations = new SurveyTranslations(context.survey.translations);\n let truncated =\n allTargets.length > MAX_POST_CHANGE_TARGETS || itemEntries.length > MAX_POST_CHANGE_ITEMS;\n\n const touchedItems = itemEntries.slice(0, MAX_POST_CHANGE_ITEMS).map((entry) => {\n const itemTranslations = surveyTranslations.getItemTranslations(entry.itemId);\n const allTranslations = (itemTranslations?.locales ?? []).flatMap((locale) =>\n Object.entries(itemTranslations?.getAllForLocale(locale) ?? {}).map(\n ([contentKey, content]) => {\n const textCharacters = [...getContentPlainText(content as Content)];\n const textPreview = textCharacters.slice(0, MAX_POST_CHANGE_TEXT_CHARS).join(\"\");\n return {\n locale,\n contentKey,\n textPreview,\n textLength: textCharacters.length,\n truncated: textCharacters.length > MAX_POST_CHANGE_TEXT_CHARS,\n };\n },\n ),\n );\n const translations = allTranslations.slice(0, MAX_POST_CHANGE_TRANSLATIONS);\n const allResponseSlots = Object.keys(context.responseSlotTypes).filter((slot) =>\n slot.startsWith(`${entry.itemId}...`),\n );\n const responseSlots = allResponseSlots.slice(0, MAX_POST_CHANGE_RESPONSE_SLOTS);\n if (\n allTranslations.length > translations.length ||\n allResponseSlots.length > responseSlots.length ||\n translations.some((translation) => translation.truncated)\n ) {\n truncated = true;\n }\n\n return {\n itemId: entry.itemId,\n itemType: entry.itemType,\n key: entry.key,\n fullKey: entry.fullKey,\n ...(entry.itemLabel ? { itemLabel: entry.itemLabel } : {}),\n translationCount: allTranslations.length,\n translations,\n responseSlotCount: allResponseSlots.length,\n responseSlots,\n };\n });\n\n return {\n version: context.version,\n itemCount: context.inspection.itemCount,\n localeCount: context.inspection.locales.length,\n locales: context.inspection.locales.slice(0, 32),\n targetCount: allTargets.length,\n touchedTargets: allTargets.slice(0, MAX_POST_CHANGE_TARGETS),\n touchedItemCount: requestedItemIds.length,\n availableTouchedItemCount: itemEntries.length,\n touchedItems,\n truncated: truncated || context.inspection.locales.length > 32,\n };\n};\n\nconst auditFindingKey = (finding: SurveyAuditFinding) =>\n [\n finding.code,\n finding.category,\n finding.itemId ?? \"\",\n finding.locale ?? \"\",\n finding.contentKey ?? \"\",\n ].join(\"\\u0000\");\n\nconst isComplexOperation = (operation: SurveyOperation) => {\n if (operation.kind === \"survey-json-patch\" || operation.kind === \"patch-item-config\") {\n return true;\n }\n if (operation.kind !== \"create-item\") return false;\n return Boolean(\n operation.item.displayConditions ||\n operation.item.disabledConditions ||\n operation.item.validations ||\n operation.item.prefills,\n );\n};\n\nconst createChangeVerification = ({\n after,\n before,\n operations,\n postChange,\n}: {\n after: SurveyAssistantEngineContext;\n before: SurveyAssistantEngineContext;\n operations: SurveyOperation[];\n postChange: NonNullable<SurveyChangeSet[\"postChange\"]>;\n}): NonNullable<SurveyChangeSet[\"verification\"]> | undefined => {\n const beforeFindingKeys = new Set(\n auditSurvey(before, { maxFindings: 10_000 }).findings.map(auditFindingKey),\n );\n const newAuditFindings = auditSurvey(after, { maxFindings: 10_000 }).findings.filter(\n (finding) => !beforeFindingKeys.has(auditFindingKey(finding)),\n );\n const reasons: NonNullable<SurveyChangeSet[\"verification\"]>[\"reasons\"] = [];\n if (\n operations.length > SUBSTANTIAL_CHANGE_OPERATION_COUNT ||\n postChange.touchedItemCount > SUBSTANTIAL_CHANGE_ITEM_COUNT\n ) {\n reasons.push(\"substantial-change\");\n }\n if (operations.some(isComplexOperation)) reasons.push(\"complex-change\");\n if (postChange.truncated) reasons.push(\"bounded-preview\");\n if (newAuditFindings.length > 0) reasons.push(\"new-audit-findings\");\n if (reasons.length === 0) return undefined;\n\n let truncated = newAuditFindings.length > MAX_VERIFICATION_AUDIT_FINDINGS;\n const auditFindings = newAuditFindings\n .slice(0, MAX_VERIFICATION_AUDIT_FINDINGS)\n .map((finding) => {\n const messageCharacters = [...finding.message];\n const messagePreview = messageCharacters\n .slice(0, MAX_VERIFICATION_MESSAGE_CHARS)\n .join(\"\");\n const messageTruncated = messageCharacters.length > MAX_VERIFICATION_MESSAGE_CHARS;\n if (messageTruncated) truncated = true;\n return {\n code: finding.code,\n severity: finding.severity,\n category: finding.category,\n ...(finding.itemId ? { itemId: finding.itemId } : {}),\n ...(finding.locale ? { locale: finding.locale } : {}),\n ...(finding.contentKey ? { contentKey: finding.contentKey } : {}),\n messagePreview,\n messageLength: messageCharacters.length,\n truncated: messageTruncated,\n };\n });\n\n return {\n required: true,\n reasons,\n newAuditFindingCount: newAuditFindings.length,\n auditFindings,\n truncated,\n };\n};\n\n/**\n * Request-scoped transactional draft for one assistant response.\n *\n * Mutation tools submit deltas. A successful delta replaces the previous\n * candidate with a newly validated, cumulative change set. A rejected delta\n * leaves the accepted draft intact and blocks authorization until a later\n * delta validates. Only the latest cumulative candidate can be authorized.\n */\nexport class TurnSurveyDraft {\n readonly turnId: string;\n\n readonly #candidates = new Map<string, SurveyChangeSet>();\n #draftOperations: SurveyOperation[] = [];\n #context: SurveyAssistantEngineContext | undefined;\n #latestChangeSetId: string | undefined;\n #unresolvedCandidates = new Map<string, Set<string>>();\n #final: SurveyAssistantTurnFinal | null = null;\n\n constructor(turnId = createId()) {\n this.turnId = turnId;\n }\n\n initialize(context: SurveyAssistantEngineContext) {\n if (this.#context) {\n throw new Error(\"The survey turn draft was initialized more than once.\");\n }\n this.#context = context;\n }\n\n stage({\n addressedTargets = [],\n operations,\n snapshot,\n summary,\n }: {\n addressedTargets?: string[];\n operations: SurveyOperation[];\n snapshot: SurveyAssistantEngineContext | SurveyDocumentSnapshot | undefined;\n summary: string;\n }): SurveyChangeSet {\n this.#assertOpen();\n\n if (!this.#context && snapshot && \"document\" in snapshot && \"trustedCapabilities\" in snapshot) {\n this.#context = snapshot;\n }\n const currentContext = this.#context ?? snapshot;\n const targets = new Set([...collectOperationTargets(operations), ...addressedTargets]);\n const delta = createSurveyChangeSet({\n operations,\n snapshot: currentContext,\n summary,\n turnId: this.turnId,\n });\n\n if (delta.status !== \"validated\" || !delta.validation.valid) {\n return this.reject(delta, targets);\n }\n\n const cumulativeOperations = [...this.#draftOperations, ...delta.operations];\n if (cumulativeOperations.length > MAX_SURVEY_ASSISTANT_OPERATIONS_PER_TURN_DRAFT) {\n return this.reject(\n createSurveyChangeSet({\n maxOperations: MAX_SURVEY_ASSISTANT_OPERATIONS_PER_TURN_DRAFT,\n operations: cumulativeOperations,\n snapshot: currentContext,\n summary,\n turnId: this.turnId,\n }),\n targets,\n );\n }\n const beforeContext = this.#context;\n if (this.#context) {\n const survey = applyValidatedSurveyOperationsToDraft({\n operations: delta.operations,\n survey: this.#context.survey,\n });\n this.#context = createSurveyAssistantEngineContext(\n {\n ...this.#context.document,\n survey,\n },\n this.#context.trustedCapabilities,\n );\n }\n const postChange = this.#context\n ? createPostChangeProjection(this.#context, targets)\n : undefined;\n const verification =\n beforeContext && this.#context && postChange\n ? createChangeVerification({\n after: this.#context,\n before: beforeContext,\n operations: delta.operations,\n postChange,\n })\n : undefined;\n const registered = surveyChangeSetSchema.parse({\n ...delta,\n operations: cumulativeOperations,\n ...(postChange ? { postChange } : {}),\n ...(verification ? { verification } : {}),\n validation: {\n valid: true,\n issues: [],\n warnings: delta.validation.warnings,\n normalizedOperations: cumulativeOperations,\n },\n ...(this.#latestChangeSetId ? { supersedesChangeIds: [this.#latestChangeSetId] } : {}),\n });\n this.#candidates.set(registered.id, registered);\n this.#draftOperations = registered.operations;\n this.#latestChangeSetId = registered.id;\n for (const [changeSetId, unresolvedTargets] of this.#unresolvedCandidates) {\n if (\n unresolvedTargets.size === 0 ||\n [...unresolvedTargets].some((target) => targets.has(target))\n ) {\n this.#unresolvedCandidates.delete(changeSetId);\n }\n }\n return registered;\n }\n\n reject(candidate: SurveyChangeSet, addressedTargets: Iterable<string> = []): SurveyChangeSet {\n this.#assertOpen();\n if (this.#candidates.has(candidate.id)) {\n throw new Error(`Survey change \"${candidate.id}\" was registered more than once.`);\n }\n\n const registered = surveyChangeSetSchema.parse({\n ...candidate,\n turnId: this.turnId,\n status: \"rejected\",\n validation: {\n ...candidate.validation,\n valid: false,\n },\n });\n this.#candidates.set(registered.id, registered);\n this.#unresolvedCandidates.set(registered.id, new Set(addressedTargets));\n return registered;\n }\n\n finalize(\n status: SurveyAssistantTurnFinal[\"status\"],\n createdAt = new Date().toISOString(),\n details: Pick<SurveyAssistantTurnFinal, \"durationMs\" | \"startedAt\" | \"terminationReason\"> = {},\n ): SurveyAssistantTurnFinal {\n if (this.#final) {\n return this.#final;\n }\n\n const blockedChangeSetIds = [...this.#unresolvedCandidates.keys()];\n const canAuthorize =\n status === \"completed\" &&\n blockedChangeSetIds.length === 0 &&\n this.#latestChangeSetId !== undefined;\n this.#final = surveyAssistantTurnFinalSchema.parse({\n protocolVersion: SURVEY_ASSISTANT_PROTOCOL_VERSION,\n turnId: this.turnId,\n status,\n executableChangeSetIds: canAuthorize ? [this.#latestChangeSetId] : [],\n ...(blockedChangeSetIds.length > 0 ? { blockedChangeSetIds } : {}),\n ...details,\n createdAt,\n });\n return this.#final;\n }\n\n getCandidate(changeSetId: string): SurveyChangeSet | undefined {\n return this.#candidates.get(changeSetId);\n }\n\n get draftOperations(): readonly SurveyOperation[] {\n return this.#draftOperations;\n }\n\n get context(): SurveyAssistantEngineContext | undefined {\n return this.#context;\n }\n\n get final(): SurveyAssistantTurnFinal | null {\n return this.#final;\n }\n\n #assertOpen() {\n if (this.#final) {\n throw new Error(\"Cannot register a survey change after the turn was finalized.\");\n }\n }\n}\n","import { getContentPlainText, type RawSurveyItem } from \"@case-framework/survey-core\";\nimport type {\n SurveyAssistantTaskContext,\n SurveyAssistantTaskItemSummary,\n SurveyDocumentSnapshot,\n} from \"../protocol\";\nimport { createSurveyAssistantEngineContext } from \"./context\";\n\nexport type SurveyAssistantTaskPurpose =\n | \"suggest-item-key\"\n | \"suggest-item-label\"\n | \"translate-content\";\n\nexport interface BuildSurveyAssistantTaskContextOptions {\n purpose: SurveyAssistantTaskPurpose;\n focusItemId?: string;\n sourceLocale?: string;\n targetLocales?: readonly string[];\n sourceTexts?: readonly string[];\n}\n\nconst MAX_RELATED_ITEMS = 48;\nconst MAX_SIBLING_ITEMS = 80;\nconst MAX_VISIBLE_TEXT_ENTRIES_PER_ITEM = 24;\nconst MAX_VISIBLE_TEXT_CHARS = 600;\nconst MAX_NAMING_EXAMPLES = 40;\nconst MAX_TRANSLATION_EXAMPLES = 60;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst getItemLabel = (item: RawSurveyItem): string | undefined => {\n if (!isRecord(item.metadata)) return undefined;\n const label = item.metadata.itemLabel;\n return typeof label === \"string\" && label.trim().length > 0 ? label.trim() : undefined;\n};\n\nconst getCenteredNeighbors = <T>(values: readonly T[], focusIndex: number, limit: number): T[] => {\n if (focusIndex < 0 || limit < 1) return [];\n const windowSize = Math.min(values.length, limit + 1);\n const idealStart = focusIndex - Math.floor(limit / 2);\n const start = Math.min(Math.max(0, idealStart), values.length - windowSize);\n return values.slice(start, start + windowSize).filter((_, index) => start + index !== focusIndex);\n};\n\nexport const buildSurveyAssistantTaskContext = (\n snapshot: SurveyDocumentSnapshot,\n options: BuildSurveyAssistantTaskContextOptions,\n): SurveyAssistantTaskContext => {\n const engineContext = createSurveyAssistantEngineContext(snapshot, undefined, {\n focusItemId: options.focusItemId,\n });\n const { inspection } = engineContext;\n const itemsById = new Map(snapshot.survey.surveyItems.map((item) => [item.id, item]));\n const parentById = new Map(\n inspection.outline.flatMap((item) =>\n item.parentId ? ([[item.itemId, item.parentId]] as const) : [],\n ),\n );\n const childIdsByParent = new Map<string, string[]>();\n for (const item of inspection.outline) {\n if (!item.parentId) continue;\n const childIds = childIdsByParent.get(item.parentId) ?? [];\n childIds.push(item.itemId);\n childIdsByParent.set(item.parentId, childIds);\n }\n const fullKeyById = new Map(inspection.keyIndex.map((item) => [item.itemId, item.fullKey]));\n\n const summarizeItem = (item: RawSurveyItem): SurveyAssistantTaskItemSummary => {\n const allVisibleText: SurveyAssistantTaskItemSummary[\"visibleText\"] = [];\n let visibleTextValueTruncated = false;\n for (const [locale, translations] of Object.entries(snapshot.survey.translations ?? {})) {\n const itemTranslations = translations.itemTranslations?.[item.id];\n if (!itemTranslations) continue;\n for (const [contentKey, content] of Object.entries(itemTranslations)) {\n const text = getContentPlainText(content).trim();\n if (text) {\n if (text.length > MAX_VISIBLE_TEXT_CHARS) visibleTextValueTruncated = true;\n allVisibleText.push({\n locale,\n contentKey,\n text:\n text.length > MAX_VISIBLE_TEXT_CHARS\n ? `${text.slice(0, MAX_VISIBLE_TEXT_CHARS)}...`\n : text,\n });\n }\n }\n }\n return {\n id: item.id,\n key: item.key,\n fullKey: fullKeyById.get(item.id) ?? item.key,\n itemType: item.itemType,\n itemLabel: getItemLabel(item),\n visibleText: allVisibleText.slice(0, MAX_VISIBLE_TEXT_ENTRIES_PER_ITEM),\n visibleTextTruncated:\n allVisibleText.length > MAX_VISIBLE_TEXT_ENTRIES_PER_ITEM || visibleTextValueTruncated,\n };\n };\n\n const rootItemId = inspection.outline.find((item) => item.depth === 0)?.itemId;\n const rootItem = rootItemId ? itemsById.get(rootItemId) : undefined;\n\n const result: SurveyAssistantTaskContext = {\n document: {\n revision: snapshot.version.revision,\n contentHash: snapshot.version.contentHash,\n capabilityDigest: snapshot.version.capabilityDigest,\n },\n survey: {\n key: rootItem?.key,\n locales: inspection.locales,\n itemCount: inspection.itemCount,\n selectedLocale: snapshot.ui.selectedLocale,\n },\n };\n\n const focusItem = options.focusItemId ? itemsById.get(options.focusItemId) : undefined;\n if (focusItem) {\n const parentId = parentById.get(focusItem.id);\n const parentItem = parentId ? itemsById.get(parentId) : undefined;\n const ancestorItems: RawSurveyItem[] = [];\n const seenAncestorIds = new Set<string>();\n let ancestorId = parentId;\n while (ancestorId && !seenAncestorIds.has(ancestorId)) {\n seenAncestorIds.add(ancestorId);\n const ancestor = itemsById.get(ancestorId);\n if (!ancestor) break;\n ancestorItems.unshift(ancestor);\n ancestorId = parentById.get(ancestorId);\n }\n\n const siblingIds = parentItem ? (childIdsByParent.get(parentItem.id) ?? []) : [];\n const siblingItemCount = Math.max(0, siblingIds.length - 1);\n const siblingItems = getCenteredNeighbors(\n siblingIds,\n siblingIds.indexOf(focusItem.id),\n MAX_SIBLING_ITEMS,\n )\n .map((itemId) => itemsById.get(itemId))\n .filter((item): item is RawSurveyItem => Boolean(item));\n const allRelatedItems: RawSurveyItem[] = [];\n const seenRelatedIds = new Set<string>();\n const pending = [...(childIdsByParent.get(focusItem.id) ?? [])];\n while (pending.length > 0) {\n const itemId = pending.shift();\n const item = itemId ? itemsById.get(itemId) : undefined;\n if (!item || seenRelatedIds.has(item.id)) continue;\n seenRelatedIds.add(item.id);\n allRelatedItems.push(item);\n pending.push(...(childIdsByParent.get(item.id) ?? []));\n }\n const relatedItems = allRelatedItems.slice(0, MAX_RELATED_ITEMS);\n\n result.focus = {\n item: summarizeItem(focusItem),\n parent: parentItem ? summarizeItem(parentItem) : undefined,\n ancestorPath: ancestorItems.map(summarizeItem),\n siblingKeys: siblingItems.map((item) => item.key),\n siblingItems: siblingItems.map(summarizeItem),\n siblingItemCount,\n siblingItemsTruncated: siblingItemCount > siblingItems.length,\n relatedItems: relatedItems.map(summarizeItem),\n relatedItemCount: allRelatedItems.length,\n relatedItemsTruncated: allRelatedItems.length > relatedItems.length,\n };\n }\n\n if (\n (options.purpose === \"suggest-item-key\" || options.purpose === \"suggest-item-label\") &&\n focusItem\n ) {\n const parentId = parentById.get(focusItem.id);\n const siblingIds = parentId ? (childIdsByParent.get(parentId) ?? []) : [];\n const siblingPositionById = new Map(siblingIds.map((itemId, index) => [itemId, index]));\n const focusSiblingPosition = siblingPositionById.get(focusItem.id);\n const rankedItems = snapshot.survey.surveyItems\n .filter((item) => item.id !== focusItem.id)\n .map((item, index) => ({\n item,\n index,\n siblingDistance:\n focusSiblingPosition !== undefined && siblingPositionById.has(item.id)\n ? Math.abs(siblingPositionById.get(item.id)! - focusSiblingPosition)\n : Number.POSITIVE_INFINITY,\n relationship:\n parentById.get(item.id) === parentId\n ? (\"sibling\" as const)\n : item.itemType === focusItem.itemType\n ? (\"same-type\" as const)\n : (\"survey\" as const),\n }))\n .sort((left, right) => {\n const rank = { sibling: 0, \"same-type\": 1, survey: 2 } as const;\n return (\n rank[left.relationship] - rank[right.relationship] ||\n left.siblingDistance - right.siblingDistance ||\n left.index - right.index\n );\n });\n const allKeyExamples = rankedItems.map(({ item, relationship }) => ({\n itemId: item.id,\n itemType: item.itemType,\n key: item.key,\n relationship,\n }));\n const allLabelExamples = rankedItems.flatMap(({ item, relationship }) => {\n const label = getItemLabel(item);\n return label\n ? [{ itemId: item.id, itemType: item.itemType, key: item.key, label, relationship }]\n : [];\n });\n result.naming = {\n keyExamples: allKeyExamples.slice(0, MAX_NAMING_EXAMPLES),\n keyExampleCount: allKeyExamples.length,\n keyExamplesTruncated: allKeyExamples.length > MAX_NAMING_EXAMPLES,\n labelExamples: allLabelExamples.slice(0, MAX_NAMING_EXAMPLES),\n labelExampleCount: allLabelExamples.length,\n labelExamplesTruncated: allLabelExamples.length > MAX_NAMING_EXAMPLES,\n };\n }\n\n const sourceLocale = options.sourceLocale;\n if (options.purpose === \"translate-content\" && sourceLocale) {\n const relevantLocales = [sourceLocale, ...(options.targetLocales ?? [])];\n const sourceTokens = new Set(\n (options.sourceTexts ?? [])\n .flatMap((text) => text.toLocaleLowerCase().split(/[^\\p{L}\\p{N}]+/u))\n .filter((token) => token.length >= 3),\n );\n const allExamples: Array<{\n itemId: string;\n contentKey: string;\n values: Record<string, string>;\n score: number;\n order: number;\n }> = [];\n snapshot.survey.surveyItems.forEach((item, itemIndex) => {\n const contentKeys = new Set<string>();\n for (const locale of relevantLocales) {\n const itemTranslations =\n snapshot.survey.translations?.[locale]?.itemTranslations?.[item.id];\n for (const contentKey of Object.keys(itemTranslations ?? {})) contentKeys.add(contentKey);\n }\n for (const contentKey of contentKeys) {\n const values: Record<string, string> = {};\n for (const locale of relevantLocales) {\n const content =\n snapshot.survey.translations?.[locale]?.itemTranslations?.[item.id]?.[contentKey];\n if (!content) continue;\n const text = getContentPlainText(content).trim();\n if (text) values[locale] = text.slice(0, MAX_VISIBLE_TEXT_CHARS);\n }\n const sourceText = values[sourceLocale];\n if (!sourceText || Object.keys(values).length < 2) continue;\n const normalizedSource = sourceText.toLocaleLowerCase();\n const score = [...sourceTokens].reduce(\n (total, token) => total + (normalizedSource.includes(token) ? 1 : 0),\n 0,\n );\n allExamples.push({ itemId: item.id, contentKey, values, score, order: itemIndex });\n }\n });\n allExamples.sort((left, right) => right.score - left.score || left.order - right.order);\n result.translation = {\n examples: allExamples\n .slice(0, MAX_TRANSLATION_EXAMPLES)\n .map(({ itemId, contentKey, values }) => ({ itemId, contentKey, values })),\n exampleCount: allExamples.length,\n examplesTruncated: allExamples.length > MAX_TRANSLATION_EXAMPLES,\n };\n }\n\n return result;\n};\n","export interface SurveyAssistantTaskResultCacheOptions {\n ttlMs?: number;\n maxEntries?: number;\n now?: () => number;\n}\n\ninterface TaskResultCacheEntry {\n expiresAt: number;\n value: unknown;\n}\n\nconst DEFAULT_TTL_MS = 15 * 60 * 1000;\nconst DEFAULT_MAX_ENTRIES = 64;\n\n/** Small in-memory LRU cache for deterministic, snapshot-scoped one-shot results. */\nexport class SurveyAssistantTaskResultCache {\n private readonly entries = new Map<string, TaskResultCacheEntry>();\n private readonly ttlMs: number;\n private readonly maxEntries: number;\n private readonly now: () => number;\n\n constructor(options: SurveyAssistantTaskResultCacheOptions = {}) {\n this.ttlMs = Math.max(0, options.ttlMs ?? DEFAULT_TTL_MS);\n this.maxEntries = Math.max(1, options.maxEntries ?? DEFAULT_MAX_ENTRIES);\n this.now = options.now ?? Date.now;\n }\n\n get<TResult>(key: string): TResult | undefined {\n const entry = this.entries.get(key);\n if (!entry) return undefined;\n if (entry.expiresAt <= this.now()) {\n this.entries.delete(key);\n return undefined;\n }\n\n this.entries.delete(key);\n this.entries.set(key, entry);\n return entry.value as TResult;\n }\n\n set<TResult>(key: string, value: TResult): void {\n this.entries.delete(key);\n this.entries.set(key, { expiresAt: this.now() + this.ttlMs, value });\n while (this.entries.size > this.maxEntries) {\n const oldestKey = this.entries.keys().next().value;\n if (oldestKey === undefined) break;\n this.entries.delete(oldestKey);\n }\n }\n\n clear(): void {\n this.entries.clear();\n }\n}\n"],"mappings":";;;;;AA2FA,MAAMA,cAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,MAAM;AAEtE,MAAMC,cAAY,UAChB,OAAO,UAAU,YAAY,MAAM,MAAM,CAAC,SAAS,IAAI,MAAM,MAAM,GAAG,KAAA;AAExE,MAAMC,aAAW,UAA+B,MAAM,QAAQ,MAAM,GAAG,QAAQ,EAAE;AAEjF,MAAM,eAAe,SAAkC;AAErD,QAAOA,WADQF,WAAS,KAAK,OAAO,GAAG,KAAK,SAAS,KAAA,IAC9B,MAAM,CAAC,QAAQ,UAA2B,OAAO,UAAU,SAAS;;AAG7F,MAAM,qBAAqB,UAA8C;AACvE,SAAQ,MAAM,MAAd;EACE,KAAK;EACL,KAAK,SACH,QAAO,UAAU;EACnB,KAAK,aACH,QAAO,UAAU;EACnB,KAAK,SACH,QAAO,UAAU;EACnB,QACE,QAAO,UAAU;;;AAIvB,MAAM,mBACJ,QACA,QACA,QACA,cACG;AACH,QAAO,GAAG,OAAO,KAAK,qBAAqB,IAAI,KAAK,YAAY;AAChE,QAAO,GAAG,OAAO,KAAK,qBAAqB,UAAU,KAAK,YAAY,UAAU;;AAGlF,MAAM,wBAAwB,EAC5B,QACA,QACA,QACA,iBAMI;AACJ,KAAI,CAACA,WAAS,OAAO,CAAE;AACvB,MAAK,MAAM,SAASE,UAAQ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