@petrarca/sonnet-schema-designer 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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/questionnaire/answerTypes.ts","../src/questionnaire/limits.ts","../src/questionnaire/valueTypes.ts","../src/questionnaire/optionsListName.ts","../src/questionnaire/classify.ts","../src/model/paths.ts","../src/model/mutate.ts","../src/model/view.ts","../src/questionnaire/showIf.ts","../src/model/conditions.ts","../src/questionnaire/reasons.ts","../src/questionnaire/edit.ts","../src/questionnaire/completion.ts","../src/questionnaire/capabilities.ts"],"sourcesContent":["/**\n * Answer types -- a question's kind of answer, as a pattern of schema keywords\n * and form hints. Pure, no React.\n *\n * An answer type is never stored: `recognizeAnswerType` finds it in a property\n * and its effective hints, and names the keywords the pattern does not account\n * for (the question's extra settings, kept untouched). See\n * docs/design/questionnaires.md, \"Answer types\".\n */\n\nimport {\n valueRefOf,\n type JsonSchemaProperty,\n type UISchema,\n} from \"@petrarca/sonnet-core/schema\";\n\nimport { limitsFor } from \"./limits\";\nimport {\n DEFAULT_VALUE_TYPES,\n valueTypeOf,\n type ValueTypeAnswer,\n} from \"./valueTypes\";\n\n/** The answer types the questionnaire designer knows itself. */\nexport type BuiltinAnswerType =\n | \"yesNo\"\n | \"shortText\"\n | \"longText\"\n | \"integer\"\n | \"decimal\"\n | \"date\"\n | \"time\"\n | \"dateTime\"\n | \"singleChoice\"\n | \"multipleChoice\"\n | \"choiceWithText\"\n | \"listOfText\"\n | \"parts\";\n\n/**\n * An answer type: a built-in one, or a contributed value type -- by its id\n * (see valueTypes.ts).\n */\nexport type AnswerType = BuiltinAnswerType | (string & {});\n\n/** What each built-in answer type is called where an author sees it. */\nexport const ANSWER_TYPE_LABELS: Record<BuiltinAnswerType, string> = {\n yesNo: \"Yes / no\",\n shortText: \"Short text\",\n longText: \"Long text\",\n integer: \"Integer\",\n decimal: \"Decimal\",\n date: \"Date\",\n time: \"Time\",\n dateTime: \"Date and time\",\n singleChoice: \"Single choice\",\n multipleChoice: \"Multiple choice\",\n choiceWithText: \"Choice with text\",\n listOfText: \"List of text\",\n parts: \"Parts\",\n};\n\n/** Whether an answer type is one the designer knows itself, not a contributed value type. */\nexport function isBuiltinAnswerType(type: string): type is BuiltinAnswerType {\n return type in ANSWER_TYPE_LABELS;\n}\n\n/** What an answer type is called: its label, or its contribution's. */\nexport function answerTypeLabel(\n type: AnswerType,\n types: readonly ValueTypeAnswer[] = DEFAULT_VALUE_TYPES,\n): string {\n if (isBuiltinAnswerType(type)) return ANSWER_TYPE_LABELS[type];\n return types.find((t) => t.type.id === type)?.type.label ?? type;\n}\n\n/**\n * The container widget a choice with text renders with: it arranges its two\n * children, `choice` and `text`, each rendered by its own widget -- a select,\n * radio buttons, a terminology picker -- resolved as for any field.\n */\nexport const CHOICE_WITH_TEXT_WIDGET = \"choice-with-text\";\n\n// The answer types that are containers: their children are answers of their own.\nconst CONTAINER_TYPES: AnswerType[] = [\"choiceWithText\", \"parts\"];\n\n/** Whether an answer type is a container -- its children answers of their own, it no answer itself. */\nexport function isContainerType(type: AnswerType): boolean {\n return CONTAINER_TYPES.includes(type);\n}\n// What a container's children may be.\nconst CHILD_TYPES: Partial<\n Record<AnswerType, Record<string, AnswerType[]> | AnswerType[]>\n> = {\n choiceWithText: { choice: [\"singleChoice\"], text: [\"shortText\", \"longText\"] },\n parts: [\n \"yesNo\",\n \"shortText\",\n \"longText\",\n \"integer\",\n \"decimal\",\n \"date\",\n \"time\",\n \"dateTime\",\n \"singleChoice\",\n ],\n};\n\n/** A recognized answer: its type, and the keywords the pattern leaves unexplained. */\nexport interface RecognizedAnswer {\n type: AnswerType;\n /** Schema keywords and hints beyond the pattern -- shown as extra settings, kept as they are. */\n extras: string[];\n}\n\n// Keywords every question may carry: its text, help and the read-only flag.\nconst QUESTION_KEYWORDS = [\"title\", \"description\", \"readOnly\"];\n// Hints every question may carry: text, help and an example.\nconst QUESTION_HINTS = [\"x-ui-title\", \"x-ui-description\", \"x-ui-placeholder\"];\n\n// The keywords and hint keys a pattern uses beyond the common ones, and the\n// widgets it knows as its presentations (undefined: no widget hint). Another\n// widget is kept as an extra setting: the type comes from the schema's shape.\ninterface Pattern {\n type: AnswerType;\n keywords: string[];\n widgets: (string | undefined)[];\n options?: string[];\n}\n\nfunction pattern(\n type: AnswerType,\n keywords: string[],\n widgets: (string | undefined)[] = [undefined],\n options?: string[],\n): Pattern {\n return { type, keywords, widgets, options };\n}\n\nconst STRING_FORMATS: Record<string, AnswerType> = {\n date: \"date\",\n time: \"time\",\n \"date-time\": \"dateTime\",\n};\n\n// The patterns of the plain scalar types, by JSON type.\nconst SCALAR_PATTERNS: Partial<Record<string, Pattern>> = {\n boolean: pattern(\"yesNo\", [\"type\"], [undefined, \"checkbox\"]),\n integer: pattern(\"integer\", [\"type\"], [undefined, \"number\"]),\n number: pattern(\"decimal\", [\"type\"], [undefined, \"number\"]),\n};\n\n// The pattern a property follows, by its shape; null when it follows none.\nfunction patternOf(\n prop: JsonSchemaProperty,\n widget: string | undefined,\n types: readonly ValueTypeAnswer[],\n): Pattern | null {\n const valueType = valueTypeOrRef(prop, types);\n if (valueType !== undefined) return valueType;\n if (isSingleChoice(prop)) {\n return pattern(\n \"singleChoice\",\n [\"type\", \"enum\"],\n [undefined, \"select\", \"radio\"],\n [\"enumNames\"],\n );\n }\n if (prop.type === \"string\") return stringPattern(prop, widget);\n if (prop.type === \"array\") return arrayPattern(prop);\n if (prop.type === \"object\") return objectPattern(prop, widget);\n return (prop.type && SCALAR_PATTERNS[prop.type]) ?? null;\n}\n\n// A value type's pattern -- also of it or a text, or several: an array of it;\n// null for a reference to no contributed type; undefined for neither.\nfunction valueTypeOrRef(\n prop: JsonSchemaProperty,\n types: readonly ValueTypeAnswer[],\n): Pattern | null | undefined {\n const valueType = valueRefOf(prop) && valueTypePattern(prop, types);\n if (valueType) return valueType;\n return prop.$ref ? null : undefined;\n}\n\n// A single choice: a string (or untyped) property with options.\nfunction isSingleChoice(prop: JsonSchemaProperty): boolean {\n const hasEnum = Array.isArray(prop.enum) && prop.enum.length > 0;\n return hasEnum && (prop.type === \"string\" || prop.type === undefined);\n}\n\n// A contributed value type: its $ref, what it narrows beside it, its widget and settings' options.\nfunction valueTypePattern(\n prop: JsonSchemaProperty,\n types: readonly ValueTypeAnswer[],\n): Pattern | null {\n const found = valueTypeOf(prop, types);\n if (!found) return null;\n const widget = found.type.definition[\"x-ui-widget\"];\n return pattern(\n found.type.id,\n [\"$ref\", \"anyOf\", \"type\", \"items\", ...(found.keywords ?? [])],\n [undefined, ...(typeof widget === \"string\" ? [widget] : [])],\n found.options,\n );\n}\n\nfunction stringPattern(\n prop: JsonSchemaProperty,\n widget: string | undefined,\n): Pattern {\n const byFormat = prop.format ? STRING_FORMATS[prop.format] : undefined;\n if (byFormat) {\n const widgetName = byFormat === \"dateTime\" ? \"date-time\" : byFormat;\n return pattern(byFormat, [\"type\", \"format\"], [undefined, widgetName]);\n }\n if (widget === \"textarea\") return pattern(\"longText\", [\"type\"], [\"textarea\"]);\n return pattern(\"shortText\", [\"type\"], [undefined, \"text\"]);\n}\n\nfunction arrayPattern(prop: JsonSchemaProperty): Pattern | null {\n const items = prop.items;\n if (\n !items ||\n items.type !== \"string\" ||\n hasOtherKeys(items, [\"type\", \"enum\"])\n ) {\n return null;\n }\n return Array.isArray(items.enum) && items.enum.length > 0\n ? pattern(\n \"multipleChoice\",\n [\"type\", \"items\", \"uniqueItems\"],\n [undefined, \"select\", \"checkbox-group\"],\n [\"enumNames\"],\n )\n : pattern(\"listOfText\", [\"type\", \"items\"], [undefined, \"tags\"]);\n}\n\nfunction objectPattern(\n prop: JsonSchemaProperty,\n widget: string | undefined,\n): Pattern | null {\n if (widget === CHOICE_WITH_TEXT_WIDGET && isChoiceWithText(prop)) {\n return pattern(\n \"choiceWithText\",\n [\"type\", \"properties\", \"required\", \"allOf\"],\n [CHOICE_WITH_TEXT_WIDGET],\n );\n }\n if (isParts(prop)) {\n return pattern(\"parts\", [\n \"type\",\n \"properties\",\n \"required\",\n \"x-ui-order\",\n \"x-ui-layout\",\n ]);\n }\n return null;\n}\n\n// A choice with text: exactly `choice` (an enum of strings) and `text` (a string).\nfunction isChoiceWithText(prop: JsonSchemaProperty): boolean {\n const children = choiceWithTextChildren(prop);\n if (!children) return false;\n const { choice, text } = children;\n return (\n Array.isArray(choice.enum) &&\n choice.enum.length > 0 &&\n text.type === \"string\" &&\n !text.enum\n );\n}\n\n/**\n * The option of a choice with text whose choice asks for the text (\"other,\n * please describe\"); none for the variant whose text is an optional note.\n *\n * The note variant has `choice` and `text` as properties. The other variant\n * has only `choice`, and one conditional of its own: if the choice is that\n * option, then `text`, required.\n */\nexport function choiceTextWhen(prop: JsonSchemaProperty): string | undefined {\n const member = prop.allOf?.length === 1 ? prop.allOf[0] : undefined;\n const constraint = member?.if?.properties?.choice;\n return constraint && \"const\" in constraint\n ? String(constraint.const)\n : undefined;\n}\n\n// A choice with text's two children, wherever its text sits; null when the\n// object is neither variant's shape.\n/** The conditional of a choice with text's \"other\" variant: if the choice is `when`, then the text, required. */\nexport function otherTextMember(\n when: string,\n text: JsonSchemaProperty,\n): JsonSchemaProperty {\n return {\n if: { properties: { choice: { const: when } }, required: [\"choice\"] },\n then: { properties: { text }, required: [\"text\"] },\n };\n}\n\n// A choice with text's two children, wherever its text sits; null when the\n// object is neither variant's shape.\nfunction choiceWithTextChildren(\n prop: JsonSchemaProperty,\n): { choice: JsonSchemaProperty; text: JsonSchemaProperty } | null {\n const p = prop.properties ?? {};\n const keys = Object.keys(p).sort().join(\",\");\n if (keys === \"choice,text\" && !prop.allOf)\n return { choice: p.choice, text: p.text };\n return keys === \"choice\" ? otherVariantChildren(prop) : null;\n}\n\n// The other variant's children: its choice, and the text of its one conditional\n// -- when that conditional is exactly otherTextMember for one of the options.\nfunction otherVariantChildren(\n prop: JsonSchemaProperty,\n): { choice: JsonSchemaProperty; text: JsonSchemaProperty } | null {\n const { choice, text } = rawChoiceAndText(prop);\n const when = choiceTextWhen(prop);\n if (!choice || !text || when === undefined || prop.allOf?.length !== 1)\n return null;\n const isOption = (choice.enum ?? []).map(String).includes(when);\n const exact =\n JSON.stringify(prop.allOf[0]) ===\n JSON.stringify(otherTextMember(when, text));\n return isOption && exact ? { choice, text } : null;\n}\n\n/** A choice with text's choice and text, wherever its variant keeps the text -- unchecked. */\nexport function rawChoiceAndText(prop: JsonSchemaProperty): {\n choice?: JsonSchemaProperty;\n text?: JsonSchemaProperty;\n} {\n const conditional = prop.allOf?.[0]?.then?.properties?.text;\n return {\n choice: prop.properties?.choice,\n text: prop.properties?.text ?? conditional,\n };\n}\n\n// Parts: an object laid out as one row of plain sub-answers -- the row is what\n// tells parts of one answer from a section of questions.\nfunction isParts(prop: JsonSchemaProperty): boolean {\n const p = prop.properties;\n const rows = prop[\"x-ui-layout\"]?.rows;\n if (!p || !rows || rows.length !== 1) return false;\n const keys = Object.keys(p);\n const inRow = new Set(rows[0].fields);\n return (\n keys.length > 0 &&\n keys.every((k) => inRow.has(k)) &&\n keys.every((k) => p[k].type !== \"object\" && p[k].type !== \"array\")\n );\n}\n\nfunction hasOtherKeys(obj: object, allowed: string[]): boolean {\n return Object.keys(obj).some((k) => !allowed.includes(k));\n}\n\n// The hint keys a question's effective hints carry beyond what the pattern explains.\nfunction hintExtras(ui: UISchema, p: Pattern): string[] {\n const extras: string[] = [];\n const container = CONTAINER_TYPES.includes(p.type);\n for (const key of Object.keys(ui)) {\n if (QUESTION_HINTS.includes(key) || key === \"x-ui-widget\") continue;\n // A container's children carry their hints in x-ui-fields; they are checked as children.\n if (container && key === \"x-ui-fields\") continue;\n if (key === \"x-ui-options\") {\n const options = Object.keys((ui[key] as object | undefined) ?? {});\n extras.push(\n ...options\n .filter((o) => !p.options?.includes(o))\n .map((o) => `x-ui-options.${o}`),\n );\n continue;\n }\n extras.push(key);\n }\n return extras;\n}\n\n/**\n * The answer type a property follows, with its extra settings; null when the\n * property follows no answer type -- the questionnaire designer then does not\n * understand it. A widget the type does not know is an extra setting, not a\n * reason: the type comes from the schema's shape.\n */\nexport function recognizeAnswerType(\n prop: JsonSchemaProperty,\n ui: UISchema,\n types: readonly ValueTypeAnswer[] = DEFAULT_VALUE_TYPES,\n): RecognizedAnswer | null {\n const widget = ui[\"x-ui-widget\"] as string | undefined;\n const p = patternOf(prop, widget, types);\n if (!p) return null;\n // A question's limits belong to its answer type: understood, not extras --\n // as does its default answer, unless it is a container, which has none.\n const known = new Set([\n ...QUESTION_KEYWORDS,\n ...p.keywords,\n ...limitsFor(p.type),\n ...(isContainerType(p.type) ? [] : [\"default\"]),\n ]);\n const schemaExtras = Object.keys(prop).filter(\n (k) => !known.has(k) && !k.startsWith(\"x-ui-\"),\n );\n const widgetExtra = p.widgets.includes(widget) ? [] : [\"x-ui-widget\"];\n const extras = [...schemaExtras, ...widgetExtra, ...hintExtras(ui, p)];\n if (!CONTAINER_TYPES.includes(p.type)) return { type: p.type, extras };\n const children = childExtras(prop, ui, p.type);\n return children ? { type: p.type, extras: [...extras, ...children] } : null;\n}\n\n// A container's children, each an answer of an allowed type: their extras,\n// prefixed by the child's key; null when a child is not such an answer.\nfunction childExtras(\n prop: JsonSchemaProperty,\n ui: UISchema,\n type: AnswerType,\n): string[] | null {\n const fields =\n (ui[\"x-ui-fields\"] as Record<string, UISchema> | undefined) ?? {};\n const allowed = CHILD_TYPES[type];\n const extras: string[] = [];\n for (const [key, child] of Object.entries(containerChildren(prop, type))) {\n const childUi = { ...embeddedHints(child), ...fields[key] };\n const answer = recognizeAnswerType(child, childUi);\n const types = Array.isArray(allowed) ? allowed : allowed?.[key];\n if (!answer || !types?.includes(answer.type)) return null;\n extras.push(...answer.extras.map((e) => `${key}.${e}`));\n }\n return extras;\n}\n\n// A container's children by key: its properties -- for a choice with text, its\n// choice and its text wherever the variant keeps it.\nfunction containerChildren(\n prop: JsonSchemaProperty,\n type: AnswerType,\n): Record<string, JsonSchemaProperty> {\n if (type !== \"choiceWithText\") return prop.properties ?? {};\n const children = choiceWithTextChildren(prop);\n return children ? { choice: children.choice, text: children.text } : {};\n}\n\n/** The hints a property carries on itself (embedded x-ui-* keys), as a UISchema entry. */\nexport function embeddedHints(prop: JsonSchemaProperty): UISchema {\n const hints: UISchema = {};\n for (const [key, value] of Object.entries(prop)) {\n if (\n key.startsWith(\"x-ui-\") &&\n key !== \"x-ui-layout\" &&\n key !== \"x-ui-order\"\n ) {\n (hints as Record<string, unknown>)[key] = value;\n }\n }\n return hints;\n}\n\n/** A new answer's schema and hints: what writing an answer type sets, as one unit. */\nexport interface AnswerFragment {\n prop: JsonSchemaProperty;\n ui: UISchema;\n}\n\n/** The options a new choice starts with, until the author names them. */\nconst NEW_OPTIONS = [\"option_1\", \"option_2\"];\n\n// The fragment of each answer type, given its options (used by the choices).\nconst FRAGMENTS: Record<\n BuiltinAnswerType,\n (options: string[]) => AnswerFragment\n> = {\n yesNo: () => ({ prop: { type: \"boolean\" }, ui: {} }),\n shortText: () => ({ prop: { type: \"string\" }, ui: {} }),\n longText: () => ({\n prop: { type: \"string\" },\n ui: { \"x-ui-widget\": \"textarea\" },\n }),\n integer: () => ({ prop: { type: \"integer\" }, ui: {} }),\n decimal: () => ({ prop: { type: \"number\" }, ui: {} }),\n date: () => ({ prop: { type: \"string\", format: \"date\" }, ui: {} }),\n time: () => ({ prop: { type: \"string\", format: \"time\" }, ui: {} }),\n dateTime: () => ({ prop: { type: \"string\", format: \"date-time\" }, ui: {} }),\n singleChoice: (options) => ({\n prop: { type: \"string\", enum: [...options] },\n ui: {},\n }),\n multipleChoice: (options) => ({\n prop: {\n type: \"array\",\n items: { type: \"string\", enum: [...options] },\n uniqueItems: true,\n },\n ui: {},\n }),\n listOfText: () => ({\n prop: { type: \"array\", items: { type: \"string\" } },\n ui: {},\n }),\n choiceWithText: (options) => ({\n prop: {\n type: \"object\",\n properties: {\n choice: { type: \"string\", enum: [...options] },\n text: { type: \"string\" },\n },\n },\n ui: { \"x-ui-widget\": CHOICE_WITH_TEXT_WIDGET },\n }),\n parts: () => ({\n prop: {\n type: \"object\",\n properties: { part_1: { type: \"string\" }, part_2: { type: \"string\" } },\n \"x-ui-layout\": { rows: [{ fields: [\"part_1\", \"part_2\"] }] },\n },\n ui: {},\n }),\n};\n\n/**\n * The schema and hints of an answer type -- the reverse of recognizeAnswerType:\n * `recognizeAnswerType(fragment.prop, fragment.ui)` is the type, with no extras.\n */\nexport function answerTypeFragment(\n type: AnswerType,\n options: string[] = NEW_OPTIONS,\n): AnswerFragment {\n // A value type is its $ref, narrowed by nothing until its settings say so.\n if (!isBuiltinAnswerType(type)) return { prop: { $ref: type }, ui: {} };\n return FRAGMENTS[type](options);\n}\n","/**\n * Limits -- what an answer may be: a text's length and pattern, a number's\n * range, a date's or a time's (`formatMinimum` / `formatMaximum`), how many a\n * list holds. Plain JSON Schema keywords on the question,\n * which the form validates; each answer type takes its own. Pure, no React.\n */\n\nimport type { JsonSchemaProperty } from \"@petrarca/sonnet-core/schema\";\nimport type { AnswerType } from \"./answerTypes\";\n\nexport type LimitKeyword =\n | \"minLength\"\n | \"maxLength\"\n | \"pattern\"\n | \"minimum\"\n | \"maximum\"\n | \"minItems\"\n | \"maxItems\"\n | \"formatMinimum\"\n | \"formatMaximum\";\n\n/** A question's limits, by keyword: counts and bounds are numbers, a pattern its text. */\nexport interface Limits {\n minLength?: number;\n maxLength?: number;\n pattern?: string;\n minimum?: number;\n maximum?: number;\n minItems?: number;\n maxItems?: number;\n /** The earliest date, time or datetime, as the answer is written. */\n formatMinimum?: string;\n formatMaximum?: string;\n}\n\nconst TEXT_LIMITS: LimitKeyword[] = [\"minLength\", \"maxLength\", \"pattern\"];\nconst NUMBER_LIMITS: LimitKeyword[] = [\"minimum\", \"maximum\"];\nconst COUNT_LIMITS: LimitKeyword[] = [\"minItems\", \"maxItems\"];\nconst TIME_LIMITS: LimitKeyword[] = [\"formatMinimum\", \"formatMaximum\"];\n\n/** The limits each answer type takes; one not listed takes none. */\nexport const ANSWER_TYPE_LIMITS: Partial<Record<AnswerType, LimitKeyword[]>> = {\n shortText: TEXT_LIMITS,\n longText: TEXT_LIMITS,\n integer: NUMBER_LIMITS,\n decimal: NUMBER_LIMITS,\n multipleChoice: COUNT_LIMITS,\n listOfText: COUNT_LIMITS,\n date: TIME_LIMITS,\n time: TIME_LIMITS,\n dateTime: TIME_LIMITS,\n};\n\n/** What each limit is called where an author sees it. */\nexport const LIMIT_LABELS: Record<LimitKeyword, string> = {\n minLength: \"Minimum length\",\n maxLength: \"Maximum length\",\n pattern: \"Pattern\",\n minimum: \"Minimum\",\n maximum: \"Maximum\",\n minItems: \"At least\",\n maxItems: \"At most\",\n formatMinimum: \"Earliest\",\n formatMaximum: \"Latest\",\n};\n\n/** The limits an answer type takes. */\nexport function limitsFor(type: AnswerType): LimitKeyword[] {\n return ANSWER_TYPE_LIMITS[type] ?? [];\n}\n\n/** The limits a question has, of those its answer type takes. */\nexport function limitsOf(prop: JsonSchemaProperty, type: AnswerType): Limits {\n const values = prop as Record<string, unknown>;\n return Object.fromEntries(\n limitsFor(type)\n .filter((k) => values[k] !== undefined)\n .map((k) => [k, values[k]]),\n ) as Limits;\n}\n","/**\n * Value types as answer types -- a value type contributed to the questionnaire\n * designer: a question whose `$ref` is the type's id is that answer type, and\n * its settings are fields the panel shows, read from and written to the\n * question through the contribution. Sonnet contributes the core types the\n * same way an application contributes its own. Pure, no React. See\n * docs/design/value-types.md (workspace).\n */\n\nimport {\n bindingOf,\n CODEABLE_CONCEPT_TYPE,\n CODING_TYPE,\n QUANTITY_TYPE,\n unitRangesKeywords,\n unitRangesOf,\n valueRefKeywords,\n valueRefOf,\n type AdditionalBinding,\n type Binding,\n type Coding,\n type JsonSchemaProperty,\n type UISchema,\n type ValueType,\n} from \"@petrarca/sonnet-core/schema\";\nimport { OPTIONS_LIST_WIDGET } from \"./optionsListName\";\n\n/** A value type's settings: the panel's fields, read from and written to the question. */\nexport interface ValueTypeSettings {\n /** The fields, by name, as JSON Schema properties of the panel's form. */\n fields: Record<string, JsonSchemaProperty>;\n /** The settings' values, read from the question's property and hints. */\n read(prop: JsonSchemaProperty, ui: UISchema): Record<string, unknown>;\n /** What the values write: keywords beside the `$ref`, and `x-ui-options` keys -- undefined removes one. */\n write(values: Record<string, unknown>): {\n prop: Partial<JsonSchemaProperty>;\n options: Record<string, unknown>;\n };\n}\n\n/** A value type contributed as an answer type of the questionnaire designer. */\nexport interface ValueTypeAnswer {\n type: ValueType;\n /** The keywords it narrows beside its `$ref` (the quantity's `properties`). */\n keywords?: string[];\n /** The `x-ui-options` keys its settings use (the quantity's `units`). */\n options?: string[];\n /** Whether a property of the type is one the designer understands; default: any. */\n accepts?(prop: JsonSchemaProperty): boolean;\n settings?: ValueTypeSettings;\n}\n\ninterface Unit {\n value: string;\n label: string;\n min?: number;\n max?: number;\n}\n\n// A quantity's units: the codes it narrows to, labelled by x-ui-options.units,\n// each with its range.\nfunction readUnits(prop: JsonSchemaProperty, ui: UISchema): Unit[] {\n const labels = new Map(\n ((ui[\"x-ui-options\"] as { units?: Unit[] } | undefined)?.units ?? []).map(\n (u) => [u.value, u.label],\n ),\n );\n const ranges = unitRangesOf(prop) ?? {};\n return (prop.properties?.unit?.enum ?? []).map((v) => ({\n value: String(v),\n label: labels.get(String(v)) ?? String(v),\n ...withoutNone(ranges[String(v)] ?? {}),\n }));\n}\n\n// A range's bounds, those it sets.\nfunction withoutNone(range: { min?: number; max?: number }) {\n return Object.fromEntries(\n Object.entries(range).filter(([, v]) => v !== undefined),\n );\n}\n\n// What units write: the codes beside the $ref, each one's range, their labels.\nfunction writeUnits(units: Unit[]) {\n const ranges = Object.fromEntries(\n units.map((u) => [u.value, { min: u.min, max: u.max }]),\n );\n return {\n prop: {\n properties: units.length\n ? { unit: { enum: units.map((u) => u.value) } }\n : undefined,\n ...unitRangesKeywords(ranges),\n },\n options: {\n units: units.length\n ? units.map((u) => ({ value: u.value, label: u.label || u.value }))\n : undefined,\n },\n };\n}\n\n/** The quantity as an answer type: narrowed at most to its units, each in its range. */\nexport const QUANTITY_ANSWER: ValueTypeAnswer = {\n type: QUANTITY_TYPE,\n keywords: [\"properties\", \"allOf\"],\n options: [\"units\"],\n accepts(prop) {\n const { unit, ...others } = prop.properties ?? {};\n const narrowsUnits =\n !unit || (Object.keys(unit).length === 1 && Array.isArray(unit.enum));\n const units = (unit?.enum ?? []).map(String);\n const ranges = unitRangesOf(prop);\n // A range only of a unit offered: none for any unit, typed.\n const rangesOfUnits =\n !!ranges && Object.keys(ranges).every((u) => units.includes(u));\n return Object.keys(others).length === 0 && narrowsUnits && rangesOfUnits;\n },\n settings: {\n fields: {\n units: {\n type: \"array\",\n title: \"Units\",\n description:\n \"The units offered, by their UCUM code (kg, cm, mm[Hg]) and label, and the range of each. None: any unit, typed.\",\n \"x-ui-widget\": OPTIONS_LIST_WIDGET,\n \"x-ui-options\": { itemLabel: \"unit\" },\n items: {\n type: \"object\",\n properties: {\n value: { type: \"string\", title: \"Code\" },\n label: { type: \"string\", title: \"Label\" },\n min: { type: \"number\", title: \"Min\" },\n max: { type: \"number\", title: \"Max\" },\n },\n },\n },\n },\n read: (prop, ui) => ({ units: readUnits(prop, ui) }),\n write: (values) =>\n writeUnits(\n ((values.units as Unit[] | undefined) ?? []).filter((u) => u.value),\n ),\n },\n};\n\ntype ListKind = \"valueSet\" | \"system\";\ntype Mode = \"auto\" | \"list\" | \"search\";\n\n// Which list a binding names, and how it is known.\nfunction listOf(binding: Binding | undefined): {\n list: string;\n listKind: ListKind;\n} {\n if (binding?.system && !binding.valueSet)\n return { list: binding.system, listKind: \"system\" };\n return { list: binding?.valueSet ?? \"\", listKind: \"valueSet\" };\n}\n\n// A coded value's settings, as the panel shows them: the list, its version, the\n// strength, one answer or several, how it is shown.\nfunction readCoding(prop: JsonSchemaProperty, ui: UISchema) {\n const binding = bindingOf(prop);\n const mode = (ui[\"x-ui-options\"] as { mode?: Mode } | undefined)?.mode;\n return {\n ...listOf(binding),\n version: binding?.version ?? \"\",\n strength: binding?.strength ?? \"required\",\n several: valueRefOf(prop)?.multiple ?? false,\n mode: mode ?? \"auto\",\n };\n}\n\n/** The binding a coded value's settings write; none without a list. */\nexport function codingBindingOf(\n values: Record<string, unknown>,\n): Binding | undefined {\n const list = String(values.list ?? \"\").trim();\n if (!list) return undefined;\n const version = String(values.version ?? \"\").trim();\n return {\n [values.listKind === \"system\" ? \"system\" : \"valueSet\"]: list,\n ...(version && { version }),\n strength: values.strength === \"extensible\" ? \"extensible\" : \"required\",\n };\n}\n\n/** The coded value as an answer type: a code from the list its binding names. */\nexport const CODING_ANSWER: ValueTypeAnswer = {\n type: CODING_TYPE,\n keywords: [\"x-binding\"],\n options: [\"mode\"],\n // Narrowed only by its binding, and that one list.\n accepts(prop) {\n const binding = prop[\"x-binding\"];\n return !prop.properties && !(binding?.valueSet && binding?.system);\n },\n settings: {\n fields: {\n list: {\n type: \"string\",\n title: \"List\",\n description:\n \"The codes offered: a list the terminology service knows, by its identifier.\",\n },\n listKind: {\n type: \"string\",\n title: \"The list is a\",\n enum: [\"valueSet\", \"system\"],\n \"x-ui-widget\": \"radio\",\n \"x-ui-options\": {\n enumNames: { valueSet: \"Value set\", system: \"Code system\" },\n orientation: \"horizontal\",\n },\n },\n version: {\n type: \"string\",\n title: \"Version\",\n description: \"None: the list's current version.\",\n },\n strength: {\n type: \"string\",\n title: \"Answers\",\n enum: [\"required\", \"extensible\"],\n \"x-ui-widget\": \"radio\",\n \"x-ui-options\": {\n enumNames: {\n required: \"Only the list's codes\",\n extensible: \"The list's codes, or another answer\",\n },\n },\n },\n several: { type: \"boolean\", title: \"Several answers\" },\n mode: {\n type: \"string\",\n title: \"Shown as\",\n enum: [\"auto\", \"list\", \"search\"],\n \"x-ui-widget\": \"radio\",\n \"x-ui-options\": {\n enumNames: {\n auto: \"As the list's size decides\",\n list: \"The whole list\",\n search: \"A search\",\n },\n },\n },\n },\n read: readCoding,\n // An open list takes a text of one's own too: a coding, or a text; several, an array of them.\n write(values) {\n const binding = codingBindingOf(values);\n return {\n prop: {\n ...valueRefKeywords(\n CODING_TYPE.id,\n binding?.strength === \"extensible\",\n values.several === true,\n ),\n \"x-binding\": binding,\n },\n options: {\n mode:\n values.mode === \"list\" || values.mode === \"search\"\n ? values.mode\n : undefined,\n },\n };\n },\n },\n};\n\n/** A further list as the panel edits it: its identifier, its title, whether it is required. */\ninterface ListRow {\n value: string;\n label: string;\n required?: boolean;\n /** Kept as read: a value set, else a code system. */\n kind?: ListKind;\n /** Kept as read: the purpose of the coding it gives. */\n purpose?: Coding;\n}\n\n// A binding's further lists as the panel's rows.\nfunction readLists(binding: Binding | undefined): ListRow[] {\n return (binding?.additional ?? []).map((a) => ({\n value: a.valueSet ?? a.system ?? \"\",\n label: a.title ?? \"\",\n ...(a.required ? { required: true } : {}),\n ...(a.valueSet ? { kind: \"valueSet\" as const } : {}),\n ...(a.purpose ? { purpose: a.purpose } : {}),\n }));\n}\n\n// The panel's rows as further lists -- a new one a code system; those without an identifier dropped.\nfunction writeLists(rows: ListRow[] | undefined): AdditionalBinding[] {\n return (rows ?? [])\n .filter((r) => r.value.trim())\n .map((r) => ({\n [r.kind === \"valueSet\" ? \"valueSet\" : \"system\"]: r.value.trim(),\n ...(r.label ? { title: r.label } : {}),\n ...(r.required ? { required: true } : {}),\n ...(r.purpose ? { purpose: r.purpose } : {}),\n }));\n}\n\n// The coded value's fields for the first list -- the same list, the same settings.\nconst { list, listKind, version, strength, mode } =\n CODING_ANSWER.settings!.fields;\n\n/** The codeable concept as an answer type: a concept coded in its first list and in further ones, or its text. */\nexport const CODEABLE_CONCEPT_ANSWER: ValueTypeAnswer = {\n type: CODEABLE_CONCEPT_TYPE,\n keywords: [\"x-binding\"],\n options: [\"mode\", \"text\"],\n // Narrowed only by its binding, and that one first list.\n accepts(prop) {\n const binding = prop[\"x-binding\"];\n return !prop.properties && !(binding?.valueSet && binding?.system);\n },\n settings: {\n fields: {\n list,\n listKind,\n version,\n strength,\n additional: {\n type: \"array\",\n title: \"Further lists\",\n description:\n \"Where the concept's other codes come from -- an identifier the terminology service knows. Required: a value with codes needs one of it.\",\n \"x-ui-widget\": OPTIONS_LIST_WIDGET,\n \"x-ui-options\": { itemLabel: \"list\", wide: true },\n items: {\n type: \"object\",\n properties: {\n value: { type: \"string\", title: \"Identifier\" },\n label: { type: \"string\", title: \"Title\" },\n required: { type: \"boolean\", title: \"Required\" },\n },\n },\n },\n mode,\n // Not `text`: the panel's own field of that name is the question's text.\n offerText: {\n type: \"boolean\",\n title: \"Offer a text\",\n description:\n \"An answer in words beside the codes -- or when no code fits.\",\n },\n },\n read(prop, ui) {\n const { several: _several, ...first } = readCoding(prop, ui);\n const options = ui[\"x-ui-options\"] as { text?: boolean } | undefined;\n return {\n ...first,\n additional: readLists(bindingOf(prop)),\n offerText: options?.text === true,\n };\n },\n write(values) {\n const binding = codingBindingOf(values);\n const additional = writeLists(values.additional as ListRow[] | undefined);\n return {\n prop: {\n \"x-binding\": binding && {\n ...binding,\n ...(additional.length ? { additional } : {}),\n },\n },\n options: {\n mode:\n values.mode === \"list\" || values.mode === \"search\"\n ? values.mode\n : undefined,\n text: values.offerText === true ? true : undefined,\n },\n };\n },\n },\n};\n\n/** The value types sonnet contributes: the core types. */\nexport const DEFAULT_VALUE_TYPES: readonly ValueTypeAnswer[] = [\n QUANTITY_ANSWER,\n CODING_ANSWER,\n CODEABLE_CONCEPT_ANSWER,\n];\n\n/** The value type a property is, among those contributed -- by its `$ref`, or that or a text; undefined when none. */\nexport function valueTypeOf(\n prop: JsonSchemaProperty,\n types: readonly ValueTypeAnswer[],\n): ValueTypeAnswer | undefined {\n const ref = valueRefOf(prop)?.ref;\n const found = ref ? types.find((t) => t.type.id === ref) : undefined;\n return found && (found.accepts?.(prop) ?? true) ? found : undefined;\n}\n\n/** The contribution of an answer type, when it is a value type. */\nexport function valueTypeAnswer(\n answerType: string,\n types: readonly ValueTypeAnswer[],\n): ValueTypeAnswer | undefined {\n return types.find((t) => t.type.id === answerType);\n}\n","/** The names the question panel's own widgets are registered by. */\nexport const OPTIONS_LIST_WIDGET = \"options-list\";\nexport const SHOW_IF_WIDGET = \"show-if\";\n","/**\n * classifyQuestionnaire -- a schema (with its uiSchema) read as a questionnaire:\n * its sections, texts and questions, and in their place whatever the\n * questionnaire designer does not understand. Pure, no React.\n *\n * Every part is sorted into one of three classes: understood (an item), partly\n * understood (an item with `extras` -- the keywords it keeps untouched) and not\n * understood (a `locked` item, with the reason). Nothing is dropped: the\n * classification only reads. See docs/design/questionnaires.md, \"The boundary\n * with the schema designer\".\n */\n\nimport { isOneOf } from \"@petrarca/sonnet-core/schema\";\nimport type {\n JsonSchemaProperty,\n UISchema,\n} from \"@petrarca/sonnet-core/schema\";\nimport { getUiEntryAtPath, type DesignerModel } from \"../model/mutate\";\nimport {\n condition as condSeg,\n prop as propSeg,\n slot as slotSeg,\n type PropertyPath,\n} from \"../model/paths\";\nimport { orderedKeys } from \"../model/view\";\nimport {\n embeddedHints,\n recognizeAnswerType,\n type AnswerType,\n} from \"./answerTypes\";\nimport { readConditional, type ShowIf } from \"./showIf\";\nimport { choiceTextWhen, isContainerType } from \"./answerTypes\";\nimport { ABSENT_KEY, readReasons, unlessReasonKey } from \"./reasons\";\nimport { limitsOf, type Limits } from \"./limits\";\nimport {\n DEFAULT_VALUE_TYPES,\n valueTypeAnswer,\n type ValueTypeAnswer,\n} from \"./valueTypes\";\n\ninterface ItemBase {\n key: string;\n path: PropertyPath;\n /** When the item is shown; none: always. */\n showIf?: ShowIf;\n}\n\n/** A section: a heading, an introduction, its items; repeating when it is a list of them. */\nexport interface SectionItem extends ItemBase {\n kind: \"section\";\n title: string;\n description?: string;\n repeats: boolean;\n required: boolean;\n /** A repeating section's count: how many entries at least, at most. */\n limits?: { minItems?: number; maxItems?: number };\n items: QuestionnaireItem[];\n extras: string[];\n}\n\n/** Static text between questions. */\nexport interface TextItem extends ItemBase {\n kind: \"text\";\n title?: string;\n text?: string;\n extras: string[];\n}\n\n/** One option of a choice: the value stored, the label shown. */\nexport interface ChoiceOption {\n value: string;\n label: string;\n}\n\n/** A question: its text, help, example, and its answer type. */\nexport interface QuestionItem extends ItemBase {\n kind: \"question\";\n title: string;\n help?: string;\n placeholder?: string;\n required: boolean;\n readOnly: boolean;\n answerType: AnswerType;\n /** How the question is shown, when it names a widget its answer type knows (`radio`, `select`, ...). */\n presentation?: string;\n /** A choice's options, in order (single, multiple, the choice of a choice with text). */\n options?: ChoiceOption[];\n /** The sub-answers of a container answer type (parts; a choice with text's choice and text). */\n parts?: QuestionItem[];\n /** A choice with text: the option that asks for the text (\"other\"); none: the text is a note. */\n textWhen?: string;\n /** What the answer may be: its length, pattern, range, count -- as its answer type takes them. */\n limits?: Limits;\n /** A value type's settings, read through its contribution (a quantity's units). */\n settings?: Record<string, unknown>;\n /** The answer given until the person answers (`default`); none for a container. */\n defaultAnswer?: unknown;\n extras: string[];\n}\n\n/** A part the questionnaire designer does not understand: kept, shown locked, edited in the schema designer. */\nexport interface LockedItem extends ItemBase {\n kind: \"locked\";\n title: string;\n reason: string;\n}\n\nexport type QuestionnaireItem =\n | SectionItem\n | TextItem\n | QuestionItem\n | LockedItem;\n\n/** A schema read as a questionnaire. */\nexport interface QuestionnaireView {\n title?: string;\n description?: string;\n items: QuestionnaireItem[];\n /** The root's keywords and hints the questionnaire designer keeps untouched (a layout, definitions). */\n extras: string[];\n /** The reasons a question may be left unanswered for; none declared: every question is answered. */\n reasons?: ChoiceOption[];\n}\n\n// Keywords a section understands; anything else is kept as an extra.\nconst SECTION_KEYWORDS = [\n \"type\",\n \"title\",\n \"description\",\n \"properties\",\n \"required\",\n \"x-ui-order\",\n];\nconst REPEATING_KEYWORDS = [\n \"type\",\n \"title\",\n \"description\",\n \"items\",\n \"minItems\",\n \"maxItems\",\n];\nconst TEXT_KEYWORDS = [\"type\", \"title\", \"description\"];\n// Keywords the root understands, besides its sections' own.\nconst ROOT_KEYWORDS = [\n \"$schema\",\n \"$id\",\n \"type\",\n \"title\",\n \"description\",\n \"properties\",\n \"required\",\n \"x-ui-order\",\n];\n// Root uiSchema keys that are not property entries.\nconst ROOT_UI_KEYS = [\"x-ui-layout\", \"x-ui-globalOptions\"];\n\n// What a classification reads: the model, and the value types it knows as answer types.\ninterface Reading {\n model: DesignerModel;\n types: readonly ValueTypeAnswer[];\n}\n\n// The hints in effect for a property: its uiSchema entry over its embedded x-ui-* keys.\nfunction effectiveHints(\n model: DesignerModel,\n prop: JsonSchemaProperty,\n path: PropertyPath,\n): UISchema {\n return { ...embeddedHints(prop), ...getUiEntryAtPath(model.uiSchema, path) };\n}\n\nfunction hintText(\n ui: UISchema,\n key: \"x-ui-title\" | \"x-ui-description\" | \"x-ui-placeholder\",\n): string | undefined {\n const value = ui[key];\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction extrasOf(prop: JsonSchemaProperty, known: string[]): string[] {\n return Object.keys(prop).filter((k) => !known.includes(k));\n}\n\n// The answer types whose children are answers of their own.\n\n/** A choice's options: its enum values with their labels (x-ui-options.enumNames); none for another type. */\nexport function optionsOf(\n prop: JsonSchemaProperty,\n ui: UISchema,\n type: AnswerType,\n): ChoiceOption[] | undefined {\n const source = choiceSource(prop, ui, type);\n if (!source) return undefined;\n const names =\n (\n source.ui[\"x-ui-options\"] as\n | { enumNames?: Record<string, string> }\n | undefined\n )?.enumNames ?? {};\n return (source.values as unknown[]).map((v) => ({\n value: String(v),\n label: names[String(v)] ?? String(v),\n }));\n}\n\n// Where a choice's values and their hints are: on the property, on its items, or on a choice with text's `choice`.\nfunction choiceSource(\n prop: JsonSchemaProperty,\n ui: UISchema,\n type: AnswerType,\n): { values: unknown[]; ui: UISchema } | undefined {\n if (type === \"singleChoice\") return { values: prop.enum ?? [], ui };\n if (type === \"multipleChoice\") return { values: prop.items?.enum ?? [], ui };\n return type === \"choiceWithText\" ? innerChoiceSource(prop, ui) : undefined;\n}\n\n// A choice with text's options: its `choice` child's values, with that child's hints.\nfunction innerChoiceSource(\n prop: JsonSchemaProperty,\n ui: UISchema,\n): { values: unknown[]; ui: UISchema } | undefined {\n const choice = prop.properties?.choice;\n if (!choice) return undefined;\n const fields =\n (ui[\"x-ui-fields\"] as Record<string, UISchema> | undefined) ?? {};\n return {\n values: choice.enum ?? [],\n ui: { ...embeddedHints(choice), ...fields.choice },\n };\n}\n\n// Why a property is not understood, in the author's words.\nfunction lockReason(prop: JsonSchemaProperty): string {\n if (prop.$ref) return \"a reference to a shared definition ($ref)\";\n if (isOneOf(prop)) return \"alternative structures (oneOf)\";\n if (prop.if) return \"a condition (if / then)\";\n if (Array.isArray(prop.anyOf)) return \"a union of types (anyOf)\";\n if (Array.isArray(prop.allOf)) return \"combined schemas (allOf)\";\n return `a ${prop.type ?? \"property\"} of no answer type's shape`;\n}\n\n// A member of a container's allOf / anyOf the questionnaire designer does not understand.\nfunction lockedMember(\n member: JsonSchemaProperty,\n combinator: \"allOf\" | \"anyOf\",\n index: number,\n path: PropertyPath,\n): LockedItem {\n return {\n kind: \"locked\",\n key: `${combinator}[${index}]`,\n path: [...path, condSeg(index, combinator)],\n title: member.if ? \"Condition\" : \"Combined schema\",\n reason: member.if\n ? \"a condition (if / then)\"\n : `combined schemas (${combinator})`,\n };\n}\n\n/** What holds a section's items: the root schema, an object, or a repeating section's items. */\ntype Container = Pick<\n JsonSchemaProperty,\n \"properties\" | \"required\" | \"x-ui-order\" | \"allOf\" | \"anyOf\"\n>;\n\n// The items of a container, in its order: its properties, and the items its\n// understood conditionals show (each with its show-if); then, locked, the\n// members it does not understand.\nfunction containerItems(\n r: Reading,\n container: Container,\n path: PropertyPath,\n): QuestionnaireItem[] {\n const properties = questionProperties(container);\n // A condition may test any item of the container -- a conditional one too: answers chain.\n const fields = containerFields(container);\n const keys = new Set(Object.keys(fields));\n const typeOf = (field: string) => fields[field];\n const requiredUnless = new Set(\n (container.allOf ?? []).map(unlessReasonKey).filter((k) => k !== undefined),\n );\n const isRequired = (key: string) =>\n (container.required?.includes(key) ?? false) || requiredUnless.has(key);\n const byKey = new Map<string, QuestionnaireItem>();\n for (const [key, prop] of Object.entries(properties)) {\n byKey.set(\n key,\n classifyItem(r, key, prop, [...path, propSeg(key)], isRequired(key)),\n );\n }\n const locked: LockedItem[] = [];\n (container.allOf ?? []).forEach((member, index) => {\n // \"Required unless a reason\" is read as the question's required flag above.\n if (unlessReasonKey(member) !== undefined) return;\n const read = readConditional(member, keys, typeOf);\n // A shown item named as a property already is not understood: neither may hide the other.\n if (!read || Object.keys(read.properties).some((k) => byKey.has(k))) {\n locked.push(lockedMember(member, \"allOf\", index, path));\n return;\n }\n for (const [key, prop] of Object.entries(read.properties)) {\n const itemPath = [\n ...path,\n condSeg(index, \"allOf\"),\n slotSeg(\"then\"),\n propSeg(key),\n ];\n byKey.set(key, {\n ...classifyItem(r, key, prop, itemPath, read.required.includes(key)),\n showIf: read.showIf,\n });\n }\n });\n (container.anyOf ?? []).forEach((member, index) =>\n locked.push(lockedMember(member, \"anyOf\", index, path)),\n );\n const order = orderedKeys(\n Object.fromEntries([...byKey.keys()].map((k) => [k, {}])),\n container[\"x-ui-order\"],\n );\n return [...order.map((k) => byKey.get(k)!), ...locked];\n}\n\n// A container's properties that are items: all of them but its reasons for no answer.\nfunction questionProperties(\n container: Container,\n): Record<string, JsonSchemaProperty> {\n const { [ABSENT_KEY]: absent, ...rest } = container.properties ?? {};\n return absent && !readReasons(absent)\n ? { ...rest, [ABSENT_KEY]: absent }\n : rest;\n}\n\n/** Every item of a container by key: its properties, and those its conditionals show -- what a show-if may test. */\nexport function containerFields(\n container: Container,\n): Record<string, JsonSchemaProperty> {\n return Object.assign(\n {},\n ...(container.allOf ?? []).map((m) => m.then?.properties ?? {}),\n questionProperties(container),\n );\n}\n\n/** The keys of a container's items in the order the form shows them -- conditional ones included. */\nexport function containerOrder(container: Container): string[] {\n const conditional = (container.allOf ?? []).flatMap((m) =>\n Object.keys(m.then?.properties ?? {}),\n );\n const keys = [...Object.keys(questionProperties(container)), ...conditional];\n return orderedKeys(\n Object.fromEntries(keys.map((k) => [k, {}])),\n container[\"x-ui-order\"],\n );\n}\n\n// The sub-answers of a container answer type: its properties -- and, for a\n// choice with text asking for its text, the text inside its conditional.\nfunction partsOf(\n r: Reading,\n prop: JsonSchemaProperty,\n path: PropertyPath,\n textWhen: string | undefined,\n): QuestionItem[] {\n const own = classifyItems(\n r,\n prop.properties,\n prop[\"x-ui-order\"],\n prop.required,\n path,\n ) as QuestionItem[];\n const text =\n textWhen === undefined\n ? undefined\n : prop.allOf?.[0]?.then?.properties?.text;\n if (!text) return own;\n const textPath = [\n ...path,\n condSeg(0, \"allOf\"),\n slotSeg(\"then\"),\n propSeg(\"text\"),\n ];\n return [\n ...own,\n classifyItem(r, \"text\", text, textPath, true) as QuestionItem,\n ];\n}\n\n// The items of a container part (parts, a choice with text): its properties only.\nfunction classifyItems(\n r: Reading,\n properties: Record<string, JsonSchemaProperty> | undefined,\n order: string[] | undefined,\n required: string[] | undefined,\n path: PropertyPath,\n): QuestionnaireItem[] {\n if (!properties) return [];\n return orderedKeys(properties, order).map((key) =>\n classifyItem(\n r,\n key,\n properties[key],\n [...path, propSeg(key)],\n required?.includes(key) ?? false,\n ),\n );\n}\n\nfunction classifyItem(\n r: Reading,\n key: string,\n prop: JsonSchemaProperty,\n path: PropertyPath,\n required: boolean,\n): QuestionnaireItem {\n const ui = effectiveHints(r.model, prop, path);\n const title = hintText(ui, \"x-ui-title\") ?? prop.title ?? key;\n\n if (prop.type === \"null\") {\n return {\n kind: \"text\",\n key,\n path,\n title: prop.title,\n text: prop.description,\n extras: extrasOf(prop, TEXT_KEYWORDS),\n };\n }\n const answer = recognizeAnswerType(prop, ui, r.types);\n if (answer)\n return questionItem(r, { key, prop, path, required, title, ui }, answer);\n const section = classifySection(r, key, prop, path, required, title);\n return (\n section ?? { kind: \"locked\", key, path, title, reason: lockReason(prop) }\n );\n}\n\n// The widget a question names, when its answer type knows it -- another is an extra.\nfunction presentationOf(ui: UISchema, extras: string[]): string | undefined {\n const widget = ui[\"x-ui-widget\"];\n return typeof widget === \"string\" && !extras.includes(\"x-ui-widget\")\n ? widget\n : undefined;\n}\n\n// A question: its texts and flags, its answer type with its options and parts.\nfunction questionItem(\n r: Reading,\n at: {\n key: string;\n prop: JsonSchemaProperty;\n path: PropertyPath;\n required: boolean;\n title: string;\n ui: UISchema;\n },\n answer: { type: AnswerType; extras: string[] },\n): QuestionItem {\n const { key, prop, path, required, title, ui } = at;\n const options = optionsOf(prop, ui, answer.type);\n const textWhen =\n answer.type === \"choiceWithText\" ? choiceTextWhen(prop) : undefined;\n const limits = limitsOf(prop, answer.type);\n const settings = settingsOf(r, answer.type, prop, ui);\n const parts = isContainerType(answer.type)\n ? partsOf(r, prop, path, textWhen)\n : undefined;\n const presentation = presentationOf(ui, answer.extras);\n return {\n kind: \"question\",\n key,\n path,\n title,\n help: hintText(ui, \"x-ui-description\") ?? prop.description,\n placeholder: hintText(ui, \"x-ui-placeholder\"),\n required,\n readOnly: prop.readOnly === true,\n answerType: answer.type,\n ...(presentation ? { presentation } : {}),\n ...(options ? { options } : {}),\n ...(parts ? { parts } : {}),\n ...(textWhen !== undefined ? { textWhen } : {}),\n ...(Object.keys(limits).length ? { limits } : {}),\n ...(settings ? { settings } : {}),\n ...defaultOf(prop, answer.type),\n extras: answer.extras,\n };\n}\n\n// A question's default answer; none for a container, which has no answer of its own.\nfunction defaultOf(\n prop: JsonSchemaProperty,\n type: AnswerType,\n): { defaultAnswer?: unknown } {\n return prop.default !== undefined && !isContainerType(type)\n ? { defaultAnswer: prop.default }\n : {};\n}\n\n// A value type's settings, read through its contribution; none for a built-in type.\nfunction settingsOf(\n r: Reading,\n type: AnswerType,\n prop: JsonSchemaProperty,\n ui: UISchema,\n): Record<string, unknown> | undefined {\n return valueTypeAnswer(type, r.types)?.settings?.read(prop, ui);\n}\n\n// A repeating section's count, as it says it.\nfunction countOf(prop: JsonSchemaProperty): SectionItem[\"limits\"] {\n return {\n ...(prop.minItems !== undefined ? { minItems: prop.minItems } : {}),\n ...(prop.maxItems !== undefined ? { maxItems: prop.maxItems } : {}),\n };\n}\n\n// A section -- an object of items -- or a repeating one, a list of such objects.\nfunction classifySection(\n r: Reading,\n key: string,\n prop: JsonSchemaProperty,\n path: PropertyPath,\n required: boolean,\n title: string,\n): SectionItem | null {\n if (prop.$ref || isOneOf(prop) || prop.if) return null;\n const repeats = prop.type === \"array\";\n const body = repeats ? prop.items : prop;\n if (!body || body.type !== \"object\" || !body.properties) return null;\n const extras = repeats\n ? [\n ...extrasOf(prop, REPEATING_KEYWORDS),\n ...extrasOf(body, SECTION_KEYWORDS).map((k) => `items.${k}`),\n ]\n : extrasOf(prop, SECTION_KEYWORDS);\n return {\n kind: \"section\",\n key,\n path,\n title,\n description: prop.description,\n repeats,\n required,\n ...(repeats ? { limits: countOf(prop) } : {}),\n items: containerItems(r, body, path),\n extras: extras.filter(\n (k) => ![\"allOf\", \"anyOf\", \"items.allOf\", \"items.anyOf\"].includes(k),\n ),\n };\n}\n\n// The reasons the questionnaire declares: those of its root's `absent`.\nfunction rootReasons(\n schema: DesignerModel[\"schema\"],\n): ChoiceOption[] | undefined {\n return readReasons(schema.properties?.[ABSENT_KEY]);\n}\n\n/** Every item of a questionnaire, at any depth: each section before what it holds. */\nexport function itemsOf(items: QuestionnaireItem[]): QuestionnaireItem[] {\n return items.flatMap((i) =>\n i.kind === \"section\" ? [i, ...itemsOf(i.items)] : [i],\n );\n}\n\n/** The schema read as a questionnaire: every part an item, nothing dropped. */\nexport function classifyQuestionnaire(\n model: DesignerModel,\n // The value types contributed as answer types; default: the core types.\n types: readonly ValueTypeAnswer[] = DEFAULT_VALUE_TYPES,\n): QuestionnaireView {\n const { schema, uiSchema } = model;\n const r: Reading = { model, types };\n const rootUi = uiSchema as Record<string, unknown>;\n return {\n title: schema.title,\n description: schema.description,\n items: containerItems(r, schema as Container, []),\n ...(rootReasons(schema) ? { reasons: rootReasons(schema) } : {}),\n extras: [\n ...Object.keys(schema).filter(\n (k) => !ROOT_KEYWORDS.includes(k) && k !== \"allOf\" && k !== \"anyOf\",\n ),\n ...ROOT_UI_KEYS.filter((k) => rootUi[k] !== undefined).map(\n (k) => `uiSchema.${k}`,\n ),\n ],\n };\n}\n","/**\n * Path navigation over a JsonSchema tree.\n *\n * A path is a list of typed segments from the root down to a property. Most\n * segments are property keys (`{kind:\"prop\"}`) -- object children nest through\n * `properties`, array-of-object children through `items.properties`, and the\n * navigator descends through `items` transparently so an array and its item\n * object share one editing surface.\n *\n * Logic constructs introduce non-property segments: `{kind:\"branch\"}` for a\n * `oneOf`/`allOf` element, and `{kind:\"slot\"}` for a fixed schema slot\n * (`then`/`else`/`items`). The discriminated union keeps the distinction\n * explicit and type-checked; a single codec (pathKey/parsePathKey) owns all\n * conversion to/from strings.\n */\n\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n} from \"@petrarca/sonnet-core/schema\";\nimport {\n isOneOf,\n getDiscriminator,\n getBranchLabel,\n} from \"@petrarca/sonnet-core/schema\";\n\n/** A fixed schema slot that holds a single sub-schema. */\nexport type PathSlot = \"then\" | \"else\" | \"items\";\n\n/**\n * The array a conditional (if/then/else) member lives in. `allOf` = every\n * condition must hold (AND); `anyOf` = any condition suffices (OR). Maps to\n * FHIR `enableBehavior` \"all\" / \"any\".\n */\nexport type ConditionCombinator = \"allOf\" | \"anyOf\";\n\n/** One step in a property path. */\nexport type PathSegment =\n | { kind: \"prop\"; key: string }\n | { kind: \"branch\"; index: number }\n | { kind: \"condition\"; combinator: ConditionCombinator; index: number }\n | { kind: \"slot\"; slot: PathSlot }\n | { kind: \"def\"; name: string };\n\nexport type PropertyPath = PathSegment[];\n\n/**\n * Whether a property key is reserved by the path codec. Keys matching\n * `/^#(branch|condition|def|slot):/` would corrupt the pathKey/parsePathKey\n * round-trip. The designer guards against these at rename/add time.\n */\nexport function isReservedKey(key: string): boolean {\n return /^#(branch|condition|def|slot):/.test(key);\n}\n\n/** Construct a property-key segment. */\nexport function prop(key: string): PathSegment {\n return { kind: \"prop\", key };\n}\n\n/** Construct a branch (oneOf element) segment. */\nexport function branch(index: number): PathSegment {\n return { kind: \"branch\", index };\n}\n\n/** Construct a condition (if/then/else member) segment for a combinator array. */\nexport function condition(\n index: number,\n combinator: ConditionCombinator = \"allOf\",\n): PathSegment {\n return { kind: \"condition\", combinator, index };\n}\n\n/** Construct a fixed-slot segment. */\nexport function slot(name: PathSlot): PathSegment {\n return { kind: \"slot\", slot: name };\n}\n\n/** Construct a definition ($defs entry) segment. Root-only in practice. */\nexport function def(name: string): PathSegment {\n return { kind: \"def\", name };\n}\n\n// ---- Codec: the single segment <-> string boundary ------------------------\n\n// Non-prop segments use a reserved \"#\" prefix that cannot be a JSON Schema\n// property key produced by the designer. Prop keys are percent-ish escaped so\n// the \".\" join is reversible even for keys containing separators.\nconst SEP = \"/\";\n\n// Escape backslash first, then the separator, so parse is unambiguous.\nfunction escapeToken(raw: string): string {\n return raw.replace(/\\\\/g, \"\\\\\\\\\").replace(/\\//g, \"\\\\/\");\n}\n\nfunction unescapeToken(raw: string): string {\n return raw.replace(/\\\\\\//g, \"/\").replace(/\\\\\\\\/g, \"\\\\\");\n}\n\nfunction encodeSegment(seg: PathSegment): string {\n switch (seg.kind) {\n case \"prop\":\n return escapeToken(seg.key);\n case \"branch\":\n return `#branch:${seg.index}`;\n case \"condition\":\n return `#condition:${seg.combinator}:${seg.index}`;\n case \"slot\":\n return `#slot:${seg.slot}`;\n case \"def\":\n return `#def:${escapeToken(seg.name)}`;\n }\n}\n\nconst VALID_SLOTS: readonly PathSlot[] = [\"then\", \"else\", \"items\"];\n\n// Parse a non-negative integer, defaulting to 0 for tampered/invalid tokens.\nfunction safeIndex(raw: string): number {\n const n = Number(raw);\n return Number.isInteger(n) && n >= 0 ? n : 0;\n}\n\n// Decode \"#condition:<combinator>:<index>\" (legacy \"#condition:<index>\" -> allOf).\nfunction decodeCondition(rest: string): PathSegment {\n const sep = rest.indexOf(\":\");\n const combinatorRaw = sep >= 0 ? rest.slice(0, sep) : \"allOf\";\n const combinator: ConditionCombinator =\n combinatorRaw === \"anyOf\" ? \"anyOf\" : \"allOf\";\n const index = safeIndex(sep >= 0 ? rest.slice(sep + 1) : rest);\n return { kind: \"condition\", combinator, index };\n}\n\nfunction decodeSegment(token: string): PathSegment {\n if (token.startsWith(\"#branch:\")) {\n return { kind: \"branch\", index: safeIndex(token.slice(\"#branch:\".length)) };\n }\n if (token.startsWith(\"#condition:\")) {\n return decodeCondition(token.slice(\"#condition:\".length));\n }\n if (token.startsWith(\"#slot:\")) {\n const s = token.slice(\"#slot:\".length) as PathSlot;\n return { kind: \"slot\", slot: VALID_SLOTS.includes(s) ? s : \"items\" };\n }\n if (token.startsWith(\"#def:\")) {\n return { kind: \"def\", name: unescapeToken(token.slice(\"#def:\".length)) };\n }\n return { kind: \"prop\", key: unescapeToken(token) };\n}\n\n// Split on unescaped separators.\nfunction splitTokens(key: string): string[] {\n const tokens: string[] = [];\n let current = \"\";\n for (let i = 0; i < key.length; i++) {\n const ch = key[i];\n if (ch === \"\\\\\" && i + 1 < key.length) {\n current += ch + key[i + 1];\n i++;\n } else if (ch === SEP) {\n tokens.push(current);\n current = \"\";\n } else {\n current += ch;\n }\n }\n tokens.push(current);\n return tokens;\n}\n\n/** Serialize a path to a stable string (React key, selection id, scope value). */\nexport function pathKey(path: PropertyPath): string {\n return path.map(encodeSegment).join(SEP);\n}\n\n/** Parse a string produced by {@link pathKey} back into a path. */\nexport function parsePathKey(key: string): PropertyPath {\n if (key === \"\") return [];\n return splitTokens(key).map(decodeSegment);\n}\n\n// ---- Comparison -----------------------------------------------------------\n\n// A stable string identity for a segment's payload; two segments are equal iff\n// their kind and identity string match. Keeps sameSegment's complexity flat.\nfunction segmentIdentity(seg: PathSegment): string {\n switch (seg.kind) {\n case \"prop\":\n return `prop:${seg.key}`;\n case \"branch\":\n return `branch:${seg.index}`;\n case \"condition\":\n return `condition:${seg.combinator}:${seg.index}`;\n case \"slot\":\n return `slot:${seg.slot}`;\n case \"def\":\n return `def:${seg.name}`;\n }\n}\n\n/** Whether two path segments refer to the same position. */\nexport function sameSegment(a: PathSegment, b: PathSegment): boolean {\n return segmentIdentity(a) === segmentIdentity(b);\n}\n\n/** Whether two paths refer to the same node (structural comparison). */\nexport function samePath(\n a: PropertyPath | null,\n b: PropertyPath | null,\n): boolean {\n if (a === null || b === null) return a === b;\n return a.length === b.length && a.every((seg, i) => sameSegment(seg, b[i]));\n}\n\n// ---- Child slots (the container abstraction) ------------------------------\n\n/** How a child slot is presented and mutated. */\nexport type SlotKind = \"property\" | \"branch\" | \"conditional\" | \"definition\";\n\n/** A single editable child of a property (or the root). */\nexport interface ChildSlot {\n /** Segment appended to the parent path to reach this child. */\n segment: PathSegment;\n /** Display label for the tree row. */\n label: string;\n /** The child schema. */\n property: JsonSchemaProperty;\n kind: SlotKind;\n removable: boolean;\n reorderable: boolean;\n}\n\n/**\n * The properties map that holds a property's named children, or undefined when\n * it has none. Object children live in `properties`; array-of-object children\n * live in `items.properties`. (Logic constructs use branch/slot children and\n * are surfaced via {@link childSlots}, not here.)\n */\nexport function childContainer(\n prop: JsonSchemaProperty,\n): Record<string, JsonSchemaProperty> | undefined {\n // A oneOf branch is an object-shaped schema that may omit `type`; treat\n // properties-bearing schemas with type \"object\" or no type (branches) as\n // containers. Exclude typed scalars that happen to carry a `properties` key\n // (valid in some JSON Schema dialects as an annotation) and oneOf unions\n // (whose children are branches, not properties).\n const typeIsObjectLike = prop.type === \"object\" || prop.type === undefined;\n if (typeIsObjectLike && prop.properties && !prop.oneOf)\n return prop.properties;\n if (prop.type === \"array\" && prop.items?.type === \"object\") {\n return prop.items.properties;\n }\n return undefined;\n}\n\n/** Whether an allOf/anyOf member is a conditional (carries an `if`). */\nfunction isConditionalMember(member: JsonSchemaProperty): boolean {\n return !!member.if;\n}\n\ninterface ConditionalMember {\n member: JsonSchemaProperty;\n combinator: ConditionCombinator;\n index: number;\n}\n\n// The conditional members in one combinator array, with their positional index.\nfunction membersOfCombinator(\n property: JsonSchemaProperty,\n combinator: ConditionCombinator,\n): ConditionalMember[] {\n const arr = property[combinator];\n if (!Array.isArray(arr)) return [];\n return arr\n .map((member, index) => ({ member, combinator, index }))\n .filter(({ member }) => isConditionalMember(member));\n}\n\n/** The conditional members of a property across both allOf (AND) and anyOf (OR). */\nfunction conditionalMembers(property: JsonSchemaProperty): ConditionalMember[] {\n return [\n ...membersOfCombinator(property, \"allOf\"),\n ...membersOfCombinator(property, \"anyOf\"),\n ];\n}\n\n// A short label for a conditional derived from its `if` (e.g. \"if smoker\").\n// The field is in `if.properties` for value operators, or `if.required` for the\n// bare `exists` operator (which has no per-property constraint).\nfunction conditionLabel(member: JsonSchemaProperty): string {\n const field =\n Object.keys(member.if?.properties ?? {})[0] ?? member.if?.required?.[0];\n return field ? `if ${field}` : \"if ...\";\n}\n\n// The then/else slots of a conditional member (only present ones are shown).\nfunction conditionalSlots(member: JsonSchemaProperty): ChildSlot[] {\n const slots: ChildSlot[] = [];\n const add = (name: \"then\" | \"else\", sub: JsonSchemaProperty | undefined) => {\n if (sub) {\n slots.push({\n segment: slot(name),\n label: name,\n property: sub,\n kind: \"conditional\",\n removable: false,\n reorderable: false,\n });\n }\n };\n add(\"then\", member.then);\n add(\"else\", member.else);\n return slots;\n}\n\n/**\n * The reusable definitions map of a schema. Canonically 2020-12 `$defs`; also\n * reads Draft-7 `definitions` so both dialects surface as editable nodes. New\n * definitions are always authored into `$defs` (see mutate.addDefinition).\n */\nexport function definitionsOf(\n property: JsonSchemaProperty,\n): Record<string, JsonSchemaProperty> | undefined {\n return property.$defs ?? property.definitions;\n}\n\n// One definition slot per $defs (or Draft-7 definitions) entry.\nfunction definitionSlots(property: JsonSchemaProperty): ChildSlot[] {\n const defs = definitionsOf(property);\n if (!defs) return [];\n return Object.keys(defs).map((name) => ({\n segment: def(name),\n label: name,\n property: defs[name],\n kind: \"definition\" as const,\n removable: true,\n reorderable: false,\n }));\n}\n\n/**\n * The ordered child slots of a property (the single extension point for the\n * tree/inspector/mutations). Surfaces object/array property children, oneOf\n * branches, if/then/else conditionals (allOf/anyOf members), and $defs\n * definitions (root-only in practice).\n */\nexport function childSlots(property: JsonSchemaProperty): ChildSlot[] {\n // A conditional (allOf member with an `if`) exposes its then/else as slots.\n if (isConditionalMember(property)) return conditionalSlots(property);\n // oneOf: one branch slot per element.\n if (isOneOf(property)) {\n const discriminator = getDiscriminator(property);\n return (property.oneOf ?? []).map((b, index) => ({\n segment: branch(index),\n label: getBranchLabel(b, discriminator, index),\n property: b,\n kind: \"branch\" as const,\n removable: true,\n reorderable: true,\n }));\n }\n // object / array-of-object: property slots, then any conditional members.\n const container = childContainer(property);\n const propertySlots: ChildSlot[] = container\n ? Object.keys(container).map((key) => ({\n segment: prop(key),\n label: key,\n property: container[key],\n kind: \"property\" as const,\n removable: true,\n reorderable: true,\n }))\n : [];\n const conditionSlots: ChildSlot[] = conditionalMembers(property).map(\n ({ member, combinator, index }) => ({\n segment: condition(index, combinator),\n label: conditionLabel(member),\n property: member,\n kind: \"conditional\" as const,\n removable: true,\n reorderable: false,\n }),\n );\n return [...propertySlots, ...conditionSlots, ...definitionSlots(property)];\n}\n\n// ---- Navigation -----------------------------------------------------------\n\n// Resolve the immediate child of a property named by one segment.\nfunction stepInto(\n parent: JsonSchemaProperty,\n seg: PathSegment,\n): JsonSchemaProperty | undefined {\n if (seg.kind === \"prop\") return childContainer(parent)?.[seg.key];\n if (seg.kind === \"branch\") return parent.oneOf?.[seg.index];\n if (seg.kind === \"condition\") return parent[seg.combinator]?.[seg.index];\n if (seg.kind === \"def\") return definitionsOf(parent)?.[seg.name];\n if (seg.slot === \"items\") return parent.items;\n return parent[seg.slot];\n}\n\n/**\n * Wrap a JsonSchema root as an object-shaped JsonSchemaProperty so the path\n * navigation machinery can traverse it with the same stepInto logic as any\n * nested property. Pass the keys needed by the caller; unused fields default\n * to undefined.\n */\nexport function schemaAsRootProp(schema: JsonSchema): JsonSchemaProperty {\n return {\n type: \"object\",\n properties: schema.properties,\n required: schema.required,\n \"x-ui-order\": schema[\"x-ui-order\"],\n allOf: schema.allOf,\n anyOf: schema.anyOf,\n $defs: schema.$defs,\n definitions: schema.definitions,\n };\n}\n\n/** Resolve a path to its property definition, or undefined if not found. */\nexport function getProperty(\n schema: JsonSchema,\n path: PropertyPath,\n): JsonSchemaProperty | undefined {\n if (path.length === 0) return undefined;\n // Treat the schema root as an object-shaped property so root children --\n // named properties AND allOf conditionals -- are reached the same way as\n // nested ones (step by step through the segment machinery).\n const root = schemaAsRootProp(schema);\n let current: JsonSchemaProperty | undefined = root;\n for (const seg of path) {\n if (!current) return undefined;\n current = stepInto(current, seg);\n }\n return current;\n}\n\n/** Whether a property has (or can have) child slots (properties, branches, conditionals). */\nexport function isContainer(prop: JsonSchemaProperty): boolean {\n return childSlots(prop).length > 0 || childContainer(prop) !== undefined;\n}\n","/**\n * Pure edit operations over { schema, uiSchema }.\n *\n * Every function returns a new pair; nothing mutates in place. Operations keep\n * the schema and uiSchema consistent -- renaming a property rewrites the property\n * key, the uiSchema entry, the required entry, and any x-ui-order reference at\n * the same level. Mirrors the graph-model/mutate.ts discipline.\n */\n\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n UISchema,\n UILayoutConfig,\n UILayoutRowConfig,\n UILayoutGroupConfig,\n UISchemaOptions,\n} from \"@petrarca/sonnet-core/schema\";\nimport {\n getProperty,\n isReservedKey,\n prop as propSeg,\n branch as branchSeg,\n condition as condSeg,\n def as defSeg,\n type ConditionCombinator,\n type PathSegment,\n type PropertyPath,\n} from \"./paths\";\n\nexport type UiSchemaMap = Record<string, UISchema>;\n\n// The property key of a segment, or undefined for non-property segments.\n// Phase 1 mutations operate on property (prop-kind) children only.\nfunction segKey(seg: PathSegment | undefined): string | undefined {\n return seg && seg.kind === \"prop\" ? seg.key : undefined;\n}\n\n// The property keys along a path (prop segments only). Used to walk the\n// uiSchema x-ui-fields nesting, which is keyed by property name.\nfunction propKeys(path: PropertyPath): string[] {\n return path.flatMap((s) => (s.kind === \"prop\" ? [s.key] : []));\n}\n\nexport interface DesignerModel {\n schema: JsonSchema;\n uiSchema: UiSchemaMap;\n}\n\n// Deep clone via structuredClone (available in the runtime targets).\nfunction clone<T>(v: T): T {\n return structuredClone(v);\n}\n\n/** Kinds that can be created as a new property. */\nexport type NewPropertyKind = \"scalar\" | \"object\" | \"array\" | \"oneOf\";\n\n/** A default property for a newly created property of a given kind. */\nexport function newProperty(kind: NewPropertyKind): JsonSchemaProperty {\n switch (kind) {\n case \"object\":\n return { type: \"object\", properties: {} };\n case \"array\":\n return { type: \"array\", items: { type: \"object\", properties: {} } };\n case \"oneOf\":\n // Start with two empty branches, each tagged by a `kind` discriminator.\n return {\n type: \"object\",\n discriminator: { propertyName: \"kind\" },\n oneOf: [newBranch(\"option_1\"), newBranch(\"option_2\")],\n };\n default:\n return { type: \"string\" };\n }\n}\n\n/** A default oneOf branch: an object with a const-valued `kind` discriminator. */\nexport function newBranch(value: string): JsonSchemaProperty {\n return {\n title: value,\n properties: { kind: { const: value } },\n };\n}\n\n// Resolve the properties container + order-owner for a parent path. Root when\n// path is empty. Returns the mutable container inside a cloned schema.\nfunction resolveContainer(\n schema: JsonSchema,\n parentPath: PropertyPath,\n): {\n properties: Record<string, JsonSchemaProperty>;\n getOrder: () => string[] | undefined;\n setOrder: (order: string[] | undefined) => void;\n getRequired: () => string[] | undefined;\n setRequired: (req: string[] | undefined) => void;\n} | null {\n if (parentPath.length === 0) {\n return {\n properties: schema.properties,\n getOrder: () => schema[\"x-ui-order\"],\n setOrder: (o) => {\n if (o) schema[\"x-ui-order\"] = o;\n else delete schema[\"x-ui-order\"];\n },\n getRequired: () => schema.required,\n setRequired: (r) => {\n if (r && r.length) schema.required = r;\n else delete schema.required;\n },\n };\n }\n const owner = getProperty(schema, parentPath);\n if (!owner) return null;\n // For arrays, order/required/properties live on items; otherwise on the\n // owner (objects and oneOf branches). A branch may not yet have a\n // properties map -- create one so children can be added.\n if (owner.oneOf) return null; // cannot add a bare property to a oneOf itself\n const target = owner.type === \"array\" ? owner.items : owner;\n if (!target) return null; // malformed array (no items)\n if (!target.properties) target.properties = {};\n const properties = target.properties;\n return {\n properties,\n getOrder: () => target[\"x-ui-order\"],\n setOrder: (o) => {\n if (o) target[\"x-ui-order\"] = o;\n else delete target[\"x-ui-order\"];\n },\n getRequired: () => target.required,\n setRequired: (r) => {\n if (r && r.length) target.required = r;\n else delete target.required;\n },\n };\n}\n\n// Unique key like \"property\", \"property_2\" within a container.\nfunction uniqueKey(\n base: string,\n properties: Record<string, JsonSchemaProperty>,\n): string {\n if (!(base in properties)) return base;\n let i = 2;\n while (`${base}_${i}` in properties) i++;\n return `${base}_${i}`;\n}\n\n/** Add a property under a parent path (root when empty). Returns the new model. */\nexport function addProperty(\n model: DesignerModel,\n parentPath: PropertyPath,\n kind: NewPropertyKind,\n): { model: DesignerModel; path: PropertyPath } {\n const schema = clone(model.schema);\n const container = resolveContainer(schema, parentPath);\n if (!container) return { model, path: parentPath };\n const key = uniqueKey(\"property\", container.properties);\n container.properties[key] = newProperty(kind);\n const order = container.getOrder();\n if (order) container.setOrder([...order, key]);\n return {\n model: { schema, uiSchema: model.uiSchema },\n path: [...parentPath, propSeg(key)],\n };\n}\n\n// Derive a branch value that is unique among existing branch titles/consts so\n// that the discriminator remains unambiguous after any add/remove sequence.\nfunction uniqueBranchValue(oneOf: JsonSchemaProperty[]): string {\n const existing = new Set(oneOf.map((b) => b.title).filter(Boolean));\n let i = 1;\n while (existing.has(`option_${i}`)) i++;\n return `option_${i}`;\n}\n\n/** Add a branch to the oneOf property at `path`. Returns the new model + branch path. */\nexport function addBranch(\n model: DesignerModel,\n path: PropertyPath,\n): { model: DesignerModel; path: PropertyPath } {\n const schema = clone(model.schema);\n const owner = getProperty(schema, path);\n if (!owner || !owner.oneOf) return { model, path };\n const index = owner.oneOf.length;\n owner.oneOf.push(newBranch(uniqueBranchValue(owner.oneOf)));\n return {\n model: { schema, uiSchema: model.uiSchema },\n path: [...path, branchSeg(index)],\n };\n}\n\n/** Remove the branch at `path` (a branch segment). Returns the new model. */\nexport function removeBranch(\n model: DesignerModel,\n path: PropertyPath,\n): DesignerModel {\n const last = path[path.length - 1];\n if (!last || last.kind !== \"branch\") return model;\n const schema = clone(model.schema);\n const owner = getProperty(schema, path.slice(0, -1));\n if (!owner?.oneOf) return model;\n owner.oneOf.splice(last.index, 1);\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Move the branch at `path` up (-1) or down (+1) among its siblings. */\nexport function moveBranch(\n model: DesignerModel,\n path: PropertyPath,\n direction: -1 | 1,\n): DesignerModel {\n const last = path[path.length - 1];\n if (!last || last.kind !== \"branch\") return model;\n const schema = clone(model.schema);\n const owner = getProperty(schema, path.slice(0, -1));\n if (!owner?.oneOf) return model;\n const from = last.index;\n const to = from + direction;\n if (to < 0 || to >= owner.oneOf.length) return model;\n const [moved] = owner.oneOf.splice(from, 1);\n owner.oneOf.splice(to, 0, moved);\n return { schema, uiSchema: model.uiSchema };\n}\n\n// ---- Conditionals (if/then/else authored as allOf members) ----------------\n\n/**\n * A seed conditional member: an empty `if` (no field yet) plus an empty `then`.\n * The condition is filled in by setCondition; `then` fields are added like any\n * object's properties.\n */\nexport function newCondition(): JsonSchemaProperty {\n return { if: { properties: {} }, then: { properties: {} } };\n}\n\n/**\n * Add a conditional (if/then/else) to the object at `objectPath` (root when\n * empty), appended to the given combinator array (`allOf` = AND, default;\n * `anyOf` = OR). Returns the new model + the condition path.\n */\nexport function addConditional(\n model: DesignerModel,\n objectPath: PropertyPath,\n combinator: ConditionCombinator = \"allOf\",\n): { model: DesignerModel; path: PropertyPath } {\n const schema = clone(model.schema);\n const owner = conditionalOwner(schema, objectPath);\n if (!owner) return { model, path: objectPath };\n if (!Array.isArray(owner[combinator])) owner[combinator] = [];\n const arr = owner[combinator]!;\n const index = arr.length;\n arr.push(newCondition());\n return {\n model: { schema, uiSchema: model.uiSchema },\n path: [...objectPath, condSeg(index, combinator)],\n };\n}\n\n// The schema object that owns an `allOf` for a given object path: the root\n// schema (path []) or an object property. Arrays/oneOf/scalars cannot host a\n// conditional directly.\nfunction conditionalOwner(\n schema: JsonSchema,\n objectPath: PropertyPath,\n): JsonSchema | JsonSchemaProperty | null {\n if (objectPath.length === 0) return schema;\n const owner = getProperty(schema, objectPath);\n if (!owner) return null;\n const objectLike = owner.type === \"object\" || owner.type === undefined;\n if (!objectLike || owner.oneOf) return null;\n return owner;\n}\n\n/** Remove the conditional at `path` (a condition segment). Returns the new model. */\nexport function removeConditional(\n model: DesignerModel,\n path: PropertyPath,\n): DesignerModel {\n const last = path[path.length - 1];\n if (!last || last.kind !== \"condition\") return model;\n const schema = clone(model.schema);\n const owner = conditionalOwner(schema, path.slice(0, -1));\n const arr = owner?.[last.combinator];\n if (!arr) return model;\n arr.splice(last.index, 1);\n if (arr.length === 0) delete owner![last.combinator];\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Write the `if` of the conditional at `path` from a condition triple. */\nexport function setCondition(\n model: DesignerModel,\n path: PropertyPath,\n ifSchema: JsonSchemaProperty,\n): DesignerModel {\n const last = path[path.length - 1];\n if (!last || last.kind !== \"condition\") return model;\n const schema = clone(model.schema);\n const member = getProperty(schema, path);\n if (!member) return model;\n member.if = ifSchema;\n if (!member.then) member.then = { properties: {} };\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Add an empty `else` branch to the conditional at `path`. */\nexport function addElse(\n model: DesignerModel,\n path: PropertyPath,\n): DesignerModel {\n const last = path[path.length - 1];\n if (!last || last.kind !== \"condition\") return model;\n const schema = clone(model.schema);\n const member = getProperty(schema, path);\n if (!member || member.else) return model;\n member.else = { properties: {} };\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Remove the `else` branch from the conditional at `path`. */\nexport function removeElse(\n model: DesignerModel,\n path: PropertyPath,\n): DesignerModel {\n const last = path[path.length - 1];\n if (!last || last.kind !== \"condition\") return model;\n const schema = clone(model.schema);\n const member = getProperty(schema, path);\n if (!member || !member.else) return model;\n delete member.else;\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** The other combinator. */\nfunction otherCombinator(c: ConditionCombinator): ConditionCombinator {\n return c === \"allOf\" ? \"anyOf\" : \"allOf\";\n}\n\n/**\n * Switch the combinator (AND/OR) for the conditionals of the object at\n * `objectPath`. Migrates every conditional member from the current combinator\n * array to `next`. Non-conditional members (structural allOf/anyOf entries)\n * stay put. No-op when already using `next` or when there are no conditionals.\n */\nexport function setConditionalBehavior(\n model: DesignerModel,\n objectPath: PropertyPath,\n next: ConditionCombinator,\n): DesignerModel {\n const schema = clone(model.schema);\n const owner = conditionalOwner(schema, objectPath);\n if (!owner) return model;\n const from = otherCombinator(next);\n const source = owner[from];\n if (!Array.isArray(source)) return model;\n\n const conditionals = source.filter((m) => !!m.if);\n if (conditionals.length === 0) return model;\n const rest = source.filter((m) => !m.if);\n\n // Move conditionals into the target array; leave structural members behind.\n if (rest.length > 0) owner[from] = rest;\n else delete owner[from];\n owner[next] = [...(owner[next] ?? []), ...conditionals];\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Delete the property at path. Returns the new model. */\nexport function deleteProperty(\n model: DesignerModel,\n path: PropertyPath,\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const parentPath = path.slice(0, -1);\n const key = segKey(path[path.length - 1]);\n if (key === undefined) return model;\n const container = resolveContainer(schema, parentPath);\n if (!container || !(key in container.properties)) return model;\n delete container.properties[key];\n const order = container.getOrder();\n if (order) container.setOrder(order.filter((k) => k !== key));\n const required = container.getRequired();\n if (required) container.setRequired(required.filter((k) => k !== key));\n\n // Drop the property's uiSchema entry at any depth (a nested one lives under\n // its ancestors' x-ui-fields), so no stale hints wait for a later namesake.\n const uiSchema = getUiEntryAtPath(model.uiSchema, path)\n ? setEntryIn(model.uiSchema, propKeys(path), undefined)\n : model.uiSchema;\n return { schema, uiSchema };\n}\n\n// Rewrite one key to another within a properties map, preserving position.\nfunction renameKeyInPlace(\n properties: Record<string, JsonSchemaProperty>,\n prevKey: string,\n nextKey: string,\n): void {\n const rebuilt: Record<string, JsonSchemaProperty> = {};\n for (const [k, v] of Object.entries(properties)) {\n rebuilt[k === prevKey ? nextKey : k] = v;\n }\n for (const k of Object.keys(properties)) delete properties[k];\n Object.assign(properties, rebuilt);\n}\n\n// Move a property's uiSchema entry to its new key, at any depth (returns a new\n// map if changed).\nfunction renameUiEntry(\n uiSchema: UiSchemaMap,\n path: PropertyPath,\n nextKey: string,\n): UiSchemaMap {\n const entry = getUiEntryAtPath(uiSchema, path);\n if (!entry) return uiSchema;\n const keys = propKeys(path);\n const cleared = setEntryIn(uiSchema, keys, undefined);\n return setEntryIn(cleared, [...keys.slice(0, -1), nextKey], entry);\n}\n\n// Update order and required arrays when a key is renamed in a container.\nfunction updateContainerRefs(\n container: ReturnType<typeof resolveContainer> & object,\n prevKey: string,\n nextKey: string,\n): void {\n const rename = (k: string) => (k === prevKey ? nextKey : k);\n const order = container.getOrder();\n if (order) container.setOrder(order.map(rename));\n const required = container.getRequired();\n if (required) container.setRequired(required.map(rename));\n}\n\n/** Rename the property at path. Rewrites key, order, required, and uiSchema. */\nexport function renameProperty(\n model: DesignerModel,\n path: PropertyPath,\n nextKey: string,\n): { model: DesignerModel; path: PropertyPath } {\n if (path.length === 0) return { model, path };\n const parentPath = path.slice(0, -1);\n const prevKey = segKey(path[path.length - 1]);\n if (prevKey === undefined) return { model, path };\n if (nextKey === prevKey || !nextKey || isReservedKey(nextKey))\n return { model, path };\n\n const schema = clone(model.schema);\n const container = resolveContainer(schema, parentPath);\n if (!container || !(prevKey in container.properties)) return { model, path };\n if (nextKey in container.properties) return { model, path }; // collision: no-op\n\n renameKeyInPlace(container.properties, prevKey, nextKey);\n updateContainerRefs(container, prevKey, nextKey);\n const uiSchema = renameUiEntry(model.uiSchema, path, nextKey);\n return {\n model: { schema, uiSchema },\n path: [...parentPath, propSeg(nextKey)],\n };\n}\n\n/** Move the property at path up (-1) or down (+1) among its siblings. */\nexport function moveProperty(\n model: DesignerModel,\n path: PropertyPath,\n direction: -1 | 1,\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const parentPath = path.slice(0, -1);\n const key = segKey(path[path.length - 1]);\n if (key === undefined) return model;\n const container = resolveContainer(schema, parentPath);\n if (!container) return model;\n\n const keys = Object.keys(container.properties);\n const order = container.getOrder() ?? keys;\n // Normalize order to include every key.\n const full = [...order.filter((k) => keys.includes(k))];\n for (const k of keys) if (!full.includes(k)) full.push(k);\n\n const idx = full.indexOf(key);\n const swap = idx + direction;\n if (idx < 0 || swap < 0 || swap >= full.length) return model;\n [full[idx], full[swap]] = [full[swap], full[idx]];\n container.setOrder(full);\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Toggle whether the property at path is required among its siblings. */\nexport function setRequired(\n model: DesignerModel,\n path: PropertyPath,\n required: boolean,\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const parentPath = path.slice(0, -1);\n const key = segKey(path[path.length - 1]);\n if (key === undefined) return model;\n const container = resolveContainer(schema, parentPath);\n if (!container) return model;\n const current = new Set(container.getRequired() ?? []);\n if (required) current.add(key);\n else current.delete(key);\n container.setRequired([...current]);\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Replace the property definition at path (merges the given partial). */\nexport function updateProperty(\n model: DesignerModel,\n path: PropertyPath,\n patch: Partial<JsonSchemaProperty>,\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const prop = getProperty(schema, path);\n if (!prop) return model;\n // Apply the patch: set defined values, delete keys whose patch value is\n // undefined so they don't persist as ghost own-keys on the schema object.\n for (const [k, v] of Object.entries(patch)) {\n if (v === undefined) delete (prop as Record<string, unknown>)[k];\n else (prop as Record<string, unknown>)[k] = v;\n }\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** The kind a property can be changed to: a JSON Schema type, or a \"oneOf\" union. */\nexport type PropertyTypeChoice =\n | NonNullable<JsonSchemaProperty[\"type\"]>\n | \"oneOf\";\n\n// The current kind choice of a property (for no-op detection).\nfunction currentTypeChoice(prop: JsonSchemaProperty): PropertyTypeChoice {\n return prop.oneOf ? \"oneOf\" : (prop.type ?? \"string\");\n}\n\n/**\n * Change the kind of the property at path, reshaping structural keys: object\n * adds an empty `properties`; array adds `items`; oneOf adds branches + a\n * discriminator; leaving a kind strips its keys. Type-specific validation keys\n * that no longer apply are dropped.\n */\nexport function changePropertyType(\n model: DesignerModel,\n path: PropertyPath,\n next: PropertyTypeChoice,\n): DesignerModel {\n if (path.length === 0 || !next) return model;\n const schema = clone(model.schema);\n const prop = getProperty(schema, path);\n // A $ref node has no concrete type; always allow retyping it (which clears\n // the $ref below). Otherwise skip when the choice is unchanged.\n if (!prop || (!prop.$ref && currentTypeChoice(prop) === next)) return model;\n\n // Strip all structural + type-specific + logic keys from the previous kind.\n delete prop.properties;\n delete prop.items;\n delete prop.enum;\n delete prop.oneOf;\n delete prop.discriminator;\n delete prop.const;\n // A concrete type replaces any $ref: the property is no longer a reference.\n delete prop.$ref;\n // Conditionals (allOf if/then/else) belong to an object; drop them when the\n // owning property is no longer an object.\n if (next !== \"object\") {\n delete prop.allOf;\n delete prop.anyOf;\n }\n delete prop.minLength;\n delete prop.maxLength;\n delete prop.pattern;\n delete prop.format;\n delete prop.minimum;\n delete prop.maximum;\n delete prop.minItems;\n delete prop.maxItems;\n\n if (next === \"oneOf\") {\n const seed = newProperty(\"oneOf\");\n prop.type = seed.type;\n prop.discriminator = seed.discriminator;\n prop.oneOf = seed.oneOf;\n } else {\n prop.type = next;\n if (next === \"object\") prop.properties = {};\n if (next === \"array\") prop.items = { type: \"string\" };\n }\n return { schema, uiSchema: model.uiSchema };\n}\n\n// The local $ref pointer for a definition name (2020-12 canonical form).\nfunction defPointer(name: string): string {\n return `#/$defs/${name}`;\n}\n\n/**\n * Point the property at path to a definition by name, writing a local `$ref`\n * (`#/$defs/<name>`) and stripping type-specific keys. Turns a plain property\n * into a reference usage. No-op for the root or an unknown target.\n */\nexport function setReference(\n model: DesignerModel,\n path: PropertyPath,\n name: string,\n): DesignerModel {\n if (path.length === 0 || !name) return model;\n const schema = clone(model.schema);\n const prop = getProperty(schema, path);\n if (!prop) return model;\n const defs = schema.$defs ?? schema.definitions;\n if (!defs || !(name in defs)) return model;\n // For an array, the reference applies to its items (\"array of <def>\"); the\n // array keeps its type and cardinality. Otherwise the property itself becomes\n // the reference.\n if (prop.type === \"array\") {\n prop.items = { $ref: defPointer(name) };\n return { schema, uiSchema: model.uiSchema };\n }\n makeReference(prop, name);\n return { schema, uiSchema: model.uiSchema };\n}\n\n// Turn a property into a $ref node: strip structural and type-specific keys,\n// keeping only annotation overrides (title/description/default) that are valid\n// 2020-12 $ref siblings at the referencing site.\nfunction makeReference(prop: JsonSchemaProperty, name: string): void {\n delete prop.properties;\n delete prop.items;\n delete prop.enum;\n delete prop.oneOf;\n delete prop.discriminator;\n delete prop.const;\n delete prop.allOf;\n delete prop.anyOf;\n delete prop.type;\n // Strip type-specific validation so it does not silently constrain the\n // referencing site independently of the definition's own constraints.\n delete prop.minLength;\n delete prop.maxLength;\n delete prop.pattern;\n delete prop.format;\n delete prop.minimum;\n delete prop.maximum;\n delete prop.minItems;\n delete prop.maxItems;\n prop.$ref = defPointer(name);\n}\n\n// Visit every object node in a schema tree, calling visitor on each.\n// The visitor receives the object and the key under which it was reached\n// (undefined for the root); returning true from the visitor skips recursing\n// into the object's children (used to skip already-matched nodes).\nfunction walkSchemaNodes(\n node: unknown,\n visitor: (obj: Record<string, unknown>, key: string | undefined) => void,\n parentKey?: string,\n): void {\n if (Array.isArray(node)) {\n for (const item of node) walkSchemaNodes(item, visitor, parentKey);\n return;\n }\n if (!node || typeof node !== \"object\") return;\n const obj = node as Record<string, unknown>;\n visitor(obj, parentKey);\n for (const key of Object.keys(obj)) {\n walkSchemaNodes(obj[key], visitor, key);\n }\n}\n\n/** Recursively rewrite every local `$ref` targeting `from` to point at `to`. */\nfunction rewriteRefs(node: unknown, from: string, to: string): void {\n walkSchemaNodes(node, (obj, key) => {\n // Only rewrite when reached via a non-$ref key, so we are visiting the\n // containing object (not a string value that happens to equal `from`).\n if (key !== \"$ref\" && obj.$ref === from) obj.$ref = to;\n });\n}\n\n// Count local $ref usages of a definition across the whole schema.\nfunction countRefUsages(schema: JsonSchema, name: string): number {\n let count = 0;\n const pointers = new Set([`#/$defs/${name}`, `#/definitions/${name}`]);\n walkSchemaNodes(schema, (obj) => {\n if (typeof obj.$ref === \"string\" && pointers.has(obj.$ref)) count++;\n });\n return count;\n}\n\n/**\n * Add a new empty object definition under `$defs`. Returns the new model and the\n * path to the created definition for selection.\n */\nexport function addDefinition(\n model: DesignerModel,\n name?: string,\n): { model: DesignerModel; path: PropertyPath } {\n const schema = clone(model.schema);\n if (!schema.$defs) schema.$defs = {};\n const key = uniqueKey(name ?? \"Definition\", schema.$defs);\n schema.$defs[key] = { type: \"object\", properties: {} };\n return {\n model: { schema, uiSchema: model.uiSchema },\n path: [defSeg(key)],\n };\n}\n\n/**\n * Rename a `$defs` entry, preserving order, and rewrite every local `$ref` that\n * targets it (both `#/$defs/` and `#/definitions/` forms) to the new pointer.\n * No-op on collision, reserved, or empty names.\n */\nexport function renameDefinition(\n model: DesignerModel,\n oldName: string,\n newName: string,\n): { model: DesignerModel; path: PropertyPath } {\n const path: PropertyPath = [defSeg(oldName)];\n if (!newName || newName === oldName || isReservedKey(newName))\n return { model, path };\n const schema = clone(model.schema);\n // Support both 2020-12 $defs and Draft-7 definitions; author to the map\n // that already contains the entry.\n const defs = schema.$defs ?? schema.definitions;\n if (!defs || !(oldName in defs) || newName in defs) return { model, path };\n\n renameKeyInPlace(defs, oldName, newName);\n rewriteRefs(schema, `#/$defs/${oldName}`, `#/$defs/${newName}`);\n rewriteRefs(schema, `#/definitions/${oldName}`, `#/$defs/${newName}`);\n return {\n model: { schema, uiSchema: model.uiSchema },\n path: [defSeg(newName)],\n };\n}\n\n/**\n * Remove a `$defs` entry. Blocked (no-op) while any local `$ref` still targets\n * it; the UI surfaces the usage count. Drops the `$defs` map when it empties.\n */\nexport function removeDefinition(\n model: DesignerModel,\n name: string,\n): DesignerModel {\n const schema = clone(model.schema);\n // Support both 2020-12 $defs and Draft-7 definitions.\n const inDefs = schema.$defs && name in schema.$defs;\n const inDefs7 = schema.definitions && name in schema.definitions;\n if (!inDefs && !inDefs7) return model;\n if (countRefUsages(schema, name) > 0) return model; // in use: keep it\n if (inDefs) {\n delete schema.$defs![name];\n if (Object.keys(schema.$defs!).length === 0) delete schema.$defs;\n } else {\n delete schema.definitions![name];\n if (Object.keys(schema.definitions!).length === 0)\n delete schema.definitions;\n }\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Whether a definition is referenced anywhere (for UI delete-guard messaging). */\nexport function definitionUsageCount(schema: JsonSchema, name: string): number {\n return countRefUsages(schema, name);\n}\n\n/** One enum choice: a value and an optional display label. */\nexport interface EnumChoice {\n value: string;\n label?: string;\n}\n\n/**\n * Set the enum choices for the property at path. Values write to `property.enum`;\n * labels write to the property's `x-ui-options.enumNames` in the uiSchema (only\n * for top-level properties, where the uiSchema map is keyed). An empty list clears\n * both. Deduplicates and drops empty values.\n */\n// Normalize choices: trim, drop empties, dedupe by value (first wins).\nfunction normalizeChoices(choices: EnumChoice[]): EnumChoice[] {\n const seen = new Set<string>();\n const clean: EnumChoice[] = [];\n for (const c of choices) {\n const value = c.value.trim();\n if (!value || seen.has(value)) continue;\n seen.add(value);\n clean.push({ value, label: c.label?.trim() || undefined });\n }\n return clean;\n}\n\n// Update a UISchema entry's x-ui-options.enumNames from labelled choices,\n// returning the new entry (or undefined if empty).\nfunction withEnumNames(\n entry: UISchema | undefined,\n choices: EnumChoice[],\n): UISchema | undefined {\n const enumNames: Record<string, string> = {};\n for (const c of choices) if (c.label) enumNames[c.value] = c.label;\n\n const next: UISchema = { ...(entry ?? {}) };\n const options = {\n ...((next[\"x-ui-options\"] as Record<string, unknown>) ?? {}),\n };\n if (Object.keys(enumNames).length) options.enumNames = enumNames;\n else delete options.enumNames;\n if (Object.keys(options).length) next[\"x-ui-options\"] = options;\n else delete next[\"x-ui-options\"];\n\n return Object.keys(next).length ? next : undefined;\n}\n\nexport function setEnum(\n model: DesignerModel,\n path: PropertyPath,\n choices: EnumChoice[],\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const prop = getProperty(schema, path);\n if (!prop) return model;\n\n const clean = normalizeChoices(choices);\n if (clean.length === 0) delete prop.enum;\n else prop.enum = clean.map((c) => c.value);\n\n // enumNames lives in the property's uiSchema entry (at any nesting depth).\n const nextEntry = withEnumNames(\n getUiEntryAtPath(model.uiSchema, path),\n clean,\n );\n const uiSchema = setEntryIn(model.uiSchema, propKeys(path), nextEntry);\n\n return { schema, uiSchema };\n}\n\n/** Read the current enum choices for a property + its uiSchema entry. */\nexport function readEnumChoices(\n prop: JsonSchemaProperty,\n uiEntry: UISchema | undefined,\n): EnumChoice[] {\n if (!Array.isArray(prop.enum)) return [];\n const enumNames =\n (uiEntry?.[\"x-ui-options\"] as { enumNames?: Record<string, string> })\n ?.enumNames ?? {};\n return prop.enum.map((v) => {\n const value = String(v);\n return { value, label: enumNames[value] };\n });\n}\n\n/** Table presentation hints for a property (embedded in the schema). */\nexport interface TableHints {\n cell?: string;\n cellOptions?: Record<string, unknown>;\n column?: NonNullable<JsonSchemaProperty[\"x-ui-column\"]>;\n}\n\n/**\n * Set (or clear) a property's table hints: x-ui-cell, x-ui-cell-options, and\n * x-ui-column. These live embedded on the property (EntityTable reads them\n * there). Empty values clear the corresponding key.\n */\nexport function setTableHints(\n model: DesignerModel,\n path: PropertyPath,\n hints: TableHints,\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const prop = getProperty(schema, path);\n if (!prop) return model;\n\n if (hints.cell) prop[\"x-ui-cell\"] = hints.cell;\n else delete prop[\"x-ui-cell\"];\n\n if (hints.cellOptions && Object.keys(hints.cellOptions).length > 0) {\n prop[\"x-ui-cell-options\"] = hints.cellOptions;\n } else {\n delete prop[\"x-ui-cell-options\"];\n }\n\n if (hints.column && Object.keys(hints.column).length > 0) {\n prop[\"x-ui-column\"] = hints.column;\n } else {\n delete prop[\"x-ui-column\"];\n }\n\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Read a property's current table hints. */\nexport function readTableHints(prop: JsonSchemaProperty): TableHints {\n return {\n cell: typeof prop[\"x-ui-cell\"] === \"string\" ? prop[\"x-ui-cell\"] : undefined,\n cellOptions: prop[\"x-ui-cell-options\"] as\n | Record<string, unknown>\n | undefined,\n column: prop[\"x-ui-column\"],\n };\n}\n\n/** Set (or clear) the top-level uiSchema entry for a property name. */\n// -- Path-aware uiSchema navigation --------------------------------------\n//\n// The uiSchema map is keyed by top-level property name. A nested property's\n// UISchema entry lives under its ancestor's `x-ui-fields` sub-map: the first\n// path segment indexes the top-level map, each subsequent segment indexes\n// through `x-ui-fields`. This mirrors how ObjectWidget/ArrayWidget read it.\n\ntype UiFieldsMap = Record<string, UISchema>;\n\n/** Read the UISchema entry for a property path, or undefined. */\nexport function getUiEntryAtPath(\n uiSchema: UiSchemaMap,\n path: PropertyPath,\n): UISchema | undefined {\n const keys = propKeys(path);\n if (keys.length === 0) return undefined;\n let entry: UISchema | undefined = uiSchema[keys[0]];\n for (let i = 1; i < keys.length && entry; i++) {\n const fields = entry[\"x-ui-fields\"] as UiFieldsMap | undefined;\n entry = fields?.[keys[i]];\n }\n return entry;\n}\n\n// Recursively set `entry` at `keys` within a fields map, pruning empties on the\n// way back up (empty entry -> removed; empty x-ui-fields -> removed).\nfunction setEntryIn(\n map: UiFieldsMap,\n keys: string[],\n entry: UISchema | undefined,\n): UiFieldsMap {\n const [head, ...rest] = keys;\n const next: UiFieldsMap = { ...map };\n\n if (rest.length === 0) {\n if (entry && Object.keys(entry).length > 0) next[head] = entry;\n else delete next[head];\n return next;\n }\n\n const current: UISchema = { ...(next[head] ?? {}) };\n const childFields = (current[\"x-ui-fields\"] as UiFieldsMap | undefined) ?? {};\n const updatedFields = setEntryIn(childFields, rest, entry);\n\n if (Object.keys(updatedFields).length > 0) {\n current[\"x-ui-fields\"] = updatedFields;\n } else {\n delete current[\"x-ui-fields\"];\n }\n\n if (Object.keys(current).length > 0) next[head] = current;\n else delete next[head];\n return next;\n}\n\n/** Set (or clear) the UISchema entry at a property path (any nesting depth). */\nexport function setUiEntry(\n model: DesignerModel,\n path: PropertyPath,\n entry: UISchema | undefined,\n): DesignerModel {\n if (path.length === 0) return model;\n const uiSchema = setEntryIn(model.uiSchema, propKeys(path), entry);\n return { schema: model.schema, uiSchema };\n}\n\n/**\n * Set (or clear) the x-ui-layout of an object/array property at path. Object\n * layout lives on the property; array layout lives on `items`.\n */\nexport function setPropertyLayout(\n model: DesignerModel,\n path: PropertyPath,\n layout: UILayoutConfig | undefined,\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const prop = getProperty(schema, path);\n if (!prop) return model;\n const target = prop.type === \"array\" ? prop.items : prop;\n if (!target) return model;\n if (layout) target[\"x-ui-layout\"] = layout;\n else delete target[\"x-ui-layout\"];\n return { schema, uiSchema: model.uiSchema };\n}\n\n// The uiSchema map is keyed by property name (UISchema values) but also carries\n// special top-level keys (x-ui-layout, x-ui-globalOptions) whose values are not\n// UISchema. Read/write them through this looser view.\ntype RootUiSchema = UiSchemaMap & {\n \"x-ui-layout\"?: UILayoutConfig;\n \"x-ui-globalOptions\"?: UISchemaOptions;\n};\n\n/** Set (or clear) the root form layout (uiSchema[\"x-ui-layout\"]). */\nexport function setRootLayout(\n model: DesignerModel,\n layout: UILayoutConfig | undefined,\n): DesignerModel {\n const uiSchema = { ...model.uiSchema } as RootUiSchema;\n if (layout) uiSchema[\"x-ui-layout\"] = layout;\n else delete uiSchema[\"x-ui-layout\"];\n return { schema: model.schema, uiSchema };\n}\n\n/**\n * Set (or clear) the root layout rows (uiSchema[\"x-ui-layout\"].rows),\n * preserving other x-ui-layout keys. Clearing rows to empty removes the key;\n * if x-ui-layout then has no keys, it is removed entirely.\n */\nexport function setRootLayoutRows(\n model: DesignerModel,\n rows: UILayoutConfig[\"rows\"],\n): DesignerModel {\n const uiSchema = { ...model.uiSchema } as RootUiSchema;\n const layout: UILayoutConfig = { ...(uiSchema[\"x-ui-layout\"] ?? {}) };\n if (rows && rows.length > 0) layout.rows = rows;\n else delete layout.rows;\n if (Object.keys(layout).length > 0) uiSchema[\"x-ui-layout\"] = layout;\n else delete uiSchema[\"x-ui-layout\"];\n return { schema: model.schema, uiSchema };\n}\n\n/**\n * Set the layout rows for a scope: the root form (path []) or an object/array\n * container (its property path). Root rows live in uiSchema[\"x-ui-layout\"];\n * a container's rows live on the property's x-ui-layout (array -> items).\n * Preserves other x-ui-layout keys.\n */\nexport function setScopedLayoutRows(\n model: DesignerModel,\n scopePath: PropertyPath,\n rows: UILayoutConfig[\"rows\"],\n): DesignerModel {\n if (scopePath.length === 0) return setRootLayoutRows(model, rows);\n\n const schema = clone(model.schema);\n const prop = getProperty(schema, scopePath);\n if (!prop) return model;\n const target = prop.type === \"array\" ? prop.items : prop;\n if (!target) return model;\n\n const layout: UILayoutConfig = { ...(target[\"x-ui-layout\"] ?? {}) };\n if (rows && rows.length > 0) layout.rows = rows;\n else delete layout.rows;\n if (Object.keys(layout).length > 0) target[\"x-ui-layout\"] = layout;\n else delete target[\"x-ui-layout\"];\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Read the current x-ui-layout for a scope (root or a container property). */\nexport function getScopedLayout(\n schema: JsonSchema,\n uiSchema: UiSchemaMap,\n scopePath: PropertyPath,\n): UILayoutConfig | undefined {\n if (scopePath.length === 0) {\n return (uiSchema as RootUiSchema)[\"x-ui-layout\"];\n }\n const prop = getProperty(schema, scopePath);\n const target = prop?.type === \"array\" ? prop.items : prop;\n return target?.[\"x-ui-layout\"];\n}\n\n/**\n * Merge scalar layout options (direction/gap/labels/compact) into a scope's\n * x-ui-layout, preserving rows and other keys. Undefined values clear the key.\n */\nexport function setScopedLayoutOptions(\n model: DesignerModel,\n scopePath: PropertyPath,\n options: Pick<UILayoutConfig, \"direction\" | \"gap\" | \"labels\" | \"compact\">,\n): DesignerModel {\n const current =\n getScopedLayout(model.schema, model.uiSchema, scopePath) ?? {};\n const merged: UILayoutConfig = { ...current };\n for (const key of [\"direction\", \"gap\", \"labels\", \"compact\"] as const) {\n const v = options[key];\n if (v === undefined || (typeof v === \"number\" && Number.isNaN(v)))\n delete merged[key];\n else (merged as Record<string, unknown>)[key] = v;\n }\n const layout = Object.keys(merged).length > 0 ? merged : undefined;\n if (scopePath.length === 0) return setRootLayout(model, layout);\n return setPropertyLayout(model, scopePath, layout);\n}\n\n/**\n * Set the group definitions for a scope, preserving other x-ui-layout keys.\n * Passing an empty list (or undefined) clears groups, returning the scope to the\n * flat row layout. Root groups live in uiSchema[\"x-ui-layout\"]; a container's\n * live on the property's x-ui-layout (array -> items).\n *\n * Groups and flat rows are mutually exclusive (the renderer gives groups\n * precedence), so setting groups drops `rows` -- otherwise the orphaned list\n * would be invisible in both the form and the designer.\n */\nexport function setScopedLayoutGroups(\n model: DesignerModel,\n scopePath: PropertyPath,\n groups: UILayoutConfig[\"groups\"],\n): DesignerModel {\n const current =\n getScopedLayout(model.schema, model.uiSchema, scopePath) ?? {};\n const merged: UILayoutConfig = { ...current };\n if (groups && groups.length > 0) {\n merged.groups = groups;\n delete merged.rows;\n } else {\n delete merged.groups;\n }\n const layout = Object.keys(merged).length > 0 ? merged : undefined;\n if (scopePath.length === 0) return setRootLayout(model, layout);\n return setPropertyLayout(model, scopePath, layout);\n}\n\n/** The groups currently defined for a scope. */\nfunction groupsOf(\n model: DesignerModel,\n scopePath: PropertyPath,\n): UILayoutGroupConfig[] {\n return getScopedLayout(model.schema, model.uiSchema, scopePath)?.groups ?? [];\n}\n\n/** Append an empty group. The label defaults to the next ordinal (\"Group 3\"). */\nexport function addLayoutGroup(\n model: DesignerModel,\n scopePath: PropertyPath,\n label?: string,\n): DesignerModel {\n const groups = groupsOf(model, scopePath);\n const next = { label: label ?? `Group ${groups.length + 1}`, rows: [] };\n return setScopedLayoutGroups(model, scopePath, [...groups, next]);\n}\n\n/** Rename one group. No-op for an unknown index or a blank label. */\nexport function renameLayoutGroup(\n model: DesignerModel,\n scopePath: PropertyPath,\n groupIndex: number,\n label: string,\n): DesignerModel {\n const groups = groupsOf(model, scopePath);\n if (!groups[groupIndex] || !label.trim()) return model;\n return setScopedLayoutGroups(\n model,\n scopePath,\n groups.map((group, i) => (i === groupIndex ? { ...group, label } : group)),\n );\n}\n\n/**\n * Place a property into one group's row, removing it from wherever it currently\n * sits across *all* groups. Passing a null target returns it to the pool.\n *\n * Needed because each group owns its own rows: without a cross-group operation a\n * field could only be moved between groups by visiting its old group first.\n */\nexport function placeFieldInGroup(\n model: DesignerModel,\n scopePath: PropertyPath,\n key: string,\n target: { groupIndex: number; rowIndex: number } | null,\n): DesignerModel {\n const groups = groupsOf(model, scopePath);\n if (!key || groups.length === 0) return model;\n const stripped = groups.map((group) => ({\n ...group,\n rows: group.rows.map((row) => ({\n ...row,\n fields: row.fields.filter((f) => f !== key),\n })),\n }));\n if (!target) return setScopedLayoutGroups(model, scopePath, stripped);\n\n const { groupIndex, rowIndex } = target;\n const row = stripped[groupIndex]?.rows[rowIndex];\n if (!row) return setScopedLayoutGroups(model, scopePath, stripped);\n stripped[groupIndex].rows = stripped[groupIndex].rows.map((r, i) =>\n i === rowIndex ? { ...r, fields: [...r.fields, key] } : r,\n );\n return setScopedLayoutGroups(model, scopePath, stripped);\n}\n\n/** Move one group left (-1) or right (+1). No-op at the ends. */\nexport function moveLayoutGroup(\n model: DesignerModel,\n scopePath: PropertyPath,\n groupIndex: number,\n direction: -1 | 1,\n): DesignerModel {\n const groups = groupsOf(model, scopePath);\n const target = groupIndex + direction;\n if (!groups[groupIndex] || target < 0 || target >= groups.length)\n return model;\n const next = [...groups];\n [next[groupIndex], next[target]] = [next[target], next[groupIndex]];\n return setScopedLayoutGroups(model, scopePath, next);\n}\n\n/**\n * Set (or clear) a group's show/hide rule. Passing undefined makes the group\n * unconditional.\n */\nexport function setLayoutGroupRule(\n model: DesignerModel,\n scopePath: PropertyPath,\n groupIndex: number,\n rule: UILayoutGroupConfig[\"rule\"],\n): DesignerModel {\n const groups = groupsOf(model, scopePath);\n if (!groups[groupIndex]) return model;\n const next = groups.map((group, i) => {\n if (i !== groupIndex) return group;\n const { rule: _drop, ...rest } = group;\n return rule ? { ...rest, rule } : rest;\n });\n return setScopedLayoutGroups(model, scopePath, next);\n}\n\n/**\n * Set the group presentation for a scope (\"groups\", \"stepper\", or a custom\n * template name). Passing undefined restores the default group presentation.\n */\nexport function setScopedLayoutVariant(\n model: DesignerModel,\n scopePath: PropertyPath,\n variant: UILayoutConfig[\"variant\"],\n): DesignerModel {\n const current =\n getScopedLayout(model.schema, model.uiSchema, scopePath) ?? {};\n const merged: UILayoutConfig = { ...current };\n if (variant && variant !== \"groups\") merged.variant = variant;\n else delete merged.variant;\n const layout = Object.keys(merged).length > 0 ? merged : undefined;\n if (scopePath.length === 0) return setRootLayout(model, layout);\n return setPropertyLayout(model, scopePath, layout);\n}\n\n/**\n * Remove one group. Its rows are not discarded: removing the last remaining group\n * flattens them back into the scope's flat row layout, so a single click can\n * never destroy every field placement.\n */\nexport function removeLayoutGroup(\n model: DesignerModel,\n scopePath: PropertyPath,\n groupIndex: number,\n): DesignerModel {\n const groups = groupsOf(model, scopePath);\n if (!groups[groupIndex]) return model;\n const remaining = groups.filter((_, i) => i !== groupIndex);\n if (remaining.length > 0) {\n return setScopedLayoutGroups(model, scopePath, remaining);\n }\n const cleared = setScopedLayoutGroups(model, scopePath, []);\n return setScopedLayoutRows(cleared, scopePath, groups[groupIndex].rows);\n}\n\n/** Replace the rows of one group in a scope. No-op for an unknown group index. */\nexport function setScopedGroupRows(\n model: DesignerModel,\n scopePath: PropertyPath,\n groupIndex: number,\n rows: UILayoutRowConfig[],\n): DesignerModel {\n const groups = getScopedLayout(\n model.schema,\n model.uiSchema,\n scopePath,\n )?.groups;\n if (!groups?.[groupIndex]) return model;\n const next = groups.map((group, i) =>\n i === groupIndex ? { ...group, rows } : group,\n );\n return setScopedLayoutGroups(model, scopePath, next);\n}\n\n/**\n * Switch a scope between flat rows and groups, carrying the existing layout over\n * so no field placement is lost: rows become the first group's rows, and leaving\n * group mode flattens every group's rows back into one list.\n */\nexport function setScopedLayoutMode(\n model: DesignerModel,\n scopePath: PropertyPath,\n mode: \"rows\" | \"groups\",\n): DesignerModel {\n const layout = getScopedLayout(model.schema, model.uiSchema, scopePath) ?? {};\n const groups = layout.groups ?? [];\n const rows = layout.rows ?? [];\n if (mode === \"groups\") {\n if (groups.length > 0) return model; // already tabbed\n // setScopedLayoutGroups drops the flat rows, so seed the group with them first.\n return setScopedLayoutGroups(model, scopePath, [\n { label: \"Group 1\", rows },\n ]);\n }\n if (groups.length === 0) return model; // already flat\n // Keep any pre-existing flat rows ahead of the flattened group rows so nothing\n // is overwritten if both somehow coexist (hand-authored uiSchema).\n const flattened = [...rows, ...groups.flatMap((group) => group.rows)];\n const cleared = setScopedLayoutGroups(model, scopePath, []);\n return setScopedLayoutRows(cleared, scopePath, flattened);\n}\n\n/** Set (or clear) the root global options (uiSchema[\"x-ui-globalOptions\"]). */\nexport function setGlobalOptions(\n model: DesignerModel,\n options: UISchemaOptions | undefined,\n): DesignerModel {\n const uiSchema = { ...model.uiSchema } as RootUiSchema;\n if (options) uiSchema[\"x-ui-globalOptions\"] = options;\n else delete uiSchema[\"x-ui-globalOptions\"];\n return { schema: model.schema, uiSchema };\n}\n","/**\n * Read-shaping: turn a JsonSchema into a property tree for the designer UI.\n *\n * Pure, no React. Ordering follows the renderer's rule: an explicit x-ui-order\n * first, then remaining keys in declaration order.\n */\n\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n RefResolver,\n} from \"@petrarca/sonnet-core/schema\";\nimport {\n childSlots,\n isContainer,\n schemaAsRootProp,\n type ChildSlot,\n type PropertyPath,\n type SlotKind,\n} from \"./paths\";\nimport { isOneOf } from \"@petrarca/sonnet-core/schema\";\n\nexport type PropertyKind =\n | \"scalar\"\n | \"enum\"\n | \"object\"\n | \"array\"\n | \"oneOf\"\n | \"conditional\"\n | \"reference\"\n | \"definition\";\n\nexport interface PropertyNode {\n path: PropertyPath;\n key: string;\n property: JsonSchemaProperty;\n kind: PropertyKind;\n /** How this node sits in its parent: a named property or a oneOf branch. */\n slotKind: SlotKind;\n required: boolean;\n /** Short type descriptor for the tree row, e.g. \"string\", \"object[]\". */\n typeLabel: string;\n /** Resolved widget override (x-ui-widget) if any. */\n widget?: string;\n /**\n * When this node is a `$ref`, the ref string it points at. Undefined for\n * non-ref nodes.\n */\n reference?: string;\n /**\n * True for nodes that live inside a resolved `$ref` (the ref's descendants).\n * These come from a shared definition and are not editable here -- the tree\n * and inspector use this to show read-only affordances. Computed once at\n * build time (no per-render schema walks). The ref node itself is NOT marked\n * (the usage can be renamed/deleted).\n */\n readOnly?: boolean;\n children: PropertyNode[];\n}\n\n/** Classify a property into a tree kind. */\nexport function propertyKind(prop: JsonSchemaProperty): PropertyKind {\n if (prop.if) return \"conditional\";\n if (isOneOf(prop)) return \"oneOf\";\n if (prop.type === \"object\" && prop.properties) return \"object\";\n if (prop.type === \"array\") return \"array\";\n if (Array.isArray(prop.enum) && prop.enum.length > 0) return \"enum\";\n return \"scalar\";\n}\n\n// Cardinality inside the brackets, standard multiplicity notation:\n// [] -- unconstrained\n// [3] -- exactly 3 (min == max)\n// [1..5] -- between 1 and 5\n// [1..] -- at least 1\n// [..5] -- at most 5\nfunction arrayCardinality(\n min: number | undefined,\n max: number | undefined,\n): string {\n if (min == null && max == null) return \"\";\n if (min != null && min === max) return `${min}`;\n return `${min ?? \"\"}..${max ?? \"\"}`;\n}\n\n// The label of a union of types, or undefined when the property is not one --\n// notably the nullable pattern generators emit for an optional field (pydantic\n// `str | None` -> anyOf [string, null]; a `type: [\"string\", \"null\"]` array),\n// which reads as its members: \"string | null\". Conditional anyOf members\n// (if/then, FHIR enableWhen) are not a type union.\nfunction unionLabelOf(prop: JsonSchemaProperty): string | undefined {\n const members = prop.anyOf;\n if (\n Array.isArray(members) &&\n members.length > 0 &&\n members.every((m) => !m.if)\n ) {\n return members.map(typeLabelOf).join(\" | \");\n }\n const type: unknown = prop.type;\n return Array.isArray(type) ? type.join(\" | \") : undefined;\n}\n\nfunction typeLabelOf(prop: JsonSchemaProperty): string {\n if (prop.if) return \"if/then/else\";\n if (isOneOf(prop)) return \"oneOf\";\n const union = unionLabelOf(prop);\n if (union) return union;\n if (prop.type === \"array\") {\n const itemType = prop.items?.type ?? \"any\";\n // Compact array indicator (e.g. \"object[]\", \"object[1..5]\") so the type\n // descriptor stays short and does not crowd out the property name.\n return `${itemType}[${arrayCardinality(prop.minItems, prop.maxItems)}]`;\n }\n return prop.type ?? \"any\";\n}\n\n/** Order keys by explicit x-ui-order, then remaining declaration order. */\nexport function orderedKeys(\n properties: Record<string, JsonSchemaProperty>,\n order: string[] | undefined,\n): string[] {\n const keys = Object.keys(properties);\n if (!order || order.length === 0) return keys;\n const inOrder = order.filter((k) => k in properties);\n const rest = keys.filter((k) => !inOrder.includes(k));\n return [...inOrder, ...rest];\n}\n\n// The required-key list for a container property (object -> its required;\n// array-of-object -> items.required). Branches/oneOf have none.\nfunction requiredOf(prop: JsonSchemaProperty): string[] | undefined {\n if (prop.type === \"object\") return prop.required;\n if (prop.type === \"array\") return prop.items?.required;\n return undefined;\n}\n\n// The x-ui-order for a container property (object own, array via items).\nfunction orderOf(prop: JsonSchemaProperty): string[] | undefined {\n if (prop.type === \"array\") return prop.items?.[\"x-ui-order\"];\n return prop[\"x-ui-order\"];\n}\n\n// The tree kind of a node built from a slot. Branches and then/else slots are\n// anonymous object schemas (may omit `type`), shown as \"object\"; a conditional\n// member (the allOf if/then/else) is shown as \"conditional\".\nfunction nodeKind(slot: ChildSlot, prop: JsonSchemaProperty): PropertyKind {\n if (slot.kind === \"branch\") return \"object\";\n if (slot.segment.kind === \"def\") return \"definition\";\n if (slot.segment.kind === \"slot\") return \"object\"; // then / else / items\n return propertyKind(prop);\n}\n\n// The required-key list a container exposes to its property children. For a\n// then/else slot the required lives on the slot schema itself.\nfunction requiredForChildren(\n prop: JsonSchemaProperty,\n isSlot: boolean,\n): string[] | undefined {\n return isSlot ? prop.required : requiredOf(prop);\n}\n\n// Resolve a $ref node one level to its target for child display; undefined when\n// the node is not a ref or the ref cannot be resolved.\nfunction resolveRefTarget(\n prop: JsonSchemaProperty,\n resolve: RefResolver | undefined,\n): JsonSchemaProperty | undefined {\n if (!prop.$ref || !resolve) return undefined;\n const target = resolve(prop.$ref);\n if (!target) return undefined;\n // Merge node-level overrides (e.g. title) over the target, as the renderer does.\n const { $ref: _drop, ...overrides } = prop;\n return { ...target, ...overrides };\n}\n\n// How a node relates to a shared definition: a direct $ref, an array whose\n// items is a $ref, or neither. `container` is the schema whose child slots the\n// node exposes (the resolved target for refs, else the property itself).\ninterface RefShape {\n kind: PropertyKind;\n typeLabel: string;\n reference?: string;\n container: JsonSchemaProperty;\n // Whether this node's children come from a shared definition (read-only).\n childrenFromRef: boolean;\n}\n\n// Classify a property's relationship to a definition and derive its display.\nfunction refShapeOf(\n slot: ChildSlot,\n prop: JsonSchemaProperty,\n resolve: RefResolver | undefined,\n): RefShape {\n // A $ref node keeps its original property (with $ref) for identity/marker,\n // but its children come from the resolved target (read-only).\n const refTarget = resolveRefTarget(prop, resolve);\n if (refTarget) {\n return {\n kind: \"reference\",\n typeLabel: refLabel(prop.$ref!),\n reference: prop.$ref,\n container: refTarget,\n childrenFromRef: true,\n };\n }\n // An array-of-$ref surfaces the referenced element's fields as read-only\n // children while remaining an array node.\n if (prop.type === \"array\" && prop.items?.$ref) {\n const itemTarget = resolveRefTarget(prop.items, resolve);\n if (itemTarget) {\n return {\n kind: \"array\",\n typeLabel: arrayItemLabel(prop.items.$ref, prop),\n reference: prop.items.$ref,\n container: itemTarget,\n childrenFromRef: true,\n };\n }\n }\n return {\n kind: nodeKind(slot, prop),\n typeLabel: typeLabelOf(prop),\n container: prop,\n childrenFromRef: false,\n };\n}\n\nfunction buildNode(\n slot: ChildSlot,\n parentPath: PropertyPath,\n required: boolean,\n resolve: RefResolver | undefined,\n inRef: boolean,\n): PropertyNode {\n const path = [...parentPath, slot.segment];\n const prop = slot.property;\n const widget =\n typeof prop[\"x-ui-widget\"] === \"string\" ? prop[\"x-ui-widget\"] : undefined;\n const ref = refShapeOf(slot, prop, resolve);\n const node: PropertyNode = {\n path,\n key: slot.label,\n property: prop,\n kind: ref.kind,\n slotKind: slot.kind,\n required,\n typeLabel: ref.typeLabel,\n widget,\n reference: ref.reference,\n readOnly: inRef || undefined,\n children: [],\n };\n if (isContainer(ref.container)) {\n const isSlot = slot.segment.kind === \"slot\";\n const req = requiredForChildren(ref.container, isSlot);\n // Descendants of a $ref node (or of an already-read-only node) are read-only.\n const childrenInRef = inRef || ref.childrenFromRef;\n node.children = orderedSlots(ref.container).map((child) =>\n buildNode(\n child,\n path,\n child.kind === \"property\" ? !!req?.includes(child.label) : false,\n resolve,\n childrenInRef,\n ),\n );\n }\n return node;\n}\n\n// The definition name from a local $ref pointer (or the trailing URI segment).\nfunction refName(ref: string): string {\n const local = ref.match(/^#\\/(?:\\$defs|definitions)\\/(.+)$/);\n return local ? local[1] : ref.split(\"/\").pop() || ref;\n}\n\n// A compact label for a ref, e.g. \"#/$defs/Address\" -> \"-> Address\"; a registry\n// id or URI shows the trailing segment.\nfunction refLabel(ref: string): string {\n return `\\u2192 ${refName(ref)}`;\n}\n\n// A compact label for an array-of-$ref, e.g. \"Address[1..3]\".\nfunction arrayItemLabel(ref: string, prop: JsonSchemaProperty): string {\n return `${refName(ref)}[${arrayCardinality(prop.minItems, prop.maxItems)}]`;\n}\n\n// Child slots in display order. x-ui-order applies ONLY to property children\n// (keyed by property name); branch/conditional/definition slots keep their\n// positional order and follow the properties. Ordering is scoped to property\n// slots so a definition sharing a name with a property (both label \"vitals\")\n// cannot shadow the property (label is not a unique key across slot kinds).\nfunction orderedSlots(prop: JsonSchemaProperty): ChildSlot[] {\n const slots = childSlots(prop);\n const propertySlots = slots.filter((s) => s.kind === \"property\");\n const otherSlots = slots.filter((s) => s.kind !== \"property\");\n const order = orderOf(prop);\n if (propertySlots.length === 0 || !order || order.length === 0) return slots;\n const byLabel = new Map(propertySlots.map((s) => [s.label, s]));\n const inOrder = order\n .filter((k) => byLabel.has(k))\n .map((k) => byLabel.get(k)!);\n const rest = propertySlots.filter((s) => !order.includes(s.label));\n return [...inOrder, ...rest, ...otherSlots];\n}\n\n/**\n * Build the full property tree for a schema. Pass `resolve` to expand `$ref`\n * nodes (read-only) so referenced structure is legible; without it, ref nodes\n * show as leaves. `resolve` mirrors the renderer's RefResolver.\n */\nexport function buildPropertyTree(\n schema: JsonSchema,\n resolve?: RefResolver,\n): PropertyNode[] {\n // Default to an in-document $defs/definitions resolver so local refs expand\n // without the consumer wiring anything; an injected resolver (registry/URI)\n // is tried first and this is the fallback.\n const effective = withInDocumentFallback(schema, resolve);\n const rootProp = schemaAsRootProp(schema);\n return orderedSlots(rootProp).map((slot) =>\n buildNode(\n slot,\n [],\n !!schema.required?.includes(slot.label),\n effective,\n false,\n ),\n );\n}\n\n// Compose the injected resolver (if any) with an in-document $defs lookup.\nfunction withInDocumentFallback(\n schema: JsonSchema,\n resolve: RefResolver | undefined,\n): RefResolver | undefined {\n const defs = schema.$defs ?? schema.definitions;\n if (!defs) return resolve;\n const local: RefResolver = (ref) => {\n const m = ref.match(/^#\\/(?:\\$defs|definitions)\\/(.+)$/);\n return m ? defs[m[1]] : undefined;\n };\n return resolve ? (ref) => resolve(ref) ?? local(ref) : local;\n}\n\n/**\n * A layout scope: a container whose fields can be arranged into rows. Root is\n * the form itself (path []); nested scopes are object/array containers.\n */\nexport interface LayoutScope {\n /** Empty for root, otherwise the property path to the container. */\n path: PropertyPath;\n /** Human label, e.g. \"Form (root)\" or \"contact\" or \"addresses (items)\". */\n label: string;\n}\n\n/** Enumerate all layout scopes: the root form plus every object/array container. */\nexport function layoutScopes(schema: JsonSchema): LayoutScope[] {\n const scopes: LayoutScope[] = [{ path: [], label: \"Form (root)\" }];\n const walk = (nodes: PropertyNode[], labelPrefix: string[]) => {\n for (const node of nodes) {\n // Layout rows are keyed by property name within a property container.\n // Skip containers reached through a non-property segment (oneOf branch,\n // conditional member, then/else slot) -- their fields are not laid out\n // by the property-name-based row model.\n const allProps = node.path.every((s) => s.kind === \"prop\");\n if (allProps && (node.kind === \"object\" || node.kind === \"array\")) {\n const labels = [...labelPrefix, node.key];\n const suffix = node.kind === \"array\" ? \" (items)\" : \"\";\n scopes.push({\n path: node.path,\n label: labels.join(\" \\u203a \") + suffix,\n });\n walk(node.children, labels);\n }\n }\n };\n walk(buildPropertyTree(schema), []);\n return scopes;\n}\n","/**\n * Show only if -- when a question is asked: conditions on the answers to other\n * questions of its section, all of them or any. Pure, no React.\n *\n * In the schema a conditional item is an `allOf` member of its section,\n * `{ if, then: { properties: { <item> }, required } }`: the renderer adds the\n * item to the form while the `if` holds and removes it -- with its answer --\n * when it does not. \"All\" is one `if` testing every condition; \"any\" is an `if`\n * of `anyOf` single conditions. Each condition is the schema designer's\n * (model/conditions.ts). A member is understood only when writing back what\n * was read gives exactly the member: what the questionnaire designer cannot\n * show as conditions stays locked. See docs/design/questionnaires.md.\n */\n\nimport {\n bindingOf,\n codeToken,\n CODEABLE_CONCEPT_TYPE_ID,\n CODING_TYPE_ID,\n parseCodeToken,\n valueRefOf,\n type JsonSchemaProperty,\n} from \"@petrarca/sonnet-core/schema\";\nimport {\n conditionToIf,\n constraintToOperator,\n type Condition,\n} from \"../model/conditions\";\n\nexport type { Condition };\n\n/** When an item is shown: all of its conditions hold, or any of them. */\nexport interface ShowIf {\n behavior: \"all\" | \"any\";\n conditions: Condition[];\n}\n\n/** A section's field, by key -- the comparand is written as its type takes it. */\nexport type FieldType = (field: string) => JsonSchemaProperty | undefined;\n\n// Whether a field's answer is a coding -- or a coding or a text.\n// What a field's answer is when it is coded: a coding, or a codeable concept -- its codings, or its text.\ntype CodedKind = \"coding\" | \"concept\";\n\nfunction codedKind(\n field: JsonSchemaProperty | undefined,\n): CodedKind | undefined {\n const ref = field && valueRefOf(field)?.ref;\n if (ref === CODING_TYPE_ID) return \"coding\";\n return ref === CODEABLE_CONCEPT_TYPE_ID ? \"concept\" : undefined;\n}\n\n// A coded answer's code, as FHIR compares codings: by system and code, never\n// the label. The code is named alone, of the code system the binding names, or\n// as `system|code`; an object only, so that a text of one's own never matches.\nfunction codingIs(\n token: string,\n field: JsonSchemaProperty,\n): JsonSchemaProperty {\n const { system, code } = parseCodeToken(token, bindingOf(field)?.system);\n return {\n type: \"object\",\n properties: {\n ...(system ? { system: { const: system } } : {}),\n code: { const: code },\n },\n required: [\"code\"],\n };\n}\n\n// What one coded answer must be: its code -- or, on a question that also takes\n// a text, that text (a text never equals a coding). A codeable concept holds\n// when any of its codings is the code, or its text is the text.\nfunction codedIs(\n c: Condition,\n field: JsonSchemaProperty,\n kind: CodedKind,\n): JsonSchemaProperty {\n if (kind === \"coding\")\n return c.asText ? { const: c.value } : codingIs(c.value, field);\n return c.asText\n ? { properties: { text: { const: c.value } }, required: [\"text\"] }\n : {\n properties: { codings: { contains: codingIs(c.value, field) } },\n required: [\"codings\"],\n };\n}\n\n// The `if` of one condition: on a coded answer, its code or text -- one of\n// several answers, as FHIR's enableWhen takes any; else the condition's own.\nfunction conditionIf(\n c: Condition,\n field: JsonSchemaProperty | undefined,\n): JsonSchemaProperty | undefined {\n const kind = codedKind(field);\n if (!field || !kind || (c.operator !== \"=\" && c.operator !== \"!=\"))\n return conditionToIf(c, field?.type);\n const one = codedIs(c, field, kind);\n const is = valueRefOf(field)?.multiple ? { contains: one } : one;\n return {\n properties: { [c.field]: c.operator === \"=\" ? is : { not: is } },\n required: [c.field],\n };\n}\n\n// The code a coded answer's constraint names, as a token; undefined when it names none.\nfunction codeOf(\n is: JsonSchemaProperty,\n field: JsonSchemaProperty,\n): string | undefined {\n const code = is.properties?.code?.const;\n if (typeof code !== \"string\") return undefined;\n const system = is.properties?.system?.const;\n return codeToken(\n { system: typeof system === \"string\" ? system : undefined, code },\n bindingOf(field)?.system,\n );\n}\n\n// A codeable concept's constraint as a coding's: its codings' code, or its text's const.\nfunction asCodingConstraint(\n one: JsonSchemaProperty | undefined,\n): JsonSchemaProperty | undefined {\n const text = one?.properties?.text?.const;\n if (typeof text === \"string\") return { const: text };\n return one?.properties?.codings?.contains;\n}\n\n// The code or text one coded answer's constraint names; undefined for neither.\nfunction codedOf(\n constraint: JsonSchemaProperty | undefined,\n field: JsonSchemaProperty,\n kind: CodedKind,\n): Pick<Condition, \"value\" | \"asText\"> | undefined {\n const one = kind === \"concept\" ? asCodingConstraint(constraint) : constraint;\n if (!one) return undefined;\n if (typeof one.const === \"string\") return { value: one.const, asText: true };\n const value = codeOf(one, field);\n return value === undefined ? undefined : { value };\n}\n\n// The operator and code (or text) of a coded answer's constraint; undefined when it is not one.\nfunction readCoding(\n constraint: JsonSchemaProperty,\n field: JsonSchemaProperty | undefined,\n): Pick<Condition, \"operator\" | \"value\" | \"asText\"> | undefined {\n const kind = codedKind(field);\n if (!field || !kind) return undefined;\n const negated = constraint.not;\n const is = negated ?? constraint;\n const one = valueRefOf(field)?.multiple ? is.contains : is;\n const read = codedOf(one, field, kind);\n return read && { operator: negated ? \"!=\" : \"=\", ...read };\n}\n\n// The `if` of one condition, or of all of them together.\nfunction allIf(conditions: Condition[], typeOf: FieldType): JsonSchemaProperty {\n const properties: Record<string, JsonSchemaProperty> = {};\n const required: string[] = [];\n for (const c of conditions) {\n const one = conditionIf(c, typeOf(c.field));\n Object.assign(properties, one?.properties ?? {});\n for (const r of one?.required ?? [])\n if (!required.includes(r)) required.push(r);\n }\n return {\n ...(Object.keys(properties).length ? { properties } : {}),\n required,\n };\n}\n\n/** The `if` a show-if is written as. */\nexport function showIfToIf(\n showIf: ShowIf,\n typeOf: FieldType,\n): JsonSchemaProperty {\n if (showIf.behavior === \"any\" && showIf.conditions.length > 1) {\n return { anyOf: showIf.conditions.map((c) => allIf([c], typeOf)) };\n }\n return allIf(showIf.conditions, typeOf);\n}\n\n// The conditions an `if` of all of them names: one per field.\nfunction readAll(ifSchema: JsonSchemaProperty, typeOf: FieldType): Condition[] {\n const props = ifSchema.properties ?? {};\n const fields = [\n ...new Set([...Object.keys(props), ...(ifSchema.required ?? [])]),\n ];\n return fields.map((field) => {\n const constraint = props[field];\n if (!constraint) return { field, operator: \"exists\", value: \"\" };\n return {\n field,\n ...(readCoding(constraint, typeOf(field)) ??\n constraintToOperator(constraint)),\n };\n });\n}\n\nfunction readShowIf(ifSchema: JsonSchemaProperty, typeOf: FieldType): ShowIf {\n if (Array.isArray(ifSchema.anyOf)) {\n return {\n behavior: \"any\",\n conditions: ifSchema.anyOf.flatMap((m) => readAll(m, typeOf)),\n };\n }\n return { behavior: \"all\", conditions: readAll(ifSchema, typeOf) };\n}\n\n// JSON with object keys sorted: two schemas alike whatever their key order.\nfunction canonical(value: unknown): string {\n return JSON.stringify(value, (_, v) =>\n v && typeof v === \"object\" && !Array.isArray(v)\n ? Object.fromEntries(\n Object.keys(v)\n .sort()\n .map((k) => [k, v[k]]),\n )\n : v,\n );\n}\n\n/** A conditional member's `then`: the items it shows and which of them are required. */\nexport interface ConditionalItems {\n showIf: ShowIf;\n properties: Record<string, JsonSchemaProperty>;\n required: string[];\n}\n\n/**\n * The show-if of a section's `allOf` member and the items it shows, or null\n * when the member is not one the questionnaire designer understands -- its `if`\n * is more than conditions on the section's fields, or its `then` more than items.\n */\nexport function readConditional(\n member: JsonSchemaProperty,\n sectionKeys: ReadonlySet<string>,\n typeOf: FieldType,\n): ConditionalItems | null {\n const { if: ifSchema, then } = member;\n if (\n !ifSchema ||\n !then?.properties ||\n Object.keys(member).some((k) => k !== \"if\" && k !== \"then\")\n )\n return null;\n if (Object.keys(then).some((k) => k !== \"properties\" && k !== \"required\"))\n return null;\n const showIf = readShowIf(ifSchema, typeOf);\n if (showIf.conditions.length === 0) return null;\n if (showIf.conditions.some((c) => !sectionKeys.has(c.field))) return null;\n if (canonical(showIfToIf(showIf, typeOf)) !== canonical(ifSchema))\n return null;\n return { showIf, properties: then.properties, required: then.required ?? [] };\n}\n","/**\n * Condition builder: the bridge between a friendly (property, operator, value)\n * triple and the JSON Schema `if` sub-schema the renderer evaluates.\n *\n * An `if` tests a sibling property. Operators map to standard schema keywords\n * (mirrors the FHIR operator table in packages/sonnet-fhir/docs/design/fhir-questionnaire-adapter.md, tier 1):\n *\n * = -> { properties: { field: { const: value } }, required: [field] }\n * != -> { properties: { field: { not: { const: value } } }, required: [field] }\n * > >= < <= -> exclusiveMinimum / minimum / exclusiveMaximum / maximum\n * exists -> { required: [field] }\n *\n * A value operator always adds `required: [field]` so an absent field does not\n * vacuously satisfy the condition.\n */\n\nimport type { JsonSchemaProperty } from \"@petrarca/sonnet-core/schema\";\n\nexport type ConditionOperator = \"=\" | \"!=\" | \">\" | \">=\" | \"<\" | \"<=\" | \"exists\";\n\nexport const CONDITION_OPERATORS: readonly ConditionOperator[] = [\n \"=\",\n \"!=\",\n \">\",\n \">=\",\n \"<\",\n \"<=\",\n \"exists\",\n];\n\n/** Human labels for the operator dropdown. */\nexport const CONDITION_OPERATOR_LABELS: Record<ConditionOperator, string> = {\n \"=\": \"equals\",\n \"!=\": \"not equals\",\n \">\": \"greater than\",\n \">=\": \"greater or equal\",\n \"<\": \"less than\",\n \"<=\": \"less or equal\",\n exists: \"exists\",\n};\n\n/** Shared select-option list for the operator dropdown (ConditionEditor + RuleEditor). */\nexport const OPERATOR_OPTIONS: { value: ConditionOperator; label: string }[] =\n CONDITION_OPERATORS.map((op) => ({\n value: op,\n label: CONDITION_OPERATOR_LABELS[op],\n }));\n\n/** A condition as edited in the inspector. */\nexport interface Condition {\n field: string;\n operator: ConditionOperator;\n /** Raw string value from the inspector; coerced to number where numeric. */\n value: string;\n /** On a coded question that also takes a text: the value is that text, not a code. */\n asText?: boolean;\n}\n\n// Numeric operators need a numeric comparand.\nconst NUMERIC_OPS: ReadonlySet<ConditionOperator> = new Set([\n \">\",\n \">=\",\n \"<\",\n \"<=\",\n]);\n\n/** The JSON Schema type of the field a condition targets, when known. */\nexport type ScopeType = JsonSchemaProperty[\"type\"];\n\n// Coerce a string value to number when it is a finite numeric literal.\nfunction coerceValue(value: string): string | number {\n if (value.trim() === \"\") return value;\n const n = Number(value);\n return Number.isFinite(n) ? n : value;\n}\n\n/**\n * Coerce the editor's string value to the type the target field actually\n * holds. Without this a boolean field compared with the *string* \"true\" can\n * never match the boolean `true` the form produces -- the rule would be\n * authorable but silently dead.\n *\n * Numeric operators always compare numerically, whatever the declared type.\n */\nfunction coerceForScope(\n value: string,\n operator: ConditionOperator,\n type: ScopeType,\n): string | number | boolean {\n if (NUMERIC_OPS.has(operator)) return coerceValue(value);\n if (type === \"boolean\") return value === \"true\";\n if (type === \"number\" || type === \"integer\") return coerceValue(value);\n return value;\n}\n\n/**\n * The per-value constraint schema for an operator + value (e.g. \"=\" + \"female\"\n * -> { const: \"female\" }). This is the value-level building block shared by the\n * conditional `if` builder and the x-ui-rule builder. `exists` yields an empty\n * schema (presence is expressed by `required` at the caller).\n *\n * Pass the target field's `type` so the comparand is written with the type the\n * form data actually carries.\n */\nexport function operatorToConstraint(\n operator: ConditionOperator,\n value: string,\n type?: ScopeType,\n): JsonSchemaProperty {\n const v = coerceForScope(value, operator, type);\n switch (operator) {\n case \"=\":\n return { const: v };\n case \"!=\":\n return { not: { const: v } };\n case \">\":\n return { exclusiveMinimum: v as number };\n case \">=\":\n return { minimum: v as number };\n case \"<\":\n return { exclusiveMaximum: v as number };\n case \"<=\":\n return { maximum: v as number };\n case \"exists\":\n return {};\n }\n}\n\n/**\n * Build the `if` sub-schema for a condition. Returns undefined for no field.\n * Pass the field's `type` so the comparand matches the form data's type.\n */\nexport function conditionToIf(\n condition: Condition,\n type?: ScopeType,\n): JsonSchemaProperty | undefined {\n const { field, operator } = condition;\n if (!field) return undefined;\n if (operator === \"exists\") {\n return { required: [field] };\n }\n return {\n properties: {\n [field]: operatorToConstraint(operator, condition.value, type),\n },\n required: [field],\n };\n}\n\n/** Recover the operator + value from a per-value constraint schema. */\nexport function constraintToOperator(c: JsonSchemaProperty): {\n operator: ConditionOperator;\n value: string;\n} {\n if (c.not && \"const\" in c.not)\n return { operator: \"!=\", value: String(c.not.const) };\n if (c.exclusiveMinimum !== undefined)\n return { operator: \">\", value: String(c.exclusiveMinimum) };\n if (c.minimum !== undefined)\n return { operator: \">=\", value: String(c.minimum) };\n if (c.exclusiveMaximum !== undefined)\n return { operator: \"<\", value: String(c.exclusiveMaximum) };\n if (c.maximum !== undefined)\n return { operator: \"<=\", value: String(c.maximum) };\n if (\"const\" in c) return { operator: \"=\", value: String(c.const) };\n return { operator: \"exists\", value: \"\" };\n}\n\n/** Recover a Condition from an `if` sub-schema (inverse of conditionToIf). */\nexport function ifToCondition(\n ifSchema: JsonSchemaProperty | undefined,\n): Condition {\n const empty: Condition = { field: \"\", operator: \"=\", value: \"\" };\n if (!ifSchema) return empty;\n const props = ifSchema.properties ?? {};\n const field = Object.keys(props)[0] ?? ifSchema.required?.[0] ?? \"\";\n if (!field) return empty;\n const constraint = props[field];\n if (!constraint) return { field, operator: \"exists\", value: \"\" };\n const { operator, value } = constraintToOperator(constraint);\n return { field, operator, value };\n}\n","/**\n * Reasons for no answer -- *unknown*, *not applicable*: a statement about a\n * question instead of its answer. Pure, no React.\n *\n * A questionnaire declares its reasons once; every section then carries them\n * in its own `absent` property, an object of question keys whose values are\n * the declared reasons, so an answer keeps its type and a reason sits beside\n * it. A required question is required *unless* the section's `absent` names\n * it -- one conditional per question, `{ if: { not: <absent names it> }, then:\n * { required: [key] } }` -- so the form asks for an answer or a reason, and\n * the renderer enforces it. See docs/design/questionnaires.md, \"Reasons for no\n * answer\".\n */\n\nimport type { JsonSchemaProperty } from \"@petrarca/sonnet-core/schema\";\nimport type { ChoiceOption } from \"./classify\";\n\n/** The property of a section that holds its reasons. */\nexport const ABSENT_KEY = \"absent\";\n/** The widget a section's reasons are entered with. */\nexport const ABSENT_WIDGET = \"absent-reasons\";\n\n/** The `absent` property of a section: question keys to one of the reasons. */\nexport function absentProperty(reasons: ChoiceOption[]): JsonSchemaProperty {\n return {\n type: \"object\",\n title: \"Not answered\",\n additionalProperties: { type: \"string\", enum: reasons.map((r) => r.value) },\n \"x-ui-widget\": ABSENT_WIDGET,\n // A pick is final: the reasons apply at once, also in a deferred form.\n \"x-ui-options\": {\n enumNames: Object.fromEntries(reasons.map((r) => [r.value, r.label])),\n immediate: true,\n },\n } as JsonSchemaProperty;\n}\n\n/** The reasons an `absent` property declares; none when the property is not of that shape. */\nexport function readReasons(\n prop: JsonSchemaProperty | undefined,\n): ChoiceOption[] | undefined {\n const values = (prop?.additionalProperties as JsonSchemaProperty | undefined)\n ?.enum;\n if (!prop || !Array.isArray(values)) return undefined;\n const names =\n (prop[\"x-ui-options\"] as { enumNames?: Record<string, string> } | undefined)\n ?.enumNames ?? {};\n const reasons = values.map((v) => ({\n value: String(v),\n label: names[String(v)] ?? String(v),\n }));\n return JSON.stringify(prop) === JSON.stringify(absentProperty(reasons))\n ? reasons\n : undefined;\n}\n\n/** The conditional that makes a question required unless a reason is given for it. */\nexport function unlessReasonMember(key: string): JsonSchemaProperty {\n return {\n if: {\n not: {\n properties: { [ABSENT_KEY]: { required: [key] } },\n required: [ABSENT_KEY],\n },\n },\n then: { required: [key] },\n };\n}\n\n/** The question an \"unless a reason\" conditional makes required; none for another member. */\nexport function unlessReasonKey(\n member: JsonSchemaProperty,\n): string | undefined {\n const key = member.then?.required?.[0];\n return key !== undefined &&\n JSON.stringify(member) === JSON.stringify(unlessReasonMember(key))\n ? key\n : undefined;\n}\n\n/** The answers of one section: its values, and its reasons in `absent`. */\ntype SectionAnswers = Record<string, unknown> & {\n [ABSENT_KEY]?: Record<string, string>;\n};\n\n/** Whether a question has an answer or a reason in its section's answers. */\nexport function answeredOrExcused(\n answers: SectionAnswers | undefined,\n key: string,\n): boolean {\n const value = answers?.[key];\n const answered =\n value !== undefined &&\n value !== null &&\n value !== \"\" &&\n !(Array.isArray(value) && value.length === 0);\n return answered || answers?.[ABSENT_KEY]?.[key] !== undefined;\n}\n","/**\n * Questionnaire edits -- what the questionnaire designer does to the schema,\n * in the author's terms. Pure, no React; built on the schema designer's own\n * operations (model/mutate.ts), so both designers edit the same way.\n *\n * Every edit changes only what it touches: the rest of the schema, its\n * uiSchema and every keyword the designer does not understand stay as they\n * are. Changing an answer type is the one edit that can drop something; it\n * returns what it dropped, so the designer asks before applying it. See\n * docs/design/questionnaires.md, \"The boundary with the schema designer\".\n */\n\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n UISchema,\n} from \"@petrarca/sonnet-core/schema\";\nimport {\n addProperty,\n deleteProperty,\n getUiEntryAtPath,\n renameProperty,\n setEnum,\n setRequired as setRequiredOnParent,\n setUiEntry,\n updateProperty,\n type DesignerModel,\n} from \"../model/mutate\";\nimport {\n condition as conditionSeg,\n getProperty,\n isReservedKey,\n prop as propSeg,\n slot as slotSeg,\n type PropertyPath,\n} from \"../model/paths\";\nimport {\n answerTypeFragment,\n choiceTextWhen,\n embeddedHints,\n isContainerType,\n otherTextMember,\n rawChoiceAndText,\n recognizeAnswerType,\n type AnswerType,\n} from \"./answerTypes\";\nimport {\n classifyQuestionnaire,\n containerFields,\n containerOrder,\n itemsOf,\n optionsOf,\n type ChoiceOption,\n type QuestionnaireItem,\n} from \"./classify\";\nimport { showIfToIf, type ShowIf } from \"./showIf\";\nimport {\n DEFAULT_VALUE_TYPES,\n valueTypeAnswer,\n type ValueTypeAnswer,\n} from \"./valueTypes\";\nimport { LIMIT_LABELS, limitsFor, limitsOf, type LimitKeyword } from \"./limits\";\nimport {\n ABSENT_KEY,\n absentProperty,\n readReasons,\n unlessReasonKey,\n unlessReasonMember,\n} from \"./reasons\";\n\n/** What an author adds: a question of an answer type, a text, or a section. */\nexport type NewItem =\n | { kind: \"question\"; answerType: AnswerType }\n | { kind: \"text\" }\n | { kind: \"section\" };\n\nconst KEY_RE = /^[a-z][a-z0-9_]*$/;\nconst MAX_KEY_LENGTH = 40;\n\n/** A key from a question's text: lower case, words joined by `_`, unique among `taken`. */\nexport function keyFromText(text: string, taken: Iterable<string>): string {\n const base =\n text\n .replace(/ß/g, \"ss\")\n .normalize(\"NFKD\")\n .replace(/[̀-ͯ]/g, \"\")\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\")\n .replace(/^(\\d)/, \"q_$1\")\n .slice(0, MAX_KEY_LENGTH)\n // Cut short, a key could end in \"_\": trimmed after the cut.\n .replace(/_+$/, \"\") || \"question\";\n const used = new Set(taken);\n if (!used.has(base)) return base;\n let i = 2;\n while (used.has(`${base}_${i}`)) i++;\n return `${base}_${i}`;\n}\n\n/** Whether a key may be set: lower case letters, digits and `_`, starting with a letter. */\nexport function isValidKey(key: string): boolean {\n return KEY_RE.test(key) && !isReservedKey(key);\n}\n\n// The properties of the container at a path (the root when empty; an array's items).\nfunction containerProperties(\n model: DesignerModel,\n path: PropertyPath,\n): Record<string, JsonSchemaProperty> {\n if (path.length === 0) return model.schema.properties ?? {};\n const owner = getProperty(model.schema, path);\n const target = owner?.type === \"array\" ? owner.items : owner;\n return target?.properties ?? {};\n}\n\n// The hints a property has at a path: its uiSchema entry over its embedded hints.\nfunction hintsAt(model: DesignerModel, path: PropertyPath): UISchema {\n const prop = getProperty(model.schema, path);\n return {\n ...(prop ? embeddedHints(prop) : {}),\n ...getUiEntryAtPath(model.uiSchema, path),\n };\n}\n\n// Replace the property at a path whole: keys absent from `next` are removed.\nfunction replaceProperty(\n model: DesignerModel,\n path: PropertyPath,\n next: JsonSchemaProperty,\n): DesignerModel {\n const current = getProperty(model.schema, path);\n if (!current) return model;\n const patch: Partial<JsonSchemaProperty> = Object.fromEntries(\n Object.keys(current).map((k) => [k, undefined]),\n );\n return updateProperty(model, path, { ...patch, ...next });\n}\n\n// The schema and hints a new item starts with.\nfunction newItemFragment(\n item: NewItem,\n text: string,\n): { prop: JsonSchemaProperty; ui: UISchema } {\n if (item.kind === \"text\")\n return { prop: { type: \"null\", title: text }, ui: {} };\n if (item.kind === \"section\")\n return { prop: { type: \"object\", title: text, properties: {} }, ui: {} };\n const fragment = answerTypeFragment(item.answerType);\n return { prop: { ...fragment.prop, title: text }, ui: fragment.ui };\n}\n\n/** Add a question, a text or a section at the end of a container; its key from its text. */\nexport function addItem(\n model: DesignerModel,\n parentPath: PropertyPath,\n item: NewItem,\n text: string,\n): { model: DesignerModel; path: PropertyPath } {\n const key = keyFromText(\n text,\n Object.keys(containerProperties(model, parentPath)),\n );\n const added = addProperty(model, parentPath, \"scalar\");\n if (added.path === parentPath) return { model, path: parentPath };\n const renamed = renameProperty(added.model, added.path, key);\n const { prop, ui } = newItemFragment(item, text);\n const replaced = replaceProperty(renamed.model, renamed.path, prop);\n const withUi = Object.keys(ui).length\n ? setUiEntry(replaced, renamed.path, ui)\n : replaced;\n // A new section carries the questionnaire's reasons for no answer.\n const reasons = declaredReasons(withUi);\n if (item.kind !== \"section\" || !reasons)\n return { model: withUi, path: renamed.path };\n const section = { ...getProperty(withUi.schema, renamed.path)! };\n section.properties = {\n ...section.properties,\n [ABSENT_KEY]: absentProperty(reasons),\n };\n return {\n model: updateProperty(withUi, renamed.path, {\n properties: section.properties,\n }),\n path: renamed.path,\n };\n}\n\n/** Set a question's, a section's or a text's heading. */\nexport function setItemText(\n model: DesignerModel,\n path: PropertyPath,\n text: string,\n): DesignerModel {\n return updateProperty(model, path, { title: text || undefined });\n}\n\n/** Set a question's help, a section's introduction, a text's body. */\nexport function setHelp(\n model: DesignerModel,\n path: PropertyPath,\n help: string,\n): DesignerModel {\n return updateProperty(model, path, { description: help || undefined });\n}\n\n/** Set whether a question is shown, not entered. */\nexport function setReadOnly(\n model: DesignerModel,\n path: PropertyPath,\n readOnly: boolean,\n): DesignerModel {\n return updateProperty(model, path, { readOnly: readOnly || undefined });\n}\n\n// Set (or clear) one hint in the uiSchema entry at a path.\nfunction setHint(\n model: DesignerModel,\n path: PropertyPath,\n key: string,\n value: unknown,\n): DesignerModel {\n const entry: UISchema = { ...getUiEntryAtPath(model.uiSchema, path) };\n if (value === undefined || value === \"\")\n delete (entry as Record<string, unknown>)[key];\n else (entry as Record<string, unknown>)[key] = value;\n return setUiEntry(model, path, Object.keys(entry).length ? entry : undefined);\n}\n\n/** Set how a question is shown -- a widget its answer type knows (`radio`, `select`, ...); undefined: its default. */\nexport function setPresentation(\n model: DesignerModel,\n path: PropertyPath,\n widget: string | undefined,\n): DesignerModel {\n return setHint(model, path, \"x-ui-widget\", widget);\n}\n\n// Whether a value is no answer: none, an empty text, an empty list.\nconst isEmptyAnswer = (value: unknown) =>\n value === undefined ||\n value === null ||\n value === \"\" ||\n (Array.isArray(value) && value.length === 0);\n\n/**\n * Set a question's default answer (`default`): given until the person\n * answers, which they may change. An empty one removes it.\n */\nexport function setDefaultAnswer(\n model: DesignerModel,\n path: PropertyPath,\n value: unknown,\n): DesignerModel {\n return updateProperty(model, path, {\n default: isEmptyAnswer(value) ? undefined : value,\n });\n}\n\n/** Set a question's example: shown in the empty field, never stored. */\nexport function setPlaceholder(\n model: DesignerModel,\n path: PropertyPath,\n example: string,\n): DesignerModel {\n return setHint(model, path, \"x-ui-placeholder\", example);\n}\n\n/** Set an item's key; refused (the model unchanged) when the key is invalid or taken. */\nexport function setKey(\n model: DesignerModel,\n path: PropertyPath,\n key: string,\n): { model: DesignerModel; path: PropertyPath } {\n const { containerPath, key: prev } = locate(path);\n const container = containerAt(model.schema, containerPath);\n if (!isValidKey(key) || !container || containerOrder(container).includes(key))\n return { model, path };\n const renamed = renameProperty(model, path, key);\n if (renamed.path === path) return { model, path };\n // The section's order and its conditions name the item by its key.\n const target = containerAt(renamed.model.schema, containerPath)!;\n if (target[\"x-ui-order\"])\n target[\"x-ui-order\"] = target[\"x-ui-order\"].map((k) =>\n k === prev ? key : k,\n );\n renameInConditions(target, prev, key);\n if (removeUnlessReason(target, prev))\n target.allOf = [...(target.allOf ?? []), unlessReasonMember(key)];\n return renamed;\n}\n\n// Where a choice's enum lives: the property, its items, or a choice with text's `choice`.\nfunction choicePath(\n model: DesignerModel,\n path: PropertyPath,\n): { path: PropertyPath; onItems: boolean } {\n const prop = getProperty(model.schema, path);\n if (prop?.type === \"object\")\n return { path: [...path, propSeg(\"choice\")], onItems: false };\n return { path, onItems: prop?.type === \"array\" };\n}\n\n/** Set a choice's options, in order: their values in the schema, their labels as hints. */\nexport function setOptions(\n model: DesignerModel,\n path: PropertyPath,\n options: ChoiceOption[],\n): DesignerModel {\n // The option that asks for a choice with text's text goes: the text becomes a note again.\n const prop = getProperty(model.schema, path);\n const when = prop?.type === \"object\" ? choiceTextWhen(prop) : undefined;\n if (when !== undefined && !options.some((o) => o.value === when)) {\n return setOptions(setChoiceTextWhen(model, path, null), path, options);\n }\n const target = choicePath(model, path);\n const choices = options.map((o) => ({\n value: o.value,\n label: o.label === o.value ? \"\" : o.label,\n }));\n if (!target.onItems) return setEnum(model, target.path, choices);\n return setItemsOptions(model, path, options, choices);\n}\n\nconst CHOICE_TYPES: AnswerType[] = [\n \"singleChoice\",\n \"multipleChoice\",\n \"choiceWithText\",\n];\n// Hints a question keeps whatever its answer type.\nconst KEPT_HINTS = [\"x-ui-title\", \"x-ui-description\", \"x-ui-placeholder\"];\n\n/** The result of changing an answer type: the new model, and what it dropped. */\nexport interface AnswerTypeChange {\n model: DesignerModel;\n /** Settings the new type does not take -- a `pattern`, an unknown widget, the options. */\n lost: string[];\n}\n\n/**\n * Change a question's answer type. Its text, help, example and read-only flag\n * stay; options move from one kind of choice to another. What the new type does\n * not take is dropped and named in `lost` -- the designer asks before applying.\n */\nexport function changeAnswerType(\n model: DesignerModel,\n path: PropertyPath,\n type: AnswerType,\n types: readonly ValueTypeAnswer[] = DEFAULT_VALUE_TYPES,\n // Keywords that do not depend on the answer type -- an application's\n // annotations, a converter's linkId -- kept, not lost.\n keep: readonly string[] = [],\n): AnswerTypeChange {\n const current = currentAnswer(model, path, types);\n if (!current || current.type === type) return { model, lost: [] };\n const { prop, options, extras } = current;\n // Options -- a choice's only -- move to another kind of choice.\n const keepOptions = CHOICE_TYPES.includes(type) && options.length > 0;\n const limits = limitsAcross(prop, current.type, type);\n const rewritten = rewriteAs(\n model,\n path,\n prop,\n type,\n keepOptions ? options : [],\n [...limits.kept, ...keep],\n );\n const dropped = extras.filter((e) => !keep.includes(e));\n return {\n model: keepOptions ? setOptions(rewritten, path, options) : rewritten,\n lost: [\n ...lostSettings(model, path, dropped, options.length > 0 && !keepOptions),\n ...limits.lost,\n ...lostDefault(prop, current.type),\n ],\n };\n}\n\n// A question's default answer across a change of type: an answer of the old\n// type is none of the new one's, so it goes, named. A container's is an extra.\nfunction lostDefault(\n prop: JsonSchemaProperty,\n from: AnswerType | undefined,\n): string[] {\n return from && !isContainerType(from) && prop.default !== undefined\n ? [\"default answer\"]\n : [];\n}\n\n// A question's limits across a change of type: the ones both take stay, the others go, named.\nfunction limitsAcross(\n prop: JsonSchemaProperty,\n from: AnswerType | undefined,\n to: AnswerType,\n): { kept: string[]; lost: string[] } {\n const limits = Object.keys(from ? limitsOf(prop, from) : {});\n const kept = limits.filter((k) => limitsFor(to).includes(k as LimitKeyword));\n return {\n kept,\n lost: limits\n .filter((k) => !kept.includes(k))\n .map((k) => LIMIT_LABELS[k as LimitKeyword].toLowerCase()),\n };\n}\n\n// The question at a path as it stands: its property, its answer type (if it\n// has one), its options and extras.\nfunction currentAnswer(\n model: DesignerModel,\n path: PropertyPath,\n types: readonly ValueTypeAnswer[],\n): {\n prop: JsonSchemaProperty;\n type?: AnswerType;\n options: ChoiceOption[];\n extras: string[];\n} | null {\n const prop = getProperty(model.schema, path);\n if (!prop) return null;\n const hints = hintsAt(model, path);\n const answer = recognizeAnswerType(prop, hints, types);\n if (!answer) return { prop, options: [], extras: [] };\n return {\n prop,\n type: answer.type,\n options: optionsOf(prop, hints, answer.type) ?? [],\n extras: [...answer.extras, ...settingsSet(prop, hints, answer.type, types)],\n };\n}\n\n// A value type's settings that have a value, by their fields' titles: what a change of type drops.\nfunction settingsSet(\n prop: JsonSchemaProperty,\n hints: UISchema,\n type: AnswerType,\n types: readonly ValueTypeAnswer[],\n): string[] {\n const settings = valueTypeAnswer(type, types)?.settings;\n if (!settings) return [];\n return Object.entries(settings.read(prop, hints))\n .filter(([, v]) => (Array.isArray(v) ? v.length > 0 : v !== undefined))\n .map(([k]) => (settings.fields[k]?.title ?? k).toLowerCase());\n}\n\n// The question at a path rewritten as an answer type: the type's fragment, with\n// the question's text, help, example, read-only flag -- and the keywords asked\n// to be kept (limits it still takes, annotations of no type) -- kept.\nfunction rewriteAs(\n model: DesignerModel,\n path: PropertyPath,\n prop: JsonSchemaProperty,\n type: AnswerType,\n options: ChoiceOption[],\n limits: string[],\n): DesignerModel {\n const fragment = answerTypeFragment(\n type,\n options.length ? options.map((o) => o.value) : undefined,\n );\n const next: JsonSchemaProperty = {\n ...fragment.prop,\n ...pick(prop, [\"title\", \"description\", \"readOnly\", ...limits]),\n ...pick(prop as Record<string, unknown>, KEPT_HINTS),\n };\n const ui: UISchema = {\n ...fragment.ui,\n ...pick(getUiEntryAtPath(model.uiSchema, path) ?? {}, KEPT_HINTS),\n };\n return setUiEntry(\n replaceProperty(model, path, next),\n path,\n Object.keys(ui).length ? ui : undefined,\n );\n}\n\n// What a change of answer type drops: the old type's extras, its options when\n// the new type takes none, a container's children's own hints.\nfunction lostSettings(\n model: DesignerModel,\n path: PropertyPath,\n extras: string[],\n optionsDropped: boolean,\n): string[] {\n const childHints = getUiEntryAtPath(model.uiSchema, path)?.[\"x-ui-fields\"]\n ? [\"the parts' settings\"]\n : [];\n return [...extras, ...(optionsDropped ? [\"options\"] : []), ...childHints];\n}\n\nfunction pick<T extends object>(obj: T, keys: string[]): Partial<T> {\n return Object.fromEntries(\n Object.entries(obj).filter(([k]) => keys.includes(k)),\n ) as Partial<T>;\n}\n\n/**\n * Set keywords the questionnaire designer keeps but does not edit itself -- a\n * converter's annotations, say -- on an item, or (an empty path) on the\n * questionnaire; an undefined value removes one.\n */\nexport function setKeywords(\n model: DesignerModel,\n path: PropertyPath,\n keywords: Record<string, unknown>,\n): DesignerModel {\n if (path.length > 0)\n return updateProperty(model, path, keywords as Partial<JsonSchemaProperty>);\n const schema = { ...model.schema } as Record<string, unknown>;\n for (const [k, v] of Object.entries(keywords)) {\n if (v === undefined) delete schema[k];\n else schema[k] = v;\n }\n return { schema: schema as JsonSchema, uiSchema: model.uiSchema };\n}\n\n// A section's own keywords: what a repeating section keeps on its list, not its entries.\nconst SECTION_OWN = [\"title\", \"description\", \"readOnly\"];\n\n/**\n * Set whether a section repeats -- a list of entries, each with the section's\n * items. Its items keep their paths: the list's entries are its container.\n */\nexport function setSectionRepeats(\n model: DesignerModel,\n path: PropertyPath,\n repeats: boolean,\n): DesignerModel {\n const prop = getProperty(model.schema, path);\n if (!prop || (prop.type === \"array\") === repeats) return model;\n const outer = repeats ? prop : (prop.items ?? {});\n const own = pick(prop, SECTION_OWN);\n const { type: _, ...body } = Object.fromEntries(\n Object.entries(outer).filter(([k]) => !SECTION_OWN.includes(k)),\n ) as JsonSchemaProperty;\n const next: JsonSchemaProperty = repeats\n ? { type: \"array\", ...own, items: { type: \"object\", ...body } }\n : { ...own, type: \"object\", ...body };\n return replaceProperty(model, path, next);\n}\n\n/** Set one of a question's limits -- its length, pattern, range or count; undefined or empty removes it. */\nexport function setLimit(\n model: DesignerModel,\n path: PropertyPath,\n keyword: LimitKeyword,\n value: number | string | undefined,\n): DesignerModel {\n return updateProperty(model, path, {\n [keyword]: value === \"\" || value === null ? undefined : value,\n } as Partial<JsonSchemaProperty>);\n}\n\n/** Set the questionnaire's own title or introduction (the root's title and description). */\nexport function setQuestionnaireText(\n model: DesignerModel,\n text: { title?: string; description?: string },\n): DesignerModel {\n const schema = { ...model.schema };\n if (text.title !== undefined) schema.title = text.title;\n if (text.description !== undefined) {\n if (text.description) schema.description = text.description;\n else delete schema.description;\n }\n return { schema, uiSchema: model.uiSchema };\n}\n\n// -- Show only if, order, and the conditionals' bookkeeping --------------------\n\ntype Container = JsonSchemaProperty & { allOf?: JsonSchemaProperty[] };\n\n/** The path of the section an item is in -- the same for its conditional siblings. */\nexport function sectionPathOf(path: PropertyPath): PropertyPath {\n return locate(path).containerPath;\n}\n\n// Where an item lives: its container's path, and the conditional member holding\n// it (its allOf index), if any.\nfunction locate(path: PropertyPath): {\n containerPath: PropertyPath;\n member?: number;\n key: string;\n} {\n const key = (path[path.length - 1] as { key: string }).key;\n const c = path[path.length - 3];\n if (path.length >= 3 && c?.kind === \"condition\" && c.combinator === \"allOf\") {\n return { containerPath: path.slice(0, -3), member: c.index, key };\n }\n return { containerPath: path.slice(0, -1), key };\n}\n\n// The mutable container at a path in a schema: the root, an object, an array's items.\nfunction containerAt(\n schema: JsonSchema,\n path: PropertyPath,\n): Container | undefined {\n if (path.length === 0) return schema as unknown as Container;\n const owner = getProperty(schema, path);\n return owner?.type === \"array\" ? owner.items : owner;\n}\n\n// Remove a key from a list, dropping the list when it empties.\nfunction withoutKey(\n obj: Record<string, unknown>,\n list: string,\n key: string,\n): void {\n const values = (obj[list] as string[] | undefined)?.filter((k) => k !== key);\n if (values?.length) obj[list] = values;\n else delete obj[list];\n}\n\n// A conditional member that shows nothing any more is removed.\nfunction dropEmptyMember(container: Container, index: number): void {\n const member = container.allOf?.[index];\n if (!member || Object.keys(member.then?.properties ?? {}).length > 0) return;\n container.allOf!.splice(index, 1);\n if (container.allOf!.length === 0) delete container.allOf;\n}\n\n/**\n * Show an item only if conditions hold, or (null) always. The item keeps its\n * key, its place in the section's order and its hints; it moves into a\n * conditional of its own -- or back among the section's properties.\n */\nexport function setShowIf(\n model: DesignerModel,\n path: PropertyPath,\n showIf: ShowIf | null,\n): { model: DesignerModel; path: PropertyPath } {\n const schema = structuredClone(model.schema);\n const { containerPath, member, key } = locate(path);\n const container = containerAt(schema, containerPath);\n const item = getProperty(schema, path);\n if (!container || !item) return { model, path };\n // A conditional of its own: its condition changes in place, the item stays put.\n if (rewriteOwnCondition(container, member, showIf)) {\n return { model: { schema, uiSchema: model.uiSchema }, path };\n }\n // Keep the item's place: the order is written out before the item moves.\n container[\"x-ui-order\"] = containerOrder(container);\n const required = takeOut(container, member, key);\n if (required === null) return { model, path };\n const next = { schema, uiSchema: model.uiSchema };\n if (!showIf || showIf.conditions.length === 0) {\n container.properties = { ...(container.properties ?? {}), [key]: item };\n if (required) container.required = [...(container.required ?? []), key];\n return { model: next, path: [...containerPath, propSeg(key)] };\n }\n const index = putConditional(container, key, item, required, showIf);\n return {\n model: next,\n path: [\n ...containerPath,\n conditionSeg(index, \"allOf\"),\n slotSeg(\"then\"),\n propSeg(key),\n ],\n };\n}\n\n// Rewrite the condition of a conditional that shows the item alone; whether it did.\nfunction rewriteOwnCondition(\n container: Container,\n member: number | undefined,\n showIf: ShowIf | null,\n): boolean {\n const own = member === undefined ? undefined : container.allOf?.[member];\n if (\n !own ||\n !showIf?.conditions.length ||\n Object.keys(own.then?.properties ?? {}).length !== 1\n )\n return false;\n own.if = showIfToIf(showIf, (field) => containerFields(container)[field]);\n return true;\n}\n\n// Take an item out of where it is -- the container's properties or a\n// conditional's `then`; whether it was required, or null when it is not there.\nfunction takeOut(\n container: Container,\n member: number | undefined,\n key: string,\n): boolean | null {\n const holder =\n member === undefined ? container : container.allOf?.[member]?.then;\n if (!holder?.properties?.[key]) return null;\n const required = holder.required?.includes(key) ?? false;\n delete holder.properties[key];\n withoutKey(holder as Record<string, unknown>, \"required\", key);\n if (member !== undefined) dropEmptyMember(container, member);\n return required;\n}\n\n// Put an item into a conditional of its own; the conditional's index.\nfunction putConditional(\n container: Container,\n key: string,\n item: JsonSchemaProperty,\n required: boolean,\n showIf: ShowIf,\n): number {\n const typeOf = (field: string) => containerFields(container)[field];\n const conditional: JsonSchemaProperty = {\n if: showIfToIf(showIf, typeOf),\n then: {\n properties: { [key]: item },\n ...(required ? { required: [key] } : {}),\n },\n };\n container.allOf = [...(container.allOf ?? []), conditional];\n return container.allOf.length - 1;\n}\n\n/** Move an item up (-1) or down (+1) among its section's items -- conditional ones included. */\nexport function moveItem(\n model: DesignerModel,\n path: PropertyPath,\n direction: -1 | 1,\n): DesignerModel {\n const schema = structuredClone(model.schema);\n const { containerPath, key } = locate(path);\n const container = containerAt(schema, containerPath);\n if (!container) return model;\n const order = containerOrder(container);\n const i = order.indexOf(key);\n const j = i + direction;\n if (i < 0 || j < 0 || j >= order.length) return model;\n [order[i], order[j]] = [order[j], order[i]];\n container[\"x-ui-order\"] = order;\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Put an item before another of its section (by key), or last (null) -- dragging it there. */\nexport function reorderItem(\n model: DesignerModel,\n path: PropertyPath,\n beforeKey: string | null,\n): DesignerModel {\n const schema = structuredClone(model.schema);\n const { containerPath, key } = locate(path);\n const container = containerAt(schema, containerPath);\n if (!container || key === beforeKey) return model;\n const order = containerOrder(container).filter((k) => k !== key);\n const at = beforeKey === null ? order.length : order.indexOf(beforeKey);\n if (at < 0) return model;\n order.splice(at, 0, key);\n container[\"x-ui-order\"] = order;\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Delete an item: its definition, its hints, its place in the order -- and its conditional, once empty. */\nexport function deleteItem(\n model: DesignerModel,\n path: PropertyPath,\n): DesignerModel {\n const deleted = deleteProperty(model, path);\n if (deleted === model) return model;\n const { containerPath, member, key } = locate(path);\n const container = containerAt(deleted.schema, containerPath);\n if (!container) return deleted;\n withoutKey(container as Record<string, unknown>, \"x-ui-order\", key);\n if (member !== undefined) dropEmptyMember(container, member);\n else removeUnlessReason(container, key);\n return deleted;\n}\n\n// Rename a field wherever a container's conditions test it.\nfunction renameInConditions(\n container: Container,\n prev: string,\n next: string,\n): void {\n const renameIn = (ifSchema: JsonSchemaProperty | undefined) => {\n if (!ifSchema) return;\n if (ifSchema.properties && prev in ifSchema.properties) {\n ifSchema.properties = Object.fromEntries(\n Object.entries(ifSchema.properties).map(([k, v]) => [\n k === prev ? next : k,\n v,\n ]),\n );\n }\n if (ifSchema.required)\n ifSchema.required = ifSchema.required.map((k) => (k === prev ? next : k));\n ifSchema.anyOf?.forEach(renameIn);\n };\n container.allOf?.forEach((m) => renameIn(m.if));\n}\n\n// A multiple choice's options: the values on its items, the labels on the property itself.\nfunction setItemsOptions(\n model: DesignerModel,\n path: PropertyPath,\n options: ChoiceOption[],\n choices: { value: string; label: string }[],\n): DesignerModel {\n const prop = getProperty(model.schema, path);\n const items = {\n ...(prop?.items ?? { type: \"string\" as const }),\n enum: options.map((o) => o.value),\n };\n const withValues = updateProperty(model, path, { items });\n const labels = Object.fromEntries(\n choices.filter((c) => c.label).map((c) => [c.value, c.label]),\n );\n const current =\n (getUiEntryAtPath(withValues.uiSchema, path)?.[\"x-ui-options\"] as Record<\n string,\n unknown\n >) ?? {};\n const { enumNames: _, ...rest } = current;\n const next = Object.keys(labels).length\n ? { ...rest, enumNames: labels }\n : rest;\n return setHint(\n withValues,\n path,\n \"x-ui-options\",\n Object.keys(next).length ? next : undefined,\n );\n}\n\n/**\n * Set a value type's settings on its question -- the quantity's units -- as its\n * contribution writes them: keywords beside the `$ref`, `x-ui-options` keys.\n */\nexport function setValueTypeSettings(\n model: DesignerModel,\n path: PropertyPath,\n answer: ValueTypeAnswer,\n values: Record<string, unknown>,\n): DesignerModel {\n if (!answer.settings) return model;\n const written = answer.settings.write(values);\n const withProp = updateProperty(model, path, written.prop);\n const current =\n (getUiEntryAtPath(withProp.uiSchema, path)?.[\"x-ui-options\"] as Record<\n string,\n unknown\n >) ?? {};\n const next = { ...current };\n for (const [k, v] of Object.entries(written.options)) {\n if (v === undefined) delete next[k];\n else next[k] = v;\n }\n return setHint(\n withProp,\n path,\n \"x-ui-options\",\n Object.keys(next).length ? next : undefined,\n );\n}\n\n/** The option a choice with text's \"other\" variant adds when its options have none. */\nexport const OTHER_OPTION = { value: \"other\", label: \"Other\" };\n\n/**\n * Set what a choice with text's text is: a note, always offered (null), or\n * asked for only when the choice is one option -- \"other, please describe\" --\n * and then required. Switching to the latter adds an \"other\" option when the\n * choice has none; the text keeps its definition either way.\n */\nexport function setChoiceTextWhen(\n model: DesignerModel,\n path: PropertyPath,\n when: string | null,\n): DesignerModel {\n const prop = getProperty(model.schema, path);\n const { choice, text } = prop ? rawChoiceAndText(prop) : {};\n if (!prop || !choice || !text) return model;\n if (when === null) {\n return updateProperty(model, path, {\n properties: { choice, text },\n allOf: undefined,\n });\n }\n const { model: withOption, value } = withAskingOption(\n model,\n path,\n prop,\n when,\n );\n const nextChoice = getProperty(withOption.schema, [\n ...path,\n propSeg(\"choice\"),\n ])!;\n return updateProperty(withOption, path, {\n properties: { choice: nextChoice },\n allOf: [otherTextMember(value, text)],\n });\n}\n\n// The option that asks for the text: `when` when the choice has it, else an\n// \"other\" option, added.\nfunction withAskingOption(\n model: DesignerModel,\n path: PropertyPath,\n prop: JsonSchemaProperty,\n when: string,\n): { model: DesignerModel; value: string } {\n const options = optionsOf(prop, hintsAt(model, path), \"choiceWithText\") ?? [];\n if (options.some((o) => o.value === when)) return { model, value: when };\n if (options.some((o) => o.value === OTHER_OPTION.value))\n return { model, value: OTHER_OPTION.value };\n return {\n model: setOptions(model, path, [...options, OTHER_OPTION]),\n value: OTHER_OPTION.value,\n };\n}\n\n// -- Reasons for no answer ---------------------------------------------------------\n\n/** The reasons the questionnaire declares (its root's `absent`); none: every question is answered. */\nexport function declaredReasons(\n model: DesignerModel,\n): ChoiceOption[] | undefined {\n return readReasons(model.schema.properties?.[ABSENT_KEY]);\n}\n\n// Remove a question's \"required unless a reason\" conditional; whether it had one.\nfunction removeUnlessReason(container: Container, key: string): boolean {\n const index = (container.allOf ?? []).findIndex(\n (m) => unlessReasonKey(m) === key,\n );\n if (index < 0) return false;\n container.allOf!.splice(index, 1);\n if (container.allOf!.length === 0) delete container.allOf;\n return true;\n}\n\n/**\n * Set whether a question must be answered. With reasons declared, an always\n * asked question is required unless a reason is given for it; a conditional\n * one, and any question without reasons, is plainly required.\n */\nexport function setQuestionRequired(\n model: DesignerModel,\n path: PropertyPath,\n required: boolean,\n): DesignerModel {\n const { containerPath, member, key } = locate(path);\n if (member !== undefined || !declaredReasons(model))\n return setRequiredOnParent(model, path, required);\n const schema = structuredClone(model.schema);\n const container = containerAt(schema, containerPath);\n if (!container) return model;\n removeUnlessReason(container, key);\n withoutKey(container as Record<string, unknown>, \"required\", key);\n if (required)\n container.allOf = [...(container.allOf ?? []), unlessReasonMember(key)];\n return { schema, uiSchema: model.uiSchema };\n}\n\n// The paths of a questionnaire's sections, the root first: where reasons live.\nfunction sectionPaths(items: QuestionnaireItem[]): PropertyPath[] {\n return itemsOf(items)\n .filter((i) => i.kind === \"section\")\n .map((i) => i.path);\n}\n\n// One section with reasons: its `absent`, its order (absent last), its required\n// questions required unless a reason is given.\nfunction withReasons(container: Container, reasons: ChoiceOption[]): void {\n container[\"x-ui-order\"] = containerOrder(container);\n container.properties = {\n ...(container.properties ?? {}),\n [ABSENT_KEY]: absentProperty(reasons),\n };\n const required = (container.required ?? []).filter((k) => k !== ABSENT_KEY);\n delete container.required;\n for (const key of required) {\n if (!(container.allOf ?? []).some((m) => unlessReasonKey(m) === key)) {\n container.allOf = [...(container.allOf ?? []), unlessReasonMember(key)];\n }\n }\n}\n\n// One section without reasons: no `absent`, its questions plainly required again.\nfunction withoutReasons(container: Container): void {\n if (container.properties) delete container.properties[ABSENT_KEY];\n const keys = (container.allOf ?? [])\n .map(unlessReasonKey)\n .filter((k): k is string => k !== undefined);\n for (const key of keys) removeUnlessReason(container, key);\n if (keys.length)\n container.required = [...(container.required ?? []), ...keys];\n}\n\n/**\n * Declare the reasons a question may be left unanswered for -- or none (null),\n * so every question is answered. Every section gets (or loses) its `absent`,\n * and its required questions become required unless a reason is given (or\n * plainly required again).\n */\nexport function setReasons(\n model: DesignerModel,\n reasons: ChoiceOption[] | null,\n): DesignerModel {\n const paths: PropertyPath[] = [\n [],\n ...sectionPaths(classifyQuestionnaire(model).items),\n ];\n const schema = structuredClone(model.schema);\n for (const path of paths) {\n const container = containerAt(schema, path);\n if (!container) continue;\n if (reasons?.length) withReasons(container, reasons);\n else withoutReasons(container);\n }\n return { schema, uiSchema: model.uiSchema };\n}\n","/**\n * Completion -- whether a set of answers is complete: every question asked has\n * an answer or a reason for none. A question shown only if conditions hold is\n * asked while they hold. Distinct from `required`, which says an answer must\n * be given. Pure, no React. See docs/design/questionnaires.md, \"Reasons for no\n * answer\".\n */\n\nimport type { QuestionnaireItem, QuestionnaireView } from \"./classify\";\nimport { answeredOrExcused } from \"./reasons\";\nimport type { Condition, ShowIf } from \"./showIf\";\n\ntype Answers = Record<string, unknown>;\n\n/** Whether the answers are complete, and the questions that still lack an answer or a reason. */\nexport interface Completion {\n complete: boolean;\n /** The missing questions, by key path (`company.vat_id`; a repeating section's entry by index). */\n missing: string[];\n}\n\n// Whether one condition holds for a section's answers.\n// The comparisons of the value operators: the answer against the condition's value.\nconst COMPARE: Record<\n Exclude<Condition[\"operator\"], \"exists\">,\n (answer: unknown, value: string) => boolean\n> = {\n \"=\": (a, v) => String(a) === v,\n \"!=\": (a, v) => String(a) !== v,\n \">\": (a, v) => Number(a) > Number(v),\n \">=\": (a, v) => Number(a) >= Number(v),\n \"<\": (a, v) => Number(a) < Number(v),\n \"<=\": (a, v) => Number(a) <= Number(v),\n};\n\nfunction holds(c: Condition, answers: Answers): boolean {\n const value = answers[c.field];\n if (c.operator === \"exists\")\n return value !== undefined && value !== null && value !== \"\";\n return (\n value !== undefined && value !== null && COMPARE[c.operator](value, c.value)\n );\n}\n\n/** Whether an item is asked, given its section's answers: always, or while its show-if holds. */\nexport function isAsked(showIf: ShowIf | undefined, answers: Answers): boolean {\n if (!showIf || showIf.conditions.length === 0) return true;\n const results = showIf.conditions.map((c) => holds(c, answers));\n return showIf.behavior === \"any\"\n ? results.some(Boolean)\n : results.every(Boolean);\n}\n\n// The questions of a section that lack an answer or a reason, as key paths.\nfunction missingIn(\n items: QuestionnaireItem[],\n answers: Answers,\n prefix: string,\n): string[] {\n return items.flatMap((item) => {\n if (\n item.kind === \"text\" ||\n item.kind === \"locked\" ||\n !isAsked(item.showIf, answers)\n )\n return [];\n const at = prefix + item.key;\n if (item.kind === \"question\")\n return answeredOrExcused(answers, item.key) ? [] : [at];\n const value = answers[item.key];\n if (!item.repeats)\n return missingIn(\n item.items,\n (value as Answers | undefined) ?? {},\n `${at}.`,\n );\n const entries = Array.isArray(value) ? (value as Answers[]) : [];\n return entries.flatMap((entry, i) =>\n missingIn(item.items, entry ?? {}, `${at}.${i}.`),\n );\n });\n}\n\n/** Whether a set of answers is complete: every question asked has an answer or a reason. */\nexport function isComplete(\n view: QuestionnaireView,\n answers: Answers,\n): Completion {\n const missing = missingIn(view.items, answers, \"\");\n return { complete: missing.length === 0, missing };\n}\n","/**\n * QuestionnaireDesigner capabilities -- a profile that limits what an author\n * may build. As the schema designer's (../capabilities.ts): the Zod schema is\n * the single source, every field optional and defaulting to the most\n * permissive value, so adding a capability never tightens a profile already\n * written. A profile limits authoring; it never hides what a schema holds --\n * a question of a type the profile does not offer is still shown and edited.\n */\n\nimport { z } from \"zod\";\nimport { warnLog } from \"@petrarca/sonnet-core/logger\";\nimport { ANSWER_TYPE_LABELS } from \"./answerTypes\";\nimport { DEFAULT_VALUE_TYPES, type ValueTypeAnswer } from \"./valueTypes\";\n\nconst BUILTIN_ANSWER_TYPES = Object.keys(ANSWER_TYPE_LABELS);\n\nexport const questionnaireCapabilitiesSchema = z\n .object({\n answerTypes: z.array(z.string()).optional().meta({\n description:\n \"The answer types offered for a new or changed question, in order -- the built-in ones by name, a value type by its id. Default: all.\",\n }),\n sections: z\n .boolean()\n .default(true)\n .meta({ description: \"Whether sections may be added.\" }),\n logic: z\n .boolean()\n .default(true)\n .meta({ description: 'Whether \"show only if\" is offered.' }),\n reasons: z.boolean().default(true).meta({\n description: \"Whether reasons for no answer may be declared.\",\n }),\n switchToDesigner: z.boolean().default(true).meta({\n description:\n \"Whether the way to the schema designer is shown (when the application offers one).\",\n }),\n previews: z\n .array(z.enum([\"form\", \"json\", \"capabilities\"]))\n .default([\"form\", \"json\"])\n .meta({\n description:\n 'The tabs of the centre pane, in order: the form, its JSON, and the profile itself (\"capabilities\", edited live).',\n }),\n })\n .meta({\n id: \"QuestionnaireDesignerCapabilities\",\n title: \"QuestionnaireDesignerCapabilities\",\n description:\n \"What a questionnaire author may build. Every field optional, defaulting to the most permissive value.\",\n });\n\nexport type QuestionnaireDesignerCapabilities = z.input<\n typeof questionnaireCapabilitiesSchema\n>;\n\n/** The resolved profile: every field set, the answer types listed. */\nexport type ResolvedQuestionnaireCapabilities = Required<\n z.output<typeof questionnaireCapabilitiesSchema>\n>;\n\n/** A profile checked: its value, or what is wrong with it, by path. */\nexport function validateQuestionnaireCapabilities(\n input: unknown,\n):\n | { ok: true; value: QuestionnaireDesignerCapabilities }\n | { ok: false; errors: string[] } {\n const parsed = questionnaireCapabilitiesSchema.safeParse(input);\n if (parsed.success)\n return { ok: true, value: input as QuestionnaireDesignerCapabilities };\n return {\n ok: false,\n errors: parsed.error.issues.map(\n (i) => `${i.path.length ? i.path.join(\".\") : \"(root)\"}: ${i.message}`,\n ),\n };\n}\n\n/** Resolve a profile: defaults applied; an invalid one warns and falls back to the defaults. */\nexport function resolveQuestionnaireCapabilities(\n capabilities: QuestionnaireDesignerCapabilities | undefined,\n // The value types contributed: offered after the built-in types when the profile names none.\n valueTypes: readonly ValueTypeAnswer[] = DEFAULT_VALUE_TYPES,\n): ResolvedQuestionnaireCapabilities {\n const parsed = questionnaireCapabilitiesSchema.safeParse(capabilities ?? {});\n if (!parsed.success) {\n warnLog(\n \"[QuestionnaireDesigner] Invalid capabilities -- falling back to defaults.\",\n parsed.error.issues,\n );\n }\n const value = parsed.success\n ? parsed.data\n : questionnaireCapabilitiesSchema.parse({});\n const all = [...BUILTIN_ANSWER_TYPES, ...valueTypes.map((t) => t.type.id)];\n return { ...value, answerTypes: knownAnswerTypes(value.answerTypes, all) };\n}\n\n// The answer types a profile names that exist -- the unknown ones warned about and dropped; none: all.\nfunction knownAnswerTypes(\n named: string[] | undefined,\n all: string[],\n): string[] {\n const known = (named ?? []).filter((t) => all.includes(t));\n const unknown = (named ?? []).filter((t) => !all.includes(t));\n if (unknown.length)\n warnLog(\n \"[QuestionnaireDesigner] Unknown answer types in the profile -- ignored.\",\n unknown,\n );\n return known.length ? known : all;\n}\n"],"mappings":";AAUA;AAAA,EACE,cAAAA;AAAA,OAGK;;;ACqBP,IAAM,cAA8B,CAAC,aAAa,aAAa,SAAS;AACxE,IAAM,gBAAgC,CAAC,WAAW,SAAS;AAC3D,IAAM,eAA+B,CAAC,YAAY,UAAU;AAC5D,IAAM,cAA8B,CAAC,iBAAiB,eAAe;AAG9D,IAAM,qBAAkE;AAAA,EAC7E,WAAW;AAAA,EACX,UAAU;AAAA,EACV,SAAS;AAAA,EACT,SAAS;AAAA,EACT,gBAAgB;AAAA,EAChB,YAAY;AAAA,EACZ,MAAM;AAAA,EACN,MAAM;AAAA,EACN,UAAU;AACZ;AAGO,IAAM,eAA6C;AAAA,EACxD,WAAW;AAAA,EACX,WAAW;AAAA,EACX,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,UAAU;AAAA,EACV,eAAe;AAAA,EACf,eAAe;AACjB;AAGO,SAAS,UAAU,MAAkC;AAC1D,SAAO,mBAAmB,IAAI,KAAK,CAAC;AACtC;AAGO,SAAS,SAASC,OAA0B,MAA0B;AAC3E,QAAM,SAASA;AACf,SAAO,OAAO;AAAA,IACZ,UAAU,IAAI,EACX,OAAO,CAAC,MAAM,OAAO,CAAC,MAAM,MAAS,EACrC,IAAI,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;AAAA,EAC9B;AACF;;;ACtEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AA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QAAQ;AACV;AAAA,MACE;AAAA,MACA;AAAA,IACF;AACF,SAAO,MAAM,SAAS,QAAQ;AAChC;","names":["valueRefOf","prop","prop","mode","list","version","prop","valueRefOf","isOneOf","prop","prop","row","mode","isOneOf","prop","slot","bindingOf","valueRefOf","condition","valueRefOf","bindingOf","readCoding","prop","prop","isOneOf","prop","list"]}