@case-framework/survey-core 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/to_mirgrate/data_types/legacy-types.ts","../src/survey/responses/response-meta.ts","../src/expressions/item-expression-registry.ts","../src/engine/active-responses.ts","../src/engine/engine.ts","../src/json-patch.ts","../src/response-exporter/validate-configuration.ts","../src/response-exporter/csv-serializer.ts","../src/response-exporter/exporter.ts","../src/response-exporter/codebook.ts"],"sourcesContent":["import { Expression } from \"./expression\";\nimport { ExpressionArg } from \"./expression\";\n\n// ----------------------------------------------------------------------\nexport type LegacyItemComponent =\n | LegacyItemComponentBase\n | LegacyItemGroupComponent\n | LegacyResponseComponent;\n\ninterface LegacyItemComponentBase {\n role: string; // purpose of the component\n key?: string; // unique identifier\n content?: Array<LegacyLocalizedObject>; // array with item that are a sub-type of LocalizedObject\n displayCondition?: Expression | boolean;\n disabled?: Expression | boolean;\n style?: Array<{ key: string; value: string }>;\n description?: Array<LegacyLocalizedObject>; // optional explanation to the content\n properties?: LegacyComponentProperties;\n}\n\nexport interface LegacyResponseComponent extends LegacyItemComponentBase {\n key: string;\n dtype?: string;\n}\n\nexport interface LegacyItemGroupComponent extends LegacyItemComponentBase {\n items: Array<LegacyItemComponent>;\n order?: Expression;\n}\n\nexport const isLegacyItemGroupComponent = (\n item: LegacyItemComponent,\n): item is LegacyItemGroupComponent => {\n const items = (item as LegacyItemGroupComponent).items;\n return items !== undefined && items.length > 0;\n};\n\nexport interface LegacyComponentProperties {\n min?: ExpressionArg | number;\n max?: ExpressionArg | number;\n stepSize?: ExpressionArg | number;\n dateInputMode?: ExpressionArg | string;\n pattern?: string;\n}\n\n// ----------------------------------------------------------------------\nexport type LegacyLocalizedObject = LegacyLocalizedString;\n\nexport interface LegacyLocalizedObjectBase {\n code: string;\n}\n\nexport interface LegacyLocalizedString extends LegacyLocalizedObjectBase {\n parts: Array<ExpressionArg>;\n resolvedText?: string;\n}\n\nexport interface LegacySurvey {\n id?: string;\n props?: LegacySurveyProps;\n prefillRules?: Expression[];\n //contextRules?: SurveyContextDef;\n maxItemsPerPage?: { large: number; small: number };\n availableFor?: string;\n requireLoginBeforeSubmission?: boolean;\n //\n surveyDefinition: LegacySurveyGroupItem;\n published?: number;\n unpublished?: number;\n versionId: string;\n metadata?: {\n [key: string]: string;\n };\n}\n\nexport interface LegacySurveyProps {\n name?: LegacyLocalizedObject[];\n description?: LegacyLocalizedObject[];\n typicalDuration?: LegacyLocalizedObject[];\n}\n\ninterface LegacySurveyItemBase {\n key: string;\n metadata?: {\n [key: string]: string;\n };\n follows?: Array<string>;\n condition?: Expression;\n priority?: number; // can be used to sort items in the list\n}\n\nexport type LegacySurveyItem = LegacySurveyGroupItem | LegacySurveySingleItem;\n\n// ----------------------------------------------------------------------\nexport interface LegacySurveyGroupItem extends LegacySurveyItemBase {\n items: Array<LegacySurveyItem>;\n selectionMethod?: Expression; // what method to use to pick next item if ambigous - default uniform random\n}\n\nexport const isLegacySurveyGroupItem = (item: LegacySurveyItem): item is LegacySurveyGroupItem => {\n const items = (item as LegacySurveyGroupItem).items;\n return items !== undefined && items.length > 0;\n};\n\n// ----------------------------------------------------------------------\n// Single Survey Items:\nexport type LegacySurveyItemTypes = \"pageBreak\" | \"test\" | \"surveyEnd\";\n\nexport interface LegacySurveySingleItem extends LegacySurveyItemBase {\n type?: LegacySurveyItemTypes;\n components?: LegacyItemGroupComponent; // any sub-type of ItemComponent\n validations?: Array<LegacyValidation>;\n confidentialMode?: LegacyConfidentialMode;\n mapToKey?: string; // if the response should be mapped to another key in confidential mode\n}\n\nexport interface LegacyValidation {\n key: string;\n type: \"soft\" | \"hard\"; // hard or softvalidation\n rule: Expression | boolean;\n}\n\nexport type LegacyConfidentialMode = \"add\" | \"replace\";\n","export interface ItemResponseMeta {\n position: number;\n}\n\nexport const SurveyEventTypes = {\n openSurvey: \"openSurvey\",\n pageChanged: \"pageChanged\",\n responseChanged: \"responseChanged\",\n languageChanged: \"languageChanged\",\n} as const;\n\nexport type SurveyEventTypes = (typeof SurveyEventTypes)[keyof typeof SurveyEventTypes];\n\nexport interface SurveyEventBase<TEventType extends SurveyEventTypes = SurveyEventTypes> {\n type: TEventType;\n timestamp: number;\n}\n\nexport interface OpenSurveyEvent extends SurveyEventBase<typeof SurveyEventTypes.openSurvey> {\n value: string; // locale code\n}\n\nexport interface PageChangedEvent extends SurveyEventBase<typeof SurveyEventTypes.pageChanged> {\n value: number;\n}\n\nexport interface ResponseChangedEvent extends SurveyEventBase<\n typeof SurveyEventTypes.responseChanged\n> {\n slotId: string;\n operation: \"set\" | \"clear\";\n}\n\nexport interface LanguageChangedEvent extends SurveyEventBase<\n typeof SurveyEventTypes.languageChanged\n> {\n value: string;\n}\n\nexport type SurveyEvent =\n | OpenSurveyEvent\n | PageChangedEvent\n | ResponseChangedEvent\n | LanguageChangedEvent;\n","import { SurveyItemCore } from \"../survey/items/survey-item\";\nimport { ValueType } from \"../survey/responses/value-types\";\nimport { Expression } from \"./expression\";\n\nexport type ItemExpressionParameterInput =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"singleSelect\"\n | \"multiSelect\";\n\nexport interface ItemExpressionParameterOption {\n value: string;\n label: string;\n description?: string;\n}\n\nexport interface ItemExpressionParameterDefinition<TItem extends SurveyItemCore = SurveyItemCore> {\n key: string;\n label: string;\n description?: string;\n input: ItemExpressionParameterInput;\n required?: boolean;\n defaultValue?: unknown;\n getOptions?: (item: TItem) => ItemExpressionParameterOption[];\n}\n\nexport interface ItemExpressionDefinition<TItem extends SurveyItemCore = SurveyItemCore> {\n id: string;\n label: string;\n description?: string;\n returnType: ValueType;\n parameters?: Array<ItemExpressionParameterDefinition<TItem>>;\n buildExpression: (item: TItem, params?: Record<string, unknown>) => Expression;\n}\n\nexport type AnyItemExpressionDefinition = ItemExpressionDefinition<any>;\n\nexport function getItemExpressionDefinition<TItem extends SurveyItemCore>(\n definitions: ReadonlyArray<ItemExpressionDefinition<TItem>> | undefined,\n expressionId: string,\n): ItemExpressionDefinition<TItem> | undefined {\n return definitions?.find((definition) => definition.id === expressionId);\n}\n\nexport function buildItemExpression<TItem extends SurveyItemCore>(\n item: TItem,\n definitions: ReadonlyArray<ItemExpressionDefinition<TItem>> | undefined,\n expressionId: string,\n params?: Record<string, unknown>,\n): Expression {\n const definition = getItemExpressionDefinition(definitions, expressionId);\n if (!definition) {\n throw new Error(`Unknown item expression: ${expressionId}`);\n }\n\n return definition.buildExpression(item, params);\n}\n","import { ExpressionEvaluator } from \"../expressions/expression-evaluator\";\nimport {\n ContextVariableType,\n ExpressionType,\n type JsonExpression,\n type Expression,\n} from \"../expressions\";\nimport type { Survey } from \"../survey\";\nimport { ReservedSurveyItemTypes } from \"../survey/items/types\";\nimport { GroupItemCore } from \"../survey/registry/built-in-items\";\nimport {\n ResponseItem,\n ValueType,\n type ResponseValue,\n type SurveyItemResponse,\n} from \"../survey/responses\";\nimport type { SurveyContext } from \"../survey/utils/context\";\n\nexport interface VisibilityEvaluationDiagnostic {\n code: \"non-boolean-visibility-result\";\n itemId: string;\n componentId?: string;\n actualType: ResponseValue[\"type\"];\n}\n\nconst itemNode = (id: string) => JSON.stringify([\"item\", id]);\nconst componentNode = (id: string, component: string) =>\n JSON.stringify([\"component\", id, component]);\nconst slotNode = (id: string) => JSON.stringify([\"answer\", id]);\n\nfunction assertDeclarativeVisibility(expression: JsonExpression | undefined): void {\n if (!expression) return;\n if (expression.type === ExpressionType.ContextVariable) {\n if (expression.contextType === ContextVariableType.CustomExpression)\n throw new Error(\n \"Visibility conditions cannot use custom callback expressions; provide a serializable custom context value instead.\",\n );\n assertDeclarativeVisibility(expression.key);\n }\n if (\"arguments\" in expression)\n for (const argument of expression.arguments ?? []) assertDeclarativeVisibility(argument);\n}\n\n/** Compile the dependencies once; each evaluation reads an immutable logical session snapshot. */\nexport class ActiveResponsePlan {\n private readonly parents = new Map<string, string>();\n private readonly components = new Map<string, string[]>();\n private readonly slots: ReturnType<Survey[\"getResponseSlotRegistry\"]>;\n\n constructor(private readonly survey: Survey) {\n this.slots = survey.getResponseSlotRegistry();\n for (const item of survey.surveyItems.values()) {\n if (item.type === ReservedSurveyItemTypes.Group)\n for (const child of (item as GroupItemCore).items ?? []) this.parents.set(child, item.id);\n for (const { slotId, componentId } of item.getConditionalResponseSlots())\n this.components.set(slotId, [...(this.components.get(slotId) ?? []), componentId]);\n }\n const graph = new Map<string, string[]>();\n const labels = new Map<string, string>();\n const refs = (expression?: Expression) =>\n expression?.responseVariableRefs.map((ref) => slotNode(ref.slotId)) ?? [];\n for (const item of survey.surveyItems.values()) {\n for (const expression of [\n item.displayConditions?.root,\n ...Object.values(item.displayConditions?.components ?? {}),\n ])\n assertDeclarativeVisibility(expression?.serialize());\n const label = item.metadata?.itemLabel?.trim() || item.id;\n const parent = this.parents.get(item.id);\n graph.set(itemNode(item.id), [\n ...(parent ? [itemNode(parent)] : []),\n ...refs(item.displayConditions?.root),\n ]);\n labels.set(itemNode(item.id), `${label} visibility`);\n for (const [component, expression] of Object.entries(\n item.displayConditions?.components ?? {},\n )) {\n graph.set(componentNode(item.id, component), [itemNode(item.id), ...refs(expression)]);\n labels.set(componentNode(item.id, component), `${label} (${component}) visibility`);\n }\n for (const slot of item.getResponseSlotDefinitions()) {\n const activation = item.getActiveResponseDependencies(slot.slotId);\n graph.set(slotNode(slot.slotId), [\n itemNode(item.id),\n ...(this.components.get(slot.slotId) ?? []).map((id) => componentNode(item.id, id)),\n ...item.getComputedResponseDependencies(slot.slotId).map(slotNode),\n ...activation.slotIds.map(slotNode),\n ...activation.componentIds.map((id) => componentNode(item.id, id)),\n ]);\n labels.set(slotNode(slot.slotId), `${label} (${slot.variableName || slot.slotId})`);\n }\n }\n const done = new Set<string>(),\n visiting = new Set<string>(),\n path: string[] = [];\n const visit = (node: string) => {\n if (visiting.has(node))\n throw new Error(\n `Cyclic response/visibility dependency: ${[...path.slice(path.indexOf(node)), node].map((id) => labels.get(id) ?? id).join(\" → \")}`,\n );\n if (done.has(node)) return;\n visiting.add(node);\n path.push(node);\n for (const dependency of graph.get(node) ?? []) visit(dependency);\n path.pop();\n visiting.delete(node);\n done.add(node);\n };\n for (const node of graph.keys()) visit(node);\n }\n\n evaluate(responses: Record<string, SurveyItemResponse>, context: SurveyContext) {\n const diagnostics: VisibilityEvaluationDiagnostic[] = [];\n const cache = new Map<string, boolean | ResponseValue | undefined>();\n const visiting = new Set<string>();\n const resolve = <T extends boolean | ResponseValue | undefined>(\n key: string,\n compute: () => T,\n ): T => {\n if (cache.has(key)) return cache.get(key) as T;\n if (visiting.has(key)) throw new Error(`Cyclic response/visibility dependency: ${key}`);\n visiting.add(key);\n try {\n const value = compute();\n cache.set(key, value);\n return value;\n } finally {\n visiting.delete(key);\n }\n };\n const condition = (itemId: string, expression?: Expression, componentId?: string) => {\n if (!expression) return true;\n const value = evaluator.eval(expression);\n if (value !== undefined && value.type !== ValueType.boolean)\n diagnostics.push({\n code: \"non-boolean-visibility-result\",\n itemId,\n ...(componentId === undefined ? {} : { componentId }),\n actualType: value.type,\n });\n return value?.type === ValueType.boolean && value.value;\n };\n const isItemVisible = (id: string): boolean =>\n resolve(itemNode(id), () => {\n const item = this.survey.surveyItems.get(id);\n const parent = this.parents.get(id);\n return (\n !!item &&\n (id === this.survey.rootItem?.id || (!!parent && isItemVisible(parent))) &&\n condition(id, item.displayConditions?.root)\n );\n });\n const isComponentVisible = (id: string, component: string): boolean =>\n resolve(\n componentNode(id, component),\n () =>\n isItemVisible(id) &&\n condition(\n id,\n this.survey.surveyItems.get(id)?.displayConditions?.components?.[component],\n component,\n ),\n );\n const getAnswer = (slotId: string): ResponseValue | undefined =>\n resolve(slotNode(slotId), () => {\n const owner = this.slots.get(slotId);\n if (\n !owner ||\n !isItemVisible(owner.itemId) ||\n !(this.components.get(slotId) ?? []).every((id) => isComponentVisible(owner.itemId, id))\n )\n return undefined;\n const item = this.survey.surveyItems.get(owner.itemId)!;\n if (!owner.computed)\n return item.getActiveResponseValue(\n slotId,\n responses[owner.itemId]?.response?.get(slotId),\n (id) => isComponentVisible(owner.itemId, id),\n getAnswer,\n );\n const sources = new ResponseItem();\n for (const id of item.getComputedResponseDependencies(slotId))\n sources.setSlotValue(id, getAnswer(id));\n return item.getComputedResponseValue(slotId, sources, (id) =>\n isComponentVisible(owner.itemId, id),\n );\n });\n const evaluator = new ExpressionEvaluator({\n responses,\n surveyContext: context,\n resolveResponseValue: getAnswer,\n });\n const getItemResponse = (id: string) => {\n const response = new ResponseItem();\n for (const slot of this.survey.surveyItems.get(id)?.getResponseSlotDefinitions() ?? [])\n if (!slot.computed) response.setSlotValue(slot.slotId, getAnswer(slot.slotId));\n return response.isEmpty() ? undefined : response;\n };\n return {\n evaluator,\n getAnswer,\n getItemResponse,\n isItemVisible,\n isComponentVisible,\n getDiagnostics: () => diagnostics.map((diagnostic) => ({ ...diagnostic })),\n };\n }\n}\n","import { ActiveResponsePlan } from \"./active-responses\";\nimport type { JsonExpression } from \"../expressions/expression\";\nimport { formatCalendarDate } from \"../calendar-date\";\nimport type { Locale } from \"date-fns\";\nimport { enUS } from \"date-fns/locale/en-US\";\nimport { generateId, shuffleIndices } from \"../utils\";\n\nimport { Survey, SurveyItemCore, ReservedSurveyItemTypes } from \"../survey\";\nimport {\n SurveyResponse,\n ResponseItem,\n ResponseValue,\n SurveyEvent,\n SurveyEventTypes,\n SurveyItemResponse,\n ValueType,\n} from \"../survey/responses\";\nimport { ExpressionEvaluator } from \"../expressions/expression-evaluator\";\nimport {\n Expression,\n TemplateDefTypes,\n TemplateValueDefinition,\n TemplateValueFormatDate,\n} from \"../expressions\";\nimport { SurveyContext } from \"../survey/utils/context\";\nimport { GroupItemCore } from \"../survey/registry/built-in-items\";\nimport { SurveyItemPrefill, SurveyItemPrefillApplyMode } from \"../survey/items/prefill\";\n\nexport type ScreenSize = \"small\" | \"large\";\n\nexport interface RenderedSurveyItem {\n id: string;\n type: string;\n items?: Array<RenderedSurveyItem>;\n}\n\nexport interface SurveyEnginePrefillEnvironment {\n getPreviousResponse?: (ref: { surveyKey?: string; slotId: string }) => ResponseValue | undefined;\n}\n\nexport interface SurveyEngineOptions {\n /** Disable defaults when reconstructing a finalized submission. */\n applyConfiguredPrefills?: boolean;\n prefillEnvironment?: SurveyEnginePrefillEnvironment;\n}\n\nexport class SurveyEngineCore {\n private activeResponsePlan: ActiveResponsePlan;\n private activeState?: ReturnType<ActiveResponsePlan[\"evaluate\"]>;\n private responseDiagnostics = new Map<\n string,\n import(\"../survey/items\").ResponseNormalizationDiagnostic[]\n >();\n private surveyDef: Survey;\n private renderedSurveyTree: RenderedSurveyItem;\n private renderedItemsCache?: {\n tree: RenderedSurveyItem;\n items: ReadonlyArray<Readonly<RenderedSurveyItem>>;\n };\n private context: SurveyContext;\n private locale: string;\n private readonly sessionSeedValue: string;\n\n private responses: {\n [itemKey: string]: SurveyItemResponse;\n };\n private prefills?: {\n [itemKey: string]: SurveyItemResponse;\n };\n private _events: Array<SurveyEvent>;\n private _openedAt: number;\n private dateLocales: Array<{ code: string; locale: Locale }>;\n private prefillEnvironment?: SurveyEnginePrefillEnvironment;\n\n private cache!: {\n validations: {\n [itemKey: string]: {\n [validationKey: string]: {\n expression: Expression;\n result: boolean;\n };\n };\n };\n displayConditions: {\n [itemKey: string]: {\n root?: {\n expression: Expression;\n result: boolean;\n };\n components?: {\n [componentKey: string]: {\n expression: Expression;\n result: boolean;\n };\n };\n };\n };\n templateValues: {\n [templateValueKey: string]: {\n value?: ResponseValue;\n templateDef: TemplateValueDefinition | undefined;\n };\n };\n disabledConditions: {\n [itemKey: string]: {\n components?: {\n [componentKey: string]: {\n expression: Expression;\n result: boolean;\n };\n };\n };\n };\n };\n\n constructor(\n survey: Survey,\n context?: SurveyContext,\n prefills?: Record<string, ResponseValue>,\n dateLocales?: Array<{ code: string; locale: Locale }>,\n options?: SurveyEngineOptions,\n ) {\n this._openedAt = this._getTimestamp();\n this.sessionSeedValue = generateId();\n\n this.surveyDef = survey;\n const { issues: configurationIssues, plan } = SurveyEngineCore.inspectConfiguration(survey);\n if (configurationIssues.length) throw new Error(configurationIssues.join(\"\\n\"));\n\n this.activeResponsePlan = plan!;\n\n this.context = context\n ? context\n : {\n locale: \"en\",\n };\n this.locale = this.context.locale;\n if (prefills) {\n const registry = survey.getResponseSlotRegistry();\n this.prefills = Object.create(null);\n for (const [slotId, value] of Object.entries(prefills)) {\n const owner = registry.get(slotId);\n if (!owner || owner.computed)\n throw new Error(`Cannot restore unknown or computed response slot \"${slotId}\"`);\n const item = survey.surveyItems.get(owner.itemId)!;\n const response = (this.prefills![owner.itemId] ??= new SurveyItemResponse(\n { itemId: item.id, itemType: item.type },\n new ResponseItem(),\n ));\n response.response!.setSlotValue(slotId, value);\n }\n }\n this.prefillEnvironment = options?.prefillEnvironment;\n\n this.dateLocales = dateLocales || [{ code: \"en\", locale: enUS }];\n this.responses = this.initResponseObject(this.surveyDef.surveyItems);\n\n this.initCache();\n if (options?.applyConfiguredPrefills !== false) this.applyConfiguredPrefills();\n this.evalExpressions();\n\n // init rendered survey\n if (!survey.rootItem) {\n throw new Error(\"constructor: root item not found\");\n }\n this.renderedSurveyTree = this.renderGroup(survey.rootItem);\n this._events = [\n {\n type: SurveyEventTypes.openSurvey,\n timestamp: this._getTimestamp(),\n value: this.context.locale,\n },\n ];\n }\n\n // PUBLIC METHODS\n setContext(context: SurveyContext) {\n this.updateContext(context);\n }\n\n getDateLocales(): Array<{ code: string; locale: Locale }> {\n return this.dateLocales.slice();\n }\n\n getCurrentDateLocale(): Locale | undefined {\n const found = this.dateLocales.find((dl) => dl.code === this.locale);\n if (!found) {\n console.warn(`Locale '${this.locale}' is not available. Using default locale.`);\n if (this.dateLocales.length > 0) {\n return this.dateLocales[0].locale;\n }\n return enUS;\n }\n return found?.locale;\n }\n\n updateContext(context: SurveyContext) {\n const localeChanged = this.locale !== context.locale;\n this.context = context;\n this.locale = context.locale;\n if (localeChanged)\n this._registerSurveyEvent({\n type: SurveyEventTypes.languageChanged,\n timestamp: this._getTimestamp(),\n value: context.locale,\n });\n\n // Reevaluate all context-dependent expressions, even when the locale is unchanged.\n this.evalExpressions();\n this.reRenderSurveyTree();\n }\n\n /** Change the presentation language without losing participant/custom context. */\n updateLocale(locale: string): boolean {\n if (this.context.locale === locale) return false;\n this.updateContext({ ...this.context, locale });\n return true;\n }\n\n setResponse(targetKey: string, response?: ResponseItem) {\n const target = this.getResponseItem(targetKey);\n if (!target) {\n throw new Error(\"setResponse: target not found for key: \" + targetKey);\n }\n\n const item = this.surveyDef.surveyItems.get(targetKey)!;\n const previousSlots = structuredClone(target.response?.serialize()?.slots ?? {});\n const normalized = item.normalizeResponse(response);\n target.response = normalized.response;\n this.responseDiagnostics.set(targetKey, normalized.diagnostics ?? []);\n const nextSlots = target.response?.serialize()?.slots ?? {};\n const timestamp = this._getTimestamp();\n // Sort value properties so equivalent values do not emit events just because\n // their object properties were constructed in a different order.\n const comparable = (value: ResponseValue | undefined) =>\n value === undefined ? undefined : JSON.stringify(value, Object.keys(value).sort());\n for (const slotId of new Set([...Object.keys(previousSlots), ...Object.keys(nextSlots)])) {\n if (comparable(previousSlots[slotId]) === comparable(nextSlots[slotId])) continue;\n this._registerSurveyEvent({\n type: SurveyEventTypes.responseChanged,\n timestamp,\n slotId,\n operation: nextSlots[slotId] === undefined ? \"clear\" : \"set\",\n });\n }\n\n this.evalExpressions();\n // re-render whole tree\n this.reRenderSurveyTree();\n }\n\n get openedAt(): number {\n return this._openedAt;\n }\n\n /** Invalid visibility results in the current evaluation; unanswered conditions are omitted. */\n getEvaluationDiagnostics() {\n return this.activeEvaluation().getDiagnostics();\n }\n\n /** Diagnostics from the latest initialization or response update for an item. */\n getResponseDiagnostics(itemId: string) {\n return (this.responseDiagnostics.get(itemId) ?? []).map((diagnostic) => ({ ...diagnostic }));\n }\n\n get sessionSeed(): string {\n return this.sessionSeedValue;\n }\n\n get survey(): Readonly<Survey> {\n return this.surveyDef;\n }\n\n getSurveyPages(size?: ScreenSize): RenderedSurveyItem[][] {\n const renderedSurvey = flattenTree(this.renderedSurveyTree);\n const pages = new Array<RenderedSurveyItem[]>();\n\n if (!size) {\n size = \"large\";\n }\n\n let currentPage: RenderedSurveyItem[] = [];\n\n renderedSurvey.forEach((item) => {\n if (item.type === ReservedSurveyItemTypes.PageBreak) {\n if (currentPage.length > 0) {\n pages.push([...currentPage]);\n currentPage = [];\n }\n return;\n }\n currentPage.push(item);\n\n if (!this.surveyDef.maxItemsPerPage) {\n return;\n }\n let max = 0;\n switch (size) {\n case \"large\":\n max = this.surveyDef.maxItemsPerPage.large;\n break;\n case \"small\":\n max = this.surveyDef.maxItemsPerPage.small;\n break;\n }\n\n if (currentPage.length >= max) {\n pages.push([...currentPage]);\n currentPage = [];\n }\n });\n if (currentPage.length > 0) {\n pages.push([...currentPage]);\n }\n return pages;\n }\n\n /** Read-only projection, with stable identity until the engine renders a new tree. */\n getRenderedSurveyItems(): ReadonlyArray<Readonly<RenderedSurveyItem>> {\n if (this.renderedItemsCache?.tree !== this.renderedSurveyTree) {\n this.renderedItemsCache = {\n tree: this.renderedSurveyTree,\n items: Object.freeze(\n flattenTree(this.renderedSurveyTree).map((item) => Object.freeze(item)),\n ),\n };\n }\n return this.renderedItemsCache.items;\n }\n\n getRenderedSurveyItem(itemId: string): RenderedSurveyItem | undefined {\n const item = this.getRenderedSurveyItems().find((item) => item.id === itemId);\n return item ? { ...item } : undefined;\n }\n\n onPageChanged(pageIndex: number) {\n this._registerSurveyEvent({\n type: SurveyEventTypes.pageChanged,\n timestamp: this._getTimestamp(),\n value: pageIndex,\n });\n }\n\n getEvents(): Readonly<Array<SurveyEvent>> {\n return this._events.slice();\n }\n\n /** Current session answers, including retained answers to hidden items. */\n getResponses(): SurveyItemResponse[] {\n return this.collectResponses(true);\n }\n\n /** Answers to currently visible items and response slots on every page; does not erase hidden session answers. */\n getSubmissionResponses(): SurveyItemResponse[] {\n return this.collectResponses(false);\n }\n\n /** Flat submission with events and item metadata kept separate from answer identity. */\n getSurveyResponse(key: string, includeHidden = false): SurveyResponse {\n const response = new SurveyResponse(key);\n for (const item of this.collectResponses(includeHidden)) response.addItemResponse(item);\n response.evaluationContext = structuredClone({\n locale: this.context.locale,\n participantFlags: this.context.participantFlags,\n });\n response.events = structuredClone(this._events);\n response.context = this.context.customValues && structuredClone(this.context.customValues);\n return response;\n }\n\n getAnswer(slotId: string): ResponseValue | undefined {\n const owner = this.surveyDef.getResponseSlotRegistry().get(slotId);\n if (!owner) throw new Error(`Unknown response slot \"${slotId}\"`);\n return owner.computed\n ? this.getComputedResponseValue(slotId)\n : this.responses[owner.itemId]?.response?.get(slotId);\n }\n\n setAnswer(slotId: string, value: ResponseValue | undefined): void {\n const owner = this.surveyDef.getResponseSlotRegistry().get(slotId);\n if (!owner || owner.computed)\n throw new Error(`Cannot write unknown or computed response slot \"${slotId}\"`);\n const response = this.responses[owner.itemId]?.response?.clone() ?? new ResponseItem();\n response.setSlotValue(slotId, value);\n this.setResponse(owner.itemId, response);\n }\n\n private collectResponses(includeHidden: boolean): SurveyItemResponse[] {\n const renderedPositions = new Map<string, number>();\n flattenTree(this.renderedSurveyTree)\n .filter((item) => item.type !== ReservedSurveyItemTypes.PageBreak)\n .forEach((item, index) => {\n if (this.responses[item.id]) {\n renderedPositions.set(item.id, index);\n }\n });\n\n const active = includeHidden ? undefined : this.activeEvaluation();\n const responses: SurveyItemResponse[] = [];\n this.surveyDef.surveyItems.forEach((item, itemId) => {\n if (!item.isInteractive()) {\n return;\n }\n\n const response = this.getResponseItem(itemId);\n if (!response) {\n return;\n }\n\n const position = renderedPositions.get(itemId);\n response.meta = position === undefined ? undefined : { position };\n if (!includeHidden && position === undefined) return;\n if (includeHidden) {\n responses.push(response);\n return;\n }\n const submission = new SurveyItemResponse(response, active!.getItemResponse(itemId));\n submission.meta = response.meta && { ...response.meta };\n responses.push(submission);\n });\n\n return responses;\n }\n\n /** Author and intrinsic validation failures, restricted to currently rendered items. */\n getInvalidResponseItems(itemIds?: readonly string[]): string[] {\n const rendered = new Set(this.getRenderedSurveyItems().map((item) => item.id));\n return [...new Set(itemIds ?? rendered)].filter(\n (id) =>\n rendered.has(id) &&\n Object.values(this.getValidationValues(id) ?? {}).some((valid) => !valid),\n );\n }\n\n getIntrinsicValidationValues(itemKey: string): Record<string, boolean> {\n const active = this.activeEvaluation();\n if (!active.isItemVisible(itemKey)) return {};\n return {\n ...this.surveyDef.surveyItems.get(itemKey)?.getResponseValidationValues(\n active.getItemResponse(itemKey),\n (id) => active.isComponentVisible(itemKey, id),\n (expression) => active.evaluator.eval(Expression.deserialize(expression)),\n ),\n };\n }\n\n getAuthorValidationValues(itemKey: string): Record<string, boolean> {\n if (!this.activeEvaluation().isItemVisible(itemKey)) return {};\n return Object.fromEntries(\n Object.entries(this.cache.validations[itemKey] ?? {}).map(([key, validation]) => [\n key,\n validation.result,\n ]),\n );\n }\n\n getDisplayConditionValue(itemKey: string, componentKey?: string): boolean | undefined {\n if (componentKey) {\n return this.cache.displayConditions[itemKey]?.components?.[componentKey]?.result;\n }\n return this.cache.displayConditions[itemKey]?.root?.result;\n }\n\n getDisabledConditionValue(itemKey: string, componentKey: string): boolean | undefined {\n return this.cache.disabledConditions[itemKey]?.components?.[componentKey]?.result;\n }\n\n getTemplateValue(templateValueKey: string): ResponseValue | undefined {\n return this.cache.templateValues[templateValueKey]?.value;\n }\n\n getValidationValues(itemKey: string):\n | {\n [validationKey: string]: boolean;\n }\n | undefined {\n const result = this.getIntrinsicValidationValues(itemKey);\n for (const [key, valid] of Object.entries(this.getAuthorValidationValues(itemKey)))\n result[key] = valid && (result[key] ?? true);\n return Object.keys(result).length ? result : undefined;\n }\n\n // INIT METHODS\n\n private initCache() {\n this.cache = {\n validations: {},\n displayConditions: {},\n templateValues: {},\n disabledConditions: {},\n };\n\n const templateKeys = this.surveyDef.getTemplateValueKeys();\n templateKeys.forEach((templateKey) => {\n this.cache.templateValues[templateKey] = {\n value: undefined,\n templateDef: this.surveyDef.getTemplateValue(templateKey),\n };\n });\n\n this.surveyDef.surveyItems.forEach((item, itemId) => {\n // Init validations\n if (item.validations && Object.keys(item.validations).length > 0) {\n this.cache.validations[itemId] = {};\n Object.keys(item.validations).forEach((validationKey) => {\n const valExp = item.validations![validationKey];\n if (!valExp) {\n console.warn(\n \"initCache: validation expression not found: \" + itemId + \" \" + validationKey,\n );\n return;\n }\n this.cache.validations[itemId][validationKey] = {\n expression: valExp,\n result: false,\n };\n });\n }\n\n // Init display conditions\n if (\n item.displayConditions !== undefined &&\n (item.displayConditions.root || item.displayConditions.components)\n ) {\n this.cache.displayConditions[itemId] = {};\n if (item.displayConditions.root) {\n this.cache.displayConditions[itemId].root = {\n expression: item.displayConditions.root,\n result: false,\n };\n }\n if (item.displayConditions.components) {\n this.cache.displayConditions[itemId].components = {};\n Object.keys(item.displayConditions.components).forEach((componentKey) => {\n const compExp = item.displayConditions?.components?.[componentKey];\n if (!compExp) {\n console.warn(\n \"initCache: display condition component expression not found: \" +\n itemId +\n \" \" +\n componentKey,\n );\n return;\n }\n this.cache.displayConditions[itemId].components![componentKey] = {\n expression: compExp,\n result: false,\n };\n });\n }\n }\n\n // Init disable conditions\n if (\n item.disabledConditions !== undefined &&\n item.disabledConditions.components !== undefined\n ) {\n this.cache.disabledConditions[itemId] = {\n components: {},\n };\n Object.keys(item.disabledConditions.components).forEach((componentKey) => {\n const compExp = item.disabledConditions?.components?.[componentKey];\n if (!compExp) {\n console.warn(\n \"initCache: disabled condition component expression not found: \" +\n itemId +\n \" \" +\n componentKey,\n );\n return;\n }\n this.cache.disabledConditions[itemId].components![componentKey] = {\n expression: compExp,\n result: false,\n };\n });\n }\n });\n }\n\n private initResponseObject(items: Map<string, SurveyItemCore>): {\n [itemId: string]: SurveyItemResponse;\n } {\n const respGroup: {\n [itemId: string]: SurveyItemResponse;\n } = {};\n\n items.forEach((item, itemId) => {\n if (!item.isInteractive()) {\n return;\n } else {\n const prefill = this.prefills?.[itemId];\n const applyPrefill = prefill && prefill.itemType === item.type;\n const normalized = item.normalizeResponse(applyPrefill ? prefill.response : undefined);\n this.responseDiagnostics.set(itemId, normalized.diagnostics ?? []);\n respGroup[itemId] = new SurveyItemResponse(\n { itemId: itemId, itemType: item.type },\n normalized.response,\n );\n }\n });\n\n return respGroup;\n }\n\n private applyConfiguredPrefills() {\n const maxPasses = Math.max(this.surveyDef.surveyItems.size, 1);\n for (let pass = 0; pass < maxPasses; pass++) {\n this.evalTemplateValues(this.createEvaluator());\n let changedInPass = false;\n\n this.surveyDef.surveyItems.forEach((item) => {\n if (!item.isInteractive()) {\n return;\n }\n changedInPass = this.applyConfiguredPrefillsForItem(item) || changedInPass;\n });\n\n if (!changedInPass) {\n break;\n }\n }\n\n this.evalTemplateValues(this.createEvaluator());\n }\n\n private applyConfiguredPrefillsForItem(item: SurveyItemCore): boolean {\n const responseItem = this.responses[item.id];\n if (!responseItem) {\n return false;\n }\n\n let changed = false;\n\n for (const prefill of item.prefills ?? []) {\n const evalEngine = this.createEvaluator();\n const targetSlot = item.resolvePrefillTarget(prefill.target);\n if (!targetSlot) {\n continue;\n }\n\n const applyMode = prefill.apply ?? SurveyItemPrefillApplyMode.ifEmpty;\n if (\n applyMode === SurveyItemPrefillApplyMode.ifEmpty &&\n responseItem.response?.get(targetSlot.slotId) !== undefined\n ) {\n continue;\n }\n\n if (!this.shouldApplyConfiguredPrefill(prefill, evalEngine)) {\n continue;\n }\n\n const resolvedValue = this.resolveConfiguredPrefillValue(prefill, targetSlot, evalEngine);\n if (!resolvedValue) {\n continue;\n }\n\n const normalizedValue = item.normalizePrefillValue(prefill, targetSlot, resolvedValue);\n if (!normalizedValue) {\n continue;\n }\n\n const nextResponse = responseItem.response?.clone() ?? new ResponseItem();\n nextResponse.setSlotValue(targetSlot.slotId, normalizedValue);\n const normalized = item.normalizeResponse(nextResponse);\n this.responseDiagnostics.set(item.id, normalized.diagnostics ?? []);\n const next = normalized.response?.isEmpty() ? undefined : normalized.response;\n if (\n JSON.stringify(responseItem.response?.serialize()) !== JSON.stringify(next?.serialize())\n ) {\n changed = true;\n }\n responseItem.response = next;\n }\n\n return changed;\n }\n\n private shouldApplyConfiguredPrefill(\n prefill: SurveyItemPrefill,\n evalEngine: ExpressionEvaluator,\n ): boolean {\n if (!prefill.when) {\n return true;\n }\n\n const resolved = evalEngine.eval(prefill.when);\n return resolved?.type === ValueType.boolean && resolved.value === true;\n }\n\n private resolveConfiguredPrefillValue(\n prefill: SurveyItemPrefill,\n _target: { slotId: string },\n evalEngine: ExpressionEvaluator,\n ): ResponseValue | undefined {\n switch (prefill.source.type) {\n case \"static\":\n return prefill.source.value;\n case \"expression\":\n return evalEngine.eval(prefill.source.expression);\n case \"templateValue\":\n return this.getTemplateValue(prefill.source.key);\n case \"previousResponse\": {\n if (!this.prefillEnvironment?.getPreviousResponse) {\n return undefined;\n }\n\n const resolved = this.prefillEnvironment.getPreviousResponse({\n surveyKey: prefill.source.ref.surveyKey,\n slotId: prefill.source.ref.slotId,\n });\n\n if (!resolved) {\n return undefined;\n }\n\n return resolved;\n }\n default:\n return undefined;\n }\n }\n\n private shouldRender(itemId: string, componentId?: string): boolean {\n const displayConditionResult = this.getDisplayConditionValue(itemId, componentId);\n if (displayConditionResult !== undefined) {\n return displayConditionResult;\n }\n return true;\n }\n\n private sequentialRender(groupDef: GroupItemCore): RenderedSurveyItem {\n const newItems: RenderedSurveyItem[] = [];\n\n for (const itemId of groupDef.items || []) {\n const shouldRender = this.shouldRender(itemId);\n if (!shouldRender) {\n continue;\n }\n\n const itemDef = this.surveyDef.surveyItems.get(itemId);\n if (!itemDef) {\n console.warn(\"sequentialRender: item not found: \" + itemId);\n continue;\n }\n\n if (itemDef.type === ReservedSurveyItemTypes.Group) {\n newItems.push(this.renderGroup(itemDef as GroupItemCore));\n continue;\n }\n\n newItems.push({\n id: itemId,\n type: itemDef.type,\n });\n }\n\n return {\n id: groupDef.id,\n type: ReservedSurveyItemTypes.Group,\n items: newItems,\n };\n }\n\n private randomizedItemRender(\n groupDef: GroupItemCore,\n parent: RenderedSurveyItem,\n ): RenderedSurveyItem {\n const newItems: RenderedSurveyItem[] =\n parent.items?.filter((rItem) => this.shouldRender(rItem.id)) || [];\n\n const itemIds = groupDef.items || [];\n const shuffledIndices = shuffleIndices(itemIds.length);\n\n for (const index of shuffledIndices) {\n const itemId = itemIds[index];\n const alreadyRenderedItem = parent.items?.find((rItem) => rItem.id === itemId);\n if (alreadyRenderedItem) {\n continue;\n }\n\n const shouldRender = this.shouldRender(itemId);\n if (!shouldRender) {\n continue;\n }\n\n const itemDef = this.surveyDef.surveyItems.get(itemId);\n if (!itemDef) {\n console.warn(\"randomizedItemRender: item not found: \" + itemId);\n continue;\n }\n\n if (itemDef.type === ReservedSurveyItemTypes.Group) {\n newItems.push(this.renderGroup(itemDef as GroupItemCore, parent));\n continue;\n }\n\n newItems.push({\n id: itemId,\n type: itemDef.type,\n });\n }\n\n return {\n id: groupDef.id,\n type: ReservedSurveyItemTypes.Group,\n items: newItems,\n };\n }\n\n private renderGroup(groupDef: GroupItemCore, parent?: RenderedSurveyItem): RenderedSurveyItem {\n if (!this.activeEvaluation().isItemVisible(groupDef.id))\n return { id: groupDef.id, type: groupDef.type, items: [] };\n if (!parent) {\n parent = {\n id: groupDef.id,\n type: ReservedSurveyItemTypes.Group,\n items: [],\n };\n }\n\n if (groupDef.config.shuffleItems) {\n return this.randomizedItemRender(groupDef, parent);\n }\n\n return this.sequentialRender(groupDef);\n }\n\n private reRenderSurveyTree() {\n if (!this.surveyDef.rootItem) {\n throw new Error(\"reRenderSurveyTree: root item not found\");\n }\n this.renderedSurveyTree = this.renderGroup(this.surveyDef.rootItem as GroupItemCore);\n }\n\n private _registerSurveyEvent(event: SurveyEvent) {\n this._events.push(event);\n }\n\n private _getTimestamp(): number {\n return Math.floor(Date.now() / 1000);\n }\n\n getResponseItem(itemId: string): SurveyItemResponse | undefined {\n return this.responses[itemId];\n }\n\n /** Resolve computed references against current answers and conditions, with cycle detection. */\n getComputedResponseValue(slotId: string): ResponseValue | undefined {\n return this.activeEvaluation().getAnswer(slotId);\n }\n\n /** Evaluate against the same current responses/context used by conditions and prefills. */\n evaluateExpression(expression: JsonExpression): ResponseValue | undefined {\n return this.activeEvaluation().evaluator.eval(Expression.deserialize(expression));\n }\n\n private activeEvaluation() {\n return (this.activeState ??= this.activeResponsePlan.evaluate(this.responses, this.context));\n }\n\n private createEvaluator(): ExpressionEvaluator {\n return this.activeResponsePlan.evaluate(this.responses, this.context).evaluator;\n }\n\n /** Active answer used by conditions and scoring; hidden session values remain in getAnswer(). */\n getActiveAnswer(slotId: string): ResponseValue | undefined {\n return this.activeEvaluation().getAnswer(slotId);\n }\n\n /** Validate static runtime contracts without constructing a response session. */\n static getConfigurationIssues(survey: Survey): string[] {\n return SurveyEngineCore.inspectConfiguration(survey).issues;\n }\n\n private static inspectConfiguration(survey: Survey) {\n const issues = [...survey.surveyItems.values()].flatMap((item) =>\n item\n .getExecutionConfigurationIssues()\n .map((issue) => `${(item.metadata?.itemLabel ?? \"\")?.trim() || item.id}: ${issue}`),\n );\n let plan: ActiveResponsePlan | undefined;\n try {\n plan = new ActiveResponsePlan(survey);\n } catch (error) {\n issues.push(error instanceof Error ? error.message : String(error));\n }\n issues.push(\n ...survey.getResponseSlotRegistry().diagnostics.map((diagnostic) => diagnostic.message),\n );\n issues.push(...survey.getBlockingExpressionIssues());\n return { issues, plan };\n }\n\n private evalExpressions() {\n this.activeState = this.activeResponsePlan.evaluate(this.responses, this.context);\n const evalEngine = this.activeState.evaluator;\n this.evalTemplateValues(evalEngine);\n this.evalDisplayConditions();\n this.evalDisableConditions(evalEngine);\n this.evalValidations(evalEngine);\n }\n\n private evalTemplateValues(evalEngine: ExpressionEvaluator) {\n Object.keys(this.cache.templateValues).forEach((templateValueKey) => {\n const templateValue = this.cache.templateValues[templateValueKey];\n this.cache.templateValues[templateValueKey].value = undefined;\n if (!templateValue.templateDef?.expression) {\n console.warn(\n \"evalTemplateValues: template value expression not found: \" + templateValueKey,\n );\n return;\n }\n\n let evaluatedValue = evalEngine.eval(templateValue.templateDef.expression);\n if (evaluatedValue === undefined) {\n console.warn(\n \"evalTemplateValues: template value expression returned undefined: \" + templateValueKey,\n );\n return;\n }\n\n switch (templateValue.templateDef.type) {\n case TemplateDefTypes.Date2String:\n if (evaluatedValue.type !== ValueType.date) {\n console.warn(\n \"evalTemplateValues: template value expression returned non-date value: \" +\n templateValueKey,\n );\n return;\n }\n evaluatedValue = {\n type: ValueType.string,\n value: formatCalendarDate(\n evaluatedValue.value,\n (templateValue.templateDef as TemplateValueFormatDate).dateFormat,\n ),\n };\n break;\n default:\n break;\n }\n this.cache.templateValues[templateValueKey].value = evaluatedValue;\n });\n }\n\n private evalDisplayConditions() {\n const active = this.activeEvaluation();\n for (const [itemId, conditions] of Object.entries(this.cache.displayConditions)) {\n if (conditions.root) conditions.root.result = active.isItemVisible(itemId);\n for (const [id, condition] of Object.entries(conditions.components ?? {}))\n condition.result = active.isComponentVisible(itemId, id);\n }\n }\n\n private evalDisableConditions(evalEngine: ExpressionEvaluator) {\n Object.keys(this.cache.disabledConditions).forEach((itemKey) => {\n const disableCondition = this.cache.disabledConditions[itemKey];\n if (disableCondition.components) {\n Object.keys(disableCondition.components).forEach((componentKey) => {\n const resolvedValue = evalEngine.eval(\n disableCondition.components![componentKey].expression,\n );\n if (resolvedValue === undefined || resolvedValue.type !== ValueType.boolean) {\n console.warn(\n \"evalDisableConditions: disable condition component expression returned undefined: \" +\n itemKey +\n \".\" +\n componentKey,\n );\n return;\n }\n this.cache.disabledConditions[itemKey].components![componentKey].result =\n resolvedValue.value;\n });\n }\n });\n }\n\n private evalValidations(evalEngine: ExpressionEvaluator) {\n Object.keys(this.cache.validations).forEach((itemId) => {\n const validation = this.cache.validations[itemId];\n\n Object.keys(validation).forEach((validationKey) => {\n const resolvedValue = evalEngine.eval(validation[validationKey].expression);\n if (resolvedValue === undefined || resolvedValue.type !== ValueType.boolean) {\n console.warn(\n \"evalValidations: validation expression returned undefined: \" +\n itemId +\n \".\" +\n validationKey,\n );\n this.cache.validations[itemId][validationKey].result = false;\n return;\n }\n this.cache.validations[itemId][validationKey].result = resolvedValue.value;\n });\n });\n }\n}\n\nexport const flattenTree = (itemTree: RenderedSurveyItem): RenderedSurveyItem[] => {\n const flatTree = new Array<RenderedSurveyItem>();\n\n itemTree.items?.forEach((item) => {\n if (item.type === ReservedSurveyItemTypes.Group) {\n flatTree.push(...flattenTree(item));\n } else {\n flatTree.push({ ...item });\n }\n });\n return flatTree;\n};\n","import { structuredCloneMethod } from \"./utils\";\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonObject = { [key: string]: JsonValue };\nexport type JsonValue = JsonPrimitive | JsonObject | JsonValue[];\n\nexport type JsonPatchOperation =\n | {\n op: \"add\" | \"replace\" | \"test\";\n path: string;\n value: JsonValue;\n }\n | {\n op: \"remove\";\n path: string;\n }\n | {\n op: \"move\" | \"copy\";\n from: string;\n path: string;\n };\n\nexport class JsonPatchError extends Error {\n constructor(\n message: string,\n readonly code: string,\n readonly path?: string,\n readonly operationIndex?: number,\n ) {\n super(message);\n this.name = \"JsonPatchError\";\n }\n}\n\nconst hasOwn = (value: object, key: string) => Object.prototype.hasOwnProperty.call(value, key);\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst assertValidPointerSegment = (segment: string, pointer: string) => {\n if (/~(?![01])/.test(segment)) {\n throw new JsonPatchError(\n `Invalid JSON pointer segment \"${segment}\" in \"${pointer}\". Only \"~0\" and \"~1\" escapes are allowed.`,\n \"invalid-json-pointer\",\n pointer,\n );\n }\n};\n\nexport const decodeJsonPointerSegment = (segment: string): string => {\n assertValidPointerSegment(segment, segment);\n return segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n};\n\nexport const encodeJsonPointerSegment = (segment: string): string =>\n segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n\nexport const parseJsonPointer = (pointer: string): string[] => {\n if (pointer === \"\") {\n return [];\n }\n\n if (!pointer.startsWith(\"/\")) {\n throw new JsonPatchError(\n `Invalid JSON pointer \"${pointer}\". It must be empty or start with \"/\".`,\n \"invalid-json-pointer\",\n pointer,\n );\n }\n\n return pointer\n .slice(1)\n .split(\"/\")\n .map((segment) => {\n assertValidPointerSegment(segment, pointer);\n return segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n });\n};\n\nconst parseArrayIndex = ({\n segment,\n arrayLength,\n allowAppend,\n allowEnd,\n path,\n}: {\n segment: string;\n arrayLength: number;\n allowAppend: boolean;\n allowEnd: boolean;\n path: string;\n}) => {\n if (segment === \"-\") {\n if (allowAppend) {\n return arrayLength;\n }\n\n throw new JsonPatchError(\n `JSON pointer \"${path}\" uses \"-\" where an existing array index is required.`,\n \"invalid-array-index\",\n path,\n );\n }\n\n if (!/^(0|[1-9][0-9]*)$/.test(segment)) {\n throw new JsonPatchError(\n `JSON pointer \"${path}\" uses invalid array index \"${segment}\".`,\n \"invalid-array-index\",\n path,\n );\n }\n\n const index = Number(segment);\n const maximum = allowEnd ? arrayLength : arrayLength - 1;\n if (index < 0 || index > maximum) {\n throw new JsonPatchError(\n `JSON pointer \"${path}\" array index ${index} is out of bounds.`,\n \"array-index-out-of-bounds\",\n path,\n );\n }\n\n return index;\n};\n\nconst getValueAtSegments = (document: unknown, segments: string[], path: string): unknown => {\n let current = document;\n\n for (const segment of segments) {\n if (Array.isArray(current)) {\n const index = parseArrayIndex({\n segment,\n arrayLength: current.length,\n allowAppend: false,\n allowEnd: false,\n path,\n });\n current = current[index];\n continue;\n }\n\n if (!isRecord(current) || !hasOwn(current, segment)) {\n throw new JsonPatchError(`JSON pointer \"${path}\" does not exist.`, \"path-not-found\", path);\n }\n\n current = current[segment];\n }\n\n return current;\n};\n\nexport const getValueAtJsonPointer = <T = unknown>(document: unknown, pointer: string): T => {\n const segments = parseJsonPointer(pointer);\n return getValueAtSegments(document, segments, pointer) as T;\n};\n\nconst deepEqualJson = (left: unknown, right: unknown): boolean => {\n if (left === right) {\n return true;\n }\n\n if (Array.isArray(left) || Array.isArray(right)) {\n if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) {\n return false;\n }\n\n return left.every((entry, index) => deepEqualJson(entry, right[index]));\n }\n\n if (isRecord(left) || isRecord(right)) {\n if (!isRecord(left) || !isRecord(right)) {\n return false;\n }\n\n const leftKeys = Object.keys(left).sort();\n const rightKeys = Object.keys(right).sort();\n if (leftKeys.length !== rightKeys.length) {\n return false;\n }\n\n return leftKeys.every(\n (key, index) => key === rightKeys[index] && deepEqualJson(left[key], right[key]),\n );\n }\n\n return false;\n};\n\nconst applyAdd = (document: unknown, path: string, value: JsonValue): unknown => {\n const segments = parseJsonPointer(path);\n if (segments.length === 0) {\n return structuredCloneMethod(value);\n }\n\n const parentSegments = segments.slice(0, -1);\n const key = segments[segments.length - 1];\n const parent = getValueAtSegments(document, parentSegments, path);\n\n if (Array.isArray(parent)) {\n const index = parseArrayIndex({\n segment: key,\n arrayLength: parent.length,\n allowAppend: true,\n allowEnd: true,\n path,\n });\n parent.splice(index, 0, structuredCloneMethod(value));\n return document;\n }\n\n if (!isRecord(parent)) {\n throw new JsonPatchError(\n `JSON pointer \"${path}\" parent is not an object or array.`,\n \"invalid-target-parent\",\n path,\n );\n }\n\n // Assignment to the special `__proto__` key invokes Object.prototype's\n // legacy setter instead of creating JSON data. Define the property directly\n // so every valid JSON Pointer key, including `__proto__`, keeps ordinary\n // own-property semantics without changing the target object's prototype.\n Object.defineProperty(parent, key, {\n configurable: true,\n enumerable: true,\n value: structuredCloneMethod(value),\n writable: true,\n });\n return document;\n};\n\nconst applyRemove = (\n document: unknown,\n path: string,\n): {\n document: unknown;\n removedValue: unknown;\n} => {\n const segments = parseJsonPointer(path);\n if (segments.length === 0) {\n throw new JsonPatchError(\"Removing the document root is not supported.\", \"remove-root\", path);\n }\n\n const parentSegments = segments.slice(0, -1);\n const key = segments[segments.length - 1];\n const parent = getValueAtSegments(document, parentSegments, path);\n\n if (Array.isArray(parent)) {\n const index = parseArrayIndex({\n segment: key,\n arrayLength: parent.length,\n allowAppend: false,\n allowEnd: false,\n path,\n });\n const [removedValue] = parent.splice(index, 1);\n return { document, removedValue };\n }\n\n if (!isRecord(parent) || !hasOwn(parent, key)) {\n throw new JsonPatchError(`JSON pointer \"${path}\" does not exist.`, \"path-not-found\", path);\n }\n\n const removedValue = parent[key];\n delete parent[key];\n return { document, removedValue };\n};\n\nconst applyReplace = (document: unknown, path: string, value: JsonValue): unknown => {\n const segments = parseJsonPointer(path);\n if (segments.length === 0) {\n return structuredCloneMethod(value);\n }\n\n getValueAtSegments(document, segments, path);\n applyRemove(document, path);\n return applyAdd(document, path, value);\n};\n\nconst assertMoveTargetIsNotDescendant = (from: string, path: string) => {\n if (from === \"\" || path === from || !path.startsWith(`${from}/`)) {\n return;\n }\n\n throw new JsonPatchError(\n `JSON Patch cannot move \"${from}\" into its own descendant \"${path}\".`,\n \"move-into-descendant\",\n path,\n );\n};\n\nexport const applyJsonPatch = <T>(document: T, operations: readonly JsonPatchOperation[]): T => {\n let patchedDocument = structuredCloneMethod(document) as unknown;\n\n operations.forEach((operation, operationIndex) => {\n try {\n switch (operation.op) {\n case \"add\":\n patchedDocument = applyAdd(patchedDocument, operation.path, operation.value);\n break;\n case \"remove\":\n patchedDocument = applyRemove(patchedDocument, operation.path).document;\n break;\n case \"replace\":\n patchedDocument = applyReplace(patchedDocument, operation.path, operation.value);\n break;\n case \"move\": {\n assertMoveTargetIsNotDescendant(operation.from, operation.path);\n if (operation.from === operation.path) {\n break;\n }\n const { document: withoutValue, removedValue } = applyRemove(\n patchedDocument,\n operation.from,\n );\n patchedDocument = applyAdd(withoutValue, operation.path, removedValue as JsonValue);\n break;\n }\n case \"copy\": {\n const value = getValueAtJsonPointer<JsonValue>(patchedDocument, operation.from);\n patchedDocument = applyAdd(patchedDocument, operation.path, value);\n break;\n }\n case \"test\": {\n const value = getValueAtJsonPointer(patchedDocument, operation.path);\n if (!deepEqualJson(value, operation.value)) {\n throw new JsonPatchError(\n `JSON Patch test failed at \"${operation.path}\".`,\n \"test-failed\",\n operation.path,\n );\n }\n break;\n }\n }\n } catch (error) {\n if (error instanceof JsonPatchError) {\n throw new JsonPatchError(error.message, error.code, error.path, operationIndex);\n }\n\n throw error;\n }\n });\n\n return patchedDocument as T;\n};\n","import type { ResponseSlotRegistry } from \"../survey/responses/slot-registry\";\nimport type { Survey } from \"../survey/survey\";\n\n/** Allow incomplete authoring drafts, but never export invalid item coding paths. */\nexport function validateExportConfiguration(\n survey: Survey,\n registry: ResponseSlotRegistry = survey.getResponseSlotRegistry(),\n): void {\n const issues = [...survey.surveyItems.values()].flatMap((item) =>\n item\n .getExecutionConfigurationIssues()\n .map((issue) => `${(item.metadata?.itemLabel ?? \"\")?.trim() || item.id}: ${issue}`),\n );\n issues.push(...registry.diagnostics.map((diagnostic) => diagnostic.message));\n issues.push(...survey.getBlockingExpressionIssues());\n if (issues.length) throw new Error(issues.join(\"\\n\"));\n}\n","import type { ExportColumn, ExportRow, CsvExportOptions } from \"./types\";\n\nconst DEFAULT_OPTIONS: Required<CsvExportOptions> = {\n separator: \",\",\n lineEnding: \"\\n\",\n includeHeader: true,\n};\n\n/**\n * Escape a cell value for CSV. Quotes the cell when it contains separator, quote, CR, or LF.\n * Doubles embedded quotes. Preserves multiline content inside quoted cells.\n */\nexport function escapeCsvCell(value: string, separator: string = \",\"): string {\n if (value === \"\") return value;\n\n const needsQuoting =\n value.includes(separator) ||\n value.includes('\"') ||\n value.includes(\"\\r\") ||\n value.includes(\"\\n\");\n\n if (!needsQuoting) return value;\n\n return `\"${value.replace(/\"/g, '\"\"')}\"`;\n}\n\n/**\n * Serialize export rows to CSV string.\n */\nexport function serializeToCsv(\n columns: ExportColumn[],\n rows: ExportRow[],\n options?: CsvExportOptions,\n): string {\n const opts = { ...DEFAULT_OPTIONS, ...options };\n const sep = opts.separator;\n const lines: string[] = [];\n\n const headers = columns.map((c) => c.header);\n\n if (opts.includeHeader) {\n lines.push(headers.map((header) => escapeCsvCell(header, sep)).join(sep));\n }\n\n for (const row of rows) {\n const cells = headers.map((header) => escapeCsvCell(row[header] ?? \"\", sep));\n lines.push(cells.join(sep));\n }\n\n return lines.join(opts.lineEnding);\n}\n","import { projectSlot, formatProjectedValue, resolvedSlotEncoding } from \"./projection\";\nimport { ActiveResponsePlan } from \"../engine/active-responses\";\nimport { ResponseItem, SurveyItemResponse } from \"../survey/responses\";\nimport { format } from \"date-fns/format\";\nimport { validateExportConfiguration } from \"./validate-configuration\";\nimport type { ResponseSlotRegistry } from \"../survey/responses/slot-registry\";\nimport type { OwnedResponseSlotDefinition } from \"../survey/responses\";\nimport { SurveyResponse } from \"../survey/responses/survey-response\";\nimport { ValueType } from \"../survey/responses/value-types\";\nimport { exportSingleResponseSlot, DEFAULT_TRANSFORM } from \"./slot-formatter\";\nimport { serializeToCsv } from \"./csv-serializer\";\nimport { encodeExportColumnId } from \"./column-id\";\nimport {\n EXPORTER_PROFILE_SCHEMA_VERSION,\n META_COLUMN_ORDER,\n type ExportBatch,\n type CombinedExportOptions,\n type ExporterProfile,\n type ExportColumn,\n type SlotTransformConfig,\n type ExportRow,\n type CsvExportOptions,\n ExportColumnSource,\n} from \"./types\";\n\n// Object property order and categorical option display order do not change meaning.\nconst canonical = (value: unknown): string =>\n JSON.stringify(value, (_key, entry) =>\n entry && typeof entry === \"object\" && !Array.isArray(entry)\n ? Object.fromEntries(Object.entries(entry).sort(([a], [b]) => a.localeCompare(b)))\n : entry,\n );\n\ninterface ExportContext {\n registry: ResponseSlotRegistry;\n slots: Map<string, OwnedResponseSlotDefinition>;\n profile: ExporterProfile | undefined;\n columns: ExportColumn[];\n included: Set<string>;\n activePlan?: ActiveResponsePlan;\n transforms: Map<string, SlotTransformConfig>;\n encodings: Map<string, string>;\n}\n\n/** Export only against schemas selected by the host, never against response version tags. */\nexport class SurveyResponseExporter {\n constructor(\n private readonly batches: ExportBatch[],\n private readonly options: CombinedExportOptions = {},\n ) {\n if (!batches.length) throw new Error(\"Supply at least one schema-bound export batch\");\n if (batches.some((batch) => !batch.schema || !Array.isArray(batch.responses)))\n throw new Error(\"Each export batch requires a schema and responses array\");\n if (batches.length > 1 && !options.codingPolicy)\n throw new Error(\"Combined export requires an explicit original or harmonized coding policy\");\n }\n\n private batch(index: number): ExportBatch {\n const batch = this.batches[index];\n if (!batch) throw new Error(`Unknown export batch: ${index}`);\n return batch;\n }\n\n private profile(batch: ExportBatch): ExporterProfile | undefined {\n if (!this.options.profile) return batch.profile;\n return {\n ...batch.profile,\n ...this.options.profile,\n slotOverrides: { ...batch.profile?.slotOverrides, ...this.options.profile.slotOverrides },\n columnHeaders: { ...batch.profile?.columnHeaders, ...this.options.profile.columnHeaders },\n contextOverrides: {\n ...batch.profile?.contextOverrides,\n ...this.options.profile.contextOverrides,\n },\n };\n }\n\n // Snapshots live for one operation only: later exports must observe schema/profile edits.\n private compileContexts(): Map<ExportBatch, ExportContext> {\n return new Map(\n this.batches.map((batch) => {\n const registry = batch.schema.getResponseSlotRegistry();\n validateExportConfiguration(batch.schema, registry);\n const slots = new Map(registry.definitions.map((slot) => [slot.slotId, slot]));\n const profile = this.profile(batch);\n const transforms = new Map(\n [...slots.values()].map((slot) => [\n slot.slotId,\n {\n ...DEFAULT_TRANSFORM,\n ...slot.exportSettings,\n ...profile?.slotOverrides?.[slot.slotId],\n },\n ]),\n );\n const columns = [...slots.values()].flatMap((slot) =>\n projectSlot(slot, transforms.get(slot.slotId)!).map((column) => ({\n ...column,\n header: profile?.columnHeaders?.[column.id]?.trim() ?? column.header,\n })),\n );\n const encodings = new Map<string, string>();\n for (const slotId of new Set(columns.map((column) => column.slotId!))) {\n const { include: _include, ...encoding } = resolvedSlotEncoding(\n slots.get(slotId)!,\n transforms.get(slotId)!,\n );\n encodings.set(slotId, canonical(encoding));\n }\n return [\n batch,\n {\n registry,\n slots,\n profile,\n transforms,\n encodings,\n columns,\n included: new Set(columns.map((column) => column.id)),\n activePlan: columns.some((column) => slots.get(column.slotId!)?.computed)\n ? new ActiveResponsePlan(batch.schema)\n : undefined,\n },\n ];\n }),\n );\n }\n\n private validateProfile(\n profile: ExporterProfile | undefined,\n batches: ExportBatch[],\n contexts: Map<ExportBatch, ExportContext>,\n extraResponses: SurveyResponse[] = [],\n ): void {\n if (!profile) return;\n if (profile.schemaVersion !== EXPORTER_PROFILE_SCHEMA_VERSION)\n throw new Error(\n `Unsupported exporter profile schema version: ${String(profile.schemaVersion)}`,\n );\n const slots = new Map(batches.flatMap((batch) => [...contexts.get(batch)!.slots]));\n const contextKeys = new Set(\n [...batches.flatMap((batch) => batch.responses), ...extraResponses].flatMap((response) =>\n Object.keys(response.context ?? {}),\n ),\n );\n const columns = new Set([\n ...[...slots.values()].flatMap((slot) =>\n projectSlot(slot, { mode: \"default\" }, true).map((column) => column.id),\n ),\n ...META_COLUMN_ORDER.map((field) => encodeExportColumnId([\"meta\", field])),\n ...[...contextKeys].map((key) => encodeExportColumnId([\"context\", key])),\n ]);\n for (const id of Object.keys(profile.slotOverrides ?? {}))\n if (!slots.has(id)) throw new Error(`Profile references unknown response slot \"${id}\"`);\n for (const id of [\n ...Object.keys(profile.columnHeaders ?? {}),\n ...(profile.responseColumnOrder ?? []),\n ])\n if (!columns.has(id)) throw new Error(`Profile references unknown export column \"${id}\"`);\n for (const id of profile.responseColumnOrder ?? [])\n if (\n ![...slots.values()].some((slot) =>\n projectSlot(slot, { mode: \"default\" }, true).some((column) => column.id === id),\n )\n )\n throw new Error(`Response column order contains a non-response column: ${id}`);\n for (const key of [\n ...Object.keys(profile.contextOverrides ?? {}),\n ...(profile.contextColumnOrder ?? []),\n ])\n if (!contextKeys.has(key)) throw new Error(`Profile references unknown context key \"${key}\"`);\n for (const slot of slots.values()) {\n if (\n (slot.naming?.kind === \"matrix\" || slot.rowId || slot.columnId) &&\n projectSlot(slot, { mode: \"default\" }, true).some((column) =>\n Object.hasOwn(profile.columnHeaders ?? {}, column.id),\n )\n )\n throw new Error(\n `Matrix variable \"${slot.slotId}\" cannot have an individual header override; edit its matrix coding components`,\n );\n }\n for (const [id, header] of Object.entries(profile.columnHeaders ?? {}))\n if (typeof header !== \"string\" || !header.trim())\n throw new Error(`Export header for \"${id}\" cannot be empty`);\n if (new Set(profile.responseColumnOrder).size !== (profile.responseColumnOrder?.length ?? 0))\n throw new Error(\"Response column order contains duplicate identities\");\n }\n\n computeResponseColumns(batchIndex = 0, extraResponses: SurveyResponse[] = []): ExportColumn[] {\n const batch = this.batch(batchIndex);\n const contexts = this.compileContexts();\n this.validateProfile(batch.profile, [batch], contexts, extraResponses);\n this.validateProfile(this.options.profile, this.batches, contexts, extraResponses);\n return contexts.get(batch)!.columns;\n }\n\n computeColumns(extraResponses: SurveyResponse[] = []): ExportColumn[] {\n return this.columns(this.compileContexts(), extraResponses);\n }\n\n private columns(\n contexts: Map<ExportBatch, ExportContext>,\n extraResponses: SurveyResponse[] = [],\n ): ExportColumn[] {\n this.validateProfile(this.options.profile, this.batches, contexts, extraResponses);\n const columns = new Map<string, ExportColumn>();\n const signatures = new Map<string, string>();\n const encodings = new Map<string, string>();\n this.batches.forEach((batch) => {\n const context = contexts.get(batch)!;\n this.validateProfile(batch.profile, [batch], contexts, extraResponses);\n for (const slot of context.slots.values()) {\n const signature = canonical({\n type: slot.valueType,\n allowedValues: slot.allowedValues?.map((value) => canonical(value)).sort(),\n codes:\n this.options.codingPolicy === \"harmonized\"\n ? (context.profile?.slotOverrides?.[slot.slotId]?.optionCodes ??\n slot.referenceValueKeys)\n : slot.referenceValueKeys,\n computed: slot.computed,\n scores: slot.referenceValueScores,\n });\n const previous = signatures.get(slot.slotId);\n if (previous && previous !== signature)\n throw new Error(\n `Incompatible schema definitions for slot \"${slot.slotId}\"; supply a compatible explicit harmonization mapping`,\n );\n signatures.set(slot.slotId, signature);\n }\n for (const column of context.columns) {\n const signature = context.encodings.get(column.slotId!)!;\n if (encodings.has(column.id) && encodings.get(column.id) !== signature)\n throw new Error(\n `Incompatible export encodings for column \"${column.id}\"; supply one harmonized profile`,\n );\n encodings.set(column.id, signature);\n const existing = columns.get(column.id);\n if (existing && existing.header !== column.header)\n throw new Error(\n `Conflicting names for column \"${column.id}\"; select an explicit harmonized output header`,\n );\n columns.set(column.id, column);\n }\n });\n const profile =\n this.options.profile ?? (this.batches.length === 1 ? this.batches[0].profile : undefined);\n const allResponses = [...this.batches.flatMap((batch) => batch.responses), ...extraResponses];\n const contextKeys = [\n ...new Set(allResponses.flatMap((response) => Object.keys(response.context ?? {}))),\n ];\n const ordered = <T>(\n values: T[],\n order: string[],\n id: (value: T) => string,\n name: (value: T) => string,\n ) =>\n values.sort((a, b) => {\n const left = order.indexOf(id(a)),\n right = order.indexOf(id(b));\n if (left >= 0 || right >= 0)\n return (left < 0 ? Infinity : left) - (right < 0 ? Infinity : right);\n return name(a).localeCompare(name(b));\n });\n const result: ExportColumn[] = [\n ...META_COLUMN_ORDER.map((field) => ({\n id: encodeExportColumnId([\"meta\", field]),\n header: profile?.columnHeaders?.[encodeExportColumnId([\"meta\", field])]?.trim() ?? field,\n source: ExportColumnSource.meta,\n metaField: field,\n })),\n ...ordered(\n contextKeys,\n profile?.contextColumnOrder ?? [],\n (value) => value,\n (value) => value,\n ).map((key) => ({\n id: encodeExportColumnId([\"context\", key]),\n header:\n profile?.columnHeaders?.[encodeExportColumnId([\"context\", key])]?.trim() ??\n `context.${key}`,\n source: ExportColumnSource.context,\n contextKey: key,\n })),\n ...ordered(\n [...columns.values()],\n profile?.responseColumnOrder ?? [],\n (value) => value.id,\n (value) => value.header,\n ),\n ];\n const headers = new Set<string>();\n for (const column of result) {\n if (headers.has(column.header))\n throw new Error(`Duplicate export column header '${column.header}'`);\n headers.add(column.header);\n }\n return result;\n }\n\n private row(\n response: SurveyResponse,\n batch: ExportBatch,\n columns: ExportColumn[],\n context: ExportContext,\n ): ExportRow {\n const { registry, slots, profile, included, transforms } = context;\n const diagnostics = registry.validateAnswers(response.answers);\n if (diagnostics.length) throw new Error(diagnostics.map((issue) => issue.message).join(\"\\n\"));\n const row: ExportRow = Object.create(null);\n const recorded: Record<string, SurveyItemResponse> = Object.create(null);\n if (context.activePlan) {\n for (const [slotId, value] of Object.entries(response.answers)) {\n const slot = slots.get(slotId)!;\n const item = batch.schema.surveyItems.get(slot.itemId)!;\n const target = (recorded[slot.itemId] ??= new SurveyItemResponse(\n { itemId: slot.itemId, itemType: item.type },\n new ResponseItem(),\n ));\n target.response!.setSlotValue(slotId, structuredClone(value));\n }\n }\n const active = context.activePlan?.evaluate(recorded, {\n locale: response.evaluationContext?.locale ?? batch.schema.locales[0] ?? \"en\",\n participantFlags: response.evaluationContext?.participantFlags,\n customValues: response.context,\n });\n for (const column of columns) {\n if (column.source === ExportColumnSource.meta) {\n switch (column.metaField) {\n case \"responseId\":\n row[column.header] = response.key;\n break;\n case \"participantId\":\n row[column.header] = response.participantId ?? \"\";\n break;\n case \"sourceId\":\n row[column.header] = batch.sourceId ?? \"\";\n break;\n case \"submittedAt\":\n row[column.header] = response.submittedAt\n ? format(new Date(response.submittedAt * 1000), \"yyyy-MM-dd'T'HH:mm:ss.SSSxxx\")\n : \"\";\n break;\n }\n } else if (column.source === ExportColumnSource.context) {\n const value = response.context?.[column.contextKey!];\n row[column.header] = exportSingleResponseSlot({\n value,\n valueType: value?.type ?? ValueType.string,\n transformConfig: profile?.contextOverrides?.[column.contextKey!] ?? {\n ...DEFAULT_TRANSFORM,\n categorical: \"ids\",\n },\n });\n } else {\n const slot = slots.get(column.slotId!);\n row[column.header] =\n slot && included.has(column.id)\n ? formatProjectedValue(\n slot,\n column,\n slot.computed ? active?.getAnswer(slot.slotId) : response.answers[slot.slotId],\n transforms.get(slot.slotId)!,\n )\n : \"\";\n }\n }\n return row;\n }\n\n /** Explicitly associate one response with a supplied batch schema. */\n exportResponse(response: SurveyResponse, batchIndex = 0): ExportRow {\n return new SurveyResponseExporter([{ ...this.batch(batchIndex), responses: [response] }], {\n profile: this.options.profile,\n }).exportRows()[0];\n }\n\n exportRows(): ExportRow[] {\n const contexts = this.compileContexts();\n return this.rows(this.columns(contexts), contexts);\n }\n\n private rows(columns: ExportColumn[], contexts: Map<ExportBatch, ExportContext>): ExportRow[] {\n return this.batches.flatMap((batch) =>\n batch.responses.map((response) => this.row(response, batch, columns, contexts.get(batch)!)),\n );\n }\n\n exportResponsesToCsv(options?: CsvExportOptions): string {\n const contexts = this.compileContexts();\n const columns = this.columns(contexts);\n return serializeToCsv(columns, this.rows(columns, contexts), options);\n }\n}\n","import { resolvedSlotEncoding } from \"./projection\";\nimport { SurveyResponseExporter } from \"./exporter\";\nimport type { ExporterProfile, ExportColumn } from \"./types\";\nimport type { Survey } from \"../survey/survey\";\nimport { validateExportConfiguration } from \"./validate-configuration\";\nimport { getContentPlainText } from \"../survey/utils/content\";\nimport type { ResponseSlotDefinition } from \"../survey/responses/slot-definition\";\nimport type { ValueType } from \"../survey/responses/value-types\";\n\n/** Single slot entry in codebook. */\nexport interface CodebookSlot {\n slotId: string;\n primitiveId: string;\n rowId?: string;\n columnId?: string;\n computed?: ResponseSlotDefinition[\"computed\"];\n variableName: string;\n encoding?: import(\"./types\").SlotTransformConfig;\n optionLabels?: Record<string, Record<string, string>>;\n allowedValues?: import(\"../survey/responses\").ResponseValue[];\n valueType: ValueType;\n /** Categorical export codes for stable reference IDs; missing mappings block code exports. */\n referenceValueKeys?: Record<string, string>;\n referenceValueScores?: Record<string, number>;\n}\n\n/** Single item entry in codebook. */\nexport interface CodebookItem {\n id: string;\n editorName: string;\n breadcrumb: string;\n type: string;\n interactive: boolean;\n slots: CodebookSlot[];\n /** Content by locale, keyed by content key (e.g. 'title', 'description'). */\n contentByLocale?: Record<string, Record<string, string>>;\n}\n\n/** Full codebook for a survey. */\nexport interface Codebook {\n surveyKey?: string;\n items: CodebookItem[];\n projection: ExportColumn[];\n profile?: ExporterProfile;\n missingValue: \"\";\n}\n\n/**\n * Generate a structured codebook from a survey definition.\n */\nexport function generateCodebook(\n survey: Survey,\n options?: { locales?: string[]; profile?: ExporterProfile },\n): Codebook {\n const registry = survey.getResponseSlotRegistry();\n validateExportConfiguration(survey, registry);\n const slots = registry.definitions;\n const locales = options?.locales ?? survey.locales;\n const slotDefsByItemId = new Map<string, CodebookSlot[]>();\n for (const slot of slots) {\n const entries = slotDefsByItemId.get(slot.itemId) ?? [];\n entries.push({\n slotId: slot.slotId,\n primitiveId: slot.primitiveId,\n ...(slot.rowId ? { rowId: slot.rowId } : {}),\n ...(slot.columnId ? { columnId: slot.columnId } : {}),\n variableName: slot.variableName,\n valueType: slot.valueType,\n encoding: resolvedSlotEncoding(slot, {\n mode: \"default\",\n ...slot.exportSettings,\n ...options?.profile?.slotOverrides?.[slot.slotId],\n }),\n optionLabels: slot.referenceValueLabels,\n allowedValues: slot.allowedValues,\n ...(slot.computed ? { computed: structuredClone(slot.computed) } : {}),\n ...(slot.referenceValueKeys ? { referenceValueKeys: { ...slot.referenceValueKeys } } : {}),\n ...(slot.referenceValueScores\n ? { referenceValueScores: { ...slot.referenceValueScores } }\n : {}),\n });\n slotDefsByItemId.set(slot.itemId, entries);\n }\n\n const items: CodebookItem[] = [];\n\n for (const item of survey.surveyItems.values()) {\n const slotList = slotDefsByItemId.get(item.id) ?? [];\n slotList.sort((a, b) => a.slotId.localeCompare(b.slotId));\n\n let contentByLocale: Record<string, Record<string, string>> | undefined;\n\n if (locales.length > 0) {\n contentByLocale = {};\n const itemTranslations = survey.getItemTranslations(item.id);\n if (itemTranslations) {\n for (const locale of locales) {\n const all = itemTranslations.getAllForLocale(locale);\n if (all) {\n const flat: Record<string, string> = {};\n for (const [contentKey, content] of Object.entries(all)) {\n flat[contentKey] = getContentPlainText(content);\n }\n contentByLocale[locale] = flat;\n }\n }\n }\n }\n\n items.push({\n id: item.id,\n editorName: survey.resolveItemEditorName(item.id, locales[0]),\n breadcrumb: survey.getItemDisplayPath(item.id, locales[0])!.breadcrumb,\n type: item.type,\n interactive: item.isInteractive(),\n slots: slotList,\n contentByLocale,\n });\n }\n\n return {\n surveyKey: survey.surveyKey,\n items: items,\n projection: new SurveyResponseExporter([\n { schema: survey, responses: [], profile: options?.profile },\n ]).computeColumns(),\n profile: options?.profile && structuredClone(options.profile),\n missingValue: \"\",\n };\n}\n\n/** Describe precisely the combined projection and each host-selected source definition. */\nexport function generateExportCodebook(\n batches: import(\"./types\").ExportBatch[],\n options: import(\"./types\").CombinedExportOptions = {},\n) {\n const exporter = new SurveyResponseExporter(batches, options);\n return {\n schemaVersion: 1,\n codingPolicy: options.codingPolicy ?? \"original\",\n columns: exporter.computeColumns(),\n missingValue: \"\",\n profile: options.profile && structuredClone(options.profile),\n sources: batches.map((batch) => ({\n sourceId: batch.sourceId,\n surveySchemaVersion: batch.schema.serialize().schemaVersion,\n profile: batch.profile && structuredClone(batch.profile),\n variables: batch.schema.getResponseSlotRegistry().definitions.map((slot) => ({\n ...slot,\n encoding: resolvedSlotEncoding(slot, {\n mode: \"default\",\n ...slot.exportSettings,\n ...(options.profile?.slotOverrides?.[slot.slotId] ??\n batch.profile?.slotOverrides?.[slot.slotId]),\n }),\n })),\n })),\n };\n}\n"],"mappings":";;;;;AA8BA,MAAa,8BACX,SACqC;CACrC,MAAM,QAAS,KAAkC;CACjD,OAAO,UAAU,KAAA,KAAa,MAAM,SAAS;AAC/C;AAgEA,MAAa,2BAA2B,SAA0D;CAChG,MAAM,QAAS,KAA+B;CAC9C,OAAO,UAAU,KAAA,KAAa,MAAM,SAAS;AAC/C;;;AClGA,MAAa,mBAAmB;CAC9B,YAAY;CACZ,aAAa;CACb,iBAAiB;CACjB,iBAAiB;AACnB;;;AC6BA,SAAgB,4BACd,aACA,cAC6C;CAC7C,OAAO,aAAa,MAAM,eAAe,WAAW,OAAO,YAAY;AACzE;AAEA,SAAgB,oBACd,MACA,aACA,cACA,QACY;CACZ,MAAM,aAAa,4BAA4B,aAAa,YAAY;CACxE,IAAI,CAAC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AK,WACxC,MAAM,SAAS,gBAAgB,KAAK;IACxC,CAAC;GACH,EAAE;EACJ,EAAE;CACJ;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/json-patch.ts","../src/expressions/shortcuts/selection.ts","../src/survey/utils/group-utils.ts","../src/expressions/editors/expression-editor.ts","../src/expressions/editors/expression-editor-generators.ts","../src/survey/composition/registry.ts","../src/survey/composition/semantics.ts","../src/engine/validation.ts","../src/survey/composition/diagnostics.ts","../src/engine/session.ts","../src/response-exporter/csv-serializer.ts","../src/response-exporter/validate-configuration.ts","../src/response-exporter/exporter.ts","../src/response-exporter/codebook.ts","../src/engine/submission.ts"],"sourcesContent":["import { structuredCloneMethod } from \"./utils\";\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonObject = { [key: string]: JsonValue };\nexport type JsonValue = JsonPrimitive | JsonObject | JsonValue[];\n\nexport type JsonPatchOperation =\n | {\n op: \"add\" | \"replace\" | \"test\";\n path: string;\n value: JsonValue;\n }\n | {\n op: \"remove\";\n path: string;\n }\n | {\n op: \"move\" | \"copy\";\n from: string;\n path: string;\n };\n\nexport class JsonPatchError extends Error {\n constructor(\n message: string,\n readonly code: string,\n readonly path?: string,\n readonly operationIndex?: number,\n ) {\n super(message);\n this.name = \"JsonPatchError\";\n }\n}\n\nconst hasOwn = (value: object, key: string) => Object.prototype.hasOwnProperty.call(value, key);\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst assertValidPointerSegment = (segment: string, pointer: string) => {\n if (/~(?![01])/.test(segment)) {\n throw new JsonPatchError(\n `Invalid JSON pointer segment \"${segment}\" in \"${pointer}\". Only \"~0\" and \"~1\" escapes are allowed.`,\n \"invalid-json-pointer\",\n pointer,\n );\n }\n};\n\nexport const decodeJsonPointerSegment = (segment: string): string => {\n assertValidPointerSegment(segment, segment);\n return segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n};\n\nexport const encodeJsonPointerSegment = (segment: string): string =>\n segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n\nexport const parseJsonPointer = (pointer: string): string[] => {\n if (pointer === \"\") {\n return [];\n }\n\n if (!pointer.startsWith(\"/\")) {\n throw new JsonPatchError(\n `Invalid JSON pointer \"${pointer}\". It must be empty or start with \"/\".`,\n \"invalid-json-pointer\",\n pointer,\n );\n }\n\n return pointer\n .slice(1)\n .split(\"/\")\n .map((segment) => {\n assertValidPointerSegment(segment, pointer);\n return segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n });\n};\n\nconst parseArrayIndex = ({\n segment,\n arrayLength,\n allowAppend,\n allowEnd,\n path,\n}: {\n segment: string;\n arrayLength: number;\n allowAppend: boolean;\n allowEnd: boolean;\n path: string;\n}) => {\n if (segment === \"-\") {\n if (allowAppend) {\n return arrayLength;\n }\n\n throw new JsonPatchError(\n `JSON pointer \"${path}\" uses \"-\" where an existing array index is required.`,\n \"invalid-array-index\",\n path,\n );\n }\n\n if (!/^(0|[1-9][0-9]*)$/.test(segment)) {\n throw new JsonPatchError(\n `JSON pointer \"${path}\" uses invalid array index \"${segment}\".`,\n \"invalid-array-index\",\n path,\n );\n }\n\n const index = Number(segment);\n const maximum = allowEnd ? arrayLength : arrayLength - 1;\n if (index < 0 || index > maximum) {\n throw new JsonPatchError(\n `JSON pointer \"${path}\" array index ${index} is out of bounds.`,\n \"array-index-out-of-bounds\",\n path,\n );\n }\n\n return index;\n};\n\nconst getValueAtSegments = (document: unknown, segments: string[], path: string): unknown => {\n let current = document;\n\n for (const segment of segments) {\n if (Array.isArray(current)) {\n const index = parseArrayIndex({\n segment,\n arrayLength: current.length,\n allowAppend: false,\n allowEnd: false,\n path,\n });\n current = current[index];\n continue;\n }\n\n if (!isRecord(current) || !hasOwn(current, segment)) {\n throw new JsonPatchError(`JSON pointer \"${path}\" does not exist.`, \"path-not-found\", path);\n }\n\n current = current[segment];\n }\n\n return current;\n};\n\nexport const getValueAtJsonPointer = <T = unknown>(document: unknown, pointer: string): T => {\n const segments = parseJsonPointer(pointer);\n return getValueAtSegments(document, segments, pointer) as T;\n};\n\nconst deepEqualJson = (left: unknown, right: unknown): boolean => {\n if (left === right) {\n return true;\n }\n\n if (Array.isArray(left) || Array.isArray(right)) {\n if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) {\n return false;\n }\n\n return left.every((entry, index) => deepEqualJson(entry, right[index]));\n }\n\n if (isRecord(left) || isRecord(right)) {\n if (!isRecord(left) || !isRecord(right)) {\n return false;\n }\n\n const leftKeys = Object.keys(left).sort();\n const rightKeys = Object.keys(right).sort();\n if (leftKeys.length !== rightKeys.length) {\n return false;\n }\n\n return leftKeys.every(\n (key, index) => key === rightKeys[index] && deepEqualJson(left[key], right[key]),\n );\n }\n\n return false;\n};\n\nconst applyAdd = (document: unknown, path: string, value: JsonValue): unknown => {\n const segments = parseJsonPointer(path);\n if (segments.length === 0) {\n return structuredCloneMethod(value);\n }\n\n const parentSegments = segments.slice(0, -1);\n const key = segments[segments.length - 1];\n const parent = getValueAtSegments(document, parentSegments, path);\n\n if (Array.isArray(parent)) {\n const index = parseArrayIndex({\n segment: key,\n arrayLength: parent.length,\n allowAppend: true,\n allowEnd: true,\n path,\n });\n parent.splice(index, 0, structuredCloneMethod(value));\n return document;\n }\n\n if (!isRecord(parent)) {\n throw new JsonPatchError(\n `JSON pointer \"${path}\" parent is not an object or array.`,\n \"invalid-target-parent\",\n path,\n );\n }\n\n // Assignment to the special `__proto__` key invokes Object.prototype's\n // legacy setter instead of creating JSON data. Define the property directly\n // so every valid JSON Pointer key, including `__proto__`, keeps ordinary\n // own-property semantics without changing the target object's prototype.\n Object.defineProperty(parent, key, {\n configurable: true,\n enumerable: true,\n value: structuredCloneMethod(value),\n writable: true,\n });\n return document;\n};\n\nconst applyRemove = (\n document: unknown,\n path: string,\n): {\n document: unknown;\n removedValue: unknown;\n} => {\n const segments = parseJsonPointer(path);\n if (segments.length === 0) {\n throw new JsonPatchError(\"Removing the document root is not supported.\", \"remove-root\", path);\n }\n\n const parentSegments = segments.slice(0, -1);\n const key = segments[segments.length - 1];\n const parent = getValueAtSegments(document, parentSegments, path);\n\n if (Array.isArray(parent)) {\n const index = parseArrayIndex({\n segment: key,\n arrayLength: parent.length,\n allowAppend: false,\n allowEnd: false,\n path,\n });\n const [removedValue] = parent.splice(index, 1);\n return { document, removedValue };\n }\n\n if (!isRecord(parent) || !hasOwn(parent, key)) {\n throw new JsonPatchError(`JSON pointer \"${path}\" does not exist.`, \"path-not-found\", path);\n }\n\n const removedValue = parent[key];\n delete parent[key];\n return { document, removedValue };\n};\n\nconst applyReplace = (document: unknown, path: string, value: JsonValue): unknown => {\n const segments = parseJsonPointer(path);\n if (segments.length === 0) {\n return structuredCloneMethod(value);\n }\n\n getValueAtSegments(document, segments, path);\n applyRemove(document, path);\n return applyAdd(document, path, value);\n};\n\nconst assertMoveTargetIsNotDescendant = (from: string, path: string) => {\n if (from === \"\" || path === from || !path.startsWith(`${from}/`)) {\n return;\n }\n\n throw new JsonPatchError(\n `JSON Patch cannot move \"${from}\" into its own descendant \"${path}\".`,\n \"move-into-descendant\",\n path,\n );\n};\n\nexport const applyJsonPatch = <T>(document: T, operations: readonly JsonPatchOperation[]): T => {\n let patchedDocument = structuredCloneMethod(document) as unknown;\n\n operations.forEach((operation, operationIndex) => {\n try {\n switch (operation.op) {\n case \"add\":\n patchedDocument = applyAdd(patchedDocument, operation.path, operation.value);\n break;\n case \"remove\":\n patchedDocument = applyRemove(patchedDocument, operation.path).document;\n break;\n case \"replace\":\n patchedDocument = applyReplace(patchedDocument, operation.path, operation.value);\n break;\n case \"move\": {\n assertMoveTargetIsNotDescendant(operation.from, operation.path);\n if (operation.from === operation.path) {\n break;\n }\n const { document: withoutValue, removedValue } = applyRemove(\n patchedDocument,\n operation.from,\n );\n patchedDocument = applyAdd(withoutValue, operation.path, removedValue as JsonValue);\n break;\n }\n case \"copy\": {\n const value = getValueAtJsonPointer<JsonValue>(patchedDocument, operation.from);\n patchedDocument = applyAdd(patchedDocument, operation.path, value);\n break;\n }\n case \"test\": {\n const value = getValueAtJsonPointer(patchedDocument, operation.path);\n if (!deepEqualJson(value, operation.value)) {\n throw new JsonPatchError(\n `JSON Patch test failed at \"${operation.path}\".`,\n \"test-failed\",\n operation.path,\n );\n }\n break;\n }\n }\n } catch (error) {\n if (error instanceof JsonPatchError) {\n throw new JsonPatchError(error.message, error.code, error.path, operationIndex);\n }\n\n throw error;\n }\n });\n\n return patchedDocument as T;\n};\n","/** Authoring shortcut for a selected choice option that is also enabled. */\nimport type { ExpressionOf, JsonExpression } from \"../schema\";\n\n/**\n * Build a selected-option test joined with `not(ownerState.disabled)` for that option.\n * `multiple` chooses membership instead of equality. The result is an ordinary expression tree;\n * no shortcut node is persisted or handled specially by the evaluator.\n */\nexport function selectedAndEnabled(\n selection: ExpressionOf<\"responseVariable\">,\n optionId: string,\n multiple: boolean,\n): JsonExpression {\n return {\n type: \"function\",\n functionName: \"and\",\n arguments: [\n {\n type: \"function\",\n functionName: multiple ? \"list_contains\" : \"eq\",\n arguments: [selection, { type: \"const\", value: { type: \"reference\", value: optionId } }],\n },\n {\n type: \"function\",\n functionName: \"not\",\n arguments: [{ type: \"ownerState\", state: \"disabled\", targetRef: { ownerId: optionId } }],\n },\n ],\n };\n}\n","/**\n * Shared utilities for array operations.\n */\n\n/**\n * Swap two elements in an array by index.\n * @returns A new array with the elements swapped\n */\nexport function swapArrayElements<T>(arr: T[], fromIndex: number, toIndex: number): T[] {\n const result = [...arr];\n [result[fromIndex], result[toIndex]] = [result[toIndex], result[fromIndex]];\n return result;\n}\n\n/**\n * Move an element from one index to another.\n * @returns A new array with the element moved\n */\nexport function moveArrayElement<T>(arr: T[], fromIndex: number, toIndex: number): T[] {\n const result = [...arr];\n const [moved] = result.splice(fromIndex, 1);\n result.splice(toIndex, 0, moved);\n return result;\n}\n","/** Mutable authoring helpers that produce canonical JSON expressions for editor workflows. */\nimport { type CalendarDate } from \"../../calendar-date\";\nimport {\n expressionSchema,\n type ExpressionEditorConfig,\n type ExpressionOf,\n type FunctionName,\n type JsonExpression,\n} from \"../schema\";\nimport { expressionArguments } from \"../tree\";\nimport { ValueType, type ResponseValue } from \"../../survey/responses/value-types\";\nimport { moveArrayElement } from \"../../survey/utils/group-utils\";\n\nexport type AnswerReference = ExpressionOf<\"responseVariable\">[\"variableRef\"];\ntype ContextVariableType = ExpressionOf<\"contextVariable\">[\"contextType\"];\n\nconst constantNode = (\n value: ResponseValue,\n editorConfig?: ExpressionEditorConfig,\n): ExpressionOf<\"const\"> => {\n const node = expressionSchema.parse({ type: \"const\", value, editorConfig });\n if (node.type !== \"const\") throw new Error(\"Expected constant node\");\n return node;\n};\n\n/** Editor-state builders produce the canonical JSON tree, never runtime wrappers. */\nexport const createFunctionExpression = (\n functionName: FunctionName,\n args: readonly (JsonExpression | undefined | null)[],\n editorConfig?: ExpressionEditorConfig,\n): ExpressionOf<\"function\"> => ({\n type: \"function\",\n functionName,\n arguments: expressionArguments(args),\n editorConfig,\n});\n\nconst contextNode = (\n contextType: ContextVariableType,\n key?: JsonExpression,\n args?: (JsonExpression | undefined)[],\n asType?: ValueType,\n editorConfig?: ExpressionEditorConfig,\n): ExpressionOf<\"contextVariable\"> => ({\n type: \"contextVariable\",\n contextType,\n ...(key ? { key } : {}),\n ...(args ? { arguments: expressionArguments(args) } : {}),\n asType,\n editorConfig,\n});\n\n// ================================\n// EXPRESSION EDITOR CLASSES\n// ================================\nexport abstract class ExpressionEditor {\n returnType!: ValueType;\n protected _editorConfig?: ExpressionEditorConfig;\n\n abstract getExpression(): JsonExpression | undefined;\n\n get editorConfig(): ExpressionEditorConfig | undefined {\n return this._editorConfig;\n }\n\n withEditorConfig(editorConfig: ExpressionEditorConfig): this {\n this._editorConfig = editorConfig;\n return this;\n }\n}\n\n// ================================\n// CONST EDITORS\n// ================================\nexport class ConstStringArrayEditor extends ExpressionEditor {\n readonly returnType = ValueType.stringArray;\n\n private _values: string[];\n\n constructor(values: string[], editorConfig?: ExpressionEditorConfig) {\n super();\n this._values = values;\n this._editorConfig = editorConfig;\n }\n\n get values(): string[] {\n return this._values;\n }\n\n set values(values: string[]) {\n this._values = values;\n }\n\n getExpression(): JsonExpression | undefined {\n return constantNode({ type: ValueType.stringArray, value: this._values }, this._editorConfig);\n }\n}\n\nexport class ConstStringEditor extends ExpressionEditor {\n readonly returnType = ValueType.string;\n\n private _value: string;\n\n constructor(value: string, editorConfig?: ExpressionEditorConfig) {\n super();\n this._value = value;\n this._editorConfig = editorConfig;\n }\n\n get value(): string {\n return this._value;\n }\n\n set value(value: string) {\n this._value = value;\n }\n\n getExpression(): JsonExpression | undefined {\n return constantNode({ type: ValueType.string, value: this._value }, this._editorConfig);\n }\n}\n\nexport class ConstNumberEditor extends ExpressionEditor {\n readonly returnType = ValueType.number;\n\n private _value: number;\n\n constructor(value: number, editorConfig?: ExpressionEditorConfig) {\n super();\n this._value = value;\n this._editorConfig = editorConfig;\n }\n\n get value(): number {\n return this._value;\n }\n\n set value(value: number) {\n this._value = value;\n }\n\n getExpression(): JsonExpression | undefined {\n return constantNode({ type: ValueType.number, value: this._value }, this._editorConfig);\n }\n}\n\nexport class ConstBooleanEditor extends ExpressionEditor {\n readonly returnType = ValueType.boolean;\n\n private _value: boolean;\n\n constructor(value: boolean, editorConfig?: ExpressionEditorConfig) {\n super();\n this._value = value;\n this._editorConfig = editorConfig;\n }\n\n get value(): boolean {\n return this._value;\n }\n\n set value(value: boolean) {\n this._value = value;\n }\n\n getExpression(): JsonExpression | undefined {\n return constantNode({ type: ValueType.boolean, value: this._value }, this._editorConfig);\n }\n}\n\nexport class ConstDateEditor extends ExpressionEditor {\n readonly returnType = ValueType.date;\n\n private _value: CalendarDate;\n\n constructor(value: CalendarDate, editorConfig?: ExpressionEditorConfig) {\n super();\n this._value = value;\n this._editorConfig = editorConfig;\n }\n\n get value(): CalendarDate {\n return this._value;\n }\n\n set value(value: CalendarDate) {\n this._value = value;\n }\n\n getExpression(): JsonExpression | undefined {\n const value = this._value;\n return constantNode({ type: ValueType.date, value: value }, this._editorConfig);\n }\n}\n\nexport class ConstNumberArrayEditor extends ExpressionEditor {\n readonly returnType = ValueType.numberArray;\n\n private _values: number[];\n\n constructor(values: number[], editorConfig?: ExpressionEditorConfig) {\n super();\n this._values = values;\n this._editorConfig = editorConfig;\n }\n\n get values(): number[] {\n return this._values;\n }\n\n set values(values: number[]) {\n this._values = values;\n }\n\n getExpression(): JsonExpression | undefined {\n return constantNode({ type: ValueType.numberArray, value: this._values }, this._editorConfig);\n }\n}\n\nexport class ConstDateArrayEditor extends ExpressionEditor {\n readonly returnType = ValueType.dateArray;\n\n private _values: CalendarDate[];\n\n constructor(values: CalendarDate[], editorConfig?: ExpressionEditorConfig) {\n super();\n this._values = values;\n this._editorConfig = editorConfig;\n }\n\n get values(): CalendarDate[] {\n return this._values;\n }\n\n set values(values: CalendarDate[]) {\n this._values = values;\n }\n\n getExpression(): JsonExpression | undefined {\n const value = this._values;\n return constantNode({ type: ValueType.dateArray, value: value }, this._editorConfig);\n }\n}\n\n// ================================\n// RESPONSE VARIABLE EXPRESSION EDITOR CLASSES\n// ================================\n\nexport class ResponseVariableEditor extends ExpressionEditor {\n constructor(\n readonly variableRef: AnswerReference,\n variableType: ValueType,\n editorConfig?: ExpressionEditorConfig,\n ) {\n super();\n this._editorConfig = editorConfig;\n this.returnType = variableRef.method === \"isDefined\" ? ValueType.boolean : variableType;\n }\n\n getExpression(): ExpressionOf<\"responseVariable\"> {\n return {\n type: \"responseVariable\",\n variableRef: { ...this.variableRef },\n editorConfig: this._editorConfig,\n };\n }\n}\n\nexport class DisabledStateEditor extends ExpressionEditor {\n readonly returnType = ValueType.boolean;\n\n constructor(\n readonly ownerId: string,\n editorConfig?: ExpressionEditorConfig,\n ) {\n super();\n this._editorConfig = editorConfig;\n }\n\n getExpression(): ExpressionOf<\"ownerState\"> {\n return {\n type: \"ownerState\",\n state: \"disabled\",\n targetRef: { ownerId: this.ownerId },\n editorConfig: this._editorConfig,\n };\n }\n}\n\n// ================================\n// CONTEXT VARIABLE EXPRESSION EDITOR CLASSES\n// ================================\n\nabstract class ContextVariableEditor extends ExpressionEditor {\n private _contextType: ContextVariableType;\n private _key?: ExpressionEditor;\n private _args?: ExpressionEditor[];\n private _asType?: ValueType;\n\n constructor(\n contextType: ContextVariableType,\n key?: ExpressionEditor,\n args?: ExpressionEditor[],\n asType?: ValueType,\n editorConfig?: ExpressionEditorConfig,\n ) {\n super();\n this._contextType = contextType;\n this._key = key;\n this._args = args;\n this._asType = asType;\n this._editorConfig = editorConfig;\n }\n\n getExpression(): JsonExpression | undefined {\n return contextNode(\n this._contextType,\n this._key?.getExpression(),\n this._args?.map((arg) => arg.getExpression()),\n this._asType,\n this._editorConfig,\n );\n }\n}\n\nexport class CtxLocaleEditor extends ContextVariableEditor {\n readonly returnType = ValueType.string;\n\n constructor(editorConfig?: ExpressionEditorConfig) {\n super(\"locale\", undefined, undefined, ValueType.string, editorConfig);\n }\n}\n\nexport class CtxCurrentDateEditor extends ContextVariableEditor {\n readonly returnType = ValueType.date;\n\n constructor(editorConfig?: ExpressionEditorConfig) {\n super(\"currentDate\", undefined, undefined, ValueType.date, editorConfig);\n }\n}\n\nexport class CtxPFlagIsDefinedEditor extends ContextVariableEditor {\n readonly returnType = ValueType.boolean;\n\n constructor(key: ExpressionEditor, editorConfig?: ExpressionEditorConfig) {\n super(\"participantFlag\", key, undefined, ValueType.boolean, editorConfig);\n }\n}\n\nexport class CtxPFlagStringEditor extends ContextVariableEditor {\n readonly returnType = ValueType.string;\n\n constructor(key: ExpressionEditor, editorConfig?: ExpressionEditorConfig) {\n super(\"participantFlag\", key, undefined, ValueType.string, editorConfig);\n }\n}\n\nexport class CtxPFlagNumEditor extends ContextVariableEditor {\n readonly returnType = ValueType.number;\n\n constructor(key: ExpressionEditor, editorConfig?: ExpressionEditorConfig) {\n super(\"participantFlag\", key, undefined, ValueType.number, editorConfig);\n }\n}\n\nexport class CtxPFlagDateEditor extends ContextVariableEditor {\n readonly returnType = ValueType.date;\n\n constructor(key: ExpressionEditor, editorConfig?: ExpressionEditorConfig) {\n super(\"participantFlag\", key, undefined, ValueType.date, editorConfig);\n }\n}\n\nexport class CtxCustomValueEditor extends ContextVariableEditor {\n constructor(key: ExpressionEditor, asType: ValueType, editorConfig?: ExpressionEditorConfig) {\n super(\"customValue\", key, undefined, asType, editorConfig);\n this.returnType = asType;\n }\n}\n\n// ================================\n// GROUP EXPRESSION EDITOR CLASSES\n// ================================\nabstract class GroupExpressionEditor extends ExpressionEditor {\n private _args: ExpressionEditor[];\n\n constructor(args: ExpressionEditor[], editorConfig?: ExpressionEditorConfig) {\n super();\n this._args = args;\n this._editorConfig = editorConfig;\n }\n\n get args(): ExpressionEditor[] {\n return this._args;\n }\n\n addArg(arg: ExpressionEditor, position?: number) {\n if (position === undefined) {\n this._args.push(arg);\n } else {\n this._args.splice(position, 0, arg);\n }\n }\n\n removeArg(position: number) {\n this._args.splice(position, 1);\n }\n\n replaceArg(position: number, arg: ExpressionEditor) {\n this._args[position] = arg;\n }\n\n swapArgs(activeIndex: number, overIndex: number) {\n this._args = moveArrayElement(this._args, activeIndex, overIndex);\n }\n}\n\nexport class AndExpressionEditor extends GroupExpressionEditor {\n readonly returnType = ValueType.boolean;\n\n constructor(args: ExpressionEditor[], editorConfig?: ExpressionEditorConfig) {\n if (args.some((arg) => arg.returnType !== ValueType.boolean)) {\n throw new Error(\"And expression editor must have boolean arguments\");\n }\n super(args, editorConfig);\n }\n\n getExpression(): JsonExpression | undefined {\n return createFunctionExpression(\n \"and\",\n this.args.map((arg) => arg.getExpression()),\n this._editorConfig,\n );\n }\n}\n\nexport class OrExpressionEditor extends GroupExpressionEditor {\n readonly returnType = ValueType.boolean;\n\n constructor(args: ExpressionEditor[], editorConfig?: ExpressionEditorConfig) {\n if (args.some((arg) => arg.returnType !== ValueType.boolean)) {\n throw new Error(\"Or expression editor must have boolean arguments\");\n }\n super(args, editorConfig);\n }\n\n getExpression(): JsonExpression {\n return createFunctionExpression(\n \"or\",\n this.args.map((arg) => arg.getExpression()),\n this._editorConfig,\n );\n }\n}\n\n// ================================\n// LIST EXPRESSION EDITOR CLASSES\n// ================================\n\nexport class StrListContainsExpressionEditor extends ExpressionEditor {\n readonly returnType = ValueType.boolean;\n private _list: ExpressionEditor | undefined;\n private _item: ExpressionEditor | undefined;\n\n constructor(\n list: ExpressionEditor,\n item: ExpressionEditor,\n editorConfig?: ExpressionEditorConfig,\n ) {\n super();\n if (list.returnType !== ValueType.stringArray) {\n throw new Error(\"List contains expression editor must have a string array list\");\n }\n if (item.returnType !== ValueType.string) {\n throw new Error(\"List contains expression editor must have a string item\");\n }\n this._list = list;\n this._item = item;\n this._editorConfig = editorConfig;\n }\n\n get list(): ExpressionEditor | undefined {\n return this._list;\n }\n\n get item(): ExpressionEditor | undefined {\n return this._item;\n }\n\n set list(list: ExpressionEditor | undefined) {\n this._list = list;\n }\n\n set item(item: ExpressionEditor | undefined) {\n this._item = item;\n }\n\n getExpression(): JsonExpression {\n return createFunctionExpression(\n \"list_contains\",\n [this._list?.getExpression(), this._item?.getExpression()],\n this._editorConfig,\n );\n }\n}\n\n// ================================\n// STRING EXPRESSION EDITOR CLASSES\n// ================================\n\nexport class StrEqExpressionEditor extends ExpressionEditor {\n readonly returnType = ValueType.boolean;\n private _a: ExpressionEditor | undefined;\n private _b: ExpressionEditor | undefined;\n\n constructor(a: ExpressionEditor, b: ExpressionEditor, editorConfig?: ExpressionEditorConfig) {\n super();\n this._a = a;\n this._b = b;\n this._editorConfig = editorConfig;\n }\n\n get a(): ExpressionEditor | undefined {\n return this._a;\n }\n\n get b(): ExpressionEditor | undefined {\n return this._b;\n }\n\n set a(a: ExpressionEditor | undefined) {\n this._a = a;\n }\n\n set b(b: ExpressionEditor | undefined) {\n this._b = b;\n }\n\n getExpression(): JsonExpression {\n return createFunctionExpression(\n \"str_eq\",\n [this._a?.getExpression(), this._b?.getExpression()],\n this._editorConfig,\n );\n }\n}\n\n// ================================\n// NUMBER EXPRESSION EDITOR CLASSES\n// ================================\n\nexport class EqExpressionEditor extends ExpressionEditor {\n readonly returnType = ValueType.boolean;\n private _a: ExpressionEditor | undefined;\n private _b: ExpressionEditor | undefined;\n\n constructor(a: ExpressionEditor, b: ExpressionEditor, editorConfig?: ExpressionEditorConfig) {\n super();\n this._a = a;\n this._b = b;\n this._editorConfig = editorConfig;\n }\n\n get a(): ExpressionEditor | undefined {\n return this._a;\n }\n\n get b(): ExpressionEditor | undefined {\n return this._b;\n }\n\n set a(a: ExpressionEditor | undefined) {\n this._a = a;\n }\n\n set b(b: ExpressionEditor | undefined) {\n this._b = b;\n }\n\n getExpression(): JsonExpression {\n return createFunctionExpression(\n \"eq\",\n [this._a?.getExpression(), this._b?.getExpression()],\n this._editorConfig,\n );\n }\n}\n\nexport class GtExpressionEditor extends ExpressionEditor {\n readonly returnType = ValueType.boolean;\n private _a: ExpressionEditor | undefined;\n private _b: ExpressionEditor | undefined;\n\n constructor(a: ExpressionEditor, b: ExpressionEditor, editorConfig?: ExpressionEditorConfig) {\n super();\n this._a = a;\n this._b = b;\n this._editorConfig = editorConfig;\n }\n\n get a(): ExpressionEditor | undefined {\n return this._a;\n }\n\n get b(): ExpressionEditor | undefined {\n return this._b;\n }\n\n set a(a: ExpressionEditor | undefined) {\n this._a = a;\n }\n\n set b(b: ExpressionEditor | undefined) {\n this._b = b;\n }\n\n getExpression(): JsonExpression {\n return createFunctionExpression(\n \"gt\",\n [this._a?.getExpression(), this._b?.getExpression()],\n this._editorConfig,\n );\n }\n}\n\nexport class GteExpressionEditor extends ExpressionEditor {\n readonly returnType = ValueType.boolean;\n private _a: ExpressionEditor | undefined;\n private _b: ExpressionEditor | undefined;\n\n constructor(a: ExpressionEditor, b: ExpressionEditor, editorConfig?: ExpressionEditorConfig) {\n super();\n this._a = a;\n this._b = b;\n this._editorConfig = editorConfig;\n }\n\n get a(): ExpressionEditor | undefined {\n return this._a;\n }\n\n get b(): ExpressionEditor | undefined {\n return this._b;\n }\n\n set a(a: ExpressionEditor | undefined) {\n this._a = a;\n }\n\n set b(b: ExpressionEditor | undefined) {\n this._b = b;\n }\n\n getExpression(): JsonExpression {\n return createFunctionExpression(\n \"gte\",\n [this._a?.getExpression(), this._b?.getExpression()],\n this._editorConfig,\n );\n }\n}\n\nexport class LtExpressionEditor extends ExpressionEditor {\n readonly returnType = ValueType.boolean;\n private _a: ExpressionEditor | undefined;\n private _b: ExpressionEditor | undefined;\n\n constructor(a: ExpressionEditor, b: ExpressionEditor, editorConfig?: ExpressionEditorConfig) {\n super();\n this._a = a;\n this._b = b;\n this._editorConfig = editorConfig;\n }\n\n get a(): ExpressionEditor | undefined {\n return this._a;\n }\n\n get b(): ExpressionEditor | undefined {\n return this._b;\n }\n\n set a(a: ExpressionEditor | undefined) {\n this._a = a;\n }\n\n set b(b: ExpressionEditor | undefined) {\n this._b = b;\n }\n\n getExpression(): JsonExpression {\n return createFunctionExpression(\n \"lt\",\n [this._a?.getExpression(), this._b?.getExpression()],\n this._editorConfig,\n );\n }\n}\n\nexport class LteExpressionEditor extends ExpressionEditor {\n readonly returnType = ValueType.boolean;\n private _a: ExpressionEditor | undefined;\n private _b: ExpressionEditor | undefined;\n\n constructor(a: ExpressionEditor, b: ExpressionEditor, editorConfig?: ExpressionEditorConfig) {\n super();\n this._a = a;\n this._b = b;\n this._editorConfig = editorConfig;\n }\n\n get a(): ExpressionEditor | undefined {\n return this._a;\n }\n\n get b(): ExpressionEditor | undefined {\n return this._b;\n }\n\n set b(b: ExpressionEditor | undefined) {\n this._b = b;\n }\n\n set a(a: ExpressionEditor | undefined) {\n this._a = a;\n }\n\n getExpression(): JsonExpression {\n return createFunctionExpression(\n \"lte\",\n [this._a?.getExpression(), this._b?.getExpression()],\n this._editorConfig,\n );\n }\n}\n\nexport class InRangeExpressionEditor extends ExpressionEditor {\n readonly returnType = ValueType.boolean;\n value: ExpressionEditor | undefined;\n min: ExpressionEditor | undefined;\n max: ExpressionEditor | undefined;\n inclusive: ExpressionEditor | undefined;\n\n constructor(\n value: ExpressionEditor,\n min: ExpressionEditor,\n max: ExpressionEditor,\n inclusive: ExpressionEditor,\n editorConfig?: ExpressionEditorConfig,\n ) {\n super();\n this.value = value;\n this.min = min;\n this.max = max;\n this.inclusive = inclusive;\n this._editorConfig = editorConfig;\n }\n\n getExpression(): JsonExpression {\n return createFunctionExpression(\n \"in_range\",\n [\n this.value?.getExpression(),\n this.min?.getExpression(),\n this.max?.getExpression(),\n this.inclusive?.getExpression(),\n ],\n this._editorConfig,\n );\n }\n}\n\nexport class SumExpressionEditor extends GroupExpressionEditor {\n readonly returnType = ValueType.number;\n\n constructor(args: ExpressionEditor[], editorConfig?: ExpressionEditorConfig) {\n super(args, editorConfig);\n }\n\n getExpression(): JsonExpression {\n return createFunctionExpression(\n \"sum\",\n this.args.map((arg) => arg.getExpression()),\n this._editorConfig,\n );\n }\n}\n\nexport class MinExpressionEditor extends GroupExpressionEditor {\n readonly returnType = ValueType.number;\n\n constructor(args: ExpressionEditor[], editorConfig?: ExpressionEditorConfig) {\n super(args, editorConfig);\n }\n\n getExpression(): JsonExpression {\n return createFunctionExpression(\n \"min\",\n this.args.map((arg) => arg.getExpression()),\n this._editorConfig,\n );\n }\n}\n\nexport class MaxExpressionEditor extends GroupExpressionEditor {\n readonly returnType = ValueType.number;\n\n constructor(args: ExpressionEditor[], editorConfig?: ExpressionEditorConfig) {\n super(args, editorConfig);\n }\n\n getExpression(): JsonExpression {\n return createFunctionExpression(\n \"max\",\n this.args.map((arg) => arg.getExpression()),\n this._editorConfig,\n );\n }\n}\n","/** Short builder aliases for authoring expressions with the editor classes. */\nimport type { CalendarDateUnit } from \"../../calendar-date\";\nimport type { FunctionName } from \"../schema\";\nimport { ValueType } from \"../../survey/responses/value-types\";\nimport {\n createFunctionExpression,\n type AnswerReference,\n DisabledStateEditor,\n AndExpressionEditor,\n ConstStringArrayEditor,\n ConstStringEditor,\n ExpressionEditor,\n StrListContainsExpressionEditor,\n OrExpressionEditor,\n ResponseVariableEditor,\n ConstNumberArrayEditor,\n ConstNumberEditor,\n ConstBooleanEditor,\n ConstDateEditor,\n ConstDateArrayEditor,\n StrEqExpressionEditor,\n EqExpressionEditor,\n GtExpressionEditor,\n GteExpressionEditor,\n LteExpressionEditor,\n LtExpressionEditor,\n InRangeExpressionEditor,\n SumExpressionEditor,\n MinExpressionEditor,\n MaxExpressionEditor,\n CtxLocaleEditor,\n CtxCurrentDateEditor,\n CtxPFlagIsDefinedEditor,\n CtxPFlagStringEditor,\n CtxPFlagNumEditor,\n CtxPFlagDateEditor,\n CtxCustomValueEditor,\n} from \"./expression-editor\";\n\n// ================================\n// CONST EXPRESSIONS\n// ================================\nexport const const_string_array = (...values: string[]): ExpressionEditor => {\n return new ConstStringArrayEditor(values);\n};\n\nexport const const_string = (value: string): ExpressionEditor => {\n return new ConstStringEditor(value);\n};\n\nexport const const_number_array = (...values: number[]): ExpressionEditor => {\n return new ConstNumberArrayEditor(values);\n};\n\nexport const const_number = (value: number): ExpressionEditor => {\n return new ConstNumberEditor(value);\n};\n\nexport const const_boolean = (value: boolean): ExpressionEditor => {\n return new ConstBooleanEditor(value);\n};\n\nexport const const_date = (value: string): ExpressionEditor => {\n return new ConstDateEditor(value);\n};\n\nexport const const_date_array = (...values: string[]): ExpressionEditor => {\n return new ConstDateArrayEditor(values);\n};\n\n// ================================\n// RESPONSE VARIABLE EXPRESSIONS\n// ================================\nexport const response_string = (valueRef: AnswerReference): ExpressionEditor => {\n return new ResponseVariableEditor(valueRef, ValueType.string);\n};\n\nexport const response_string_array = (valueRef: AnswerReference): ExpressionEditor => {\n return new ResponseVariableEditor(valueRef, ValueType.stringArray);\n};\n\nexport const response_number = (valueRef: AnswerReference): ExpressionEditor => {\n return new ResponseVariableEditor(valueRef, ValueType.number);\n};\n\nexport const response_boolean = (valueRef: AnswerReference): ExpressionEditor => {\n return new ResponseVariableEditor(valueRef, ValueType.boolean);\n};\n\nexport const response_date = (valueRef: AnswerReference): ExpressionEditor => {\n return new ResponseVariableEditor(valueRef, ValueType.date);\n};\n\nexport const response_number_array = (valueRef: AnswerReference): ExpressionEditor => {\n return new ResponseVariableEditor(valueRef, ValueType.numberArray);\n};\n\nexport const response_date_array = (valueRef: AnswerReference): ExpressionEditor => {\n return new ResponseVariableEditor(valueRef, ValueType.dateArray);\n};\n\n// ================================\n// CONTEXT VARIABLE EXPRESSIONS\n// ================================\nexport const ctx_locale = (): ExpressionEditor => {\n return new CtxLocaleEditor();\n};\n\nexport const ctx_current_date = (): ExpressionEditor => {\n return new CtxCurrentDateEditor();\n};\n\nexport const ctx_pflag_is_defined = (key: ExpressionEditor): ExpressionEditor => {\n return new CtxPFlagIsDefinedEditor(key);\n};\n\nexport const ctx_pflag_string = (key: ExpressionEditor): ExpressionEditor => {\n return new CtxPFlagStringEditor(key);\n};\n\nexport const ctx_pflag_num = (key: ExpressionEditor): ExpressionEditor => {\n return new CtxPFlagNumEditor(key);\n};\n\nexport const ctx_pflag_date = (key: ExpressionEditor): ExpressionEditor => {\n return new CtxPFlagDateEditor(key);\n};\n\nexport const ctx_custom_value = (key: ExpressionEditor, dType: ValueType): ExpressionEditor => {\n return new CtxCustomValueEditor(key, dType);\n};\n\n// ================================\n// LOGIC EXPRESSIONS\n// ================================\nexport const and = (...args: ExpressionEditor[]): ExpressionEditor => {\n return new AndExpressionEditor(args);\n};\n\nexport const or = (...args: ExpressionEditor[]): ExpressionEditor => {\n return new OrExpressionEditor(args);\n};\n\n// ================================\n// LIST EXPRESSIONS\n// ================================\n\nexport const str_list_contains = (\n list: ExpressionEditor,\n item: ExpressionEditor,\n): ExpressionEditor => {\n return new StrListContainsExpressionEditor(list, item);\n};\n\n/** Number of list entries, or of entries that also appear in `filter` (e.g. listed options). */\nexport const list_count = (list: ExpressionEditor, filter?: ExpressionEditor): ExpressionEditor =>\n new FunctionCallEditor(\"list_count\", filter ? [list, filter] : [list], ValueType.number);\n\n// ================================\n// CONDITIONAL EXPRESSIONS\n// ================================\n\n/** `then` when the condition is true, otherwise `otherwise` (missing when omitted). */\nexport const if_else = (\n condition: ExpressionEditor,\n then: ExpressionEditor,\n otherwise?: ExpressionEditor,\n): ExpressionEditor =>\n new FunctionCallEditor(\n \"if\",\n otherwise ? [condition, then, otherwise] : [condition, then],\n then.returnType ?? otherwise?.returnType,\n );\n\n// ================================\n// STRING EXPRESSIONS\n// ================================\n\nexport const str_eq = (a: ExpressionEditor, b: ExpressionEditor): ExpressionEditor => {\n return new StrEqExpressionEditor(a, b);\n};\n\n// ================================\n// NUMBER EXPRESSIONS\n// ================================\n\nexport const eq = (a: ExpressionEditor, b: ExpressionEditor): ExpressionEditor => {\n return new EqExpressionEditor(a, b);\n};\n\nexport const gt = (a: ExpressionEditor, b: ExpressionEditor): ExpressionEditor => {\n return new GtExpressionEditor(a, b);\n};\n\nexport const gte = (a: ExpressionEditor, b: ExpressionEditor): ExpressionEditor => {\n return new GteExpressionEditor(a, b);\n};\n\nexport const lt = (a: ExpressionEditor, b: ExpressionEditor): ExpressionEditor => {\n return new LtExpressionEditor(a, b);\n};\n\nexport const lte = (a: ExpressionEditor, b: ExpressionEditor): ExpressionEditor => {\n return new LteExpressionEditor(a, b);\n};\n\nexport const in_range = (\n value: ExpressionEditor,\n min: ExpressionEditor,\n max: ExpressionEditor,\n inclusive: ExpressionEditor,\n): ExpressionEditor => {\n return new InRangeExpressionEditor(value, min, max, inclusive);\n};\n\nexport const sum = (...args: ExpressionEditor[]): ExpressionEditor => {\n return new SumExpressionEditor(args);\n};\n\nexport const min = (...args: ExpressionEditor[]): ExpressionEditor => {\n return new MinExpressionEditor(args);\n};\n\nexport const max = (...args: ExpressionEditor[]): ExpressionEditor => {\n return new MaxExpressionEditor(args);\n};\n\nclass FunctionCallEditor extends ExpressionEditor {\n constructor(\n readonly name: FunctionName,\n readonly args: ExpressionEditor[],\n readonly returnType: ValueType,\n ) {\n super();\n }\n getExpression() {\n return createFunctionExpression(\n this.name,\n this.args.map((arg) => arg.getExpression()),\n this.editorConfig,\n );\n }\n}\nexport const date_eq = (a: ExpressionEditor, b: ExpressionEditor): ExpressionEditor =>\n new FunctionCallEditor(\"date_eq\", [a, b], ValueType.boolean);\nexport const date_gt = (a: ExpressionEditor, b: ExpressionEditor): ExpressionEditor =>\n new FunctionCallEditor(\"date_gt\", [a, b], ValueType.boolean);\nexport const date_gte = (a: ExpressionEditor, b: ExpressionEditor): ExpressionEditor =>\n new FunctionCallEditor(\"date_gte\", [a, b], ValueType.boolean);\nexport const date_lt = (a: ExpressionEditor, b: ExpressionEditor): ExpressionEditor =>\n new FunctionCallEditor(\"date_lt\", [a, b], ValueType.boolean);\nexport const date_lte = (a: ExpressionEditor, b: ExpressionEditor): ExpressionEditor =>\n new FunctionCallEditor(\"date_lte\", [a, b], ValueType.boolean);\nexport const date_add_days = (a: ExpressionEditor, b: ExpressionEditor): ExpressionEditor =>\n new FunctionCallEditor(\"date_add_days\", [a, b], ValueType.date);\nexport const date_add_months = (a: ExpressionEditor, b: ExpressionEditor): ExpressionEditor =>\n new FunctionCallEditor(\"date_add_months\", [a, b], ValueType.date);\nexport const date_add_years = (a: ExpressionEditor, b: ExpressionEditor): ExpressionEditor =>\n new FunctionCallEditor(\"date_add_years\", [a, b], ValueType.date);\n/** Signed completed units in a - b, e.g. age as `date_diff(ctx_current_date(), birth, \"years\")`. */\nexport const date_diff = (\n a: ExpressionEditor,\n b: ExpressionEditor,\n unit: CalendarDateUnit,\n): ExpressionEditor =>\n new FunctionCallEditor(\"date_diff\", [a, b, const_string(unit)], ValueType.number);\nexport const date_min = (...args: ExpressionEditor[]): ExpressionEditor =>\n new FunctionCallEditor(\"date_min\", args, ValueType.date);\nexport const date_max = (...args: ExpressionEditor[]): ExpressionEditor =>\n new FunctionCallEditor(\"date_max\", args, ValueType.date);\n\nexport const is_disabled = (ownerId: string): ExpressionEditor => new DisabledStateEditor(ownerId);\n","import { z } from \"zod\";\nimport { contentOwner, type ContentRole } from \"../../schema/annotations\";\nimport type { JsonExpression } from \"../../expressions/schema\";\nimport type { ResponseSlotDefinition } from \"../responses/slot-definition\";\nimport type { ResponseValue } from \"../responses/value-types\";\nimport {\n createCompositionSchema,\n createSurveySchema,\n elementShape,\n type CompositionBody,\n type ElementEnvelope,\n} from \"./schema\";\n\n/** Unknown configs exist only at the registry dispatch boundary and are parsed before domain calls. */\nexport type RuntimeElement = ElementEnvelope<string, unknown>;\nexport type SlotBinding = {\n slotId: string;\n controlId: string;\n /** Compound controls name an input using owned content, e.g. its matrix row and column. */\n labelRefs?: readonly { ownerId: string; role: string }[];\n visibilityIds?: string[];\n selection?: {\n options: string[];\n multiple: boolean;\n maxSelection?: number | null;\n /** Whether the adapter exposes clearing a single selection (radio repeat-click defaults to true). */\n allowClear?: boolean;\n };\n};\n\nexport type FollowUpBinding =\n | { triggerId: string; selectionSlotId: string }\n | { triggerId: string; expression: JsonExpression };\n\nexport type ElementFacts = {\n slots: ResponseSlotDefinition[];\n bindings: SlotBinding[];\n followUps: FollowUpBinding[];\n fullWidth: boolean;\n minWidthRem: number;\n componentParents: Record<string, string[]>;\n};\n\nexport type DomainRead = (slotId: string) => ResponseValue | undefined;\nexport type InputValidationIssue = { slotId: string; code: string; messageOwnerId?: string };\nexport type DomainEvaluation = (expression: JsonExpression) => ResponseValue | undefined;\nexport type ElementDefinition = {\n elementType: string;\n /** Headless naming for outlines, codebooks and custom elements without authored wording. */\n labelByLocale?: Readonly<Record<string, string>>;\n schema: z.ZodType<RuntimeElement>;\n inspect(input: unknown): ElementFacts;\n compute(input: unknown, slotId: string, read: DomainRead): ResponseValue | undefined;\n validate(input: unknown, read: DomainRead, evaluate: DomainEvaluation): InputValidationIssue[];\n};\n\nexport type ElementSchema<\n K extends string,\n S extends z.ZodType<Record<string, unknown>>,\n> = z.ZodObject<\n typeof elementShape & { elementType: z.ZodLiteral<K>; config: z.ZodNonOptional<S> },\n z.core.$strict\n>;\nexport type DefinedElement<K extends string, S extends z.ZodType<Record<string, unknown>>> = Omit<\n ElementDefinition,\n \"elementType\" | \"schema\"\n> & { elementType: K; schema: ElementSchema<K, S> };\n\nexport function defineElement<\n const K extends string,\n S extends z.ZodType<Record<string, unknown>>,\n>(definition: {\n elementType: K;\n labelByLocale?: Readonly<Record<string, string>>;\n config: S;\n roles?: readonly ContentRole[];\n facts?: (config: z.output<S>, elementId: string) => Partial<ElementFacts>;\n compute?: (config: z.output<S>, slotId: string, read: DomainRead) => ResponseValue | undefined;\n validate?: (\n config: z.output<S>,\n elementId: string,\n read: DomainRead,\n evaluate: DomainEvaluation,\n ) => InputValidationIssue[];\n}): DefinedElement<K, S> {\n const schema = contentOwner(\n z.strictObject({\n ...elementShape,\n elementType: z.literal(definition.elementType),\n config: definition.config.nonoptional(),\n }),\n definition.roles ?? [],\n );\n return {\n elementType: definition.elementType,\n labelByLocale: definition.labelByLocale,\n schema,\n inspect(input: unknown): ElementFacts {\n const node = schema.parse(input);\n return {\n slots: [],\n bindings: [],\n followUps: [],\n fullWidth: false,\n minWidthRem: 12,\n componentParents: {},\n ...definition.facts?.(node.config, node.id),\n };\n },\n compute(input: unknown, slotId: string, read: DomainRead): ResponseValue | undefined {\n return definition.compute?.(schema.parse(input).config, slotId, read);\n },\n validate(input: unknown, read: DomainRead, evaluate: DomainEvaluation): InputValidationIssue[] {\n const node = schema.parse(input);\n return definition.validate?.(node.config, node.id, read, evaluate) ?? [];\n },\n } satisfies ElementDefinition;\n}\n\nexport type RegisteredElement<D extends readonly ElementDefinition[]> = z.output<\n D[number][\"schema\"]\n>;\n\nexport type ElementRegistry<D extends readonly ElementDefinition[] = readonly ElementDefinition[]> =\n {\n definitions: D;\n labels: ReadonlyMap<string, Readonly<Record<string, string>>>;\n elementSchema: z.ZodType<RuntimeElement>;\n bodySchema: z.ZodType<CompositionBody<RuntimeElement>>;\n surveySchema: ReturnType<typeof createSurveySchema<RuntimeElement>>;\n get(elementType: string): ElementDefinition;\n };\n\n/** A registry is finalized once. Its one recursive schema is shared by built-in and custom bodies. */\nexport function createElementRegistry<const D extends readonly ElementDefinition[]>(\n create: (body: z.ZodType<CompositionBody<RuntimeElement>>) => D,\n): ElementRegistry<D> {\n const deferred = z.lazy(() => composition);\n const definitions = create(deferred);\n const byType = new Map<string, ElementDefinition>();\n for (const definition of definitions) {\n if (byType.has(definition.elementType))\n throw new Error(`Duplicate element registration: ${definition.elementType}`);\n byType.set(definition.elementType, definition);\n }\n const variants = definitions.map((definition) => definition.schema);\n const element = variants.length ? z.union(variants) : z.never();\n const composition: z.ZodType<CompositionBody<RuntimeElement>> = createCompositionSchema(element);\n return {\n definitions,\n labels: new Map(\n definitions.map((definition) => [definition.elementType, definition.labelByLocale ?? {}]),\n ),\n elementSchema: element,\n bodySchema: composition,\n surveySchema: createSurveySchema(composition),\n get(elementType: string): ElementDefinition {\n const definition = byType.get(elementType);\n if (!definition) throw new Error(`Unknown element type: ${elementType}`);\n return definition;\n },\n };\n}\nexport type CompositionSurvey = z.output<ElementRegistry[\"surveySchema\"]>;\nexport type FlowItem = CompositionSurvey[\"surveyItems\"][number];\nexport type FlowGroup = Extract<FlowItem, { itemType: \"group\" }>;\nexport type SurveyLocaleContent = NonNullable<CompositionSurvey[\"translations\"]>[string];\nexport type SurveyCardContent = NonNullable<SurveyLocaleContent[\"surveyCardContent\"]>;\nexport type NavigationContent = NonNullable<SurveyLocaleContent[\"navigationContent\"]>;\nexport type TemplateValueDefinition = NonNullable<CompositionSurvey[\"templateValues\"]>[string];\nexport type RawSurveyAsset = NonNullable<CompositionSurvey[\"assets\"]>[string];\n","import type { Survey } from \"./document\";\nimport { getContentPlainText } from \"../utils/content\";\nimport { resolveParticipantContent } from \"../utils/localization\";\n\n/** Structural context is independent of an element's explicit accessible label. */\nexport function getElementSemanticContext(survey: Survey, elementId: string) {\n const owner = survey.owners.get(elementId);\n if (!owner) throw new Error(`Unknown element '${elementId}'`);\n let ancestor = owner.parentId ? survey.owners.get(owner.parentId) : undefined;\n while (ancestor && ancestor.followUpTriggerId === owner.followUpTriggerId) {\n if (ancestor.kind === \"section\" || ancestor.kind === \"item\") return ancestor;\n ancestor = ancestor.parentId ? survey.owners.get(ancestor.parentId) : undefined;\n }\n return undefined;\n}\n\nexport function resolveElementName(survey: Survey, elementId: string, locales: readonly string[]) {\n const owner = survey.owners.get(elementId);\n if (!owner) throw new Error(`Unknown element '${elementId}'`);\n const name = (ownerId: string, role: string) => {\n if (!survey.owners.get(ownerId)?.roles.some((entry) => entry.role === role)) return undefined;\n const resolved = resolveParticipantContent(survey, ownerId, role, locales);\n const text = getContentPlainText(resolved?.content).trim();\n return text && resolved\n ? { ownerId, role, text, content: resolved.content, locale: resolved.locale }\n : undefined;\n };\n const own = name(elementId, \"label\");\n if (own) return own;\n let ancestor = owner.parentId ? survey.owners.get(owner.parentId) : undefined;\n while (ancestor) {\n const current = ancestor;\n const inputs = [...survey.elements.values()].filter((element) => {\n const candidate = survey.owners.get(element.node.id)!;\n return (\n element.facts.bindings.length > 0 &&\n candidate.followUpTriggerId === owner.followUpTriggerId &&\n current.path.every((part, index) => candidate.path[index] === part)\n );\n });\n if (inputs.length === 1) {\n const inherited = name(ancestor.id, \"title\") ?? name(ancestor.id, \"label\");\n if (inherited) return inherited;\n }\n if (ancestor.kind === \"section\" || ancestor.id === owner.followUpTriggerId) return undefined;\n ancestor = ancestor.parentId ? survey.owners.get(ancestor.parentId) : undefined;\n }\n return undefined;\n}\n","import { ownValue } from \"../schema/string-record\";\nimport type { DefinitionDiagnostic, Survey } from \"../survey/composition/document\";\nimport type { InputValidationIssue } from \"../survey/composition/registry\";\nimport { evaluateExpression, ExpressionEvaluationError } from \"../expressions/evaluator\";\nimport { SurveyStateGraph, hasPermittedChange, type RecordedContext } from \"./survey-state-graph\";\nimport type { ResponseValue } from \"../survey/responses/value-types\";\nimport { hasLocalizationText, readLocalizationContent } from \"../survey/utils/localization\";\nimport { resolveElementName } from \"../survey/composition/semantics\";\nimport type { JsonExpression } from \"../expressions/schema\";\nimport type { SchemaPath } from \"../schema/annotations\";\n\nexport type AuthoringWarning = { ownerId: string; code: string; message: string };\n\nexport function validateSurveyAnswers(\n plan: SurveyStateGraph,\n answers: Readonly<Record<string, ResponseValue>>,\n context: RecordedContext,\n options: { phase: \"page\" | \"submit\"; itemIds?: readonly string[] },\n) {\n const snapshot = plan.evaluate({ answers, context });\n const evaluationDiagnostics: DefinitionDiagnostic[] = [];\n const eligible = (slotId: string) => {\n const binding = plan.bindings.get(slotId);\n return !!binding && hasPermittedChange(binding, snapshot);\n };\n const evaluate = (expression: Parameters<typeof evaluateExpression>[0], path: SchemaPath) => {\n try {\n return evaluateExpression(expression, {\n ...context,\n answer: snapshot.answer,\n disabled: snapshot.disabled,\n });\n } catch (error) {\n if (!(error instanceof ExpressionEvaluationError)) throw error;\n evaluationDiagnostics.push({\n code: \"validation-evaluation\",\n severity: \"warning\",\n path,\n message: error.message,\n });\n return undefined;\n }\n };\n const issues: InputValidationIssue[] = [];\n const authorWarnings: AuthoringWarning[] = [];\n const active = (slotId: string) => {\n const binding = plan.bindings.get(slotId);\n return (\n !!binding && [binding.controlId, ...(binding.visibilityIds ?? [])].every(snapshot.visible)\n );\n };\n const included = (itemId: string) => !options.itemIds || options.itemIds.includes(itemId);\n for (const element of plan.document.elements.values()) {\n if (!included(element.itemId)) continue;\n for (const binding of element.facts.bindings) {\n if (\n !binding.selection ||\n !active(binding.slotId) ||\n [binding.controlId, ...(binding.visibilityIds ?? [])].some(snapshot.disabled)\n )\n continue;\n if (!hasPermittedChange(binding, snapshot))\n authorWarnings.push({\n ownerId: binding.controlId,\n code: \"non-interactive-choice\",\n message:\n \"Option locks, visibility, or the selection limit leave this choice with no permitted participant change. Its constraints will not block progress; its active answer is still submitted.\",\n });\n if (binding.selection.multiple) {\n const answer = snapshot.answer(binding.slotId);\n if (answer?.type === \"reference[]\")\n for (const optionId of answer.value.filter(snapshot.disabled))\n authorWarnings.push({\n ownerId: optionId,\n code: \"locked-checkbox-selection\",\n message:\n \"This selected checkbox is now locked and cannot be unticked. It remains an active, submitted answer. Use visibility if the answer should stop applying.\",\n });\n }\n }\n for (const issue of plan.document.registry\n .get(element.node.elementType)\n .validate(element.node, snapshot.answer, (expression) =>\n evaluate(expression, element.path),\n )) {\n if (eligible(issue.slotId)) issues.push(issue);\n else if (active(issue.slotId))\n authorWarnings.push({\n ownerId: issue.messageOwnerId ?? plan.bindings.get(issue.slotId)!.controlId,\n code: \"locked-input-constraint\",\n message: `The ${issue.code} constraint is not satisfied, but this input currently permits no participant change. It will not block progress; its active answer is still submitted.`,\n });\n }\n }\n for (const item of plan.document.data.surveyItems) {\n if (item.itemType !== \"content\" || !included(item.id)) continue;\n for (const rule of item.config.validationRules ?? []) {\n if (rule.phase === \"submit\" && options.phase !== \"submit\") continue;\n const targets = rule.targets.filter(eligible);\n const activeTargets = rule.targets.filter(active);\n if (!activeTargets.length) continue;\n if (rule.when) {\n const result = evaluate(rule.when, [...plan.document.owners.get(rule.id)!.path, \"when\"]);\n if (result?.type !== \"boolean\" || !result.value) continue;\n }\n const result = evaluate(rule.expression, [\n ...plan.document.owners.get(rule.id)!.path,\n \"expression\",\n ]);\n if (result?.type !== \"boolean\" || !result.value) {\n issues.push(\n ...targets.map((slotId) => ({ slotId, code: \"rule\", messageOwnerId: rule.id })),\n );\n if (!targets.length)\n authorWarnings.push({\n ownerId: rule.id,\n code: \"locked-rule-targets\",\n message:\n \"This applicable rule fails, but none of its active targets permits a participant change. It will not block progress. Check the rule and disabling conditions.\",\n });\n }\n }\n }\n return {\n issues,\n diagnostics: [...snapshot.diagnostics, ...evaluationDiagnostics],\n authorWarnings,\n };\n}\n\n// Wording revisions share the immutable element index. This plan is used only for\n// structural dependency inspection, never to evaluate a participant session or render content.\nconst authoringDependencyPlans = new WeakMap<Survey[\"elements\"], SurveyStateGraph>();\nconst staticWarnings = new WeakMap<Survey[\"elements\"], AuthoringWarning[]>();\n\n/** Conservative proofs only: dynamic conditions and prefills are checked in a real preview. */\nfunction staticConstraintWarnings(survey: Survey, plan: SurveyStateGraph): AuthoringWarning[] {\n const literal = (expression: JsonExpression | undefined, value: boolean) =>\n expression?.type === \"const\" &&\n expression.value?.type === \"boolean\" &&\n expression.value.value === value;\n const parents = (id: string) => {\n const owner = survey.owners.get(id)!;\n return [\n ...(owner.parentId ? [owner.parentId] : []),\n ...(owner.elementId\n ? (ownValue(survey.elements.get(owner.elementId)?.facts.componentParents, id) ?? [])\n : []),\n ];\n };\n const visible = (id: string): boolean => {\n const owner = survey.owners.get(id)!;\n return (\n !owner.followUpTriggerId &&\n (!owner.visibility || literal(owner.visibility, true)) &&\n parents(id).every(visible)\n );\n };\n const hidden = (id: string): boolean =>\n literal(survey.owners.get(id)!.visibility, false) || parents(id).some(hidden);\n const disabled = (id: string): boolean =>\n literal(survey.owners.get(id)!.disabled, true) || parents(id).some(disabled);\n const locked = (slotId: string) => {\n const binding = plan.bindings.get(slotId);\n if (!binding) return false;\n const controls = [binding.controlId, ...(binding.visibilityIds ?? [])];\n return (\n controls.every(visible) &&\n (controls.some(disabled) ||\n !!binding.selection?.options.every((id) => hidden(id) || disabled(id)))\n );\n };\n const warnings: AuthoringWarning[] = [];\n for (const element of survey.elements.values()) {\n if (!element.facts.bindings.some((binding) => locked(binding.slotId))) continue;\n // An authored prefill may satisfy the requirement. Never call external sources or guess\n // participant context during synchronous author inspection.\n for (const issue of survey.registry.get(element.node.elementType).validate(\n element.node,\n () => undefined,\n () => undefined,\n ))\n if (\n (issue.code === \"required\" || issue.code === \"mustBeTrue\") &&\n locked(issue.slotId) &&\n !ownValue(element.node.prefills, issue.slotId)?.length\n )\n warnings.push({\n ownerId: issue.messageOwnerId ?? plan.bindings.get(issue.slotId)!.controlId,\n code: \"locked-input-constraint\",\n message: `The ${issue.code} constraint starts unsatisfied on an input with no permitted participant change and no prefill. It will not block progress. Check the requirement and disabling conditions.`,\n });\n }\n for (const item of survey.data.surveyItems) {\n if (item.itemType !== \"content\") continue;\n for (const rule of item.config.validationRules ?? []) {\n if (!literal(rule.expression, false) || (rule.when && !literal(rule.when, true))) continue;\n if (rule.targets.length && rule.targets.every(locked))\n warnings.push({\n ownerId: rule.id,\n code: \"locked-rule-targets\",\n message:\n \"This rule always fails, but all its targets are locked. It will not block progress. Check the rule and disabling conditions.\",\n });\n }\n }\n return warnings;\n}\n\nexport function getAuthoringWarnings(survey: Survey, locale: string) {\n const warnings: AuthoringWarning[] = [];\n const itemsWithElements = new Set([...survey.elements.values()].map((element) => element.itemId));\n for (const item of survey.data.surveyItems)\n if (item.itemType === \"content\" && !itemsWithElements.has(item.id))\n warnings.push({\n ownerId: item.id,\n code: \"empty-content-item\",\n message: \"Add an element to this empty item, or remove the item.\",\n });\n for (const owner of survey.owners.values()) {\n for (const role of owner.roles.filter((role) => role.recommended))\n if (\n !hasLocalizationText(\n readLocalizationContent(\n survey,\n { scope: \"content\", ownerId: owner.id, role: role.role },\n locale,\n ),\n )\n )\n warnings.push({\n ownerId: owner.id,\n code: \"missing-content\",\n message: `Add ${role.role} to make this structure understandable`,\n });\n }\n let plan = authoringDependencyPlans.get(survey.elements);\n if (!plan) {\n plan = new SurveyStateGraph(survey, { admission: \"draft\" });\n authoringDependencyPlans.set(survey.elements, plan);\n }\n let conflicts = staticWarnings.get(survey.elements);\n if (!conflicts) {\n conflicts = staticConstraintWarnings(survey, plan);\n staticWarnings.set(survey.elements, conflicts);\n }\n warnings.push(...conflicts);\n for (const item of survey.data.surveyItems) {\n if (item.itemType !== \"content\") continue;\n for (const rule of item.config.validationRules ?? []) {\n if (rule.phase === \"submit\") continue;\n const dependencies = [rule.expression, ...(rule.when ? [rule.when] : [])].flatMap(\n (expression) => [...plan.storedDependencies(expression)],\n );\n if (\n dependencies.some((id) => {\n const dependencyItem = survey.slots.get(id)?.itemId;\n return (\n dependencyItem &&\n dependencyItem !== item.id &&\n !isStaticallyBefore(survey, dependencyItem, item.id)\n );\n })\n )\n warnings.push({\n ownerId: rule.id,\n code: \"cross-item-page-rule\",\n message:\n \"This rule runs before leaving the page and reads answers from another item. If those answers are on a later page, the participant may be unable to continue. Consider submit-only validation or an explicit condition for unanswered dependencies.\",\n });\n }\n }\n for (const element of survey.elements.values()) {\n for (const binding of element.facts.bindings) {\n if (binding.labelRefs) {\n for (const ref of binding.labelRefs)\n if (\n !hasLocalizationText(\n readLocalizationContent(survey, { scope: \"content\", ...ref }, locale),\n ) &&\n !warnings.some(\n (warning) => warning.ownerId === ref.ownerId && warning.code === \"missing-content\",\n )\n )\n warnings.push({\n ownerId: ref.ownerId,\n code: \"missing-accessible-name\",\n message: `Add ${ref.role} to name this input in the selected language`,\n });\n } else if (\n !resolveElementName(survey, element.node.id, [locale]) &&\n !warnings.some(\n (warning) =>\n warning.ownerId === element.node.id && warning.code === \"missing-accessible-name\",\n )\n ) {\n warnings.push({\n ownerId: element.node.id,\n code: \"missing-accessible-name\",\n message: \"Add a label, or an unambiguous enclosing title, in the selected language\",\n });\n }\n }\n }\n for (const element of survey.elements.values())\n for (const binding of element.facts.bindings) {\n if (!binding.selection?.multiple) continue;\n for (const id of binding.selection.options) {\n const condition = survey.owners.get(id)?.disabled;\n if (\n condition &&\n [...plan.storedDependencies(condition)].some((slotId) => slotId !== binding.slotId)\n )\n warnings.push({\n ownerId: id,\n code: \"external-checkbox-lock\",\n message:\n \"This condition depends on another answer. An already selected checkbox can become locked and will still be submitted. Use visibility if the selection should stop applying.\",\n });\n }\n }\n return warnings;\n}\n\n/** A shared shuffled ancestor only changes order between its distinct children. */\nfunction isStaticallyBefore(survey: Survey, earlierId: string, laterId: string): boolean {\n const earlier = [...survey.getItemPath(earlierId), earlierId];\n const later = [...survey.getItemPath(laterId), laterId];\n const branch = earlier.findIndex((id, index) => id !== later[index]);\n if (branch < 1) return false;\n const parent = survey.getItem(earlier[branch - 1]);\n return (\n parent?.itemType === \"group\" &&\n !parent.config.shuffleItems &&\n parent.config.items.indexOf(earlier[branch]) < parent.config.items.indexOf(later[branch])\n );\n}\n","import { SurveyStateGraph } from \"../../engine/survey-state-graph\";\nimport { getAuthoringWarnings } from \"../../engine/validation\";\nimport {\n DefinitionError,\n type ContentOwner,\n type DefinitionDiagnostic,\n type Survey,\n} from \"./document\";\nimport type { SchemaPath } from \"../../schema/annotations\";\nimport type { SurveySession } from \"../../engine/session\";\nexport type LocatedDefinitionDiagnostic = DefinitionDiagnostic & {\n ownerItemId?: string;\n ownerId?: string;\n};\n\n/** Observed author-only conflicts use the same validation result as the player and host. */\nexport function getSessionDiagnostics(session: SurveySession): LocatedDefinitionDiagnostic[] {\n const result = session.validate(\"submit\");\n return [\n ...result.authorWarnings.map((warning) => {\n const owner = session.document.owners.get(warning.ownerId);\n return {\n ...warning,\n severity: \"warning\" as const,\n path: owner?.path ?? [],\n ownerItemId: owner?.itemId,\n };\n }),\n ...result.diagnostics.map((diagnostic) => {\n const owner = ownerAtPath(session.document, diagnostic.path);\n return { ...diagnostic, ownerId: owner?.id, ownerItemId: owner?.itemId };\n }),\n ];\n}\nexport function ownerAtPath(survey: Survey, path: SchemaPath): ContentOwner | undefined {\n return [...survey.owners.values()]\n .filter(\n (owner) =>\n owner.path.length <= path.length && owner.path.every((part, index) => part === path[index]),\n )\n .sort((a, b) => b.path.length - a.path.length)[0];\n}\n/**\n * Every dangling reference an editor draft admits: missing answers, state targets, options,\n * owners and non-flow items from the document index, plus comparisons with removed option\n * identities reported by the compiled graph. Always empty for a runnable survey.\n */\nexport function getBrokenReferences(survey: Survey): LocatedDefinitionDiagnostic[] {\n return getDefinitionDiagnostics(survey).filter(\n (diagnostic) => diagnostic.severity === \"error\" && diagnostic.kind === \"reference\",\n );\n}\nconst compiledDiagnostics = new WeakMap<Survey[\"elements\"], readonly DefinitionDiagnostic[]>();\n/** Use the authoritative definition/compiler diagnostics, including state reads and custom definitions. */\nexport function getDefinitionDiagnostics(\n survey: Survey,\n locale?: string,\n): LocatedDefinitionDiagnostic[] {\n let compiled = compiledDiagnostics.get(survey.elements);\n if (!compiled) {\n try {\n // Only compiler diagnostics are structural. Localization diagnostics belong to\n // the current document, even when wording edits reuse the element index.\n compiled = new SurveyStateGraph(survey, { admission: \"draft\" }).admittedDiagnostics;\n } catch (error) {\n if (error instanceof DefinitionError) compiled = error.diagnostics;\n else throw error;\n }\n compiledDiagnostics.set(survey.elements, compiled);\n }\n const located = [...survey.diagnostics, ...compiled].map((diagnostic) => {\n const owner =\n ownerAtPath(survey, diagnostic.path) ??\n (diagnostic.path[0] === \"translations\" && diagnostic.path[2] === \"content\"\n ? survey.owners.get(String(diagnostic.path[3]))\n : undefined);\n return { ...diagnostic, ownerItemId: owner?.itemId, ownerId: owner?.id };\n });\n if (locale) {\n try {\n for (const warning of getAuthoringWarnings(survey, locale)) {\n const owner = survey.owners.get(warning.ownerId);\n located.push({\n ...warning,\n severity: \"warning\",\n path: owner?.path ?? [],\n ownerItemId: owner?.itemId,\n });\n }\n } catch (error) {\n if (!(error instanceof DefinitionError))\n throw error; /* Already reported by graph compilation. */\n }\n }\n return [\n ...new Map(\n located.map((issue) => [JSON.stringify([issue.code, issue.path, issue.message]), issue]),\n ).values(),\n ];\n}\n","import { stringRecord, ownValue, setOwnValue } from \"../schema/string-record\";\nimport { z } from \"zod\";\nimport { responseValueSchema } from \"../survey/responses/value-schema\";\nimport { validateResponseSlotValue, responseValueElements } from \"../survey/responses/value-domain\";\nimport type { ResponseValue } from \"../survey/responses/value-types\";\nimport type { Survey, DefinitionDiagnostic, SurveyAdmission } from \"../survey/composition/document\";\nimport { evaluateExpression, ExpressionEvaluationError } from \"../expressions/evaluator\";\nimport type { JsonExpression } from \"../expressions/schema\";\nimport { SurveyStateGraph, canWriteSelection } from \"./survey-state-graph\";\nimport { validateSurveyAnswers } from \"./validation\";\nimport { createSeededRandom, shuffleArray } from \"../utils\";\nimport type { JsonSurveyResponse } from \"../survey/responses/survey-response\";\nimport { calendarDateFromLocalDate, calendarDaySchema, formatCalendarDate } from \"../calendar-date\";\n\nimport { surveyEventSchema } from \"../survey/responses/response-meta\";\n\nexport const sessionSnapshotSchema = z.strictObject({\n schemaVersion: z.literal(1),\n binding: z.strictObject({ sessionId: z.string().min(1), definitionId: z.string().min(1) }),\n answers: stringRecord(z.string().min(1), responseValueSchema),\n initialization: z.literal(\"complete\"),\n navigation: z.strictObject({\n pageIndex: z.number().int().nonnegative(),\n viewport: z.enum([\"small\", \"large\"]),\n }),\n randomization: z.strictObject({ seed: z.string().min(1) }),\n context: z.strictObject({\n locale: z.string().min(1),\n /** Defaults to the participant-local day when a new session starts; kept on resume. */\n currentDate: calendarDaySchema.optional(),\n participantFlags: stringRecord(z.string(), z.string()).optional(),\n customValues: stringRecord(z.string(), responseValueSchema).optional(),\n }),\n events: z.array(surveyEventSchema),\n});\nexport type SurveySessionSnapshot = z.infer<typeof sessionSnapshotSchema>;\n\ntype Binding = SurveySessionSnapshot[\"binding\"];\n\nexport type SessionInput =\n | {\n mode: \"new\";\n binding: Binding;\n context: SurveySessionSnapshot[\"context\"];\n answers?: Record<string, ResponseValue>;\n seed?: string;\n /**\n * Editor previews only: run an unfinished draft whose dangling references and unfinished\n * expressions evaluate as missing. Participant hosts keep the strict default.\n */\n admission?: SurveyAdmission;\n }\n | { mode: \"resumed\"; binding: Binding; snapshot: unknown };\nexport interface PrefillSources {\n previousResponse?: (reference: {\n surveyKey?: string;\n slotId: string;\n }) => Promise<ResponseValue | undefined> | ResponseValue | undefined;\n}\nexport type AnswerWrite = { slotId: string; value: ResponseValue | undefined };\n\n// Survey response events retain their existing Unix-second wire contract.\nconst eventTimestamp = () => Math.floor(Date.now() / 1000);\n\n// Stored answers include precision metadata, unlike comparisons of domain values.\n// Canonical values are flat objects; key order must not create a participant edit.\nconst comparableAnswer = (value: ResponseValue) => JSON.stringify(value, Object.keys(value).sort());\n\nfunction freezeAnswer(value: ResponseValue): ResponseValue {\n if (Array.isArray(value.value)) Object.freeze(value.value);\n return Object.freeze(value);\n}\n\nfunction sameRecord<T>(\n left: Readonly<Record<string, T>> | undefined,\n right: Readonly<Record<string, T>> | undefined,\n equal: (left: T, right: T) => boolean,\n) {\n const entries = Object.entries(left ?? {});\n return (\n entries.length === Object.keys(right ?? {}).length &&\n entries.every(([key, value]) => {\n const other = ownValue(right, key);\n return other !== undefined && equal(value, other);\n })\n );\n}\n\n/** Owns retained answers; participant adapters receive no privileged initialization write path. */\nexport class SurveySession {\n readonly stateGraph: SurveyStateGraph;\n private revision = 0;\n private presentationRevision = 0;\n private itemPresentationRevisions = new Map<string, number>();\n private initializationDiagnostics: DefinitionDiagnostic[] = [];\n private listeners = new Set<() => void>();\n\n subscribe = (listener: () => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n getRevision = () => this.revision;\n\n /** State/context changes notify every item; wording changes only notify their owning item. */\n getItemRevision = (itemId: string) =>\n this.revision - this.presentationRevision + (this.itemPresentationRevisions.get(itemId) ?? 0);\n\n /** Prefer the current page, then the next surviving item, then the previous one. */\n private pageAnchors(writtenItems: ReadonlySet<string> = new Set()) {\n const pages = this.pages();\n return [\n // A changed page boundary can separate the edited input from its old siblings.\n // Only prefer writes on the current page; batch ordering must not drive navigation.\n ...(pages[this.pageIndex] ?? []).filter((id) => writtenItems.has(id)),\n ...pages.slice(this.pageIndex).flat(),\n ...pages.slice(0, this.pageIndex).flat().reverse(),\n ];\n }\n\n private reconcilePageAndNotify(anchors?: readonly string[]) {\n const pages = this.pages();\n const pageByItem = new Map(\n pages.flatMap((items, index) => items.map((id) => [id, index] as const)),\n );\n const anchoredPage = anchors\n ?.map((id) => pageByItem.get(id))\n .find((index) => index !== undefined);\n this.state.navigation.pageIndex =\n anchoredPage ?? Math.min(this.pageIndex, Math.max(0, pages.length - 1));\n this.revision++;\n this.listeners.forEach((listener) => listener());\n }\n\n private constructor(\n private currentDocument: Survey,\n private state: SurveySessionSnapshot,\n admission: SurveyAdmission = \"strict\",\n ) {\n this.stateGraph = new SurveyStateGraph(currentDocument, { admission });\n this.validateAnswers(state.answers);\n for (const value of Object.values(state.answers)) freezeAnswer(value);\n for (const value of Object.values(state.context.customValues ?? {})) freezeAnswer(value);\n }\n\n get document(): Survey {\n return this.currentDocument;\n }\n\n /** Wording-only authoring revisions share the compiler indexes and cannot change execution.\n * Keep the compiled graph, answers, navigation and initialization when updating a live preview.\n * A structural/configuration revision must create a new session instead.\n */\n updatePresentation(document: Survey) {\n if (document === this.currentDocument) return;\n if (document.elements !== this.currentDocument.elements)\n throw new Error(\"Only wording revisions can update a session presentation\");\n const affected = new Set<string>();\n let sharedContentChanged = false;\n for (const locale of new Set([...document.locales, ...this.currentDocument.locales])) {\n const before = this.currentDocument.data.translations?.[locale];\n const after = document.data.translations?.[locale];\n if (before === after) continue;\n sharedContentChanged ||=\n before?.navigationContent !== after?.navigationContent ||\n before?.validationMessages !== after?.validationMessages;\n for (const owner of document.owners.values())\n if (before?.content[owner.id] !== after?.content[owner.id]) affected.add(owner.itemId);\n }\n if (!sharedContentChanged) {\n this.presentationRevision++;\n for (const id of affected)\n this.itemPresentationRevisions.set(id, (this.itemPresentationRevisions.get(id) ?? 0) + 1);\n }\n this.currentDocument = document;\n this.reconcilePageAndNotify();\n }\n\n static async create(document: Survey, input: SessionInput, sources: PrefillSources = {}) {\n if (input.mode === \"resumed\") {\n const snapshot = sessionSnapshotSchema.parse(input.snapshot);\n if (\n snapshot.binding.sessionId !== input.binding.sessionId ||\n snapshot.binding.definitionId !== input.binding.definitionId\n )\n throw new Error(\"Resume snapshot does not match the session and exact survey definition\");\n const session = new SurveySession(document, snapshot);\n if (session.pageIndex >= Math.max(1, session.pages().length))\n throw new Error(\"Resume page index is outside the survey\");\n return session;\n }\n const session = new SurveySession(\n document,\n sessionSnapshotSchema.parse({\n schemaVersion: 1,\n binding: input.binding,\n answers: input.answers ?? {},\n initialization: \"complete\",\n navigation: { pageIndex: 0, viewport: \"large\" },\n randomization: { seed: input.seed ?? crypto.randomUUID() },\n context: {\n ...input.context,\n currentDate: input.context.currentDate ?? calendarDateFromLocalDate(new Date()),\n },\n events: [{ type: \"openSurvey\", timestamp: eventTimestamp(), value: input.context.locale }],\n }),\n input.admission,\n );\n await session.initialize(sources);\n return session;\n }\n\n snapshot(): SurveySessionSnapshot {\n return structuredClone(this.state);\n }\n\n private itemMetadata() {\n return Object.fromEntries(\n this.pages()\n .flat()\n .map((itemId, position) => [itemId, { position }]),\n );\n }\n\n active() {\n return this.stateGraph.evaluate({ answers: this.state.answers, context: this.state.context });\n }\n\n get locale() {\n return this.state.context.locale;\n }\n\n get pageIndex() {\n return this.state.navigation.pageIndex;\n }\n\n setLocale(locale: string) {\n this.setContext({ ...this.state.context, locale });\n }\n\n /** Replace host context without restarting initialization or losing retained answers. */\n setContext(context: SurveySessionSnapshot[\"context\"]) {\n const parsed = sessionSnapshotSchema.shape.context.parse(context);\n const previous = this.state.context;\n // Omitting the current date keeps the session's frozen day instead of clearing it.\n const next = { ...parsed, currentDate: parsed.currentDate ?? previous.currentDate };\n if (!next.locale.trim()) throw new Error(\"A locale is required\");\n const localeChanged = next.locale !== previous.locale;\n if (\n !localeChanged &&\n next.currentDate === previous.currentDate &&\n sameRecord(previous.participantFlags, next.participantFlags, (a, b) => a === b) &&\n // Both sides have canonical schema field order. Context equality includes\n // metadata such as number precision, not only the answer's domain value.\n sameRecord(\n previous.customValues,\n next.customValues,\n (a, b) => JSON.stringify(a) === JSON.stringify(b),\n )\n )\n return;\n for (const value of Object.values(next.customValues ?? {})) freezeAnswer(value);\n const anchors = this.pageAnchors();\n this.state = {\n ...this.state,\n context: next,\n events: localeChanged\n ? [\n ...this.state.events,\n { type: \"languageChanged\", timestamp: eventTimestamp(), value: next.locale },\n ]\n : this.state.events,\n };\n this.reconcilePageAndNotify(anchors);\n }\n\n orderedIds(ids: readonly string[], ownerId: string): string[] {\n return shuffleArray(ids, createSeededRandom(`${this.state.randomization.seed}:${ownerId}`));\n }\n\n setViewport(viewport: \"small\" | \"large\") {\n if (viewport === this.state.navigation.viewport) return;\n const anchors = this.pageAnchors();\n this.state.navigation.viewport = viewport;\n this.reconcilePageAndNotify(anchors);\n }\n\n pages(viewport: \"small\" | \"large\" = this.state.navigation.viewport) {\n const active = this.active(),\n byId = new Map(this.document.data.surveyItems.map((item) => [item.id, item]));\n const pages: string[][] = [[]];\n const limit = this.document.data.maxItemsPerPage?.[viewport] ?? Infinity;\n const next = () => {\n if (pages.at(-1)!.length) pages.push([]);\n };\n const visit = (id: string) => {\n const item = byId.get(id);\n if (!item || !active.visible(id)) return;\n if (item.itemType === \"group\")\n (item.config.shuffleItems\n ? this.orderedIds(item.config.items, item.id)\n : item.config.items\n ).forEach(visit);\n else if (item.itemType === \"page-break\") next();\n else {\n if (pages.at(-1)!.length >= limit) next();\n pages.at(-1)!.push(id);\n }\n };\n visit(this.document.rootId);\n return pages.filter((page) => page.length);\n }\n\n validate(phase: \"page\" | \"submit\", itemIds?: readonly string[]) {\n const result = validateSurveyAnswers(this.stateGraph, this.state.answers, this.state.context, {\n phase,\n itemIds,\n });\n return { ...result, diagnostics: [...this.initializationDiagnostics, ...result.diagnostics] };\n }\n\n goToPage(index: number, viewport: \"small\" | \"large\" = this.state.navigation.viewport) {\n const pages = this.pages(viewport);\n if (!Number.isInteger(index) || index < 0 || index >= pages.length)\n throw new Error(\"Invalid page index\");\n if (index > this.pageIndex) {\n const result = this.validate(\"page\", pages[this.pageIndex]);\n if (result.issues.length) throw new Error(\"Current page has blocking validation errors\");\n }\n this.state = {\n ...this.state,\n navigation: { pageIndex: index, viewport },\n events: [\n ...this.state.events,\n { type: \"pageChanged\", timestamp: eventTimestamp(), value: index },\n ],\n };\n this.reconcilePageAndNotify();\n }\n\n submission(responseId: string): JsonSurveyResponse {\n const result = this.validate(\"submit\");\n if (result.issues.length) throw new Error(\"Survey has blocking validation errors\");\n return structuredClone({\n schemaVersion: 2,\n responseId,\n definitionId: this.state.binding.definitionId,\n answers: this.active().activeAnswers(),\n events: this.state.events,\n itemMetadata: this.itemMetadata(),\n customValues: this.state.context.customValues,\n evaluationContext: {\n locale: this.state.context.locale,\n currentDate: this.state.context.currentDate,\n participantFlags: this.state.context.participantFlags,\n },\n randomization: this.state.randomization,\n });\n }\n\n private validateAnswers(answers: Readonly<Record<string, ResponseValue>>) {\n for (const [slotId, value] of Object.entries(answers)) {\n const slot = this.document.slots.get(slotId);\n if (!slot || slot.computed) throw new Error(`Unknown or computed answer target '${slotId}'`);\n const errors = validateResponseSlotValue(slot, value);\n if (errors.length) throw new Error(errors.join(\"; \"));\n if (value.type === \"reference[]\" && new Set(value.value).size !== value.value.length)\n throw new Error(`Duplicate selected options in '${slotId}'`);\n }\n }\n\n write(writes: readonly AnswerWrite[]): void {\n if (new Set(writes.map((write) => write.slotId)).size !== writes.length)\n throw new Error(\"One action cannot write a slot twice\");\n const before = this.active();\n const changed = writes.filter(({ slotId, value }) => {\n const previous = ownValue(this.state.answers, slotId);\n return previous === undefined || value === undefined\n ? previous !== value\n : comparableAnswer(previous) !== comparableAnswer(value);\n });\n for (const { slotId, value } of writes) {\n const slot = this.document.slots.get(slotId);\n const binding = this.stateGraph.bindings.get(slotId);\n if (!slot || slot.computed || !binding)\n throw new Error(`Slot '${slotId}' is not a writable input`);\n if (value !== undefined) this.validateAnswers({ [slotId]: value });\n }\n for (const { slotId, value } of changed) {\n const binding = this.stateGraph.bindings.get(slotId)!;\n if (!canWriteSelection(binding, ownValue(this.state.answers, slotId), value, before))\n throw new Error(`Participant write to '${slotId}' is not permitted in the current state`);\n }\n if (!changed.length) return;\n const anchors = this.pageAnchors(\n new Set(changed.map(({ slotId }) => this.document.slots.get(slotId)!.itemId)),\n );\n const answers = { ...this.state.answers };\n const timestamp = eventTimestamp();\n for (const { slotId, value } of changed) {\n if (value === undefined) delete answers[slotId];\n else setOwnValue(answers, slotId, freezeAnswer(structuredClone(value)));\n }\n const events = [...this.state.events];\n for (const { slotId, value } of changed) {\n const event = {\n type: \"responseChanged\" as const,\n slotId,\n operation: value === undefined ? (\"clear\" as const) : (\"set\" as const),\n timestamp,\n };\n const previous = events.at(-1);\n // A run of edits to one answer is one activity event, with its latest timestamp.\n // Clears, other inputs, navigation and language changes retain their boundaries.\n if (\n previous?.type === event.type &&\n previous.slotId === slotId &&\n previous.operation === event.operation\n )\n events[events.length - 1] = event;\n else events.push(event);\n }\n this.state = { ...this.state, answers, events };\n this.reconcilePageAndNotify(anchors);\n }\n\n evaluate(expression: JsonExpression) {\n const active = this.active();\n return evaluateExpression(expression, {\n ...this.state.context,\n answer: active.answer,\n disabled: active.disabled,\n });\n }\n\n private async initialize(sources: PrefillSources) {\n const prefills = new Map(\n [...this.document.elements.values()].flatMap((element) =>\n Object.entries(element.node.prefills ?? {}),\n ),\n );\n for (const slotId of this.stateGraph.initializationOrder) {\n if (Object.hasOwn(this.state.answers, slotId)) continue;\n for (const [index, candidate] of (prefills.get(slotId) ?? []).entries()) {\n const element = this.document.elements.get(this.document.slots.get(slotId)!.elementId!)!;\n const path = [...element.path, \"prefills\", slotId, index];\n const warn = (message: string) =>\n this.initializationDiagnostics.push({\n code: \"prefill-value\",\n severity: \"warning\",\n path,\n message,\n });\n const evaluate = (expression: JsonExpression) => {\n try {\n return this.evaluate(expression);\n } catch (error) {\n if (!(error instanceof ExpressionEvaluationError)) throw error;\n warn(`Prefill '${candidate.id}' was skipped: ${error.message}`);\n return undefined;\n }\n };\n if (candidate.when) {\n const result = evaluate(candidate.when);\n if (result?.type !== \"boolean\" || !result.value) continue;\n }\n let value: ResponseValue | undefined;\n switch (candidate.source.type) {\n case \"static\":\n value = candidate.source.value;\n break;\n case \"expression\":\n value = evaluate(candidate.source.expression);\n break;\n case \"templateValue\": {\n const template = ownValue(this.document.data.templateValues, candidate.source.key);\n if (template?.expression) {\n value = evaluate(template.expression);\n if (template.type === \"formatDate\" && value?.type === \"date\")\n value = {\n type: \"string\",\n value: formatCalendarDate(value.value, template.dateFormat),\n };\n }\n break;\n }\n case \"previousResponse\":\n if (!sources.previousResponse && candidate.source.ifUnsupported !== \"skip\")\n throw new Error(\"This host does not supply previous responses for prefills\");\n value = await sources.previousResponse?.(candidate.source.ref);\n break;\n }\n if (value === undefined) continue;\n // Previous selections may include options removed from the current definition.\n // Preserve the still-valid identities as before, without filtering hidden options\n // or applying this normalization to participant writes/restored answers.\n if (candidate.source.type === \"previousResponse\") {\n const parsed = responseValueSchema.safeParse(value);\n const slot = this.document.slots.get(slotId)!;\n if (\n parsed.success &&\n parsed.data.type === \"reference[]\" &&\n slot.valueType === \"reference[]\" &&\n slot.allowedValues\n ) {\n const allowed = new Set(\n slot.allowedValues\n .flatMap(responseValueElements)\n .flatMap((option) => (option.type === \"reference\" ? [option.value] : [])),\n );\n const retained = parsed.data.value.filter((id) => allowed.has(id));\n if (retained.length !== parsed.data.value.length) {\n warn(\n `Prefill '${candidate.id}' discarded options outside the current response domain`,\n );\n if (!retained.length) continue;\n value = { type: \"reference[]\", value: retained };\n }\n }\n }\n const issues = this.document.slots.validateAnswers({ [slotId]: value });\n if (issues.length) {\n warn(\n `Prefill '${candidate.id}' was skipped: ${issues.map((issue) => issue.message).join(\"; \")}`,\n );\n continue;\n }\n setOwnValue(this.state.answers, slotId, freezeAnswer(structuredClone(value)));\n break;\n }\n }\n }\n}\n","import type { ExportColumn, ExportRow, CsvExportOptions } from \"./types\";\n\nconst DEFAULT_OPTIONS: Required<CsvExportOptions> = {\n separator: \",\",\n lineEnding: \"\\n\",\n includeHeader: true,\n};\n\n/**\n * Escape a cell value for CSV. Quotes the cell when it contains separator, quote, CR, or LF.\n * Doubles embedded quotes. Preserves multiline content inside quoted cells.\n */\nexport function escapeCsvCell(value: string, separator: string = \",\"): string {\n if (value === \"\") return value;\n\n const needsQuoting =\n value.includes(separator) ||\n value.includes('\"') ||\n value.includes(\"\\r\") ||\n value.includes(\"\\n\");\n\n if (!needsQuoting) return value;\n\n return `\"${value.replace(/\"/g, '\"\"')}\"`;\n}\n\n/**\n * Serialize export rows to CSV string.\n */\nexport function serializeToCsv(\n columns: ExportColumn[],\n rows: ExportRow[],\n options?: CsvExportOptions,\n): string {\n const opts = { ...DEFAULT_OPTIONS, ...options };\n const sep = opts.separator;\n const lines: string[] = [];\n\n const headers = columns.map((c) => c.header);\n\n if (opts.includeHeader) {\n lines.push(headers.map((header) => escapeCsvCell(header, sep)).join(sep));\n }\n\n for (const row of rows) {\n const cells = headers.map((header) => escapeCsvCell(row[header] ?? \"\", sep));\n lines.push(cells.join(sep));\n }\n\n return lines.join(opts.lineEnding);\n}\n","import { SurveyStateGraph } from \"../engine/survey-state-graph\";\nimport type { ResponseSlotRegistry } from \"../survey/responses/slot-registry\";\nimport type { Survey } from \"../survey/composition/document\";\n\n/** Export requires an executable definition, including complete expression operands. */\nexport function validateExportConfiguration(\n survey: Survey,\n registry: ResponseSlotRegistry = survey.slots,\n) {\n registry.assertValid();\n new SurveyStateGraph(survey);\n}\n","import { ownValue } from \"../schema/string-record\";\nimport {\n projectSlot,\n formatProjectedValue,\n resolvedSlotEncoding,\n localizedExportSlots,\n} from \"./projection\";\nimport { SurveyStateGraph } from \"../engine/survey-state-graph\";\nimport { format } from \"date-fns/format\";\nimport { validateExportConfiguration } from \"./validate-configuration\";\nimport type { ResponseSlotRegistry } from \"../survey/responses/slot-registry\";\nimport type { ReadonlyResponseSlotDefinition } from \"../survey/responses\";\nimport { SurveyResponse } from \"../survey/responses/survey-response\";\nimport { ValueType } from \"../survey/responses/value-types\";\nimport { exportSingleResponseSlot, DEFAULT_TRANSFORM } from \"./slot-formatter\";\nimport { serializeToCsv } from \"./csv-serializer\";\nimport { encodeExportColumnId } from \"./column-id\";\nimport {\n EXPORTER_PROFILE_SCHEMA_VERSION,\n META_COLUMN_ORDER,\n type ExportBatch,\n type CombinedExportOptions,\n type ExporterProfile,\n type ExportColumn,\n type SlotTransformConfig,\n type ExportRow,\n type CsvExportOptions,\n ExportColumnSource,\n} from \"./types\";\n\n// Object property order and categorical option display order do not change meaning.\nconst canonical = (value: unknown): string =>\n JSON.stringify(value, (_key, entry) =>\n entry && typeof entry === \"object\" && !Array.isArray(entry)\n ? Object.fromEntries(Object.entries(entry).sort(([a], [b]) => a.localeCompare(b)))\n : entry,\n );\n\ninterface ExportContext {\n registry: ResponseSlotRegistry;\n slots: Map<string, ReadonlyResponseSlotDefinition>;\n profile: ExporterProfile | undefined;\n columns: ExportColumn[];\n included: Set<string>;\n stateGraph: SurveyStateGraph;\n transforms: Map<string, SlotTransformConfig>;\n encodings: Map<string, string>;\n}\n\n/** Export only against schemas selected by the host, never against response version tags. */\nexport class SurveyResponseExporter {\n constructor(\n private readonly batches: ExportBatch[],\n private readonly options: CombinedExportOptions = {},\n ) {\n if (!batches.length) throw new Error(\"Supply at least one schema-bound export batch\");\n if (batches.some((batch) => !batch.schema || !Array.isArray(batch.responses)))\n throw new Error(\"Each export batch requires a schema and responses array\");\n if (batches.length > 1 && !options.codingPolicy)\n throw new Error(\"Combined export requires an explicit original or harmonized coding policy\");\n }\n\n private batch(index: number): ExportBatch {\n const batch = this.batches[index];\n if (!batch) throw new Error(`Unknown export batch: ${index}`);\n return batch;\n }\n\n private profile(batch: ExportBatch): ExporterProfile | undefined {\n if (!this.options.profile) return batch.profile;\n return {\n ...batch.profile,\n ...this.options.profile,\n slotOverrides: { ...batch.profile?.slotOverrides, ...this.options.profile.slotOverrides },\n columnHeaders: { ...batch.profile?.columnHeaders, ...this.options.profile.columnHeaders },\n contextOverrides: {\n ...batch.profile?.contextOverrides,\n ...this.options.profile.contextOverrides,\n },\n };\n }\n\n // Snapshots live for one operation only: later exports must observe schema/profile edits.\n private compileContexts(): Map<ExportBatch, ExportContext> {\n return new Map(\n this.batches.map((batch) => {\n const registry = batch.schema.slots;\n validateExportConfiguration(batch.schema, registry);\n const slots = new Map(\n localizedExportSlots(batch.schema).map((slot) => [slot.slotId, slot]),\n );\n const profile = this.profile(batch);\n const transforms = new Map(\n [...slots.values()].map((slot) => [\n slot.slotId,\n {\n ...DEFAULT_TRANSFORM,\n ...slot.exportSettings,\n ...ownValue(profile?.slotOverrides, slot.slotId),\n },\n ]),\n );\n const columns = [...slots.values()].flatMap((slot) =>\n projectSlot(slot, transforms.get(slot.slotId)!).map((column) => ({\n ...column,\n header: ownValue(profile?.columnHeaders, column.id)?.trim() ?? column.header,\n })),\n );\n const encodings = new Map<string, string>();\n for (const slotId of new Set(columns.map((column) => column.slotId!))) {\n const { include: _include, ...encoding } = resolvedSlotEncoding(\n slots.get(slotId)!,\n transforms.get(slotId)!,\n );\n encodings.set(slotId, canonical(encoding));\n }\n return [\n batch,\n {\n registry,\n slots,\n profile,\n transforms,\n encodings,\n columns,\n included: new Set(columns.map((column) => column.id)),\n stateGraph: new SurveyStateGraph(batch.schema),\n },\n ];\n }),\n );\n }\n\n private validateProfile(\n profile: ExporterProfile | undefined,\n batches: ExportBatch[],\n contexts: Map<ExportBatch, ExportContext>,\n extraResponses: SurveyResponse[] = [],\n ): void {\n if (!profile) return;\n if (profile.schemaVersion !== EXPORTER_PROFILE_SCHEMA_VERSION)\n throw new Error(\n `Unsupported exporter profile schema version: ${String(profile.schemaVersion)}`,\n );\n const slots = new Map(batches.flatMap((batch) => [...contexts.get(batch)!.slots]));\n const contextKeys = new Set(\n [...batches.flatMap((batch) => batch.responses), ...extraResponses].flatMap((response) =>\n Object.keys(response.customValues ?? {}),\n ),\n );\n const columns = new Set([\n ...[...slots.values()].flatMap((slot) =>\n projectSlot(slot, { mode: \"default\" }, true).map((column) => column.id),\n ),\n ...META_COLUMN_ORDER.map((field) => encodeExportColumnId([\"meta\", field])),\n ...[...contextKeys].map((key) => encodeExportColumnId([\"context\", key])),\n ]);\n for (const id of Object.keys(profile.slotOverrides ?? {}))\n if (!slots.has(id)) throw new Error(`Profile references unknown response slot \"${id}\"`);\n for (const id of [\n ...Object.keys(profile.columnHeaders ?? {}),\n ...(profile.responseColumnOrder ?? []),\n ])\n if (!columns.has(id)) throw new Error(`Profile references unknown export column \"${id}\"`);\n for (const id of profile.responseColumnOrder ?? [])\n if (\n ![...slots.values()].some((slot) =>\n projectSlot(slot, { mode: \"default\" }, true).some((column) => column.id === id),\n )\n )\n throw new Error(`Response column order contains a non-response column: ${id}`);\n for (const key of [\n ...Object.keys(profile.contextOverrides ?? {}),\n ...(profile.contextColumnOrder ?? []),\n ])\n if (!contextKeys.has(key)) throw new Error(`Profile references unknown context key \"${key}\"`);\n for (const slot of slots.values()) {\n if (\n (slot.naming?.kind === \"matrix\" || slot.rowId || slot.columnId) &&\n projectSlot(slot, { mode: \"default\" }, true).some((column) =>\n Object.hasOwn(profile.columnHeaders ?? {}, column.id),\n )\n )\n throw new Error(\n `Matrix variable \"${slot.slotId}\" cannot have an individual header override; edit its matrix coding components`,\n );\n }\n for (const [id, header] of Object.entries(profile.columnHeaders ?? {}))\n if (typeof header !== \"string\" || !header.trim())\n throw new Error(`Export header for \"${id}\" cannot be empty`);\n if (new Set(profile.responseColumnOrder).size !== (profile.responseColumnOrder?.length ?? 0))\n throw new Error(\"Response column order contains duplicate identities\");\n }\n\n computeResponseColumns(batchIndex = 0, extraResponses: SurveyResponse[] = []): ExportColumn[] {\n const batch = this.batch(batchIndex);\n const contexts = this.compileContexts();\n this.validateProfile(batch.profile, [batch], contexts, extraResponses);\n this.validateProfile(this.options.profile, this.batches, contexts, extraResponses);\n return contexts.get(batch)!.columns;\n }\n\n computeColumns(extraResponses: SurveyResponse[] = []): ExportColumn[] {\n return this.columns(this.compileContexts(), extraResponses);\n }\n\n private columns(\n contexts: Map<ExportBatch, ExportContext>,\n extraResponses: SurveyResponse[] = [],\n ): ExportColumn[] {\n this.validateProfile(this.options.profile, this.batches, contexts, extraResponses);\n const columns = new Map<string, ExportColumn>();\n const signatures = new Map<string, string>();\n const encodings = new Map<string, string>();\n this.batches.forEach((batch) => {\n const context = contexts.get(batch)!;\n this.validateProfile(batch.profile, [batch], contexts, extraResponses);\n for (const slot of context.slots.values()) {\n const signature = canonical({\n type: slot.valueType,\n allowedValues: slot.allowedValues?.map((value) => canonical(value)).sort(),\n codes:\n this.options.codingPolicy === \"harmonized\"\n ? (ownValue(context.profile?.slotOverrides, slot.slotId)?.optionCodes ??\n slot.referenceValueKeys)\n : slot.referenceValueKeys,\n computed: slot.computed,\n scores: slot.referenceValueScores,\n });\n const previous = signatures.get(slot.slotId);\n if (previous && previous !== signature)\n throw new Error(\n `Incompatible schema definitions for slot \"${slot.slotId}\"; supply a compatible explicit harmonization mapping`,\n );\n signatures.set(slot.slotId, signature);\n }\n for (const column of context.columns) {\n const signature = context.encodings.get(column.slotId!)!;\n if (encodings.has(column.id) && encodings.get(column.id) !== signature)\n throw new Error(\n `Incompatible export encodings for column \"${column.id}\"; supply one harmonized profile`,\n );\n encodings.set(column.id, signature);\n const existing = columns.get(column.id);\n if (existing && existing.header !== column.header)\n throw new Error(\n `Conflicting names for column \"${column.id}\"; select an explicit harmonized output header`,\n );\n columns.set(column.id, column);\n }\n });\n const profile =\n this.options.profile ?? (this.batches.length === 1 ? this.batches[0].profile : undefined);\n const allResponses = [...this.batches.flatMap((batch) => batch.responses), ...extraResponses];\n const contextKeys = [\n ...new Set(allResponses.flatMap((response) => Object.keys(response.customValues ?? {}))),\n ];\n const ordered = <T>(\n values: T[],\n order: string[],\n id: (value: T) => string,\n name: (value: T) => string,\n ) =>\n values.sort((a, b) => {\n const left = order.indexOf(id(a)),\n right = order.indexOf(id(b));\n if (left >= 0 || right >= 0)\n return (left < 0 ? Infinity : left) - (right < 0 ? Infinity : right);\n return name(a).localeCompare(name(b));\n });\n const result: ExportColumn[] = [\n ...META_COLUMN_ORDER.map((field) => ({\n id: encodeExportColumnId([\"meta\", field]),\n header: profile?.columnHeaders?.[encodeExportColumnId([\"meta\", field])]?.trim() ?? field,\n source: ExportColumnSource.meta,\n metaField: field,\n })),\n ...ordered(\n contextKeys,\n profile?.contextColumnOrder ?? [],\n (value) => value,\n (value) => value,\n ).map((key) => ({\n id: encodeExportColumnId([\"context\", key]),\n header:\n profile?.columnHeaders?.[encodeExportColumnId([\"context\", key])]?.trim() ??\n `context.${key}`,\n source: ExportColumnSource.context,\n contextKey: key,\n })),\n ...ordered(\n [...columns.values()],\n profile?.responseColumnOrder ?? [],\n (value) => value.id,\n (value) => value.header,\n ),\n ];\n const headers = new Set<string>();\n for (const column of result) {\n if (headers.has(column.header))\n throw new Error(`Duplicate export column header '${column.header}'`);\n headers.add(column.header);\n }\n return result;\n }\n\n private row(\n response: SurveyResponse,\n batch: ExportBatch,\n columns: ExportColumn[],\n context: ExportContext,\n ): ExportRow {\n const { registry, slots, profile, included, transforms } = context;\n const diagnostics = registry.validateAnswers(response.answers);\n if (diagnostics.length) throw new Error(diagnostics.map((issue) => issue.message).join(\"\\n\"));\n const row: ExportRow = Object.create(null);\n const active = context.stateGraph.evaluate({\n answers: response.answers,\n context: {\n locale: response.evaluationContext?.locale ?? batch.schema.locales[0] ?? \"en\",\n currentDate: response.evaluationContext?.currentDate,\n participantFlags: response.evaluationContext?.participantFlags,\n customValues: response.customValues,\n },\n });\n for (const column of columns) {\n if (column.source === ExportColumnSource.meta) {\n switch (column.metaField) {\n case \"responseId\":\n row[column.header] = response.responseId;\n break;\n case \"participantId\":\n row[column.header] = response.participantId ?? \"\";\n break;\n case \"sourceId\":\n row[column.header] = batch.sourceId ?? \"\";\n break;\n case \"submittedAt\":\n row[column.header] = response.submittedAt\n ? format(new Date(response.submittedAt * 1000), \"yyyy-MM-dd'T'HH:mm:ss.SSSxxx\")\n : \"\";\n break;\n }\n } else if (column.source === ExportColumnSource.context) {\n const value = ownValue(response.customValues, column.contextKey!);\n row[column.header] = exportSingleResponseSlot({\n value,\n valueType: value?.type ?? ValueType.string,\n transformConfig: ownValue(profile?.contextOverrides, column.contextKey!) ?? {\n ...DEFAULT_TRANSFORM,\n categorical: \"ids\",\n },\n });\n } else {\n const slot = slots.get(column.slotId!);\n row[column.header] =\n slot && included.has(column.id)\n ? formatProjectedValue(\n slot,\n column,\n active.answer(slot.slotId),\n transforms.get(slot.slotId)!,\n )\n : \"\";\n }\n }\n return row;\n }\n\n /** Explicitly associate one response with a supplied batch schema. */\n exportResponse(response: SurveyResponse, batchIndex = 0): ExportRow {\n return new SurveyResponseExporter([{ ...this.batch(batchIndex), responses: [response] }], {\n profile: this.options.profile,\n }).exportRows()[0];\n }\n\n exportRows(): ExportRow[] {\n const contexts = this.compileContexts();\n return this.rows(this.columns(contexts), contexts);\n }\n\n private rows(columns: ExportColumn[], contexts: Map<ExportBatch, ExportContext>): ExportRow[] {\n return this.batches.flatMap((batch) =>\n batch.responses.map((response) => this.row(response, batch, columns, contexts.get(batch)!)),\n );\n }\n\n exportResponsesToCsv(options?: CsvExportOptions): string {\n const contexts = this.compileContexts();\n const columns = this.columns(contexts);\n return serializeToCsv(columns, this.rows(columns, contexts), options);\n }\n}\n","import { ownValue, setOwnValue } from \"../schema/string-record\";\nimport { resolvedSlotEncoding, localizedExportSlots } from \"./projection\";\nimport { SurveyResponseExporter } from \"./exporter\";\nimport type { ExporterProfile, ExportColumn } from \"./types\";\nimport type { Survey } from \"../survey/composition/document\";\nimport { validateExportConfiguration } from \"./validate-configuration\";\nimport { getContentPlainText } from \"../survey/utils/content\";\nimport type { ResponseSlotDefinition } from \"../survey/responses/slot-definition\";\nimport type { ResponseValue, ValueType } from \"../survey/responses/value-types\";\n\n/** Single slot entry in codebook. */\nexport interface CodebookSlot {\n slotId: string;\n elementId: string;\n rowId?: string;\n columnId?: string;\n computed?: ResponseSlotDefinition[\"computed\"];\n variableName: string;\n encoding?: import(\"./types\").SlotTransformConfig;\n optionLabels?: Record<string, Record<string, string>>;\n allowedValues?: import(\"../survey/responses\").ResponseValue[];\n valueType: ValueType;\n /** Categorical export codes for stable reference IDs; missing mappings block code exports. */\n referenceValueKeys?: Record<string, string>;\n referenceValueScores?: Record<string, number>;\n}\n\n/** Single item entry in codebook. */\nexport interface CodebookItem {\n id: string;\n editorName: string;\n breadcrumb: string;\n type: string;\n interactive: boolean;\n slots: CodebookSlot[];\n /** Content by locale, owner identity, and declared role. */\n contentByLocale?: Record<string, Record<string, Record<string, string>>>;\n}\n\n/** Full codebook for a survey. */\nexport interface Codebook {\n surveyKey?: string;\n items: CodebookItem[];\n projection: ExportColumn[];\n profile?: ExporterProfile;\n missingValue: \"\";\n}\n\n/**\n * Generate a structured codebook from a survey definition.\n */\nexport function generateCodebook(\n survey: Survey,\n options?: { locales?: string[]; profile?: ExporterProfile },\n): Codebook {\n const registry = survey.slots;\n validateExportConfiguration(survey, registry);\n const slots = localizedExportSlots(survey);\n const locales = options?.locales ?? survey.locales;\n const slotDefsByItemId = new Map<string, CodebookSlot[]>();\n for (const slot of slots) {\n const entries = slotDefsByItemId.get(slot.itemId) ?? [];\n entries.push({\n slotId: slot.slotId,\n elementId: slot.elementId,\n ...(slot.rowId ? { rowId: slot.rowId } : {}),\n ...(slot.columnId ? { columnId: slot.columnId } : {}),\n variableName: slot.variableName,\n valueType: slot.valueType,\n encoding: resolvedSlotEncoding(slot, {\n mode: \"default\",\n ...slot.exportSettings,\n ...ownValue(options?.profile?.slotOverrides, slot.slotId),\n }),\n optionLabels: slot.referenceValueLabels,\n ...(slot.allowedValues\n ? {\n allowedValues: slot.allowedValues.map((value) => structuredClone<ResponseValue>(value)),\n }\n : {}),\n ...(slot.computed\n ? { computed: { ...slot.computed, sourceSlotIds: [...slot.computed.sourceSlotIds] } }\n : {}),\n ...(slot.referenceValueKeys ? { referenceValueKeys: { ...slot.referenceValueKeys } } : {}),\n ...(slot.referenceValueScores\n ? { referenceValueScores: { ...slot.referenceValueScores } }\n : {}),\n });\n slotDefsByItemId.set(slot.itemId, entries);\n }\n\n const items: CodebookItem[] = [];\n\n for (const item of survey.data.surveyItems) {\n const slotList = slotDefsByItemId.get(item.id) ?? [];\n slotList.sort((a, b) => a.slotId.localeCompare(b.slotId));\n\n let contentByLocale: Record<string, Record<string, Record<string, string>>> | undefined;\n\n if (locales.length > 0) {\n contentByLocale = {};\n for (const locale of locales) {\n const values: Record<string, Record<string, string>> = {};\n for (const owner of survey.owners.values())\n if (owner.itemId === item.id) {\n const roles = ownValue(ownValue(survey.data.translations, locale)?.content, owner.id);\n if (roles)\n setOwnValue(\n values,\n owner.id,\n Object.fromEntries(\n Object.entries(roles).map(([role, content]) => [\n role,\n getContentPlainText(content),\n ]),\n ),\n );\n }\n setOwnValue(contentByLocale, locale, values);\n }\n }\n items.push({\n id: item.id,\n editorName: survey.resolveItemEditorName(item.id, locales[0]),\n breadcrumb: survey.getItemDisplayPath(item.id, locales[0])!.breadcrumb,\n type: item.itemType,\n interactive: slotList.some((slot) => !slot.computed),\n slots: slotList,\n contentByLocale,\n });\n }\n\n return {\n surveyKey: survey.data.metadata?.surveyKey,\n items: items,\n projection: new SurveyResponseExporter([\n { schema: survey, responses: [], profile: options?.profile },\n ]).computeColumns(),\n profile: options?.profile && structuredClone(options.profile),\n missingValue: \"\",\n };\n}\n\n/** Describe precisely the combined projection and each host-selected source definition. */\nexport function generateExportCodebook(\n batches: import(\"./types\").ExportBatch[],\n options: import(\"./types\").CombinedExportOptions = {},\n) {\n const exporter = new SurveyResponseExporter(batches, options);\n return {\n schemaVersion: 1,\n codingPolicy: options.codingPolicy ?? \"original\",\n columns: exporter.computeColumns(),\n missingValue: \"\",\n profile: options.profile && structuredClone(options.profile),\n sources: batches.map((batch) => ({\n sourceId: batch.sourceId,\n surveySchemaVersion: batch.schema.serialize().schemaVersion,\n profile: batch.profile && structuredClone(batch.profile),\n variables: localizedExportSlots(batch.schema).map((slot) => ({\n ...slot,\n encoding: resolvedSlotEncoding(slot, {\n mode: \"default\",\n ...slot.exportSettings,\n ...(ownValue(options.profile?.slotOverrides, slot.slotId) ??\n ownValue(batch.profile?.slotOverrides, slot.slotId)),\n }),\n })),\n })),\n };\n}\n","import { SurveyStateGraph, type RecordedContext } from \"./survey-state-graph\";\nimport { validateSurveyAnswers } from \"./validation\";\nimport { SurveyResponse } from \"../survey/responses/survey-response\";\nimport type { Survey } from \"../survey/composition/document\";\n\n/** The host chooses the exact definition and trusted context before calling this boundary. */\nexport function validateSurveySubmission(\n survey: Survey,\n input: unknown,\n context: RecordedContext & { locale: string },\n binding: { definitionId: string },\n): SurveyResponse {\n const response = SurveyResponse.deserialize(input);\n if (response.definitionId !== binding.definitionId)\n throw new Error(\n `Response was given against definition '${response.definitionId}', not '${binding.definitionId}'`,\n );\n const issues = survey.slots.validateAnswers(response.answers);\n if (issues.length) throw new Error(issues.map((issue) => issue.message).join(\"\\n\"));\n const plan = new SurveyStateGraph(survey);\n const active = plan.evaluate({ answers: response.answers, context });\n const applicable = active.activeAnswers();\n // Hidden components are retained only in resume state, never in response storage.\n const validation = validateSurveyAnswers(plan, applicable, context, { phase: \"submit\" });\n if (validation.issues.length)\n throw new Error(validation.issues.map((issue) => `${issue.slotId}: ${issue.code}`).join(\"\\n\"));\n response.answers = structuredClone(applicable);\n response.evaluationContext = {\n locale: context.locale,\n currentDate: context.currentDate,\n participantFlags: context.participantFlags && { ...context.participantFlags },\n };\n response.customValues = context.customValues && structuredClone(context.customValues);\n return response;\n}\n"],"mappings":";;;;;;AAsBA,IAAa,iBAAb,cAAoC,MAAM;CAG7B;CACA;CACA;CAJX,YACE,SACA,MACA,MACA,gBACA;EACA,MAAM,OAAO;EAJJ,KAAA,OAAA;EACA,KAAA,OAAA;EACA,KAAA,iBAAA;EAGT,KAAK,OAAO;CACd;AACF;AAEA,MAAM,UAAU,OAAe,QAAgB,OAAO,UAAU,eAAe,KAAK,OAAO,GAAG;AAE9F,MAAM,YAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAErE,MAAM,6BAA6B,SAAiB,YAAoB;CACtE,IAAI,YAAY,KAAK,OAAO,GAC1B,MAAM,IAAI,eACR,iCAAiC,QAAQ,QAAQ,QAAQ,6CACzD,wBACA,OACF;AAEJ;AAEA,MAAa,4BAA4B,YAA4B;CACnE,0BAA0B,SAAS,OAAO;CAC1C,OAAO,QAAQ,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,GAAG;AACvD;AAEA,MAAa,4BAA4B,YACvC,QAAQ,QAAQ,MAAM,IAAI,CAAC,CAAC,QAAQ,OAAO,IAAI;AAEjD,M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