@formspec/build 0.1.0-alpha.24 → 0.1.0-alpha.27
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.
- package/dist/analyzer/program.d.ts +12 -0
- package/dist/analyzer/program.d.ts.map +1 -1
- package/dist/browser.cjs.map +1 -1
- package/dist/browser.d.ts +1 -0
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/build-alpha.d.ts +167 -22
- package/dist/build-beta.d.ts +167 -22
- package/dist/build-internal.d.ts +167 -22
- package/dist/build.d.ts +239 -21
- package/dist/cli.cjs +118 -6
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +117 -6
- package/dist/cli.js.map +1 -1
- package/dist/generators/class-schema.d.ts +27 -0
- package/dist/generators/class-schema.d.ts.map +1 -1
- package/dist/generators/mixed-authoring.d.ts.map +1 -1
- package/dist/index.cjs +114 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +111 -6
- package/dist/index.js.map +1 -1
- package/dist/internals.cjs +46 -0
- package/dist/internals.cjs.map +1 -1
- package/dist/internals.d.ts +1 -1
- package/dist/internals.d.ts.map +1 -1
- package/dist/internals.js +44 -0
- package/dist/internals.js.map +1 -1
- package/dist/json-schema/ir-generator.d.ts +30 -0
- package/dist/json-schema/ir-generator.d.ts.map +1 -1
- package/dist/json-schema/schema.d.ts +2 -2
- package/dist/json-schema/types.d.ts +35 -4
- package/dist/json-schema/types.d.ts.map +1 -1
- package/dist/ui-schema/schema.d.ts +2 -7
- package/dist/ui-schema/schema.d.ts.map +1 -1
- package/dist/ui-schema/types.d.ts +58 -0
- package/dist/ui-schema/types.d.ts.map +1 -1
- package/package.json +4 -4
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/canonicalize/chain-dsl-canonicalizer.ts","../src/canonicalize/tsdoc-canonicalizer.ts","../src/json-schema/ir-generator.ts","../src/json-schema/generator.ts","../src/ui-schema/schema.ts","../src/ui-schema/ir-generator.ts","../src/ui-schema/generator.ts","../src/index.ts","../src/extensions/registry.ts","../src/analyzer/program.ts","../src/analyzer/class-analyzer.ts","../src/analyzer/jsdoc-constraints.ts","../src/analyzer/tsdoc-parser.ts","../src/validate/constraint-validator.ts","../src/generators/class-schema.ts","../src/generators/mixed-authoring.ts"],"sourcesContent":["/**\n * Canonicalizer that translates chain DSL `FormSpec` objects into the\n * canonical FormIR intermediate representation.\n *\n * This module maps the runtime objects produced by `@formspec/dsl` builder\n * functions (`field.*`, `group`, `when`, `formspec`) into the IR that all\n * downstream phases (validation, JSON Schema generation, UI Schema generation)\n * consume.\n */\n\nimport type {\n // Source types (chain DSL)\n AnyField,\n ArrayField,\n BooleanField,\n Conditional,\n DynamicEnumField,\n DynamicSchemaField,\n EnumOptionValue,\n FormElement,\n FormSpec,\n Group,\n NumberField,\n ObjectField,\n StaticEnumField,\n TextField,\n} from \"@formspec/core\";\nimport type {\n // IR types\n JsonValue,\n AnnotationNode,\n ArrayTypeNode,\n ConstraintNode,\n ConditionalLayoutNode,\n DisplayNameAnnotationNode,\n DynamicTypeNode,\n EnumMember,\n EnumTypeNode,\n FieldNode,\n FormIR,\n FormIRElement,\n GroupLayoutNode,\n LengthConstraintNode,\n NumericConstraintNode,\n ObjectProperty,\n PatternConstraintNode,\n ObjectTypeNode,\n PlaceholderAnnotationNode,\n PrimitiveTypeNode,\n Provenance,\n TypeNode,\n} from \"@formspec/core/internals\";\nimport { IR_VERSION } from \"@formspec/core/internals\";\n\n// =============================================================================\n// CONSTANTS\n// =============================================================================\n\n/** Default provenance for chain DSL nodes (no source location available). */\nconst CHAIN_DSL_PROVENANCE: Provenance = {\n surface: \"chain-dsl\",\n file: \"\",\n line: 0,\n column: 0,\n} as const;\n\n// =============================================================================\n// TYPE GUARDS\n// =============================================================================\n\nfunction isGroup(el: FormElement): el is Group<readonly FormElement[]> {\n return el._type === \"group\";\n}\n\nfunction isConditional(\n el: FormElement\n): el is Conditional<string, unknown, readonly FormElement[]> {\n return el._type === \"conditional\";\n}\n\nfunction isField(el: FormElement): el is AnyField {\n return el._type === \"field\";\n}\n\n// =============================================================================\n// PUBLIC API\n// =============================================================================\n\n/**\n * Translates a chain DSL `FormSpec` into the canonical `FormIR`.\n *\n * @param form - A form specification created via `formspec(...)` from `@formspec/dsl`\n * @returns The canonical intermediate representation\n */\nexport function canonicalizeChainDSL(form: FormSpec<readonly FormElement[]>): FormIR {\n return {\n kind: \"form-ir\",\n irVersion: IR_VERSION,\n elements: canonicalizeElements(form.elements),\n rootAnnotations: [],\n typeRegistry: {},\n provenance: CHAIN_DSL_PROVENANCE,\n };\n}\n\n// =============================================================================\n// ELEMENT CANONICALIZATION\n// =============================================================================\n\n/**\n * Canonicalizes an array of chain DSL form elements into IR elements.\n */\nfunction canonicalizeElements(elements: readonly FormElement[]): FormIRElement[] {\n return elements.map(canonicalizeElement);\n}\n\n/**\n * Dispatches a single form element to its specific canonicalization function.\n */\nfunction canonicalizeElement(element: FormElement): FormIRElement {\n if (isField(element)) {\n return canonicalizeField(element);\n }\n if (isGroup(element)) {\n return canonicalizeGroup(element);\n }\n if (isConditional(element)) {\n return canonicalizeConditional(element);\n }\n const _exhaustive: never = element;\n throw new Error(`Unknown element type: ${JSON.stringify(_exhaustive)}`);\n}\n\n// =============================================================================\n// FIELD CANONICALIZATION\n// =============================================================================\n\n/**\n * Dispatches a field element to its type-specific canonicalization function.\n */\nfunction canonicalizeField(field: AnyField): FieldNode {\n switch (field._field) {\n case \"text\":\n return canonicalizeTextField(field);\n case \"number\":\n return canonicalizeNumberField(field);\n case \"boolean\":\n return canonicalizeBooleanField(field);\n case \"enum\":\n return canonicalizeStaticEnumField(field);\n case \"dynamic_enum\":\n return canonicalizeDynamicEnumField(field);\n case \"dynamic_schema\":\n return canonicalizeDynamicSchemaField(field);\n case \"array\":\n return canonicalizeArrayField(field);\n case \"object\":\n return canonicalizeObjectField(field);\n default: {\n const _exhaustive: never = field;\n throw new Error(`Unknown field type: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n\n// =============================================================================\n// SPECIFIC FIELD TYPE CANONICALIZERS\n// =============================================================================\n\nfunction canonicalizeTextField(field: TextField<string>): FieldNode {\n const type: PrimitiveTypeNode = { kind: \"primitive\", primitiveKind: \"string\" };\n const constraints: ConstraintNode[] = [];\n\n if (field.minLength !== undefined) {\n const c: LengthConstraintNode = {\n kind: \"constraint\",\n constraintKind: \"minLength\",\n value: field.minLength,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n constraints.push(c);\n }\n\n if (field.maxLength !== undefined) {\n const c: LengthConstraintNode = {\n kind: \"constraint\",\n constraintKind: \"maxLength\",\n value: field.maxLength,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n constraints.push(c);\n }\n\n if (field.pattern !== undefined) {\n const c: PatternConstraintNode = {\n kind: \"constraint\",\n constraintKind: \"pattern\",\n pattern: field.pattern,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n constraints.push(c);\n }\n\n return buildFieldNode(\n field.name,\n type,\n field.required,\n buildAnnotations(field.label, field.placeholder),\n constraints\n );\n}\n\nfunction canonicalizeNumberField(field: NumberField<string>): FieldNode {\n const type: PrimitiveTypeNode = { kind: \"primitive\", primitiveKind: \"number\" };\n const constraints: ConstraintNode[] = [];\n\n if (field.min !== undefined) {\n const c: NumericConstraintNode = {\n kind: \"constraint\",\n constraintKind: \"minimum\",\n value: field.min,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n constraints.push(c);\n }\n\n if (field.max !== undefined) {\n const c: NumericConstraintNode = {\n kind: \"constraint\",\n constraintKind: \"maximum\",\n value: field.max,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n constraints.push(c);\n }\n\n if (field.multipleOf !== undefined) {\n const c: NumericConstraintNode = {\n kind: \"constraint\",\n constraintKind: \"multipleOf\",\n value: field.multipleOf,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n constraints.push(c);\n }\n\n return buildFieldNode(\n field.name,\n type,\n field.required,\n buildAnnotations(field.label),\n constraints\n );\n}\n\nfunction canonicalizeBooleanField(field: BooleanField<string>): FieldNode {\n const type: PrimitiveTypeNode = { kind: \"primitive\", primitiveKind: \"boolean\" };\n return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));\n}\n\nfunction canonicalizeStaticEnumField(\n field: StaticEnumField<string, readonly EnumOptionValue[]>\n): FieldNode {\n const members: EnumMember[] = field.options.map((opt) => {\n if (typeof opt === \"string\") {\n return { value: opt } satisfies EnumMember;\n }\n // Object option with id/label\n return { value: opt.id, displayName: opt.label } satisfies EnumMember;\n });\n\n const type: EnumTypeNode = { kind: \"enum\", members };\n return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));\n}\n\nfunction canonicalizeDynamicEnumField(field: DynamicEnumField<string, string>): FieldNode {\n const type: DynamicTypeNode = {\n kind: \"dynamic\",\n dynamicKind: \"enum\",\n sourceKey: field.source,\n parameterFields: field.params ? [...field.params] : [],\n };\n return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));\n}\n\nfunction canonicalizeDynamicSchemaField(field: DynamicSchemaField<string>): FieldNode {\n const type: DynamicTypeNode = {\n kind: \"dynamic\",\n dynamicKind: \"schema\",\n sourceKey: field.schemaSource,\n parameterFields: [],\n };\n return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));\n}\n\nfunction canonicalizeArrayField(field: ArrayField<string, readonly FormElement[]>): FieldNode {\n // Array items form an object type from the sub-elements\n const itemProperties = buildObjectProperties(field.items);\n const itemsType: ObjectTypeNode = {\n kind: \"object\",\n properties: itemProperties,\n additionalProperties: true,\n };\n const type: ArrayTypeNode = { kind: \"array\", items: itemsType };\n\n const constraints: ConstraintNode[] = [];\n if (field.minItems !== undefined) {\n const c: LengthConstraintNode = {\n kind: \"constraint\",\n constraintKind: \"minItems\",\n value: field.minItems,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n constraints.push(c);\n }\n if (field.maxItems !== undefined) {\n const c: LengthConstraintNode = {\n kind: \"constraint\",\n constraintKind: \"maxItems\",\n value: field.maxItems,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n constraints.push(c);\n }\n\n return buildFieldNode(\n field.name,\n type,\n field.required,\n buildAnnotations(field.label),\n constraints\n );\n}\n\nfunction canonicalizeObjectField(field: ObjectField<string, readonly FormElement[]>): FieldNode {\n const properties = buildObjectProperties(field.properties);\n const type: ObjectTypeNode = {\n kind: \"object\",\n properties,\n additionalProperties: true,\n };\n return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));\n}\n\n// =============================================================================\n// LAYOUT CANONICALIZATION\n// =============================================================================\n\nfunction canonicalizeGroup(g: Group<readonly FormElement[]>): GroupLayoutNode {\n return {\n kind: \"group\",\n label: g.label,\n elements: canonicalizeElements(g.elements),\n provenance: CHAIN_DSL_PROVENANCE,\n };\n}\n\nfunction canonicalizeConditional(\n c: Conditional<string, unknown, readonly FormElement[]>\n): ConditionalLayoutNode {\n return {\n kind: \"conditional\",\n fieldName: c.field,\n // Conditional values from the chain DSL are JSON-serializable primitives\n // (strings, numbers, booleans) produced by the `is()` predicate helper.\n value: assertJsonValue(c.value),\n elements: canonicalizeElements(c.elements),\n provenance: CHAIN_DSL_PROVENANCE,\n };\n}\n\n// =============================================================================\n// HELPERS\n// =============================================================================\n\n/**\n * Validates that a value is JSON-serializable (`JsonValue`).\n * The chain DSL's `is()` helper constrains conditional values to\n * JSON-compatible primitives, but the TypeScript type is `unknown`.\n * This runtime guard replaces an `as` cast with a validated assertion.\n */\nfunction assertJsonValue(v: unknown): JsonValue {\n if (v === null || typeof v === \"string\" || typeof v === \"number\" || typeof v === \"boolean\") {\n return v;\n }\n if (Array.isArray(v)) {\n return v.map(assertJsonValue);\n }\n if (typeof v === \"object\") {\n const result: Record<string, JsonValue> = {};\n for (const [key, val] of Object.entries(v)) {\n result[key] = assertJsonValue(val);\n }\n return result;\n }\n // Remaining types (function, symbol, bigint, undefined) are not JSON-serializable\n throw new TypeError(`Conditional value is not a valid JsonValue: ${typeof v}`);\n}\n\n/**\n * Builds a FieldNode from common field properties.\n */\nfunction buildFieldNode(\n name: string,\n type: TypeNode,\n required: boolean | undefined,\n annotations: AnnotationNode[],\n constraints: ConstraintNode[] = []\n): FieldNode {\n return {\n kind: \"field\",\n name,\n type,\n required: required === true,\n constraints,\n annotations,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n}\n\n/**\n * Builds annotation nodes from optional label and placeholder values.\n */\nfunction buildAnnotations(label?: string, placeholder?: string): AnnotationNode[] {\n const annotations: AnnotationNode[] = [];\n\n if (label !== undefined) {\n const a: DisplayNameAnnotationNode = {\n kind: \"annotation\",\n annotationKind: \"displayName\",\n value: label,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n annotations.push(a);\n }\n\n if (placeholder !== undefined) {\n const a: PlaceholderAnnotationNode = {\n kind: \"annotation\",\n annotationKind: \"placeholder\",\n value: placeholder,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n annotations.push(a);\n }\n\n return annotations;\n}\n\n/**\n * Converts an array of form elements into ObjectProperty nodes.\n * Used for ObjectField properties and ArrayField items.\n *\n * Only field elements produce properties; groups and conditionals within\n * an object/array context are recursively flattened to extract their fields.\n *\n * Fields inside conditional branches are always marked `optional: true`\n * because their presence in the data depends on the condition being met.\n * This matches the DSL's type inference behavior where conditional fields\n * produce optional properties in `InferFormSchema`.\n *\n * @param elements - The form elements to convert\n * @param insideConditional - Whether these elements are inside a conditional branch\n */\nfunction buildObjectProperties(\n elements: readonly FormElement[],\n insideConditional = false\n): ObjectProperty[] {\n const properties: ObjectProperty[] = [];\n\n for (const el of elements) {\n if (isField(el)) {\n const fieldNode = canonicalizeField(el);\n properties.push({\n name: fieldNode.name,\n type: fieldNode.type,\n // Fields inside a conditional branch are always optional in the\n // data schema, regardless of their `required` flag — the condition\n // may not be met, so the field may be absent.\n optional: insideConditional || !fieldNode.required,\n constraints: fieldNode.constraints,\n annotations: fieldNode.annotations,\n provenance: CHAIN_DSL_PROVENANCE,\n });\n } else if (isGroup(el)) {\n // Groups inside object/array items contribute their fields by flattening.\n // Groups do not affect optionality — pass through the current state.\n properties.push(...buildObjectProperties(el.elements, insideConditional));\n } else if (isConditional(el)) {\n // Conditionals inside object/array items contribute their fields by\n // flattening, but all fields inside are forced optional.\n properties.push(...buildObjectProperties(el.elements, true));\n }\n }\n\n return properties;\n}\n","/**\n * TSDoc canonicalizer — assembles an {@link IRClassAnalysis} into a canonical\n * {@link FormIR}, applying layout metadata from `@Group` and `@ShowWhen`\n * TSDoc tags.\n *\n * The analysis functions in `class-analyzer.ts` produce `FieldNode[]`,\n * `fieldLayouts`, and `typeRegistry` directly. This canonicalizer uses\n * the layout metadata to wrap fields in `GroupLayoutNode` and\n * `ConditionalLayoutNode` elements.\n */\n\nimport type {\n FormIR,\n FormIRElement,\n FieldNode,\n GroupLayoutNode,\n ConditionalLayoutNode,\n Provenance,\n} from \"@formspec/core/internals\";\nimport { IR_VERSION } from \"@formspec/core/internals\";\nimport type { IRClassAnalysis, FieldLayoutMetadata } from \"../analyzer/class-analyzer.js\";\n\n/**\n * Source-level metadata for provenance tracking.\n */\nexport interface TSDocSource {\n /** Absolute path to the source file. */\n readonly file: string;\n}\n\n/**\n * Wraps an {@link IRClassAnalysis} (from `analyzeClassToIR`,\n * `analyzeInterfaceToIR`, or `analyzeTypeAliasToIR`) into a canonical\n * {@link FormIR}.\n *\n * Fields with `@Group` TSDoc tags are grouped into `GroupLayoutNode` elements.\n * Fields with `@ShowWhen` TSDoc tags are wrapped in `ConditionalLayoutNode` elements.\n * When both are present, the conditional wraps the field inside the group.\n *\n * @param analysis - IR analysis result (fields are already FieldNode[])\n * @param source - Optional source file metadata for provenance\n * @returns The canonical FormIR\n */\nexport function canonicalizeTSDoc(analysis: IRClassAnalysis, source?: TSDocSource): FormIR {\n const file = source?.file ?? \"\";\n\n const provenance: Provenance = {\n surface: \"tsdoc\",\n file,\n line: 1,\n column: 0,\n };\n\n const elements = assembleElements(analysis.fields, analysis.fieldLayouts, provenance);\n\n return {\n kind: \"form-ir\",\n irVersion: IR_VERSION,\n elements,\n typeRegistry: analysis.typeRegistry,\n ...(analysis.annotations !== undefined &&\n analysis.annotations.length > 0 && { rootAnnotations: analysis.annotations }),\n ...(analysis.annotations !== undefined &&\n analysis.annotations.length > 0 && { annotations: analysis.annotations }),\n provenance,\n };\n}\n\n/**\n * Assembles flat fields and their layout metadata into a tree of\n * `FormIRElement[]` with groups and conditionals.\n *\n * Fields are processed in order. Consecutive fields with the same\n * `@Group` label are collected into a single `GroupLayoutNode`.\n * Fields with `@ShowWhen` are wrapped in `ConditionalLayoutNode`.\n */\nfunction assembleElements(\n fields: readonly FieldNode[],\n layouts: readonly FieldLayoutMetadata[],\n provenance: Provenance\n): readonly FormIRElement[] {\n const elements: FormIRElement[] = [];\n\n // Group consecutive fields with the same group label together.\n // We use an ordered map to preserve insertion order of groups.\n const groupMap = new Map<string, FormIRElement[]>();\n const topLevelOrder: (\n | { type: \"group\"; label: string }\n | { type: \"element\"; element: FormIRElement }\n )[] = [];\n\n for (let i = 0; i < fields.length; i++) {\n const field = fields[i];\n const layout = layouts[i];\n if (!field || !layout) continue;\n\n // Wrap in conditional if @ShowWhen is present\n const element = wrapInConditional(field, layout, provenance);\n\n if (layout.groupLabel !== undefined) {\n const label = layout.groupLabel;\n let groupElements = groupMap.get(label);\n if (!groupElements) {\n groupElements = [];\n groupMap.set(label, groupElements);\n topLevelOrder.push({ type: \"group\", label });\n }\n groupElements.push(element);\n } else {\n topLevelOrder.push({ type: \"element\", element });\n }\n }\n\n // Assemble the final element array in order\n for (const entry of topLevelOrder) {\n if (entry.type === \"group\") {\n const groupElements = groupMap.get(entry.label);\n if (groupElements) {\n const groupNode: GroupLayoutNode = {\n kind: \"group\",\n label: entry.label,\n elements: groupElements,\n provenance,\n };\n elements.push(groupNode);\n // Clear so duplicate group labels in topLevelOrder don't re-emit\n groupMap.delete(entry.label);\n }\n } else {\n elements.push(entry.element);\n }\n }\n\n return elements;\n}\n\n/**\n * Wraps a field in a `ConditionalLayoutNode` if the layout has `showWhen` metadata.\n */\nfunction wrapInConditional(\n field: FieldNode,\n layout: FieldLayoutMetadata,\n provenance: Provenance\n): FormIRElement {\n if (layout.showWhen === undefined) {\n return field;\n }\n\n const conditional: ConditionalLayoutNode = {\n kind: \"conditional\",\n fieldName: layout.showWhen.field,\n value: layout.showWhen.value,\n elements: [field],\n provenance,\n };\n\n return conditional;\n}\n","/**\n * JSON Schema 2020-12 generator that consumes the canonical FormIR.\n *\n * This generator is a pure function of the IR. It never consults the TypeScript\n * AST or surface syntax directly — only the IR (per the JSON Schema vocabulary spec §1.2).\n *\n * @see https://json-schema.org/draft/2020-12/schema\n * @see https://json-schema.org/draft/2020-12/schema\n */\n\nimport type {\n FormIR,\n FormIRElement,\n FieldNode,\n TypeNode,\n PrimitiveTypeNode,\n EnumTypeNode,\n ArrayTypeNode,\n ObjectTypeNode,\n RecordTypeNode,\n UnionTypeNode,\n ReferenceTypeNode,\n DynamicTypeNode,\n CustomTypeNode,\n ConstraintNode,\n AnnotationNode,\n ObjectProperty,\n} from \"@formspec/core/internals\";\nimport type { ExtensionRegistry } from \"../extensions/index.js\";\n\n// =============================================================================\n// OUTPUT TYPE\n// =============================================================================\n\n/**\n * A JSON Schema 2020-12 document, sub-schema, or keyword collection.\n *\n * This interface covers the subset of JSON Schema 2020-12 that this generator\n * emits, plus an index signature for custom `x-formspec-*` extension keywords.\n *\n * @public\n */\nexport interface JsonSchema2020 {\n $schema?: string;\n $ref?: string;\n $defs?: Record<string, JsonSchema2020>;\n type?: string;\n properties?: Record<string, JsonSchema2020>;\n required?: string[];\n items?: JsonSchema2020;\n additionalProperties?: boolean | JsonSchema2020;\n enum?: readonly (string | number)[];\n const?: unknown;\n allOf?: readonly JsonSchema2020[];\n oneOf?: readonly JsonSchema2020[];\n anyOf?: readonly JsonSchema2020[];\n // Constraints\n minimum?: number;\n maximum?: number;\n exclusiveMinimum?: number;\n exclusiveMaximum?: number;\n multipleOf?: number;\n minLength?: number;\n maxLength?: number;\n minItems?: number;\n maxItems?: number;\n pattern?: string;\n uniqueItems?: boolean;\n format?: string;\n // Annotations\n title?: string;\n description?: string;\n default?: unknown;\n deprecated?: boolean;\n // Extensions (open for vendor-prefixed keywords, e.g., x-formspec-*, x-stripe-*)\n // The vendor prefix is configurable (white-labelable).\n [key: `x-${string}`]: unknown;\n}\n\n// =============================================================================\n// CONTEXT\n// =============================================================================\n\n/**\n * Mutable accumulator passed through the generation traversal.\n *\n * Using a context object rather than return-value threading keeps the\n * recursive generators simple and avoids repeated object spreading.\n */\ninterface GeneratorContext {\n /** Named type schemas collected during traversal, keyed by reference name. */\n readonly defs: Record<string, JsonSchema2020>;\n /** Optional extension registry for resolving custom IR nodes. */\n readonly extensionRegistry: ExtensionRegistry | undefined;\n /** Vendor prefix passed through to extension toJsonSchema handlers. */\n readonly vendorPrefix: string;\n}\n\n/**\n * Options for generating JSON Schema from a canonical FormIR.\n *\n * @internal\n */\nexport interface GenerateJsonSchemaFromIROptions {\n /**\n * Registry used to resolve custom types, constraints, and annotations.\n *\n * JSON Schema generation throws when custom IR nodes are present without a\n * matching registration in this registry.\n */\n readonly extensionRegistry?: ExtensionRegistry | undefined;\n /**\n * Vendor prefix passed to extension `toJsonSchema` hooks.\n * @defaultValue \"x-formspec\"\n */\n readonly vendorPrefix?: string | undefined;\n}\n\nfunction makeContext(options?: GenerateJsonSchemaFromIROptions): GeneratorContext {\n const vendorPrefix = options?.vendorPrefix ?? \"x-formspec\";\n if (!vendorPrefix.startsWith(\"x-\")) {\n throw new Error(\n `Invalid vendorPrefix \"${vendorPrefix}\". Extension JSON Schema keywords must start with \"x-\".`\n );\n }\n\n return {\n defs: {},\n extensionRegistry: options?.extensionRegistry,\n vendorPrefix,\n };\n}\n\n// =============================================================================\n// PUBLIC API\n// =============================================================================\n\n/**\n * Generates a JSON Schema 2020-12 object from a canonical FormIR.\n *\n * Groups and conditionals are flattened — they influence UI layout but do not\n * affect the data schema. All fields appear at the level they would occupy in\n * the output data.\n *\n * Named types in the `typeRegistry` are emitted as `$defs` entries and\n * referenced via `$ref` (per PP7 — high-fidelity output).\n *\n * @example\n * ```typescript\n * import { canonicalizeDSL } from \"./canonicalize/index.js\";\n * import { generateJsonSchemaFromIR } from \"./json-schema/ir-generator.js\";\n * import { formspec, field } from \"@formspec/dsl\";\n *\n * const form = formspec(\n * field.text(\"name\", { label: \"Name\", required: true }),\n * field.number(\"age\", { min: 0 }),\n * );\n * const ir = canonicalizeDSL(form);\n * const schema = generateJsonSchemaFromIR(ir);\n * // {\n * // $schema: \"https://json-schema.org/draft/2020-12/schema\",\n * // type: \"object\",\n * // properties: {\n * // name: { type: \"string\", title: \"Name\" },\n * // age: { type: \"number\", minimum: 0 }\n * // },\n * // required: [\"name\"]\n * // }\n * ```\n *\n * Advanced API — most consumers should use `generateJsonSchema()` or\n * `buildFormSchemas()`, which canonicalize form definitions automatically.\n * Callers of this function are responsible for providing pre-canonicalized IR.\n *\n * @param ir - The canonical FormIR produced by a canonicalizer\n * @returns A plain JSON-serializable JSON Schema 2020-12 object\n *\n * @internal\n */\nexport function generateJsonSchemaFromIR(\n ir: FormIR,\n options?: GenerateJsonSchemaFromIROptions\n): JsonSchema2020 {\n const ctx = makeContext(options);\n\n // Seed $defs from the type registry so referenced types are available even if\n // the field tree traversal never visits them (e.g., unreferenced types added\n // by a TSDoc canonicalizer pass).\n for (const [name, typeDef] of Object.entries(ir.typeRegistry)) {\n ctx.defs[name] = generateTypeNode(typeDef.type, ctx);\n if (typeDef.constraints && typeDef.constraints.length > 0) {\n applyConstraints(ctx.defs[name], typeDef.constraints, ctx);\n }\n if (typeDef.annotations && typeDef.annotations.length > 0) {\n applyAnnotations(ctx.defs[name], typeDef.annotations, ctx);\n }\n }\n\n const properties: Record<string, JsonSchema2020> = {};\n const required: string[] = [];\n\n collectFields(ir.elements, properties, required, ctx);\n\n // Deduplicate required (same field can appear across conditional branches).\n const uniqueRequired = [...new Set(required)];\n\n const result: JsonSchema2020 = {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n type: \"object\",\n properties,\n ...(uniqueRequired.length > 0 && { required: uniqueRequired }),\n };\n\n if (ir.annotations && ir.annotations.length > 0) {\n applyAnnotations(result, ir.annotations, ctx);\n }\n\n if (Object.keys(ctx.defs).length > 0) {\n result.$defs = ctx.defs;\n }\n\n return result;\n}\n\n// =============================================================================\n// ELEMENT TRAVERSAL\n// =============================================================================\n\n/**\n * Recursively visits all IR elements, collecting field schemas and required names.\n *\n * Groups and conditionals are transparent to the schema — their children are\n * lifted to the enclosing level (per the JSON Schema vocabulary spec §1.2).\n */\nfunction collectFields(\n elements: readonly FormIRElement[],\n properties: Record<string, JsonSchema2020>,\n required: string[],\n ctx: GeneratorContext\n): void {\n for (const element of elements) {\n switch (element.kind) {\n case \"field\":\n properties[element.name] = generateFieldSchema(element, ctx);\n if (element.required) {\n required.push(element.name);\n }\n break;\n\n case \"group\":\n // Groups are UI-only; flatten children into the enclosing schema.\n collectFields(element.elements, properties, required, ctx);\n break;\n\n case \"conditional\":\n // Conditional visibility is UI-only; all fields remain in the schema.\n collectFields(element.elements, properties, required, ctx);\n break;\n\n default: {\n const _exhaustive: never = element;\n void _exhaustive;\n }\n }\n }\n}\n\n// =============================================================================\n// FIELD SCHEMA GENERATION\n// =============================================================================\n\n/**\n * Generates the JSON Schema sub-schema for a single FieldNode.\n */\nfunction generateFieldSchema(field: FieldNode, ctx: GeneratorContext): JsonSchema2020 {\n const schema = generateTypeNode(field.type, ctx);\n const itemStringSchema =\n schema.type === \"array\" && schema.items?.type === \"string\" ? schema.items : undefined;\n\n // Partition constraints into direct (no path) and path-targeted.\n const directConstraints: ConstraintNode[] = [];\n const itemConstraints: ConstraintNode[] = [];\n const pathConstraints: ConstraintNode[] = [];\n for (const c of field.constraints) {\n if (c.path) {\n pathConstraints.push(c);\n } else if (itemStringSchema !== undefined && isStringItemConstraint(c)) {\n itemConstraints.push(c);\n } else {\n directConstraints.push(c);\n }\n }\n\n // Apply direct constraints. multipleOf:1 on a number type is a special case:\n // it promotes the type to \"integer\" and removes the multipleOf keyword.\n applyConstraints(schema, directConstraints, ctx);\n\n if (itemStringSchema !== undefined) {\n applyConstraints(itemStringSchema, itemConstraints, ctx);\n }\n\n // Apply annotations (title, description, default, deprecated, etc.).\n const rootAnnotations: AnnotationNode[] = [];\n const itemAnnotations: AnnotationNode[] = [];\n for (const annotation of field.annotations) {\n if (itemStringSchema !== undefined && annotation.annotationKind === \"format\") {\n itemAnnotations.push(annotation);\n } else {\n rootAnnotations.push(annotation);\n }\n }\n\n applyAnnotations(schema, rootAnnotations, ctx);\n if (itemStringSchema !== undefined) {\n applyAnnotations(itemStringSchema, itemAnnotations, ctx);\n }\n\n // If no path-targeted constraints, return as-is.\n if (pathConstraints.length === 0) {\n return schema;\n }\n\n return applyPathTargetedConstraints(schema, pathConstraints, ctx);\n}\n\n/**\n * Returns true if a constraint should be applied to the `items` schema of a\n * primitive `string[]` rather than the array itself.\n *\n * `@const` is intentionally excluded: arrays cannot carry primitive const\n * constraints in FormSpec, so `@const` on `string[]` remains a validation\n * error instead of targeting the item schema.\n */\nfunction isStringItemConstraint(constraint: ConstraintNode): boolean {\n switch (constraint.constraintKind) {\n case \"minLength\":\n case \"maxLength\":\n case \"pattern\":\n return true;\n default:\n return false;\n }\n}\n\n/**\n * Applies path-targeted constraints to a schema via allOf composition.\n *\n * For $ref schemas: wraps in allOf with property overrides.\n * For inline object schemas: applies directly to nested properties.\n * For array schemas: applies path constraints to the items sub-schema.\n */\nfunction applyPathTargetedConstraints(\n schema: JsonSchema2020,\n pathConstraints: readonly ConstraintNode[],\n ctx: GeneratorContext\n): JsonSchema2020 {\n // Array transparency: path-targeted constraints target the item type.\n if (schema.type === \"array\" && schema.items) {\n schema.items = applyPathTargetedConstraints(schema.items, pathConstraints, ctx);\n return schema;\n }\n\n // Group path constraints by target field name (first path segment).\n // Callers guarantee all entries have a defined `path` (filtered upstream).\n const byTarget = new Map<string, ConstraintNode[]>();\n for (const c of pathConstraints) {\n const target = c.path?.segments[0];\n if (!target) continue;\n const group = byTarget.get(target) ?? [];\n group.push(c);\n byTarget.set(target, group);\n }\n\n // Build the property overrides object.\n const propertyOverrides: Record<string, JsonSchema2020> = {};\n for (const [target, constraints] of byTarget) {\n const subSchema: JsonSchema2020 = {};\n applyConstraints(subSchema, constraints, ctx);\n propertyOverrides[target] = subSchema;\n }\n\n // $ref schema: wrap in allOf to preserve $ref semantics while adding overrides.\n if (schema.$ref) {\n const { $ref, ...rest } = schema;\n const refPart: JsonSchema2020 = { $ref };\n const overridePart: JsonSchema2020 = {\n properties: propertyOverrides,\n ...rest,\n };\n return { allOf: [refPart, overridePart] };\n }\n\n // Inline object schema: merge property overrides directly where possible.\n if (schema.type === \"object\" && schema.properties) {\n const missingOverrides: Record<string, JsonSchema2020> = {};\n\n for (const [target, overrideSchema] of Object.entries(propertyOverrides)) {\n if (schema.properties[target]) {\n Object.assign(schema.properties[target], overrideSchema);\n } else {\n // Do not introduce new properties directly; compose via allOf instead\n // to preserve additionalProperties semantics on the base object.\n missingOverrides[target] = overrideSchema;\n }\n }\n\n if (Object.keys(missingOverrides).length === 0) {\n return schema;\n }\n\n return {\n allOf: [schema, { properties: missingOverrides }],\n };\n }\n\n // allOf schema (already composed): add property overrides as another member.\n if (schema.allOf) {\n schema.allOf = [...schema.allOf, { properties: propertyOverrides }];\n return schema;\n }\n\n // Fallback: for non-object/non-$ref schemas, path-targeted constraints do not\n // apply in a meaningful way. Return the original schema unchanged and rely\n // on validation diagnostics to surface misuse of path-based constraints.\n return schema;\n}\n\n// =============================================================================\n// TYPE NODE GENERATION\n// =============================================================================\n\n/**\n * Converts a TypeNode to a JSON Schema sub-schema.\n *\n * This function is intentionally exhaustive — all TypeNode variants are handled.\n * TypeScript's exhaustiveness check via the default branch ensures new variants\n * added to the IR are caught at compile time.\n */\nfunction generateTypeNode(type: TypeNode, ctx: GeneratorContext): JsonSchema2020 {\n switch (type.kind) {\n case \"primitive\":\n return generatePrimitiveType(type);\n\n case \"enum\":\n return generateEnumType(type);\n\n case \"array\":\n return generateArrayType(type, ctx);\n\n case \"object\":\n return generateObjectType(type, ctx);\n\n case \"record\":\n return generateRecordType(type, ctx);\n\n case \"union\":\n return generateUnionType(type, ctx);\n\n case \"reference\":\n return generateReferenceType(type);\n\n case \"dynamic\":\n return generateDynamicType(type);\n\n case \"custom\":\n return generateCustomType(type, ctx);\n\n default: {\n // TypeScript exhaustiveness guard.\n const _exhaustive: never = type;\n return _exhaustive;\n }\n }\n}\n\n/**\n * Maps primitive IR types to JSON Schema type keywords.\n *\n * Note: `integer` is NOT a primitive kind in the IR. Integer semantics are\n * expressed via a `multipleOf: 1` constraint on a number type; `applyConstraints`\n * handles the promotion (per the JSON Schema vocabulary spec §2.1).\n */\nfunction generatePrimitiveType(type: PrimitiveTypeNode): JsonSchema2020 {\n return {\n type:\n type.primitiveKind === \"integer\" || type.primitiveKind === \"bigint\"\n ? \"integer\"\n : type.primitiveKind,\n };\n}\n\n/**\n * Generates JSON Schema for a static enum type.\n *\n * When any member has a displayName, the output uses the `oneOf` form with\n * per-member `const`/`title` entries (per the JSON Schema vocabulary spec §2.3). Otherwise the\n * flat `enum` keyword is used (simpler, equally valid).\n */\nfunction generateEnumType(type: EnumTypeNode): JsonSchema2020 {\n const hasDisplayNames = type.members.some((m) => m.displayName !== undefined);\n\n if (hasDisplayNames) {\n return {\n oneOf: type.members.map((m) => {\n const entry: JsonSchema2020 = { const: m.value };\n if (m.displayName !== undefined) {\n entry.title = m.displayName;\n }\n return entry;\n }),\n };\n }\n\n return { enum: type.members.map((m) => m.value) };\n}\n\n/**\n * Generates JSON Schema for an array type.\n * Per 2020-12, `items` is a single schema (not an array); tuple types use\n * `prefixItems` + `items: false`.\n */\nfunction generateArrayType(type: ArrayTypeNode, ctx: GeneratorContext): JsonSchema2020 {\n return {\n type: \"array\",\n items: generateTypeNode(type.items, ctx),\n };\n}\n\n/**\n * Generates JSON Schema for an object type.\n *\n * `additionalProperties` is emitted only when the IR explicitly closes the\n * object. Ordinary static object types now canonicalize to\n * `additionalProperties: true`, which omits the keyword per spec 003 §2.5.\n */\nfunction generateObjectType(type: ObjectTypeNode, ctx: GeneratorContext): JsonSchema2020 {\n const properties: Record<string, JsonSchema2020> = {};\n const required: string[] = [];\n\n for (const prop of type.properties) {\n properties[prop.name] = generatePropertySchema(prop, ctx);\n if (!prop.optional) {\n required.push(prop.name);\n }\n }\n\n const schema: JsonSchema2020 = { type: \"object\", properties };\n\n if (required.length > 0) {\n schema.required = required;\n }\n\n if (!type.additionalProperties) {\n schema.additionalProperties = false;\n }\n\n return schema;\n}\n\n/**\n * Generates JSON Schema for a record (dictionary) type per spec 003 §2.5.\n *\n * `Record<string, T>` and `{ [k: string]: T }` both emit:\n * `{ \"type\": \"object\", \"additionalProperties\": <T schema> }`\n *\n * No `properties` key is emitted — the record has no named properties.\n */\nfunction generateRecordType(type: RecordTypeNode, ctx: GeneratorContext): JsonSchema2020 {\n return {\n type: \"object\",\n additionalProperties: generateTypeNode(type.valueType, ctx),\n };\n}\n\n/**\n * Generates a schema for an ObjectProperty, applying its use-site constraints\n * and annotations (per the JSON Schema vocabulary spec §5.4 — inline allOf at use site).\n */\nfunction generatePropertySchema(prop: ObjectProperty, ctx: GeneratorContext): JsonSchema2020 {\n const schema = generateTypeNode(prop.type, ctx);\n applyConstraints(schema, prop.constraints, ctx);\n applyAnnotations(schema, prop.annotations, ctx);\n return schema;\n}\n\n/**\n * Generates JSON Schema for a union type.\n *\n * Union handling strategy (per spec 003):\n * - Boolean shorthand: `true | false` → `{ type: \"boolean\" }` (not oneOf/anyOf)\n * - Nullable unions: `T | null` → `{ \"oneOf\": [<T schema>, { \"type\": \"null\" }] }` (§2.3)\n * - All other unions → `anyOf` (members may overlap; discriminated union\n * detection is deferred to a future phase per design doc 003 §7.4)\n */\nfunction generateUnionType(type: UnionTypeNode, ctx: GeneratorContext): JsonSchema2020 {\n // Boolean shorthand: union of true-literal and false-literal → type: \"boolean\"\n if (isBooleanUnion(type)) {\n return { type: \"boolean\" };\n }\n\n // Nullable union: `T | null` → oneOf per spec 003 §2.3.\n // A nullable union is any union where exactly one member is the null primitive.\n if (isNullableUnion(type)) {\n return {\n oneOf: type.members.map((m) => generateTypeNode(m, ctx)),\n };\n }\n\n // Default: anyOf for non-discriminated object unions (spec 003 §7.4).\n // Discriminated union detection (shared required property with distinct consts)\n // is deferred to a future phase.\n return {\n anyOf: type.members.map((m) => generateTypeNode(m, ctx)),\n };\n}\n\n/**\n * Returns true if the union is `true | false` (boolean shorthand).\n */\nfunction isBooleanUnion(type: UnionTypeNode): boolean {\n if (type.members.length !== 2) return false;\n const kinds = type.members.map((m) => m.kind);\n // Both must be primitives; check if both are \"boolean\" primitives.\n // The IR currently does not have a boolean literal node, so boolean union\n // is represented as two primitive boolean members.\n return (\n kinds.every((k) => k === \"primitive\") &&\n type.members.every((m) => m.kind === \"primitive\" && m.primitiveKind === \"boolean\")\n );\n}\n\n/**\n * Returns true if the union is a nullable wrapper union (`T | null` for any T).\n *\n * A nullable union is a two-member union where exactly one member is the `null`\n * primitive type and the other member is any non-null type.\n * Per spec 003 §2.3, nullable unions map to `oneOf` (not `anyOf`).\n */\nfunction isNullableUnion(type: UnionTypeNode): boolean {\n if (type.members.length !== 2) return false;\n const nullCount = type.members.filter(\n (m) => m.kind === \"primitive\" && m.primitiveKind === \"null\"\n ).length;\n return nullCount === 1;\n}\n\n/**\n * Generates JSON Schema for a reference type.\n *\n * The referenced type's schema is stored in `$defs` (seeded from the type\n * registry before traversal begins). The reference simply emits a `$ref`.\n */\nfunction generateReferenceType(type: ReferenceTypeNode): JsonSchema2020 {\n return { $ref: `#/$defs/${type.name}` };\n}\n\n/**\n * Generates JSON Schema for a dynamic type (runtime-resolved enum or schema).\n *\n * Dynamic enums emit `x-formspec-source` and optionally `x-formspec-params`.\n * Dynamic schemas emit `x-formspec-schemaSource` with `additionalProperties: true`\n * since the actual schema is determined at runtime (per the JSON Schema vocabulary spec §3.2).\n */\nfunction generateDynamicType(type: DynamicTypeNode): JsonSchema2020 {\n if (type.dynamicKind === \"enum\") {\n const schema: JsonSchema2020 = {\n type: \"string\",\n \"x-formspec-source\": type.sourceKey,\n };\n if (type.parameterFields.length > 0) {\n schema[\"x-formspec-params\"] = [...type.parameterFields];\n }\n return schema;\n }\n\n // dynamicKind === \"schema\"\n return {\n type: \"object\",\n additionalProperties: true,\n \"x-formspec-schemaSource\": type.sourceKey,\n };\n}\n\n// =============================================================================\n// CONSTRAINT APPLICATION\n// =============================================================================\n\n/**\n * Applies constraint nodes onto an existing JSON Schema object (mutates in place).\n *\n * All callers pass freshly-created objects so there is no aliasing risk.\n *\n * Special rule (per the JSON Schema vocabulary spec §2.1): `multipleOf: 1` on a `\"number\"` type\n * promotes to `\"integer\"` and suppresses the `multipleOf` keyword (integer is a\n * subtype of number; expressing it via multipleOf:1 is redundant).\n *\n * Path-targeted constraints are handled separately by `applyPathTargetedConstraints`.\n */\nfunction applyConstraints(\n schema: JsonSchema2020,\n constraints: readonly ConstraintNode[],\n ctx: GeneratorContext\n): void {\n for (const constraint of constraints) {\n switch (constraint.constraintKind) {\n case \"minimum\":\n schema.minimum = constraint.value;\n break;\n\n case \"maximum\":\n schema.maximum = constraint.value;\n break;\n\n case \"exclusiveMinimum\":\n schema.exclusiveMinimum = constraint.value;\n break;\n\n case \"exclusiveMaximum\":\n schema.exclusiveMaximum = constraint.value;\n break;\n\n case \"multipleOf\": {\n const { value } = constraint;\n if (value === 1 && schema.type === \"number\") {\n // Promote number → integer; omit the multipleOf keyword (redundant).\n schema.type = \"integer\";\n } else {\n schema.multipleOf = value;\n }\n break;\n }\n\n case \"minLength\":\n schema.minLength = constraint.value;\n break;\n\n case \"maxLength\":\n schema.maxLength = constraint.value;\n break;\n\n case \"minItems\":\n schema.minItems = constraint.value;\n break;\n\n case \"maxItems\":\n schema.maxItems = constraint.value;\n break;\n\n case \"pattern\":\n schema.pattern = constraint.pattern;\n break;\n\n case \"uniqueItems\":\n schema.uniqueItems = constraint.value;\n break;\n\n case \"const\":\n schema.const = constraint.value;\n break;\n\n case \"allowedMembers\":\n // EnumMemberConstraintNode — not yet emitted to JSON Schema (Phase 6 validation).\n break;\n\n case \"custom\":\n applyCustomConstraint(schema, constraint, ctx);\n break;\n\n default: {\n // TypeScript exhaustiveness guard.\n const _exhaustive: never = constraint;\n void _exhaustive;\n }\n }\n }\n}\n\n// =============================================================================\n// ANNOTATION APPLICATION\n// =============================================================================\n\n/**\n * Applies annotation nodes onto an existing JSON Schema object (mutates in place).\n *\n * Mapping per the JSON Schema vocabulary spec §2.8:\n * - `displayName` → `title`\n * - `description` → `description` (from summary text, spec 002 §2.3)\n * - `remarks` → `x-<vendor>-remarks` (from @remarks, spec 003 §3.2)\n * - `defaultValue` → `default`\n * - `deprecated` → `deprecated: true` (2020-12 standard annotation)\n * - `format` → `format`\n *\n * UI-only annotations (`placeholder`, `formatHint`) are silently ignored here —\n * they belong in the UI Schema, not the data schema.\n */\nfunction applyAnnotations(\n schema: JsonSchema2020,\n annotations: readonly AnnotationNode[],\n ctx: GeneratorContext\n): void {\n for (const annotation of annotations) {\n switch (annotation.annotationKind) {\n case \"displayName\":\n schema.title = annotation.value;\n break;\n\n case \"description\":\n schema.description = annotation.value;\n break;\n\n case \"remarks\":\n schema[`${ctx.vendorPrefix}-remarks` as `x-${string}`] = annotation.value;\n break;\n\n case \"defaultValue\":\n schema.default = annotation.value;\n break;\n\n case \"format\":\n schema.format = annotation.value;\n break;\n\n case \"deprecated\":\n schema.deprecated = true;\n if (annotation.message !== undefined && annotation.message !== \"\") {\n schema[`${ctx.vendorPrefix}-deprecation-description` as `x-${string}`] =\n annotation.message;\n }\n break;\n\n case \"placeholder\":\n // UI-only — belongs in UI Schema, not emitted here.\n break;\n\n case \"formatHint\":\n // UI-only — belongs in UI Schema, not emitted here.\n break;\n\n case \"custom\":\n applyCustomAnnotation(schema, annotation, ctx);\n break;\n\n default: {\n // TypeScript exhaustiveness guard.\n const _exhaustive: never = annotation;\n void _exhaustive;\n }\n }\n }\n}\n\nfunction generateCustomType(type: CustomTypeNode, ctx: GeneratorContext): JsonSchema2020 {\n const registration = ctx.extensionRegistry?.findType(type.typeId);\n if (registration === undefined) {\n throw new Error(\n `Cannot generate JSON Schema for custom type \"${type.typeId}\" without a matching extension registration`\n );\n }\n\n // Trust boundary: extensions are responsible for returning valid JSON Schema.\n // Core only depends on Record<string, unknown> here, so we cast at the edge.\n return registration.toJsonSchema(type.payload, ctx.vendorPrefix) as JsonSchema2020;\n}\n\nfunction applyCustomConstraint(\n schema: JsonSchema2020,\n constraint: Extract<ConstraintNode, { constraintKind: \"custom\" }>,\n ctx: GeneratorContext\n): void {\n const registration = ctx.extensionRegistry?.findConstraint(constraint.constraintId);\n if (registration === undefined) {\n throw new Error(\n `Cannot generate JSON Schema for custom constraint \"${constraint.constraintId}\" without a matching extension registration`\n );\n }\n\n assignVendorPrefixedExtensionKeywords(\n schema,\n registration.toJsonSchema(constraint.payload, ctx.vendorPrefix),\n ctx.vendorPrefix,\n `custom constraint \"${constraint.constraintId}\"`\n );\n}\n\nfunction applyCustomAnnotation(\n schema: JsonSchema2020,\n annotation: Extract<AnnotationNode, { annotationKind: \"custom\" }>,\n ctx: GeneratorContext\n): void {\n const registration = ctx.extensionRegistry?.findAnnotation(annotation.annotationId);\n if (registration === undefined) {\n throw new Error(\n `Cannot generate JSON Schema for custom annotation \"${annotation.annotationId}\" without a matching extension registration`\n );\n }\n\n if (registration.toJsonSchema === undefined) {\n return;\n }\n\n assignVendorPrefixedExtensionKeywords(\n schema,\n registration.toJsonSchema(annotation.value, ctx.vendorPrefix),\n ctx.vendorPrefix,\n `custom annotation \"${annotation.annotationId}\"`\n );\n}\n\nfunction assignVendorPrefixedExtensionKeywords(\n schema: JsonSchema2020,\n extensionSchema: Record<string, unknown>,\n vendorPrefix: string,\n source: string\n): void {\n for (const [key, value] of Object.entries(extensionSchema)) {\n if (!key.startsWith(`${vendorPrefix}-`)) {\n throw new Error(\n `Cannot apply ${source}: extension hooks may only emit \"${vendorPrefix}-*\" JSON Schema keywords`\n );\n }\n schema[key as `x-${string}`] = value;\n }\n}\n","/**\n * JSON Schema generator for FormSpec forms.\n *\n * Routes through the canonical IR pipeline: Chain DSL → FormIR → JSON Schema 2020-12.\n */\n\nimport type { FormElement, FormSpec } from \"@formspec/core\";\nimport { canonicalizeChainDSL } from \"../canonicalize/index.js\";\nimport {\n generateJsonSchemaFromIR,\n type GenerateJsonSchemaFromIROptions,\n type JsonSchema2020,\n} from \"./ir-generator.js\";\n\n/**\n * Options for generating JSON Schema from a Chain DSL form.\n *\n * @public\n */\nexport interface GenerateJsonSchemaOptions {\n /**\n * Vendor prefix for emitted extension keywords.\n * @defaultValue \"x-formspec\"\n */\n readonly vendorPrefix?: string | undefined;\n}\n\n/**\n * Generates a JSON Schema 2020-12 from a FormSpec.\n *\n * All generation routes through the canonical IR. The chain DSL is first\n * canonicalized to a FormIR, then the IR-based generator produces the schema.\n *\n * @example\n * ```typescript\n * const form = formspec(\n * field.text(\"name\", { label: \"Name\", required: true }),\n * field.number(\"age\", { min: 0 }),\n * );\n *\n * const schema = generateJsonSchema(form);\n * // {\n * // $schema: \"https://json-schema.org/draft/2020-12/schema\",\n * // type: \"object\",\n * // properties: {\n * // name: { type: \"string\", title: \"Name\" },\n * // age: { type: \"number\", minimum: 0 }\n * // },\n * // required: [\"name\"]\n * // }\n * ```\n *\n * @param form - The FormSpec to convert\n * @returns A JSON Schema 2020-12 object\n *\n * @public\n */\nexport function generateJsonSchema<E extends readonly FormElement[]>(\n form: FormSpec<E>,\n options?: GenerateJsonSchemaOptions\n): JsonSchema2020 {\n const ir = canonicalizeChainDSL(form);\n const internalOptions: GenerateJsonSchemaFromIROptions | undefined =\n options?.vendorPrefix === undefined ? undefined : { vendorPrefix: options.vendorPrefix };\n return generateJsonSchemaFromIR(ir, internalOptions);\n}\n","/**\n * Zod schemas for JSON Forms UI Schema.\n *\n * These schemas are the source of truth for UI Schema validation.\n * TypeScript types are derived from these schemas via `z.infer<>`.\n *\n * @see https://jsonforms.io/docs/uischema/\n */\n\nimport { z } from \"zod\";\n\n// =============================================================================\n// Primitive helpers\n// =============================================================================\n\n/** JSON Pointer string (e.g., \"#/properties/fieldName\") */\nconst jsonPointerSchema = z.string();\n\n// =============================================================================\n// Rule Effect and Element Type enums\n// =============================================================================\n\n/**\n * Zod schema for rule effect values.\n *\n * @internal\n */\nexport const ruleEffectSchema = z.enum([\"SHOW\", \"HIDE\", \"ENABLE\", \"DISABLE\"]);\n\n/**\n * Rule effect types for conditional visibility.\n *\n * @internal\n */\nexport type RuleEffect = z.infer<typeof ruleEffectSchema>;\n\n/**\n * Zod schema for UI Schema element type strings.\n *\n * @internal\n */\nexport const uiSchemaElementTypeSchema = z.enum([\n \"Control\",\n \"VerticalLayout\",\n \"HorizontalLayout\",\n \"Group\",\n \"Categorization\",\n \"Category\",\n \"Label\",\n]);\n\n/**\n * UI Schema element types.\n *\n * @internal\n */\nexport type UISchemaElementType = z.infer<typeof uiSchemaElementTypeSchema>;\n\n// =============================================================================\n// Rule Condition Schema (recursive)\n// =============================================================================\n\n// Forward-declare the recursive TypeScript type.\n// We use an interface here (rather than z.infer<>) because the recursive\n// z.lazy() type annotation requires us to pre-declare the shape.\n/**\n * JSON Schema subset used in rule conditions.\n *\n * @internal\n */\nexport interface RuleConditionSchema {\n const?: unknown;\n enum?: readonly unknown[];\n type?: string;\n not?: RuleConditionSchema;\n minimum?: number;\n maximum?: number;\n exclusiveMinimum?: number;\n exclusiveMaximum?: number;\n minLength?: number;\n properties?: Record<string, RuleConditionSchema>;\n required?: string[];\n allOf?: RuleConditionSchema[];\n}\n\n/**\n * Zod schema for the rule-condition JSON Schema subset.\n *\n * @internal\n */\nexport const ruleConditionSchema: z.ZodType<RuleConditionSchema> = z.lazy(() =>\n z\n .object({\n const: z.unknown().optional(),\n enum: z.array(z.unknown()).readonly().optional(),\n type: z.string().optional(),\n not: ruleConditionSchema.optional(),\n minimum: z.number().optional(),\n maximum: z.number().optional(),\n exclusiveMinimum: z.number().optional(),\n exclusiveMaximum: z.number().optional(),\n minLength: z.number().optional(),\n properties: z.record(z.string(), ruleConditionSchema).optional(),\n required: z.array(z.string()).optional(),\n allOf: z.array(ruleConditionSchema).optional(),\n })\n .strict()\n) as z.ZodType<RuleConditionSchema>;\n\n// =============================================================================\n// Schema-Based Condition and Rule\n// =============================================================================\n\n/**\n * Zod schema for a schema-based rule condition.\n *\n * @internal\n */\nexport const schemaBasedConditionSchema = z\n .object({\n scope: jsonPointerSchema,\n schema: ruleConditionSchema,\n })\n .strict();\n\n/**\n * Condition for a rule.\n *\n * @internal\n */\nexport type SchemaBasedCondition = z.infer<typeof schemaBasedConditionSchema>;\n\n/**\n * Zod schema for a UI Schema rule.\n *\n * @internal\n */\nexport const ruleSchema = z\n .object({\n effect: ruleEffectSchema,\n condition: schemaBasedConditionSchema,\n })\n .strict();\n\n/**\n * Rule for conditional element visibility/enablement.\n *\n * @internal\n */\nexport type Rule = z.infer<typeof ruleSchema>;\n\n// =============================================================================\n// UI Schema Element Schemas (recursive via z.lazy)\n// =============================================================================\n\n// Forward-declare UISchemaElement so layout schemas can reference it.\n// We declare the type up-front and wire the Zod schema below.\n/**\n * Union of all UI Schema element types.\n *\n * @internal\n */\nexport type UISchemaElement =\n | ControlElement\n | VerticalLayout\n | HorizontalLayout\n | GroupLayout\n | Categorization\n | Category\n | LabelElement;\n\n// The Zod schema for UISchemaElement is defined as a const using z.lazy(),\n// which defers evaluation until first use. This allows all element schemas\n// below to be referenced even though they are declared after this line.\n/**\n * Zod schema for any UI Schema element.\n *\n * @internal\n */\nexport const uiSchemaElementSchema: z.ZodType<UISchemaElement> = z.lazy(() =>\n z.union([\n controlSchema,\n verticalLayoutSchema,\n horizontalLayoutSchema,\n groupLayoutSchema,\n categorizationSchema,\n categorySchema,\n labelElementSchema,\n ])\n) as z.ZodType<UISchemaElement>;\n\n// -----------------------------------------------------------------------------\n// Control\n// -----------------------------------------------------------------------------\n\n/**\n * Zod schema for a Control element.\n *\n * @internal\n */\nexport const controlSchema = z\n .object({\n type: z.literal(\"Control\"),\n scope: jsonPointerSchema,\n label: z.union([z.string(), z.literal(false)]).optional(),\n rule: ruleSchema.optional(),\n options: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough();\n\n/**\n * A Control element that binds to a JSON Schema property.\n *\n * @internal\n */\nexport type ControlElement = z.infer<typeof controlSchema>;\n\n// -----------------------------------------------------------------------------\n// VerticalLayout\n// -----------------------------------------------------------------------------\n\n// Pre-declare the interface so the Zod schema can reference UISchemaElement.\n/**\n * A vertical layout element.\n *\n * @internal\n */\nexport interface VerticalLayout {\n type: \"VerticalLayout\";\n elements: UISchemaElement[];\n rule?: Rule | undefined;\n options?: Record<string, unknown> | undefined;\n [k: string]: unknown;\n}\n\n/**\n * Zod schema for a vertical layout element.\n *\n * @internal\n */\nexport const verticalLayoutSchema: z.ZodType<VerticalLayout> = z.lazy(() =>\n z\n .object({\n type: z.literal(\"VerticalLayout\"),\n elements: z.array(uiSchemaElementSchema),\n rule: ruleSchema.optional(),\n options: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough()\n);\n\n// -----------------------------------------------------------------------------\n// HorizontalLayout\n// -----------------------------------------------------------------------------\n\n/**\n * A horizontal layout element.\n *\n * @internal\n */\nexport interface HorizontalLayout {\n type: \"HorizontalLayout\";\n elements: UISchemaElement[];\n rule?: Rule | undefined;\n options?: Record<string, unknown> | undefined;\n [k: string]: unknown;\n}\n\n/**\n * Zod schema for a horizontal layout element.\n *\n * @internal\n */\nexport const horizontalLayoutSchema: z.ZodType<HorizontalLayout> = z.lazy(() =>\n z\n .object({\n type: z.literal(\"HorizontalLayout\"),\n elements: z.array(uiSchemaElementSchema),\n rule: ruleSchema.optional(),\n options: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough()\n);\n\n// -----------------------------------------------------------------------------\n// GroupLayout\n// -----------------------------------------------------------------------------\n\n/**\n * A group element with a label.\n *\n * @internal\n */\nexport interface GroupLayout {\n type: \"Group\";\n label: string;\n elements: UISchemaElement[];\n rule?: Rule | undefined;\n options?: Record<string, unknown> | undefined;\n [k: string]: unknown;\n}\n\n/**\n * Zod schema for a group layout element.\n *\n * @internal\n */\nexport const groupLayoutSchema: z.ZodType<GroupLayout> = z.lazy(() =>\n z\n .object({\n type: z.literal(\"Group\"),\n label: z.string(),\n elements: z.array(uiSchemaElementSchema),\n rule: ruleSchema.optional(),\n options: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough()\n);\n\n// -----------------------------------------------------------------------------\n// Category\n// -----------------------------------------------------------------------------\n\n/**\n * A Category element, used inside a Categorization layout.\n *\n * @internal\n */\nexport interface Category {\n type: \"Category\";\n label: string;\n elements: UISchemaElement[];\n rule?: Rule | undefined;\n options?: Record<string, unknown> | undefined;\n [k: string]: unknown;\n}\n\n/**\n * Zod schema for a category element.\n *\n * @internal\n */\nexport const categorySchema: z.ZodType<Category> = z.lazy(() =>\n z\n .object({\n type: z.literal(\"Category\"),\n label: z.string(),\n elements: z.array(uiSchemaElementSchema),\n rule: ruleSchema.optional(),\n options: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough()\n);\n\n// -----------------------------------------------------------------------------\n// Categorization\n// -----------------------------------------------------------------------------\n\n/**\n * A Categorization element (tab-based layout).\n *\n * @internal\n */\nexport interface Categorization {\n type: \"Categorization\";\n elements: Category[];\n label?: string | undefined;\n rule?: Rule | undefined;\n options?: Record<string, unknown> | undefined;\n [k: string]: unknown;\n}\n\n/**\n * Zod schema for a categorization element.\n *\n * @internal\n */\nexport const categorizationSchema: z.ZodType<Categorization> = z.lazy(() =>\n z\n .object({\n type: z.literal(\"Categorization\"),\n elements: z.array(categorySchema),\n label: z.string().optional(),\n rule: ruleSchema.optional(),\n options: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough()\n);\n\n// -----------------------------------------------------------------------------\n// LabelElement\n// -----------------------------------------------------------------------------\n\n/**\n * Zod schema for a Label element.\n *\n * @internal\n */\nexport const labelElementSchema = z\n .object({\n type: z.literal(\"Label\"),\n text: z.string(),\n rule: ruleSchema.optional(),\n options: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough();\n\n/**\n * A Label element for displaying static text.\n *\n * @internal\n */\nexport type LabelElement = z.infer<typeof labelElementSchema>;\n\n// =============================================================================\n// Root UISchema\n// =============================================================================\n\n/**\n * Root UI Schema (always a layout — not a Control, Category, or Label).\n *\n * @internal\n */\nexport type UISchema = VerticalLayout | HorizontalLayout | GroupLayout | Categorization;\n\n/**\n * Zod schema for the root UI Schema (layout types only).\n *\n * @internal\n */\nexport const uiSchema: z.ZodType<UISchema> = z.lazy(() =>\n z.union([verticalLayoutSchema, horizontalLayoutSchema, groupLayoutSchema, categorizationSchema])\n) as z.ZodType<UISchema>;\n","/**\n * JSON Forms UI Schema generator that operates on the canonical FormIR.\n *\n * This generator consumes the IR produced by the Canonicalize phase and\n * produces a JSON Forms UI Schema. All downstream UI Schema generation\n * should use this module for UI Schema generation.\n */\n\nimport type { FormIR, FormIRElement, FieldNode, GroupLayoutNode } from \"@formspec/core/internals\";\nimport type {\n UISchema,\n UISchemaElement,\n ControlElement,\n GroupLayout,\n Rule,\n RuleConditionSchema,\n} from \"./types.js\";\nimport { uiSchema as uiSchemaValidator } from \"./schema.js\";\nimport { z } from \"zod\";\n\n// =============================================================================\n// HELPERS\n// =============================================================================\n\n/**\n * Parses a value through a Zod schema, converting validation errors to a\n * descriptive Error.\n */\nfunction parseOrThrow<T>(schema: z.ZodType<T>, value: unknown, label: string): T {\n try {\n return schema.parse(value);\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(\n `Generated ${label} failed validation:\\n${error.issues.map((i) => ` ${i.path.join(\".\")}: ${i.message}`).join(\"\\n\")}`\n );\n }\n throw error;\n }\n}\n\n/**\n * Converts a field name to a JSON Pointer scope string.\n */\nfunction fieldToScope(fieldName: string): string {\n return `#/properties/${fieldName}`;\n}\n\n/**\n * Creates a SHOW rule for a single conditional field/value pair.\n */\nfunction createShowRule(fieldName: string, value: unknown): Rule {\n return {\n effect: \"SHOW\",\n condition: {\n scope: fieldToScope(fieldName),\n schema: { const: value },\n },\n };\n}\n\n/**\n * Combines two SHOW rules into a single rule using an allOf condition.\n *\n * When elements are nested inside multiple conditionals, all parent conditions\n * must be met for the element to be visible. This function flattens both\n * conditions into a single rule using a top-level allOf so JSON Forms evaluates\n * every predicate simultaneously without nesting rule fragments.\n */\nfunction flattenConditionSchema(scope: string, schema: RuleConditionSchema): RuleConditionSchema[] {\n if (schema.allOf === undefined) {\n if (scope === \"#\") {\n return [schema];\n }\n\n const fieldName = scope.replace(\"#/properties/\", \"\");\n return [\n {\n properties: {\n [fieldName]: schema,\n },\n },\n ];\n }\n\n return schema.allOf.flatMap((member) => flattenConditionSchema(scope, member));\n}\n\nfunction combineRules(parentRule: Rule, childRule: Rule): Rule {\n return {\n effect: \"SHOW\",\n condition: {\n scope: \"#\",\n schema: {\n allOf: [\n ...flattenConditionSchema(parentRule.condition.scope, parentRule.condition.schema),\n ...flattenConditionSchema(childRule.condition.scope, childRule.condition.schema),\n ],\n },\n },\n };\n}\n\n// =============================================================================\n// ELEMENT CONVERSION\n// =============================================================================\n\n/**\n * Converts a FieldNode from the IR to a ControlElement.\n *\n * The label is sourced from the first `displayName` annotation on the field,\n * matching how the chain DSL propagates the `label` option through the\n * canonicalization phase.\n */\nfunction fieldNodeToControl(field: FieldNode, parentRule?: Rule): ControlElement {\n const displayNameAnnotation = field.annotations.find((a) => a.annotationKind === \"displayName\");\n const placeholderAnnotation = field.annotations.find((a) => a.annotationKind === \"placeholder\");\n\n const control: ControlElement = {\n type: \"Control\",\n scope: fieldToScope(field.name),\n ...(displayNameAnnotation !== undefined && { label: displayNameAnnotation.value }),\n ...(placeholderAnnotation !== undefined && {\n options: { placeholder: placeholderAnnotation.value },\n }),\n ...(parentRule !== undefined && { rule: parentRule }),\n };\n\n return control;\n}\n\n/**\n * Converts a GroupLayoutNode from the IR to a GroupLayout element.\n *\n * The group's children are recursively converted; the optional parent rule is\n * forwarded to nested elements so that a group inside a conditional inherits\n * the visibility rule.\n */\nfunction groupNodeToLayout(group: GroupLayoutNode, parentRule?: Rule): GroupLayout {\n return {\n type: \"Group\",\n label: group.label,\n elements: irElementsToUiSchema(group.elements, parentRule),\n ...(parentRule !== undefined && { rule: parentRule }),\n };\n}\n\n/**\n * Converts an array of IR elements to UI Schema elements.\n *\n * @param elements - The IR elements to convert\n * @param parentRule - Optional rule inherited from a parent ConditionalLayoutNode\n * @returns Array of UI Schema elements\n */\nfunction irElementsToUiSchema(\n elements: readonly FormIRElement[],\n parentRule?: Rule\n): UISchemaElement[] {\n const result: UISchemaElement[] = [];\n\n for (const element of elements) {\n switch (element.kind) {\n case \"field\": {\n result.push(fieldNodeToControl(element, parentRule));\n break;\n }\n\n case \"group\": {\n result.push(groupNodeToLayout(element, parentRule));\n break;\n }\n\n case \"conditional\": {\n // Build the rule for this conditional level.\n const newRule = createShowRule(element.fieldName, element.value);\n // Combine with the inherited parent rule for nested conditionals.\n const combinedRule = parentRule !== undefined ? combineRules(parentRule, newRule) : newRule;\n // Children are flattened into the parent container with the combined\n // rule attached.\n const childElements = irElementsToUiSchema(element.elements, combinedRule);\n result.push(...childElements);\n break;\n }\n\n default: {\n const _exhaustive: never = element;\n void _exhaustive;\n throw new Error(\"Unhandled IR element kind\");\n }\n }\n }\n\n return result;\n}\n\n// =============================================================================\n// PUBLIC API\n// =============================================================================\n\n/**\n * Generates a JSON Forms UI Schema from a canonical `FormIR`.\n *\n * Mapping rules:\n * - `FieldNode` → `ControlElement` with `scope: \"#/properties/<name>\"`\n * - `displayName` annotation → `label` on the `ControlElement`\n * - `GroupLayoutNode` → `GroupLayout` with recursively converted `elements`\n * - `ConditionalLayoutNode` → children flattened with a `SHOW` rule\n * - Nested conditionals → combined `allOf` rule\n * - Root wrapper is always `{ type: \"VerticalLayout\", elements: [...] }`\n *\n * @example\n * ```typescript\n * const ir = canonicalizeDSL(\n * formspec(\n * group(\"Customer\", field.text(\"name\", { label: \"Name\" })),\n * when(is(\"status\", \"draft\"), field.text(\"notes\", { label: \"Notes\" })),\n * )\n * );\n *\n * const uiSchema = generateUiSchemaFromIR(ir);\n * // {\n * // type: \"VerticalLayout\",\n * // elements: [\n * // {\n * // type: \"Group\",\n * // label: \"Customer\",\n * // elements: [{ type: \"Control\", scope: \"#/properties/name\", label: \"Name\" }]\n * // },\n * // {\n * // type: \"Control\",\n * // scope: \"#/properties/notes\",\n * // label: \"Notes\",\n * // rule: { effect: \"SHOW\", condition: { scope: \"#/properties/status\", schema: { const: \"draft\" } } }\n * // }\n * // ]\n * // }\n * ```\n *\n * @param ir - The canonical FormIR produced by the Canonicalize phase\n * @returns A validated JSON Forms UI Schema\n */\nexport function generateUiSchemaFromIR(ir: FormIR): UISchema {\n const result: UISchema = {\n type: \"VerticalLayout\",\n elements: irElementsToUiSchema(ir.elements),\n };\n\n return parseOrThrow(uiSchemaValidator, result, \"UI Schema\");\n}\n","/**\n * JSON Forms UI Schema generator for FormSpec forms.\n *\n * Routes through the canonical IR pipeline: Chain DSL → FormIR → UI Schema.\n */\n\nimport type { FormElement, FormSpec } from \"@formspec/core\";\nimport { canonicalizeChainDSL } from \"../canonicalize/index.js\";\nimport { generateUiSchemaFromIR } from \"./ir-generator.js\";\nimport type { UISchema } from \"./types.js\";\n\n/**\n * Generates a JSON Forms UI Schema from a FormSpec.\n *\n * All generation routes through the canonical IR. The chain DSL is first\n * canonicalized to a FormIR, then the IR-based generator produces the schema.\n *\n * @example\n * ```typescript\n * const form = formspec(\n * group(\"Customer\",\n * field.text(\"name\", { label: \"Name\" }),\n * ),\n * when(\"status\", \"draft\",\n * field.text(\"notes\", { label: \"Notes\" }),\n * ),\n * );\n *\n * const uiSchema = generateUiSchema(form);\n * // {\n * // type: \"VerticalLayout\",\n * // elements: [\n * // {\n * // type: \"Group\",\n * // label: \"Customer\",\n * // elements: [\n * // { type: \"Control\", scope: \"#/properties/name\", label: \"Name\" }\n * // ]\n * // },\n * // {\n * // type: \"Control\",\n * // scope: \"#/properties/notes\",\n * // label: \"Notes\",\n * // rule: {\n * // effect: \"SHOW\",\n * // condition: { scope: \"#/properties/status\", schema: { const: \"draft\" } }\n * // }\n * // }\n * // ]\n * // }\n * ```\n *\n * @param form - The FormSpec to convert\n * @returns A JSON Forms UI Schema\n *\n * @public\n */\nexport function generateUiSchema<E extends readonly FormElement[]>(form: FormSpec<E>): UISchema {\n const ir = canonicalizeChainDSL(form);\n return generateUiSchemaFromIR(ir);\n}\n","/**\n * `@formspec/build` - Build tools for FormSpec\n *\n * This package provides generators to compile FormSpec forms into:\n * - JSON Schema 2020-12 (for validation)\n * - JSON Forms UI Schema (for rendering)\n *\n * @example\n * ```typescript\n * import { buildFormSchemas } from \"@formspec/build\";\n * import { formspec, field, group } from \"@formspec/dsl\";\n *\n * const form = formspec(\n * group(\"Customer\",\n * field.text(\"name\", { label: \"Name\", required: true }),\n * field.text(\"email\", { label: \"Email\" }),\n * ),\n * );\n *\n * const { jsonSchema, uiSchema } = buildFormSchemas(form);\n * ```\n *\n * @packageDocumentation\n */\n\nimport type { FormElement, FormSpec } from \"@formspec/core\";\nimport { generateJsonSchema, type GenerateJsonSchemaOptions } from \"./json-schema/generator.js\";\nimport { generateUiSchema } from \"./ui-schema/generator.js\";\nimport { type JsonSchema2020 } from \"./json-schema/ir-generator.js\";\nimport type { UISchema } from \"./ui-schema/types.js\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\n// =============================================================================\n// Type Exports\n// =============================================================================\n\nexport type { JsonSchema2020 } from \"./json-schema/ir-generator.js\";\nexport type { GenerateJsonSchemaOptions } from \"./json-schema/generator.js\";\nexport type {\n AnyField,\n ArrayField,\n BooleanField,\n Conditional,\n DynamicEnumField,\n DynamicSchemaField,\n ExtensionApplicableType,\n ExtensionDefinition,\n ExtensionPayloadValue,\n ExtensionTypeKind,\n EnumOption,\n EnumOptionValue,\n FormElement,\n FormSpec,\n Group,\n NumberField,\n ObjectField,\n StaticEnumField,\n TextField,\n CustomAnnotationRegistration,\n CustomConstraintRegistration,\n CustomTypeRegistration,\n ConstraintTagRegistration,\n BuiltinConstraintBroadeningRegistration,\n BuiltinConstraintName,\n ConstraintSemanticRole,\n VocabularyKeywordRegistration,\n} from \"@formspec/core\";\n\nexport type {\n JSONSchema7,\n JSONSchemaType,\n ExtendedJSONSchema7,\n FormSpecSchemaExtensions,\n} from \"./json-schema/types.js\";\n\nexport { createExtensionRegistry } from \"./extensions/index.js\";\nexport type { ExtensionRegistry } from \"./extensions/index.js\";\n\nexport type {\n UISchema,\n UISchemaElement,\n UISchemaElementBase,\n UISchemaElementType,\n ControlElement,\n VerticalLayout,\n HorizontalLayout,\n GroupLayout,\n Categorization,\n Category,\n LabelElement,\n Rule,\n RuleEffect,\n RuleConditionSchema,\n SchemaBasedCondition,\n} from \"./ui-schema/types.js\";\n\nexport type {\n StaticSchemaGenerationOptions,\n GenerateFromClassOptions,\n GenerateFromClassResult,\n GenerateSchemasOptions,\n} from \"./generators/class-schema.js\";\nexport type {\n BuildMixedAuthoringSchemasOptions,\n MixedAuthoringSchemas,\n} from \"./generators/mixed-authoring.js\";\n\n// =============================================================================\n// Chain DSL Generators\n// =============================================================================\n\nexport { generateJsonSchema } from \"./json-schema/generator.js\";\nexport { generateUiSchema } from \"./ui-schema/generator.js\";\nexport { generateSchemasFromClass, generateSchemas } from \"./generators/class-schema.js\";\nexport { buildMixedAuthoringSchemas } from \"./generators/mixed-authoring.js\";\n\n/**\n * Result of building form schemas.\n *\n * @public\n */\nexport interface BuildResult {\n /** JSON Schema 2020-12 for validation */\n readonly jsonSchema: JsonSchema2020;\n /** JSON Forms UI Schema for rendering */\n readonly uiSchema: UISchema;\n}\n\n/**\n * Options for building schemas from a FormSpec.\n *\n * Currently identical to `GenerateJsonSchemaOptions`. Defined separately so the\n * Chain DSL surface can grow independently in the future if needed.\n *\n * @public\n */\nexport type BuildFormSchemasOptions = GenerateJsonSchemaOptions;\n\n/**\n * Builds both JSON Schema and UI Schema from a FormSpec.\n *\n * This is a convenience function that combines `generateJsonSchema`\n * and `generateUiSchema`.\n *\n * @example\n * ```typescript\n * const form = formspec(\n * field.text(\"name\", { required: true }),\n * field.number(\"age\", { min: 0 }),\n * );\n *\n * const { jsonSchema, uiSchema } = buildFormSchemas(form);\n *\n * // Use with JSON Forms renderer\n * <JsonForms\n * schema={jsonSchema}\n * uischema={uiSchema}\n * data={formData}\n * renderers={materialRenderers}\n * />\n * ```\n *\n * @param form - The FormSpec to build schemas from\n * @returns Object containing both jsonSchema and uiSchema\n *\n * @public\n */\nexport function buildFormSchemas<E extends readonly FormElement[]>(\n form: FormSpec<E>,\n options?: BuildFormSchemasOptions\n): BuildResult {\n return {\n jsonSchema: generateJsonSchema(form, options),\n uiSchema: generateUiSchema(form),\n };\n}\n\n/**\n * Options for writing schemas to disk.\n *\n * @public\n */\nexport interface WriteSchemasOptions extends GenerateJsonSchemaOptions {\n /** Output directory for the schema files */\n readonly outDir: string;\n /** Base name for the output files (without extension). Defaults to \"schema\" */\n readonly name?: string;\n /** Number of spaces for JSON indentation. Defaults to 2 */\n readonly indent?: number;\n}\n\n/**\n * Result of writing schemas to disk.\n *\n * @public\n */\nexport interface WriteSchemasResult {\n /** Path to the generated JSON Schema file */\n readonly jsonSchemaPath: string;\n /** Path to the generated UI Schema file */\n readonly uiSchemaPath: string;\n}\n\n/**\n * Builds and writes both JSON Schema and UI Schema files to disk.\n *\n * This is a convenience function for build-time schema generation.\n * It creates the output directory if it doesn't exist.\n *\n * @example\n * ```typescript\n * import { formspec, field } from \"formspec\";\n * import { writeSchemas } from \"@formspec/build\";\n *\n * const ProductForm = formspec(\n * field.text(\"name\", { required: true }),\n * field.enum(\"status\", [\"draft\", \"active\"]),\n * );\n *\n * // Write schemas to ./generated/product-schema.json and ./generated/product-uischema.json\n * const { jsonSchemaPath, uiSchemaPath } = writeSchemas(ProductForm, {\n * outDir: \"./generated\",\n * name: \"product\",\n * });\n *\n * console.log(`Generated: ${jsonSchemaPath}, ${uiSchemaPath}`);\n * ```\n *\n * @param form - The FormSpec to build schemas from\n * @param options - Output options (directory, file name, indentation)\n * @returns Object containing paths to the generated files\n *\n * @public\n */\nexport function writeSchemas<E extends readonly FormElement[]>(\n form: FormSpec<E>,\n options: WriteSchemasOptions\n): WriteSchemasResult {\n const { outDir, name = \"schema\", indent = 2, vendorPrefix } = options;\n\n // Build schemas\n const buildOptions = vendorPrefix === undefined ? undefined : { vendorPrefix };\n\n const { jsonSchema, uiSchema } = buildFormSchemas(form, buildOptions);\n\n // Ensure output directory exists\n if (!fs.existsSync(outDir)) {\n fs.mkdirSync(outDir, { recursive: true });\n }\n\n // Write files\n const jsonSchemaPath = path.join(outDir, `${name}-schema.json`);\n const uiSchemaPath = path.join(outDir, `${name}-uischema.json`);\n\n fs.writeFileSync(jsonSchemaPath, JSON.stringify(jsonSchema, null, indent));\n fs.writeFileSync(uiSchemaPath, JSON.stringify(uiSchema, null, indent));\n\n return { jsonSchemaPath, uiSchemaPath };\n}\n","/**\n * Extension registry for resolving custom types, constraints, and annotations\n * during JSON Schema generation and IR validation.\n *\n * The registry is created from a list of {@link ExtensionDefinition} objects\n * and provides O(1) lookup by fully-qualified ID (extensionId + \"/\" + name).\n *\n * @packageDocumentation\n */\n\nimport type {\n ExtensionDefinition,\n CustomTypeRegistration,\n CustomConstraintRegistration,\n CustomAnnotationRegistration,\n ConstraintTagRegistration,\n BuiltinConstraintBroadeningRegistration,\n} from \"@formspec/core\";\n\n// =============================================================================\n// PUBLIC API\n// =============================================================================\n\n/**\n * A registry of extensions that provides lookup by fully-qualified ID.\n *\n * Type IDs follow the format: `<extensionId>/<typeName>`\n * Constraint IDs follow the format: `<extensionId>/<constraintName>`\n * Annotation IDs follow the format: `<extensionId>/<annotationName>`\n *\n * @public\n */\nexport interface ExtensionRegistry {\n /** The extensions registered in this registry (in registration order). */\n readonly extensions: readonly ExtensionDefinition[];\n\n /**\n * Look up a custom type registration by its fully-qualified type ID.\n *\n * @param typeId - The fully-qualified type ID (e.g., \"x-stripe/monetary/Decimal\").\n * @returns The registration if found, otherwise `undefined`.\n */\n findType(typeId: string): CustomTypeRegistration | undefined;\n /**\n * Look up a custom type registration by a TypeScript-facing type name.\n *\n * This is used during TSDoc/class analysis to resolve extension-defined\n * custom types from source-level declarations.\n */\n findTypeByName(\n typeName: string\n ): { readonly extensionId: string; readonly registration: CustomTypeRegistration } | undefined;\n\n /**\n * Look up a custom constraint registration by its fully-qualified constraint ID.\n *\n * @param constraintId - The fully-qualified constraint ID.\n * @returns The registration if found, otherwise `undefined`.\n */\n findConstraint(constraintId: string): CustomConstraintRegistration | undefined;\n /**\n * Look up a TSDoc custom constraint-tag registration by tag name.\n */\n findConstraintTag(tagName: string):\n | {\n readonly extensionId: string;\n readonly registration: ConstraintTagRegistration;\n }\n | undefined;\n /**\n * Look up built-in tag broadening for a given custom type ID.\n */\n findBuiltinConstraintBroadening(\n typeId: string,\n tagName: string\n ):\n | {\n readonly extensionId: string;\n readonly registration: BuiltinConstraintBroadeningRegistration;\n }\n | undefined;\n\n /**\n * Look up a custom annotation registration by its fully-qualified annotation ID.\n *\n * @param annotationId - The fully-qualified annotation ID.\n * @returns The registration if found, otherwise `undefined`.\n */\n findAnnotation(annotationId: string): CustomAnnotationRegistration | undefined;\n}\n\n// =============================================================================\n// IMPLEMENTATION\n// =============================================================================\n\n/**\n * Creates an extension registry from a list of extension definitions.\n *\n * The registry indexes all types, constraints, and annotations by their\n * fully-qualified IDs (`<extensionId>/<name>`) for O(1) lookup during\n * generation and validation.\n *\n * @param extensions - The extension definitions to register.\n * @returns An {@link ExtensionRegistry} instance.\n * @throws If duplicate type/constraint/annotation IDs are detected across extensions.\n *\n * @public\n */\nexport function createExtensionRegistry(\n extensions: readonly ExtensionDefinition[]\n): ExtensionRegistry {\n const typeMap = new Map<string, CustomTypeRegistration>();\n const typeNameMap = new Map<\n string,\n { readonly extensionId: string; readonly registration: CustomTypeRegistration }\n >();\n const constraintMap = new Map<string, CustomConstraintRegistration>();\n const constraintTagMap = new Map<\n string,\n { readonly extensionId: string; readonly registration: ConstraintTagRegistration }\n >();\n const builtinBroadeningMap = new Map<\n string,\n { readonly extensionId: string; readonly registration: BuiltinConstraintBroadeningRegistration }\n >();\n const annotationMap = new Map<string, CustomAnnotationRegistration>();\n\n for (const ext of extensions) {\n if (ext.types !== undefined) {\n for (const type of ext.types) {\n const qualifiedId = `${ext.extensionId}/${type.typeName}`;\n if (typeMap.has(qualifiedId)) {\n throw new Error(`Duplicate custom type ID: \"${qualifiedId}\"`);\n }\n typeMap.set(qualifiedId, type);\n\n for (const sourceTypeName of type.tsTypeNames ?? [type.typeName]) {\n if (typeNameMap.has(sourceTypeName)) {\n throw new Error(`Duplicate custom type source name: \"${sourceTypeName}\"`);\n }\n typeNameMap.set(sourceTypeName, {\n extensionId: ext.extensionId,\n registration: type,\n });\n }\n\n if (type.builtinConstraintBroadenings !== undefined) {\n for (const broadening of type.builtinConstraintBroadenings) {\n const key = `${qualifiedId}:${broadening.tagName}`;\n if (builtinBroadeningMap.has(key)) {\n throw new Error(`Duplicate built-in constraint broadening: \"${key}\"`);\n }\n builtinBroadeningMap.set(key, {\n extensionId: ext.extensionId,\n registration: broadening,\n });\n }\n }\n }\n }\n\n if (ext.constraints !== undefined) {\n for (const constraint of ext.constraints) {\n const qualifiedId = `${ext.extensionId}/${constraint.constraintName}`;\n if (constraintMap.has(qualifiedId)) {\n throw new Error(`Duplicate custom constraint ID: \"${qualifiedId}\"`);\n }\n constraintMap.set(qualifiedId, constraint);\n }\n }\n\n if (ext.constraintTags !== undefined) {\n for (const tag of ext.constraintTags) {\n if (constraintTagMap.has(tag.tagName)) {\n throw new Error(`Duplicate custom constraint tag: \"@${tag.tagName}\"`);\n }\n constraintTagMap.set(tag.tagName, {\n extensionId: ext.extensionId,\n registration: tag,\n });\n }\n }\n\n if (ext.annotations !== undefined) {\n for (const annotation of ext.annotations) {\n const qualifiedId = `${ext.extensionId}/${annotation.annotationName}`;\n if (annotationMap.has(qualifiedId)) {\n throw new Error(`Duplicate custom annotation ID: \"${qualifiedId}\"`);\n }\n annotationMap.set(qualifiedId, annotation);\n }\n }\n }\n\n return {\n extensions,\n findType: (typeId: string) => typeMap.get(typeId),\n findTypeByName: (typeName: string) => typeNameMap.get(typeName),\n findConstraint: (constraintId: string) => constraintMap.get(constraintId),\n findConstraintTag: (tagName: string) => constraintTagMap.get(tagName),\n findBuiltinConstraintBroadening: (typeId: string, tagName: string) =>\n builtinBroadeningMap.get(`${typeId}:${tagName}`),\n findAnnotation: (annotationId: string) => annotationMap.get(annotationId),\n };\n}\n","/**\n * TypeScript program setup for static analysis.\n *\n * Creates a TypeScript program with type checker from a source file,\n * using the project's tsconfig.json for compiler options.\n */\n\nimport * as ts from \"typescript\";\nimport * as path from \"node:path\";\nimport {\n analyzeClassToIR,\n analyzeInterfaceToIR,\n analyzeTypeAliasToIR,\n type IRClassAnalysis,\n} from \"./class-analyzer.js\";\nimport type { ExtensionRegistry } from \"../extensions/index.js\";\n\n/**\n * Result of creating a TypeScript program for analysis.\n */\nexport interface ProgramContext {\n /** The TypeScript program */\n program: ts.Program;\n /** Type checker for resolving types */\n checker: ts.TypeChecker;\n /** The source file being analyzed */\n sourceFile: ts.SourceFile;\n}\n\n/**\n * Creates a TypeScript program for analyzing a source file.\n *\n * Looks for tsconfig.json in the file's directory or parent directories.\n * Falls back to default compiler options if no config is found.\n *\n * @param filePath - Absolute path to the TypeScript source file\n * @returns Program context with checker and source file\n */\nexport function createProgramContext(filePath: string): ProgramContext {\n const absolutePath = path.resolve(filePath);\n const fileDir = path.dirname(absolutePath);\n\n // Find tsconfig.json - using ts.sys.fileExists which has `this: void` requirement\n const configPath = ts.findConfigFile(fileDir, ts.sys.fileExists.bind(ts.sys), \"tsconfig.json\");\n\n let compilerOptions: ts.CompilerOptions;\n let fileNames: string[];\n\n if (configPath) {\n const configFile = ts.readConfigFile(configPath, ts.sys.readFile.bind(ts.sys));\n if (configFile.error) {\n throw new Error(\n `Error reading tsconfig.json: ${ts.flattenDiagnosticMessageText(configFile.error.messageText, \"\\n\")}`\n );\n }\n\n const parsed = ts.parseJsonConfigFileContent(\n configFile.config,\n ts.sys,\n path.dirname(configPath)\n );\n\n if (parsed.errors.length > 0) {\n const errorMessages = parsed.errors\n .map((e) => ts.flattenDiagnosticMessageText(e.messageText, \"\\n\"))\n .join(\"\\n\");\n throw new Error(`Error parsing tsconfig.json: ${errorMessages}`);\n }\n\n compilerOptions = parsed.options;\n // Include the target file in the program\n fileNames = parsed.fileNames.includes(absolutePath)\n ? parsed.fileNames\n : [...parsed.fileNames, absolutePath];\n } else {\n // Fallback to default options\n compilerOptions = {\n target: ts.ScriptTarget.ES2022,\n module: ts.ModuleKind.NodeNext,\n moduleResolution: ts.ModuleResolutionKind.NodeNext,\n strict: true,\n skipLibCheck: true,\n declaration: true,\n };\n fileNames = [absolutePath];\n }\n\n const program = ts.createProgram(fileNames, compilerOptions);\n const sourceFile = program.getSourceFile(absolutePath);\n\n if (!sourceFile) {\n throw new Error(`Could not find source file: ${absolutePath}`);\n }\n\n return {\n program,\n checker: program.getTypeChecker(),\n sourceFile,\n };\n}\n\n/**\n * Generic AST node finder by name. Walks the source file tree and returns\n * the first node matching the predicate with the given name.\n */\nfunction findNodeByName<T extends ts.Node>(\n sourceFile: ts.SourceFile,\n name: string,\n predicate: (node: ts.Node) => node is T,\n getName: (node: T) => string | undefined\n): T | null {\n let result: T | null = null;\n\n function visit(node: ts.Node): void {\n if (result) return;\n\n if (predicate(node) && getName(node) === name) {\n result = node;\n return;\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return result;\n}\n\n/**\n * Finds a class declaration by name in a source file.\n *\n * @param sourceFile - The source file to search\n * @param className - Name of the class to find\n * @returns The class declaration node, or null if not found\n */\nexport function findClassByName(\n sourceFile: ts.SourceFile,\n className: string\n): ts.ClassDeclaration | null {\n return findNodeByName(sourceFile, className, ts.isClassDeclaration, (n) => n.name?.text);\n}\n\n/**\n * Finds an interface declaration by name in a source file.\n *\n * @param sourceFile - The source file to search\n * @param interfaceName - Name of the interface to find\n * @returns The interface declaration node, or null if not found\n */\nexport function findInterfaceByName(\n sourceFile: ts.SourceFile,\n interfaceName: string\n): ts.InterfaceDeclaration | null {\n return findNodeByName(sourceFile, interfaceName, ts.isInterfaceDeclaration, (n) => n.name.text);\n}\n\n/**\n * Finds a type alias declaration by name in a source file.\n *\n * @param sourceFile - The source file to search\n * @param aliasName - Name of the type alias to find\n * @returns The type alias declaration node, or null if not found\n */\nexport function findTypeAliasByName(\n sourceFile: ts.SourceFile,\n aliasName: string\n): ts.TypeAliasDeclaration | null {\n return findNodeByName(sourceFile, aliasName, ts.isTypeAliasDeclaration, (n) => n.name.text);\n}\n\n/**\n * Analyzes a named type (class, interface, or type alias) from a TypeScript\n * source file and returns an `IRClassAnalysis`.\n *\n * Tries each declaration kind in order: class → interface → type alias.\n * Throws if the name is not found or if the type alias analysis fails.\n *\n * @param filePath - Absolute or relative path to the TypeScript source file (resolved internally)\n * @param typeName - Name of the class, interface, or type alias to analyze\n * @param extensionRegistry - Optional extension registry for custom type handling\n * @returns IR analysis result\n */\nexport function analyzeNamedTypeToIR(\n filePath: string,\n typeName: string,\n extensionRegistry?: ExtensionRegistry\n): IRClassAnalysis {\n const ctx = createProgramContext(filePath);\n\n const classDecl = findClassByName(ctx.sourceFile, typeName);\n if (classDecl !== null) {\n return analyzeClassToIR(classDecl, ctx.checker, filePath, extensionRegistry);\n }\n\n const interfaceDecl = findInterfaceByName(ctx.sourceFile, typeName);\n if (interfaceDecl !== null) {\n return analyzeInterfaceToIR(interfaceDecl, ctx.checker, filePath, extensionRegistry);\n }\n\n const typeAlias = findTypeAliasByName(ctx.sourceFile, typeName);\n if (typeAlias !== null) {\n const result = analyzeTypeAliasToIR(typeAlias, ctx.checker, filePath, extensionRegistry);\n if (result.ok) {\n return result.analysis;\n }\n throw new Error(result.error);\n }\n\n throw new Error(\n `Type \"${typeName}\" not found as a class, interface, or type alias in ${filePath}`\n );\n}\n","/**\n * Class analyzer for extracting fields, types, and JSDoc constraints.\n *\n * Produces `IRClassAnalysis` containing `FieldNode[]` and `typeRegistry`\n * directly from class, interface, or type alias declarations.\n * All downstream generation routes through the canonical FormIR.\n */\n\nimport * as ts from \"typescript\";\nimport type { ConstraintSemanticDiagnostic } from \"@formspec/analysis/internal\";\nimport type {\n FieldNode,\n TypeNode,\n EnumTypeNode,\n EnumMember,\n ConstraintNode,\n AnnotationNode,\n Provenance,\n ObjectProperty,\n RecordTypeNode,\n TypeDefinition,\n JsonValue,\n} from \"@formspec/core/internals\";\nimport {\n extractJSDocConstraintNodes,\n extractJSDocAnnotationNodes,\n extractDefaultValueAnnotation,\n extractJSDocParseResult,\n} from \"./jsdoc-constraints.js\";\nimport { extractDisplayNameMetadata } from \"./tsdoc-parser.js\";\nimport type { ExtensionRegistry } from \"../extensions/index.js\";\n\n// =============================================================================\n// TYPE GUARDS\n// =============================================================================\n\n/**\n * Type guard for ts.ObjectType — checks that the TypeFlags.Object bit is set.\n */\nfunction isObjectType(type: ts.Type): type is ts.ObjectType {\n return !!(type.flags & ts.TypeFlags.Object);\n}\n\n/**\n * Type guard for ts.TypeReference — checks ObjectFlags.Reference on top of ObjectType.\n * The internal `as` cast is isolated inside this guard and is required because\n * TypeScript's public API does not expose objectFlags on ts.Type directly.\n */\nfunction isTypeReference(type: ts.Type): type is ts.TypeReference {\n // as cast is isolated inside type guard\n return (\n !!(type.flags & ts.TypeFlags.Object) &&\n !!((type as ts.ObjectType).objectFlags & ts.ObjectFlags.Reference)\n );\n}\n\n/**\n * Placeholder used while a named object type is still being expanded.\n *\n * The object identity matters: final empty-object schemas are distinct\n * instances, so we can tell an in-progress registry entry from a real one.\n */\nconst RESOLVING_TYPE_PLACEHOLDER: TypeNode = {\n kind: \"object\",\n properties: [],\n additionalProperties: true,\n};\n\nfunction makeParseOptions(\n extensionRegistry: ExtensionRegistry | undefined,\n fieldType?: TypeNode,\n checker?: ts.TypeChecker,\n subjectType?: ts.Type,\n hostType?: ts.Type\n): import(\"./tsdoc-parser.js\").ParseTSDocOptions | undefined {\n if (\n extensionRegistry === undefined &&\n fieldType === undefined &&\n checker === undefined &&\n subjectType === undefined &&\n hostType === undefined\n ) {\n return undefined;\n }\n\n return {\n ...(extensionRegistry !== undefined && { extensionRegistry }),\n ...(fieldType !== undefined && { fieldType }),\n ...(checker !== undefined && { checker }),\n ...(subjectType !== undefined && { subjectType }),\n ...(hostType !== undefined && { hostType }),\n };\n}\n\n// =============================================================================\n// IR OUTPUT TYPES\n// =============================================================================\n\n/**\n * Layout metadata extracted from `@Group` and `@ShowWhen` TSDoc tags.\n * One entry per field, in the same order as `fields`.\n */\nexport interface FieldLayoutMetadata {\n /** Group label from `@Group(\"label\")`, or undefined if ungrouped. */\n readonly groupLabel?: string;\n /** ShowWhen condition from `@ShowWhen({ field, value })`, or undefined if always visible. */\n readonly showWhen?: { readonly field: string; readonly value: JsonValue };\n}\n\n/**\n * Result of analyzing a class/interface/type alias into canonical IR.\n */\nexport interface IRClassAnalysis {\n /** Type name */\n readonly name: string;\n /** Analyzed fields as canonical IR FieldNodes */\n readonly fields: readonly FieldNode[];\n /** Layout metadata per field (same order/length as `fields`). */\n readonly fieldLayouts: readonly FieldLayoutMetadata[];\n /** Named type definitions referenced by fields */\n readonly typeRegistry: Record<string, TypeDefinition>;\n /** Root-level metadata for the analyzed declaration. */\n readonly annotations?: readonly AnnotationNode[];\n /** Extraction-time diagnostics surfaced before IR validation. */\n readonly diagnostics?: readonly ConstraintSemanticDiagnostic[];\n /** Instance methods (retained for downstream method-schema generation) */\n readonly instanceMethods: readonly MethodInfo[];\n /** Static methods */\n readonly staticMethods: readonly MethodInfo[];\n}\n\n/**\n * Result of analyzing a type alias into IR — either success or error.\n */\nexport type AnalyzeTypeAliasToIRResult =\n | { readonly ok: true; readonly analysis: IRClassAnalysis }\n | { readonly ok: false; readonly error: string };\n\n// =============================================================================\n// IR ANALYSIS — PUBLIC API\n// =============================================================================\n\n/**\n * Analyzes a class declaration and produces canonical IR FieldNodes.\n */\nexport function analyzeClassToIR(\n classDecl: ts.ClassDeclaration,\n checker: ts.TypeChecker,\n file = \"\",\n extensionRegistry?: ExtensionRegistry\n): IRClassAnalysis {\n const name = classDecl.name?.text ?? \"AnonymousClass\";\n const fields: FieldNode[] = [];\n const fieldLayouts: FieldLayoutMetadata[] = [];\n const typeRegistry: Record<string, TypeDefinition> = {};\n const diagnostics: ConstraintSemanticDiagnostic[] = [];\n const classType = checker.getTypeAtLocation(classDecl);\n const classDoc = extractJSDocParseResult(\n classDecl,\n file,\n makeParseOptions(extensionRegistry, undefined, checker, classType, classType)\n );\n const annotations = [...classDoc.annotations];\n diagnostics.push(...classDoc.diagnostics);\n const visiting = new Set<ts.Type>();\n const instanceMethods: MethodInfo[] = [];\n const staticMethods: MethodInfo[] = [];\n\n for (const member of classDecl.members) {\n if (ts.isPropertyDeclaration(member)) {\n const fieldNode = analyzeFieldToIR(\n member,\n checker,\n file,\n typeRegistry,\n visiting,\n diagnostics,\n classType,\n extensionRegistry\n );\n if (fieldNode) {\n fields.push(fieldNode);\n fieldLayouts.push({});\n }\n } else if (ts.isMethodDeclaration(member)) {\n const methodInfo = analyzeMethod(member, checker);\n if (methodInfo) {\n const isStatic = member.modifiers?.some((m) => m.kind === ts.SyntaxKind.StaticKeyword);\n if (isStatic) {\n staticMethods.push(methodInfo);\n } else {\n instanceMethods.push(methodInfo);\n }\n }\n }\n }\n\n return {\n name,\n fields,\n fieldLayouts,\n typeRegistry,\n ...(annotations.length > 0 && { annotations }),\n ...(diagnostics.length > 0 && { diagnostics }),\n instanceMethods,\n staticMethods,\n };\n}\n\n/**\n * Analyzes an interface declaration and produces canonical IR FieldNodes.\n */\nexport function analyzeInterfaceToIR(\n interfaceDecl: ts.InterfaceDeclaration,\n checker: ts.TypeChecker,\n file = \"\",\n extensionRegistry?: ExtensionRegistry\n): IRClassAnalysis {\n const name = interfaceDecl.name.text;\n const fields: FieldNode[] = [];\n const typeRegistry: Record<string, TypeDefinition> = {};\n const diagnostics: ConstraintSemanticDiagnostic[] = [];\n const interfaceType = checker.getTypeAtLocation(interfaceDecl);\n const interfaceDoc = extractJSDocParseResult(\n interfaceDecl,\n file,\n makeParseOptions(extensionRegistry, undefined, checker, interfaceType, interfaceType)\n );\n const annotations = [...interfaceDoc.annotations];\n diagnostics.push(...interfaceDoc.diagnostics);\n const visiting = new Set<ts.Type>();\n\n for (const member of interfaceDecl.members) {\n if (ts.isPropertySignature(member)) {\n const fieldNode = analyzeInterfacePropertyToIR(\n member,\n checker,\n file,\n typeRegistry,\n visiting,\n diagnostics,\n interfaceType,\n extensionRegistry\n );\n if (fieldNode) {\n fields.push(fieldNode);\n }\n }\n }\n\n const fieldLayouts: FieldLayoutMetadata[] = fields.map(() => ({}));\n return {\n name,\n fields,\n fieldLayouts,\n typeRegistry,\n ...(annotations.length > 0 && { annotations }),\n ...(diagnostics.length > 0 && { diagnostics }),\n instanceMethods: [],\n staticMethods: [],\n };\n}\n\n/**\n * Analyzes a type alias declaration and produces canonical IR FieldNodes.\n */\nexport function analyzeTypeAliasToIR(\n typeAlias: ts.TypeAliasDeclaration,\n checker: ts.TypeChecker,\n file = \"\",\n extensionRegistry?: ExtensionRegistry\n): AnalyzeTypeAliasToIRResult {\n if (!ts.isTypeLiteralNode(typeAlias.type)) {\n const sourceFile = typeAlias.getSourceFile();\n const { line } = sourceFile.getLineAndCharacterOfPosition(typeAlias.getStart());\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- enum reverse mapping can be undefined for compiler-internal kinds\n const kindDesc = ts.SyntaxKind[typeAlias.type.kind] ?? \"unknown\";\n return {\n ok: false,\n error: `Type alias \"${typeAlias.name.text}\" at line ${String(line + 1)} is not an object type literal (found ${kindDesc})`,\n };\n }\n\n const name = typeAlias.name.text;\n const fields: FieldNode[] = [];\n const typeRegistry: Record<string, TypeDefinition> = {};\n const diagnostics: ConstraintSemanticDiagnostic[] = [];\n const aliasType = checker.getTypeAtLocation(typeAlias);\n const typeAliasDoc = extractJSDocParseResult(\n typeAlias,\n file,\n makeParseOptions(extensionRegistry, undefined, checker, aliasType, aliasType)\n );\n const annotations = [...typeAliasDoc.annotations];\n diagnostics.push(...typeAliasDoc.diagnostics);\n const visiting = new Set<ts.Type>();\n\n for (const member of typeAlias.type.members) {\n if (ts.isPropertySignature(member)) {\n const fieldNode = analyzeInterfacePropertyToIR(\n member,\n checker,\n file,\n typeRegistry,\n visiting,\n diagnostics,\n aliasType,\n extensionRegistry\n );\n if (fieldNode) {\n fields.push(fieldNode);\n }\n }\n }\n\n return {\n ok: true,\n analysis: {\n name,\n fields,\n fieldLayouts: fields.map(() => ({})),\n typeRegistry,\n ...(annotations.length > 0 && { annotations }),\n ...(diagnostics.length > 0 && { diagnostics }),\n instanceMethods: [],\n staticMethods: [],\n },\n };\n}\n\n// =============================================================================\n// IR FIELD ANALYSIS — PRIVATE\n// =============================================================================\n\n/**\n * Analyzes a class property declaration into a canonical IR FieldNode.\n */\nfunction analyzeFieldToIR(\n prop: ts.PropertyDeclaration,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n diagnostics: ConstraintSemanticDiagnostic[],\n hostType: ts.Type,\n extensionRegistry?: ExtensionRegistry\n): FieldNode | null {\n if (!ts.isIdentifier(prop.name)) {\n return null;\n }\n\n const name = prop.name.text;\n const tsType = checker.getTypeAtLocation(prop);\n const optional = prop.questionToken !== undefined;\n const provenance = provenanceForNode(prop, file);\n\n // Resolve ts.Type → TypeNode\n let type = resolveTypeNode(\n tsType,\n checker,\n file,\n typeRegistry,\n visiting,\n prop,\n extensionRegistry,\n diagnostics\n );\n\n // Collect constraints\n const constraints: ConstraintNode[] = [];\n\n // Inherit constraints from type alias declarations (lower precedence)\n if (prop.type && !shouldEmitPrimitiveAliasDefinition(prop.type, checker)) {\n constraints.push(\n ...extractTypeAliasConstraintNodes(prop.type, checker, file, extensionRegistry)\n );\n }\n\n // Extract JSDoc constraints\n const docResult = extractJSDocParseResult(\n prop,\n file,\n makeParseOptions(extensionRegistry, type, checker, tsType, hostType)\n );\n constraints.push(...docResult.constraints);\n diagnostics.push(...docResult.diagnostics);\n\n // Collect annotations\n let annotations: AnnotationNode[] = [];\n\n // JSDoc annotations (@displayName, @deprecated, summary, @remarks)\n annotations.push(...docResult.annotations);\n\n // Default value annotation\n const defaultAnnotation = extractDefaultValueAnnotation(prop.initializer, file);\n if (defaultAnnotation && !annotations.some((a) => a.annotationKind === \"defaultValue\")) {\n annotations.push(defaultAnnotation);\n }\n\n ({ type, annotations } = applyEnumMemberDisplayNames(type, annotations));\n\n return {\n kind: \"field\",\n name,\n type,\n required: !optional,\n constraints,\n annotations,\n provenance,\n };\n}\n\n/**\n * Analyzes an interface/type-alias property signature into a canonical IR FieldNode.\n */\nfunction analyzeInterfacePropertyToIR(\n prop: ts.PropertySignature,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n diagnostics: ConstraintSemanticDiagnostic[],\n hostType: ts.Type,\n extensionRegistry?: ExtensionRegistry\n): FieldNode | null {\n if (!ts.isIdentifier(prop.name)) {\n return null;\n }\n\n const name = prop.name.text;\n const tsType = checker.getTypeAtLocation(prop);\n const optional = prop.questionToken !== undefined;\n const provenance = provenanceForNode(prop, file);\n\n // Resolve ts.Type → TypeNode\n let type = resolveTypeNode(\n tsType,\n checker,\n file,\n typeRegistry,\n visiting,\n prop,\n extensionRegistry,\n diagnostics\n );\n\n // Collect constraints\n const constraints: ConstraintNode[] = [];\n\n // Inherit constraints from type alias declarations\n if (prop.type && !shouldEmitPrimitiveAliasDefinition(prop.type, checker)) {\n constraints.push(\n ...extractTypeAliasConstraintNodes(prop.type, checker, file, extensionRegistry)\n );\n }\n\n // JSDoc constraints\n const docResult = extractJSDocParseResult(\n prop,\n file,\n makeParseOptions(extensionRegistry, type, checker, tsType, hostType)\n );\n constraints.push(...docResult.constraints);\n diagnostics.push(...docResult.diagnostics);\n\n // Collect annotations\n let annotations: AnnotationNode[] = [];\n\n // JSDoc annotations (@displayName, @deprecated, summary, @remarks)\n annotations.push(...docResult.annotations);\n\n ({ type, annotations } = applyEnumMemberDisplayNames(type, annotations));\n\n return {\n kind: \"field\",\n name,\n type,\n required: !optional,\n constraints,\n annotations,\n provenance,\n };\n}\n\n/**\n * Rewrites enum-member display-name annotations into EnumMember.displayName\n * values and strips those annotations from the field-level annotation list.\n *\n * The TSDoc surface uses `@displayName :value Label` for enum member labels.\n * Plain `@displayName Label` annotations remain as field-level titles.\n */\nfunction applyEnumMemberDisplayNames(\n type: TypeNode,\n annotations: readonly AnnotationNode[]\n): { type: TypeNode; annotations: AnnotationNode[] } {\n if (\n !annotations.some(\n (annotation) =>\n annotation.annotationKind === \"displayName\" && annotation.value.trim().startsWith(\":\")\n )\n ) {\n return { type, annotations: [...annotations] };\n }\n\n const consumed = new Set<AnnotationNode>();\n const nextType = rewriteEnumDisplayNames(type, annotations, consumed);\n\n if (consumed.size === 0) {\n return { type, annotations: [...annotations] };\n }\n\n return {\n type: nextType,\n annotations: annotations.filter((annotation) => !consumed.has(annotation)),\n };\n}\n\nfunction rewriteEnumDisplayNames(\n type: TypeNode,\n annotations: readonly AnnotationNode[],\n consumed: Set<AnnotationNode>\n): TypeNode {\n switch (type.kind) {\n case \"enum\":\n return applyEnumMemberDisplayNamesToEnum(type, annotations, consumed);\n\n case \"union\": {\n return {\n ...type,\n members: type.members.map((member) =>\n rewriteEnumDisplayNames(member, annotations, consumed)\n ),\n };\n }\n\n default:\n return type;\n }\n}\n\nfunction applyEnumMemberDisplayNamesToEnum(\n type: EnumTypeNode,\n annotations: readonly AnnotationNode[],\n consumed: Set<AnnotationNode>\n): EnumTypeNode {\n const displayNames = new Map<string, string>();\n\n for (const annotation of annotations) {\n if (annotation.annotationKind !== \"displayName\") continue;\n\n const parsed = parseEnumMemberDisplayName(annotation.value);\n if (!parsed) continue;\n\n // Once parsed as a member-target display name, never let it fall back to a\n // field-level title, even if the target value does not exist.\n consumed.add(annotation);\n\n const member = type.members.find((m) => String(m.value) === parsed.value);\n if (!member) continue;\n\n displayNames.set(String(member.value), parsed.label);\n }\n\n if (displayNames.size === 0) {\n return type;\n }\n\n return {\n ...type,\n members: type.members.map((member) => {\n const displayName = displayNames.get(String(member.value));\n return displayName !== undefined ? { ...member, displayName } : member;\n }),\n };\n}\n\nfunction parseEnumMemberDisplayName(value: string): { value: string; label: string } | null {\n const trimmed = value.trim();\n const match = /^:([^\\s]+)\\s+([\\s\\S]+)$/.exec(trimmed);\n if (!match?.[1] || !match[2]) return null;\n\n const label = match[2].trim();\n if (label === \"\") return null;\n\n return { value: match[1], label };\n}\n\nfunction resolveRegisteredCustomType(\n sourceNode: ts.Node | undefined,\n extensionRegistry: ExtensionRegistry | undefined,\n checker: ts.TypeChecker\n): TypeNode | null {\n if (sourceNode === undefined || extensionRegistry === undefined) {\n return null;\n }\n\n const typeNode = extractTypeNodeFromSource(sourceNode);\n if (typeNode === undefined) {\n return null;\n }\n\n return resolveRegisteredCustomTypeFromTypeNode(typeNode, extensionRegistry, checker);\n}\n\nfunction resolveRegisteredCustomTypeFromTypeNode(\n typeNode: ts.TypeNode,\n extensionRegistry: ExtensionRegistry,\n checker: ts.TypeChecker\n): TypeNode | null {\n if (ts.isParenthesizedTypeNode(typeNode)) {\n return resolveRegisteredCustomTypeFromTypeNode(typeNode.type, extensionRegistry, checker);\n }\n\n const typeName = getTypeNodeRegistrationName(typeNode);\n if (typeName === null) {\n return null;\n }\n\n const registration = extensionRegistry.findTypeByName(typeName);\n if (registration !== undefined) {\n return {\n kind: \"custom\",\n typeId: `${registration.extensionId}/${registration.registration.typeName}`,\n payload: null,\n };\n }\n\n if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) {\n const aliasDecl = checker\n .getSymbolAtLocation(typeNode.typeName)\n ?.declarations?.find(ts.isTypeAliasDeclaration);\n if (aliasDecl !== undefined) {\n return resolveRegisteredCustomTypeFromTypeNode(aliasDecl.type, extensionRegistry, checker);\n }\n }\n\n return null;\n}\n\nfunction extractTypeNodeFromSource(sourceNode: ts.Node): ts.TypeNode | undefined {\n if (\n ts.isPropertyDeclaration(sourceNode) ||\n ts.isPropertySignature(sourceNode) ||\n ts.isParameter(sourceNode) ||\n ts.isTypeAliasDeclaration(sourceNode)\n ) {\n return sourceNode.type;\n }\n\n if (ts.isTypeNode(sourceNode)) {\n return sourceNode;\n }\n\n return undefined;\n}\n\nfunction getTypeNodeRegistrationName(typeNode: ts.TypeNode): string | null {\n if (ts.isTypeReferenceNode(typeNode)) {\n return ts.isIdentifier(typeNode.typeName)\n ? typeNode.typeName.text\n : typeNode.typeName.right.text;\n }\n\n if (ts.isParenthesizedTypeNode(typeNode)) {\n return getTypeNodeRegistrationName(typeNode.type);\n }\n\n if (\n typeNode.kind === ts.SyntaxKind.BigIntKeyword ||\n typeNode.kind === ts.SyntaxKind.StringKeyword ||\n typeNode.kind === ts.SyntaxKind.NumberKeyword ||\n typeNode.kind === ts.SyntaxKind.BooleanKeyword\n ) {\n return typeNode.getText();\n }\n\n return null;\n}\n\n// =============================================================================\n// TYPE RESOLUTION — ts.Type → TypeNode\n// =============================================================================\n\n/**\n * Resolves a TypeScript type to a canonical IR TypeNode.\n */\nexport function resolveTypeNode(\n type: ts.Type,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n sourceNode?: ts.Node,\n extensionRegistry?: ExtensionRegistry,\n diagnostics?: ConstraintSemanticDiagnostic[]\n): TypeNode {\n const customType = resolveRegisteredCustomType(sourceNode, extensionRegistry, checker);\n if (customType) {\n return customType;\n }\n const primitiveAlias = tryResolveNamedPrimitiveAlias(\n type,\n checker,\n file,\n typeRegistry,\n visiting,\n sourceNode,\n extensionRegistry,\n diagnostics\n );\n if (primitiveAlias) {\n return primitiveAlias;\n }\n\n // --- Primitives ---\n if (type.flags & ts.TypeFlags.String) {\n return { kind: \"primitive\", primitiveKind: \"string\" };\n }\n if (type.flags & ts.TypeFlags.Number) {\n return { kind: \"primitive\", primitiveKind: \"number\" };\n }\n if (type.flags & (ts.TypeFlags.BigInt | ts.TypeFlags.BigIntLiteral)) {\n return { kind: \"primitive\", primitiveKind: \"bigint\" };\n }\n if (type.flags & ts.TypeFlags.Boolean) {\n return { kind: \"primitive\", primitiveKind: \"boolean\" };\n }\n if (type.flags & ts.TypeFlags.Null) {\n return { kind: \"primitive\", primitiveKind: \"null\" };\n }\n if (type.flags & ts.TypeFlags.Undefined) {\n // Undefined maps to null for nullable semantics in JSON Schema\n return { kind: \"primitive\", primitiveKind: \"null\" };\n }\n\n // --- String literal ---\n if (type.isStringLiteral()) {\n return {\n kind: \"enum\",\n members: [{ value: type.value }],\n };\n }\n\n // --- Number literal ---\n if (type.isNumberLiteral()) {\n return {\n kind: \"enum\",\n members: [{ value: type.value }],\n };\n }\n\n // --- Union types ---\n if (type.isUnion()) {\n return resolveUnionType(\n type,\n checker,\n file,\n typeRegistry,\n visiting,\n sourceNode,\n extensionRegistry,\n diagnostics\n );\n }\n\n // --- Array types ---\n if (checker.isArrayType(type)) {\n return resolveArrayType(\n type,\n checker,\n file,\n typeRegistry,\n visiting,\n sourceNode,\n extensionRegistry,\n diagnostics\n );\n }\n\n // --- Object types ---\n if (isObjectType(type)) {\n return resolveObjectType(\n type,\n checker,\n file,\n typeRegistry,\n visiting,\n extensionRegistry,\n diagnostics\n );\n }\n\n // --- Fallback: treat unknown/any/void as string ---\n return { kind: \"primitive\", primitiveKind: \"string\" };\n}\n\nfunction tryResolveNamedPrimitiveAlias(\n type: ts.Type,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n sourceNode?: ts.Node,\n extensionRegistry?: ExtensionRegistry,\n diagnostics?: ConstraintSemanticDiagnostic[]\n): TypeNode | null {\n if (\n !(\n type.flags &\n (ts.TypeFlags.String |\n ts.TypeFlags.Number |\n ts.TypeFlags.BigInt |\n ts.TypeFlags.BigIntLiteral |\n ts.TypeFlags.Boolean |\n ts.TypeFlags.Null)\n )\n ) {\n return null;\n }\n\n const aliasDecl =\n type.aliasSymbol?.declarations?.find(ts.isTypeAliasDeclaration) ??\n getReferencedTypeAliasDeclaration(sourceNode, checker);\n if (!aliasDecl) {\n return null;\n }\n\n const aliasName = aliasDecl.name.text;\n if (!typeRegistry[aliasName]) {\n const aliasType = checker.getTypeFromTypeNode(aliasDecl.type);\n const constraints = [\n ...extractJSDocConstraintNodes(aliasDecl, file, makeParseOptions(extensionRegistry)),\n ...extractTypeAliasConstraintNodes(aliasDecl.type, checker, file, extensionRegistry),\n ];\n const annotations = extractJSDocAnnotationNodes(\n aliasDecl,\n file,\n makeParseOptions(extensionRegistry)\n );\n typeRegistry[aliasName] = {\n name: aliasName,\n type: resolveAliasedPrimitiveTarget(\n aliasType,\n checker,\n file,\n typeRegistry,\n visiting,\n extensionRegistry,\n diagnostics\n ),\n ...(constraints.length > 0 && { constraints }),\n ...(annotations.length > 0 && { annotations }),\n provenance: provenanceForDeclaration(aliasDecl, file),\n };\n }\n\n return { kind: \"reference\", name: aliasName, typeArguments: [] };\n}\n\nfunction getReferencedTypeAliasDeclaration(\n sourceNode: ts.Node | undefined,\n checker: ts.TypeChecker\n): ts.TypeAliasDeclaration | undefined {\n const typeNode =\n sourceNode &&\n (ts.isPropertyDeclaration(sourceNode) ||\n ts.isPropertySignature(sourceNode) ||\n ts.isParameter(sourceNode))\n ? sourceNode.type\n : undefined;\n if (!typeNode || !ts.isTypeReferenceNode(typeNode)) {\n return undefined;\n }\n\n return checker\n .getSymbolAtLocation(typeNode.typeName)\n ?.declarations?.find(ts.isTypeAliasDeclaration);\n}\n\nfunction shouldEmitPrimitiveAliasDefinition(\n typeNode: ts.TypeNode,\n checker: ts.TypeChecker\n): boolean {\n if (!ts.isTypeReferenceNode(typeNode)) {\n return false;\n }\n\n const aliasDecl = checker\n .getSymbolAtLocation(typeNode.typeName)\n ?.declarations?.find(ts.isTypeAliasDeclaration);\n if (!aliasDecl) {\n return false;\n }\n\n const resolved = checker.getTypeFromTypeNode(aliasDecl.type);\n return !!(\n resolved.flags &\n (ts.TypeFlags.String |\n ts.TypeFlags.Number |\n ts.TypeFlags.BigInt |\n ts.TypeFlags.BigIntLiteral |\n ts.TypeFlags.Boolean |\n ts.TypeFlags.Null)\n );\n}\n\nfunction resolveAliasedPrimitiveTarget(\n type: ts.Type,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n extensionRegistry?: ExtensionRegistry,\n diagnostics?: ConstraintSemanticDiagnostic[]\n): TypeNode {\n const nestedAliasDecl = type.aliasSymbol?.declarations?.find(ts.isTypeAliasDeclaration);\n if (nestedAliasDecl !== undefined) {\n return resolveAliasedPrimitiveTarget(\n checker.getTypeFromTypeNode(nestedAliasDecl.type),\n checker,\n file,\n typeRegistry,\n visiting,\n extensionRegistry,\n diagnostics\n );\n }\n\n return resolveTypeNode(\n type,\n checker,\n file,\n typeRegistry,\n visiting,\n undefined,\n extensionRegistry,\n diagnostics\n );\n}\n\nfunction resolveUnionType(\n type: ts.UnionType,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n sourceNode?: ts.Node,\n extensionRegistry?: ExtensionRegistry,\n diagnostics?: ConstraintSemanticDiagnostic[]\n): TypeNode {\n const typeName = getNamedTypeName(type);\n const namedDecl = getNamedTypeDeclaration(type);\n\n if (typeName && typeName in typeRegistry) {\n return { kind: \"reference\", name: typeName, typeArguments: [] };\n }\n\n const allTypes = type.types;\n const unionMemberTypeNodes = extractUnionMemberTypeNodes(sourceNode, checker);\n const nonNullSourceNodes = unionMemberTypeNodes.filter(\n (memberTypeNode) => !isNullishTypeNode(resolveAliasedTypeNode(memberTypeNode, checker))\n );\n const nonNullTypes = allTypes.filter(\n (memberType) => !(memberType.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined))\n );\n const nonNullMembers = nonNullTypes.map((memberType, index) => ({\n memberType,\n sourceNode:\n nonNullSourceNodes.length === nonNullTypes.length ? nonNullSourceNodes[index] : undefined,\n }));\n const hasNull = allTypes.some((t) => t.flags & ts.TypeFlags.Null);\n const memberDisplayNames = new Map<string, string>();\n if (namedDecl) {\n for (const [value, label] of extractDisplayNameMetadata(namedDecl).memberDisplayNames) {\n memberDisplayNames.set(value, label);\n }\n }\n if (sourceNode) {\n for (const [value, label] of extractDisplayNameMetadata(sourceNode).memberDisplayNames) {\n memberDisplayNames.set(value, label);\n }\n }\n\n const registerNamed = (result: TypeNode): TypeNode => {\n if (!typeName) {\n return result;\n }\n const annotations = namedDecl\n ? extractJSDocAnnotationNodes(namedDecl, file, makeParseOptions(extensionRegistry))\n : undefined;\n typeRegistry[typeName] = {\n name: typeName,\n type: result,\n ...(annotations !== undefined && annotations.length > 0 && { annotations }),\n provenance: provenanceForDeclaration(namedDecl ?? sourceNode, file),\n };\n return { kind: \"reference\", name: typeName, typeArguments: [] };\n };\n\n const applyMemberLabels = (members: readonly (string | number)[]): EnumMember[] =>\n members.map((value) => {\n const displayName = memberDisplayNames.get(String(value));\n return displayName !== undefined ? { value, displayName } : { value };\n });\n\n const isBooleanUnion =\n nonNullTypes.length === 2 && nonNullTypes.every((t) => t.flags & ts.TypeFlags.BooleanLiteral);\n\n if (isBooleanUnion) {\n const boolNode: TypeNode = { kind: \"primitive\", primitiveKind: \"boolean\" };\n const result: TypeNode = hasNull\n ? {\n kind: \"union\",\n members: [boolNode, { kind: \"primitive\", primitiveKind: \"null\" }],\n }\n : boolNode;\n return registerNamed(result);\n }\n\n const allStringLiterals = nonNullTypes.every((t) => t.isStringLiteral());\n if (allStringLiterals && nonNullTypes.length > 0) {\n const stringTypes = nonNullTypes.filter((t): t is ts.StringLiteralType => t.isStringLiteral());\n const enumNode: TypeNode = {\n kind: \"enum\",\n members: applyMemberLabels(stringTypes.map((t) => t.value)),\n };\n const result: TypeNode = hasNull\n ? {\n kind: \"union\",\n members: [enumNode, { kind: \"primitive\", primitiveKind: \"null\" }],\n }\n : enumNode;\n return registerNamed(result);\n }\n\n const allNumberLiterals = nonNullTypes.every((t) => t.isNumberLiteral());\n if (allNumberLiterals && nonNullTypes.length > 0) {\n const numberTypes = nonNullTypes.filter((t): t is ts.NumberLiteralType => t.isNumberLiteral());\n const enumNode: TypeNode = {\n kind: \"enum\",\n members: applyMemberLabels(numberTypes.map((t) => t.value)),\n };\n const result: TypeNode = hasNull\n ? {\n kind: \"union\",\n members: [enumNode, { kind: \"primitive\", primitiveKind: \"null\" }],\n }\n : enumNode;\n return registerNamed(result);\n }\n\n if (nonNullMembers.length === 1 && nonNullMembers[0]) {\n const inner = resolveTypeNode(\n nonNullMembers[0].memberType,\n checker,\n file,\n typeRegistry,\n visiting,\n nonNullMembers[0].sourceNode ?? sourceNode,\n extensionRegistry,\n diagnostics\n );\n const result: TypeNode = hasNull\n ? {\n kind: \"union\",\n members: [inner, { kind: \"primitive\", primitiveKind: \"null\" }],\n }\n : inner;\n return registerNamed(result);\n }\n\n const members = nonNullMembers.map(({ memberType, sourceNode: memberSourceNode }) =>\n resolveTypeNode(\n memberType,\n checker,\n file,\n typeRegistry,\n visiting,\n memberSourceNode ?? sourceNode,\n extensionRegistry,\n diagnostics\n )\n );\n if (hasNull) {\n members.push({ kind: \"primitive\", primitiveKind: \"null\" });\n }\n return registerNamed({ kind: \"union\", members });\n}\n\nfunction resolveArrayType(\n type: ts.Type,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n sourceNode?: ts.Node,\n extensionRegistry?: ExtensionRegistry,\n diagnostics?: ConstraintSemanticDiagnostic[]\n): TypeNode {\n const typeArgs = isTypeReference(type) ? type.typeArguments : undefined;\n const elementType = typeArgs?.[0];\n const elementSourceNode = extractArrayElementTypeNode(sourceNode, checker);\n\n const items = elementType\n ? resolveTypeNode(\n elementType,\n checker,\n file,\n typeRegistry,\n visiting,\n elementSourceNode,\n extensionRegistry,\n diagnostics\n )\n : ({ kind: \"primitive\", primitiveKind: \"string\" } satisfies TypeNode);\n\n return { kind: \"array\", items };\n}\n\n/**\n * Returns a `RecordTypeNode` if `type` is a pure dictionary type (string index\n * signature with no named properties), or `null` otherwise.\n *\n * This handles both `Record<string, T>` (a mapped/aliased type) and inline\n * `{ [k: string]: T }` index signature types per spec 003 §2.5.\n */\nfunction tryResolveRecordType(\n type: ts.ObjectType,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n extensionRegistry?: ExtensionRegistry,\n diagnostics?: ConstraintSemanticDiagnostic[]\n): RecordTypeNode | null {\n // Only types with no named properties qualify as pure dictionaries.\n if (type.getProperties().length > 0) {\n return null;\n }\n const indexInfo = checker.getIndexInfoOfType(type, ts.IndexKind.String);\n if (!indexInfo) {\n return null;\n }\n\n const valueType = resolveTypeNode(\n indexInfo.type,\n checker,\n file,\n typeRegistry,\n visiting,\n undefined,\n extensionRegistry,\n diagnostics\n );\n return { kind: \"record\", valueType };\n}\n\nfunction typeNodeContainsReference(type: TypeNode, targetName: string): boolean {\n switch (type.kind) {\n case \"reference\":\n return type.name === targetName;\n case \"array\":\n return typeNodeContainsReference(type.items, targetName);\n case \"record\":\n return typeNodeContainsReference(type.valueType, targetName);\n case \"union\":\n return type.members.some((member) => typeNodeContainsReference(member, targetName));\n case \"object\":\n return type.properties.some((property) =>\n typeNodeContainsReference(property.type, targetName)\n );\n case \"primitive\":\n case \"enum\":\n case \"dynamic\":\n case \"custom\":\n return false;\n default: {\n const _exhaustive: never = type;\n return _exhaustive;\n }\n }\n}\n\nfunction resolveObjectType(\n type: ts.ObjectType,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n extensionRegistry?: ExtensionRegistry,\n diagnostics?: ConstraintSemanticDiagnostic[]\n): TypeNode {\n const typeName = getNamedTypeName(type);\n const namedTypeName = typeName ?? undefined;\n const namedDecl = getNamedTypeDeclaration(type);\n const shouldRegisterNamedType =\n namedTypeName !== undefined &&\n !(namedTypeName === \"Record\" && namedDecl?.getSourceFile().fileName !== file);\n const clearNamedTypeRegistration = (): void => {\n if (namedTypeName === undefined || !shouldRegisterNamedType) {\n return;\n }\n Reflect.deleteProperty(typeRegistry, namedTypeName);\n };\n\n if (visiting.has(type)) {\n // Recursive object expansion is deferred through the named-type registry.\n // Anonymous cycles still collapse to a closed empty object sentinel.\n if (namedTypeName !== undefined && shouldRegisterNamedType) {\n return { kind: \"reference\", name: namedTypeName, typeArguments: [] };\n }\n return { kind: \"object\", properties: [], additionalProperties: false };\n }\n\n // Seed the registry with a placeholder before traversing children so any\n // recursive property reference can resolve to a stable `$ref`.\n if (namedTypeName !== undefined && shouldRegisterNamedType && !typeRegistry[namedTypeName]) {\n typeRegistry[namedTypeName] = {\n name: namedTypeName,\n type: RESOLVING_TYPE_PLACEHOLDER,\n provenance: provenanceForDeclaration(namedDecl, file),\n };\n }\n\n visiting.add(type);\n\n // Detect previously resolved named types before walking the object body.\n if (\n namedTypeName !== undefined &&\n shouldRegisterNamedType &&\n typeRegistry[namedTypeName]?.type !== undefined\n ) {\n if (typeRegistry[namedTypeName].type !== RESOLVING_TYPE_PLACEHOLDER) {\n visiting.delete(type);\n return { kind: \"reference\", name: namedTypeName, typeArguments: [] };\n }\n }\n\n // Detect pure dictionary types (Record<string, T> or { [k: string]: T })\n // after the recursion guard/placeholder setup so recursive records can point\n // back at the named type instead of collapsing to an empty object.\n const recordNode = tryResolveRecordType(\n type,\n checker,\n file,\n typeRegistry,\n visiting,\n extensionRegistry,\n diagnostics\n );\n if (recordNode) {\n visiting.delete(type);\n if (namedTypeName !== undefined && shouldRegisterNamedType) {\n const isRecursiveRecord = typeNodeContainsReference(recordNode.valueType, namedTypeName);\n if (!isRecursiveRecord) {\n clearNamedTypeRegistration();\n return recordNode;\n }\n const annotations = namedDecl\n ? extractJSDocAnnotationNodes(namedDecl, file, makeParseOptions(extensionRegistry))\n : undefined;\n typeRegistry[namedTypeName] = {\n name: namedTypeName,\n type: recordNode,\n ...(annotations !== undefined && annotations.length > 0 && { annotations }),\n provenance: provenanceForDeclaration(namedDecl, file),\n };\n return { kind: \"reference\", name: namedTypeName, typeArguments: [] };\n }\n return recordNode;\n }\n\n const properties: ObjectProperty[] = [];\n\n // Get FieldInfo-level analysis from named type declarations for constraint propagation\n const fieldInfoMap = getNamedTypeFieldNodeInfoMap(\n type,\n checker,\n file,\n typeRegistry,\n visiting,\n diagnostics ?? [],\n extensionRegistry\n );\n\n for (const prop of type.getProperties()) {\n const declaration = prop.valueDeclaration ?? prop.declarations?.[0];\n if (!declaration) continue;\n\n const propType = checker.getTypeOfSymbolAtLocation(prop, declaration);\n const optional = !!(prop.flags & ts.SymbolFlags.Optional);\n const propTypeNode = resolveTypeNode(\n propType,\n checker,\n file,\n typeRegistry,\n visiting,\n declaration,\n extensionRegistry,\n diagnostics\n );\n\n // Get constraints and annotations from the declaration if available\n const fieldNodeInfo = fieldInfoMap?.get(prop.name);\n\n properties.push({\n name: prop.name,\n type: propTypeNode,\n optional,\n constraints: fieldNodeInfo?.constraints ?? [],\n annotations: fieldNodeInfo?.annotations ?? [],\n provenance: fieldNodeInfo?.provenance ?? provenanceForFile(file),\n });\n }\n\n visiting.delete(type);\n\n const objectNode: TypeNode = {\n kind: \"object\",\n properties,\n additionalProperties: true,\n };\n\n // Register named types\n if (namedTypeName !== undefined && shouldRegisterNamedType) {\n const annotations = namedDecl\n ? extractJSDocAnnotationNodes(namedDecl, file, makeParseOptions(extensionRegistry))\n : undefined;\n typeRegistry[namedTypeName] = {\n name: namedTypeName,\n type: objectNode,\n ...(annotations !== undefined && annotations.length > 0 && { annotations }),\n provenance: provenanceForDeclaration(namedDecl, file),\n };\n return { kind: \"reference\", name: namedTypeName, typeArguments: [] };\n }\n\n return objectNode;\n}\n\n// =============================================================================\n// NAMED TYPE FIELD INFO MAP — for nested constraint propagation\n// =============================================================================\n\ninterface FieldNodeInfo {\n readonly constraints: readonly ConstraintNode[];\n readonly annotations: readonly AnnotationNode[];\n readonly provenance: Provenance;\n}\n\n/**\n * Builds a map from property name to constraint/annotation info for named types.\n * This enables propagating TSDoc constraints from nested type declarations.\n */\nfunction getNamedTypeFieldNodeInfoMap(\n type: ts.Type,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n diagnostics: ConstraintSemanticDiagnostic[],\n extensionRegistry?: ExtensionRegistry\n): Map<string, FieldNodeInfo> | null {\n const symbols = [type.getSymbol(), type.aliasSymbol].filter(\n (s): s is ts.Symbol => s?.declarations != null && s.declarations.length > 0\n );\n\n for (const symbol of symbols) {\n const declarations = symbol.declarations;\n if (!declarations) continue;\n\n // Try class declaration\n const classDecl = declarations.find(ts.isClassDeclaration);\n if (classDecl) {\n const map = new Map<string, FieldNodeInfo>();\n const hostType = checker.getTypeAtLocation(classDecl);\n for (const member of classDecl.members) {\n if (ts.isPropertyDeclaration(member) && ts.isIdentifier(member.name)) {\n const fieldNode = analyzeFieldToIR(\n member,\n checker,\n file,\n typeRegistry,\n visiting,\n diagnostics,\n hostType,\n extensionRegistry\n );\n if (fieldNode) {\n map.set(fieldNode.name, {\n constraints: [...fieldNode.constraints],\n annotations: [...fieldNode.annotations],\n provenance: fieldNode.provenance,\n });\n }\n }\n }\n return map;\n }\n\n // Try interface declaration\n const interfaceDecl = declarations.find(ts.isInterfaceDeclaration);\n if (interfaceDecl) {\n return buildFieldNodeInfoMap(\n interfaceDecl.members,\n checker,\n file,\n typeRegistry,\n visiting,\n checker.getTypeAtLocation(interfaceDecl),\n diagnostics,\n extensionRegistry\n );\n }\n\n // Try type alias with type literal body\n const typeAliasDecl = declarations.find(ts.isTypeAliasDeclaration);\n if (typeAliasDecl && ts.isTypeLiteralNode(typeAliasDecl.type)) {\n return buildFieldNodeInfoMap(\n typeAliasDecl.type.members,\n checker,\n file,\n typeRegistry,\n visiting,\n checker.getTypeAtLocation(typeAliasDecl),\n diagnostics,\n extensionRegistry\n );\n }\n }\n\n return null;\n}\n\nfunction extractArrayElementTypeNode(\n sourceNode: ts.Node | undefined,\n checker: ts.TypeChecker\n): ts.TypeNode | undefined {\n const typeNode = sourceNode === undefined ? undefined : extractTypeNodeFromSource(sourceNode);\n if (typeNode === undefined) {\n return undefined;\n }\n const resolvedTypeNode = resolveAliasedTypeNode(typeNode, checker);\n if (ts.isArrayTypeNode(resolvedTypeNode)) {\n return resolvedTypeNode.elementType;\n }\n if (\n ts.isTypeReferenceNode(resolvedTypeNode) &&\n ts.isIdentifier(resolvedTypeNode.typeName) &&\n resolvedTypeNode.typeName.text === \"Array\" &&\n resolvedTypeNode.typeArguments?.[0]\n ) {\n return resolvedTypeNode.typeArguments[0];\n }\n return undefined;\n}\n\nfunction extractUnionMemberTypeNodes(\n sourceNode: ts.Node | undefined,\n checker: ts.TypeChecker\n): readonly ts.TypeNode[] {\n const typeNode = sourceNode === undefined ? undefined : extractTypeNodeFromSource(sourceNode);\n if (!typeNode) {\n return [];\n }\n const resolvedTypeNode = resolveAliasedTypeNode(typeNode, checker);\n return ts.isUnionTypeNode(resolvedTypeNode) ? [...resolvedTypeNode.types] : [];\n}\n\nfunction resolveAliasedTypeNode(\n typeNode: ts.TypeNode,\n checker: ts.TypeChecker,\n visited: Set<ts.TypeAliasDeclaration> = new Set<ts.TypeAliasDeclaration>()\n): ts.TypeNode {\n if (ts.isParenthesizedTypeNode(typeNode)) {\n return resolveAliasedTypeNode(typeNode.type, checker, visited);\n }\n\n if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) {\n return typeNode;\n }\n\n const symbol = checker.getSymbolAtLocation(typeNode.typeName);\n const aliasDecl = symbol?.declarations?.find(ts.isTypeAliasDeclaration);\n if (aliasDecl === undefined || visited.has(aliasDecl)) {\n return typeNode;\n }\n\n visited.add(aliasDecl);\n return resolveAliasedTypeNode(aliasDecl.type, checker, visited);\n}\n\nfunction isNullishTypeNode(typeNode: ts.TypeNode): boolean {\n if (\n typeNode.kind === ts.SyntaxKind.NullKeyword ||\n typeNode.kind === ts.SyntaxKind.UndefinedKeyword\n ) {\n return true;\n }\n\n return (\n ts.isLiteralTypeNode(typeNode) &&\n (typeNode.literal.kind === ts.SyntaxKind.NullKeyword ||\n typeNode.literal.kind === ts.SyntaxKind.UndefinedKeyword)\n );\n}\n\nfunction buildFieldNodeInfoMap(\n members: ts.NodeArray<ts.TypeElement>,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n hostType: ts.Type,\n diagnostics: ConstraintSemanticDiagnostic[],\n extensionRegistry?: ExtensionRegistry\n): Map<string, FieldNodeInfo> {\n const map = new Map<string, FieldNodeInfo>();\n for (const member of members) {\n if (ts.isPropertySignature(member)) {\n const fieldNode = analyzeInterfacePropertyToIR(\n member,\n checker,\n file,\n typeRegistry,\n visiting,\n diagnostics,\n hostType,\n extensionRegistry\n );\n if (fieldNode) {\n map.set(fieldNode.name, {\n constraints: [...fieldNode.constraints],\n annotations: [...fieldNode.annotations],\n provenance: fieldNode.provenance,\n });\n }\n }\n }\n return map;\n}\n\n// =============================================================================\n// TYPE ALIAS CONSTRAINT PROPAGATION\n// =============================================================================\n\n/** Maximum depth for transitive type alias constraint propagation. */\nconst MAX_ALIAS_CHAIN_DEPTH = 8;\n\n/**\n * Given a type node referencing a type alias, extracts IR ConstraintNodes\n * from the alias declaration's JSDoc tags.\n *\n * Follows alias chains transitively: if `type Percentage = Integer` and\n * `type Integer = number`, constraints from both `Percentage` and `Integer`\n * are collected. Constraints from closer aliases appear first in the result\n * (higher precedence). Recursion is capped at {@link MAX_ALIAS_CHAIN_DEPTH}\n * levels; exceeding the limit throws to surface pathological alias chains.\n */\nfunction extractTypeAliasConstraintNodes(\n typeNode: ts.TypeNode,\n checker: ts.TypeChecker,\n file: string,\n extensionRegistry?: ExtensionRegistry,\n depth = 0\n): ConstraintNode[] {\n if (!ts.isTypeReferenceNode(typeNode)) return [];\n\n if (depth >= MAX_ALIAS_CHAIN_DEPTH) {\n const aliasName = typeNode.typeName.getText();\n throw new Error(\n `Type alias chain exceeds maximum depth of ${String(MAX_ALIAS_CHAIN_DEPTH)} ` +\n `at alias \"${aliasName}\" in ${file}. ` +\n `Simplify the alias chain or check for circular references.`\n );\n }\n\n const symbol = checker.getSymbolAtLocation(typeNode.typeName);\n if (!symbol?.declarations) return [];\n\n const aliasDecl = symbol.declarations.find(ts.isTypeAliasDeclaration);\n if (!aliasDecl) return [];\n\n // Don't extract from object type aliases\n if (ts.isTypeLiteralNode(aliasDecl.type)) return [];\n\n const aliasFieldType = resolveTypeNode(\n checker.getTypeAtLocation(aliasDecl.type),\n checker,\n file,\n {},\n new Set<ts.Type>(),\n aliasDecl.type,\n extensionRegistry\n );\n const constraints = extractJSDocConstraintNodes(\n aliasDecl,\n file,\n makeParseOptions(extensionRegistry, aliasFieldType)\n );\n\n // Transitively follow alias chains (e.g., Percentage → Integer → number)\n // Constraints from parent aliases are appended after the immediate alias's\n // constraints, giving the immediate alias higher precedence.\n constraints.push(\n ...extractTypeAliasConstraintNodes(aliasDecl.type, checker, file, extensionRegistry, depth + 1)\n );\n\n return constraints;\n}\n\n// =============================================================================\n// PROVENANCE HELPERS\n// =============================================================================\n\nfunction provenanceForNode(node: ts.Node, file: string): Provenance {\n const sourceFile = node.getSourceFile();\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n return {\n surface: \"tsdoc\",\n file,\n line: line + 1,\n column: character,\n };\n}\n\nfunction provenanceForFile(file: string): Provenance {\n return { surface: \"tsdoc\", file, line: 0, column: 0 };\n}\n\nfunction provenanceForDeclaration(node: ts.Node | undefined, file: string): Provenance {\n if (!node) {\n return provenanceForFile(file);\n }\n return provenanceForNode(node, file);\n}\n\n// =============================================================================\n// NAMED TYPE HELPERS\n// =============================================================================\n\n/**\n * Extracts a stable type name from a ts.Type when it originates from\n * a named declaration (class, interface, or type alias).\n */\nfunction getNamedTypeName(type: ts.Type): string | null {\n const symbol = type.getSymbol();\n if (symbol?.declarations) {\n const decl = symbol.declarations[0];\n if (\n decl &&\n (ts.isClassDeclaration(decl) ||\n ts.isInterfaceDeclaration(decl) ||\n ts.isTypeAliasDeclaration(decl))\n ) {\n const name = ts.isClassDeclaration(decl) ? decl.name?.text : decl.name.text;\n if (name) return name;\n }\n }\n\n const aliasSymbol = type.aliasSymbol;\n if (aliasSymbol?.declarations) {\n const aliasDecl = aliasSymbol.declarations.find(ts.isTypeAliasDeclaration);\n if (aliasDecl) {\n return aliasDecl.name.text;\n }\n }\n\n return null;\n}\n\n/**\n * Returns the declaration that defines a named type, if available.\n */\nfunction getNamedTypeDeclaration(type: ts.Type): ts.Declaration | undefined {\n const symbol = type.getSymbol();\n if (symbol?.declarations) {\n const decl = symbol.declarations[0];\n if (\n decl &&\n (ts.isClassDeclaration(decl) ||\n ts.isInterfaceDeclaration(decl) ||\n ts.isTypeAliasDeclaration(decl))\n ) {\n return decl;\n }\n }\n\n const aliasSymbol = type.aliasSymbol;\n if (aliasSymbol?.declarations) {\n return aliasSymbol.declarations.find(ts.isTypeAliasDeclaration);\n }\n\n return undefined;\n}\n\n// =============================================================================\n// SHARED OUTPUT TYPES\n// =============================================================================\n\n/**\n * Analyzed method information.\n */\nexport interface MethodInfo {\n /** Method name */\n name: string;\n /** Method parameters */\n parameters: ParameterInfo[];\n /** Return type node */\n returnTypeNode: ts.TypeNode | undefined;\n /** Resolved return type */\n returnType: ts.Type;\n}\n\n/**\n * Analyzed parameter information.\n */\nexport interface ParameterInfo {\n /** Parameter name */\n name: string;\n /** TypeScript type node */\n typeNode: ts.TypeNode | undefined;\n /** Resolved type */\n type: ts.Type;\n /** If this is InferSchema<typeof X>, the export name X */\n formSpecExportName: string | null;\n /** Whether the parameter is optional (has ? or default value) */\n optional: boolean;\n}\n\n// =============================================================================\n// SHARED HELPERS\n// =============================================================================\n\n/**\n * Analyzes a method declaration to extract method info.\n * Shared between IR and legacy paths.\n */\nfunction analyzeMethod(method: ts.MethodDeclaration, checker: ts.TypeChecker): MethodInfo | null {\n if (!ts.isIdentifier(method.name)) {\n return null;\n }\n\n const name = method.name.text;\n const parameters: ParameterInfo[] = [];\n\n for (const param of method.parameters) {\n if (ts.isIdentifier(param.name)) {\n const paramInfo = analyzeParameter(param, checker);\n parameters.push(paramInfo);\n }\n }\n\n const returnTypeNode = method.type;\n const signature = checker.getSignatureFromDeclaration(method);\n const returnType = signature\n ? checker.getReturnTypeOfSignature(signature)\n : checker.getTypeAtLocation(method);\n\n return { name, parameters, returnTypeNode, returnType };\n}\n\nfunction analyzeParameter(param: ts.ParameterDeclaration, checker: ts.TypeChecker): ParameterInfo {\n const name = ts.isIdentifier(param.name) ? param.name.text : \"param\";\n const typeNode = param.type;\n const type = checker.getTypeAtLocation(param);\n const formSpecExportName = detectFormSpecReference(typeNode);\n const optional = param.questionToken !== undefined || param.initializer !== undefined;\n\n return { name, typeNode, type, formSpecExportName, optional };\n}\n\nfunction detectFormSpecReference(typeNode: ts.TypeNode | undefined): string | null {\n if (!typeNode) return null;\n\n if (!ts.isTypeReferenceNode(typeNode)) return null;\n\n const typeName = ts.isIdentifier(typeNode.typeName)\n ? typeNode.typeName.text\n : ts.isQualifiedName(typeNode.typeName)\n ? typeNode.typeName.right.text\n : null;\n\n if (typeName !== \"InferSchema\" && typeName !== \"InferFormSchema\") return null;\n\n const typeArg = typeNode.typeArguments?.[0];\n if (!typeArg || !ts.isTypeQueryNode(typeArg)) return null;\n\n if (ts.isIdentifier(typeArg.exprName)) {\n return typeArg.exprName.text;\n }\n\n if (ts.isQualifiedName(typeArg.exprName)) {\n return typeArg.exprName.right.text;\n }\n\n return null;\n}\n","/**\n * JSDoc constraint and annotation extractor.\n *\n * Extracts constraints and annotation tags from JSDoc comments on\n * class/interface fields and returns canonical IR nodes directly:\n * - {@link ConstraintNode} for set-influencing tags (@minimum, @pattern, etc.)\n * - {@link AnnotationNode} for value-influencing tags (@displayName, etc.)\n *\n * The IR extraction path uses the official `@microsoft/tsdoc` parser for\n * all canonical tags.\n *\n * Supported constraints correspond to the built-in FormSpec constraint tags\n * (e.g., `@minimum`, `@maximum`, `@pattern`).\n */\n\nimport * as ts from \"typescript\";\nimport type { ConstraintNode, AnnotationNode, JsonValue } from \"@formspec/core/internals\";\nimport {\n parseTSDocTags,\n hasDeprecatedTagTSDoc,\n type ParseTSDocOptions,\n type TSDocParseResult,\n} from \"./tsdoc-parser.js\";\n\n// =============================================================================\n// IR API — uses @microsoft/tsdoc for structured parsing\n// =============================================================================\n\nexport function extractJSDocParseResult(\n node: ts.Node,\n file = \"\",\n options?: ParseTSDocOptions\n): TSDocParseResult {\n return parseTSDocTags(node, file, options);\n}\n\n/**\n * Extracts constraints from JSDoc comments on a TypeScript AST node and returns\n * canonical {@link ConstraintNode} objects.\n *\n * Uses the official `@microsoft/tsdoc` parser for structured tag extraction.\n * Constraints are registered as custom block tags in the TSDoc configuration.\n *\n * @param node - The AST node to inspect for JSDoc tags\n * @param file - Absolute path to the source file for provenance\n * @returns Canonical constraint nodes for each valid constraint tag\n */\nexport function extractJSDocConstraintNodes(\n node: ts.Node,\n file = \"\",\n options?: ParseTSDocOptions\n): ConstraintNode[] {\n const result = extractJSDocParseResult(node, file, options);\n return [...result.constraints];\n}\n\n/**\n * Extracts canonical annotation tags from a node and returns\n * {@link AnnotationNode} objects.\n *\n * @param node - The AST node to inspect for annotation tags\n * @param file - Absolute path to the source file for provenance\n * @returns Canonical annotation nodes\n */\nexport function extractJSDocAnnotationNodes(\n node: ts.Node,\n file = \"\",\n options?: ParseTSDocOptions\n): AnnotationNode[] {\n const result = extractJSDocParseResult(node, file, options);\n return [...result.annotations];\n}\n\n/**\n * Checks if a node has a TSDoc `@deprecated` tag.\n *\n * Uses the TSDoc parser for structured detection.\n */\nexport function hasDeprecatedTag(node: ts.Node): boolean {\n return hasDeprecatedTagTSDoc(node);\n}\n\n/**\n * Extracts a default value from a property initializer and returns a\n * {@link DefaultValueAnnotationNode} if present.\n *\n * Only extracts literal values (strings, numbers, booleans, null).\n */\nexport function extractDefaultValueAnnotation(\n initializer: ts.Expression | undefined,\n file = \"\"\n): AnnotationNode | null {\n if (!initializer) return null;\n\n let value: JsonValue | undefined;\n\n if (ts.isStringLiteral(initializer)) {\n value = initializer.text;\n } else if (ts.isNumericLiteral(initializer)) {\n value = Number(initializer.text);\n } else if (initializer.kind === ts.SyntaxKind.TrueKeyword) {\n value = true;\n } else if (initializer.kind === ts.SyntaxKind.FalseKeyword) {\n value = false;\n } else if (initializer.kind === ts.SyntaxKind.NullKeyword) {\n value = null;\n } else if (ts.isPrefixUnaryExpression(initializer)) {\n if (\n initializer.operator === ts.SyntaxKind.MinusToken &&\n ts.isNumericLiteral(initializer.operand)\n ) {\n value = -Number(initializer.operand.text);\n }\n }\n\n if (value === undefined) return null;\n\n const sourceFile = initializer.getSourceFile();\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(initializer.getStart());\n\n return {\n kind: \"annotation\",\n annotationKind: \"defaultValue\",\n value,\n provenance: {\n surface: \"tsdoc\",\n file,\n line: line + 1,\n column: character,\n },\n };\n}\n","/**\n * TSDoc-based structured tag parser.\n *\n * Bridges the TypeScript compiler AST with the official `@microsoft/tsdoc`\n * parser to extract constraint and annotation tags from JSDoc comments\n * on class/interface/type-alias properties.\n *\n * The parser recognises two categories of tags:\n *\n * 1. **Constraint tags** (all alphanumeric, TSDoc-compliant):\n * `@minimum`, `@maximum`, `@exclusiveMinimum`, `@exclusiveMaximum`,\n * `@multipleOf`, `@minLength`, `@maxLength`, `@minItems`, `@maxItems`,\n * `@uniqueItems`, `@pattern`, `@enumOptions`, `@const`\n * — Parsed via TSDocParser as custom block tags.\n * Both camelCase and PascalCase forms are accepted (e.g., `@Minimum`).\n *\n * 2. **Annotation tags** (`@displayName`, `@format`, `@placeholder`):\n * These are parsed as structured custom block tags and mapped directly\n * onto annotation IR nodes.\n *\n * The `@deprecated` tag is a standard TSDoc block tag, parsed structurally.\n *\n * Description and remarks extraction (spec 002 §2.3):\n * - Summary text (bare text before the first block tag) → `description` annotation\n * - `@remarks` block → `remarks` annotation (separate channel)\n * - `@description` is NOT supported (not a standard TSDoc tag)\n *\n * **Fallback strategy**: TSDoc treats `{` / `}` as inline tag delimiters and\n * `@` as a tag prefix, so content containing these characters (e.g. JSON\n * objects in `@EnumOptions`, regex patterns with `@` in `@Pattern`) gets\n * mangled by the TSDoc parser. The shared comment syntax parser is the\n * primary source for these payloads; the TS compiler's `ts.getJSDocTags()`\n * API remains as a fallback when a raw payload cannot be recovered from the\n * shared parse.\n */\n\nimport * as ts from \"typescript\";\nimport {\n checkSyntheticTagApplication,\n extractPathTarget as extractSharedPathTarget,\n getTagDefinition,\n hasTypeSemanticCapability,\n parseConstraintTagValue,\n parseDefaultValueTagValue,\n type ParsedCommentTag,\n resolveDeclarationPlacement,\n resolvePathTargetType,\n sliceCommentSpan,\n parseCommentBlock,\n parseTagSyntax,\n type ConstraintSemanticDiagnostic,\n type FormSpecValueKind,\n type SemanticCapability,\n} from \"@formspec/analysis/internal\";\nimport {\n TSDocParser,\n TSDocConfiguration,\n TSDocTagDefinition,\n TSDocTagSyntaxKind,\n DocExcerpt,\n DocPlainText,\n DocSoftBreak,\n TextRange,\n type DocNode,\n type DocBlock,\n} from \"@microsoft/tsdoc\";\nimport {\n BUILTIN_CONSTRAINT_DEFINITIONS,\n normalizeConstraintTagName,\n isBuiltinConstraintName,\n} from \"@formspec/core/internals\";\nimport {\n type ConstraintNode,\n type AnnotationNode,\n type Provenance,\n type PathTarget,\n type TypeNode,\n} from \"@formspec/core/internals\";\nimport type { ExtensionRegistry } from \"../extensions/index.js\";\n\n// =============================================================================\n// CONFIGURATION\n// =============================================================================\n\n/**\n * Tags whose content may contain TSDoc-significant characters (`{}`, `@`)\n * and must be extracted via the TS compiler JSDoc API rather than the\n * TSDoc DocNode tree to avoid content mangling.\n *\n * - `@pattern`: regex patterns commonly contain `@` (e.g. email validation)\n * - `@enumOptions`: JSON arrays may contain object literals with `{}`\n * - `@defaultValue`: JSON defaults may contain objects, arrays, or quoted strings\n */\nconst TAGS_REQUIRING_RAW_TEXT = new Set([\"pattern\", \"enumOptions\", \"defaultValue\"]);\n\n/**\n * Creates a TSDocConfiguration with FormSpec custom block tag definitions\n * registered for all constraint tags.\n */\nfunction createFormSpecTSDocConfig(extensionTagNames: readonly string[] = []): TSDocConfiguration {\n const config = new TSDocConfiguration();\n\n // Register each constraint tag as a custom block tag (allowMultiple so\n // repeated tags don't produce warnings).\n for (const tagName of Object.keys(BUILTIN_CONSTRAINT_DEFINITIONS)) {\n config.addTagDefinition(\n new TSDocTagDefinition({\n tagName: \"@\" + tagName,\n syntaxKind: TSDocTagSyntaxKind.BlockTag,\n allowMultiple: true,\n })\n );\n }\n\n // Register annotation tags that participate in the canonical IR.\n for (const tagName of [\"displayName\", \"format\", \"placeholder\"]) {\n config.addTagDefinition(\n new TSDocTagDefinition({\n tagName: \"@\" + tagName,\n syntaxKind: TSDocTagSyntaxKind.BlockTag,\n allowMultiple: true,\n })\n );\n }\n\n for (const tagName of extensionTagNames) {\n config.addTagDefinition(\n new TSDocTagDefinition({\n tagName: \"@\" + tagName,\n syntaxKind: TSDocTagSyntaxKind.BlockTag,\n allowMultiple: true,\n })\n );\n }\n\n return config;\n}\n\nfunction sharedCommentSyntaxOptions(\n options?: ParseTSDocOptions,\n offset?: number\n): NonNullable<Parameters<typeof parseCommentBlock>[1]> {\n const extensions = options?.extensionRegistry?.extensions;\n return {\n ...(offset !== undefined ? { offset } : {}),\n ...(extensions !== undefined ? { extensions } : {}),\n };\n}\n\nfunction sharedTagValueOptions(options?: ParseTSDocOptions) {\n return {\n ...(options?.extensionRegistry !== undefined ? { registry: options.extensionRegistry } : {}),\n ...(options?.fieldType !== undefined ? { fieldType: options.fieldType } : {}),\n };\n}\n\nconst SYNTHETIC_TYPE_FORMAT_FLAGS =\n ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope;\n\nfunction collectImportedNames(sourceFile: ts.SourceFile): ReadonlySet<string> {\n const importedNames = new Set<string>();\n\n for (const statement of sourceFile.statements) {\n if (ts.isImportDeclaration(statement) && statement.importClause !== undefined) {\n const clause = statement.importClause;\n if (clause.name !== undefined) {\n importedNames.add(clause.name.text);\n }\n if (clause.namedBindings !== undefined) {\n if (ts.isNamedImports(clause.namedBindings)) {\n for (const specifier of clause.namedBindings.elements) {\n importedNames.add(specifier.name.text);\n }\n } else if (ts.isNamespaceImport(clause.namedBindings)) {\n importedNames.add(clause.namedBindings.name.text);\n }\n }\n continue;\n }\n\n if (ts.isImportEqualsDeclaration(statement)) {\n importedNames.add(statement.name.text);\n }\n }\n\n return importedNames;\n}\n\nfunction isNonReferenceIdentifier(node: ts.Identifier): boolean {\n const parent = node.parent;\n\n if (\n (ts.isBindingElement(parent) ||\n ts.isClassDeclaration(parent) ||\n ts.isEnumDeclaration(parent) ||\n ts.isEnumMember(parent) ||\n ts.isFunctionDeclaration(parent) ||\n ts.isFunctionExpression(parent) ||\n ts.isImportClause(parent) ||\n ts.isImportEqualsDeclaration(parent) ||\n ts.isImportSpecifier(parent) ||\n ts.isInterfaceDeclaration(parent) ||\n ts.isMethodDeclaration(parent) ||\n ts.isMethodSignature(parent) ||\n ts.isModuleDeclaration(parent) ||\n ts.isNamespaceExport(parent) ||\n ts.isNamespaceImport(parent) ||\n ts.isParameter(parent) ||\n ts.isPropertyDeclaration(parent) ||\n ts.isPropertySignature(parent) ||\n ts.isSetAccessorDeclaration(parent) ||\n ts.isGetAccessorDeclaration(parent) ||\n ts.isTypeAliasDeclaration(parent) ||\n ts.isTypeParameterDeclaration(parent) ||\n ts.isVariableDeclaration(parent)) &&\n parent.name === node\n ) {\n return true;\n }\n\n if (\n (ts.isPropertyAssignment(parent) || ts.isPropertyAccessExpression(parent)) &&\n parent.name === node\n ) {\n return true;\n }\n\n if (ts.isQualifiedName(parent) && parent.right === node) {\n return true;\n }\n\n return false;\n}\n\nfunction statementReferencesImportedName(\n statement: ts.Statement,\n importedNames: ReadonlySet<string>\n): boolean {\n let referencesImportedName = false;\n\n const visit = (node: ts.Node): void => {\n if (referencesImportedName) {\n return;\n }\n\n if (ts.isIdentifier(node) && importedNames.has(node.text) && !isNonReferenceIdentifier(node)) {\n referencesImportedName = true;\n return;\n }\n\n ts.forEachChild(node, visit);\n };\n\n visit(statement);\n return referencesImportedName;\n}\n\nfunction buildSupportingDeclarations(sourceFile: ts.SourceFile): readonly string[] {\n const importedNames = collectImportedNames(sourceFile);\n\n return sourceFile.statements\n .filter((statement) => {\n // Always exclude imports and re-exports\n if (ts.isImportDeclaration(statement)) return false;\n if (ts.isImportEqualsDeclaration(statement)) return false;\n if (ts.isExportDeclaration(statement) && statement.moduleSpecifier !== undefined)\n return false;\n\n // Skip declarations whose AST references an imported identifier.\n // This prevents the synthetic program from emitting errors about\n // unresolvable imported types without falsely matching comments,\n // string literals, or unrelated property names.\n if (importedNames.size > 0 && statementReferencesImportedName(statement, importedNames)) {\n return false;\n }\n\n return true;\n })\n .map((statement) => statement.getText(sourceFile));\n}\n\nfunction renderSyntheticArgumentExpression(\n valueKind: FormSpecValueKind | null,\n argumentText: string\n): string | null {\n const trimmed = argumentText.trim();\n if (trimmed === \"\") {\n return null;\n }\n\n switch (valueKind) {\n case \"number\":\n case \"integer\":\n case \"signedInteger\":\n return Number.isFinite(Number(trimmed)) ? trimmed : JSON.stringify(trimmed);\n case \"string\":\n return JSON.stringify(argumentText);\n case \"json\":\n try {\n JSON.parse(trimmed);\n return `(${trimmed})`;\n } catch {\n return JSON.stringify(trimmed);\n }\n case \"boolean\":\n return trimmed === \"true\" || trimmed === \"false\" ? trimmed : JSON.stringify(trimmed);\n case \"condition\":\n return \"undefined as unknown as FormSpecCondition\";\n case null:\n return null;\n default: {\n return String(valueKind);\n }\n }\n}\n\nfunction getArrayElementType(type: ts.Type, checker: ts.TypeChecker): ts.Type | null {\n if (!checker.isArrayType(type)) {\n return null;\n }\n\n return checker.getTypeArguments(type as ts.TypeReference)[0] ?? null;\n}\n\nfunction supportsConstraintCapability(\n type: ts.Type,\n checker: ts.TypeChecker,\n capability: SemanticCapability | undefined\n): boolean {\n if (capability === undefined) {\n return true;\n }\n\n if (hasTypeSemanticCapability(type, checker, capability)) {\n return true;\n }\n\n if (capability === \"string-like\") {\n const itemType = getArrayElementType(type, checker);\n return itemType !== null && hasTypeSemanticCapability(itemType, checker, capability);\n }\n\n return false;\n}\n\nfunction makeDiagnostic(\n code: string,\n message: string,\n provenance: Provenance\n): ConstraintSemanticDiagnostic {\n return {\n code,\n message,\n severity: \"error\",\n primaryLocation: provenance,\n relatedLocations: [],\n };\n}\n\nfunction placementLabel(\n placement: NonNullable<ReturnType<typeof resolveDeclarationPlacement>>\n): string {\n switch (placement) {\n case \"class\":\n return \"class declarations\";\n case \"class-field\":\n return \"class fields\";\n case \"class-method\":\n return \"class methods\";\n case \"interface\":\n return \"interface declarations\";\n case \"interface-field\":\n return \"interface fields\";\n case \"type-alias\":\n return \"type aliases\";\n case \"type-alias-field\":\n return \"type-alias properties\";\n case \"variable\":\n return \"variables\";\n case \"function\":\n return \"functions\";\n case \"function-parameter\":\n return \"function parameters\";\n case \"method-parameter\":\n return \"method parameters\";\n default: {\n const exhaustive: never = placement;\n return String(exhaustive);\n }\n }\n}\n\nfunction capabilityLabel(capability: string | undefined): string {\n switch (capability) {\n case \"numeric-comparable\":\n return \"number\";\n case \"string-like\":\n return \"string\";\n case \"array-like\":\n return \"array\";\n case \"enum-member-addressable\":\n return \"enum\";\n case \"json-like\":\n return \"JSON-compatible\";\n case \"object-like\":\n return \"object\";\n case \"condition-like\":\n return \"conditional\";\n case undefined:\n return \"compatible\";\n default:\n return capability;\n }\n}\n\nfunction getBroadenedCustomTypeId(fieldType: TypeNode | undefined): string | undefined {\n if (fieldType?.kind === \"custom\") {\n return fieldType.typeId;\n }\n\n if (fieldType?.kind !== \"union\") {\n return undefined;\n }\n\n const customMembers = fieldType.members.filter(\n (member): member is Extract<TypeNode, { kind: \"custom\" }> => member.kind === \"custom\"\n );\n if (customMembers.length !== 1) {\n return undefined;\n }\n\n const nonCustomMembers = fieldType.members.filter((member) => member.kind !== \"custom\");\n const allOtherMembersAreNull = nonCustomMembers.every(\n (member) => member.kind === \"primitive\" && member.primitiveKind === \"null\"\n );\n const customMember = customMembers[0];\n return allOtherMembersAreNull && customMember !== undefined ? customMember.typeId : undefined;\n}\n\nfunction hasBuiltinConstraintBroadening(tagName: string, options?: ParseTSDocOptions): boolean {\n const broadenedTypeId = getBroadenedCustomTypeId(options?.fieldType);\n return (\n broadenedTypeId !== undefined &&\n options?.extensionRegistry?.findBuiltinConstraintBroadening(broadenedTypeId, tagName) !==\n undefined\n );\n}\n\nfunction buildCompilerBackedConstraintDiagnostics(\n node: ts.Node,\n sourceFile: ts.SourceFile,\n tagName: string,\n parsedTag: ParsedCommentTag | null,\n provenance: Provenance,\n supportingDeclarations: readonly string[],\n options?: ParseTSDocOptions\n): readonly ConstraintSemanticDiagnostic[] {\n if (!isBuiltinConstraintName(tagName)) {\n return [];\n }\n\n const checker = options?.checker;\n const subjectType = options?.subjectType;\n if (checker === undefined || subjectType === undefined) {\n return [];\n }\n\n const placement = resolveDeclarationPlacement(node);\n if (placement === null) {\n return [];\n }\n\n const definition = getTagDefinition(tagName, options?.extensionRegistry?.extensions);\n if (definition === null) {\n return [];\n }\n\n if (!definition.placements.includes(placement)) {\n return [\n makeDiagnostic(\n \"INVALID_TAG_PLACEMENT\",\n `Tag \"@${tagName}\" is not allowed on ${placementLabel(placement)}.`,\n provenance\n ),\n ];\n }\n\n const target = parsedTag?.target ?? null;\n const hasBroadening = target === null && hasBuiltinConstraintBroadening(tagName, options);\n if (target !== null) {\n if (target.kind !== \"path\") {\n return [\n makeDiagnostic(\n \"UNSUPPORTED_TARGETING_SYNTAX\",\n `Tag \"@${tagName}\" does not support ${target.kind} targeting syntax.`,\n provenance\n ),\n ];\n }\n\n if (!target.valid || target.path === null) {\n return [\n makeDiagnostic(\n \"UNSUPPORTED_TARGETING_SYNTAX\",\n `Tag \"@${tagName}\" has invalid path targeting syntax.`,\n provenance\n ),\n ];\n }\n\n const resolution = resolvePathTargetType(subjectType, checker, target.path.segments);\n if (resolution.kind === \"missing-property\") {\n return [\n makeDiagnostic(\n \"UNKNOWN_PATH_TARGET\",\n `Target \"${target.rawText}\": path-targeted constraint \"${tagName}\" references unknown path segment \"${resolution.segment}\"`,\n provenance\n ),\n ];\n }\n\n if (resolution.kind === \"unresolvable\") {\n const actualType = checker.typeToString(resolution.type, node, SYNTHETIC_TYPE_FORMAT_FLAGS);\n return [\n makeDiagnostic(\n \"TYPE_MISMATCH\",\n `Target \"${target.rawText}\": path-targeted constraint \"${tagName}\" is invalid because type \"${actualType}\" cannot be traversed`,\n provenance\n ),\n ];\n }\n\n const requiredCapability = definition.capabilities[0];\n if (\n requiredCapability !== undefined &&\n !supportsConstraintCapability(resolution.type, checker, requiredCapability)\n ) {\n const actualType = checker.typeToString(resolution.type, node, SYNTHETIC_TYPE_FORMAT_FLAGS);\n return [\n makeDiagnostic(\n \"TYPE_MISMATCH\",\n `Target \"${target.rawText}\": constraint \"${tagName}\" is only valid on ${capabilityLabel(requiredCapability)} targets, but field type is \"${actualType}\"`,\n provenance\n ),\n ];\n }\n } else if (!hasBroadening) {\n const requiredCapability = definition.capabilities[0];\n if (\n requiredCapability !== undefined &&\n !supportsConstraintCapability(subjectType, checker, requiredCapability)\n ) {\n const actualType = checker.typeToString(subjectType, node, SYNTHETIC_TYPE_FORMAT_FLAGS);\n return [\n makeDiagnostic(\n \"TYPE_MISMATCH\",\n `Target \"${node.getText(sourceFile)}\": constraint \"${tagName}\" is only valid on ${capabilityLabel(requiredCapability)} targets, but field type is \"${actualType}\"`,\n provenance\n ),\n ];\n }\n }\n\n const argumentExpression = renderSyntheticArgumentExpression(\n definition.valueKind,\n parsedTag?.argumentText ?? \"\"\n );\n if (definition.requiresArgument && argumentExpression === null) {\n return [];\n }\n\n if (hasBroadening) {\n return [];\n }\n\n const subjectTypeText = checker.typeToString(subjectType, node, SYNTHETIC_TYPE_FORMAT_FLAGS);\n const hostType = options?.hostType ?? subjectType;\n const hostTypeText = checker.typeToString(hostType, node, SYNTHETIC_TYPE_FORMAT_FLAGS);\n const result = checkSyntheticTagApplication({\n tagName,\n placement,\n hostType: hostTypeText,\n subjectType: subjectTypeText,\n ...(target?.kind === \"path\" ? { target: { kind: \"path\" as const, text: target.rawText } } : {}),\n ...(argumentExpression !== null ? { argumentExpression } : {}),\n supportingDeclarations,\n ...(options?.extensionRegistry !== undefined\n ? {\n extensions: options.extensionRegistry.extensions.map((extension) => ({\n extensionId: extension.extensionId,\n ...(extension.constraintTags !== undefined\n ? {\n constraintTags: extension.constraintTags.map((tag) => ({ tagName: tag.tagName })),\n }\n : {}),\n })),\n }\n : {}),\n });\n\n if (result.diagnostics.length === 0) {\n return [];\n }\n\n const expectedLabel =\n definition.valueKind === null ? \"compatible argument\" : capabilityLabel(definition.valueKind);\n return [\n makeDiagnostic(\n \"TYPE_MISMATCH\",\n `Tag \"@${tagName}\" received an invalid argument for ${expectedLabel}.`,\n provenance\n ),\n ];\n}\n\n/**\n * Shared parser instance — thread-safe because TSDocParser is stateless;\n * all parse state lives in the returned ParserContext.\n */\nconst parserCache = new Map<string, TSDocParser>();\nconst parseResultCache = new Map<string, TSDocParseResult>();\n\nfunction getParser(options?: ParseTSDocOptions): TSDocParser {\n const extensionTagNames = [\n ...(options?.extensionRegistry?.extensions.flatMap((extension) =>\n (extension.constraintTags ?? []).map((tag) => tag.tagName)\n ) ?? []),\n ].sort();\n const cacheKey = extensionTagNames.join(\"|\");\n const existing = parserCache.get(cacheKey);\n if (existing) {\n return existing;\n }\n\n const parser = new TSDocParser(createFormSpecTSDocConfig(extensionTagNames));\n parserCache.set(cacheKey, parser);\n return parser;\n}\n\n// =============================================================================\n// PUBLIC API\n// =============================================================================\n\n/**\n * Result of parsing a single JSDoc comment attached to a TS AST node.\n */\nexport interface TSDocParseResult {\n /** Constraint IR nodes extracted from custom block tags. */\n readonly constraints: readonly ConstraintNode[];\n /** Annotation IR nodes extracted from canonical TSDoc block tags. */\n readonly annotations: readonly AnnotationNode[];\n /** Compiler-backed extraction diagnostics for invalid tag applications. */\n readonly diagnostics: readonly ConstraintSemanticDiagnostic[];\n}\n\n/**\n * Optional extension-aware parsing inputs for TSDoc extraction.\n */\nexport interface ParseTSDocOptions {\n /**\n * Extension registry used to resolve custom tags and custom-type-specific\n * broadening of built-in constraint tags.\n */\n readonly extensionRegistry?: ExtensionRegistry;\n /**\n * Effective field/type node for the declaration being parsed. Required when\n * built-in tags may broaden onto a custom type.\n */\n readonly fieldType?: TypeNode;\n /** Type checker used for compiler-backed placement and type validation. */\n readonly checker?: ts.TypeChecker;\n /** The declaration type that the parsed tag applies to. */\n readonly subjectType?: ts.Type;\n /** Optional enclosing host type for future cross-field signature checks. */\n readonly hostType?: ts.Type;\n}\n\n/**\n * Display-name metadata extracted from a node's JSDoc tags.\n *\n * The root display name is returned separately from member-target labels so\n * callers can apply the former to the enclosing type/form and the latter to\n * enum members.\n */\nexport interface DisplayNameMetadata {\n readonly displayName?: string;\n readonly memberDisplayNames: ReadonlyMap<string, string>;\n}\n\nfunction getExtensionRegistryCacheKey(registry: ExtensionRegistry | undefined): string {\n if (registry === undefined) {\n return \"\";\n }\n\n return registry.extensions\n .map((extension) =>\n JSON.stringify({\n extensionId: extension.extensionId,\n typeNames: extension.types?.map((type) => type.typeName) ?? [],\n constraintTags: extension.constraintTags?.map((tag) => tag.tagName) ?? [],\n })\n )\n .join(\"|\");\n}\n\nfunction getParseCacheKey(\n node: ts.Node,\n file: string,\n options: ParseTSDocOptions | undefined\n): string {\n const sourceFile = node.getSourceFile();\n const checker = options?.checker;\n return JSON.stringify({\n file,\n sourceFile: sourceFile.fileName,\n sourceText: sourceFile.text,\n start: node.getFullStart(),\n end: node.getEnd(),\n fieldType: options?.fieldType ?? null,\n subjectType:\n checker !== undefined && options?.subjectType !== undefined\n ? checker.typeToString(options.subjectType, node, SYNTHETIC_TYPE_FORMAT_FLAGS)\n : null,\n hostType:\n checker !== undefined && options?.hostType !== undefined\n ? checker.typeToString(options.hostType, node, SYNTHETIC_TYPE_FORMAT_FLAGS)\n : null,\n extensions: getExtensionRegistryCacheKey(options?.extensionRegistry),\n });\n}\n\n/**\n * Parses the JSDoc comment attached to a TypeScript AST node using the\n * official TSDoc parser and returns canonical IR constraint and annotation\n * nodes.\n *\n * For constraint tags (`@minimum`, `@pattern`, `@enumOptions`, etc.),\n * the structured TSDoc parser is used. Canonical annotation tags\n * (`@displayName`) are also parsed structurally. Summary text and `@remarks`\n * are extracted as separate annotation nodes.\n *\n * @param node - The TS AST node to inspect (PropertyDeclaration, PropertySignature, etc.)\n * @param file - Absolute source file path for provenance\n * @returns Parsed constraint and annotation nodes\n */\nexport function parseTSDocTags(\n node: ts.Node,\n file = \"\",\n options?: ParseTSDocOptions\n): TSDocParseResult {\n const cacheKey = getParseCacheKey(node, file, options);\n const cached = parseResultCache.get(cacheKey);\n if (cached !== undefined) {\n return cached;\n }\n\n const constraints: ConstraintNode[] = [];\n const annotations: AnnotationNode[] = [];\n const diagnostics: ConstraintSemanticDiagnostic[] = [];\n let displayName: string | undefined;\n let placeholder: string | undefined;\n let displayNameProvenance: Provenance | undefined;\n let placeholderProvenance: Provenance | undefined;\n const rawTextTags: {\n readonly tag: ParsedCommentTag;\n readonly commentText: string;\n readonly commentOffset: number;\n }[] = [];\n\n // ----- Phase 1: TSDoc structural parse for constraint tags -----\n const sourceFile = node.getSourceFile();\n const sourceText = sourceFile.getFullText();\n const supportingDeclarations = buildSupportingDeclarations(sourceFile);\n const commentRanges = ts.getLeadingCommentRanges(sourceText, node.getFullStart());\n const rawTextFallbacks = collectRawTextFallbacks(node, file);\n\n if (commentRanges) {\n for (const range of commentRanges) {\n // Only parse /** ... */ comments (kind 3 = MultiLineCommentTrivia)\n if (range.kind !== ts.SyntaxKind.MultiLineCommentTrivia) {\n continue;\n }\n const commentText = sourceText.substring(range.pos, range.end);\n if (!commentText.startsWith(\"/**\")) {\n continue;\n }\n\n const parser = getParser(options);\n const parserContext = parser.parseRange(\n TextRange.fromStringRange(sourceText, range.pos, range.end)\n );\n const docComment = parserContext.docComment;\n const parsedComment = parseCommentBlock(\n commentText,\n sharedCommentSyntaxOptions(options, range.pos)\n );\n let parsedTagCursor = 0;\n\n const nextParsedTag = (normalizedTagName: string) => {\n while (parsedTagCursor < parsedComment.tags.length) {\n const candidate = parsedComment.tags[parsedTagCursor];\n parsedTagCursor += 1;\n if (candidate?.normalizedTagName === normalizedTagName) {\n return candidate;\n }\n }\n return null;\n };\n\n for (const parsedTag of parsedComment.tags) {\n if (TAGS_REQUIRING_RAW_TEXT.has(parsedTag.normalizedTagName)) {\n rawTextTags.push({ tag: parsedTag, commentText, commentOffset: range.pos });\n }\n }\n\n // Extract constraint nodes from custom blocks.\n // Tags in TAGS_REQUIRING_RAW_TEXT are skipped here and handled via the\n // TS compiler API in Phase 1b below.\n for (const block of docComment.customBlocks) {\n const tagName = normalizeConstraintTagName(block.blockTag.tagName.substring(1)); // Remove leading @ and normalize to camelCase\n const parsedTag = nextParsedTag(tagName);\n if (tagName === \"displayName\" || tagName === \"format\" || tagName === \"placeholder\") {\n const text = getBestBlockPayloadText(parsedTag, commentText, range.pos, block);\n if (text === \"\") continue;\n\n const provenance =\n parsedTag !== null\n ? provenanceForParsedTag(parsedTag, sourceFile, file)\n : provenanceForComment(range, sourceFile, file, tagName);\n switch (tagName) {\n case \"displayName\":\n if (!isMemberTargetDisplayName(text) && displayName === undefined) {\n displayName = text;\n displayNameProvenance = provenance;\n }\n break;\n\n case \"format\":\n annotations.push({\n kind: \"annotation\",\n annotationKind: \"format\",\n value: text,\n provenance,\n });\n break;\n\n case \"placeholder\":\n if (placeholder === undefined) {\n placeholder = text;\n placeholderProvenance = provenance;\n }\n break;\n }\n continue;\n }\n\n if (TAGS_REQUIRING_RAW_TEXT.has(tagName)) continue;\n\n const text = getBestBlockPayloadText(parsedTag, commentText, range.pos, block);\n const expectedType = isBuiltinConstraintName(tagName)\n ? BUILTIN_CONSTRAINT_DEFINITIONS[tagName]\n : undefined;\n if (text === \"\" && expectedType !== \"boolean\") continue;\n\n const provenance =\n parsedTag !== null\n ? provenanceForParsedTag(parsedTag, sourceFile, file)\n : provenanceForComment(range, sourceFile, file, tagName);\n const compilerDiagnostics = buildCompilerBackedConstraintDiagnostics(\n node,\n sourceFile,\n tagName,\n parsedTag,\n provenance,\n supportingDeclarations,\n options\n );\n if (compilerDiagnostics.length > 0) {\n diagnostics.push(...compilerDiagnostics);\n continue;\n }\n const constraintNode = parseConstraintTagValue(\n tagName,\n text,\n provenance,\n sharedTagValueOptions(options)\n );\n if (constraintNode) {\n constraints.push(constraintNode);\n }\n }\n\n // Extract @deprecated from the standard deprecated block\n if (docComment.deprecatedBlock !== undefined) {\n const message = extractBlockText(docComment.deprecatedBlock).trim();\n annotations.push({\n kind: \"annotation\",\n annotationKind: \"deprecated\",\n ...(message !== \"\" && { message }),\n provenance: provenanceForComment(range, sourceFile, file, \"deprecated\"),\n });\n }\n\n // Summary text → description annotation (spec 002 §2.3)\n {\n const summary = extractPlainText(docComment.summarySection).trim();\n if (summary !== \"\") {\n annotations.push({\n kind: \"annotation\",\n annotationKind: \"description\",\n value: summary,\n provenance: provenanceForComment(range, sourceFile, file, \"summary\"),\n });\n }\n }\n\n // @remarks → separate remarks annotation (spec 002 §2.3)\n if (docComment.remarksBlock !== undefined) {\n const remarksText = extractBlockText(docComment.remarksBlock).trim();\n if (remarksText !== \"\") {\n annotations.push({\n kind: \"annotation\",\n annotationKind: \"remarks\",\n value: remarksText,\n provenance: provenanceForComment(range, sourceFile, file, \"remarks\"),\n });\n }\n }\n }\n }\n\n if (displayName !== undefined && displayNameProvenance !== undefined) {\n annotations.push({\n kind: \"annotation\",\n annotationKind: \"displayName\",\n value: displayName,\n provenance: displayNameProvenance,\n });\n }\n\n if (placeholder !== undefined && placeholderProvenance !== undefined) {\n annotations.push({\n kind: \"annotation\",\n annotationKind: \"placeholder\",\n value: placeholder,\n provenance: placeholderProvenance,\n });\n }\n\n // ----- Phase 1b: TS compiler API for tags with TSDoc-incompatible content -----\n // @pattern, @enumOptions, and @defaultValue content can contain `@`, `{}`,\n // or quoted JSON payloads that the TSDoc parser treats as structural markers.\n // Prefer the shared syntax parse for these payloads and fall back to the\n // TS compiler API when a raw payload cannot be recovered from comments.\n if (rawTextTags.length > 0) {\n for (const rawTextTag of rawTextTags) {\n const fallbackQueue = rawTextFallbacks.get(rawTextTag.tag.normalizedTagName);\n const fallback = fallbackQueue?.shift();\n const text = choosePreferredPayloadText(\n getSharedPayloadText(rawTextTag.tag, rawTextTag.commentText, rawTextTag.commentOffset),\n fallback?.text ?? \"\"\n );\n if (text === \"\") continue;\n\n const provenance = provenanceForParsedTag(rawTextTag.tag, sourceFile, file);\n if (rawTextTag.tag.normalizedTagName === \"defaultValue\") {\n const defaultValueNode = parseDefaultValueTagValue(text, provenance);\n annotations.push(defaultValueNode);\n continue;\n }\n\n const compilerDiagnostics = buildCompilerBackedConstraintDiagnostics(\n node,\n sourceFile,\n rawTextTag.tag.normalizedTagName,\n rawTextTag.tag,\n provenance,\n supportingDeclarations,\n options\n );\n if (compilerDiagnostics.length > 0) {\n diagnostics.push(...compilerDiagnostics);\n continue;\n }\n\n const constraintNode = parseConstraintTagValue(\n rawTextTag.tag.normalizedTagName,\n text,\n provenance,\n sharedTagValueOptions(options)\n );\n if (constraintNode) {\n constraints.push(constraintNode);\n }\n }\n }\n\n for (const [tagName, fallbacks] of rawTextFallbacks) {\n for (const fallback of fallbacks) {\n const text = fallback.text.trim();\n if (text === \"\") continue;\n\n const provenance = fallback.provenance;\n if (tagName === \"defaultValue\") {\n const defaultValueNode = parseDefaultValueTagValue(text, provenance);\n annotations.push(defaultValueNode);\n continue;\n }\n\n const compilerDiagnostics = buildCompilerBackedConstraintDiagnostics(\n node,\n sourceFile,\n tagName,\n null,\n provenance,\n supportingDeclarations,\n options\n );\n if (compilerDiagnostics.length > 0) {\n diagnostics.push(...compilerDiagnostics);\n continue;\n }\n\n const constraintNode = parseConstraintTagValue(\n tagName,\n text,\n provenance,\n sharedTagValueOptions(options)\n );\n if (constraintNode) {\n constraints.push(constraintNode);\n }\n }\n }\n\n const result = { constraints, annotations, diagnostics };\n parseResultCache.set(cacheKey, result);\n return result;\n}\n\n/**\n * Checks if a TS AST node has a `@deprecated` tag using the TSDoc parser.\n *\n * Falls back to the TS compiler API for nodes without doc comments.\n */\nexport function hasDeprecatedTagTSDoc(node: ts.Node): boolean {\n const sourceFile = node.getSourceFile();\n const sourceText = sourceFile.getFullText();\n const commentRanges = ts.getLeadingCommentRanges(sourceText, node.getFullStart());\n\n if (commentRanges) {\n for (const range of commentRanges) {\n if (range.kind !== ts.SyntaxKind.MultiLineCommentTrivia) continue;\n const commentText = sourceText.substring(range.pos, range.end);\n if (!commentText.startsWith(\"/**\")) continue;\n\n const parser = getParser();\n const parserContext = parser.parseRange(\n TextRange.fromStringRange(sourceText, range.pos, range.end)\n );\n if (parserContext.docComment.deprecatedBlock !== undefined) {\n return true;\n }\n }\n }\n\n return false;\n}\n\n/**\n * Extracts root and member-target display-name metadata from a node's JSDoc tags.\n *\n * Member-target display-name tags use the syntax `@displayName :member Label`.\n * The first non-target `@displayName` is returned as the root display name.\n */\nexport function extractDisplayNameMetadata(node: ts.Node): DisplayNameMetadata {\n let displayName: string | undefined;\n const memberDisplayNames = new Map<string, string>();\n const sourceFile = node.getSourceFile();\n const sourceText = sourceFile.getFullText();\n const commentRanges = ts.getLeadingCommentRanges(sourceText, node.getFullStart());\n\n if (commentRanges) {\n for (const range of commentRanges) {\n if (range.kind !== ts.SyntaxKind.MultiLineCommentTrivia) continue;\n const commentText = sourceText.substring(range.pos, range.end);\n if (!commentText.startsWith(\"/**\")) continue;\n\n const parsed = parseCommentBlock(commentText);\n for (const tag of parsed.tags) {\n if (tag.normalizedTagName !== \"displayName\") {\n continue;\n }\n\n if (tag.target !== null && tag.argumentText !== \"\") {\n memberDisplayNames.set(tag.target.rawText, tag.argumentText);\n continue;\n }\n\n if (tag.argumentText !== \"\") {\n displayName ??= tag.argumentText;\n }\n }\n }\n }\n\n return {\n ...(displayName !== undefined && { displayName }),\n memberDisplayNames,\n };\n}\n\n// =============================================================================\n// PUBLIC HELPERS — path target extraction\n// =============================================================================\n\n/**\n * Extracts a path-target prefix (`:fieldName`) from constraint tag text.\n * Returns the parsed PathTarget and remaining text, or null if no path target.\n *\n * @example\n * extractPathTarget(\":value 0\") // → { path: { segments: [\"value\"] }, remainingText: \"0\" }\n * extractPathTarget(\"42\") // → null\n */\nexport function extractPathTarget(\n text: string\n): { path: PathTarget; remainingText: string } | null {\n return extractSharedPathTarget(text);\n}\n\n// =============================================================================\n// PRIVATE HELPERS — TSDoc text extraction\n// =============================================================================\n\n/**\n * Recursively extracts plain text content from a TSDoc DocNode tree.\n *\n * Walks child nodes and concatenates DocPlainText and DocSoftBreak content.\n */\nfunction extractBlockText(block: DocBlock): string {\n return extractPlainText(block.content);\n}\n\nfunction extractPlainText(node: DocNode): string {\n let result = \"\";\n if (node instanceof DocExcerpt) {\n return node.content.toString();\n }\n if (node instanceof DocPlainText) {\n return node.text;\n }\n if (node instanceof DocSoftBreak) {\n return \" \";\n }\n if (typeof node.getChildNodes === \"function\") {\n for (const child of node.getChildNodes()) {\n result += extractPlainText(child);\n }\n }\n return result;\n}\n\nfunction choosePreferredPayloadText(primary: string, fallback: string): string {\n const preferred = primary.trim();\n const alternate = fallback.trim();\n\n if (preferred === \"\") return alternate;\n if (alternate === \"\") return preferred;\n if (alternate.includes(\"\\n\")) return alternate;\n if (alternate.length > preferred.length && alternate.startsWith(preferred)) {\n return alternate;\n }\n\n return preferred;\n}\n\nfunction getSharedPayloadText(\n tag: ParsedCommentTag,\n commentText: string,\n commentOffset: number\n): string {\n if (tag.payloadSpan === null) {\n return \"\";\n }\n\n return sliceCommentSpan(commentText, tag.payloadSpan, {\n offset: commentOffset,\n }).trim();\n}\n\nfunction getBestBlockPayloadText(\n tag: ParsedCommentTag | null,\n commentText: string,\n commentOffset: number,\n block: DocBlock\n): string {\n const sharedText = tag === null ? \"\" : getSharedPayloadText(tag, commentText, commentOffset);\n const blockText = extractBlockText(block).replace(/\\s+/g, \" \").trim();\n return choosePreferredPayloadText(sharedText, blockText);\n}\n\nfunction collectRawTextFallbacks(\n node: ts.Node,\n file: string\n): Map<string, { text: string; provenance: Provenance }[]> {\n const fallbacks = new Map<string, { text: string; provenance: Provenance }[]>();\n\n for (const tag of ts.getJSDocTags(node)) {\n const tagName = normalizeConstraintTagName(tag.tagName.text);\n if (!TAGS_REQUIRING_RAW_TEXT.has(tagName)) continue;\n\n const commentText = getTagCommentText(tag)?.trim() ?? \"\";\n if (commentText === \"\") continue;\n\n const entries = fallbacks.get(tagName) ?? [];\n entries.push({\n text: commentText,\n provenance: provenanceForJSDocTag(tag, file),\n });\n fallbacks.set(tagName, entries);\n }\n\n return fallbacks;\n}\n\n// =============================================================================\n// PRIVATE HELPERS — constraint value parsing\n// =============================================================================\n\nfunction isMemberTargetDisplayName(text: string): boolean {\n return parseTagSyntax(\"displayName\", text).target !== null;\n}\n\n// =============================================================================\n// PRIVATE HELPERS — provenance\n// =============================================================================\n\nfunction provenanceForComment(\n range: ts.CommentRange,\n sourceFile: ts.SourceFile,\n file: string,\n tagName: string\n): Provenance {\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(range.pos);\n return {\n surface: \"tsdoc\",\n file,\n line: line + 1,\n column: character,\n tagName: \"@\" + tagName,\n };\n}\n\nfunction provenanceForParsedTag(\n tag: ParsedCommentTag,\n sourceFile: ts.SourceFile,\n file: string\n): Provenance {\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(tag.tagNameSpan.start);\n return {\n surface: \"tsdoc\",\n file,\n line: line + 1,\n column: character,\n tagName: \"@\" + tag.normalizedTagName,\n };\n}\n\nfunction provenanceForJSDocTag(tag: ts.JSDocTag, file: string): Provenance {\n const sourceFile = tag.getSourceFile();\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(tag.getStart());\n return {\n surface: \"tsdoc\",\n file,\n line: line + 1,\n column: character,\n tagName: \"@\" + tag.tagName.text,\n };\n}\n\n/**\n * Extracts the text content from a TypeScript JSDoc tag's comment.\n */\nfunction getTagCommentText(tag: ts.JSDocTag): string | undefined {\n if (tag.comment === undefined) {\n return undefined;\n }\n if (typeof tag.comment === \"string\") {\n return tag.comment;\n }\n return ts.getTextOfJSDocComment(tag.comment);\n}\n","/**\n * Constraint validator for the FormSpec IR.\n *\n * Delegates target-centric semantic analysis to `@formspec/analysis` so build\n * validation and editor tooling share the same inheritance, path-target,\n * contradiction, and broadening semantics.\n *\n * @packageDocumentation\n */\n\nimport {\n analyzeConstraintTargets,\n type ConstraintRegistryLike,\n type ConstraintSemanticDiagnostic,\n} from \"@formspec/analysis/internal\";\nimport type { FormIR, FormIRElement, FieldNode, ObjectProperty } from \"@formspec/core/internals\";\nimport type { ExtensionRegistry } from \"../extensions/index.js\";\n\nexport type ValidationDiagnostic = ConstraintSemanticDiagnostic;\n\nexport interface ValidationResult {\n readonly diagnostics: readonly ValidationDiagnostic[];\n readonly valid: boolean;\n}\n\nexport interface ValidateIROptions {\n readonly vendorPrefix?: string;\n readonly extensionRegistry?: ExtensionRegistry;\n}\n\ninterface ValidationContext {\n readonly diagnostics: ValidationDiagnostic[];\n readonly extensionRegistry: ConstraintRegistryLike | undefined;\n readonly typeRegistry: FormIR[\"typeRegistry\"];\n}\n\nfunction validateFieldNode(ctx: ValidationContext, field: FieldNode): void {\n const analysis = analyzeConstraintTargets(\n field.name,\n field.type,\n field.constraints,\n ctx.typeRegistry,\n ctx.extensionRegistry === undefined\n ? undefined\n : {\n extensionRegistry: ctx.extensionRegistry,\n }\n );\n ctx.diagnostics.push(...analysis.diagnostics);\n\n if (field.type.kind === \"object\") {\n for (const property of field.type.properties) {\n validateObjectProperty(ctx, field.name, property);\n }\n }\n}\n\nfunction validateObjectProperty(\n ctx: ValidationContext,\n parentName: string,\n property: ObjectProperty\n): void {\n const qualifiedName = `${parentName}.${property.name}`;\n const analysis = analyzeConstraintTargets(\n qualifiedName,\n property.type,\n property.constraints,\n ctx.typeRegistry,\n ctx.extensionRegistry === undefined\n ? undefined\n : {\n extensionRegistry: ctx.extensionRegistry,\n }\n );\n ctx.diagnostics.push(...analysis.diagnostics);\n\n if (property.type.kind === \"object\") {\n for (const nestedProperty of property.type.properties) {\n validateObjectProperty(ctx, qualifiedName, nestedProperty);\n }\n }\n}\n\nfunction validateElement(ctx: ValidationContext, element: FormIRElement): void {\n switch (element.kind) {\n case \"field\":\n validateFieldNode(ctx, element);\n break;\n case \"group\":\n for (const child of element.elements) {\n validateElement(ctx, child);\n }\n break;\n case \"conditional\":\n for (const child of element.elements) {\n validateElement(ctx, child);\n }\n break;\n default: {\n const exhaustive: never = element;\n throw new Error(`Unhandled element kind: ${String(exhaustive)}`);\n }\n }\n}\n\nexport function validateIR(ir: FormIR, options?: ValidateIROptions): ValidationResult {\n const ctx: ValidationContext = {\n diagnostics: [],\n extensionRegistry: options?.extensionRegistry,\n typeRegistry: ir.typeRegistry,\n };\n\n for (const element of ir.elements) {\n validateElement(ctx, element);\n }\n\n return {\n diagnostics: ctx.diagnostics,\n valid: ctx.diagnostics.every((diagnostic) => diagnostic.severity !== \"error\"),\n };\n}\n","/**\n * Class schema generator.\n *\n * Generates JSON Schema 2020-12 and JSON Forms UI Schema from statically\n * analyzed class/interface/type alias declarations, routing through the\n * canonical FormIR pipeline.\n */\n\nimport type { UISchema } from \"../ui-schema/types.js\";\nimport {\n analyzeNamedTypeToIR,\n createProgramContext,\n findClassByName,\n} from \"../analyzer/program.js\";\nimport { analyzeClassToIR, type IRClassAnalysis } from \"../analyzer/class-analyzer.js\";\nimport { canonicalizeTSDoc, type TSDocSource } from \"../canonicalize/index.js\";\nimport {\n generateJsonSchemaFromIR,\n type GenerateJsonSchemaFromIROptions,\n type JsonSchema2020,\n} from \"../json-schema/ir-generator.js\";\nimport type { ExtensionRegistry } from \"../extensions/index.js\";\nimport { generateUiSchemaFromIR } from \"../ui-schema/ir-generator.js\";\nimport { validateIR, type ValidationDiagnostic } from \"../validate/index.js\";\n\n/**\n * Generated schemas for a class.\n *\n * @beta\n */\nexport interface ClassSchemas {\n /** JSON Schema 2020-12 for validation */\n jsonSchema: JsonSchema2020;\n /** JSON Forms UI Schema for rendering */\n uiSchema: UISchema;\n}\n\n/**\n * Generates JSON Schema 2020-12 and UI Schema from an IR class analysis.\n *\n * Routes through the canonical IR pipeline:\n * IRClassAnalysis → canonicalizeTSDoc → FormIR → JSON Schema / UI Schema\n *\n * @param analysis - The IR analysis result (from analyzeClassToIR, analyzeInterfaceToIR, or analyzeTypeAliasToIR)\n * @param source - Optional source file metadata for provenance\n * @returns Generated JSON Schema and UI Schema\n */\nexport function generateClassSchemas(\n analysis: IRClassAnalysis,\n source?: TSDocSource,\n options?: GenerateJsonSchemaFromIROptions\n): ClassSchemas {\n const errorDiagnostics = analysis.diagnostics?.filter(\n (diagnostic) => diagnostic.severity === \"error\"\n );\n if (errorDiagnostics !== undefined && errorDiagnostics.length > 0) {\n throw new Error(formatValidationError(errorDiagnostics));\n }\n\n const ir = canonicalizeTSDoc(analysis, source);\n const validationResult = validateIR(ir, {\n ...(options?.extensionRegistry !== undefined && {\n extensionRegistry: options.extensionRegistry,\n }),\n ...(options?.vendorPrefix !== undefined && { vendorPrefix: options.vendorPrefix }),\n });\n if (!validationResult.valid) {\n throw new Error(formatValidationError(validationResult.diagnostics));\n }\n\n return {\n jsonSchema: generateJsonSchemaFromIR(ir, options),\n uiSchema: generateUiSchemaFromIR(ir),\n };\n}\n\nfunction formatValidationError(diagnostics: readonly ValidationDiagnostic[]): string {\n const lines = diagnostics.map((diagnostic) => {\n const primary = formatLocation(diagnostic.primaryLocation);\n const related =\n diagnostic.relatedLocations.length > 0\n ? ` [related: ${diagnostic.relatedLocations.map(formatLocation).join(\", \")}]`\n : \"\";\n return `${diagnostic.code}: ${diagnostic.message} (${primary})${related}`;\n });\n\n return `FormSpec validation failed:\\n${lines.map((line) => `- ${line}`).join(\"\\n\")}`;\n}\n\nfunction formatLocation(location: ValidationDiagnostic[\"primaryLocation\"]): string {\n return `${location.file}:${String(location.line)}:${String(location.column)}`;\n}\n\n/**\n * Shared options for schema generation flows that support custom extensions.\n *\n * @public\n */\nexport interface StaticSchemaGenerationOptions {\n /**\n * Registry used to resolve custom types, constraints, and annotations.\n */\n readonly extensionRegistry?: ExtensionRegistry | undefined;\n /**\n * Vendor prefix for emitted extension keywords.\n * @defaultValue \"x-formspec\"\n */\n readonly vendorPrefix?: string | undefined;\n}\n\n/**\n * Options for generating schemas from a decorated class.\n *\n * @public\n */\nexport interface GenerateFromClassOptions extends StaticSchemaGenerationOptions {\n /** Path to the TypeScript source file */\n filePath: string;\n /** Class name to analyze */\n className: string;\n}\n\n/**\n * Result of generating schemas from a decorated class.\n *\n * @public\n */\nexport interface GenerateFromClassResult {\n /** JSON Schema 2020-12 for validation */\n jsonSchema: JsonSchema2020;\n /** JSON Forms UI Schema for rendering */\n uiSchema: UISchema;\n}\n\n/**\n * Generates JSON Schema and UI Schema from a decorated TypeScript class.\n *\n * This is a high-level entry point that handles the entire pipeline:\n * creating a TypeScript program, finding the class, analyzing it to IR,\n * and generating schemas — all in one call.\n *\n * @example\n * ```typescript\n * const result = generateSchemasFromClass({\n * filePath: \"./src/forms.ts\",\n * className: \"UserForm\",\n * });\n * console.log(result.jsonSchema);\n * ```\n *\n * @param options - File path, class name, and optional compiler options\n * @returns Generated JSON Schema and UI Schema\n *\n * @public\n */\nexport function generateSchemasFromClass(\n options: GenerateFromClassOptions\n): GenerateFromClassResult {\n const ctx = createProgramContext(options.filePath);\n const classDecl = findClassByName(ctx.sourceFile, options.className);\n\n if (!classDecl) {\n throw new Error(`Class \"${options.className}\" not found in ${options.filePath}`);\n }\n\n const analysis = analyzeClassToIR(\n classDecl,\n ctx.checker,\n options.filePath,\n options.extensionRegistry\n );\n return generateClassSchemas(\n analysis,\n { file: options.filePath },\n {\n extensionRegistry: options.extensionRegistry,\n vendorPrefix: options.vendorPrefix,\n }\n );\n}\n\n/**\n * Options for generating schemas from a named type (class, interface, or type alias).\n *\n * @public\n */\nexport interface GenerateSchemasOptions extends StaticSchemaGenerationOptions {\n /** Path to the TypeScript source file */\n filePath: string;\n /** Name of the exported class, interface, or type alias to analyze */\n typeName: string;\n}\n\n/**\n * Generates JSON Schema and UI Schema from a named TypeScript\n * type — a decorated class, an interface with TSDoc tags, or a type alias.\n *\n * This is the recommended entry point. It automatically detects whether\n * the name resolves to a class, interface, or type alias and uses the\n * appropriate IR analysis pipeline.\n *\n * @example\n * ```typescript\n * const result = generateSchemas({\n * filePath: \"./src/config.ts\",\n * typeName: \"DiscountConfig\",\n * });\n * ```\n *\n * @param options - File path and type name\n * @returns Generated JSON Schema and UI Schema\n *\n * @public\n */\nexport function generateSchemas(options: GenerateSchemasOptions): GenerateFromClassResult {\n const analysis = analyzeNamedTypeToIR(\n options.filePath,\n options.typeName,\n options.extensionRegistry\n );\n return generateClassSchemas(analysis, { file: options.filePath }, options);\n}\n","/**\n * Mixed-authoring schema generator.\n *\n * Composes a statically analyzed TSDoc/class/interface/type-alias model with\n * ChainDSL-authored field overlays. The static model remains authoritative for\n * structure and constraints; overlays may add runtime field behavior such as\n * dynamic enum or dynamic schema metadata.\n */\n\nimport type {\n FormElement,\n FormSpec,\n} from \"@formspec/core\";\nimport type {\n AnnotationNode,\n FieldNode,\n FormIRElement,\n TypeNode,\n} from \"@formspec/core/internals\";\nimport type { JsonSchema2020 } from \"../json-schema/ir-generator.js\";\nimport { generateJsonSchemaFromIR } from \"../json-schema/ir-generator.js\";\nimport { generateUiSchemaFromIR } from \"../ui-schema/ir-generator.js\";\nimport type { UISchema } from \"../ui-schema/types.js\";\nimport { canonicalizeChainDSL, canonicalizeTSDoc } from \"../canonicalize/index.js\";\nimport { analyzeNamedTypeToIR } from \"../analyzer/program.js\";\nimport type { IRClassAnalysis } from \"../analyzer/class-analyzer.js\";\nimport type { StaticSchemaGenerationOptions } from \"./class-schema.js\";\n\n/**\n * Result of generating schemas from a mixed-authoring composition.\n *\n * @public\n */\nexport interface MixedAuthoringSchemas {\n /** JSON Schema 2020-12 for validation. */\n readonly jsonSchema: JsonSchema2020;\n /** JSON Forms UI Schema for rendering. */\n readonly uiSchema: UISchema;\n}\n\n/**\n * Options for generating mixed-authoring schemas.\n *\n * The `typeName` can resolve to a class, interface, or object type alias, just\n * like `generateSchemas()`.\n *\n * @public\n */\nexport interface BuildMixedAuthoringSchemasOptions extends StaticSchemaGenerationOptions {\n /** Path to the TypeScript source file. */\n readonly filePath: string;\n /** Name of the class, interface, or type alias to analyze. */\n readonly typeName: string;\n /** ChainDSL overlays to apply to the static model. Groups and conditionals are flattened by field name. */\n readonly overlays: FormSpec<readonly FormElement[]>;\n}\n\n/**\n * Builds JSON Schema and UI Schema from a TSDoc-derived model with ChainDSL\n * field overlays.\n *\n * Overlays are matched by field name. The static model wins for structure,\n * ordering, and constraints; ChainDSL overlays may contribute dynamic runtime\n * field metadata such as dynamic enum or dynamic schema keywords, and may fill\n * in missing annotations.\n *\n * @public\n */\nexport function buildMixedAuthoringSchemas(\n options: BuildMixedAuthoringSchemasOptions\n): MixedAuthoringSchemas {\n const { filePath, typeName, overlays, ...schemaOptions } = options;\n const analysis = analyzeNamedTypeToIR(filePath, typeName, schemaOptions.extensionRegistry);\n const composedAnalysis = composeAnalysisWithOverlays(analysis, overlays);\n const ir = canonicalizeTSDoc(composedAnalysis, { file: filePath });\n\n return {\n jsonSchema: generateJsonSchemaFromIR(ir, schemaOptions),\n uiSchema: generateUiSchemaFromIR(ir),\n };\n}\n\nfunction composeAnalysisWithOverlays(\n analysis: IRClassAnalysis,\n overlays: FormSpec<readonly FormElement[]>\n): IRClassAnalysis {\n const overlayIR = canonicalizeChainDSL(overlays);\n const overlayFields = collectOverlayFields(overlayIR.elements);\n\n if (overlayFields.length === 0) {\n return analysis;\n }\n\n const overlayByName = new Map<string, FieldNode>();\n for (const field of overlayFields) {\n if (overlayByName.has(field.name)) {\n throw new Error(`Mixed-authoring overlays define \"${field.name}\" more than once`);\n }\n overlayByName.set(field.name, field);\n }\n\n const mergedFields: FieldNode[] = [];\n\n for (const baseField of analysis.fields) {\n const overlayField = overlayByName.get(baseField.name);\n if (overlayField === undefined) {\n mergedFields.push(baseField);\n continue;\n }\n\n mergedFields.push(mergeFieldOverlay(baseField, overlayField, analysis.typeRegistry));\n overlayByName.delete(baseField.name);\n }\n\n if (overlayByName.size > 0) {\n const unknownFields = [...overlayByName.keys()].sort().join(\", \");\n throw new Error(\n `Mixed-authoring overlays reference fields that are not present in the static model: ${unknownFields}`\n );\n }\n\n return {\n ...analysis,\n fields: mergedFields,\n };\n}\n\nfunction collectOverlayFields(elements: readonly FormIRElement[]): FieldNode[] {\n const fields: FieldNode[] = [];\n\n for (const element of elements) {\n switch (element.kind) {\n case \"field\":\n fields.push(element);\n break;\n case \"group\":\n fields.push(...collectOverlayFields(element.elements));\n break;\n case \"conditional\":\n fields.push(...collectOverlayFields(element.elements));\n break;\n default: {\n const _exhaustive: never = element;\n void _exhaustive;\n }\n }\n }\n\n return fields;\n}\n\nfunction mergeFieldOverlay(\n baseField: FieldNode,\n overlayField: FieldNode,\n typeRegistry: IRClassAnalysis[\"typeRegistry\"]\n): FieldNode {\n assertSupportedOverlayField(baseField, overlayField);\n return {\n ...baseField,\n type: mergeFieldType(baseField, overlayField, typeRegistry),\n annotations: mergeAnnotations(baseField.annotations, overlayField.annotations),\n };\n}\n\nfunction assertSupportedOverlayField(baseField: FieldNode, overlayField: FieldNode): void {\n if (overlayField.constraints.length > 0) {\n throw new Error(\n `Mixed-authoring overlay for \"${baseField.name}\" cannot define constraints; keep constraints on the static model`\n );\n }\n\n if (overlayField.required && !baseField.required) {\n throw new Error(\n `Mixed-authoring overlay for \"${baseField.name}\" cannot change requiredness; keep requiredness on the static model`\n );\n }\n}\n\nfunction mergeFieldType(\n baseField: FieldNode,\n overlayField: FieldNode,\n typeRegistry: IRClassAnalysis[\"typeRegistry\"]\n): TypeNode {\n const { type: baseType } = baseField;\n const { type: overlayType } = overlayField;\n\n if (overlayType.kind === \"object\" || overlayType.kind === \"array\") {\n throw new Error(\n `Mixed-authoring overlays do not support nested object or array overlays for \"${baseField.name}\"`\n );\n }\n\n if (overlayType.kind === \"dynamic\") {\n if (!isCompatibleDynamicOverlay(baseField, overlayField, typeRegistry)) {\n throw new Error(\n `Mixed-authoring overlay for \"${baseField.name}\" is incompatible with the static field type`\n );\n }\n return overlayType;\n }\n\n if (!isSameStaticTypeShape(baseType, overlayType)) {\n throw new Error(\n `Mixed-authoring overlay for \"${baseField.name}\" must preserve the static field type`\n );\n }\n\n return baseType;\n}\n\nfunction isCompatibleDynamicOverlay(\n baseField: FieldNode,\n overlayField: FieldNode,\n typeRegistry: IRClassAnalysis[\"typeRegistry\"]\n): boolean {\n const overlayType = overlayField.type;\n if (overlayType.kind !== \"dynamic\") {\n return false;\n }\n\n const resolvedBaseType = resolveReferenceType(baseField.type, typeRegistry);\n if (resolvedBaseType === null) {\n return false;\n }\n\n if (overlayType.dynamicKind === \"enum\") {\n return resolvedBaseType.kind === \"primitive\"\n ? resolvedBaseType.primitiveKind === \"string\"\n : resolvedBaseType.kind === \"enum\";\n }\n\n return resolvedBaseType.kind === \"object\" || resolvedBaseType.kind === \"record\";\n}\n\nfunction resolveReferenceType(\n type: TypeNode,\n typeRegistry: IRClassAnalysis[\"typeRegistry\"],\n seen = new Set<string>()\n): TypeNode | null {\n if (type.kind !== \"reference\") {\n return type;\n }\n\n if (seen.has(type.name)) {\n return null;\n }\n\n const definition = typeRegistry[type.name];\n if (definition === undefined) {\n return null;\n }\n\n seen.add(type.name);\n return resolveReferenceType(definition.type, typeRegistry, seen);\n}\n\nfunction isSameStaticTypeShape(baseType: TypeNode, overlayType: TypeNode): boolean {\n if (baseType.kind !== overlayType.kind) {\n return false;\n }\n\n switch (baseType.kind) {\n case \"primitive\":\n return (\n overlayType.kind === \"primitive\" && baseType.primitiveKind === overlayType.primitiveKind\n );\n case \"enum\":\n return overlayType.kind === \"enum\";\n case \"dynamic\":\n return (\n overlayType.kind === \"dynamic\" &&\n baseType.dynamicKind === overlayType.dynamicKind &&\n baseType.sourceKey === overlayType.sourceKey\n );\n case \"record\":\n return overlayType.kind === \"record\";\n case \"reference\":\n return overlayType.kind === \"reference\" && baseType.name === overlayType.name;\n case \"union\":\n return overlayType.kind === \"union\";\n case \"custom\":\n return overlayType.kind === \"custom\" && baseType.typeId === overlayType.typeId;\n case \"object\":\n case \"array\":\n // Mixed authoring keeps the static type verbatim for structured fields.\n // We only need shape equality for scalar-like overlays that could replace\n // the static field type if we returned the overlay type by mistake.\n return true;\n default: {\n const _exhaustive: never = baseType;\n return _exhaustive;\n }\n }\n}\n\nfunction mergeAnnotations(\n baseAnnotations: readonly AnnotationNode[],\n overlayAnnotations: readonly AnnotationNode[]\n): AnnotationNode[] {\n const baseKeys = new Set(baseAnnotations.map(annotationKey));\n const overlayOnly = overlayAnnotations.filter(\n (annotation) => !baseKeys.has(annotationKey(annotation))\n );\n return [...baseAnnotations, ...overlayOnly];\n}\n\nfunction annotationKey(annotation: AnnotationNode): string {\n return annotation.annotationKind === \"custom\"\n ? `${annotation.annotationKind}:${annotation.annotationId}`\n : annotation.annotationKind;\n}\n"],"mappings":";AAoDA,SAAS,kBAAkB;AAO3B,IAAM,uBAAmC;AAAA,EACvC,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AAAA,EACN,QAAQ;AACV;AAMA,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YAAM,cAAqB;AAC3B,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAEA,SAAS,iBACP,iBACA,oBACkB;AAClB,QAAM,WAAW,IAAI,IAAI,gBAAgB,IAAI,aAAa,CAAC;AAC3D,QAAM,cAAc,mBAAmB;AAAA,IACrC,CAAC,eAAe,CAAC,SAAS,IAAI,cAAc,UAAU,CAAC;AAAA,EACzD;AACA,SAAO,CAAC,GAAG,iBAAiB,GAAG,WAAW;AAC5C;AAEA,SAAS,cAAc,YAAoC;AACzD,SAAO,WAAW,mBAAmB,WACjC,GAAG,WAAW,cAAc,IAAI,WAAW,YAAY,KACvD,WAAW;AACjB;;;AR9IO,SAAS,iBACd,MACA,SACa;AACb,SAAO;AAAA,IACL,YAAY,mBAAmB,MAAM,OAAO;AAAA,IAC5C,UAAU,iBAAiB,IAAI;AAAA,EACjC;AACF;AA2DO,SAAS,aACd,MACA,SACoB;AACpB,QAAM,EAAE,QAAQ,OAAO,UAAU,SAAS,GAAG,aAAa,IAAI;AAG9D,QAAM,eAAe,iBAAiB,SAAY,SAAY,EAAE,aAAa;AAE7E,QAAM,EAAE,YAAY,UAAAC,UAAS,IAAI,iBAAiB,MAAM,YAAY;AAGpE,MAAI,CAAI,cAAW,MAAM,GAAG;AAC1B,IAAG,aAAU,QAAQ,EAAE,WAAW,KAAK,CAAC;AAAA,EAC1C;AAGA,QAAM,iBAAsB,WAAK,QAAQ,GAAG,IAAI,cAAc;AAC9D,QAAM,eAAoB,WAAK,QAAQ,GAAG,IAAI,gBAAgB;AAE9D,EAAG,iBAAc,gBAAgB,KAAK,UAAU,YAAY,MAAM,MAAM,CAAC;AACzE,EAAG,iBAAc,cAAc,KAAK,UAAUA,WAAU,MAAM,MAAM,CAAC;AAErE,SAAO,EAAE,gBAAgB,aAAa;AACxC;","names":["IR_VERSION","z","path","ts","ts","ts","text","provenance","members","isBooleanUnion","uiSchema"]}
|
|
1
|
+
{"version":3,"sources":["../src/canonicalize/chain-dsl-canonicalizer.ts","../src/canonicalize/tsdoc-canonicalizer.ts","../src/json-schema/ir-generator.ts","../src/json-schema/generator.ts","../src/ui-schema/schema.ts","../src/ui-schema/ir-generator.ts","../src/ui-schema/generator.ts","../src/index.ts","../src/extensions/registry.ts","../src/json-schema/schema.ts","../src/generators/class-schema.ts","../src/analyzer/program.ts","../src/analyzer/class-analyzer.ts","../src/analyzer/jsdoc-constraints.ts","../src/analyzer/tsdoc-parser.ts","../src/validate/constraint-validator.ts","../src/generators/mixed-authoring.ts"],"sourcesContent":["/**\n * Canonicalizer that translates chain DSL `FormSpec` objects into the\n * canonical FormIR intermediate representation.\n *\n * This module maps the runtime objects produced by `@formspec/dsl` builder\n * functions (`field.*`, `group`, `when`, `formspec`) into the IR that all\n * downstream phases (validation, JSON Schema generation, UI Schema generation)\n * consume.\n */\n\nimport type {\n // Source types (chain DSL)\n AnyField,\n ArrayField,\n BooleanField,\n Conditional,\n DynamicEnumField,\n DynamicSchemaField,\n EnumOptionValue,\n FormElement,\n FormSpec,\n Group,\n NumberField,\n ObjectField,\n StaticEnumField,\n TextField,\n} from \"@formspec/core\";\nimport type {\n // IR types\n JsonValue,\n AnnotationNode,\n ArrayTypeNode,\n ConstraintNode,\n ConditionalLayoutNode,\n DisplayNameAnnotationNode,\n DynamicTypeNode,\n EnumMember,\n EnumTypeNode,\n FieldNode,\n FormIR,\n FormIRElement,\n GroupLayoutNode,\n LengthConstraintNode,\n NumericConstraintNode,\n ObjectProperty,\n PatternConstraintNode,\n ObjectTypeNode,\n PlaceholderAnnotationNode,\n PrimitiveTypeNode,\n Provenance,\n TypeNode,\n} from \"@formspec/core/internals\";\nimport { IR_VERSION } from \"@formspec/core/internals\";\n\n// =============================================================================\n// CONSTANTS\n// =============================================================================\n\n/** Default provenance for chain DSL nodes (no source location available). */\nconst CHAIN_DSL_PROVENANCE: Provenance = {\n surface: \"chain-dsl\",\n file: \"\",\n line: 0,\n column: 0,\n} as const;\n\n// =============================================================================\n// TYPE GUARDS\n// =============================================================================\n\nfunction isGroup(el: FormElement): el is Group<readonly FormElement[]> {\n return el._type === \"group\";\n}\n\nfunction isConditional(\n el: FormElement\n): el is Conditional<string, unknown, readonly FormElement[]> {\n return el._type === \"conditional\";\n}\n\nfunction isField(el: FormElement): el is AnyField {\n return el._type === \"field\";\n}\n\n// =============================================================================\n// PUBLIC API\n// =============================================================================\n\n/**\n * Translates a chain DSL `FormSpec` into the canonical `FormIR`.\n *\n * @param form - A form specification created via `formspec(...)` from `@formspec/dsl`\n * @returns The canonical intermediate representation\n */\nexport function canonicalizeChainDSL(form: FormSpec<readonly FormElement[]>): FormIR {\n return {\n kind: \"form-ir\",\n irVersion: IR_VERSION,\n elements: canonicalizeElements(form.elements),\n rootAnnotations: [],\n typeRegistry: {},\n provenance: CHAIN_DSL_PROVENANCE,\n };\n}\n\n// =============================================================================\n// ELEMENT CANONICALIZATION\n// =============================================================================\n\n/**\n * Canonicalizes an array of chain DSL form elements into IR elements.\n */\nfunction canonicalizeElements(elements: readonly FormElement[]): FormIRElement[] {\n return elements.map(canonicalizeElement);\n}\n\n/**\n * Dispatches a single form element to its specific canonicalization function.\n */\nfunction canonicalizeElement(element: FormElement): FormIRElement {\n if (isField(element)) {\n return canonicalizeField(element);\n }\n if (isGroup(element)) {\n return canonicalizeGroup(element);\n }\n if (isConditional(element)) {\n return canonicalizeConditional(element);\n }\n const _exhaustive: never = element;\n throw new Error(`Unknown element type: ${JSON.stringify(_exhaustive)}`);\n}\n\n// =============================================================================\n// FIELD CANONICALIZATION\n// =============================================================================\n\n/**\n * Dispatches a field element to its type-specific canonicalization function.\n */\nfunction canonicalizeField(field: AnyField): FieldNode {\n switch (field._field) {\n case \"text\":\n return canonicalizeTextField(field);\n case \"number\":\n return canonicalizeNumberField(field);\n case \"boolean\":\n return canonicalizeBooleanField(field);\n case \"enum\":\n return canonicalizeStaticEnumField(field);\n case \"dynamic_enum\":\n return canonicalizeDynamicEnumField(field);\n case \"dynamic_schema\":\n return canonicalizeDynamicSchemaField(field);\n case \"array\":\n return canonicalizeArrayField(field);\n case \"object\":\n return canonicalizeObjectField(field);\n default: {\n const _exhaustive: never = field;\n throw new Error(`Unknown field type: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n\n// =============================================================================\n// SPECIFIC FIELD TYPE CANONICALIZERS\n// =============================================================================\n\nfunction canonicalizeTextField(field: TextField<string>): FieldNode {\n const type: PrimitiveTypeNode = { kind: \"primitive\", primitiveKind: \"string\" };\n const constraints: ConstraintNode[] = [];\n\n if (field.minLength !== undefined) {\n const c: LengthConstraintNode = {\n kind: \"constraint\",\n constraintKind: \"minLength\",\n value: field.minLength,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n constraints.push(c);\n }\n\n if (field.maxLength !== undefined) {\n const c: LengthConstraintNode = {\n kind: \"constraint\",\n constraintKind: \"maxLength\",\n value: field.maxLength,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n constraints.push(c);\n }\n\n if (field.pattern !== undefined) {\n const c: PatternConstraintNode = {\n kind: \"constraint\",\n constraintKind: \"pattern\",\n pattern: field.pattern,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n constraints.push(c);\n }\n\n return buildFieldNode(\n field.name,\n type,\n field.required,\n buildAnnotations(field.label, field.placeholder),\n constraints\n );\n}\n\nfunction canonicalizeNumberField(field: NumberField<string>): FieldNode {\n const type: PrimitiveTypeNode = { kind: \"primitive\", primitiveKind: \"number\" };\n const constraints: ConstraintNode[] = [];\n\n if (field.min !== undefined) {\n const c: NumericConstraintNode = {\n kind: \"constraint\",\n constraintKind: \"minimum\",\n value: field.min,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n constraints.push(c);\n }\n\n if (field.max !== undefined) {\n const c: NumericConstraintNode = {\n kind: \"constraint\",\n constraintKind: \"maximum\",\n value: field.max,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n constraints.push(c);\n }\n\n if (field.multipleOf !== undefined) {\n const c: NumericConstraintNode = {\n kind: \"constraint\",\n constraintKind: \"multipleOf\",\n value: field.multipleOf,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n constraints.push(c);\n }\n\n return buildFieldNode(\n field.name,\n type,\n field.required,\n buildAnnotations(field.label),\n constraints\n );\n}\n\nfunction canonicalizeBooleanField(field: BooleanField<string>): FieldNode {\n const type: PrimitiveTypeNode = { kind: \"primitive\", primitiveKind: \"boolean\" };\n return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));\n}\n\nfunction canonicalizeStaticEnumField(\n field: StaticEnumField<string, readonly EnumOptionValue[]>\n): FieldNode {\n const members: EnumMember[] = field.options.map((opt) => {\n if (typeof opt === \"string\") {\n return { value: opt } satisfies EnumMember;\n }\n // Object option with id/label\n return { value: opt.id, displayName: opt.label } satisfies EnumMember;\n });\n\n const type: EnumTypeNode = { kind: \"enum\", members };\n return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));\n}\n\nfunction canonicalizeDynamicEnumField(field: DynamicEnumField<string, string>): FieldNode {\n const type: DynamicTypeNode = {\n kind: \"dynamic\",\n dynamicKind: \"enum\",\n sourceKey: field.source,\n parameterFields: field.params ? [...field.params] : [],\n };\n return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));\n}\n\nfunction canonicalizeDynamicSchemaField(field: DynamicSchemaField<string>): FieldNode {\n const type: DynamicTypeNode = {\n kind: \"dynamic\",\n dynamicKind: \"schema\",\n sourceKey: field.schemaSource,\n parameterFields: [],\n };\n return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));\n}\n\nfunction canonicalizeArrayField(field: ArrayField<string, readonly FormElement[]>): FieldNode {\n // Array items form an object type from the sub-elements\n const itemProperties = buildObjectProperties(field.items);\n const itemsType: ObjectTypeNode = {\n kind: \"object\",\n properties: itemProperties,\n additionalProperties: true,\n };\n const type: ArrayTypeNode = { kind: \"array\", items: itemsType };\n\n const constraints: ConstraintNode[] = [];\n if (field.minItems !== undefined) {\n const c: LengthConstraintNode = {\n kind: \"constraint\",\n constraintKind: \"minItems\",\n value: field.minItems,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n constraints.push(c);\n }\n if (field.maxItems !== undefined) {\n const c: LengthConstraintNode = {\n kind: \"constraint\",\n constraintKind: \"maxItems\",\n value: field.maxItems,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n constraints.push(c);\n }\n\n return buildFieldNode(\n field.name,\n type,\n field.required,\n buildAnnotations(field.label),\n constraints\n );\n}\n\nfunction canonicalizeObjectField(field: ObjectField<string, readonly FormElement[]>): FieldNode {\n const properties = buildObjectProperties(field.properties);\n const type: ObjectTypeNode = {\n kind: \"object\",\n properties,\n additionalProperties: true,\n };\n return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));\n}\n\n// =============================================================================\n// LAYOUT CANONICALIZATION\n// =============================================================================\n\nfunction canonicalizeGroup(g: Group<readonly FormElement[]>): GroupLayoutNode {\n return {\n kind: \"group\",\n label: g.label,\n elements: canonicalizeElements(g.elements),\n provenance: CHAIN_DSL_PROVENANCE,\n };\n}\n\nfunction canonicalizeConditional(\n c: Conditional<string, unknown, readonly FormElement[]>\n): ConditionalLayoutNode {\n return {\n kind: \"conditional\",\n fieldName: c.field,\n // Conditional values from the chain DSL are JSON-serializable primitives\n // (strings, numbers, booleans) produced by the `is()` predicate helper.\n value: assertJsonValue(c.value),\n elements: canonicalizeElements(c.elements),\n provenance: CHAIN_DSL_PROVENANCE,\n };\n}\n\n// =============================================================================\n// HELPERS\n// =============================================================================\n\n/**\n * Validates that a value is JSON-serializable (`JsonValue`).\n * The chain DSL's `is()` helper constrains conditional values to\n * JSON-compatible primitives, but the TypeScript type is `unknown`.\n * This runtime guard replaces an `as` cast with a validated assertion.\n */\nfunction assertJsonValue(v: unknown): JsonValue {\n if (v === null || typeof v === \"string\" || typeof v === \"number\" || typeof v === \"boolean\") {\n return v;\n }\n if (Array.isArray(v)) {\n return v.map(assertJsonValue);\n }\n if (typeof v === \"object\") {\n const result: Record<string, JsonValue> = {};\n for (const [key, val] of Object.entries(v)) {\n result[key] = assertJsonValue(val);\n }\n return result;\n }\n // Remaining types (function, symbol, bigint, undefined) are not JSON-serializable\n throw new TypeError(`Conditional value is not a valid JsonValue: ${typeof v}`);\n}\n\n/**\n * Builds a FieldNode from common field properties.\n */\nfunction buildFieldNode(\n name: string,\n type: TypeNode,\n required: boolean | undefined,\n annotations: AnnotationNode[],\n constraints: ConstraintNode[] = []\n): FieldNode {\n return {\n kind: \"field\",\n name,\n type,\n required: required === true,\n constraints,\n annotations,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n}\n\n/**\n * Builds annotation nodes from optional label and placeholder values.\n */\nfunction buildAnnotations(label?: string, placeholder?: string): AnnotationNode[] {\n const annotations: AnnotationNode[] = [];\n\n if (label !== undefined) {\n const a: DisplayNameAnnotationNode = {\n kind: \"annotation\",\n annotationKind: \"displayName\",\n value: label,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n annotations.push(a);\n }\n\n if (placeholder !== undefined) {\n const a: PlaceholderAnnotationNode = {\n kind: \"annotation\",\n annotationKind: \"placeholder\",\n value: placeholder,\n provenance: CHAIN_DSL_PROVENANCE,\n };\n annotations.push(a);\n }\n\n return annotations;\n}\n\n/**\n * Converts an array of form elements into ObjectProperty nodes.\n * Used for ObjectField properties and ArrayField items.\n *\n * Only field elements produce properties; groups and conditionals within\n * an object/array context are recursively flattened to extract their fields.\n *\n * Fields inside conditional branches are always marked `optional: true`\n * because their presence in the data depends on the condition being met.\n * This matches the DSL's type inference behavior where conditional fields\n * produce optional properties in `InferFormSchema`.\n *\n * @param elements - The form elements to convert\n * @param insideConditional - Whether these elements are inside a conditional branch\n */\nfunction buildObjectProperties(\n elements: readonly FormElement[],\n insideConditional = false\n): ObjectProperty[] {\n const properties: ObjectProperty[] = [];\n\n for (const el of elements) {\n if (isField(el)) {\n const fieldNode = canonicalizeField(el);\n properties.push({\n name: fieldNode.name,\n type: fieldNode.type,\n // Fields inside a conditional branch are always optional in the\n // data schema, regardless of their `required` flag — the condition\n // may not be met, so the field may be absent.\n optional: insideConditional || !fieldNode.required,\n constraints: fieldNode.constraints,\n annotations: fieldNode.annotations,\n provenance: CHAIN_DSL_PROVENANCE,\n });\n } else if (isGroup(el)) {\n // Groups inside object/array items contribute their fields by flattening.\n // Groups do not affect optionality — pass through the current state.\n properties.push(...buildObjectProperties(el.elements, insideConditional));\n } else if (isConditional(el)) {\n // Conditionals inside object/array items contribute their fields by\n // flattening, but all fields inside are forced optional.\n properties.push(...buildObjectProperties(el.elements, true));\n }\n }\n\n return properties;\n}\n","/**\n * TSDoc canonicalizer — assembles an {@link IRClassAnalysis} into a canonical\n * {@link FormIR}, applying layout metadata from `@Group` and `@ShowWhen`\n * TSDoc tags.\n *\n * The analysis functions in `class-analyzer.ts` produce `FieldNode[]`,\n * `fieldLayouts`, and `typeRegistry` directly. This canonicalizer uses\n * the layout metadata to wrap fields in `GroupLayoutNode` and\n * `ConditionalLayoutNode` elements.\n */\n\nimport type {\n FormIR,\n FormIRElement,\n FieldNode,\n GroupLayoutNode,\n ConditionalLayoutNode,\n Provenance,\n} from \"@formspec/core/internals\";\nimport { IR_VERSION } from \"@formspec/core/internals\";\nimport type { IRClassAnalysis, FieldLayoutMetadata } from \"../analyzer/class-analyzer.js\";\n\n/**\n * Source-level metadata for provenance tracking.\n */\nexport interface TSDocSource {\n /** Absolute path to the source file. */\n readonly file: string;\n}\n\n/**\n * Wraps an {@link IRClassAnalysis} (from `analyzeClassToIR`,\n * `analyzeInterfaceToIR`, or `analyzeTypeAliasToIR`) into a canonical\n * {@link FormIR}.\n *\n * Fields with `@Group` TSDoc tags are grouped into `GroupLayoutNode` elements.\n * Fields with `@ShowWhen` TSDoc tags are wrapped in `ConditionalLayoutNode` elements.\n * When both are present, the conditional wraps the field inside the group.\n *\n * @param analysis - IR analysis result (fields are already FieldNode[])\n * @param source - Optional source file metadata for provenance\n * @returns The canonical FormIR\n */\nexport function canonicalizeTSDoc(analysis: IRClassAnalysis, source?: TSDocSource): FormIR {\n const file = source?.file ?? \"\";\n\n const provenance: Provenance = {\n surface: \"tsdoc\",\n file,\n line: 1,\n column: 0,\n };\n\n const elements = assembleElements(analysis.fields, analysis.fieldLayouts, provenance);\n\n return {\n kind: \"form-ir\",\n irVersion: IR_VERSION,\n elements,\n typeRegistry: analysis.typeRegistry,\n ...(analysis.annotations !== undefined &&\n analysis.annotations.length > 0 && { rootAnnotations: analysis.annotations }),\n ...(analysis.annotations !== undefined &&\n analysis.annotations.length > 0 && { annotations: analysis.annotations }),\n provenance,\n };\n}\n\n/**\n * Assembles flat fields and their layout metadata into a tree of\n * `FormIRElement[]` with groups and conditionals.\n *\n * Fields are processed in order. Consecutive fields with the same\n * `@Group` label are collected into a single `GroupLayoutNode`.\n * Fields with `@ShowWhen` are wrapped in `ConditionalLayoutNode`.\n */\nfunction assembleElements(\n fields: readonly FieldNode[],\n layouts: readonly FieldLayoutMetadata[],\n provenance: Provenance\n): readonly FormIRElement[] {\n const elements: FormIRElement[] = [];\n\n // Group consecutive fields with the same group label together.\n // We use an ordered map to preserve insertion order of groups.\n const groupMap = new Map<string, FormIRElement[]>();\n const topLevelOrder: (\n | { type: \"group\"; label: string }\n | { type: \"element\"; element: FormIRElement }\n )[] = [];\n\n for (let i = 0; i < fields.length; i++) {\n const field = fields[i];\n const layout = layouts[i];\n if (!field || !layout) continue;\n\n // Wrap in conditional if @ShowWhen is present\n const element = wrapInConditional(field, layout, provenance);\n\n if (layout.groupLabel !== undefined) {\n const label = layout.groupLabel;\n let groupElements = groupMap.get(label);\n if (!groupElements) {\n groupElements = [];\n groupMap.set(label, groupElements);\n topLevelOrder.push({ type: \"group\", label });\n }\n groupElements.push(element);\n } else {\n topLevelOrder.push({ type: \"element\", element });\n }\n }\n\n // Assemble the final element array in order\n for (const entry of topLevelOrder) {\n if (entry.type === \"group\") {\n const groupElements = groupMap.get(entry.label);\n if (groupElements) {\n const groupNode: GroupLayoutNode = {\n kind: \"group\",\n label: entry.label,\n elements: groupElements,\n provenance,\n };\n elements.push(groupNode);\n // Clear so duplicate group labels in topLevelOrder don't re-emit\n groupMap.delete(entry.label);\n }\n } else {\n elements.push(entry.element);\n }\n }\n\n return elements;\n}\n\n/**\n * Wraps a field in a `ConditionalLayoutNode` if the layout has `showWhen` metadata.\n */\nfunction wrapInConditional(\n field: FieldNode,\n layout: FieldLayoutMetadata,\n provenance: Provenance\n): FormIRElement {\n if (layout.showWhen === undefined) {\n return field;\n }\n\n const conditional: ConditionalLayoutNode = {\n kind: \"conditional\",\n fieldName: layout.showWhen.field,\n value: layout.showWhen.value,\n elements: [field],\n provenance,\n };\n\n return conditional;\n}\n","/**\n * JSON Schema 2020-12 generator that consumes the canonical FormIR.\n *\n * This generator is a pure function of the IR. It never consults the TypeScript\n * AST or surface syntax directly — only the IR (per the JSON Schema vocabulary spec §1.2).\n *\n * @see https://json-schema.org/draft/2020-12/schema\n * @see https://json-schema.org/draft/2020-12/schema\n */\n\nimport type {\n FormIR,\n FormIRElement,\n FieldNode,\n TypeNode,\n PrimitiveTypeNode,\n EnumTypeNode,\n ArrayTypeNode,\n ObjectTypeNode,\n RecordTypeNode,\n UnionTypeNode,\n ReferenceTypeNode,\n DynamicTypeNode,\n CustomTypeNode,\n ConstraintNode,\n AnnotationNode,\n ObjectProperty,\n} from \"@formspec/core/internals\";\nimport type { ExtensionRegistry } from \"../extensions/index.js\";\n\n// =============================================================================\n// OUTPUT TYPE\n// =============================================================================\n\n/**\n * A JSON Schema 2020-12 document, sub-schema, or keyword collection.\n *\n * This interface covers the subset of JSON Schema 2020-12 that this generator\n * emits, plus an index signature for custom `x-formspec-*` extension keywords.\n *\n * @public\n */\nexport interface JsonSchema2020 {\n /** Declared JSON Schema dialect URI for the document root. */\n $schema?: string;\n /** Reference to another schema location. */\n $ref?: string;\n /** Named reusable schema definitions keyed by definition name. */\n $defs?: Record<string, JsonSchema2020>;\n /** JSON Schema type keyword for the current node. */\n type?: string;\n /** Object properties keyed by property name. */\n properties?: Record<string, JsonSchema2020>;\n /** Property names that must be present on object values. */\n required?: string[];\n /** Item schema applied to array elements. */\n items?: JsonSchema2020;\n /** Whether, or how, additional object properties are allowed. */\n additionalProperties?: boolean | JsonSchema2020;\n /** Closed set of allowed scalar values. */\n enum?: readonly (string | number)[];\n /** Literal value the instance must equal. */\n const?: unknown;\n /** Schemas that must all validate successfully. */\n allOf?: readonly JsonSchema2020[];\n /** Schemas of which exactly one should validate successfully. */\n oneOf?: readonly JsonSchema2020[];\n /** Schemas of which at least one may validate successfully. */\n anyOf?: readonly JsonSchema2020[];\n // Constraints\n /** Inclusive numeric lower bound. */\n minimum?: number;\n /** Inclusive numeric upper bound. */\n maximum?: number;\n /** Exclusive numeric lower bound. */\n exclusiveMinimum?: number;\n /** Exclusive numeric upper bound. */\n exclusiveMaximum?: number;\n /** Required numeric step interval. */\n multipleOf?: number;\n /** Inclusive minimum string length. */\n minLength?: number;\n /** Inclusive maximum string length. */\n maxLength?: number;\n /** Inclusive minimum array length. */\n minItems?: number;\n /** Inclusive maximum array length. */\n maxItems?: number;\n /** Regular expression pattern applied to string values. */\n pattern?: string;\n /** Whether array elements must be unique. */\n uniqueItems?: boolean;\n /** Format hint for downstream validators and tooling. */\n format?: string;\n // Annotations\n /** Human-readable title for the schema node. */\n title?: string;\n /** Human-readable description for the schema node. */\n description?: string;\n /** Default value suggested for the schema node. */\n default?: unknown;\n /** Whether the schema node is deprecated. */\n deprecated?: boolean;\n // Extensions (open for vendor-prefixed keywords, e.g., x-formspec-*, x-stripe-*)\n // The vendor prefix is configurable (white-labelable).\n /** Additional vendor-prefixed extension keywords. */\n [key: `x-${string}`]: unknown;\n}\n\n// =============================================================================\n// CONTEXT\n// =============================================================================\n\n/**\n * Mutable accumulator passed through the generation traversal.\n *\n * Using a context object rather than return-value threading keeps the\n * recursive generators simple and avoids repeated object spreading.\n */\ninterface GeneratorContext {\n /** Named type schemas collected during traversal, keyed by reference name. */\n readonly defs: Record<string, JsonSchema2020>;\n /** Optional extension registry for resolving custom IR nodes. */\n readonly extensionRegistry: ExtensionRegistry | undefined;\n /** Vendor prefix passed through to extension toJsonSchema handlers. */\n readonly vendorPrefix: string;\n}\n\n/**\n * Options for generating JSON Schema from a canonical FormIR.\n *\n * @internal\n */\nexport interface GenerateJsonSchemaFromIROptions {\n /**\n * Registry used to resolve custom types, constraints, and annotations.\n *\n * JSON Schema generation throws when custom IR nodes are present without a\n * matching registration in this registry.\n */\n readonly extensionRegistry?: ExtensionRegistry | undefined;\n /**\n * Vendor prefix passed to extension `toJsonSchema` hooks.\n * @defaultValue \"x-formspec\"\n */\n readonly vendorPrefix?: string | undefined;\n}\n\nfunction makeContext(options?: GenerateJsonSchemaFromIROptions): GeneratorContext {\n const vendorPrefix = options?.vendorPrefix ?? \"x-formspec\";\n if (!vendorPrefix.startsWith(\"x-\")) {\n throw new Error(\n `Invalid vendorPrefix \"${vendorPrefix}\". Extension JSON Schema keywords must start with \"x-\".`\n );\n }\n\n return {\n defs: {},\n extensionRegistry: options?.extensionRegistry,\n vendorPrefix,\n };\n}\n\n// =============================================================================\n// PUBLIC API\n// =============================================================================\n\n/**\n * Generates a JSON Schema 2020-12 object from a canonical FormIR.\n *\n * Groups and conditionals are flattened — they influence UI layout but do not\n * affect the data schema. All fields appear at the level they would occupy in\n * the output data.\n *\n * Named types in the `typeRegistry` are emitted as `$defs` entries and\n * referenced via `$ref` (per PP7 — high-fidelity output).\n *\n * @example\n * ```typescript\n * import { canonicalizeDSL } from \"./canonicalize/index.js\";\n * import { generateJsonSchemaFromIR } from \"./json-schema/ir-generator.js\";\n * import { formspec, field } from \"@formspec/dsl\";\n *\n * const form = formspec(\n * field.text(\"name\", { label: \"Name\", required: true }),\n * field.number(\"age\", { min: 0 }),\n * );\n * const ir = canonicalizeDSL(form);\n * const schema = generateJsonSchemaFromIR(ir);\n * // {\n * // $schema: \"https://json-schema.org/draft/2020-12/schema\",\n * // type: \"object\",\n * // properties: {\n * // name: { type: \"string\", title: \"Name\" },\n * // age: { type: \"number\", minimum: 0 }\n * // },\n * // required: [\"name\"]\n * // }\n * ```\n *\n * Advanced API — most consumers should use `generateJsonSchema()` or\n * `buildFormSchemas()`, which canonicalize form definitions automatically.\n * Callers of this function are responsible for providing pre-canonicalized IR.\n *\n * @param ir - The canonical FormIR produced by a canonicalizer\n * @returns A plain JSON-serializable JSON Schema 2020-12 object\n *\n * @internal\n */\nexport function generateJsonSchemaFromIR(\n ir: FormIR,\n options?: GenerateJsonSchemaFromIROptions\n): JsonSchema2020 {\n const ctx = makeContext(options);\n\n // Seed $defs from the type registry so referenced types are available even if\n // the field tree traversal never visits them (e.g., unreferenced types added\n // by a TSDoc canonicalizer pass).\n for (const [name, typeDef] of Object.entries(ir.typeRegistry)) {\n ctx.defs[name] = generateTypeNode(typeDef.type, ctx);\n if (typeDef.constraints && typeDef.constraints.length > 0) {\n applyConstraints(ctx.defs[name], typeDef.constraints, ctx);\n }\n if (typeDef.annotations && typeDef.annotations.length > 0) {\n applyAnnotations(ctx.defs[name], typeDef.annotations, ctx);\n }\n }\n\n const properties: Record<string, JsonSchema2020> = {};\n const required: string[] = [];\n\n collectFields(ir.elements, properties, required, ctx);\n\n // Deduplicate required (same field can appear across conditional branches).\n const uniqueRequired = [...new Set(required)];\n\n const result: JsonSchema2020 = {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n type: \"object\",\n properties,\n ...(uniqueRequired.length > 0 && { required: uniqueRequired }),\n };\n\n if (ir.annotations && ir.annotations.length > 0) {\n applyAnnotations(result, ir.annotations, ctx);\n }\n\n if (Object.keys(ctx.defs).length > 0) {\n result.$defs = ctx.defs;\n }\n\n return result;\n}\n\n// =============================================================================\n// ELEMENT TRAVERSAL\n// =============================================================================\n\n/**\n * Recursively visits all IR elements, collecting field schemas and required names.\n *\n * Groups and conditionals are transparent to the schema — their children are\n * lifted to the enclosing level (per the JSON Schema vocabulary spec §1.2).\n */\nfunction collectFields(\n elements: readonly FormIRElement[],\n properties: Record<string, JsonSchema2020>,\n required: string[],\n ctx: GeneratorContext\n): void {\n for (const element of elements) {\n switch (element.kind) {\n case \"field\":\n properties[element.name] = generateFieldSchema(element, ctx);\n if (element.required) {\n required.push(element.name);\n }\n break;\n\n case \"group\":\n // Groups are UI-only; flatten children into the enclosing schema.\n collectFields(element.elements, properties, required, ctx);\n break;\n\n case \"conditional\":\n // Conditional visibility is UI-only; all fields remain in the schema.\n collectFields(element.elements, properties, required, ctx);\n break;\n\n default: {\n const _exhaustive: never = element;\n void _exhaustive;\n }\n }\n }\n}\n\n// =============================================================================\n// FIELD SCHEMA GENERATION\n// =============================================================================\n\n/**\n * Generates the JSON Schema sub-schema for a single FieldNode.\n */\nfunction generateFieldSchema(field: FieldNode, ctx: GeneratorContext): JsonSchema2020 {\n const schema = generateTypeNode(field.type, ctx);\n const itemStringSchema =\n schema.type === \"array\" && schema.items?.type === \"string\" ? schema.items : undefined;\n\n // Partition constraints into direct (no path) and path-targeted.\n const directConstraints: ConstraintNode[] = [];\n const itemConstraints: ConstraintNode[] = [];\n const pathConstraints: ConstraintNode[] = [];\n for (const c of field.constraints) {\n if (c.path) {\n pathConstraints.push(c);\n } else if (itemStringSchema !== undefined && isStringItemConstraint(c)) {\n itemConstraints.push(c);\n } else {\n directConstraints.push(c);\n }\n }\n\n // Apply direct constraints. multipleOf:1 on a number type is a special case:\n // it promotes the type to \"integer\" and removes the multipleOf keyword.\n applyConstraints(schema, directConstraints, ctx);\n\n if (itemStringSchema !== undefined) {\n applyConstraints(itemStringSchema, itemConstraints, ctx);\n }\n\n // Apply annotations (title, description, default, deprecated, etc.).\n const rootAnnotations: AnnotationNode[] = [];\n const itemAnnotations: AnnotationNode[] = [];\n for (const annotation of field.annotations) {\n if (itemStringSchema !== undefined && annotation.annotationKind === \"format\") {\n itemAnnotations.push(annotation);\n } else {\n rootAnnotations.push(annotation);\n }\n }\n\n applyAnnotations(schema, rootAnnotations, ctx);\n if (itemStringSchema !== undefined) {\n applyAnnotations(itemStringSchema, itemAnnotations, ctx);\n }\n\n // If no path-targeted constraints, return as-is.\n if (pathConstraints.length === 0) {\n return schema;\n }\n\n return applyPathTargetedConstraints(schema, pathConstraints, ctx);\n}\n\n/**\n * Returns true if a constraint should be applied to the `items` schema of a\n * primitive `string[]` rather than the array itself.\n *\n * `@const` is intentionally excluded: arrays cannot carry primitive const\n * constraints in FormSpec, so `@const` on `string[]` remains a validation\n * error instead of targeting the item schema.\n */\nfunction isStringItemConstraint(constraint: ConstraintNode): boolean {\n switch (constraint.constraintKind) {\n case \"minLength\":\n case \"maxLength\":\n case \"pattern\":\n return true;\n default:\n return false;\n }\n}\n\n/**\n * Applies path-targeted constraints to a schema via allOf composition.\n *\n * For $ref schemas: wraps in allOf with property overrides.\n * For inline object schemas: applies directly to nested properties.\n * For array schemas: applies path constraints to the items sub-schema.\n */\nfunction applyPathTargetedConstraints(\n schema: JsonSchema2020,\n pathConstraints: readonly ConstraintNode[],\n ctx: GeneratorContext\n): JsonSchema2020 {\n // Array transparency: path-targeted constraints target the item type.\n if (schema.type === \"array\" && schema.items) {\n schema.items = applyPathTargetedConstraints(schema.items, pathConstraints, ctx);\n return schema;\n }\n\n // Group path constraints by target field name (first path segment).\n // Callers guarantee all entries have a defined `path` (filtered upstream).\n const byTarget = new Map<string, ConstraintNode[]>();\n for (const c of pathConstraints) {\n const target = c.path?.segments[0];\n if (!target) continue;\n const group = byTarget.get(target) ?? [];\n group.push(c);\n byTarget.set(target, group);\n }\n\n // Build the property overrides object.\n const propertyOverrides: Record<string, JsonSchema2020> = {};\n for (const [target, constraints] of byTarget) {\n const subSchema: JsonSchema2020 = {};\n applyConstraints(subSchema, constraints, ctx);\n propertyOverrides[target] = subSchema;\n }\n\n // $ref schema: wrap in allOf to preserve $ref semantics while adding overrides.\n if (schema.$ref) {\n const { $ref, ...rest } = schema;\n const refPart: JsonSchema2020 = { $ref };\n const overridePart: JsonSchema2020 = {\n properties: propertyOverrides,\n ...rest,\n };\n return { allOf: [refPart, overridePart] };\n }\n\n // Inline object schema: merge property overrides directly where possible.\n if (schema.type === \"object\" && schema.properties) {\n const missingOverrides: Record<string, JsonSchema2020> = {};\n\n for (const [target, overrideSchema] of Object.entries(propertyOverrides)) {\n if (schema.properties[target]) {\n Object.assign(schema.properties[target], overrideSchema);\n } else {\n // Do not introduce new properties directly; compose via allOf instead\n // to preserve additionalProperties semantics on the base object.\n missingOverrides[target] = overrideSchema;\n }\n }\n\n if (Object.keys(missingOverrides).length === 0) {\n return schema;\n }\n\n return {\n allOf: [schema, { properties: missingOverrides }],\n };\n }\n\n // allOf schema (already composed): add property overrides as another member.\n if (schema.allOf) {\n schema.allOf = [...schema.allOf, { properties: propertyOverrides }];\n return schema;\n }\n\n // Fallback: for non-object/non-$ref schemas, path-targeted constraints do not\n // apply in a meaningful way. Return the original schema unchanged and rely\n // on validation diagnostics to surface misuse of path-based constraints.\n return schema;\n}\n\n// =============================================================================\n// TYPE NODE GENERATION\n// =============================================================================\n\n/**\n * Converts a TypeNode to a JSON Schema sub-schema.\n *\n * This function is intentionally exhaustive — all TypeNode variants are handled.\n * TypeScript's exhaustiveness check via the default branch ensures new variants\n * added to the IR are caught at compile time.\n */\nfunction generateTypeNode(type: TypeNode, ctx: GeneratorContext): JsonSchema2020 {\n switch (type.kind) {\n case \"primitive\":\n return generatePrimitiveType(type);\n\n case \"enum\":\n return generateEnumType(type);\n\n case \"array\":\n return generateArrayType(type, ctx);\n\n case \"object\":\n return generateObjectType(type, ctx);\n\n case \"record\":\n return generateRecordType(type, ctx);\n\n case \"union\":\n return generateUnionType(type, ctx);\n\n case \"reference\":\n return generateReferenceType(type);\n\n case \"dynamic\":\n return generateDynamicType(type);\n\n case \"custom\":\n return generateCustomType(type, ctx);\n\n default: {\n // TypeScript exhaustiveness guard.\n const _exhaustive: never = type;\n return _exhaustive;\n }\n }\n}\n\n/**\n * Maps primitive IR types to JSON Schema type keywords.\n *\n * Note: `integer` is NOT a primitive kind in the IR. Integer semantics are\n * expressed via a `multipleOf: 1` constraint on a number type; `applyConstraints`\n * handles the promotion (per the JSON Schema vocabulary spec §2.1).\n */\nfunction generatePrimitiveType(type: PrimitiveTypeNode): JsonSchema2020 {\n return {\n type:\n type.primitiveKind === \"integer\" || type.primitiveKind === \"bigint\"\n ? \"integer\"\n : type.primitiveKind,\n };\n}\n\n/**\n * Generates JSON Schema for a static enum type.\n *\n * When any member has a displayName, the output uses the `oneOf` form with\n * per-member `const`/`title` entries (per the JSON Schema vocabulary spec §2.3). Otherwise the\n * flat `enum` keyword is used (simpler, equally valid).\n */\nfunction generateEnumType(type: EnumTypeNode): JsonSchema2020 {\n const hasDisplayNames = type.members.some((m) => m.displayName !== undefined);\n\n if (hasDisplayNames) {\n return {\n oneOf: type.members.map((m) => {\n const entry: JsonSchema2020 = { const: m.value };\n if (m.displayName !== undefined) {\n entry.title = m.displayName;\n }\n return entry;\n }),\n };\n }\n\n return { enum: type.members.map((m) => m.value) };\n}\n\n/**\n * Generates JSON Schema for an array type.\n * Per 2020-12, `items` is a single schema (not an array); tuple types use\n * `prefixItems` + `items: false`.\n */\nfunction generateArrayType(type: ArrayTypeNode, ctx: GeneratorContext): JsonSchema2020 {\n return {\n type: \"array\",\n items: generateTypeNode(type.items, ctx),\n };\n}\n\n/**\n * Generates JSON Schema for an object type.\n *\n * `additionalProperties` is emitted only when the IR explicitly closes the\n * object. Ordinary static object types now canonicalize to\n * `additionalProperties: true`, which omits the keyword per spec 003 §2.5.\n */\nfunction generateObjectType(type: ObjectTypeNode, ctx: GeneratorContext): JsonSchema2020 {\n const properties: Record<string, JsonSchema2020> = {};\n const required: string[] = [];\n\n for (const prop of type.properties) {\n properties[prop.name] = generatePropertySchema(prop, ctx);\n if (!prop.optional) {\n required.push(prop.name);\n }\n }\n\n const schema: JsonSchema2020 = { type: \"object\", properties };\n\n if (required.length > 0) {\n schema.required = required;\n }\n\n if (!type.additionalProperties) {\n schema.additionalProperties = false;\n }\n\n return schema;\n}\n\n/**\n * Generates JSON Schema for a record (dictionary) type per spec 003 §2.5.\n *\n * `Record<string, T>` and `{ [k: string]: T }` both emit:\n * `{ \"type\": \"object\", \"additionalProperties\": <T schema> }`\n *\n * No `properties` key is emitted — the record has no named properties.\n */\nfunction generateRecordType(type: RecordTypeNode, ctx: GeneratorContext): JsonSchema2020 {\n return {\n type: \"object\",\n additionalProperties: generateTypeNode(type.valueType, ctx),\n };\n}\n\n/**\n * Generates a schema for an ObjectProperty, applying its use-site constraints\n * and annotations (per the JSON Schema vocabulary spec §5.4 — inline allOf at use site).\n */\nfunction generatePropertySchema(prop: ObjectProperty, ctx: GeneratorContext): JsonSchema2020 {\n const schema = generateTypeNode(prop.type, ctx);\n applyConstraints(schema, prop.constraints, ctx);\n applyAnnotations(schema, prop.annotations, ctx);\n return schema;\n}\n\n/**\n * Generates JSON Schema for a union type.\n *\n * Union handling strategy (per spec 003):\n * - Boolean shorthand: `true | false` → `{ type: \"boolean\" }` (not oneOf/anyOf)\n * - Nullable unions: `T | null` → `{ \"oneOf\": [<T schema>, { \"type\": \"null\" }] }` (§2.3)\n * - All other unions → `anyOf` (members may overlap; discriminated union\n * detection is deferred to a future phase per design doc 003 §7.4)\n */\nfunction generateUnionType(type: UnionTypeNode, ctx: GeneratorContext): JsonSchema2020 {\n // Boolean shorthand: union of true-literal and false-literal → type: \"boolean\"\n if (isBooleanUnion(type)) {\n return { type: \"boolean\" };\n }\n\n // Nullable union: `T | null` → oneOf per spec 003 §2.3.\n // A nullable union is any union where exactly one member is the null primitive.\n if (isNullableUnion(type)) {\n return {\n oneOf: type.members.map((m) => generateTypeNode(m, ctx)),\n };\n }\n\n // Default: anyOf for non-discriminated object unions (spec 003 §7.4).\n // Discriminated union detection (shared required property with distinct consts)\n // is deferred to a future phase.\n return {\n anyOf: type.members.map((m) => generateTypeNode(m, ctx)),\n };\n}\n\n/**\n * Returns true if the union is `true | false` (boolean shorthand).\n */\nfunction isBooleanUnion(type: UnionTypeNode): boolean {\n if (type.members.length !== 2) return false;\n const kinds = type.members.map((m) => m.kind);\n // Both must be primitives; check if both are \"boolean\" primitives.\n // The IR currently does not have a boolean literal node, so boolean union\n // is represented as two primitive boolean members.\n return (\n kinds.every((k) => k === \"primitive\") &&\n type.members.every((m) => m.kind === \"primitive\" && m.primitiveKind === \"boolean\")\n );\n}\n\n/**\n * Returns true if the union is a nullable wrapper union (`T | null` for any T).\n *\n * A nullable union is a two-member union where exactly one member is the `null`\n * primitive type and the other member is any non-null type.\n * Per spec 003 §2.3, nullable unions map to `oneOf` (not `anyOf`).\n */\nfunction isNullableUnion(type: UnionTypeNode): boolean {\n if (type.members.length !== 2) return false;\n const nullCount = type.members.filter(\n (m) => m.kind === \"primitive\" && m.primitiveKind === \"null\"\n ).length;\n return nullCount === 1;\n}\n\n/**\n * Generates JSON Schema for a reference type.\n *\n * The referenced type's schema is stored in `$defs` (seeded from the type\n * registry before traversal begins). The reference simply emits a `$ref`.\n */\nfunction generateReferenceType(type: ReferenceTypeNode): JsonSchema2020 {\n return { $ref: `#/$defs/${type.name}` };\n}\n\n/**\n * Generates JSON Schema for a dynamic type (runtime-resolved enum or schema).\n *\n * Dynamic enums emit `x-formspec-source` and optionally `x-formspec-params`.\n * Dynamic schemas emit `x-formspec-schemaSource` with `additionalProperties: true`\n * since the actual schema is determined at runtime (per the JSON Schema vocabulary spec §3.2).\n */\nfunction generateDynamicType(type: DynamicTypeNode): JsonSchema2020 {\n if (type.dynamicKind === \"enum\") {\n const schema: JsonSchema2020 = {\n type: \"string\",\n \"x-formspec-source\": type.sourceKey,\n };\n if (type.parameterFields.length > 0) {\n schema[\"x-formspec-params\"] = [...type.parameterFields];\n }\n return schema;\n }\n\n // dynamicKind === \"schema\"\n return {\n type: \"object\",\n additionalProperties: true,\n \"x-formspec-schemaSource\": type.sourceKey,\n };\n}\n\n// =============================================================================\n// CONSTRAINT APPLICATION\n// =============================================================================\n\n/**\n * Applies constraint nodes onto an existing JSON Schema object (mutates in place).\n *\n * All callers pass freshly-created objects so there is no aliasing risk.\n *\n * Special rule (per the JSON Schema vocabulary spec §2.1): `multipleOf: 1` on a `\"number\"` type\n * promotes to `\"integer\"` and suppresses the `multipleOf` keyword (integer is a\n * subtype of number; expressing it via multipleOf:1 is redundant).\n *\n * Path-targeted constraints are handled separately by `applyPathTargetedConstraints`.\n */\nfunction applyConstraints(\n schema: JsonSchema2020,\n constraints: readonly ConstraintNode[],\n ctx: GeneratorContext\n): void {\n for (const constraint of constraints) {\n switch (constraint.constraintKind) {\n case \"minimum\":\n schema.minimum = constraint.value;\n break;\n\n case \"maximum\":\n schema.maximum = constraint.value;\n break;\n\n case \"exclusiveMinimum\":\n schema.exclusiveMinimum = constraint.value;\n break;\n\n case \"exclusiveMaximum\":\n schema.exclusiveMaximum = constraint.value;\n break;\n\n case \"multipleOf\": {\n const { value } = constraint;\n if (value === 1 && schema.type === \"number\") {\n // Promote number → integer; omit the multipleOf keyword (redundant).\n schema.type = \"integer\";\n } else {\n schema.multipleOf = value;\n }\n break;\n }\n\n case \"minLength\":\n schema.minLength = constraint.value;\n break;\n\n case \"maxLength\":\n schema.maxLength = constraint.value;\n break;\n\n case \"minItems\":\n schema.minItems = constraint.value;\n break;\n\n case \"maxItems\":\n schema.maxItems = constraint.value;\n break;\n\n case \"pattern\":\n schema.pattern = constraint.pattern;\n break;\n\n case \"uniqueItems\":\n schema.uniqueItems = constraint.value;\n break;\n\n case \"const\":\n schema.const = constraint.value;\n break;\n\n case \"allowedMembers\":\n // EnumMemberConstraintNode — not yet emitted to JSON Schema (Phase 6 validation).\n break;\n\n case \"custom\":\n applyCustomConstraint(schema, constraint, ctx);\n break;\n\n default: {\n // TypeScript exhaustiveness guard.\n const _exhaustive: never = constraint;\n void _exhaustive;\n }\n }\n }\n}\n\n// =============================================================================\n// ANNOTATION APPLICATION\n// =============================================================================\n\n/**\n * Applies annotation nodes onto an existing JSON Schema object (mutates in place).\n *\n * Mapping per the JSON Schema vocabulary spec §2.8:\n * - `displayName` → `title`\n * - `description` → `description` (from summary text, spec 002 §2.3)\n * - `remarks` → `x-<vendor>-remarks` (from @remarks, spec 003 §3.2)\n * - `defaultValue` → `default`\n * - `deprecated` → `deprecated: true` (2020-12 standard annotation)\n * - `format` → `format`\n *\n * UI-only annotations (`placeholder`, `formatHint`) are silently ignored here —\n * they belong in the UI Schema, not the data schema.\n */\nfunction applyAnnotations(\n schema: JsonSchema2020,\n annotations: readonly AnnotationNode[],\n ctx: GeneratorContext\n): void {\n for (const annotation of annotations) {\n switch (annotation.annotationKind) {\n case \"displayName\":\n schema.title = annotation.value;\n break;\n\n case \"description\":\n schema.description = annotation.value;\n break;\n\n case \"remarks\":\n schema[`${ctx.vendorPrefix}-remarks` as `x-${string}`] = annotation.value;\n break;\n\n case \"defaultValue\":\n schema.default = annotation.value;\n break;\n\n case \"format\":\n schema.format = annotation.value;\n break;\n\n case \"deprecated\":\n schema.deprecated = true;\n if (annotation.message !== undefined && annotation.message !== \"\") {\n schema[`${ctx.vendorPrefix}-deprecation-description` as `x-${string}`] =\n annotation.message;\n }\n break;\n\n case \"placeholder\":\n // UI-only — belongs in UI Schema, not emitted here.\n break;\n\n case \"formatHint\":\n // UI-only — belongs in UI Schema, not emitted here.\n break;\n\n case \"custom\":\n applyCustomAnnotation(schema, annotation, ctx);\n break;\n\n default: {\n // TypeScript exhaustiveness guard.\n const _exhaustive: never = annotation;\n void _exhaustive;\n }\n }\n }\n}\n\nfunction generateCustomType(type: CustomTypeNode, ctx: GeneratorContext): JsonSchema2020 {\n const registration = ctx.extensionRegistry?.findType(type.typeId);\n if (registration === undefined) {\n throw new Error(\n `Cannot generate JSON Schema for custom type \"${type.typeId}\" without a matching extension registration`\n );\n }\n\n // Trust boundary: extensions are responsible for returning valid JSON Schema.\n // Core only depends on Record<string, unknown> here, so we cast at the edge.\n return registration.toJsonSchema(type.payload, ctx.vendorPrefix) as JsonSchema2020;\n}\n\nfunction applyCustomConstraint(\n schema: JsonSchema2020,\n constraint: Extract<ConstraintNode, { constraintKind: \"custom\" }>,\n ctx: GeneratorContext\n): void {\n const registration = ctx.extensionRegistry?.findConstraint(constraint.constraintId);\n if (registration === undefined) {\n throw new Error(\n `Cannot generate JSON Schema for custom constraint \"${constraint.constraintId}\" without a matching extension registration`\n );\n }\n\n assignVendorPrefixedExtensionKeywords(\n schema,\n registration.toJsonSchema(constraint.payload, ctx.vendorPrefix),\n ctx.vendorPrefix,\n `custom constraint \"${constraint.constraintId}\"`\n );\n}\n\nfunction applyCustomAnnotation(\n schema: JsonSchema2020,\n annotation: Extract<AnnotationNode, { annotationKind: \"custom\" }>,\n ctx: GeneratorContext\n): void {\n const registration = ctx.extensionRegistry?.findAnnotation(annotation.annotationId);\n if (registration === undefined) {\n throw new Error(\n `Cannot generate JSON Schema for custom annotation \"${annotation.annotationId}\" without a matching extension registration`\n );\n }\n\n if (registration.toJsonSchema === undefined) {\n return;\n }\n\n assignVendorPrefixedExtensionKeywords(\n schema,\n registration.toJsonSchema(annotation.value, ctx.vendorPrefix),\n ctx.vendorPrefix,\n `custom annotation \"${annotation.annotationId}\"`\n );\n}\n\nfunction assignVendorPrefixedExtensionKeywords(\n schema: JsonSchema2020,\n extensionSchema: Record<string, unknown>,\n vendorPrefix: string,\n source: string\n): void {\n for (const [key, value] of Object.entries(extensionSchema)) {\n if (!key.startsWith(`${vendorPrefix}-`)) {\n throw new Error(\n `Cannot apply ${source}: extension hooks may only emit \"${vendorPrefix}-*\" JSON Schema keywords`\n );\n }\n schema[key as `x-${string}`] = value;\n }\n}\n","/**\n * JSON Schema generator for FormSpec forms.\n *\n * Routes through the canonical IR pipeline: Chain DSL → FormIR → JSON Schema 2020-12.\n */\n\nimport type { FormElement, FormSpec } from \"@formspec/core\";\nimport { canonicalizeChainDSL } from \"../canonicalize/index.js\";\nimport {\n generateJsonSchemaFromIR,\n type GenerateJsonSchemaFromIROptions,\n type JsonSchema2020,\n} from \"./ir-generator.js\";\n\n/**\n * Options for generating JSON Schema from a Chain DSL form.\n *\n * @public\n */\nexport interface GenerateJsonSchemaOptions {\n /**\n * Vendor prefix for emitted extension keywords.\n * @defaultValue \"x-formspec\"\n */\n readonly vendorPrefix?: string | undefined;\n}\n\n/**\n * Generates a JSON Schema 2020-12 from a FormSpec.\n *\n * All generation routes through the canonical IR. The chain DSL is first\n * canonicalized to a FormIR, then the IR-based generator produces the schema.\n *\n * @example\n * ```typescript\n * const form = formspec(\n * field.text(\"name\", { label: \"Name\", required: true }),\n * field.number(\"age\", { min: 0 }),\n * );\n *\n * const schema = generateJsonSchema(form);\n * // {\n * // $schema: \"https://json-schema.org/draft/2020-12/schema\",\n * // type: \"object\",\n * // properties: {\n * // name: { type: \"string\", title: \"Name\" },\n * // age: { type: \"number\", minimum: 0 }\n * // },\n * // required: [\"name\"]\n * // }\n * ```\n *\n * @param form - The FormSpec to convert\n * @returns A JSON Schema 2020-12 object\n *\n * @public\n */\nexport function generateJsonSchema<E extends readonly FormElement[]>(\n form: FormSpec<E>,\n options?: GenerateJsonSchemaOptions\n): JsonSchema2020 {\n const ir = canonicalizeChainDSL(form);\n const internalOptions: GenerateJsonSchemaFromIROptions | undefined =\n options?.vendorPrefix === undefined ? undefined : { vendorPrefix: options.vendorPrefix };\n return generateJsonSchemaFromIR(ir, internalOptions);\n}\n","/**\n * Zod schemas for JSON Forms UI Schema.\n *\n * These schemas are the source of truth for UI Schema validation.\n * TypeScript types are derived from these schemas via `z.infer<>`.\n *\n * @see https://jsonforms.io/docs/uischema/\n */\n\nimport { z } from \"zod\";\nimport type { UISchema } from \"./types.js\";\n\n// =============================================================================\n// Primitive helpers\n// =============================================================================\n\n/** JSON Pointer string (e.g., \"#/properties/fieldName\") */\nconst jsonPointerSchema = z.string();\n\n// =============================================================================\n// Rule Effect and Element Type enums\n// =============================================================================\n\n/**\n * Zod schema for rule effect values.\n *\n * @internal\n */\nexport const ruleEffectSchema = z.enum([\"SHOW\", \"HIDE\", \"ENABLE\", \"DISABLE\"]);\n\n/**\n * Rule effect types for conditional visibility.\n *\n * @internal\n */\nexport type RuleEffect = z.infer<typeof ruleEffectSchema>;\n\n/**\n * Zod schema for UI Schema element type strings.\n *\n * @internal\n */\nexport const uiSchemaElementTypeSchema = z.enum([\n \"Control\",\n \"VerticalLayout\",\n \"HorizontalLayout\",\n \"Group\",\n \"Categorization\",\n \"Category\",\n \"Label\",\n]);\n\n/**\n * UI Schema element types.\n *\n * @internal\n */\nexport type UISchemaElementType = z.infer<typeof uiSchemaElementTypeSchema>;\n\n// =============================================================================\n// Rule Condition Schema (recursive)\n// =============================================================================\n\n// Forward-declare the recursive TypeScript type.\n// We use an interface here (rather than z.infer<>) because the recursive\n// z.lazy() type annotation requires us to pre-declare the shape.\n/**\n * JSON Schema subset used in rule conditions.\n *\n * @internal\n */\nexport interface RuleConditionSchema {\n const?: unknown;\n enum?: readonly unknown[];\n type?: string;\n not?: RuleConditionSchema;\n minimum?: number;\n maximum?: number;\n exclusiveMinimum?: number;\n exclusiveMaximum?: number;\n minLength?: number;\n properties?: Record<string, RuleConditionSchema>;\n required?: string[];\n allOf?: RuleConditionSchema[];\n}\n\n/**\n * Zod schema for the rule-condition JSON Schema subset.\n *\n * @internal\n */\nexport const ruleConditionSchema: z.ZodType<RuleConditionSchema> = z.lazy(() =>\n z\n .object({\n const: z.unknown().optional(),\n enum: z.array(z.unknown()).readonly().optional(),\n type: z.string().optional(),\n not: ruleConditionSchema.optional(),\n minimum: z.number().optional(),\n maximum: z.number().optional(),\n exclusiveMinimum: z.number().optional(),\n exclusiveMaximum: z.number().optional(),\n minLength: z.number().optional(),\n properties: z.record(z.string(), ruleConditionSchema).optional(),\n required: z.array(z.string()).optional(),\n allOf: z.array(ruleConditionSchema).optional(),\n })\n .strict()\n) as z.ZodType<RuleConditionSchema>;\n\n// =============================================================================\n// Schema-Based Condition and Rule\n// =============================================================================\n\n/**\n * Zod schema for a schema-based rule condition.\n *\n * @internal\n */\nexport const schemaBasedConditionSchema = z\n .object({\n scope: jsonPointerSchema,\n schema: ruleConditionSchema,\n })\n .strict();\n\n/**\n * Condition for a rule.\n *\n * @internal\n */\nexport type SchemaBasedCondition = z.infer<typeof schemaBasedConditionSchema>;\n\n/**\n * Zod schema for a UI Schema rule.\n *\n * @internal\n */\nexport const ruleSchema = z\n .object({\n effect: ruleEffectSchema,\n condition: schemaBasedConditionSchema,\n })\n .strict();\n\n/**\n * Rule for conditional element visibility/enablement.\n *\n * @internal\n */\nexport type Rule = z.infer<typeof ruleSchema>;\n\n// =============================================================================\n// UI Schema Element Schemas (recursive via z.lazy)\n// =============================================================================\n\n// Forward-declare UISchemaElement so layout schemas can reference it.\n// We declare the type up-front and wire the Zod schema below.\n/**\n * Union of all UI Schema element types.\n *\n * @internal\n */\nexport type UISchemaElement =\n | ControlElement\n | VerticalLayout\n | HorizontalLayout\n | GroupLayout\n | Categorization\n | Category\n | LabelElement;\n\n// The Zod schema for UISchemaElement is defined as a const using z.lazy(),\n// which defers evaluation until first use. This allows all element schemas\n// below to be referenced even though they are declared after this line.\n/**\n * Zod schema for any UI Schema element.\n *\n * @internal\n */\nexport const uiSchemaElementSchema: z.ZodType<UISchemaElement> = z.lazy(() =>\n z.union([\n controlSchema,\n verticalLayoutSchema,\n horizontalLayoutSchema,\n groupLayoutSchema,\n categorizationSchema,\n categorySchema,\n labelElementSchema,\n ])\n) as z.ZodType<UISchemaElement>;\n\n// -----------------------------------------------------------------------------\n// Control\n// -----------------------------------------------------------------------------\n\n/**\n * Zod schema for a Control element.\n *\n * @internal\n */\nexport const controlSchema = z\n .object({\n type: z.literal(\"Control\"),\n scope: jsonPointerSchema,\n label: z.union([z.string(), z.literal(false)]).optional(),\n rule: ruleSchema.optional(),\n options: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough();\n\n/**\n * A Control element that binds to a JSON Schema property.\n *\n * @internal\n */\nexport type ControlElement = z.infer<typeof controlSchema>;\n\n// -----------------------------------------------------------------------------\n// VerticalLayout\n// -----------------------------------------------------------------------------\n\n// Pre-declare the interface so the Zod schema can reference UISchemaElement.\n/**\n * A vertical layout element.\n *\n * @internal\n */\nexport interface VerticalLayout {\n type: \"VerticalLayout\";\n elements: UISchemaElement[];\n rule?: Rule | undefined;\n options?: Record<string, unknown> | undefined;\n [k: string]: unknown;\n}\n\n/**\n * Zod schema for a vertical layout element.\n *\n * @internal\n */\nexport const verticalLayoutSchema: z.ZodType<VerticalLayout> = z.lazy(() =>\n z\n .object({\n type: z.literal(\"VerticalLayout\"),\n elements: z.array(uiSchemaElementSchema),\n rule: ruleSchema.optional(),\n options: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough()\n);\n\n// -----------------------------------------------------------------------------\n// HorizontalLayout\n// -----------------------------------------------------------------------------\n\n/**\n * A horizontal layout element.\n *\n * @internal\n */\nexport interface HorizontalLayout {\n type: \"HorizontalLayout\";\n elements: UISchemaElement[];\n rule?: Rule | undefined;\n options?: Record<string, unknown> | undefined;\n [k: string]: unknown;\n}\n\n/**\n * Zod schema for a horizontal layout element.\n *\n * @internal\n */\nexport const horizontalLayoutSchema: z.ZodType<HorizontalLayout> = z.lazy(() =>\n z\n .object({\n type: z.literal(\"HorizontalLayout\"),\n elements: z.array(uiSchemaElementSchema),\n rule: ruleSchema.optional(),\n options: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough()\n);\n\n// -----------------------------------------------------------------------------\n// GroupLayout\n// -----------------------------------------------------------------------------\n\n/**\n * A group element with a label.\n *\n * @internal\n */\nexport interface GroupLayout {\n type: \"Group\";\n label: string;\n elements: UISchemaElement[];\n rule?: Rule | undefined;\n options?: Record<string, unknown> | undefined;\n [k: string]: unknown;\n}\n\n/**\n * Zod schema for a group layout element.\n *\n * @internal\n */\nexport const groupLayoutSchema: z.ZodType<GroupLayout> = z.lazy(() =>\n z\n .object({\n type: z.literal(\"Group\"),\n label: z.string(),\n elements: z.array(uiSchemaElementSchema),\n rule: ruleSchema.optional(),\n options: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough()\n);\n\n// -----------------------------------------------------------------------------\n// Category\n// -----------------------------------------------------------------------------\n\n/**\n * A Category element, used inside a Categorization layout.\n *\n * @internal\n */\nexport interface Category {\n type: \"Category\";\n label: string;\n elements: UISchemaElement[];\n rule?: Rule | undefined;\n options?: Record<string, unknown> | undefined;\n [k: string]: unknown;\n}\n\n/**\n * Zod schema for a category element.\n *\n * @internal\n */\nexport const categorySchema: z.ZodType<Category> = z.lazy(() =>\n z\n .object({\n type: z.literal(\"Category\"),\n label: z.string(),\n elements: z.array(uiSchemaElementSchema),\n rule: ruleSchema.optional(),\n options: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough()\n);\n\n// -----------------------------------------------------------------------------\n// Categorization\n// -----------------------------------------------------------------------------\n\n/**\n * A Categorization element (tab-based layout).\n *\n * @internal\n */\nexport interface Categorization {\n type: \"Categorization\";\n elements: Category[];\n label?: string | undefined;\n rule?: Rule | undefined;\n options?: Record<string, unknown> | undefined;\n [k: string]: unknown;\n}\n\n/**\n * Zod schema for a categorization element.\n *\n * @internal\n */\nexport const categorizationSchema: z.ZodType<Categorization> = z.lazy(() =>\n z\n .object({\n type: z.literal(\"Categorization\"),\n elements: z.array(categorySchema),\n label: z.string().optional(),\n rule: ruleSchema.optional(),\n options: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough()\n);\n\n// -----------------------------------------------------------------------------\n// LabelElement\n// -----------------------------------------------------------------------------\n\n/**\n * Zod schema for a Label element.\n *\n * @internal\n */\nexport const labelElementSchema = z\n .object({\n type: z.literal(\"Label\"),\n text: z.string(),\n rule: ruleSchema.optional(),\n options: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough();\n\n/**\n * A Label element for displaying static text.\n *\n * @internal\n */\nexport type LabelElement = z.infer<typeof labelElementSchema>;\n\n// =============================================================================\n// Root UISchema\n// =============================================================================\n\n/**\n * Zod schema for the root UI Schema (layout types only).\n *\n * @public\n */\nexport const uiSchema: z.ZodType<UISchema> = z.lazy(() =>\n z.union([verticalLayoutSchema, horizontalLayoutSchema, groupLayoutSchema, categorizationSchema])\n) as z.ZodType<UISchema>;\n","/**\n * JSON Forms UI Schema generator that operates on the canonical FormIR.\n *\n * This generator consumes the IR produced by the Canonicalize phase and\n * produces a JSON Forms UI Schema. All downstream UI Schema generation\n * should use this module for UI Schema generation.\n */\n\nimport type { FormIR, FormIRElement, FieldNode, GroupLayoutNode } from \"@formspec/core/internals\";\nimport type {\n UISchema,\n UISchemaElement,\n ControlElement,\n GroupLayout,\n Rule,\n RuleConditionSchema,\n} from \"./types.js\";\nimport { uiSchema as uiSchemaValidator } from \"./schema.js\";\nimport { z } from \"zod\";\n\n// =============================================================================\n// HELPERS\n// =============================================================================\n\n/**\n * Parses a value through a Zod schema, converting validation errors to a\n * descriptive Error.\n */\nfunction parseOrThrow<T>(schema: z.ZodType<T>, value: unknown, label: string): T {\n try {\n return schema.parse(value);\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(\n `Generated ${label} failed validation:\\n${error.issues.map((i) => ` ${i.path.join(\".\")}: ${i.message}`).join(\"\\n\")}`\n );\n }\n throw error;\n }\n}\n\n/**\n * Converts a field name to a JSON Pointer scope string.\n */\nfunction fieldToScope(fieldName: string): string {\n return `#/properties/${fieldName}`;\n}\n\n/**\n * Creates a SHOW rule for a single conditional field/value pair.\n */\nfunction createShowRule(fieldName: string, value: unknown): Rule {\n return {\n effect: \"SHOW\",\n condition: {\n scope: fieldToScope(fieldName),\n schema: { const: value },\n },\n };\n}\n\n/**\n * Combines two SHOW rules into a single rule using an allOf condition.\n *\n * When elements are nested inside multiple conditionals, all parent conditions\n * must be met for the element to be visible. This function flattens both\n * conditions into a single rule using a top-level allOf so JSON Forms evaluates\n * every predicate simultaneously without nesting rule fragments.\n */\nfunction flattenConditionSchema(scope: string, schema: RuleConditionSchema): RuleConditionSchema[] {\n if (schema.allOf === undefined) {\n if (scope === \"#\") {\n return [schema];\n }\n\n const fieldName = scope.replace(\"#/properties/\", \"\");\n return [\n {\n properties: {\n [fieldName]: schema,\n },\n },\n ];\n }\n\n return schema.allOf.flatMap((member) => flattenConditionSchema(scope, member));\n}\n\nfunction combineRules(parentRule: Rule, childRule: Rule): Rule {\n return {\n effect: \"SHOW\",\n condition: {\n scope: \"#\",\n schema: {\n allOf: [\n ...flattenConditionSchema(parentRule.condition.scope, parentRule.condition.schema),\n ...flattenConditionSchema(childRule.condition.scope, childRule.condition.schema),\n ],\n },\n },\n };\n}\n\n// =============================================================================\n// ELEMENT CONVERSION\n// =============================================================================\n\n/**\n * Converts a FieldNode from the IR to a ControlElement.\n *\n * The label is sourced from the first `displayName` annotation on the field,\n * matching how the chain DSL propagates the `label` option through the\n * canonicalization phase.\n */\nfunction fieldNodeToControl(field: FieldNode, parentRule?: Rule): ControlElement {\n const displayNameAnnotation = field.annotations.find((a) => a.annotationKind === \"displayName\");\n const placeholderAnnotation = field.annotations.find((a) => a.annotationKind === \"placeholder\");\n\n const control: ControlElement = {\n type: \"Control\",\n scope: fieldToScope(field.name),\n ...(displayNameAnnotation !== undefined && { label: displayNameAnnotation.value }),\n ...(placeholderAnnotation !== undefined && {\n options: { placeholder: placeholderAnnotation.value },\n }),\n ...(parentRule !== undefined && { rule: parentRule }),\n };\n\n return control;\n}\n\n/**\n * Converts a GroupLayoutNode from the IR to a GroupLayout element.\n *\n * The group's children are recursively converted; the optional parent rule is\n * forwarded to nested elements so that a group inside a conditional inherits\n * the visibility rule.\n */\nfunction groupNodeToLayout(group: GroupLayoutNode, parentRule?: Rule): GroupLayout {\n return {\n type: \"Group\",\n label: group.label,\n elements: irElementsToUiSchema(group.elements, parentRule),\n ...(parentRule !== undefined && { rule: parentRule }),\n };\n}\n\n/**\n * Converts an array of IR elements to UI Schema elements.\n *\n * @param elements - The IR elements to convert\n * @param parentRule - Optional rule inherited from a parent ConditionalLayoutNode\n * @returns Array of UI Schema elements\n */\nfunction irElementsToUiSchema(\n elements: readonly FormIRElement[],\n parentRule?: Rule\n): UISchemaElement[] {\n const result: UISchemaElement[] = [];\n\n for (const element of elements) {\n switch (element.kind) {\n case \"field\": {\n result.push(fieldNodeToControl(element, parentRule));\n break;\n }\n\n case \"group\": {\n result.push(groupNodeToLayout(element, parentRule));\n break;\n }\n\n case \"conditional\": {\n // Build the rule for this conditional level.\n const newRule = createShowRule(element.fieldName, element.value);\n // Combine with the inherited parent rule for nested conditionals.\n const combinedRule = parentRule !== undefined ? combineRules(parentRule, newRule) : newRule;\n // Children are flattened into the parent container with the combined\n // rule attached.\n const childElements = irElementsToUiSchema(element.elements, combinedRule);\n result.push(...childElements);\n break;\n }\n\n default: {\n const _exhaustive: never = element;\n void _exhaustive;\n throw new Error(\"Unhandled IR element kind\");\n }\n }\n }\n\n return result;\n}\n\n// =============================================================================\n// PUBLIC API\n// =============================================================================\n\n/**\n * Generates a JSON Forms UI Schema from a canonical `FormIR`.\n *\n * Mapping rules:\n * - `FieldNode` → `ControlElement` with `scope: \"#/properties/<name>\"`\n * - `displayName` annotation → `label` on the `ControlElement`\n * - `GroupLayoutNode` → `GroupLayout` with recursively converted `elements`\n * - `ConditionalLayoutNode` → children flattened with a `SHOW` rule\n * - Nested conditionals → combined `allOf` rule\n * - Root wrapper is always `{ type: \"VerticalLayout\", elements: [...] }`\n *\n * @example\n * ```typescript\n * const ir = canonicalizeDSL(\n * formspec(\n * group(\"Customer\", field.text(\"name\", { label: \"Name\" })),\n * when(is(\"status\", \"draft\"), field.text(\"notes\", { label: \"Notes\" })),\n * )\n * );\n *\n * const uiSchema = generateUiSchemaFromIR(ir);\n * // {\n * // type: \"VerticalLayout\",\n * // elements: [\n * // {\n * // type: \"Group\",\n * // label: \"Customer\",\n * // elements: [{ type: \"Control\", scope: \"#/properties/name\", label: \"Name\" }]\n * // },\n * // {\n * // type: \"Control\",\n * // scope: \"#/properties/notes\",\n * // label: \"Notes\",\n * // rule: { effect: \"SHOW\", condition: { scope: \"#/properties/status\", schema: { const: \"draft\" } } }\n * // }\n * // ]\n * // }\n * ```\n *\n * @param ir - The canonical FormIR produced by the Canonicalize phase\n * @returns A validated JSON Forms UI Schema\n */\nexport function generateUiSchemaFromIR(ir: FormIR): UISchema {\n const result: UISchema = {\n type: \"VerticalLayout\",\n elements: irElementsToUiSchema(ir.elements),\n };\n\n return parseOrThrow(uiSchemaValidator, result, \"UI Schema\");\n}\n","/**\n * JSON Forms UI Schema generator for FormSpec forms.\n *\n * Routes through the canonical IR pipeline: Chain DSL → FormIR → UI Schema.\n */\n\nimport type { FormElement, FormSpec } from \"@formspec/core\";\nimport { canonicalizeChainDSL } from \"../canonicalize/index.js\";\nimport { generateUiSchemaFromIR } from \"./ir-generator.js\";\nimport type { UISchema } from \"./types.js\";\n\n/**\n * Generates a JSON Forms UI Schema from a FormSpec.\n *\n * All generation routes through the canonical IR. The chain DSL is first\n * canonicalized to a FormIR, then the IR-based generator produces the schema.\n *\n * @example\n * ```typescript\n * const form = formspec(\n * group(\"Customer\",\n * field.text(\"name\", { label: \"Name\" }),\n * ),\n * when(\"status\", \"draft\",\n * field.text(\"notes\", { label: \"Notes\" }),\n * ),\n * );\n *\n * const uiSchema = generateUiSchema(form);\n * // {\n * // type: \"VerticalLayout\",\n * // elements: [\n * // {\n * // type: \"Group\",\n * // label: \"Customer\",\n * // elements: [\n * // { type: \"Control\", scope: \"#/properties/name\", label: \"Name\" }\n * // ]\n * // },\n * // {\n * // type: \"Control\",\n * // scope: \"#/properties/notes\",\n * // label: \"Notes\",\n * // rule: {\n * // effect: \"SHOW\",\n * // condition: { scope: \"#/properties/status\", schema: { const: \"draft\" } }\n * // }\n * // }\n * // ]\n * // }\n * ```\n *\n * @param form - The FormSpec to convert\n * @returns A JSON Forms UI Schema\n *\n * @public\n */\nexport function generateUiSchema<E extends readonly FormElement[]>(form: FormSpec<E>): UISchema {\n const ir = canonicalizeChainDSL(form);\n return generateUiSchemaFromIR(ir);\n}\n","/**\n * `@formspec/build` - Build tools for FormSpec\n *\n * This package provides generators to compile FormSpec forms into:\n * - JSON Schema 2020-12 (for validation)\n * - JSON Forms UI Schema (for rendering)\n *\n * @example\n * ```typescript\n * import { buildFormSchemas } from \"@formspec/build\";\n * import { formspec, field, group } from \"@formspec/dsl\";\n *\n * const form = formspec(\n * group(\"Customer\",\n * field.text(\"name\", { label: \"Name\", required: true }),\n * field.text(\"email\", { label: \"Email\" }),\n * ),\n * );\n *\n * const { jsonSchema, uiSchema } = buildFormSchemas(form);\n * ```\n *\n * @packageDocumentation\n */\n\nimport type { FormElement, FormSpec } from \"@formspec/core\";\nimport { generateJsonSchema, type GenerateJsonSchemaOptions } from \"./json-schema/generator.js\";\nimport { generateUiSchema } from \"./ui-schema/generator.js\";\nimport { type JsonSchema2020 } from \"./json-schema/ir-generator.js\";\nimport type { UISchema } from \"./ui-schema/types.js\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\n// =============================================================================\n// Type Exports\n// =============================================================================\n\nexport type { JsonSchema2020 } from \"./json-schema/ir-generator.js\";\nexport type { GenerateJsonSchemaOptions } from \"./json-schema/generator.js\";\nexport type {\n BuiltinConstraintBroadeningRegistration,\n ConstraintTagRegistration,\n CustomAnnotationRegistration,\n CustomConstraintRegistration,\n CustomTypeRegistration,\n ExtensionDefinition,\n AnyField,\n ArrayField,\n BooleanField,\n Conditional,\n DynamicEnumField,\n DynamicSchemaField,\n EnumOption,\n EnumOptionValue,\n FormElement,\n FormSpec,\n Group,\n NumberField,\n ObjectField,\n StaticEnumField,\n TextField,\n} from \"@formspec/core\";\n\nexport type {\n JSONSchema7,\n JSONSchemaType,\n ExtendedJSONSchema7,\n FormSpecSchemaExtensions,\n} from \"./json-schema/types.js\";\n\nexport { createExtensionRegistry } from \"./extensions/index.js\";\nexport type { ExtensionRegistry } from \"./extensions/index.js\";\n\nexport type {\n UISchema,\n UISchemaElement,\n UISchemaElementBase,\n UISchemaElementType,\n ControlElement,\n VerticalLayout,\n HorizontalLayout,\n GroupLayout,\n Categorization,\n Category,\n LabelElement,\n Rule,\n RuleEffect,\n RuleConditionSchema,\n SchemaBasedCondition,\n} from \"./ui-schema/types.js\";\n\nexport type {\n GenerateFromClassOptions,\n GenerateFromClassResult,\n GenerateSchemasOptions,\n GenerateSchemasFromProgramOptions,\n StaticSchemaGenerationOptions,\n} from \"./generators/class-schema.js\";\nexport type {\n BuildMixedAuthoringSchemasOptions,\n MixedAuthoringSchemas,\n} from \"./generators/mixed-authoring.js\";\n\n// =============================================================================\n// Zod Validation Schemas\n// =============================================================================\n\nexport { jsonSchema7Schema } from \"./json-schema/schema.js\";\nexport { uiSchema as uiSchemaSchema } from \"./ui-schema/schema.js\";\n\n// =============================================================================\n// Chain DSL Generators\n// =============================================================================\n\nexport { generateJsonSchema } from \"./json-schema/generator.js\";\nexport { generateUiSchema } from \"./ui-schema/generator.js\";\nexport {\n generateSchemasFromClass,\n generateSchemas,\n generateSchemasFromProgram,\n} from \"./generators/class-schema.js\";\nexport { buildMixedAuthoringSchemas } from \"./generators/mixed-authoring.js\";\n\n/**\n * Result of building form schemas.\n *\n * @public\n */\nexport interface BuildResult {\n /** JSON Schema 2020-12 for validation */\n readonly jsonSchema: JsonSchema2020;\n /** JSON Forms UI Schema for rendering */\n readonly uiSchema: UISchema;\n}\n\n/**\n * Options for building schemas from a FormSpec.\n *\n * Currently identical to `GenerateJsonSchemaOptions`. Defined separately so the\n * Chain DSL surface can grow independently in the future if needed.\n *\n * @public\n */\nexport type BuildFormSchemasOptions = GenerateJsonSchemaOptions;\n\n/**\n * Builds both JSON Schema and UI Schema from a FormSpec.\n *\n * This is a convenience function that combines `generateJsonSchema`\n * and `generateUiSchema`.\n *\n * @example\n * ```typescript\n * const form = formspec(\n * field.text(\"name\", { required: true }),\n * field.number(\"age\", { min: 0 }),\n * );\n *\n * const { jsonSchema, uiSchema } = buildFormSchemas(form);\n *\n * // Use with JSON Forms renderer\n * <JsonForms\n * schema={jsonSchema}\n * uischema={uiSchema}\n * data={formData}\n * renderers={materialRenderers}\n * />\n * ```\n *\n * @param form - The FormSpec to build schemas from\n * @returns Object containing both jsonSchema and uiSchema\n *\n * @public\n */\nexport function buildFormSchemas<E extends readonly FormElement[]>(\n form: FormSpec<E>,\n options?: BuildFormSchemasOptions\n): BuildResult {\n return {\n jsonSchema: generateJsonSchema(form, options),\n uiSchema: generateUiSchema(form),\n };\n}\n\n/**\n * Options for writing schemas to disk.\n *\n * @public\n */\nexport interface WriteSchemasOptions extends GenerateJsonSchemaOptions {\n /** Output directory for the schema files */\n readonly outDir: string;\n /** Base name for the output files (without extension). Defaults to \"schema\" */\n readonly name?: string;\n /** Number of spaces for JSON indentation. Defaults to 2 */\n readonly indent?: number;\n}\n\n/**\n * Result of writing schemas to disk.\n *\n * @public\n */\nexport interface WriteSchemasResult {\n /** Path to the generated JSON Schema file */\n readonly jsonSchemaPath: string;\n /** Path to the generated UI Schema file */\n readonly uiSchemaPath: string;\n}\n\n/**\n * Builds and writes both JSON Schema and UI Schema files to disk.\n *\n * This is a convenience function for build-time schema generation.\n * It creates the output directory if it doesn't exist.\n *\n * @example\n * ```typescript\n * import { formspec, field } from \"formspec\";\n * import { writeSchemas } from \"@formspec/build\";\n *\n * const ProductForm = formspec(\n * field.text(\"name\", { required: true }),\n * field.enum(\"status\", [\"draft\", \"active\"]),\n * );\n *\n * // Write schemas to ./generated/product-schema.json and ./generated/product-uischema.json\n * const { jsonSchemaPath, uiSchemaPath } = writeSchemas(ProductForm, {\n * outDir: \"./generated\",\n * name: \"product\",\n * });\n *\n * console.log(`Generated: ${jsonSchemaPath}, ${uiSchemaPath}`);\n * ```\n *\n * @param form - The FormSpec to build schemas from\n * @param options - Output options (directory, file name, indentation)\n * @returns Object containing paths to the generated files\n *\n * @public\n */\nexport function writeSchemas<E extends readonly FormElement[]>(\n form: FormSpec<E>,\n options: WriteSchemasOptions\n): WriteSchemasResult {\n const { outDir, name = \"schema\", indent = 2, vendorPrefix } = options;\n\n // Build schemas\n const buildOptions = vendorPrefix === undefined ? undefined : { vendorPrefix };\n\n const { jsonSchema, uiSchema } = buildFormSchemas(form, buildOptions);\n\n // Ensure output directory exists\n if (!fs.existsSync(outDir)) {\n fs.mkdirSync(outDir, { recursive: true });\n }\n\n // Write files\n const jsonSchemaPath = path.join(outDir, `${name}-schema.json`);\n const uiSchemaPath = path.join(outDir, `${name}-uischema.json`);\n\n fs.writeFileSync(jsonSchemaPath, JSON.stringify(jsonSchema, null, indent));\n fs.writeFileSync(uiSchemaPath, JSON.stringify(uiSchema, null, indent));\n\n return { jsonSchemaPath, uiSchemaPath };\n}\n","/**\n * Extension registry for resolving custom types, constraints, and annotations\n * during JSON Schema generation and IR validation.\n *\n * The registry is created from a list of {@link ExtensionDefinition} objects\n * and provides O(1) lookup by fully-qualified ID (extensionId + \"/\" + name).\n *\n * @packageDocumentation\n */\n\nimport type {\n ExtensionDefinition,\n CustomTypeRegistration,\n CustomConstraintRegistration,\n CustomAnnotationRegistration,\n ConstraintTagRegistration,\n BuiltinConstraintBroadeningRegistration,\n} from \"@formspec/core\";\n\n// =============================================================================\n// PUBLIC API\n// =============================================================================\n\n/**\n * A registry of extensions that provides lookup by fully-qualified ID.\n *\n * Type IDs follow the format: `<extensionId>/<typeName>`\n * Constraint IDs follow the format: `<extensionId>/<constraintName>`\n * Annotation IDs follow the format: `<extensionId>/<annotationName>`\n *\n * @public\n */\nexport interface ExtensionRegistry {\n /** The extensions registered in this registry (in registration order). */\n readonly extensions: readonly ExtensionDefinition[];\n\n /**\n * Look up a custom type registration by its fully-qualified type ID.\n *\n * @param typeId - The fully-qualified type ID (e.g., \"x-stripe/monetary/Decimal\").\n * @returns The registration if found, otherwise `undefined`.\n */\n findType(typeId: string): CustomTypeRegistration | undefined;\n /**\n * Look up a custom type registration by a TypeScript-facing type name.\n *\n * This is used during TSDoc/class analysis to resolve extension-defined\n * custom types from source-level declarations.\n */\n findTypeByName(\n typeName: string\n ): { readonly extensionId: string; readonly registration: CustomTypeRegistration } | undefined;\n\n /**\n * Look up a custom constraint registration by its fully-qualified constraint ID.\n *\n * @param constraintId - The fully-qualified constraint ID.\n * @returns The registration if found, otherwise `undefined`.\n */\n findConstraint(constraintId: string): CustomConstraintRegistration | undefined;\n /**\n * Look up a TSDoc custom constraint-tag registration by tag name.\n */\n findConstraintTag(tagName: string):\n | {\n readonly extensionId: string;\n readonly registration: ConstraintTagRegistration;\n }\n | undefined;\n /**\n * Look up built-in tag broadening for a given custom type ID.\n */\n findBuiltinConstraintBroadening(\n typeId: string,\n tagName: string\n ):\n | {\n readonly extensionId: string;\n readonly registration: BuiltinConstraintBroadeningRegistration;\n }\n | undefined;\n\n /**\n * Look up a custom annotation registration by its fully-qualified annotation ID.\n *\n * @param annotationId - The fully-qualified annotation ID.\n * @returns The registration if found, otherwise `undefined`.\n */\n findAnnotation(annotationId: string): CustomAnnotationRegistration | undefined;\n}\n\n// =============================================================================\n// IMPLEMENTATION\n// =============================================================================\n\n/**\n * Creates an extension registry from a list of extension definitions.\n *\n * The registry indexes all types, constraints, and annotations by their\n * fully-qualified IDs (`<extensionId>/<name>`) for O(1) lookup during\n * generation and validation.\n *\n * @param extensions - The extension definitions to register.\n * @returns An {@link ExtensionRegistry} instance.\n * @throws If duplicate type/constraint/annotation IDs are detected across extensions.\n *\n * @public\n */\nexport function createExtensionRegistry(\n extensions: readonly ExtensionDefinition[]\n): ExtensionRegistry {\n const typeMap = new Map<string, CustomTypeRegistration>();\n const typeNameMap = new Map<\n string,\n { readonly extensionId: string; readonly registration: CustomTypeRegistration }\n >();\n const constraintMap = new Map<string, CustomConstraintRegistration>();\n const constraintTagMap = new Map<\n string,\n { readonly extensionId: string; readonly registration: ConstraintTagRegistration }\n >();\n const builtinBroadeningMap = new Map<\n string,\n { readonly extensionId: string; readonly registration: BuiltinConstraintBroadeningRegistration }\n >();\n const annotationMap = new Map<string, CustomAnnotationRegistration>();\n\n for (const ext of extensions) {\n if (ext.types !== undefined) {\n for (const type of ext.types) {\n const qualifiedId = `${ext.extensionId}/${type.typeName}`;\n if (typeMap.has(qualifiedId)) {\n throw new Error(`Duplicate custom type ID: \"${qualifiedId}\"`);\n }\n typeMap.set(qualifiedId, type);\n\n for (const sourceTypeName of type.tsTypeNames ?? [type.typeName]) {\n if (typeNameMap.has(sourceTypeName)) {\n throw new Error(`Duplicate custom type source name: \"${sourceTypeName}\"`);\n }\n typeNameMap.set(sourceTypeName, {\n extensionId: ext.extensionId,\n registration: type,\n });\n }\n\n if (type.builtinConstraintBroadenings !== undefined) {\n for (const broadening of type.builtinConstraintBroadenings) {\n const key = `${qualifiedId}:${broadening.tagName}`;\n if (builtinBroadeningMap.has(key)) {\n throw new Error(`Duplicate built-in constraint broadening: \"${key}\"`);\n }\n builtinBroadeningMap.set(key, {\n extensionId: ext.extensionId,\n registration: broadening,\n });\n }\n }\n }\n }\n\n if (ext.constraints !== undefined) {\n for (const constraint of ext.constraints) {\n const qualifiedId = `${ext.extensionId}/${constraint.constraintName}`;\n if (constraintMap.has(qualifiedId)) {\n throw new Error(`Duplicate custom constraint ID: \"${qualifiedId}\"`);\n }\n constraintMap.set(qualifiedId, constraint);\n }\n }\n\n if (ext.constraintTags !== undefined) {\n for (const tag of ext.constraintTags) {\n if (constraintTagMap.has(tag.tagName)) {\n throw new Error(`Duplicate custom constraint tag: \"@${tag.tagName}\"`);\n }\n constraintTagMap.set(tag.tagName, {\n extensionId: ext.extensionId,\n registration: tag,\n });\n }\n }\n\n if (ext.annotations !== undefined) {\n for (const annotation of ext.annotations) {\n const qualifiedId = `${ext.extensionId}/${annotation.annotationName}`;\n if (annotationMap.has(qualifiedId)) {\n throw new Error(`Duplicate custom annotation ID: \"${qualifiedId}\"`);\n }\n annotationMap.set(qualifiedId, annotation);\n }\n }\n }\n\n return {\n extensions,\n findType: (typeId: string) => typeMap.get(typeId),\n findTypeByName: (typeName: string) => typeNameMap.get(typeName),\n findConstraint: (constraintId: string) => constraintMap.get(constraintId),\n findConstraintTag: (tagName: string) => constraintTagMap.get(tagName),\n findBuiltinConstraintBroadening: (typeId: string, tagName: string) =>\n builtinBroadeningMap.get(`${typeId}:${tagName}`),\n findAnnotation: (annotationId: string) => annotationMap.get(annotationId),\n };\n}\n","/**\n * Zod schemas for JSON Schema output validation.\n *\n * These schemas cover the subset of JSON Schema that FormSpec generates,\n * plus the FormSpec-specific `x-formspec-*` extension properties.\n *\n * @see https://json-schema.org/draft/2020-12/schema\n */\n\nimport { z } from \"zod\";\nimport type { JSONSchema7 } from \"./types.js\";\n\n// =============================================================================\n// JSON Schema type enum\n// =============================================================================\n\n/**\n * Zod schema for JSON Schema primitive type strings.\n *\n * @public\n */\nexport const jsonSchemaTypeSchema = z.enum([\n \"string\",\n \"number\",\n \"integer\",\n \"boolean\",\n \"object\",\n \"array\",\n \"null\",\n]);\n\n// =============================================================================\n// JSON Schema validator schema (recursive)\n// =============================================================================\n\n// We annotate with z.ZodType<JSONSchema7> for the recursive self-reference.\n// The @ts-expect-error is required because exactOptionalPropertyTypes:true causes\n// Zod's inferred output type for optional fields (`T | undefined`) to be\n// incompatible with the JSONSchema7 interface's exact optional fields (`T?`).\n// The runtime behavior is correct: z.optional() will strip `undefined` values\n// during parsing and correctly handle absent keys.\n//\n/**\n * Zod schema for the legacy JSON Schema 7 subset used by `@formspec/build`.\n *\n * @public\n */\n// @ts-expect-error -- exactOptionalPropertyTypes: Zod optional infers `T | undefined`\n// but JSONSchema7 uses exact optional `?:` which disallows explicit undefined.\nexport const jsonSchema7Schema: z.ZodType<JSONSchema7> = z.lazy(() =>\n z\n .object({\n $schema: z.string().optional(),\n $id: z.string().optional(),\n $ref: z.string().optional(),\n\n // Metadata\n title: z.string().optional(),\n description: z.string().optional(),\n deprecated: z.boolean().optional(),\n\n // Type\n type: z.union([jsonSchemaTypeSchema, z.array(jsonSchemaTypeSchema)]).optional(),\n\n // String validation\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n pattern: z.string().optional(),\n\n // Number validation\n minimum: z.number().optional(),\n maximum: z.number().optional(),\n exclusiveMinimum: z.number().optional(),\n exclusiveMaximum: z.number().optional(),\n\n // Enum\n enum: z\n .array(z.union([z.string(), z.number(), z.boolean(), z.null()]))\n .readonly()\n .optional(),\n const: z.union([z.string(), z.number(), z.boolean(), z.null()]).optional(),\n\n // Object\n properties: z.record(z.string(), jsonSchema7Schema).optional(),\n required: z.array(z.string()).optional(),\n additionalProperties: z.union([z.boolean(), jsonSchema7Schema]).optional(),\n\n // Array\n items: z.union([jsonSchema7Schema, z.array(jsonSchema7Schema)]).optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n\n // Composition\n allOf: z.array(jsonSchema7Schema).optional(),\n anyOf: z.array(jsonSchema7Schema).optional(),\n oneOf: z.array(jsonSchema7Schema).optional(),\n not: jsonSchema7Schema.optional(),\n\n // Conditional\n if: jsonSchema7Schema.optional(),\n then: jsonSchema7Schema.optional(),\n else: jsonSchema7Schema.optional(),\n\n // Format\n format: z.string().optional(),\n\n // Default\n default: z.unknown().optional(),\n\n // FormSpec extensions\n \"x-formspec-source\": z.string().optional(),\n \"x-formspec-params\": z.array(z.string()).readonly().optional(),\n \"x-formspec-schemaSource\": z.string().optional(),\n })\n // passthrough preserves arbitrary x-formspec-* extension properties\n // added by custom constraint tags without causing validation failures\n .passthrough()\n);\n","/**\n * Class schema generator.\n *\n * Generates JSON Schema 2020-12 and JSON Forms UI Schema from statically\n * analyzed class/interface/type alias declarations, routing through the\n * canonical FormIR pipeline.\n */\n\nimport * as ts from \"typescript\";\nimport type { UISchema } from \"../ui-schema/types.js\";\nimport {\n analyzeNamedTypeToIRFromProgramContext,\n createProgramContext,\n createProgramContextFromProgram,\n findClassByName,\n} from \"../analyzer/program.js\";\nimport { analyzeClassToIR, type IRClassAnalysis } from \"../analyzer/class-analyzer.js\";\nimport { canonicalizeTSDoc, type TSDocSource } from \"../canonicalize/index.js\";\nimport {\n generateJsonSchemaFromIR,\n type GenerateJsonSchemaFromIROptions,\n type JsonSchema2020,\n} from \"../json-schema/ir-generator.js\";\nimport type { ExtensionRegistry } from \"../extensions/index.js\";\nimport { generateUiSchemaFromIR } from \"../ui-schema/ir-generator.js\";\nimport { validateIR, type ValidationDiagnostic } from \"../validate/index.js\";\n\n/**\n * Generated schemas for a class.\n *\n * @beta\n */\nexport interface ClassSchemas {\n /** JSON Schema 2020-12 for validation */\n jsonSchema: JsonSchema2020;\n /** JSON Forms UI Schema for rendering */\n uiSchema: UISchema;\n}\n\n/**\n * Generates JSON Schema 2020-12 and UI Schema from an IR class analysis.\n *\n * Routes through the canonical IR pipeline:\n * IRClassAnalysis → canonicalizeTSDoc → FormIR → JSON Schema / UI Schema\n *\n * @param analysis - The IR analysis result (from analyzeClassToIR, analyzeInterfaceToIR, or analyzeTypeAliasToIR)\n * @param source - Optional source file metadata for provenance\n * @returns Generated JSON Schema and UI Schema\n */\nexport function generateClassSchemas(\n analysis: IRClassAnalysis,\n source?: TSDocSource,\n options?: GenerateJsonSchemaFromIROptions\n): ClassSchemas {\n const errorDiagnostics = analysis.diagnostics?.filter(\n (diagnostic) => diagnostic.severity === \"error\"\n );\n if (errorDiagnostics !== undefined && errorDiagnostics.length > 0) {\n throw new Error(formatValidationError(errorDiagnostics));\n }\n\n const ir = canonicalizeTSDoc(analysis, source);\n const validationResult = validateIR(ir, {\n ...(options?.extensionRegistry !== undefined && {\n extensionRegistry: options.extensionRegistry,\n }),\n ...(options?.vendorPrefix !== undefined && { vendorPrefix: options.vendorPrefix }),\n });\n if (!validationResult.valid) {\n throw new Error(formatValidationError(validationResult.diagnostics));\n }\n\n return {\n jsonSchema: generateJsonSchemaFromIR(ir, options),\n uiSchema: generateUiSchemaFromIR(ir),\n };\n}\n\nfunction formatValidationError(diagnostics: readonly ValidationDiagnostic[]): string {\n const lines = diagnostics.map((diagnostic) => {\n const primary = formatLocation(diagnostic.primaryLocation);\n const related =\n diagnostic.relatedLocations.length > 0\n ? ` [related: ${diagnostic.relatedLocations.map(formatLocation).join(\", \")}]`\n : \"\";\n return `${diagnostic.code}: ${diagnostic.message} (${primary})${related}`;\n });\n\n return `FormSpec validation failed:\\n${lines.map((line) => `- ${line}`).join(\"\\n\")}`;\n}\n\nfunction formatLocation(location: ValidationDiagnostic[\"primaryLocation\"]): string {\n return `${location.file}:${String(location.line)}:${String(location.column)}`;\n}\n\n/**\n * Shared options for schema generation flows that support custom extensions.\n *\n * @public\n */\nexport interface StaticSchemaGenerationOptions {\n /**\n * Registry used to resolve custom types, constraints, and annotations.\n */\n readonly extensionRegistry?: ExtensionRegistry | undefined;\n /**\n * Vendor prefix for emitted extension keywords.\n * @defaultValue \"x-formspec\"\n */\n readonly vendorPrefix?: string | undefined;\n}\n\n/**\n * Options for generating schemas from a decorated class.\n *\n * @public\n */\nexport interface GenerateFromClassOptions extends StaticSchemaGenerationOptions {\n /** Path to the TypeScript source file */\n filePath: string;\n /** Class name to analyze */\n className: string;\n}\n\n/**\n * Result of generating schemas from a decorated class.\n *\n * @public\n */\nexport interface GenerateFromClassResult {\n /** JSON Schema 2020-12 for validation */\n jsonSchema: JsonSchema2020;\n /** JSON Forms UI Schema for rendering */\n uiSchema: UISchema;\n}\n\n/**\n * Options for generating schemas from a named type inside an existing TypeScript program.\n *\n * @public\n */\nexport interface GenerateSchemasFromProgramOptions extends StaticSchemaGenerationOptions {\n /** Existing TypeScript program supplied by the caller. */\n readonly program: ts.Program;\n /** Path to the TypeScript source file */\n readonly filePath: string;\n /** Name of the exported class, interface, or type alias to analyze */\n readonly typeName: string;\n}\n\n/**\n * Generates JSON Schema and UI Schema from a decorated TypeScript class.\n *\n * This is a high-level entry point that handles the entire pipeline:\n * creating a TypeScript program, finding the class, analyzing it to IR,\n * and generating schemas — all in one call.\n *\n * @example\n * ```typescript\n * const result = generateSchemasFromClass({\n * filePath: \"./src/forms.ts\",\n * className: \"UserForm\",\n * });\n * console.log(result.jsonSchema);\n * ```\n *\n * @param options - File path, class name, and optional compiler options\n * @returns Generated JSON Schema and UI Schema\n *\n * @public\n */\nexport function generateSchemasFromClass(\n options: GenerateFromClassOptions\n): GenerateFromClassResult {\n const ctx = createProgramContext(options.filePath);\n const classDecl = findClassByName(ctx.sourceFile, options.className);\n\n if (!classDecl) {\n throw new Error(`Class \"${options.className}\" not found in ${options.filePath}`);\n }\n\n const analysis = analyzeClassToIR(\n classDecl,\n ctx.checker,\n options.filePath,\n options.extensionRegistry\n );\n return generateClassSchemas(\n analysis,\n { file: options.filePath },\n {\n extensionRegistry: options.extensionRegistry,\n vendorPrefix: options.vendorPrefix,\n }\n );\n}\n\n/**\n * Options for generating schemas from a named type (class, interface, or type alias).\n *\n * @public\n */\nexport interface GenerateSchemasOptions extends StaticSchemaGenerationOptions {\n /** Path to the TypeScript source file */\n filePath: string;\n /** Name of the exported class, interface, or type alias to analyze */\n typeName: string;\n}\n\n/**\n * Generates JSON Schema and UI Schema from a named TypeScript\n * type — a decorated class, an interface with TSDoc tags, or a type alias.\n *\n * This is the recommended entry point. It automatically detects whether\n * the name resolves to a class, interface, or type alias and uses the\n * appropriate IR analysis pipeline.\n *\n * @example\n * ```typescript\n * const result = generateSchemas({\n * filePath: \"./src/config.ts\",\n * typeName: \"DiscountConfig\",\n * });\n * ```\n *\n * @param options - File path and type name\n * @returns Generated JSON Schema and UI Schema\n *\n * @public\n */\nexport function generateSchemas(options: GenerateSchemasOptions): GenerateFromClassResult {\n const ctx = createProgramContext(options.filePath);\n return generateSchemasFromProgram({\n ...options,\n program: ctx.program,\n });\n}\n\n/**\n * Generates JSON Schema and UI Schema from a named type within an existing\n * TypeScript program supplied by the caller.\n *\n * This low-level entry point lets downstream tooling reuse a host-owned\n * `Program` for both FormSpec extraction and other TypeScript analysis.\n *\n * @param options - Host program, file path, type name, and optional schema generation options\n * @returns Generated JSON Schema and UI Schema\n *\n * @public\n */\nexport function generateSchemasFromProgram(\n options: GenerateSchemasFromProgramOptions\n): GenerateFromClassResult;\nexport function generateSchemasFromProgram(\n options: GenerateSchemasFromProgramOptions\n): GenerateFromClassResult {\n const ctx = createProgramContextFromProgram(options.program, options.filePath);\n const analysis = analyzeNamedTypeToIRFromProgramContext(\n ctx,\n options.filePath,\n options.typeName,\n options.extensionRegistry\n );\n return generateClassSchemas(\n analysis,\n { file: options.filePath },\n {\n extensionRegistry: options.extensionRegistry,\n vendorPrefix: options.vendorPrefix,\n }\n );\n}\n","/**\n * TypeScript program setup for static analysis.\n *\n * Creates a TypeScript program with type checker from a source file,\n * using the project's tsconfig.json for compiler options.\n */\n\nimport * as ts from \"typescript\";\nimport * as path from \"node:path\";\nimport {\n analyzeClassToIR,\n analyzeInterfaceToIR,\n analyzeTypeAliasToIR,\n type IRClassAnalysis,\n} from \"./class-analyzer.js\";\nimport type { ExtensionRegistry } from \"../extensions/index.js\";\n\n/**\n * Result of creating a TypeScript program for analysis.\n */\nexport interface ProgramContext {\n /** The TypeScript program */\n program: ts.Program;\n /** Type checker for resolving types */\n checker: ts.TypeChecker;\n /** The source file being analyzed */\n sourceFile: ts.SourceFile;\n}\n\n/**\n * Resolves a source file and checker from an existing TypeScript program.\n *\n * @param program - Existing TypeScript program supplied by the host\n * @param filePath - Absolute or relative path to the TypeScript source file\n * @returns Program context with checker and source file\n */\nexport function createProgramContextFromProgram(\n program: ts.Program,\n filePath: string\n): ProgramContext {\n const absolutePath = path.resolve(filePath);\n const sourceFile = program.getSourceFile(absolutePath) ?? program.getSourceFile(filePath);\n\n if (!sourceFile) {\n throw new Error(`Could not find source file in provided program: ${absolutePath}`);\n }\n\n return {\n program,\n checker: program.getTypeChecker(),\n sourceFile,\n };\n}\n\n/**\n * Creates a TypeScript program for analyzing a source file.\n *\n * Looks for tsconfig.json in the file's directory or parent directories.\n * Falls back to default compiler options if no config is found.\n *\n * @param filePath - Absolute path to the TypeScript source file\n * @returns Program context with checker and source file\n */\nexport function createProgramContext(filePath: string): ProgramContext {\n const absolutePath = path.resolve(filePath);\n const fileDir = path.dirname(absolutePath);\n\n // Find tsconfig.json - using ts.sys.fileExists which has `this: void` requirement\n const configPath = ts.findConfigFile(fileDir, ts.sys.fileExists.bind(ts.sys), \"tsconfig.json\");\n\n let compilerOptions: ts.CompilerOptions;\n let fileNames: string[];\n\n if (configPath) {\n const configFile = ts.readConfigFile(configPath, ts.sys.readFile.bind(ts.sys));\n if (configFile.error) {\n throw new Error(\n `Error reading tsconfig.json: ${ts.flattenDiagnosticMessageText(configFile.error.messageText, \"\\n\")}`\n );\n }\n\n const parsed = ts.parseJsonConfigFileContent(\n configFile.config,\n ts.sys,\n path.dirname(configPath)\n );\n\n if (parsed.errors.length > 0) {\n const errorMessages = parsed.errors\n .map((e) => ts.flattenDiagnosticMessageText(e.messageText, \"\\n\"))\n .join(\"\\n\");\n throw new Error(`Error parsing tsconfig.json: ${errorMessages}`);\n }\n\n compilerOptions = parsed.options;\n // Include the target file in the program\n fileNames = parsed.fileNames.includes(absolutePath)\n ? parsed.fileNames\n : [...parsed.fileNames, absolutePath];\n } else {\n // Fallback to default options\n compilerOptions = {\n target: ts.ScriptTarget.ES2022,\n module: ts.ModuleKind.NodeNext,\n moduleResolution: ts.ModuleResolutionKind.NodeNext,\n strict: true,\n skipLibCheck: true,\n declaration: true,\n };\n fileNames = [absolutePath];\n }\n\n const program = ts.createProgram(fileNames, compilerOptions);\n const sourceFile = program.getSourceFile(absolutePath);\n\n if (!sourceFile) {\n throw new Error(`Could not find source file: ${absolutePath}`);\n }\n\n return {\n program,\n checker: program.getTypeChecker(),\n sourceFile,\n };\n}\n\n/**\n * Generic AST node finder by name. Walks the source file tree and returns\n * the first node matching the predicate with the given name.\n */\nfunction findNodeByName<T extends ts.Node>(\n sourceFile: ts.SourceFile,\n name: string,\n predicate: (node: ts.Node) => node is T,\n getName: (node: T) => string | undefined\n): T | null {\n let result: T | null = null;\n\n function visit(node: ts.Node): void {\n if (result) return;\n\n if (predicate(node) && getName(node) === name) {\n result = node;\n return;\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return result;\n}\n\n/**\n * Finds a class declaration by name in a source file.\n *\n * @param sourceFile - The source file to search\n * @param className - Name of the class to find\n * @returns The class declaration node, or null if not found\n */\nexport function findClassByName(\n sourceFile: ts.SourceFile,\n className: string\n): ts.ClassDeclaration | null {\n return findNodeByName(sourceFile, className, ts.isClassDeclaration, (n) => n.name?.text);\n}\n\n/**\n * Finds an interface declaration by name in a source file.\n *\n * @param sourceFile - The source file to search\n * @param interfaceName - Name of the interface to find\n * @returns The interface declaration node, or null if not found\n */\nexport function findInterfaceByName(\n sourceFile: ts.SourceFile,\n interfaceName: string\n): ts.InterfaceDeclaration | null {\n return findNodeByName(sourceFile, interfaceName, ts.isInterfaceDeclaration, (n) => n.name.text);\n}\n\n/**\n * Finds a type alias declaration by name in a source file.\n *\n * @param sourceFile - The source file to search\n * @param aliasName - Name of the type alias to find\n * @returns The type alias declaration node, or null if not found\n */\nexport function findTypeAliasByName(\n sourceFile: ts.SourceFile,\n aliasName: string\n): ts.TypeAliasDeclaration | null {\n return findNodeByName(sourceFile, aliasName, ts.isTypeAliasDeclaration, (n) => n.name.text);\n}\n\n/**\n * Analyzes a named type (class, interface, or type alias) from a TypeScript\n * source file and returns an `IRClassAnalysis`.\n *\n * Tries each declaration kind in order: class → interface → type alias.\n * Throws if the name is not found or if the type alias analysis fails.\n *\n * @param filePath - Absolute or relative path to the TypeScript source file (resolved internally)\n * @param typeName - Name of the class, interface, or type alias to analyze\n * @param extensionRegistry - Optional extension registry for custom type handling\n * @returns IR analysis result\n */\nexport function analyzeNamedTypeToIR(\n filePath: string,\n typeName: string,\n extensionRegistry?: ExtensionRegistry\n): IRClassAnalysis {\n const ctx = createProgramContext(filePath);\n return analyzeNamedTypeToIRFromProgramContext(ctx, filePath, typeName, extensionRegistry);\n}\n\n/**\n * Analyzes a named type from an existing program context and returns an `IRClassAnalysis`.\n */\nexport function analyzeNamedTypeToIRFromProgramContext(\n ctx: ProgramContext,\n filePath: string,\n typeName: string,\n extensionRegistry?: ExtensionRegistry\n): IRClassAnalysis {\n const analysisFilePath = path.resolve(filePath);\n\n const classDecl = findClassByName(ctx.sourceFile, typeName);\n if (classDecl !== null) {\n return analyzeClassToIR(classDecl, ctx.checker, analysisFilePath, extensionRegistry);\n }\n\n const interfaceDecl = findInterfaceByName(ctx.sourceFile, typeName);\n if (interfaceDecl !== null) {\n return analyzeInterfaceToIR(interfaceDecl, ctx.checker, analysisFilePath, extensionRegistry);\n }\n\n const typeAlias = findTypeAliasByName(ctx.sourceFile, typeName);\n if (typeAlias !== null) {\n const result = analyzeTypeAliasToIR(\n typeAlias,\n ctx.checker,\n analysisFilePath,\n extensionRegistry\n );\n if (result.ok) {\n return result.analysis;\n }\n throw new Error(result.error);\n }\n\n throw new Error(\n `Type \"${typeName}\" not found as a class, interface, or type alias in ${analysisFilePath}`\n );\n}\n","/**\n * Class analyzer for extracting fields, types, and JSDoc constraints.\n *\n * Produces `IRClassAnalysis` containing `FieldNode[]` and `typeRegistry`\n * directly from class, interface, or type alias declarations.\n * All downstream generation routes through the canonical FormIR.\n */\n\nimport * as ts from \"typescript\";\nimport type { ConstraintSemanticDiagnostic } from \"@formspec/analysis/internal\";\nimport type {\n FieldNode,\n TypeNode,\n EnumTypeNode,\n EnumMember,\n ConstraintNode,\n AnnotationNode,\n Provenance,\n ObjectProperty,\n RecordTypeNode,\n TypeDefinition,\n JsonValue,\n} from \"@formspec/core/internals\";\nimport {\n extractJSDocConstraintNodes,\n extractJSDocAnnotationNodes,\n extractDefaultValueAnnotation,\n extractJSDocParseResult,\n} from \"./jsdoc-constraints.js\";\nimport { extractDisplayNameMetadata } from \"./tsdoc-parser.js\";\nimport type { ExtensionRegistry } from \"../extensions/index.js\";\n\n// =============================================================================\n// TYPE GUARDS\n// =============================================================================\n\n/**\n * Type guard for ts.ObjectType — checks that the TypeFlags.Object bit is set.\n */\nfunction isObjectType(type: ts.Type): type is ts.ObjectType {\n return !!(type.flags & ts.TypeFlags.Object);\n}\n\n/**\n * Type guard for ts.TypeReference — checks ObjectFlags.Reference on top of ObjectType.\n * The internal `as` cast is isolated inside this guard and is required because\n * TypeScript's public API does not expose objectFlags on ts.Type directly.\n */\nfunction isTypeReference(type: ts.Type): type is ts.TypeReference {\n // as cast is isolated inside type guard\n return (\n !!(type.flags & ts.TypeFlags.Object) &&\n !!((type as ts.ObjectType).objectFlags & ts.ObjectFlags.Reference)\n );\n}\n\n/**\n * Placeholder used while a named object type is still being expanded.\n *\n * The object identity matters: final empty-object schemas are distinct\n * instances, so we can tell an in-progress registry entry from a real one.\n */\nconst RESOLVING_TYPE_PLACEHOLDER: TypeNode = {\n kind: \"object\",\n properties: [],\n additionalProperties: true,\n};\n\nfunction makeParseOptions(\n extensionRegistry: ExtensionRegistry | undefined,\n fieldType?: TypeNode,\n checker?: ts.TypeChecker,\n subjectType?: ts.Type,\n hostType?: ts.Type\n): import(\"./tsdoc-parser.js\").ParseTSDocOptions | undefined {\n if (\n extensionRegistry === undefined &&\n fieldType === undefined &&\n checker === undefined &&\n subjectType === undefined &&\n hostType === undefined\n ) {\n return undefined;\n }\n\n return {\n ...(extensionRegistry !== undefined && { extensionRegistry }),\n ...(fieldType !== undefined && { fieldType }),\n ...(checker !== undefined && { checker }),\n ...(subjectType !== undefined && { subjectType }),\n ...(hostType !== undefined && { hostType }),\n };\n}\n\n// =============================================================================\n// IR OUTPUT TYPES\n// =============================================================================\n\n/**\n * Layout metadata extracted from `@Group` and `@ShowWhen` TSDoc tags.\n * One entry per field, in the same order as `fields`.\n */\nexport interface FieldLayoutMetadata {\n /** Group label from `@Group(\"label\")`, or undefined if ungrouped. */\n readonly groupLabel?: string;\n /** ShowWhen condition from `@ShowWhen({ field, value })`, or undefined if always visible. */\n readonly showWhen?: { readonly field: string; readonly value: JsonValue };\n}\n\n/**\n * Result of analyzing a class/interface/type alias into canonical IR.\n */\nexport interface IRClassAnalysis {\n /** Type name */\n readonly name: string;\n /** Analyzed fields as canonical IR FieldNodes */\n readonly fields: readonly FieldNode[];\n /** Layout metadata per field (same order/length as `fields`). */\n readonly fieldLayouts: readonly FieldLayoutMetadata[];\n /** Named type definitions referenced by fields */\n readonly typeRegistry: Record<string, TypeDefinition>;\n /** Root-level metadata for the analyzed declaration. */\n readonly annotations?: readonly AnnotationNode[];\n /** Extraction-time diagnostics surfaced before IR validation. */\n readonly diagnostics?: readonly ConstraintSemanticDiagnostic[];\n /** Instance methods (retained for downstream method-schema generation) */\n readonly instanceMethods: readonly MethodInfo[];\n /** Static methods */\n readonly staticMethods: readonly MethodInfo[];\n}\n\n/**\n * Result of analyzing a type alias into IR — either success or error.\n */\nexport type AnalyzeTypeAliasToIRResult =\n | { readonly ok: true; readonly analysis: IRClassAnalysis }\n | { readonly ok: false; readonly error: string };\n\n// =============================================================================\n// IR ANALYSIS — PUBLIC API\n// =============================================================================\n\n/**\n * Analyzes a class declaration and produces canonical IR FieldNodes.\n */\nexport function analyzeClassToIR(\n classDecl: ts.ClassDeclaration,\n checker: ts.TypeChecker,\n file = \"\",\n extensionRegistry?: ExtensionRegistry\n): IRClassAnalysis {\n const name = classDecl.name?.text ?? \"AnonymousClass\";\n const fields: FieldNode[] = [];\n const fieldLayouts: FieldLayoutMetadata[] = [];\n const typeRegistry: Record<string, TypeDefinition> = {};\n const diagnostics: ConstraintSemanticDiagnostic[] = [];\n const classType = checker.getTypeAtLocation(classDecl);\n const classDoc = extractJSDocParseResult(\n classDecl,\n file,\n makeParseOptions(extensionRegistry, undefined, checker, classType, classType)\n );\n const annotations = [...classDoc.annotations];\n diagnostics.push(...classDoc.diagnostics);\n const visiting = new Set<ts.Type>();\n const instanceMethods: MethodInfo[] = [];\n const staticMethods: MethodInfo[] = [];\n\n for (const member of classDecl.members) {\n if (ts.isPropertyDeclaration(member)) {\n const fieldNode = analyzeFieldToIR(\n member,\n checker,\n file,\n typeRegistry,\n visiting,\n diagnostics,\n classType,\n extensionRegistry\n );\n if (fieldNode) {\n fields.push(fieldNode);\n fieldLayouts.push({});\n }\n } else if (ts.isMethodDeclaration(member)) {\n const methodInfo = analyzeMethod(member, checker);\n if (methodInfo) {\n const isStatic = member.modifiers?.some((m) => m.kind === ts.SyntaxKind.StaticKeyword);\n if (isStatic) {\n staticMethods.push(methodInfo);\n } else {\n instanceMethods.push(methodInfo);\n }\n }\n }\n }\n\n return {\n name,\n fields,\n fieldLayouts,\n typeRegistry,\n ...(annotations.length > 0 && { annotations }),\n ...(diagnostics.length > 0 && { diagnostics }),\n instanceMethods,\n staticMethods,\n };\n}\n\n/**\n * Analyzes an interface declaration and produces canonical IR FieldNodes.\n */\nexport function analyzeInterfaceToIR(\n interfaceDecl: ts.InterfaceDeclaration,\n checker: ts.TypeChecker,\n file = \"\",\n extensionRegistry?: ExtensionRegistry\n): IRClassAnalysis {\n const name = interfaceDecl.name.text;\n const fields: FieldNode[] = [];\n const typeRegistry: Record<string, TypeDefinition> = {};\n const diagnostics: ConstraintSemanticDiagnostic[] = [];\n const interfaceType = checker.getTypeAtLocation(interfaceDecl);\n const interfaceDoc = extractJSDocParseResult(\n interfaceDecl,\n file,\n makeParseOptions(extensionRegistry, undefined, checker, interfaceType, interfaceType)\n );\n const annotations = [...interfaceDoc.annotations];\n diagnostics.push(...interfaceDoc.diagnostics);\n const visiting = new Set<ts.Type>();\n\n for (const member of interfaceDecl.members) {\n if (ts.isPropertySignature(member)) {\n const fieldNode = analyzeInterfacePropertyToIR(\n member,\n checker,\n file,\n typeRegistry,\n visiting,\n diagnostics,\n interfaceType,\n extensionRegistry\n );\n if (fieldNode) {\n fields.push(fieldNode);\n }\n }\n }\n\n const fieldLayouts: FieldLayoutMetadata[] = fields.map(() => ({}));\n return {\n name,\n fields,\n fieldLayouts,\n typeRegistry,\n ...(annotations.length > 0 && { annotations }),\n ...(diagnostics.length > 0 && { diagnostics }),\n instanceMethods: [],\n staticMethods: [],\n };\n}\n\n/**\n * Analyzes a type alias declaration and produces canonical IR FieldNodes.\n */\nexport function analyzeTypeAliasToIR(\n typeAlias: ts.TypeAliasDeclaration,\n checker: ts.TypeChecker,\n file = \"\",\n extensionRegistry?: ExtensionRegistry\n): AnalyzeTypeAliasToIRResult {\n if (!ts.isTypeLiteralNode(typeAlias.type)) {\n const sourceFile = typeAlias.getSourceFile();\n const { line } = sourceFile.getLineAndCharacterOfPosition(typeAlias.getStart());\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- enum reverse mapping can be undefined for compiler-internal kinds\n const kindDesc = ts.SyntaxKind[typeAlias.type.kind] ?? \"unknown\";\n return {\n ok: false,\n error: `Type alias \"${typeAlias.name.text}\" at line ${String(line + 1)} is not an object type literal (found ${kindDesc})`,\n };\n }\n\n const name = typeAlias.name.text;\n const fields: FieldNode[] = [];\n const typeRegistry: Record<string, TypeDefinition> = {};\n const diagnostics: ConstraintSemanticDiagnostic[] = [];\n const aliasType = checker.getTypeAtLocation(typeAlias);\n const typeAliasDoc = extractJSDocParseResult(\n typeAlias,\n file,\n makeParseOptions(extensionRegistry, undefined, checker, aliasType, aliasType)\n );\n const annotations = [...typeAliasDoc.annotations];\n diagnostics.push(...typeAliasDoc.diagnostics);\n const visiting = new Set<ts.Type>();\n\n for (const member of typeAlias.type.members) {\n if (ts.isPropertySignature(member)) {\n const fieldNode = analyzeInterfacePropertyToIR(\n member,\n checker,\n file,\n typeRegistry,\n visiting,\n diagnostics,\n aliasType,\n extensionRegistry\n );\n if (fieldNode) {\n fields.push(fieldNode);\n }\n }\n }\n\n return {\n ok: true,\n analysis: {\n name,\n fields,\n fieldLayouts: fields.map(() => ({})),\n typeRegistry,\n ...(annotations.length > 0 && { annotations }),\n ...(diagnostics.length > 0 && { diagnostics }),\n instanceMethods: [],\n staticMethods: [],\n },\n };\n}\n\n// =============================================================================\n// IR FIELD ANALYSIS — PRIVATE\n// =============================================================================\n\n/**\n * Analyzes a class property declaration into a canonical IR FieldNode.\n */\nfunction analyzeFieldToIR(\n prop: ts.PropertyDeclaration,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n diagnostics: ConstraintSemanticDiagnostic[],\n hostType: ts.Type,\n extensionRegistry?: ExtensionRegistry\n): FieldNode | null {\n if (!ts.isIdentifier(prop.name)) {\n return null;\n }\n\n const name = prop.name.text;\n const tsType = checker.getTypeAtLocation(prop);\n const optional = prop.questionToken !== undefined;\n const provenance = provenanceForNode(prop, file);\n\n // Resolve ts.Type → TypeNode\n let type = resolveTypeNode(\n tsType,\n checker,\n file,\n typeRegistry,\n visiting,\n prop,\n extensionRegistry,\n diagnostics\n );\n\n // Collect constraints\n const constraints: ConstraintNode[] = [];\n\n // Inherit constraints from type alias declarations (lower precedence)\n if (prop.type && !shouldEmitPrimitiveAliasDefinition(prop.type, checker)) {\n constraints.push(\n ...extractTypeAliasConstraintNodes(prop.type, checker, file, extensionRegistry)\n );\n }\n\n // Extract JSDoc constraints\n const docResult = extractJSDocParseResult(\n prop,\n file,\n makeParseOptions(extensionRegistry, type, checker, tsType, hostType)\n );\n constraints.push(...docResult.constraints);\n diagnostics.push(...docResult.diagnostics);\n\n // Collect annotations\n let annotations: AnnotationNode[] = [];\n\n // JSDoc annotations (@displayName, @deprecated, summary, @remarks)\n annotations.push(...docResult.annotations);\n\n // Default value annotation\n const defaultAnnotation = extractDefaultValueAnnotation(prop.initializer, file);\n if (defaultAnnotation && !annotations.some((a) => a.annotationKind === \"defaultValue\")) {\n annotations.push(defaultAnnotation);\n }\n\n ({ type, annotations } = applyEnumMemberDisplayNames(type, annotations));\n\n return {\n kind: \"field\",\n name,\n type,\n required: !optional,\n constraints,\n annotations,\n provenance,\n };\n}\n\n/**\n * Analyzes an interface/type-alias property signature into a canonical IR FieldNode.\n */\nfunction analyzeInterfacePropertyToIR(\n prop: ts.PropertySignature,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n diagnostics: ConstraintSemanticDiagnostic[],\n hostType: ts.Type,\n extensionRegistry?: ExtensionRegistry\n): FieldNode | null {\n if (!ts.isIdentifier(prop.name)) {\n return null;\n }\n\n const name = prop.name.text;\n const tsType = checker.getTypeAtLocation(prop);\n const optional = prop.questionToken !== undefined;\n const provenance = provenanceForNode(prop, file);\n\n // Resolve ts.Type → TypeNode\n let type = resolveTypeNode(\n tsType,\n checker,\n file,\n typeRegistry,\n visiting,\n prop,\n extensionRegistry,\n diagnostics\n );\n\n // Collect constraints\n const constraints: ConstraintNode[] = [];\n\n // Inherit constraints from type alias declarations\n if (prop.type && !shouldEmitPrimitiveAliasDefinition(prop.type, checker)) {\n constraints.push(\n ...extractTypeAliasConstraintNodes(prop.type, checker, file, extensionRegistry)\n );\n }\n\n // JSDoc constraints\n const docResult = extractJSDocParseResult(\n prop,\n file,\n makeParseOptions(extensionRegistry, type, checker, tsType, hostType)\n );\n constraints.push(...docResult.constraints);\n diagnostics.push(...docResult.diagnostics);\n\n // Collect annotations\n let annotations: AnnotationNode[] = [];\n\n // JSDoc annotations (@displayName, @deprecated, summary, @remarks)\n annotations.push(...docResult.annotations);\n\n ({ type, annotations } = applyEnumMemberDisplayNames(type, annotations));\n\n return {\n kind: \"field\",\n name,\n type,\n required: !optional,\n constraints,\n annotations,\n provenance,\n };\n}\n\n/**\n * Rewrites enum-member display-name annotations into EnumMember.displayName\n * values and strips those annotations from the field-level annotation list.\n *\n * The TSDoc surface uses `@displayName :value Label` for enum member labels.\n * Plain `@displayName Label` annotations remain as field-level titles.\n */\nfunction applyEnumMemberDisplayNames(\n type: TypeNode,\n annotations: readonly AnnotationNode[]\n): { type: TypeNode; annotations: AnnotationNode[] } {\n if (\n !annotations.some(\n (annotation) =>\n annotation.annotationKind === \"displayName\" && annotation.value.trim().startsWith(\":\")\n )\n ) {\n return { type, annotations: [...annotations] };\n }\n\n const consumed = new Set<AnnotationNode>();\n const nextType = rewriteEnumDisplayNames(type, annotations, consumed);\n\n if (consumed.size === 0) {\n return { type, annotations: [...annotations] };\n }\n\n return {\n type: nextType,\n annotations: annotations.filter((annotation) => !consumed.has(annotation)),\n };\n}\n\nfunction rewriteEnumDisplayNames(\n type: TypeNode,\n annotations: readonly AnnotationNode[],\n consumed: Set<AnnotationNode>\n): TypeNode {\n switch (type.kind) {\n case \"enum\":\n return applyEnumMemberDisplayNamesToEnum(type, annotations, consumed);\n\n case \"union\": {\n return {\n ...type,\n members: type.members.map((member) =>\n rewriteEnumDisplayNames(member, annotations, consumed)\n ),\n };\n }\n\n default:\n return type;\n }\n}\n\nfunction applyEnumMemberDisplayNamesToEnum(\n type: EnumTypeNode,\n annotations: readonly AnnotationNode[],\n consumed: Set<AnnotationNode>\n): EnumTypeNode {\n const displayNames = new Map<string, string>();\n\n for (const annotation of annotations) {\n if (annotation.annotationKind !== \"displayName\") continue;\n\n const parsed = parseEnumMemberDisplayName(annotation.value);\n if (!parsed) continue;\n\n // Once parsed as a member-target display name, never let it fall back to a\n // field-level title, even if the target value does not exist.\n consumed.add(annotation);\n\n const member = type.members.find((m) => String(m.value) === parsed.value);\n if (!member) continue;\n\n displayNames.set(String(member.value), parsed.label);\n }\n\n if (displayNames.size === 0) {\n return type;\n }\n\n return {\n ...type,\n members: type.members.map((member) => {\n const displayName = displayNames.get(String(member.value));\n return displayName !== undefined ? { ...member, displayName } : member;\n }),\n };\n}\n\nfunction parseEnumMemberDisplayName(value: string): { value: string; label: string } | null {\n const trimmed = value.trim();\n const match = /^:([^\\s]+)\\s+([\\s\\S]+)$/.exec(trimmed);\n if (!match?.[1] || !match[2]) return null;\n\n const label = match[2].trim();\n if (label === \"\") return null;\n\n return { value: match[1], label };\n}\n\nfunction resolveRegisteredCustomType(\n sourceNode: ts.Node | undefined,\n extensionRegistry: ExtensionRegistry | undefined,\n checker: ts.TypeChecker\n): TypeNode | null {\n if (sourceNode === undefined || extensionRegistry === undefined) {\n return null;\n }\n\n const typeNode = extractTypeNodeFromSource(sourceNode);\n if (typeNode === undefined) {\n return null;\n }\n\n return resolveRegisteredCustomTypeFromTypeNode(typeNode, extensionRegistry, checker);\n}\n\nfunction resolveRegisteredCustomTypeFromTypeNode(\n typeNode: ts.TypeNode,\n extensionRegistry: ExtensionRegistry,\n checker: ts.TypeChecker\n): TypeNode | null {\n if (ts.isParenthesizedTypeNode(typeNode)) {\n return resolveRegisteredCustomTypeFromTypeNode(typeNode.type, extensionRegistry, checker);\n }\n\n const typeName = getTypeNodeRegistrationName(typeNode);\n if (typeName === null) {\n return null;\n }\n\n const registration = extensionRegistry.findTypeByName(typeName);\n if (registration !== undefined) {\n return {\n kind: \"custom\",\n typeId: `${registration.extensionId}/${registration.registration.typeName}`,\n payload: null,\n };\n }\n\n if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) {\n const aliasDecl = checker\n .getSymbolAtLocation(typeNode.typeName)\n ?.declarations?.find(ts.isTypeAliasDeclaration);\n if (aliasDecl !== undefined) {\n return resolveRegisteredCustomTypeFromTypeNode(aliasDecl.type, extensionRegistry, checker);\n }\n }\n\n return null;\n}\n\nfunction extractTypeNodeFromSource(sourceNode: ts.Node): ts.TypeNode | undefined {\n if (\n ts.isPropertyDeclaration(sourceNode) ||\n ts.isPropertySignature(sourceNode) ||\n ts.isParameter(sourceNode) ||\n ts.isTypeAliasDeclaration(sourceNode)\n ) {\n return sourceNode.type;\n }\n\n if (ts.isTypeNode(sourceNode)) {\n return sourceNode;\n }\n\n return undefined;\n}\n\nfunction getTypeNodeRegistrationName(typeNode: ts.TypeNode): string | null {\n if (ts.isTypeReferenceNode(typeNode)) {\n return ts.isIdentifier(typeNode.typeName)\n ? typeNode.typeName.text\n : typeNode.typeName.right.text;\n }\n\n if (ts.isParenthesizedTypeNode(typeNode)) {\n return getTypeNodeRegistrationName(typeNode.type);\n }\n\n if (\n typeNode.kind === ts.SyntaxKind.BigIntKeyword ||\n typeNode.kind === ts.SyntaxKind.StringKeyword ||\n typeNode.kind === ts.SyntaxKind.NumberKeyword ||\n typeNode.kind === ts.SyntaxKind.BooleanKeyword\n ) {\n return typeNode.getText();\n }\n\n return null;\n}\n\n// =============================================================================\n// TYPE RESOLUTION — ts.Type → TypeNode\n// =============================================================================\n\n/**\n * Resolves a TypeScript type to a canonical IR TypeNode.\n */\nexport function resolveTypeNode(\n type: ts.Type,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n sourceNode?: ts.Node,\n extensionRegistry?: ExtensionRegistry,\n diagnostics?: ConstraintSemanticDiagnostic[]\n): TypeNode {\n const customType = resolveRegisteredCustomType(sourceNode, extensionRegistry, checker);\n if (customType) {\n return customType;\n }\n const primitiveAlias = tryResolveNamedPrimitiveAlias(\n type,\n checker,\n file,\n typeRegistry,\n visiting,\n sourceNode,\n extensionRegistry,\n diagnostics\n );\n if (primitiveAlias) {\n return primitiveAlias;\n }\n\n // --- Primitives ---\n if (type.flags & ts.TypeFlags.String) {\n return { kind: \"primitive\", primitiveKind: \"string\" };\n }\n if (type.flags & ts.TypeFlags.Number) {\n return { kind: \"primitive\", primitiveKind: \"number\" };\n }\n if (type.flags & (ts.TypeFlags.BigInt | ts.TypeFlags.BigIntLiteral)) {\n return { kind: \"primitive\", primitiveKind: \"bigint\" };\n }\n if (type.flags & ts.TypeFlags.Boolean) {\n return { kind: \"primitive\", primitiveKind: \"boolean\" };\n }\n if (type.flags & ts.TypeFlags.Null) {\n return { kind: \"primitive\", primitiveKind: \"null\" };\n }\n if (type.flags & ts.TypeFlags.Undefined) {\n // Undefined maps to null for nullable semantics in JSON Schema\n return { kind: \"primitive\", primitiveKind: \"null\" };\n }\n\n // --- String literal ---\n if (type.isStringLiteral()) {\n return {\n kind: \"enum\",\n members: [{ value: type.value }],\n };\n }\n\n // --- Number literal ---\n if (type.isNumberLiteral()) {\n return {\n kind: \"enum\",\n members: [{ value: type.value }],\n };\n }\n\n // --- Union types ---\n if (type.isUnion()) {\n return resolveUnionType(\n type,\n checker,\n file,\n typeRegistry,\n visiting,\n sourceNode,\n extensionRegistry,\n diagnostics\n );\n }\n\n // --- Array types ---\n if (checker.isArrayType(type)) {\n return resolveArrayType(\n type,\n checker,\n file,\n typeRegistry,\n visiting,\n sourceNode,\n extensionRegistry,\n diagnostics\n );\n }\n\n // --- Object types ---\n if (isObjectType(type)) {\n return resolveObjectType(\n type,\n checker,\n file,\n typeRegistry,\n visiting,\n extensionRegistry,\n diagnostics\n );\n }\n\n // --- Fallback: treat unknown/any/void as string ---\n return { kind: \"primitive\", primitiveKind: \"string\" };\n}\n\nfunction tryResolveNamedPrimitiveAlias(\n type: ts.Type,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n sourceNode?: ts.Node,\n extensionRegistry?: ExtensionRegistry,\n diagnostics?: ConstraintSemanticDiagnostic[]\n): TypeNode | null {\n if (\n !(\n type.flags &\n (ts.TypeFlags.String |\n ts.TypeFlags.Number |\n ts.TypeFlags.BigInt |\n ts.TypeFlags.BigIntLiteral |\n ts.TypeFlags.Boolean |\n ts.TypeFlags.Null)\n )\n ) {\n return null;\n }\n\n const aliasDecl =\n type.aliasSymbol?.declarations?.find(ts.isTypeAliasDeclaration) ??\n getReferencedTypeAliasDeclaration(sourceNode, checker);\n if (!aliasDecl) {\n return null;\n }\n\n const aliasName = aliasDecl.name.text;\n if (!typeRegistry[aliasName]) {\n const aliasType = checker.getTypeFromTypeNode(aliasDecl.type);\n const constraints = [\n ...extractJSDocConstraintNodes(aliasDecl, file, makeParseOptions(extensionRegistry)),\n ...extractTypeAliasConstraintNodes(aliasDecl.type, checker, file, extensionRegistry),\n ];\n const annotations = extractJSDocAnnotationNodes(\n aliasDecl,\n file,\n makeParseOptions(extensionRegistry)\n );\n typeRegistry[aliasName] = {\n name: aliasName,\n type: resolveAliasedPrimitiveTarget(\n aliasType,\n checker,\n file,\n typeRegistry,\n visiting,\n extensionRegistry,\n diagnostics\n ),\n ...(constraints.length > 0 && { constraints }),\n ...(annotations.length > 0 && { annotations }),\n provenance: provenanceForDeclaration(aliasDecl, file),\n };\n }\n\n return { kind: \"reference\", name: aliasName, typeArguments: [] };\n}\n\nfunction getReferencedTypeAliasDeclaration(\n sourceNode: ts.Node | undefined,\n checker: ts.TypeChecker\n): ts.TypeAliasDeclaration | undefined {\n const typeNode =\n sourceNode &&\n (ts.isPropertyDeclaration(sourceNode) ||\n ts.isPropertySignature(sourceNode) ||\n ts.isParameter(sourceNode))\n ? sourceNode.type\n : undefined;\n if (!typeNode || !ts.isTypeReferenceNode(typeNode)) {\n return undefined;\n }\n\n return checker\n .getSymbolAtLocation(typeNode.typeName)\n ?.declarations?.find(ts.isTypeAliasDeclaration);\n}\n\nfunction shouldEmitPrimitiveAliasDefinition(\n typeNode: ts.TypeNode,\n checker: ts.TypeChecker\n): boolean {\n if (!ts.isTypeReferenceNode(typeNode)) {\n return false;\n }\n\n const aliasDecl = checker\n .getSymbolAtLocation(typeNode.typeName)\n ?.declarations?.find(ts.isTypeAliasDeclaration);\n if (!aliasDecl) {\n return false;\n }\n\n const resolved = checker.getTypeFromTypeNode(aliasDecl.type);\n return !!(\n resolved.flags &\n (ts.TypeFlags.String |\n ts.TypeFlags.Number |\n ts.TypeFlags.BigInt |\n ts.TypeFlags.BigIntLiteral |\n ts.TypeFlags.Boolean |\n ts.TypeFlags.Null)\n );\n}\n\nfunction resolveAliasedPrimitiveTarget(\n type: ts.Type,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n extensionRegistry?: ExtensionRegistry,\n diagnostics?: ConstraintSemanticDiagnostic[]\n): TypeNode {\n const nestedAliasDecl = type.aliasSymbol?.declarations?.find(ts.isTypeAliasDeclaration);\n if (nestedAliasDecl !== undefined) {\n return resolveAliasedPrimitiveTarget(\n checker.getTypeFromTypeNode(nestedAliasDecl.type),\n checker,\n file,\n typeRegistry,\n visiting,\n extensionRegistry,\n diagnostics\n );\n }\n\n return resolveTypeNode(\n type,\n checker,\n file,\n typeRegistry,\n visiting,\n undefined,\n extensionRegistry,\n diagnostics\n );\n}\n\nfunction resolveUnionType(\n type: ts.UnionType,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n sourceNode?: ts.Node,\n extensionRegistry?: ExtensionRegistry,\n diagnostics?: ConstraintSemanticDiagnostic[]\n): TypeNode {\n const typeName = getNamedTypeName(type);\n const namedDecl = getNamedTypeDeclaration(type);\n\n if (typeName && typeName in typeRegistry) {\n return { kind: \"reference\", name: typeName, typeArguments: [] };\n }\n\n const allTypes = type.types;\n const unionMemberTypeNodes = extractUnionMemberTypeNodes(sourceNode, checker);\n const nonNullSourceNodes = unionMemberTypeNodes.filter(\n (memberTypeNode) => !isNullishTypeNode(resolveAliasedTypeNode(memberTypeNode, checker))\n );\n const nonNullTypes = allTypes.filter(\n (memberType) => !(memberType.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined))\n );\n const nonNullMembers = nonNullTypes.map((memberType, index) => ({\n memberType,\n sourceNode:\n nonNullSourceNodes.length === nonNullTypes.length ? nonNullSourceNodes[index] : undefined,\n }));\n const hasNull = allTypes.some((t) => t.flags & ts.TypeFlags.Null);\n const memberDisplayNames = new Map<string, string>();\n if (namedDecl) {\n for (const [value, label] of extractDisplayNameMetadata(namedDecl).memberDisplayNames) {\n memberDisplayNames.set(value, label);\n }\n }\n if (sourceNode) {\n for (const [value, label] of extractDisplayNameMetadata(sourceNode).memberDisplayNames) {\n memberDisplayNames.set(value, label);\n }\n }\n\n const registerNamed = (result: TypeNode): TypeNode => {\n if (!typeName) {\n return result;\n }\n const annotations = namedDecl\n ? extractJSDocAnnotationNodes(namedDecl, file, makeParseOptions(extensionRegistry))\n : undefined;\n typeRegistry[typeName] = {\n name: typeName,\n type: result,\n ...(annotations !== undefined && annotations.length > 0 && { annotations }),\n provenance: provenanceForDeclaration(namedDecl ?? sourceNode, file),\n };\n return { kind: \"reference\", name: typeName, typeArguments: [] };\n };\n\n const applyMemberLabels = (members: readonly (string | number)[]): EnumMember[] =>\n members.map((value) => {\n const displayName = memberDisplayNames.get(String(value));\n return displayName !== undefined ? { value, displayName } : { value };\n });\n\n const isBooleanUnion =\n nonNullTypes.length === 2 && nonNullTypes.every((t) => t.flags & ts.TypeFlags.BooleanLiteral);\n\n if (isBooleanUnion) {\n const boolNode: TypeNode = { kind: \"primitive\", primitiveKind: \"boolean\" };\n const result: TypeNode = hasNull\n ? {\n kind: \"union\",\n members: [boolNode, { kind: \"primitive\", primitiveKind: \"null\" }],\n }\n : boolNode;\n return registerNamed(result);\n }\n\n const allStringLiterals = nonNullTypes.every((t) => t.isStringLiteral());\n if (allStringLiterals && nonNullTypes.length > 0) {\n const stringTypes = nonNullTypes.filter((t): t is ts.StringLiteralType => t.isStringLiteral());\n const enumNode: TypeNode = {\n kind: \"enum\",\n members: applyMemberLabels(stringTypes.map((t) => t.value)),\n };\n const result: TypeNode = hasNull\n ? {\n kind: \"union\",\n members: [enumNode, { kind: \"primitive\", primitiveKind: \"null\" }],\n }\n : enumNode;\n return registerNamed(result);\n }\n\n const allNumberLiterals = nonNullTypes.every((t) => t.isNumberLiteral());\n if (allNumberLiterals && nonNullTypes.length > 0) {\n const numberTypes = nonNullTypes.filter((t): t is ts.NumberLiteralType => t.isNumberLiteral());\n const enumNode: TypeNode = {\n kind: \"enum\",\n members: applyMemberLabels(numberTypes.map((t) => t.value)),\n };\n const result: TypeNode = hasNull\n ? {\n kind: \"union\",\n members: [enumNode, { kind: \"primitive\", primitiveKind: \"null\" }],\n }\n : enumNode;\n return registerNamed(result);\n }\n\n if (nonNullMembers.length === 1 && nonNullMembers[0]) {\n const inner = resolveTypeNode(\n nonNullMembers[0].memberType,\n checker,\n file,\n typeRegistry,\n visiting,\n nonNullMembers[0].sourceNode ?? sourceNode,\n extensionRegistry,\n diagnostics\n );\n const result: TypeNode = hasNull\n ? {\n kind: \"union\",\n members: [inner, { kind: \"primitive\", primitiveKind: \"null\" }],\n }\n : inner;\n return registerNamed(result);\n }\n\n const members = nonNullMembers.map(({ memberType, sourceNode: memberSourceNode }) =>\n resolveTypeNode(\n memberType,\n checker,\n file,\n typeRegistry,\n visiting,\n memberSourceNode ?? sourceNode,\n extensionRegistry,\n diagnostics\n )\n );\n if (hasNull) {\n members.push({ kind: \"primitive\", primitiveKind: \"null\" });\n }\n return registerNamed({ kind: \"union\", members });\n}\n\nfunction resolveArrayType(\n type: ts.Type,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n sourceNode?: ts.Node,\n extensionRegistry?: ExtensionRegistry,\n diagnostics?: ConstraintSemanticDiagnostic[]\n): TypeNode {\n const typeArgs = isTypeReference(type) ? type.typeArguments : undefined;\n const elementType = typeArgs?.[0];\n const elementSourceNode = extractArrayElementTypeNode(sourceNode, checker);\n\n const items = elementType\n ? resolveTypeNode(\n elementType,\n checker,\n file,\n typeRegistry,\n visiting,\n elementSourceNode,\n extensionRegistry,\n diagnostics\n )\n : ({ kind: \"primitive\", primitiveKind: \"string\" } satisfies TypeNode);\n\n return { kind: \"array\", items };\n}\n\n/**\n * Returns a `RecordTypeNode` if `type` is a pure dictionary type (string index\n * signature with no named properties), or `null` otherwise.\n *\n * This handles both `Record<string, T>` (a mapped/aliased type) and inline\n * `{ [k: string]: T }` index signature types per spec 003 §2.5.\n */\nfunction tryResolveRecordType(\n type: ts.ObjectType,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n extensionRegistry?: ExtensionRegistry,\n diagnostics?: ConstraintSemanticDiagnostic[]\n): RecordTypeNode | null {\n // Only types with no named properties qualify as pure dictionaries.\n if (type.getProperties().length > 0) {\n return null;\n }\n const indexInfo = checker.getIndexInfoOfType(type, ts.IndexKind.String);\n if (!indexInfo) {\n return null;\n }\n\n const valueType = resolveTypeNode(\n indexInfo.type,\n checker,\n file,\n typeRegistry,\n visiting,\n undefined,\n extensionRegistry,\n diagnostics\n );\n return { kind: \"record\", valueType };\n}\n\nfunction typeNodeContainsReference(type: TypeNode, targetName: string): boolean {\n switch (type.kind) {\n case \"reference\":\n return type.name === targetName;\n case \"array\":\n return typeNodeContainsReference(type.items, targetName);\n case \"record\":\n return typeNodeContainsReference(type.valueType, targetName);\n case \"union\":\n return type.members.some((member) => typeNodeContainsReference(member, targetName));\n case \"object\":\n return type.properties.some((property) =>\n typeNodeContainsReference(property.type, targetName)\n );\n case \"primitive\":\n case \"enum\":\n case \"dynamic\":\n case \"custom\":\n return false;\n default: {\n const _exhaustive: never = type;\n return _exhaustive;\n }\n }\n}\n\nfunction resolveObjectType(\n type: ts.ObjectType,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n extensionRegistry?: ExtensionRegistry,\n diagnostics?: ConstraintSemanticDiagnostic[]\n): TypeNode {\n const typeName = getNamedTypeName(type);\n const namedTypeName = typeName ?? undefined;\n const namedDecl = getNamedTypeDeclaration(type);\n const shouldRegisterNamedType =\n namedTypeName !== undefined &&\n !(namedTypeName === \"Record\" && namedDecl?.getSourceFile().fileName !== file);\n const clearNamedTypeRegistration = (): void => {\n if (namedTypeName === undefined || !shouldRegisterNamedType) {\n return;\n }\n Reflect.deleteProperty(typeRegistry, namedTypeName);\n };\n\n if (visiting.has(type)) {\n // Recursive object expansion is deferred through the named-type registry.\n // Anonymous cycles still collapse to a closed empty object sentinel.\n if (namedTypeName !== undefined && shouldRegisterNamedType) {\n return { kind: \"reference\", name: namedTypeName, typeArguments: [] };\n }\n return { kind: \"object\", properties: [], additionalProperties: false };\n }\n\n // Seed the registry with a placeholder before traversing children so any\n // recursive property reference can resolve to a stable `$ref`.\n if (namedTypeName !== undefined && shouldRegisterNamedType && !typeRegistry[namedTypeName]) {\n typeRegistry[namedTypeName] = {\n name: namedTypeName,\n type: RESOLVING_TYPE_PLACEHOLDER,\n provenance: provenanceForDeclaration(namedDecl, file),\n };\n }\n\n visiting.add(type);\n\n // Detect previously resolved named types before walking the object body.\n if (\n namedTypeName !== undefined &&\n shouldRegisterNamedType &&\n typeRegistry[namedTypeName]?.type !== undefined\n ) {\n if (typeRegistry[namedTypeName].type !== RESOLVING_TYPE_PLACEHOLDER) {\n visiting.delete(type);\n return { kind: \"reference\", name: namedTypeName, typeArguments: [] };\n }\n }\n\n // Detect pure dictionary types (Record<string, T> or { [k: string]: T })\n // after the recursion guard/placeholder setup so recursive records can point\n // back at the named type instead of collapsing to an empty object.\n const recordNode = tryResolveRecordType(\n type,\n checker,\n file,\n typeRegistry,\n visiting,\n extensionRegistry,\n diagnostics\n );\n if (recordNode) {\n visiting.delete(type);\n if (namedTypeName !== undefined && shouldRegisterNamedType) {\n const isRecursiveRecord = typeNodeContainsReference(recordNode.valueType, namedTypeName);\n if (!isRecursiveRecord) {\n clearNamedTypeRegistration();\n return recordNode;\n }\n const annotations = namedDecl\n ? extractJSDocAnnotationNodes(namedDecl, file, makeParseOptions(extensionRegistry))\n : undefined;\n typeRegistry[namedTypeName] = {\n name: namedTypeName,\n type: recordNode,\n ...(annotations !== undefined && annotations.length > 0 && { annotations }),\n provenance: provenanceForDeclaration(namedDecl, file),\n };\n return { kind: \"reference\", name: namedTypeName, typeArguments: [] };\n }\n return recordNode;\n }\n\n const properties: ObjectProperty[] = [];\n\n // Get FieldInfo-level analysis from named type declarations for constraint propagation\n const fieldInfoMap = getNamedTypeFieldNodeInfoMap(\n type,\n checker,\n file,\n typeRegistry,\n visiting,\n diagnostics ?? [],\n extensionRegistry\n );\n\n for (const prop of type.getProperties()) {\n const declaration = prop.valueDeclaration ?? prop.declarations?.[0];\n if (!declaration) continue;\n\n const propType = checker.getTypeOfSymbolAtLocation(prop, declaration);\n const optional = !!(prop.flags & ts.SymbolFlags.Optional);\n const propTypeNode = resolveTypeNode(\n propType,\n checker,\n file,\n typeRegistry,\n visiting,\n declaration,\n extensionRegistry,\n diagnostics\n );\n\n // Get constraints and annotations from the declaration if available\n const fieldNodeInfo = fieldInfoMap?.get(prop.name);\n\n properties.push({\n name: prop.name,\n type: propTypeNode,\n optional,\n constraints: fieldNodeInfo?.constraints ?? [],\n annotations: fieldNodeInfo?.annotations ?? [],\n provenance: fieldNodeInfo?.provenance ?? provenanceForFile(file),\n });\n }\n\n visiting.delete(type);\n\n const objectNode: TypeNode = {\n kind: \"object\",\n properties,\n additionalProperties: true,\n };\n\n // Register named types\n if (namedTypeName !== undefined && shouldRegisterNamedType) {\n const annotations = namedDecl\n ? extractJSDocAnnotationNodes(namedDecl, file, makeParseOptions(extensionRegistry))\n : undefined;\n typeRegistry[namedTypeName] = {\n name: namedTypeName,\n type: objectNode,\n ...(annotations !== undefined && annotations.length > 0 && { annotations }),\n provenance: provenanceForDeclaration(namedDecl, file),\n };\n return { kind: \"reference\", name: namedTypeName, typeArguments: [] };\n }\n\n return objectNode;\n}\n\n// =============================================================================\n// NAMED TYPE FIELD INFO MAP — for nested constraint propagation\n// =============================================================================\n\ninterface FieldNodeInfo {\n readonly constraints: readonly ConstraintNode[];\n readonly annotations: readonly AnnotationNode[];\n readonly provenance: Provenance;\n}\n\n/**\n * Builds a map from property name to constraint/annotation info for named types.\n * This enables propagating TSDoc constraints from nested type declarations.\n */\nfunction getNamedTypeFieldNodeInfoMap(\n type: ts.Type,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n diagnostics: ConstraintSemanticDiagnostic[],\n extensionRegistry?: ExtensionRegistry\n): Map<string, FieldNodeInfo> | null {\n const symbols = [type.getSymbol(), type.aliasSymbol].filter(\n (s): s is ts.Symbol => s?.declarations != null && s.declarations.length > 0\n );\n\n for (const symbol of symbols) {\n const declarations = symbol.declarations;\n if (!declarations) continue;\n\n // Try class declaration\n const classDecl = declarations.find(ts.isClassDeclaration);\n if (classDecl) {\n const map = new Map<string, FieldNodeInfo>();\n const hostType = checker.getTypeAtLocation(classDecl);\n for (const member of classDecl.members) {\n if (ts.isPropertyDeclaration(member) && ts.isIdentifier(member.name)) {\n const fieldNode = analyzeFieldToIR(\n member,\n checker,\n file,\n typeRegistry,\n visiting,\n diagnostics,\n hostType,\n extensionRegistry\n );\n if (fieldNode) {\n map.set(fieldNode.name, {\n constraints: [...fieldNode.constraints],\n annotations: [...fieldNode.annotations],\n provenance: fieldNode.provenance,\n });\n }\n }\n }\n return map;\n }\n\n // Try interface declaration\n const interfaceDecl = declarations.find(ts.isInterfaceDeclaration);\n if (interfaceDecl) {\n return buildFieldNodeInfoMap(\n interfaceDecl.members,\n checker,\n file,\n typeRegistry,\n visiting,\n checker.getTypeAtLocation(interfaceDecl),\n diagnostics,\n extensionRegistry\n );\n }\n\n // Try type alias with type literal body\n const typeAliasDecl = declarations.find(ts.isTypeAliasDeclaration);\n if (typeAliasDecl && ts.isTypeLiteralNode(typeAliasDecl.type)) {\n return buildFieldNodeInfoMap(\n typeAliasDecl.type.members,\n checker,\n file,\n typeRegistry,\n visiting,\n checker.getTypeAtLocation(typeAliasDecl),\n diagnostics,\n extensionRegistry\n );\n }\n }\n\n return null;\n}\n\nfunction extractArrayElementTypeNode(\n sourceNode: ts.Node | undefined,\n checker: ts.TypeChecker\n): ts.TypeNode | undefined {\n const typeNode = sourceNode === undefined ? undefined : extractTypeNodeFromSource(sourceNode);\n if (typeNode === undefined) {\n return undefined;\n }\n const resolvedTypeNode = resolveAliasedTypeNode(typeNode, checker);\n if (ts.isArrayTypeNode(resolvedTypeNode)) {\n return resolvedTypeNode.elementType;\n }\n if (\n ts.isTypeReferenceNode(resolvedTypeNode) &&\n ts.isIdentifier(resolvedTypeNode.typeName) &&\n resolvedTypeNode.typeName.text === \"Array\" &&\n resolvedTypeNode.typeArguments?.[0]\n ) {\n return resolvedTypeNode.typeArguments[0];\n }\n return undefined;\n}\n\nfunction extractUnionMemberTypeNodes(\n sourceNode: ts.Node | undefined,\n checker: ts.TypeChecker\n): readonly ts.TypeNode[] {\n const typeNode = sourceNode === undefined ? undefined : extractTypeNodeFromSource(sourceNode);\n if (!typeNode) {\n return [];\n }\n const resolvedTypeNode = resolveAliasedTypeNode(typeNode, checker);\n return ts.isUnionTypeNode(resolvedTypeNode) ? [...resolvedTypeNode.types] : [];\n}\n\nfunction resolveAliasedTypeNode(\n typeNode: ts.TypeNode,\n checker: ts.TypeChecker,\n visited: Set<ts.TypeAliasDeclaration> = new Set<ts.TypeAliasDeclaration>()\n): ts.TypeNode {\n if (ts.isParenthesizedTypeNode(typeNode)) {\n return resolveAliasedTypeNode(typeNode.type, checker, visited);\n }\n\n if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) {\n return typeNode;\n }\n\n const symbol = checker.getSymbolAtLocation(typeNode.typeName);\n const aliasDecl = symbol?.declarations?.find(ts.isTypeAliasDeclaration);\n if (aliasDecl === undefined || visited.has(aliasDecl)) {\n return typeNode;\n }\n\n visited.add(aliasDecl);\n return resolveAliasedTypeNode(aliasDecl.type, checker, visited);\n}\n\nfunction isNullishTypeNode(typeNode: ts.TypeNode): boolean {\n if (\n typeNode.kind === ts.SyntaxKind.NullKeyword ||\n typeNode.kind === ts.SyntaxKind.UndefinedKeyword\n ) {\n return true;\n }\n\n return (\n ts.isLiteralTypeNode(typeNode) &&\n (typeNode.literal.kind === ts.SyntaxKind.NullKeyword ||\n typeNode.literal.kind === ts.SyntaxKind.UndefinedKeyword)\n );\n}\n\nfunction buildFieldNodeInfoMap(\n members: ts.NodeArray<ts.TypeElement>,\n checker: ts.TypeChecker,\n file: string,\n typeRegistry: Record<string, TypeDefinition>,\n visiting: Set<ts.Type>,\n hostType: ts.Type,\n diagnostics: ConstraintSemanticDiagnostic[],\n extensionRegistry?: ExtensionRegistry\n): Map<string, FieldNodeInfo> {\n const map = new Map<string, FieldNodeInfo>();\n for (const member of members) {\n if (ts.isPropertySignature(member)) {\n const fieldNode = analyzeInterfacePropertyToIR(\n member,\n checker,\n file,\n typeRegistry,\n visiting,\n diagnostics,\n hostType,\n extensionRegistry\n );\n if (fieldNode) {\n map.set(fieldNode.name, {\n constraints: [...fieldNode.constraints],\n annotations: [...fieldNode.annotations],\n provenance: fieldNode.provenance,\n });\n }\n }\n }\n return map;\n}\n\n// =============================================================================\n// TYPE ALIAS CONSTRAINT PROPAGATION\n// =============================================================================\n\n/** Maximum depth for transitive type alias constraint propagation. */\nconst MAX_ALIAS_CHAIN_DEPTH = 8;\n\n/**\n * Given a type node referencing a type alias, extracts IR ConstraintNodes\n * from the alias declaration's JSDoc tags.\n *\n * Follows alias chains transitively: if `type Percentage = Integer` and\n * `type Integer = number`, constraints from both `Percentage` and `Integer`\n * are collected. Constraints from closer aliases appear first in the result\n * (higher precedence). Recursion is capped at {@link MAX_ALIAS_CHAIN_DEPTH}\n * levels; exceeding the limit throws to surface pathological alias chains.\n */\nfunction extractTypeAliasConstraintNodes(\n typeNode: ts.TypeNode,\n checker: ts.TypeChecker,\n file: string,\n extensionRegistry?: ExtensionRegistry,\n depth = 0\n): ConstraintNode[] {\n if (!ts.isTypeReferenceNode(typeNode)) return [];\n\n if (depth >= MAX_ALIAS_CHAIN_DEPTH) {\n const aliasName = typeNode.typeName.getText();\n throw new Error(\n `Type alias chain exceeds maximum depth of ${String(MAX_ALIAS_CHAIN_DEPTH)} ` +\n `at alias \"${aliasName}\" in ${file}. ` +\n `Simplify the alias chain or check for circular references.`\n );\n }\n\n const symbol = checker.getSymbolAtLocation(typeNode.typeName);\n if (!symbol?.declarations) return [];\n\n const aliasDecl = symbol.declarations.find(ts.isTypeAliasDeclaration);\n if (!aliasDecl) return [];\n\n // Don't extract from object type aliases\n if (ts.isTypeLiteralNode(aliasDecl.type)) return [];\n\n const aliasFieldType = resolveTypeNode(\n checker.getTypeAtLocation(aliasDecl.type),\n checker,\n file,\n {},\n new Set<ts.Type>(),\n aliasDecl.type,\n extensionRegistry\n );\n const constraints = extractJSDocConstraintNodes(\n aliasDecl,\n file,\n makeParseOptions(extensionRegistry, aliasFieldType)\n );\n\n // Transitively follow alias chains (e.g., Percentage → Integer → number)\n // Constraints from parent aliases are appended after the immediate alias's\n // constraints, giving the immediate alias higher precedence.\n constraints.push(\n ...extractTypeAliasConstraintNodes(aliasDecl.type, checker, file, extensionRegistry, depth + 1)\n );\n\n return constraints;\n}\n\n// =============================================================================\n// PROVENANCE HELPERS\n// =============================================================================\n\nfunction provenanceForNode(node: ts.Node, file: string): Provenance {\n const sourceFile = node.getSourceFile();\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n return {\n surface: \"tsdoc\",\n file,\n line: line + 1,\n column: character,\n };\n}\n\nfunction provenanceForFile(file: string): Provenance {\n return { surface: \"tsdoc\", file, line: 0, column: 0 };\n}\n\nfunction provenanceForDeclaration(node: ts.Node | undefined, file: string): Provenance {\n if (!node) {\n return provenanceForFile(file);\n }\n return provenanceForNode(node, file);\n}\n\n// =============================================================================\n// NAMED TYPE HELPERS\n// =============================================================================\n\n/**\n * Extracts a stable type name from a ts.Type when it originates from\n * a named declaration (class, interface, or type alias).\n */\nfunction getNamedTypeName(type: ts.Type): string | null {\n const symbol = type.getSymbol();\n if (symbol?.declarations) {\n const decl = symbol.declarations[0];\n if (\n decl &&\n (ts.isClassDeclaration(decl) ||\n ts.isInterfaceDeclaration(decl) ||\n ts.isTypeAliasDeclaration(decl))\n ) {\n const name = ts.isClassDeclaration(decl) ? decl.name?.text : decl.name.text;\n if (name) return name;\n }\n }\n\n const aliasSymbol = type.aliasSymbol;\n if (aliasSymbol?.declarations) {\n const aliasDecl = aliasSymbol.declarations.find(ts.isTypeAliasDeclaration);\n if (aliasDecl) {\n return aliasDecl.name.text;\n }\n }\n\n return null;\n}\n\n/**\n * Returns the declaration that defines a named type, if available.\n */\nfunction getNamedTypeDeclaration(type: ts.Type): ts.Declaration | undefined {\n const symbol = type.getSymbol();\n if (symbol?.declarations) {\n const decl = symbol.declarations[0];\n if (\n decl &&\n (ts.isClassDeclaration(decl) ||\n ts.isInterfaceDeclaration(decl) ||\n ts.isTypeAliasDeclaration(decl))\n ) {\n return decl;\n }\n }\n\n const aliasSymbol = type.aliasSymbol;\n if (aliasSymbol?.declarations) {\n return aliasSymbol.declarations.find(ts.isTypeAliasDeclaration);\n }\n\n return undefined;\n}\n\n// =============================================================================\n// SHARED OUTPUT TYPES\n// =============================================================================\n\n/**\n * Analyzed method information.\n */\nexport interface MethodInfo {\n /** Method name */\n name: string;\n /** Method parameters */\n parameters: ParameterInfo[];\n /** Return type node */\n returnTypeNode: ts.TypeNode | undefined;\n /** Resolved return type */\n returnType: ts.Type;\n}\n\n/**\n * Analyzed parameter information.\n */\nexport interface ParameterInfo {\n /** Parameter name */\n name: string;\n /** TypeScript type node */\n typeNode: ts.TypeNode | undefined;\n /** Resolved type */\n type: ts.Type;\n /** If this is InferSchema<typeof X>, the export name X */\n formSpecExportName: string | null;\n /** Whether the parameter is optional (has ? or default value) */\n optional: boolean;\n}\n\n// =============================================================================\n// SHARED HELPERS\n// =============================================================================\n\n/**\n * Analyzes a method declaration to extract method info.\n * Shared between IR and legacy paths.\n */\nfunction analyzeMethod(method: ts.MethodDeclaration, checker: ts.TypeChecker): MethodInfo | null {\n if (!ts.isIdentifier(method.name)) {\n return null;\n }\n\n const name = method.name.text;\n const parameters: ParameterInfo[] = [];\n\n for (const param of method.parameters) {\n if (ts.isIdentifier(param.name)) {\n const paramInfo = analyzeParameter(param, checker);\n parameters.push(paramInfo);\n }\n }\n\n const returnTypeNode = method.type;\n const signature = checker.getSignatureFromDeclaration(method);\n const returnType = signature\n ? checker.getReturnTypeOfSignature(signature)\n : checker.getTypeAtLocation(method);\n\n return { name, parameters, returnTypeNode, returnType };\n}\n\nfunction analyzeParameter(param: ts.ParameterDeclaration, checker: ts.TypeChecker): ParameterInfo {\n const name = ts.isIdentifier(param.name) ? param.name.text : \"param\";\n const typeNode = param.type;\n const type = checker.getTypeAtLocation(param);\n const formSpecExportName = detectFormSpecReference(typeNode);\n const optional = param.questionToken !== undefined || param.initializer !== undefined;\n\n return { name, typeNode, type, formSpecExportName, optional };\n}\n\nfunction detectFormSpecReference(typeNode: ts.TypeNode | undefined): string | null {\n if (!typeNode) return null;\n\n if (!ts.isTypeReferenceNode(typeNode)) return null;\n\n const typeName = ts.isIdentifier(typeNode.typeName)\n ? typeNode.typeName.text\n : ts.isQualifiedName(typeNode.typeName)\n ? typeNode.typeName.right.text\n : null;\n\n if (typeName !== \"InferSchema\" && typeName !== \"InferFormSchema\") return null;\n\n const typeArg = typeNode.typeArguments?.[0];\n if (!typeArg || !ts.isTypeQueryNode(typeArg)) return null;\n\n if (ts.isIdentifier(typeArg.exprName)) {\n return typeArg.exprName.text;\n }\n\n if (ts.isQualifiedName(typeArg.exprName)) {\n return typeArg.exprName.right.text;\n }\n\n return null;\n}\n","/**\n * JSDoc constraint and annotation extractor.\n *\n * Extracts constraints and annotation tags from JSDoc comments on\n * class/interface fields and returns canonical IR nodes directly:\n * - {@link ConstraintNode} for set-influencing tags (@minimum, @pattern, etc.)\n * - {@link AnnotationNode} for value-influencing tags (@displayName, etc.)\n *\n * The IR extraction path uses the official `@microsoft/tsdoc` parser for\n * all canonical tags.\n *\n * Supported constraints correspond to the built-in FormSpec constraint tags\n * (e.g., `@minimum`, `@maximum`, `@pattern`).\n */\n\nimport * as ts from \"typescript\";\nimport type { ConstraintNode, AnnotationNode, JsonValue } from \"@formspec/core/internals\";\nimport {\n parseTSDocTags,\n hasDeprecatedTagTSDoc,\n type ParseTSDocOptions,\n type TSDocParseResult,\n} from \"./tsdoc-parser.js\";\n\n// =============================================================================\n// IR API — uses @microsoft/tsdoc for structured parsing\n// =============================================================================\n\nexport function extractJSDocParseResult(\n node: ts.Node,\n file = \"\",\n options?: ParseTSDocOptions\n): TSDocParseResult {\n return parseTSDocTags(node, file, options);\n}\n\n/**\n * Extracts constraints from JSDoc comments on a TypeScript AST node and returns\n * canonical {@link ConstraintNode} objects.\n *\n * Uses the official `@microsoft/tsdoc` parser for structured tag extraction.\n * Constraints are registered as custom block tags in the TSDoc configuration.\n *\n * @param node - The AST node to inspect for JSDoc tags\n * @param file - Absolute path to the source file for provenance\n * @returns Canonical constraint nodes for each valid constraint tag\n */\nexport function extractJSDocConstraintNodes(\n node: ts.Node,\n file = \"\",\n options?: ParseTSDocOptions\n): ConstraintNode[] {\n const result = extractJSDocParseResult(node, file, options);\n return [...result.constraints];\n}\n\n/**\n * Extracts canonical annotation tags from a node and returns\n * {@link AnnotationNode} objects.\n *\n * @param node - The AST node to inspect for annotation tags\n * @param file - Absolute path to the source file for provenance\n * @returns Canonical annotation nodes\n */\nexport function extractJSDocAnnotationNodes(\n node: ts.Node,\n file = \"\",\n options?: ParseTSDocOptions\n): AnnotationNode[] {\n const result = extractJSDocParseResult(node, file, options);\n return [...result.annotations];\n}\n\n/**\n * Checks if a node has a TSDoc `@deprecated` tag.\n *\n * Uses the TSDoc parser for structured detection.\n */\nexport function hasDeprecatedTag(node: ts.Node): boolean {\n return hasDeprecatedTagTSDoc(node);\n}\n\n/**\n * Extracts a default value from a property initializer and returns a\n * {@link DefaultValueAnnotationNode} if present.\n *\n * Only extracts literal values (strings, numbers, booleans, null).\n */\nexport function extractDefaultValueAnnotation(\n initializer: ts.Expression | undefined,\n file = \"\"\n): AnnotationNode | null {\n if (!initializer) return null;\n\n let value: JsonValue | undefined;\n\n if (ts.isStringLiteral(initializer)) {\n value = initializer.text;\n } else if (ts.isNumericLiteral(initializer)) {\n value = Number(initializer.text);\n } else if (initializer.kind === ts.SyntaxKind.TrueKeyword) {\n value = true;\n } else if (initializer.kind === ts.SyntaxKind.FalseKeyword) {\n value = false;\n } else if (initializer.kind === ts.SyntaxKind.NullKeyword) {\n value = null;\n } else if (ts.isPrefixUnaryExpression(initializer)) {\n if (\n initializer.operator === ts.SyntaxKind.MinusToken &&\n ts.isNumericLiteral(initializer.operand)\n ) {\n value = -Number(initializer.operand.text);\n }\n }\n\n if (value === undefined) return null;\n\n const sourceFile = initializer.getSourceFile();\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(initializer.getStart());\n\n return {\n kind: \"annotation\",\n annotationKind: \"defaultValue\",\n value,\n provenance: {\n surface: \"tsdoc\",\n file,\n line: line + 1,\n column: character,\n },\n };\n}\n","/**\n * TSDoc-based structured tag parser.\n *\n * Bridges the TypeScript compiler AST with the official `@microsoft/tsdoc`\n * parser to extract constraint and annotation tags from JSDoc comments\n * on class/interface/type-alias properties.\n *\n * The parser recognises two categories of tags:\n *\n * 1. **Constraint tags** (all alphanumeric, TSDoc-compliant):\n * `@minimum`, `@maximum`, `@exclusiveMinimum`, `@exclusiveMaximum`,\n * `@multipleOf`, `@minLength`, `@maxLength`, `@minItems`, `@maxItems`,\n * `@uniqueItems`, `@pattern`, `@enumOptions`, `@const`\n * — Parsed via TSDocParser as custom block tags.\n * Both camelCase and PascalCase forms are accepted (e.g., `@Minimum`).\n *\n * 2. **Annotation tags** (`@displayName`, `@format`, `@placeholder`):\n * These are parsed as structured custom block tags and mapped directly\n * onto annotation IR nodes.\n *\n * The `@deprecated` tag is a standard TSDoc block tag, parsed structurally.\n *\n * Description and remarks extraction (spec 002 §2.3):\n * - Summary text (bare text before the first block tag) → `description` annotation\n * - `@remarks` block → `remarks` annotation (separate channel)\n * - `@description` is NOT supported (not a standard TSDoc tag)\n *\n * **Fallback strategy**: TSDoc treats `{` / `}` as inline tag delimiters and\n * `@` as a tag prefix, so content containing these characters (e.g. JSON\n * objects in `@EnumOptions`, regex patterns with `@` in `@Pattern`) gets\n * mangled by the TSDoc parser. The shared comment syntax parser is the\n * primary source for these payloads; the TS compiler's `ts.getJSDocTags()`\n * API remains as a fallback when a raw payload cannot be recovered from the\n * shared parse.\n */\n\nimport * as ts from \"typescript\";\nimport {\n checkSyntheticTagApplication,\n extractPathTarget as extractSharedPathTarget,\n getTagDefinition,\n hasTypeSemanticCapability,\n parseConstraintTagValue,\n parseDefaultValueTagValue,\n type ParsedCommentTag,\n resolveDeclarationPlacement,\n resolvePathTargetType,\n sliceCommentSpan,\n parseCommentBlock,\n parseTagSyntax,\n type ConstraintSemanticDiagnostic,\n type FormSpecValueKind,\n type SemanticCapability,\n} from \"@formspec/analysis/internal\";\nimport {\n TSDocParser,\n TSDocConfiguration,\n TSDocTagDefinition,\n TSDocTagSyntaxKind,\n DocExcerpt,\n DocPlainText,\n DocSoftBreak,\n TextRange,\n type DocNode,\n type DocBlock,\n} from \"@microsoft/tsdoc\";\nimport {\n BUILTIN_CONSTRAINT_DEFINITIONS,\n normalizeConstraintTagName,\n isBuiltinConstraintName,\n} from \"@formspec/core/internals\";\nimport {\n type ConstraintNode,\n type AnnotationNode,\n type Provenance,\n type PathTarget,\n type TypeNode,\n} from \"@formspec/core/internals\";\nimport type { ExtensionRegistry } from \"../extensions/index.js\";\n\n// =============================================================================\n// CONFIGURATION\n// =============================================================================\n\n/**\n * Tags whose content may contain TSDoc-significant characters (`{}`, `@`)\n * and must be extracted via the TS compiler JSDoc API rather than the\n * TSDoc DocNode tree to avoid content mangling.\n *\n * - `@pattern`: regex patterns commonly contain `@` (e.g. email validation)\n * - `@enumOptions`: JSON arrays may contain object literals with `{}`\n * - `@defaultValue`: JSON defaults may contain objects, arrays, or quoted strings\n */\nconst TAGS_REQUIRING_RAW_TEXT = new Set([\"pattern\", \"enumOptions\", \"defaultValue\"]);\n\n/**\n * Creates a TSDocConfiguration with FormSpec custom block tag definitions\n * registered for all constraint tags.\n */\nfunction createFormSpecTSDocConfig(extensionTagNames: readonly string[] = []): TSDocConfiguration {\n const config = new TSDocConfiguration();\n\n // Register each constraint tag as a custom block tag (allowMultiple so\n // repeated tags don't produce warnings).\n for (const tagName of Object.keys(BUILTIN_CONSTRAINT_DEFINITIONS)) {\n config.addTagDefinition(\n new TSDocTagDefinition({\n tagName: \"@\" + tagName,\n syntaxKind: TSDocTagSyntaxKind.BlockTag,\n allowMultiple: true,\n })\n );\n }\n\n // Register annotation tags that participate in the canonical IR.\n for (const tagName of [\"displayName\", \"format\", \"placeholder\"]) {\n config.addTagDefinition(\n new TSDocTagDefinition({\n tagName: \"@\" + tagName,\n syntaxKind: TSDocTagSyntaxKind.BlockTag,\n allowMultiple: true,\n })\n );\n }\n\n for (const tagName of extensionTagNames) {\n config.addTagDefinition(\n new TSDocTagDefinition({\n tagName: \"@\" + tagName,\n syntaxKind: TSDocTagSyntaxKind.BlockTag,\n allowMultiple: true,\n })\n );\n }\n\n return config;\n}\n\nfunction sharedCommentSyntaxOptions(\n options?: ParseTSDocOptions,\n offset?: number\n): NonNullable<Parameters<typeof parseCommentBlock>[1]> {\n const extensions = options?.extensionRegistry?.extensions;\n return {\n ...(offset !== undefined ? { offset } : {}),\n ...(extensions !== undefined ? { extensions } : {}),\n };\n}\n\nfunction sharedTagValueOptions(options?: ParseTSDocOptions) {\n return {\n ...(options?.extensionRegistry !== undefined ? { registry: options.extensionRegistry } : {}),\n ...(options?.fieldType !== undefined ? { fieldType: options.fieldType } : {}),\n };\n}\n\nconst SYNTHETIC_TYPE_FORMAT_FLAGS =\n ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope;\n\nfunction collectImportedNames(sourceFile: ts.SourceFile): ReadonlySet<string> {\n const importedNames = new Set<string>();\n\n for (const statement of sourceFile.statements) {\n if (ts.isImportDeclaration(statement) && statement.importClause !== undefined) {\n const clause = statement.importClause;\n if (clause.name !== undefined) {\n importedNames.add(clause.name.text);\n }\n if (clause.namedBindings !== undefined) {\n if (ts.isNamedImports(clause.namedBindings)) {\n for (const specifier of clause.namedBindings.elements) {\n importedNames.add(specifier.name.text);\n }\n } else if (ts.isNamespaceImport(clause.namedBindings)) {\n importedNames.add(clause.namedBindings.name.text);\n }\n }\n continue;\n }\n\n if (ts.isImportEqualsDeclaration(statement)) {\n importedNames.add(statement.name.text);\n }\n }\n\n return importedNames;\n}\n\nfunction isNonReferenceIdentifier(node: ts.Identifier): boolean {\n const parent = node.parent;\n\n if (\n (ts.isBindingElement(parent) ||\n ts.isClassDeclaration(parent) ||\n ts.isEnumDeclaration(parent) ||\n ts.isEnumMember(parent) ||\n ts.isFunctionDeclaration(parent) ||\n ts.isFunctionExpression(parent) ||\n ts.isImportClause(parent) ||\n ts.isImportEqualsDeclaration(parent) ||\n ts.isImportSpecifier(parent) ||\n ts.isInterfaceDeclaration(parent) ||\n ts.isMethodDeclaration(parent) ||\n ts.isMethodSignature(parent) ||\n ts.isModuleDeclaration(parent) ||\n ts.isNamespaceExport(parent) ||\n ts.isNamespaceImport(parent) ||\n ts.isParameter(parent) ||\n ts.isPropertyDeclaration(parent) ||\n ts.isPropertySignature(parent) ||\n ts.isSetAccessorDeclaration(parent) ||\n ts.isGetAccessorDeclaration(parent) ||\n ts.isTypeAliasDeclaration(parent) ||\n ts.isTypeParameterDeclaration(parent) ||\n ts.isVariableDeclaration(parent)) &&\n parent.name === node\n ) {\n return true;\n }\n\n if (\n (ts.isPropertyAssignment(parent) || ts.isPropertyAccessExpression(parent)) &&\n parent.name === node\n ) {\n return true;\n }\n\n if (ts.isQualifiedName(parent) && parent.right === node) {\n return true;\n }\n\n return false;\n}\n\nfunction statementReferencesImportedName(\n statement: ts.Statement,\n importedNames: ReadonlySet<string>\n): boolean {\n let referencesImportedName = false;\n\n const visit = (node: ts.Node): void => {\n if (referencesImportedName) {\n return;\n }\n\n if (ts.isIdentifier(node) && importedNames.has(node.text) && !isNonReferenceIdentifier(node)) {\n referencesImportedName = true;\n return;\n }\n\n ts.forEachChild(node, visit);\n };\n\n visit(statement);\n return referencesImportedName;\n}\n\nfunction buildSupportingDeclarations(sourceFile: ts.SourceFile): readonly string[] {\n const importedNames = collectImportedNames(sourceFile);\n\n return sourceFile.statements\n .filter((statement) => {\n // Always exclude imports and re-exports\n if (ts.isImportDeclaration(statement)) return false;\n if (ts.isImportEqualsDeclaration(statement)) return false;\n if (ts.isExportDeclaration(statement) && statement.moduleSpecifier !== undefined)\n return false;\n\n // Skip declarations whose AST references an imported identifier.\n // This prevents the synthetic program from emitting errors about\n // unresolvable imported types without falsely matching comments,\n // string literals, or unrelated property names.\n if (importedNames.size > 0 && statementReferencesImportedName(statement, importedNames)) {\n return false;\n }\n\n return true;\n })\n .map((statement) => statement.getText(sourceFile));\n}\n\nfunction renderSyntheticArgumentExpression(\n valueKind: FormSpecValueKind | null,\n argumentText: string\n): string | null {\n const trimmed = argumentText.trim();\n if (trimmed === \"\") {\n return null;\n }\n\n switch (valueKind) {\n case \"number\":\n case \"integer\":\n case \"signedInteger\":\n return Number.isFinite(Number(trimmed)) ? trimmed : JSON.stringify(trimmed);\n case \"string\":\n return JSON.stringify(argumentText);\n case \"json\":\n try {\n JSON.parse(trimmed);\n return `(${trimmed})`;\n } catch {\n return JSON.stringify(trimmed);\n }\n case \"boolean\":\n return trimmed === \"true\" || trimmed === \"false\" ? trimmed : JSON.stringify(trimmed);\n case \"condition\":\n return \"undefined as unknown as FormSpecCondition\";\n case null:\n return null;\n default: {\n return String(valueKind);\n }\n }\n}\n\nfunction getArrayElementType(type: ts.Type, checker: ts.TypeChecker): ts.Type | null {\n if (!checker.isArrayType(type)) {\n return null;\n }\n\n return checker.getTypeArguments(type as ts.TypeReference)[0] ?? null;\n}\n\nfunction supportsConstraintCapability(\n type: ts.Type,\n checker: ts.TypeChecker,\n capability: SemanticCapability | undefined\n): boolean {\n if (capability === undefined) {\n return true;\n }\n\n if (hasTypeSemanticCapability(type, checker, capability)) {\n return true;\n }\n\n if (capability === \"string-like\") {\n const itemType = getArrayElementType(type, checker);\n return itemType !== null && hasTypeSemanticCapability(itemType, checker, capability);\n }\n\n return false;\n}\n\nfunction makeDiagnostic(\n code: string,\n message: string,\n provenance: Provenance\n): ConstraintSemanticDiagnostic {\n return {\n code,\n message,\n severity: \"error\",\n primaryLocation: provenance,\n relatedLocations: [],\n };\n}\n\nfunction placementLabel(\n placement: NonNullable<ReturnType<typeof resolveDeclarationPlacement>>\n): string {\n switch (placement) {\n case \"class\":\n return \"class declarations\";\n case \"class-field\":\n return \"class fields\";\n case \"class-method\":\n return \"class methods\";\n case \"interface\":\n return \"interface declarations\";\n case \"interface-field\":\n return \"interface fields\";\n case \"type-alias\":\n return \"type aliases\";\n case \"type-alias-field\":\n return \"type-alias properties\";\n case \"variable\":\n return \"variables\";\n case \"function\":\n return \"functions\";\n case \"function-parameter\":\n return \"function parameters\";\n case \"method-parameter\":\n return \"method parameters\";\n default: {\n const exhaustive: never = placement;\n return String(exhaustive);\n }\n }\n}\n\nfunction capabilityLabel(capability: string | undefined): string {\n switch (capability) {\n case \"numeric-comparable\":\n return \"number\";\n case \"string-like\":\n return \"string\";\n case \"array-like\":\n return \"array\";\n case \"enum-member-addressable\":\n return \"enum\";\n case \"json-like\":\n return \"JSON-compatible\";\n case \"object-like\":\n return \"object\";\n case \"condition-like\":\n return \"conditional\";\n case undefined:\n return \"compatible\";\n default:\n return capability;\n }\n}\n\nfunction getBroadenedCustomTypeId(fieldType: TypeNode | undefined): string | undefined {\n if (fieldType?.kind === \"custom\") {\n return fieldType.typeId;\n }\n\n if (fieldType?.kind !== \"union\") {\n return undefined;\n }\n\n const customMembers = fieldType.members.filter(\n (member): member is Extract<TypeNode, { kind: \"custom\" }> => member.kind === \"custom\"\n );\n if (customMembers.length !== 1) {\n return undefined;\n }\n\n const nonCustomMembers = fieldType.members.filter((member) => member.kind !== \"custom\");\n const allOtherMembersAreNull = nonCustomMembers.every(\n (member) => member.kind === \"primitive\" && member.primitiveKind === \"null\"\n );\n const customMember = customMembers[0];\n return allOtherMembersAreNull && customMember !== undefined ? customMember.typeId : undefined;\n}\n\nfunction hasBuiltinConstraintBroadening(tagName: string, options?: ParseTSDocOptions): boolean {\n const broadenedTypeId = getBroadenedCustomTypeId(options?.fieldType);\n return (\n broadenedTypeId !== undefined &&\n options?.extensionRegistry?.findBuiltinConstraintBroadening(broadenedTypeId, tagName) !==\n undefined\n );\n}\n\nfunction buildCompilerBackedConstraintDiagnostics(\n node: ts.Node,\n sourceFile: ts.SourceFile,\n tagName: string,\n parsedTag: ParsedCommentTag | null,\n provenance: Provenance,\n supportingDeclarations: readonly string[],\n options?: ParseTSDocOptions\n): readonly ConstraintSemanticDiagnostic[] {\n if (!isBuiltinConstraintName(tagName)) {\n return [];\n }\n\n const checker = options?.checker;\n const subjectType = options?.subjectType;\n if (checker === undefined || subjectType === undefined) {\n return [];\n }\n\n const placement = resolveDeclarationPlacement(node);\n if (placement === null) {\n return [];\n }\n\n const definition = getTagDefinition(tagName, options?.extensionRegistry?.extensions);\n if (definition === null) {\n return [];\n }\n\n if (!definition.placements.includes(placement)) {\n return [\n makeDiagnostic(\n \"INVALID_TAG_PLACEMENT\",\n `Tag \"@${tagName}\" is not allowed on ${placementLabel(placement)}.`,\n provenance\n ),\n ];\n }\n\n const target = parsedTag?.target ?? null;\n const hasBroadening = target === null && hasBuiltinConstraintBroadening(tagName, options);\n if (target !== null) {\n if (target.kind !== \"path\") {\n return [\n makeDiagnostic(\n \"UNSUPPORTED_TARGETING_SYNTAX\",\n `Tag \"@${tagName}\" does not support ${target.kind} targeting syntax.`,\n provenance\n ),\n ];\n }\n\n if (!target.valid || target.path === null) {\n return [\n makeDiagnostic(\n \"UNSUPPORTED_TARGETING_SYNTAX\",\n `Tag \"@${tagName}\" has invalid path targeting syntax.`,\n provenance\n ),\n ];\n }\n\n const resolution = resolvePathTargetType(subjectType, checker, target.path.segments);\n if (resolution.kind === \"missing-property\") {\n return [\n makeDiagnostic(\n \"UNKNOWN_PATH_TARGET\",\n `Target \"${target.rawText}\": path-targeted constraint \"${tagName}\" references unknown path segment \"${resolution.segment}\"`,\n provenance\n ),\n ];\n }\n\n if (resolution.kind === \"unresolvable\") {\n const actualType = checker.typeToString(resolution.type, node, SYNTHETIC_TYPE_FORMAT_FLAGS);\n return [\n makeDiagnostic(\n \"TYPE_MISMATCH\",\n `Target \"${target.rawText}\": path-targeted constraint \"${tagName}\" is invalid because type \"${actualType}\" cannot be traversed`,\n provenance\n ),\n ];\n }\n\n const requiredCapability = definition.capabilities[0];\n if (\n requiredCapability !== undefined &&\n !supportsConstraintCapability(resolution.type, checker, requiredCapability)\n ) {\n const actualType = checker.typeToString(resolution.type, node, SYNTHETIC_TYPE_FORMAT_FLAGS);\n return [\n makeDiagnostic(\n \"TYPE_MISMATCH\",\n `Target \"${target.rawText}\": constraint \"${tagName}\" is only valid on ${capabilityLabel(requiredCapability)} targets, but field type is \"${actualType}\"`,\n provenance\n ),\n ];\n }\n } else if (!hasBroadening) {\n const requiredCapability = definition.capabilities[0];\n if (\n requiredCapability !== undefined &&\n !supportsConstraintCapability(subjectType, checker, requiredCapability)\n ) {\n const actualType = checker.typeToString(subjectType, node, SYNTHETIC_TYPE_FORMAT_FLAGS);\n return [\n makeDiagnostic(\n \"TYPE_MISMATCH\",\n `Target \"${node.getText(sourceFile)}\": constraint \"${tagName}\" is only valid on ${capabilityLabel(requiredCapability)} targets, but field type is \"${actualType}\"`,\n provenance\n ),\n ];\n }\n }\n\n const argumentExpression = renderSyntheticArgumentExpression(\n definition.valueKind,\n parsedTag?.argumentText ?? \"\"\n );\n if (definition.requiresArgument && argumentExpression === null) {\n return [];\n }\n\n if (hasBroadening) {\n return [];\n }\n\n const subjectTypeText = checker.typeToString(subjectType, node, SYNTHETIC_TYPE_FORMAT_FLAGS);\n const hostType = options?.hostType ?? subjectType;\n const hostTypeText = checker.typeToString(hostType, node, SYNTHETIC_TYPE_FORMAT_FLAGS);\n const result = checkSyntheticTagApplication({\n tagName,\n placement,\n hostType: hostTypeText,\n subjectType: subjectTypeText,\n ...(target?.kind === \"path\" ? { target: { kind: \"path\" as const, text: target.rawText } } : {}),\n ...(argumentExpression !== null ? { argumentExpression } : {}),\n supportingDeclarations,\n ...(options?.extensionRegistry !== undefined\n ? {\n extensions: options.extensionRegistry.extensions.map((extension) => ({\n extensionId: extension.extensionId,\n ...(extension.constraintTags !== undefined\n ? {\n constraintTags: extension.constraintTags.map((tag) => ({ tagName: tag.tagName })),\n }\n : {}),\n })),\n }\n : {}),\n });\n\n if (result.diagnostics.length === 0) {\n return [];\n }\n\n const expectedLabel =\n definition.valueKind === null ? \"compatible argument\" : capabilityLabel(definition.valueKind);\n return [\n makeDiagnostic(\n \"TYPE_MISMATCH\",\n `Tag \"@${tagName}\" received an invalid argument for ${expectedLabel}.`,\n provenance\n ),\n ];\n}\n\n/**\n * Shared parser instance — thread-safe because TSDocParser is stateless;\n * all parse state lives in the returned ParserContext.\n */\nconst parserCache = new Map<string, TSDocParser>();\nconst parseResultCache = new Map<string, TSDocParseResult>();\n\nfunction getParser(options?: ParseTSDocOptions): TSDocParser {\n const extensionTagNames = [\n ...(options?.extensionRegistry?.extensions.flatMap((extension) =>\n (extension.constraintTags ?? []).map((tag) => tag.tagName)\n ) ?? []),\n ].sort();\n const cacheKey = extensionTagNames.join(\"|\");\n const existing = parserCache.get(cacheKey);\n if (existing) {\n return existing;\n }\n\n const parser = new TSDocParser(createFormSpecTSDocConfig(extensionTagNames));\n parserCache.set(cacheKey, parser);\n return parser;\n}\n\n// =============================================================================\n// PUBLIC API\n// =============================================================================\n\n/**\n * Result of parsing a single JSDoc comment attached to a TS AST node.\n */\nexport interface TSDocParseResult {\n /** Constraint IR nodes extracted from custom block tags. */\n readonly constraints: readonly ConstraintNode[];\n /** Annotation IR nodes extracted from canonical TSDoc block tags. */\n readonly annotations: readonly AnnotationNode[];\n /** Compiler-backed extraction diagnostics for invalid tag applications. */\n readonly diagnostics: readonly ConstraintSemanticDiagnostic[];\n}\n\n/**\n * Optional extension-aware parsing inputs for TSDoc extraction.\n */\nexport interface ParseTSDocOptions {\n /**\n * Extension registry used to resolve custom tags and custom-type-specific\n * broadening of built-in constraint tags.\n */\n readonly extensionRegistry?: ExtensionRegistry;\n /**\n * Effective field/type node for the declaration being parsed. Required when\n * built-in tags may broaden onto a custom type.\n */\n readonly fieldType?: TypeNode;\n /** Type checker used for compiler-backed placement and type validation. */\n readonly checker?: ts.TypeChecker;\n /** The declaration type that the parsed tag applies to. */\n readonly subjectType?: ts.Type;\n /** Optional enclosing host type for future cross-field signature checks. */\n readonly hostType?: ts.Type;\n}\n\n/**\n * Display-name metadata extracted from a node's JSDoc tags.\n *\n * The root display name is returned separately from member-target labels so\n * callers can apply the former to the enclosing type/form and the latter to\n * enum members.\n */\nexport interface DisplayNameMetadata {\n readonly displayName?: string;\n readonly memberDisplayNames: ReadonlyMap<string, string>;\n}\n\nfunction getExtensionRegistryCacheKey(registry: ExtensionRegistry | undefined): string {\n if (registry === undefined) {\n return \"\";\n }\n\n return registry.extensions\n .map((extension) =>\n JSON.stringify({\n extensionId: extension.extensionId,\n typeNames: extension.types?.map((type) => type.typeName) ?? [],\n constraintTags: extension.constraintTags?.map((tag) => tag.tagName) ?? [],\n })\n )\n .join(\"|\");\n}\n\nfunction getParseCacheKey(\n node: ts.Node,\n file: string,\n options: ParseTSDocOptions | undefined\n): string {\n const sourceFile = node.getSourceFile();\n const checker = options?.checker;\n return JSON.stringify({\n file,\n sourceFile: sourceFile.fileName,\n sourceText: sourceFile.text,\n start: node.getFullStart(),\n end: node.getEnd(),\n fieldType: options?.fieldType ?? null,\n subjectType:\n checker !== undefined && options?.subjectType !== undefined\n ? checker.typeToString(options.subjectType, node, SYNTHETIC_TYPE_FORMAT_FLAGS)\n : null,\n hostType:\n checker !== undefined && options?.hostType !== undefined\n ? checker.typeToString(options.hostType, node, SYNTHETIC_TYPE_FORMAT_FLAGS)\n : null,\n extensions: getExtensionRegistryCacheKey(options?.extensionRegistry),\n });\n}\n\n/**\n * Parses the JSDoc comment attached to a TypeScript AST node using the\n * official TSDoc parser and returns canonical IR constraint and annotation\n * nodes.\n *\n * For constraint tags (`@minimum`, `@pattern`, `@enumOptions`, etc.),\n * the structured TSDoc parser is used. Canonical annotation tags\n * (`@displayName`) are also parsed structurally. Summary text and `@remarks`\n * are extracted as separate annotation nodes.\n *\n * @param node - The TS AST node to inspect (PropertyDeclaration, PropertySignature, etc.)\n * @param file - Absolute source file path for provenance\n * @returns Parsed constraint and annotation nodes\n */\nexport function parseTSDocTags(\n node: ts.Node,\n file = \"\",\n options?: ParseTSDocOptions\n): TSDocParseResult {\n const cacheKey = getParseCacheKey(node, file, options);\n const cached = parseResultCache.get(cacheKey);\n if (cached !== undefined) {\n return cached;\n }\n\n const constraints: ConstraintNode[] = [];\n const annotations: AnnotationNode[] = [];\n const diagnostics: ConstraintSemanticDiagnostic[] = [];\n let displayName: string | undefined;\n let placeholder: string | undefined;\n let displayNameProvenance: Provenance | undefined;\n let placeholderProvenance: Provenance | undefined;\n const rawTextTags: {\n readonly tag: ParsedCommentTag;\n readonly commentText: string;\n readonly commentOffset: number;\n }[] = [];\n\n // ----- Phase 1: TSDoc structural parse for constraint tags -----\n const sourceFile = node.getSourceFile();\n const sourceText = sourceFile.getFullText();\n const supportingDeclarations = buildSupportingDeclarations(sourceFile);\n const commentRanges = ts.getLeadingCommentRanges(sourceText, node.getFullStart());\n const rawTextFallbacks = collectRawTextFallbacks(node, file);\n\n if (commentRanges) {\n for (const range of commentRanges) {\n // Only parse /** ... */ comments (kind 3 = MultiLineCommentTrivia)\n if (range.kind !== ts.SyntaxKind.MultiLineCommentTrivia) {\n continue;\n }\n const commentText = sourceText.substring(range.pos, range.end);\n if (!commentText.startsWith(\"/**\")) {\n continue;\n }\n\n const parser = getParser(options);\n const parserContext = parser.parseRange(\n TextRange.fromStringRange(sourceText, range.pos, range.end)\n );\n const docComment = parserContext.docComment;\n const parsedComment = parseCommentBlock(\n commentText,\n sharedCommentSyntaxOptions(options, range.pos)\n );\n let parsedTagCursor = 0;\n\n const nextParsedTag = (normalizedTagName: string) => {\n while (parsedTagCursor < parsedComment.tags.length) {\n const candidate = parsedComment.tags[parsedTagCursor];\n parsedTagCursor += 1;\n if (candidate?.normalizedTagName === normalizedTagName) {\n return candidate;\n }\n }\n return null;\n };\n\n for (const parsedTag of parsedComment.tags) {\n if (TAGS_REQUIRING_RAW_TEXT.has(parsedTag.normalizedTagName)) {\n rawTextTags.push({ tag: parsedTag, commentText, commentOffset: range.pos });\n }\n }\n\n // Extract constraint nodes from custom blocks.\n // Tags in TAGS_REQUIRING_RAW_TEXT are skipped here and handled via the\n // TS compiler API in Phase 1b below.\n for (const block of docComment.customBlocks) {\n const tagName = normalizeConstraintTagName(block.blockTag.tagName.substring(1)); // Remove leading @ and normalize to camelCase\n const parsedTag = nextParsedTag(tagName);\n if (tagName === \"displayName\" || tagName === \"format\" || tagName === \"placeholder\") {\n const text = getBestBlockPayloadText(parsedTag, commentText, range.pos, block);\n if (text === \"\") continue;\n\n const provenance =\n parsedTag !== null\n ? provenanceForParsedTag(parsedTag, sourceFile, file)\n : provenanceForComment(range, sourceFile, file, tagName);\n switch (tagName) {\n case \"displayName\":\n if (!isMemberTargetDisplayName(text) && displayName === undefined) {\n displayName = text;\n displayNameProvenance = provenance;\n }\n break;\n\n case \"format\":\n annotations.push({\n kind: \"annotation\",\n annotationKind: \"format\",\n value: text,\n provenance,\n });\n break;\n\n case \"placeholder\":\n if (placeholder === undefined) {\n placeholder = text;\n placeholderProvenance = provenance;\n }\n break;\n }\n continue;\n }\n\n if (TAGS_REQUIRING_RAW_TEXT.has(tagName)) continue;\n\n const text = getBestBlockPayloadText(parsedTag, commentText, range.pos, block);\n const expectedType = isBuiltinConstraintName(tagName)\n ? BUILTIN_CONSTRAINT_DEFINITIONS[tagName]\n : undefined;\n if (text === \"\" && expectedType !== \"boolean\") continue;\n\n const provenance =\n parsedTag !== null\n ? provenanceForParsedTag(parsedTag, sourceFile, file)\n : provenanceForComment(range, sourceFile, file, tagName);\n const compilerDiagnostics = buildCompilerBackedConstraintDiagnostics(\n node,\n sourceFile,\n tagName,\n parsedTag,\n provenance,\n supportingDeclarations,\n options\n );\n if (compilerDiagnostics.length > 0) {\n diagnostics.push(...compilerDiagnostics);\n continue;\n }\n const constraintNode = parseConstraintTagValue(\n tagName,\n text,\n provenance,\n sharedTagValueOptions(options)\n );\n if (constraintNode) {\n constraints.push(constraintNode);\n }\n }\n\n // Extract @deprecated from the standard deprecated block\n if (docComment.deprecatedBlock !== undefined) {\n const message = extractBlockText(docComment.deprecatedBlock).trim();\n annotations.push({\n kind: \"annotation\",\n annotationKind: \"deprecated\",\n ...(message !== \"\" && { message }),\n provenance: provenanceForComment(range, sourceFile, file, \"deprecated\"),\n });\n }\n\n // Summary text → description annotation (spec 002 §2.3)\n {\n const summary = extractPlainText(docComment.summarySection).trim();\n if (summary !== \"\") {\n annotations.push({\n kind: \"annotation\",\n annotationKind: \"description\",\n value: summary,\n provenance: provenanceForComment(range, sourceFile, file, \"summary\"),\n });\n }\n }\n\n // @remarks → separate remarks annotation (spec 002 §2.3)\n if (docComment.remarksBlock !== undefined) {\n const remarksText = extractBlockText(docComment.remarksBlock).trim();\n if (remarksText !== \"\") {\n annotations.push({\n kind: \"annotation\",\n annotationKind: \"remarks\",\n value: remarksText,\n provenance: provenanceForComment(range, sourceFile, file, \"remarks\"),\n });\n }\n }\n }\n }\n\n if (displayName !== undefined && displayNameProvenance !== undefined) {\n annotations.push({\n kind: \"annotation\",\n annotationKind: \"displayName\",\n value: displayName,\n provenance: displayNameProvenance,\n });\n }\n\n if (placeholder !== undefined && placeholderProvenance !== undefined) {\n annotations.push({\n kind: \"annotation\",\n annotationKind: \"placeholder\",\n value: placeholder,\n provenance: placeholderProvenance,\n });\n }\n\n // ----- Phase 1b: TS compiler API for tags with TSDoc-incompatible content -----\n // @pattern, @enumOptions, and @defaultValue content can contain `@`, `{}`,\n // or quoted JSON payloads that the TSDoc parser treats as structural markers.\n // Prefer the shared syntax parse for these payloads and fall back to the\n // TS compiler API when a raw payload cannot be recovered from comments.\n if (rawTextTags.length > 0) {\n for (const rawTextTag of rawTextTags) {\n const fallbackQueue = rawTextFallbacks.get(rawTextTag.tag.normalizedTagName);\n const fallback = fallbackQueue?.shift();\n const text = choosePreferredPayloadText(\n getSharedPayloadText(rawTextTag.tag, rawTextTag.commentText, rawTextTag.commentOffset),\n fallback?.text ?? \"\"\n );\n if (text === \"\") continue;\n\n const provenance = provenanceForParsedTag(rawTextTag.tag, sourceFile, file);\n if (rawTextTag.tag.normalizedTagName === \"defaultValue\") {\n const defaultValueNode = parseDefaultValueTagValue(text, provenance);\n annotations.push(defaultValueNode);\n continue;\n }\n\n const compilerDiagnostics = buildCompilerBackedConstraintDiagnostics(\n node,\n sourceFile,\n rawTextTag.tag.normalizedTagName,\n rawTextTag.tag,\n provenance,\n supportingDeclarations,\n options\n );\n if (compilerDiagnostics.length > 0) {\n diagnostics.push(...compilerDiagnostics);\n continue;\n }\n\n const constraintNode = parseConstraintTagValue(\n rawTextTag.tag.normalizedTagName,\n text,\n provenance,\n sharedTagValueOptions(options)\n );\n if (constraintNode) {\n constraints.push(constraintNode);\n }\n }\n }\n\n for (const [tagName, fallbacks] of rawTextFallbacks) {\n for (const fallback of fallbacks) {\n const text = fallback.text.trim();\n if (text === \"\") continue;\n\n const provenance = fallback.provenance;\n if (tagName === \"defaultValue\") {\n const defaultValueNode = parseDefaultValueTagValue(text, provenance);\n annotations.push(defaultValueNode);\n continue;\n }\n\n const compilerDiagnostics = buildCompilerBackedConstraintDiagnostics(\n node,\n sourceFile,\n tagName,\n null,\n provenance,\n supportingDeclarations,\n options\n );\n if (compilerDiagnostics.length > 0) {\n diagnostics.push(...compilerDiagnostics);\n continue;\n }\n\n const constraintNode = parseConstraintTagValue(\n tagName,\n text,\n provenance,\n sharedTagValueOptions(options)\n );\n if (constraintNode) {\n constraints.push(constraintNode);\n }\n }\n }\n\n const result = { constraints, annotations, diagnostics };\n parseResultCache.set(cacheKey, result);\n return result;\n}\n\n/**\n * Checks if a TS AST node has a `@deprecated` tag using the TSDoc parser.\n *\n * Falls back to the TS compiler API for nodes without doc comments.\n */\nexport function hasDeprecatedTagTSDoc(node: ts.Node): boolean {\n const sourceFile = node.getSourceFile();\n const sourceText = sourceFile.getFullText();\n const commentRanges = ts.getLeadingCommentRanges(sourceText, node.getFullStart());\n\n if (commentRanges) {\n for (const range of commentRanges) {\n if (range.kind !== ts.SyntaxKind.MultiLineCommentTrivia) continue;\n const commentText = sourceText.substring(range.pos, range.end);\n if (!commentText.startsWith(\"/**\")) continue;\n\n const parser = getParser();\n const parserContext = parser.parseRange(\n TextRange.fromStringRange(sourceText, range.pos, range.end)\n );\n if (parserContext.docComment.deprecatedBlock !== undefined) {\n return true;\n }\n }\n }\n\n return false;\n}\n\n/**\n * Extracts root and member-target display-name metadata from a node's JSDoc tags.\n *\n * Member-target display-name tags use the syntax `@displayName :member Label`.\n * The first non-target `@displayName` is returned as the root display name.\n */\nexport function extractDisplayNameMetadata(node: ts.Node): DisplayNameMetadata {\n let displayName: string | undefined;\n const memberDisplayNames = new Map<string, string>();\n const sourceFile = node.getSourceFile();\n const sourceText = sourceFile.getFullText();\n const commentRanges = ts.getLeadingCommentRanges(sourceText, node.getFullStart());\n\n if (commentRanges) {\n for (const range of commentRanges) {\n if (range.kind !== ts.SyntaxKind.MultiLineCommentTrivia) continue;\n const commentText = sourceText.substring(range.pos, range.end);\n if (!commentText.startsWith(\"/**\")) continue;\n\n const parsed = parseCommentBlock(commentText);\n for (const tag of parsed.tags) {\n if (tag.normalizedTagName !== \"displayName\") {\n continue;\n }\n\n if (tag.target !== null && tag.argumentText !== \"\") {\n memberDisplayNames.set(tag.target.rawText, tag.argumentText);\n continue;\n }\n\n if (tag.argumentText !== \"\") {\n displayName ??= tag.argumentText;\n }\n }\n }\n }\n\n return {\n ...(displayName !== undefined && { displayName }),\n memberDisplayNames,\n };\n}\n\n// =============================================================================\n// PUBLIC HELPERS — path target extraction\n// =============================================================================\n\n/**\n * Extracts a path-target prefix (`:fieldName`) from constraint tag text.\n * Returns the parsed PathTarget and remaining text, or null if no path target.\n *\n * @example\n * extractPathTarget(\":value 0\") // → { path: { segments: [\"value\"] }, remainingText: \"0\" }\n * extractPathTarget(\"42\") // → null\n */\nexport function extractPathTarget(\n text: string\n): { path: PathTarget; remainingText: string } | null {\n return extractSharedPathTarget(text);\n}\n\n// =============================================================================\n// PRIVATE HELPERS — TSDoc text extraction\n// =============================================================================\n\n/**\n * Recursively extracts plain text content from a TSDoc DocNode tree.\n *\n * Walks child nodes and concatenates DocPlainText and DocSoftBreak content.\n */\nfunction extractBlockText(block: DocBlock): string {\n return extractPlainText(block.content);\n}\n\nfunction extractPlainText(node: DocNode): string {\n let result = \"\";\n if (node instanceof DocExcerpt) {\n return node.content.toString();\n }\n if (node instanceof DocPlainText) {\n return node.text;\n }\n if (node instanceof DocSoftBreak) {\n return \" \";\n }\n if (typeof node.getChildNodes === \"function\") {\n for (const child of node.getChildNodes()) {\n result += extractPlainText(child);\n }\n }\n return result;\n}\n\nfunction choosePreferredPayloadText(primary: string, fallback: string): string {\n const preferred = primary.trim();\n const alternate = fallback.trim();\n\n if (preferred === \"\") return alternate;\n if (alternate === \"\") return preferred;\n if (alternate.includes(\"\\n\")) return alternate;\n if (alternate.length > preferred.length && alternate.startsWith(preferred)) {\n return alternate;\n }\n\n return preferred;\n}\n\nfunction getSharedPayloadText(\n tag: ParsedCommentTag,\n commentText: string,\n commentOffset: number\n): string {\n if (tag.payloadSpan === null) {\n return \"\";\n }\n\n return sliceCommentSpan(commentText, tag.payloadSpan, {\n offset: commentOffset,\n }).trim();\n}\n\nfunction getBestBlockPayloadText(\n tag: ParsedCommentTag | null,\n commentText: string,\n commentOffset: number,\n block: DocBlock\n): string {\n const sharedText = tag === null ? \"\" : getSharedPayloadText(tag, commentText, commentOffset);\n const blockText = extractBlockText(block).replace(/\\s+/g, \" \").trim();\n return choosePreferredPayloadText(sharedText, blockText);\n}\n\nfunction collectRawTextFallbacks(\n node: ts.Node,\n file: string\n): Map<string, { text: string; provenance: Provenance }[]> {\n const fallbacks = new Map<string, { text: string; provenance: Provenance }[]>();\n\n for (const tag of ts.getJSDocTags(node)) {\n const tagName = normalizeConstraintTagName(tag.tagName.text);\n if (!TAGS_REQUIRING_RAW_TEXT.has(tagName)) continue;\n\n const commentText = getTagCommentText(tag)?.trim() ?? \"\";\n if (commentText === \"\") continue;\n\n const entries = fallbacks.get(tagName) ?? [];\n entries.push({\n text: commentText,\n provenance: provenanceForJSDocTag(tag, file),\n });\n fallbacks.set(tagName, entries);\n }\n\n return fallbacks;\n}\n\n// =============================================================================\n// PRIVATE HELPERS — constraint value parsing\n// =============================================================================\n\nfunction isMemberTargetDisplayName(text: string): boolean {\n return parseTagSyntax(\"displayName\", text).target !== null;\n}\n\n// =============================================================================\n// PRIVATE HELPERS — provenance\n// =============================================================================\n\nfunction provenanceForComment(\n range: ts.CommentRange,\n sourceFile: ts.SourceFile,\n file: string,\n tagName: string\n): Provenance {\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(range.pos);\n return {\n surface: \"tsdoc\",\n file,\n line: line + 1,\n column: character,\n tagName: \"@\" + tagName,\n };\n}\n\nfunction provenanceForParsedTag(\n tag: ParsedCommentTag,\n sourceFile: ts.SourceFile,\n file: string\n): Provenance {\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(tag.tagNameSpan.start);\n return {\n surface: \"tsdoc\",\n file,\n line: line + 1,\n column: character,\n tagName: \"@\" + tag.normalizedTagName,\n };\n}\n\nfunction provenanceForJSDocTag(tag: ts.JSDocTag, file: string): Provenance {\n const sourceFile = tag.getSourceFile();\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(tag.getStart());\n return {\n surface: \"tsdoc\",\n file,\n line: line + 1,\n column: character,\n tagName: \"@\" + tag.tagName.text,\n };\n}\n\n/**\n * Extracts the text content from a TypeScript JSDoc tag's comment.\n */\nfunction getTagCommentText(tag: ts.JSDocTag): string | undefined {\n if (tag.comment === undefined) {\n return undefined;\n }\n if (typeof tag.comment === \"string\") {\n return tag.comment;\n }\n return ts.getTextOfJSDocComment(tag.comment);\n}\n","/**\n * Constraint validator for the FormSpec IR.\n *\n * Delegates target-centric semantic analysis to `@formspec/analysis` so build\n * validation and editor tooling share the same inheritance, path-target,\n * contradiction, and broadening semantics.\n *\n * @packageDocumentation\n */\n\nimport {\n analyzeConstraintTargets,\n type ConstraintRegistryLike,\n type ConstraintSemanticDiagnostic,\n} from \"@formspec/analysis/internal\";\nimport type { FormIR, FormIRElement, FieldNode, ObjectProperty } from \"@formspec/core/internals\";\nimport type { ExtensionRegistry } from \"../extensions/index.js\";\n\nexport type ValidationDiagnostic = ConstraintSemanticDiagnostic;\n\nexport interface ValidationResult {\n readonly diagnostics: readonly ValidationDiagnostic[];\n readonly valid: boolean;\n}\n\nexport interface ValidateIROptions {\n readonly vendorPrefix?: string;\n readonly extensionRegistry?: ExtensionRegistry;\n}\n\ninterface ValidationContext {\n readonly diagnostics: ValidationDiagnostic[];\n readonly extensionRegistry: ConstraintRegistryLike | undefined;\n readonly typeRegistry: FormIR[\"typeRegistry\"];\n}\n\nfunction validateFieldNode(ctx: ValidationContext, field: FieldNode): void {\n const analysis = analyzeConstraintTargets(\n field.name,\n field.type,\n field.constraints,\n ctx.typeRegistry,\n ctx.extensionRegistry === undefined\n ? undefined\n : {\n extensionRegistry: ctx.extensionRegistry,\n }\n );\n ctx.diagnostics.push(...analysis.diagnostics);\n\n if (field.type.kind === \"object\") {\n for (const property of field.type.properties) {\n validateObjectProperty(ctx, field.name, property);\n }\n }\n}\n\nfunction validateObjectProperty(\n ctx: ValidationContext,\n parentName: string,\n property: ObjectProperty\n): void {\n const qualifiedName = `${parentName}.${property.name}`;\n const analysis = analyzeConstraintTargets(\n qualifiedName,\n property.type,\n property.constraints,\n ctx.typeRegistry,\n ctx.extensionRegistry === undefined\n ? undefined\n : {\n extensionRegistry: ctx.extensionRegistry,\n }\n );\n ctx.diagnostics.push(...analysis.diagnostics);\n\n if (property.type.kind === \"object\") {\n for (const nestedProperty of property.type.properties) {\n validateObjectProperty(ctx, qualifiedName, nestedProperty);\n }\n }\n}\n\nfunction validateElement(ctx: ValidationContext, element: FormIRElement): void {\n switch (element.kind) {\n case \"field\":\n validateFieldNode(ctx, element);\n break;\n case \"group\":\n for (const child of element.elements) {\n validateElement(ctx, child);\n }\n break;\n case \"conditional\":\n for (const child of element.elements) {\n validateElement(ctx, child);\n }\n break;\n default: {\n const exhaustive: never = element;\n throw new Error(`Unhandled element kind: ${String(exhaustive)}`);\n }\n }\n}\n\nexport function validateIR(ir: FormIR, options?: ValidateIROptions): ValidationResult {\n const ctx: ValidationContext = {\n diagnostics: [],\n extensionRegistry: options?.extensionRegistry,\n typeRegistry: ir.typeRegistry,\n };\n\n for (const element of ir.elements) {\n validateElement(ctx, element);\n }\n\n return {\n diagnostics: ctx.diagnostics,\n valid: ctx.diagnostics.every((diagnostic) => diagnostic.severity !== \"error\"),\n };\n}\n","/**\n * Mixed-authoring schema generator.\n *\n * Composes a statically analyzed TSDoc/class/interface/type-alias model with\n * ChainDSL-authored field overlays. The static model remains authoritative for\n * structure and constraints; overlays may add runtime field behavior such as\n * dynamic enum or dynamic schema metadata.\n */\n\nimport type { FormElement, FormSpec } from \"@formspec/core\";\nimport type { AnnotationNode, FieldNode, FormIRElement, TypeNode } from \"@formspec/core/internals\";\nimport type { JsonSchema2020 } from \"../json-schema/ir-generator.js\";\nimport { generateJsonSchemaFromIR } from \"../json-schema/ir-generator.js\";\nimport { generateUiSchemaFromIR } from \"../ui-schema/ir-generator.js\";\nimport type { UISchema } from \"../ui-schema/types.js\";\nimport { canonicalizeChainDSL, canonicalizeTSDoc } from \"../canonicalize/index.js\";\nimport { analyzeNamedTypeToIR } from \"../analyzer/program.js\";\nimport type { IRClassAnalysis } from \"../analyzer/class-analyzer.js\";\nimport type { StaticSchemaGenerationOptions } from \"./class-schema.js\";\n\n/**\n * Result of generating schemas from a mixed-authoring composition.\n *\n * @public\n */\nexport interface MixedAuthoringSchemas {\n /** JSON Schema 2020-12 for validation. */\n readonly jsonSchema: JsonSchema2020;\n /** JSON Forms UI Schema for rendering. */\n readonly uiSchema: UISchema;\n}\n\n/**\n * Options for generating mixed-authoring schemas.\n *\n * The `typeName` can resolve to a class, interface, or object type alias, just\n * like `generateSchemas()`.\n *\n * @public\n */\nexport interface BuildMixedAuthoringSchemasOptions extends StaticSchemaGenerationOptions {\n /** Path to the TypeScript source file. */\n readonly filePath: string;\n /** Name of the class, interface, or type alias to analyze. */\n readonly typeName: string;\n /** ChainDSL overlays to apply to the static model. Groups and conditionals are flattened by field name. */\n readonly overlays: FormSpec<readonly FormElement[]>;\n}\n\n/**\n * Builds JSON Schema and UI Schema from a TSDoc-derived model with ChainDSL\n * field overlays.\n *\n * Overlays are matched by field name. The static model wins for structure,\n * ordering, and constraints; ChainDSL overlays may contribute dynamic runtime\n * field metadata such as dynamic enum or dynamic schema keywords, and may fill\n * in missing annotations.\n *\n * @public\n */\nexport function buildMixedAuthoringSchemas(\n options: BuildMixedAuthoringSchemasOptions\n): MixedAuthoringSchemas {\n const { filePath, typeName, overlays, ...schemaOptions } = options;\n const analysis = analyzeNamedTypeToIR(filePath, typeName, schemaOptions.extensionRegistry);\n const composedAnalysis = composeAnalysisWithOverlays(analysis, overlays);\n const ir = canonicalizeTSDoc(composedAnalysis, { file: filePath });\n\n return {\n jsonSchema: generateJsonSchemaFromIR(ir, schemaOptions),\n uiSchema: generateUiSchemaFromIR(ir),\n };\n}\n\nfunction composeAnalysisWithOverlays(\n analysis: IRClassAnalysis,\n overlays: FormSpec<readonly FormElement[]>\n): IRClassAnalysis {\n const overlayIR = canonicalizeChainDSL(overlays);\n const overlayFields = collectOverlayFields(overlayIR.elements);\n\n if (overlayFields.length === 0) {\n return analysis;\n }\n\n const overlayByName = new Map<string, FieldNode>();\n for (const field of overlayFields) {\n if (overlayByName.has(field.name)) {\n throw new Error(`Mixed-authoring overlays define \"${field.name}\" more than once`);\n }\n overlayByName.set(field.name, field);\n }\n\n const mergedFields: FieldNode[] = [];\n\n for (const baseField of analysis.fields) {\n const overlayField = overlayByName.get(baseField.name);\n if (overlayField === undefined) {\n mergedFields.push(baseField);\n continue;\n }\n\n mergedFields.push(mergeFieldOverlay(baseField, overlayField, analysis.typeRegistry));\n overlayByName.delete(baseField.name);\n }\n\n if (overlayByName.size > 0) {\n const unknownFields = [...overlayByName.keys()].sort().join(\", \");\n throw new Error(\n `Mixed-authoring overlays reference fields that are not present in the static model: ${unknownFields}`\n );\n }\n\n return {\n ...analysis,\n fields: mergedFields,\n };\n}\n\nfunction collectOverlayFields(elements: readonly FormIRElement[]): FieldNode[] {\n const fields: FieldNode[] = [];\n\n for (const element of elements) {\n switch (element.kind) {\n case \"field\":\n fields.push(element);\n break;\n case \"group\":\n fields.push(...collectOverlayFields(element.elements));\n break;\n case \"conditional\":\n fields.push(...collectOverlayFields(element.elements));\n break;\n default: {\n const _exhaustive: never = element;\n void _exhaustive;\n }\n }\n }\n\n return fields;\n}\n\nfunction mergeFieldOverlay(\n baseField: FieldNode,\n overlayField: FieldNode,\n typeRegistry: IRClassAnalysis[\"typeRegistry\"]\n): FieldNode {\n assertSupportedOverlayField(baseField, overlayField);\n return {\n ...baseField,\n type: mergeFieldType(baseField, overlayField, typeRegistry),\n annotations: mergeAnnotations(baseField.annotations, overlayField.annotations),\n };\n}\n\nfunction assertSupportedOverlayField(baseField: FieldNode, overlayField: FieldNode): void {\n if (overlayField.constraints.length > 0) {\n throw new Error(\n `Mixed-authoring overlay for \"${baseField.name}\" cannot define constraints; keep constraints on the static model`\n );\n }\n\n if (overlayField.required && !baseField.required) {\n throw new Error(\n `Mixed-authoring overlay for \"${baseField.name}\" cannot change requiredness; keep requiredness on the static model`\n );\n }\n}\n\nfunction mergeFieldType(\n baseField: FieldNode,\n overlayField: FieldNode,\n typeRegistry: IRClassAnalysis[\"typeRegistry\"]\n): TypeNode {\n const { type: baseType } = baseField;\n const { type: overlayType } = overlayField;\n\n if (overlayType.kind === \"object\" || overlayType.kind === \"array\") {\n throw new Error(\n `Mixed-authoring overlays do not support nested object or array overlays for \"${baseField.name}\"`\n );\n }\n\n if (overlayType.kind === \"dynamic\") {\n if (!isCompatibleDynamicOverlay(baseField, overlayField, typeRegistry)) {\n throw new Error(\n `Mixed-authoring overlay for \"${baseField.name}\" is incompatible with the static field type`\n );\n }\n return overlayType;\n }\n\n if (!isSameStaticTypeShape(baseType, overlayType)) {\n throw new Error(\n `Mixed-authoring overlay for \"${baseField.name}\" must preserve the static field type`\n );\n }\n\n return baseType;\n}\n\nfunction isCompatibleDynamicOverlay(\n baseField: FieldNode,\n overlayField: FieldNode,\n typeRegistry: IRClassAnalysis[\"typeRegistry\"]\n): boolean {\n const overlayType = overlayField.type;\n if (overlayType.kind !== \"dynamic\") {\n return false;\n }\n\n const resolvedBaseType = resolveReferenceType(baseField.type, typeRegistry);\n if (resolvedBaseType === null) {\n return false;\n }\n\n if (overlayType.dynamicKind === \"enum\") {\n return resolvedBaseType.kind === \"primitive\"\n ? resolvedBaseType.primitiveKind === \"string\"\n : resolvedBaseType.kind === \"enum\";\n }\n\n return resolvedBaseType.kind === \"object\" || resolvedBaseType.kind === \"record\";\n}\n\nfunction resolveReferenceType(\n type: TypeNode,\n typeRegistry: IRClassAnalysis[\"typeRegistry\"],\n seen = new Set<string>()\n): TypeNode | null {\n if (type.kind !== \"reference\") {\n return type;\n }\n\n if (seen.has(type.name)) {\n return null;\n }\n\n const definition = typeRegistry[type.name];\n if (definition === undefined) {\n return null;\n }\n\n seen.add(type.name);\n return resolveReferenceType(definition.type, typeRegistry, seen);\n}\n\nfunction isSameStaticTypeShape(baseType: TypeNode, overlayType: TypeNode): boolean {\n if (baseType.kind !== overlayType.kind) {\n return false;\n }\n\n switch (baseType.kind) {\n case \"primitive\":\n return (\n overlayType.kind === \"primitive\" && baseType.primitiveKind === overlayType.primitiveKind\n );\n case \"enum\":\n return overlayType.kind === \"enum\";\n case \"dynamic\":\n return (\n overlayType.kind === \"dynamic\" &&\n baseType.dynamicKind === overlayType.dynamicKind &&\n baseType.sourceKey === overlayType.sourceKey\n );\n case \"record\":\n return overlayType.kind === \"record\";\n case \"reference\":\n return overlayType.kind === \"reference\" && baseType.name === overlayType.name;\n case \"union\":\n return overlayType.kind === \"union\";\n case \"custom\":\n return overlayType.kind === \"custom\" && baseType.typeId === overlayType.typeId;\n case \"object\":\n case \"array\":\n // Mixed authoring keeps the static type verbatim for structured fields.\n // We only need shape equality for scalar-like overlays that could replace\n // the static field type if we returned the overlay type by mistake.\n return true;\n default: {\n const _exhaustive: never = baseType;\n return _exhaustive;\n }\n }\n}\n\nfunction mergeAnnotations(\n baseAnnotations: readonly AnnotationNode[],\n overlayAnnotations: readonly AnnotationNode[]\n): AnnotationNode[] {\n const baseKeys = new Set(baseAnnotations.map(annotationKey));\n const overlayOnly = overlayAnnotations.filter(\n (annotation) => !baseKeys.has(annotationKey(annotation))\n );\n return [...baseAnnotations, ...overlayOnly];\n}\n\nfunction annotationKey(annotation: AnnotationNode): string {\n return annotation.annotationKind === \"custom\"\n ? `${annotation.annotationKind}:${annotation.annotationId}`\n : annotation.annotationKind;\n}\n"],"mappings":";AAoDA,SAAS,kBAAkB;AAO3B,IAAM,uBAAmC;AAAA,EACvC,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AAAA,EACN,QAAQ;AACV;AAMA,SAAS,QAAQ,IAAsD;AACrE,SAAO,GAAG,UAAU;AACtB;AAEA,SAAS,cACP,IAC4D;AAC5D,SAAO,GAAG,UAAU;AACtB;AAEA,SAAS,QAAQ,IAAiC;AAChD,SAAO,GAAG,UAAU;AACtB;AAYO,SAAS,qBAAqB,MAAgD;AACnF,SAAO;AAAA,IACL,MAAM;AAAA,IACN,WAAW;AAAA,IACX,UAAU,qBAAqB,KAAK,QAAQ;AAAA,IAC5C,iBAAiB,CAAC;AAAA,IAClB,cAAc,CAAC;AAAA,IACf,YAAY;AAAA,EACd;AACF;AASA,SAAS,qBAAqB,UAAmD;AAC/E,SAAO,SAAS,IAAI,mBAAmB;AACzC;AAKA,SAAS,oBAAoB,SAAqC;AAChE,MAAI,QAAQ,OAAO,GAAG;AACpB,WAAO,kBAAkB,OAAO;AAAA,EAClC;AACA,MAAI,QAAQ,OAAO,GAAG;AACpB,WAAO,kBAAkB,OAAO;AAAA,EAClC;AACA,MAAI,cAAc,OAAO,GAAG;AAC1B,WAAO,wBAAwB,OAAO;AAAA,EACxC;AACA,QAAM,cAAqB;AAC3B,QAAM,IAAI,MAAM,yBAAyB,KAAK,UAAU,WAAW,CAAC,EAAE;AACxE;AASA,SAAS,kBAAkB,OAA4B;AACrD,UAAQ,MAAM,QAAQ;AAAA,IACpB,KAAK;AACH,aAAO,sBAAsB,KAAK;AAAA,IACpC,KAAK;AACH,aAAO,wBAAwB,KAAK;AAAA,IACtC,KAAK;AACH,aAAO,yBAAyB,KAAK;AAAA,IACvC,KAAK;AACH,aAAO,4BAA4B,KAAK;A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