@formspec/build 0.1.0-alpha.2 → 0.1.0-alpha.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/README.md +120 -0
  2. package/dist/__tests__/alias-chain-propagation.test.d.ts +9 -0
  3. package/dist/__tests__/alias-chain-propagation.test.d.ts.map +1 -0
  4. package/dist/__tests__/chain-dsl-canonicalizer.test.d.ts +2 -0
  5. package/dist/__tests__/chain-dsl-canonicalizer.test.d.ts.map +1 -0
  6. package/dist/__tests__/class-schema.test.d.ts +2 -0
  7. package/dist/__tests__/class-schema.test.d.ts.map +1 -0
  8. package/dist/__tests__/constraint-validator.test.d.ts +2 -0
  9. package/dist/__tests__/constraint-validator.test.d.ts.map +1 -0
  10. package/dist/__tests__/date-extension.integration.test.d.ts +2 -0
  11. package/dist/__tests__/date-extension.integration.test.d.ts.map +1 -0
  12. package/dist/__tests__/extension-api.test.d.ts +2 -0
  13. package/dist/__tests__/extension-api.test.d.ts.map +1 -0
  14. package/dist/__tests__/extension-runtime.integration.test.d.ts +2 -0
  15. package/dist/__tests__/extension-runtime.integration.test.d.ts.map +1 -0
  16. package/dist/__tests__/fixtures/alias-chains.d.ts +37 -0
  17. package/dist/__tests__/fixtures/alias-chains.d.ts.map +1 -0
  18. package/dist/__tests__/fixtures/class-schema-regressions.d.ts +87 -0
  19. package/dist/__tests__/fixtures/class-schema-regressions.d.ts.map +1 -0
  20. package/dist/__tests__/fixtures/edge-cases.d.ts +132 -0
  21. package/dist/__tests__/fixtures/edge-cases.d.ts.map +1 -0
  22. package/dist/__tests__/fixtures/example-a-builtins.d.ts +30 -0
  23. package/dist/__tests__/fixtures/example-a-builtins.d.ts.map +1 -0
  24. package/dist/__tests__/fixtures/example-date-extension.d.ts +12 -0
  25. package/dist/__tests__/fixtures/example-date-extension.d.ts.map +1 -0
  26. package/dist/__tests__/fixtures/example-interface-types.d.ts +102 -0
  27. package/dist/__tests__/fixtures/example-interface-types.d.ts.map +1 -0
  28. package/dist/__tests__/fixtures/example-numeric-extension.d.ts +20 -0
  29. package/dist/__tests__/fixtures/example-numeric-extension.d.ts.map +1 -0
  30. package/dist/__tests__/fixtures/extension-forms.d.ts +7 -0
  31. package/dist/__tests__/fixtures/extension-forms.d.ts.map +1 -0
  32. package/dist/__tests__/fixtures/mixed-authoring-shipping-address.d.ts +31 -0
  33. package/dist/__tests__/fixtures/mixed-authoring-shipping-address.d.ts.map +1 -0
  34. package/dist/__tests__/fixtures/named-primitive-aliases.d.ts +15 -0
  35. package/dist/__tests__/fixtures/named-primitive-aliases.d.ts.map +1 -0
  36. package/dist/__tests__/fixtures/nested-array-path-constraints.d.ts +14 -0
  37. package/dist/__tests__/fixtures/nested-array-path-constraints.d.ts.map +1 -0
  38. package/dist/__tests__/fixtures/sample-forms.d.ts +65 -0
  39. package/dist/__tests__/fixtures/sample-forms.d.ts.map +1 -0
  40. package/dist/__tests__/generate-schemas.test.d.ts +2 -0
  41. package/dist/__tests__/generate-schemas.test.d.ts.map +1 -0
  42. package/dist/__tests__/guards.test.d.ts +2 -0
  43. package/dist/__tests__/guards.test.d.ts.map +1 -0
  44. package/dist/__tests__/ir-analyzer.test.d.ts +11 -0
  45. package/dist/__tests__/ir-analyzer.test.d.ts.map +1 -0
  46. package/dist/__tests__/ir-jsdoc-constraints.test.d.ts +12 -0
  47. package/dist/__tests__/ir-jsdoc-constraints.test.d.ts.map +1 -0
  48. package/dist/__tests__/ir-json-schema-generator.test.d.ts +11 -0
  49. package/dist/__tests__/ir-json-schema-generator.test.d.ts.map +1 -0
  50. package/dist/__tests__/ir-ui-schema-generator.test.d.ts +2 -0
  51. package/dist/__tests__/ir-ui-schema-generator.test.d.ts.map +1 -0
  52. package/dist/__tests__/mixed-authoring.test.d.ts +2 -0
  53. package/dist/__tests__/mixed-authoring.test.d.ts.map +1 -0
  54. package/dist/__tests__/numeric-extension.integration.test.d.ts +2 -0
  55. package/dist/__tests__/numeric-extension.integration.test.d.ts.map +1 -0
  56. package/dist/__tests__/parity/fixtures/address/chain-dsl.d.ts +9 -0
  57. package/dist/__tests__/parity/fixtures/address/chain-dsl.d.ts.map +1 -0
  58. package/dist/__tests__/parity/fixtures/address/expected-ir.d.ts +9 -0
  59. package/dist/__tests__/parity/fixtures/address/expected-ir.d.ts.map +1 -0
  60. package/dist/__tests__/parity/fixtures/address/tsdoc.d.ts +19 -0
  61. package/dist/__tests__/parity/fixtures/address/tsdoc.d.ts.map +1 -0
  62. package/dist/__tests__/parity/fixtures/plan-status/chain-dsl.d.ts +19 -0
  63. package/dist/__tests__/parity/fixtures/plan-status/chain-dsl.d.ts.map +1 -0
  64. package/dist/__tests__/parity/fixtures/plan-status/expected-ir.d.ts +6 -0
  65. package/dist/__tests__/parity/fixtures/plan-status/expected-ir.d.ts.map +1 -0
  66. package/dist/__tests__/parity/fixtures/plan-status/tsdoc.d.ts +17 -0
  67. package/dist/__tests__/parity/fixtures/plan-status/tsdoc.d.ts.map +1 -0
  68. package/dist/__tests__/parity/fixtures/product-config/chain-dsl.d.ts +13 -0
  69. package/dist/__tests__/parity/fixtures/product-config/chain-dsl.d.ts.map +1 -0
  70. package/dist/__tests__/parity/fixtures/product-config/expected-ir.d.ts +9 -0
  71. package/dist/__tests__/parity/fixtures/product-config/expected-ir.d.ts.map +1 -0
  72. package/dist/__tests__/parity/fixtures/product-config/tsdoc.d.ts +28 -0
  73. package/dist/__tests__/parity/fixtures/product-config/tsdoc.d.ts.map +1 -0
  74. package/dist/__tests__/parity/fixtures/usd-cents/chain-dsl.d.ts +9 -0
  75. package/dist/__tests__/parity/fixtures/usd-cents/chain-dsl.d.ts.map +1 -0
  76. package/dist/__tests__/parity/fixtures/usd-cents/expected-ir.d.ts +6 -0
  77. package/dist/__tests__/parity/fixtures/usd-cents/expected-ir.d.ts.map +1 -0
  78. package/dist/__tests__/parity/fixtures/usd-cents/tsdoc.d.ts +19 -0
  79. package/dist/__tests__/parity/fixtures/usd-cents/tsdoc.d.ts.map +1 -0
  80. package/dist/__tests__/parity/fixtures/user-registration/chain-dsl.d.ts +12 -0
  81. package/dist/__tests__/parity/fixtures/user-registration/chain-dsl.d.ts.map +1 -0
  82. package/dist/__tests__/parity/fixtures/user-registration/expected-ir.d.ts +9 -0
  83. package/dist/__tests__/parity/fixtures/user-registration/expected-ir.d.ts.map +1 -0
  84. package/dist/__tests__/parity/fixtures/user-registration/tsdoc.d.ts +19 -0
  85. package/dist/__tests__/parity/fixtures/user-registration/tsdoc.d.ts.map +1 -0
  86. package/dist/__tests__/parity/parity.test.d.ts +18 -0
  87. package/dist/__tests__/parity/parity.test.d.ts.map +1 -0
  88. package/dist/__tests__/parity/utils.d.ts +151 -0
  89. package/dist/__tests__/parity/utils.d.ts.map +1 -0
  90. package/dist/__tests__/path-target-parser.test.d.ts +9 -0
  91. package/dist/__tests__/path-target-parser.test.d.ts.map +1 -0
  92. package/dist/analyzer/class-analyzer.d.ts +100 -0
  93. package/dist/analyzer/class-analyzer.d.ts.map +1 -0
  94. package/dist/analyzer/jsdoc-constraints.d.ts +53 -0
  95. package/dist/analyzer/jsdoc-constraints.d.ts.map +1 -0
  96. package/dist/analyzer/program.d.ts +68 -0
  97. package/dist/analyzer/program.d.ts.map +1 -0
  98. package/dist/analyzer/tsdoc-parser.d.ts +122 -0
  99. package/dist/analyzer/tsdoc-parser.d.ts.map +1 -0
  100. package/dist/browser.cjs +1291 -0
  101. package/dist/browser.cjs.map +1 -0
  102. package/dist/browser.d.ts +73 -0
  103. package/dist/browser.d.ts.map +1 -0
  104. package/dist/browser.js +1242 -0
  105. package/dist/browser.js.map +1 -0
  106. package/dist/build.d.ts +996 -0
  107. package/dist/canonicalize/chain-dsl-canonicalizer.d.ts +18 -0
  108. package/dist/canonicalize/chain-dsl-canonicalizer.d.ts.map +1 -0
  109. package/dist/canonicalize/index.d.ts +8 -0
  110. package/dist/canonicalize/index.d.ts.map +1 -0
  111. package/dist/canonicalize/tsdoc-canonicalizer.d.ts +34 -0
  112. package/dist/canonicalize/tsdoc-canonicalizer.d.ts.map +1 -0
  113. package/dist/cli.cjs +3862 -0
  114. package/dist/cli.cjs.map +1 -0
  115. package/dist/cli.js +3826 -103
  116. package/dist/cli.js.map +1 -1
  117. package/dist/extensions/index.d.ts +8 -0
  118. package/dist/extensions/index.d.ts.map +1 -0
  119. package/dist/extensions/registry.d.ts +79 -0
  120. package/dist/extensions/registry.d.ts.map +1 -0
  121. package/dist/generators/class-schema.d.ts +99 -0
  122. package/dist/generators/class-schema.d.ts.map +1 -0
  123. package/dist/generators/method-schema.d.ts +65 -0
  124. package/dist/generators/method-schema.d.ts.map +1 -0
  125. package/dist/generators/mixed-authoring.d.ts +45 -0
  126. package/dist/generators/mixed-authoring.d.ts.map +1 -0
  127. package/dist/index.cjs +3627 -0
  128. package/dist/index.cjs.map +1 -0
  129. package/dist/index.d.ts +33 -8
  130. package/dist/index.d.ts.map +1 -1
  131. package/dist/index.js +3587 -106
  132. package/dist/index.js.map +1 -1
  133. package/dist/internals.cjs +3371 -0
  134. package/dist/internals.cjs.map +1 -0
  135. package/dist/internals.d.ts +30 -0
  136. package/dist/internals.d.ts.map +1 -0
  137. package/dist/internals.js +3345 -0
  138. package/dist/internals.js.map +1 -0
  139. package/dist/json-schema/generator.d.ts +16 -5
  140. package/dist/json-schema/generator.d.ts.map +1 -1
  141. package/dist/json-schema/ir-generator.d.ts +108 -0
  142. package/dist/json-schema/ir-generator.d.ts.map +1 -0
  143. package/dist/json-schema/schema.d.ts +16 -0
  144. package/dist/json-schema/schema.d.ts.map +1 -0
  145. package/dist/json-schema/types.d.ts +29 -2
  146. package/dist/json-schema/types.d.ts.map +1 -1
  147. package/dist/ui-schema/generator.d.ts +5 -0
  148. package/dist/ui-schema/generator.d.ts.map +1 -1
  149. package/dist/ui-schema/ir-generator.d.ts +53 -0
  150. package/dist/ui-schema/ir-generator.d.ts.map +1 -0
  151. package/dist/ui-schema/schema.d.ts +357 -0
  152. package/dist/ui-schema/schema.d.ts.map +1 -0
  153. package/dist/ui-schema/types.d.ts +8 -73
  154. package/dist/ui-schema/types.d.ts.map +1 -1
  155. package/dist/validate/constraint-validator.d.ts +23 -0
  156. package/dist/validate/constraint-validator.d.ts.map +1 -0
  157. package/dist/validate/index.d.ts +9 -0
  158. package/dist/validate/index.d.ts.map +1 -0
  159. package/package.json +27 -7
  160. package/dist/__tests__/cli.test.js +0 -178
  161. package/dist/__tests__/cli.test.js.map +0 -1
  162. package/dist/__tests__/edge-cases.test.js +0 -217
  163. package/dist/__tests__/edge-cases.test.js.map +0 -1
  164. package/dist/__tests__/generator.test.js +0 -225
  165. package/dist/__tests__/generator.test.js.map +0 -1
  166. package/dist/__tests__/integration.test.js +0 -163
  167. package/dist/__tests__/integration.test.js.map +0 -1
  168. package/dist/__tests__/write-schemas.test.js +0 -196
  169. package/dist/__tests__/write-schemas.test.js.map +0 -1
  170. package/dist/json-schema/generator.js +0 -161
  171. package/dist/json-schema/generator.js.map +0 -1
  172. package/dist/json-schema/types.js +0 -7
  173. package/dist/json-schema/types.js.map +0 -1
  174. package/dist/ui-schema/generator.js +0 -150
  175. package/dist/ui-schema/generator.js.map +0 -1
  176. package/dist/ui-schema/types.js +0 -8
  177. package/dist/ui-schema/types.js.map +0 -1
@@ -0,0 +1,3345 @@
1
+ // src/canonicalize/chain-dsl-canonicalizer.ts
2
+ import { IR_VERSION } from "@formspec/core";
3
+ var CHAIN_DSL_PROVENANCE = {
4
+ surface: "chain-dsl",
5
+ file: "",
6
+ line: 0,
7
+ column: 0
8
+ };
9
+ function isGroup(el) {
10
+ return el._type === "group";
11
+ }
12
+ function isConditional(el) {
13
+ return el._type === "conditional";
14
+ }
15
+ function isField(el) {
16
+ return el._type === "field";
17
+ }
18
+ function canonicalizeChainDSL(form) {
19
+ return {
20
+ kind: "form-ir",
21
+ irVersion: IR_VERSION,
22
+ elements: canonicalizeElements(form.elements),
23
+ rootAnnotations: [],
24
+ typeRegistry: {},
25
+ provenance: CHAIN_DSL_PROVENANCE
26
+ };
27
+ }
28
+ function canonicalizeElements(elements) {
29
+ return elements.map(canonicalizeElement);
30
+ }
31
+ function canonicalizeElement(element) {
32
+ if (isField(element)) {
33
+ return canonicalizeField(element);
34
+ }
35
+ if (isGroup(element)) {
36
+ return canonicalizeGroup(element);
37
+ }
38
+ if (isConditional(element)) {
39
+ return canonicalizeConditional(element);
40
+ }
41
+ const _exhaustive = element;
42
+ throw new Error(`Unknown element type: ${JSON.stringify(_exhaustive)}`);
43
+ }
44
+ function canonicalizeField(field) {
45
+ switch (field._field) {
46
+ case "text":
47
+ return canonicalizeTextField(field);
48
+ case "number":
49
+ return canonicalizeNumberField(field);
50
+ case "boolean":
51
+ return canonicalizeBooleanField(field);
52
+ case "enum":
53
+ return canonicalizeStaticEnumField(field);
54
+ case "dynamic_enum":
55
+ return canonicalizeDynamicEnumField(field);
56
+ case "dynamic_schema":
57
+ return canonicalizeDynamicSchemaField(field);
58
+ case "array":
59
+ return canonicalizeArrayField(field);
60
+ case "object":
61
+ return canonicalizeObjectField(field);
62
+ default: {
63
+ const _exhaustive = field;
64
+ throw new Error(`Unknown field type: ${JSON.stringify(_exhaustive)}`);
65
+ }
66
+ }
67
+ }
68
+ function canonicalizeTextField(field) {
69
+ const type = { kind: "primitive", primitiveKind: "string" };
70
+ const constraints = [];
71
+ if (field.minLength !== void 0) {
72
+ const c = {
73
+ kind: "constraint",
74
+ constraintKind: "minLength",
75
+ value: field.minLength,
76
+ provenance: CHAIN_DSL_PROVENANCE
77
+ };
78
+ constraints.push(c);
79
+ }
80
+ if (field.maxLength !== void 0) {
81
+ const c = {
82
+ kind: "constraint",
83
+ constraintKind: "maxLength",
84
+ value: field.maxLength,
85
+ provenance: CHAIN_DSL_PROVENANCE
86
+ };
87
+ constraints.push(c);
88
+ }
89
+ if (field.pattern !== void 0) {
90
+ const c = {
91
+ kind: "constraint",
92
+ constraintKind: "pattern",
93
+ pattern: field.pattern,
94
+ provenance: CHAIN_DSL_PROVENANCE
95
+ };
96
+ constraints.push(c);
97
+ }
98
+ return buildFieldNode(
99
+ field.name,
100
+ type,
101
+ field.required,
102
+ buildAnnotations(field.label, field.placeholder),
103
+ constraints
104
+ );
105
+ }
106
+ function canonicalizeNumberField(field) {
107
+ const type = { kind: "primitive", primitiveKind: "number" };
108
+ const constraints = [];
109
+ if (field.min !== void 0) {
110
+ const c = {
111
+ kind: "constraint",
112
+ constraintKind: "minimum",
113
+ value: field.min,
114
+ provenance: CHAIN_DSL_PROVENANCE
115
+ };
116
+ constraints.push(c);
117
+ }
118
+ if (field.max !== void 0) {
119
+ const c = {
120
+ kind: "constraint",
121
+ constraintKind: "maximum",
122
+ value: field.max,
123
+ provenance: CHAIN_DSL_PROVENANCE
124
+ };
125
+ constraints.push(c);
126
+ }
127
+ if (field.multipleOf !== void 0) {
128
+ const c = {
129
+ kind: "constraint",
130
+ constraintKind: "multipleOf",
131
+ value: field.multipleOf,
132
+ provenance: CHAIN_DSL_PROVENANCE
133
+ };
134
+ constraints.push(c);
135
+ }
136
+ return buildFieldNode(
137
+ field.name,
138
+ type,
139
+ field.required,
140
+ buildAnnotations(field.label),
141
+ constraints
142
+ );
143
+ }
144
+ function canonicalizeBooleanField(field) {
145
+ const type = { kind: "primitive", primitiveKind: "boolean" };
146
+ return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));
147
+ }
148
+ function canonicalizeStaticEnumField(field) {
149
+ const members = field.options.map((opt) => {
150
+ if (typeof opt === "string") {
151
+ return { value: opt };
152
+ }
153
+ return { value: opt.id, displayName: opt.label };
154
+ });
155
+ const type = { kind: "enum", members };
156
+ return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));
157
+ }
158
+ function canonicalizeDynamicEnumField(field) {
159
+ const type = {
160
+ kind: "dynamic",
161
+ dynamicKind: "enum",
162
+ sourceKey: field.source,
163
+ parameterFields: field.params ? [...field.params] : []
164
+ };
165
+ return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));
166
+ }
167
+ function canonicalizeDynamicSchemaField(field) {
168
+ const type = {
169
+ kind: "dynamic",
170
+ dynamicKind: "schema",
171
+ sourceKey: field.schemaSource,
172
+ parameterFields: []
173
+ };
174
+ return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));
175
+ }
176
+ function canonicalizeArrayField(field) {
177
+ const itemProperties = buildObjectProperties(field.items);
178
+ const itemsType = {
179
+ kind: "object",
180
+ properties: itemProperties,
181
+ additionalProperties: true
182
+ };
183
+ const type = { kind: "array", items: itemsType };
184
+ const constraints = [];
185
+ if (field.minItems !== void 0) {
186
+ const c = {
187
+ kind: "constraint",
188
+ constraintKind: "minItems",
189
+ value: field.minItems,
190
+ provenance: CHAIN_DSL_PROVENANCE
191
+ };
192
+ constraints.push(c);
193
+ }
194
+ if (field.maxItems !== void 0) {
195
+ const c = {
196
+ kind: "constraint",
197
+ constraintKind: "maxItems",
198
+ value: field.maxItems,
199
+ provenance: CHAIN_DSL_PROVENANCE
200
+ };
201
+ constraints.push(c);
202
+ }
203
+ return buildFieldNode(
204
+ field.name,
205
+ type,
206
+ field.required,
207
+ buildAnnotations(field.label),
208
+ constraints
209
+ );
210
+ }
211
+ function canonicalizeObjectField(field) {
212
+ const properties = buildObjectProperties(field.properties);
213
+ const type = {
214
+ kind: "object",
215
+ properties,
216
+ additionalProperties: true
217
+ };
218
+ return buildFieldNode(field.name, type, field.required, buildAnnotations(field.label));
219
+ }
220
+ function canonicalizeGroup(g) {
221
+ return {
222
+ kind: "group",
223
+ label: g.label,
224
+ elements: canonicalizeElements(g.elements),
225
+ provenance: CHAIN_DSL_PROVENANCE
226
+ };
227
+ }
228
+ function canonicalizeConditional(c) {
229
+ return {
230
+ kind: "conditional",
231
+ fieldName: c.field,
232
+ // Conditional values from the chain DSL are JSON-serializable primitives
233
+ // (strings, numbers, booleans) produced by the `is()` predicate helper.
234
+ value: assertJsonValue(c.value),
235
+ elements: canonicalizeElements(c.elements),
236
+ provenance: CHAIN_DSL_PROVENANCE
237
+ };
238
+ }
239
+ function assertJsonValue(v) {
240
+ if (v === null || typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
241
+ return v;
242
+ }
243
+ if (Array.isArray(v)) {
244
+ return v.map(assertJsonValue);
245
+ }
246
+ if (typeof v === "object") {
247
+ const result = {};
248
+ for (const [key, val] of Object.entries(v)) {
249
+ result[key] = assertJsonValue(val);
250
+ }
251
+ return result;
252
+ }
253
+ throw new TypeError(`Conditional value is not a valid JsonValue: ${typeof v}`);
254
+ }
255
+ function buildFieldNode(name, type, required, annotations, constraints = []) {
256
+ return {
257
+ kind: "field",
258
+ name,
259
+ type,
260
+ required: required === true,
261
+ constraints,
262
+ annotations,
263
+ provenance: CHAIN_DSL_PROVENANCE
264
+ };
265
+ }
266
+ function buildAnnotations(label, placeholder) {
267
+ const annotations = [];
268
+ if (label !== void 0) {
269
+ const a = {
270
+ kind: "annotation",
271
+ annotationKind: "displayName",
272
+ value: label,
273
+ provenance: CHAIN_DSL_PROVENANCE
274
+ };
275
+ annotations.push(a);
276
+ }
277
+ if (placeholder !== void 0) {
278
+ const a = {
279
+ kind: "annotation",
280
+ annotationKind: "placeholder",
281
+ value: placeholder,
282
+ provenance: CHAIN_DSL_PROVENANCE
283
+ };
284
+ annotations.push(a);
285
+ }
286
+ return annotations;
287
+ }
288
+ function buildObjectProperties(elements, insideConditional = false) {
289
+ const properties = [];
290
+ for (const el of elements) {
291
+ if (isField(el)) {
292
+ const fieldNode = canonicalizeField(el);
293
+ properties.push({
294
+ name: fieldNode.name,
295
+ type: fieldNode.type,
296
+ // Fields inside a conditional branch are always optional in the
297
+ // data schema, regardless of their `required` flag — the condition
298
+ // may not be met, so the field may be absent.
299
+ optional: insideConditional || !fieldNode.required,
300
+ constraints: fieldNode.constraints,
301
+ annotations: fieldNode.annotations,
302
+ provenance: CHAIN_DSL_PROVENANCE
303
+ });
304
+ } else if (isGroup(el)) {
305
+ properties.push(...buildObjectProperties(el.elements, insideConditional));
306
+ } else if (isConditional(el)) {
307
+ properties.push(...buildObjectProperties(el.elements, true));
308
+ }
309
+ }
310
+ return properties;
311
+ }
312
+
313
+ // src/canonicalize/tsdoc-canonicalizer.ts
314
+ import { IR_VERSION as IR_VERSION2 } from "@formspec/core";
315
+ function canonicalizeTSDoc(analysis, source) {
316
+ const file = source?.file ?? "";
317
+ const provenance = {
318
+ surface: "tsdoc",
319
+ file,
320
+ line: 1,
321
+ column: 0
322
+ };
323
+ const elements = assembleElements(analysis.fields, analysis.fieldLayouts, provenance);
324
+ return {
325
+ kind: "form-ir",
326
+ irVersion: IR_VERSION2,
327
+ elements,
328
+ typeRegistry: analysis.typeRegistry,
329
+ ...analysis.annotations !== void 0 && analysis.annotations.length > 0 && { rootAnnotations: analysis.annotations },
330
+ ...analysis.annotations !== void 0 && analysis.annotations.length > 0 && { annotations: analysis.annotations },
331
+ provenance
332
+ };
333
+ }
334
+ function assembleElements(fields, layouts, provenance) {
335
+ const elements = [];
336
+ const groupMap = /* @__PURE__ */ new Map();
337
+ const topLevelOrder = [];
338
+ for (let i = 0; i < fields.length; i++) {
339
+ const field = fields[i];
340
+ const layout = layouts[i];
341
+ if (!field || !layout) continue;
342
+ const element = wrapInConditional(field, layout, provenance);
343
+ if (layout.groupLabel !== void 0) {
344
+ const label = layout.groupLabel;
345
+ let groupElements = groupMap.get(label);
346
+ if (!groupElements) {
347
+ groupElements = [];
348
+ groupMap.set(label, groupElements);
349
+ topLevelOrder.push({ type: "group", label });
350
+ }
351
+ groupElements.push(element);
352
+ } else {
353
+ topLevelOrder.push({ type: "element", element });
354
+ }
355
+ }
356
+ for (const entry of topLevelOrder) {
357
+ if (entry.type === "group") {
358
+ const groupElements = groupMap.get(entry.label);
359
+ if (groupElements) {
360
+ const groupNode = {
361
+ kind: "group",
362
+ label: entry.label,
363
+ elements: groupElements,
364
+ provenance
365
+ };
366
+ elements.push(groupNode);
367
+ groupMap.delete(entry.label);
368
+ }
369
+ } else {
370
+ elements.push(entry.element);
371
+ }
372
+ }
373
+ return elements;
374
+ }
375
+ function wrapInConditional(field, layout, provenance) {
376
+ if (layout.showWhen === void 0) {
377
+ return field;
378
+ }
379
+ const conditional = {
380
+ kind: "conditional",
381
+ fieldName: layout.showWhen.field,
382
+ value: layout.showWhen.value,
383
+ elements: [field],
384
+ provenance
385
+ };
386
+ return conditional;
387
+ }
388
+
389
+ // src/analyzer/program.ts
390
+ import * as ts4 from "typescript";
391
+ import * as path from "path";
392
+
393
+ // src/analyzer/class-analyzer.ts
394
+ import * as ts3 from "typescript";
395
+
396
+ // src/analyzer/jsdoc-constraints.ts
397
+ import * as ts2 from "typescript";
398
+
399
+ // src/analyzer/tsdoc-parser.ts
400
+ import * as ts from "typescript";
401
+ import {
402
+ checkSyntheticTagApplication,
403
+ extractPathTarget as extractSharedPathTarget,
404
+ getTagDefinition,
405
+ hasTypeSemanticCapability,
406
+ parseConstraintTagValue,
407
+ parseDefaultValueTagValue,
408
+ resolveDeclarationPlacement,
409
+ resolvePathTargetType,
410
+ sliceCommentSpan,
411
+ parseCommentBlock,
412
+ parseTagSyntax
413
+ } from "@formspec/analysis";
414
+ import {
415
+ TSDocParser,
416
+ TSDocConfiguration,
417
+ TSDocTagDefinition,
418
+ TSDocTagSyntaxKind,
419
+ DocPlainText,
420
+ DocSoftBreak,
421
+ TextRange
422
+ } from "@microsoft/tsdoc";
423
+ import {
424
+ BUILTIN_CONSTRAINT_DEFINITIONS,
425
+ normalizeConstraintTagName,
426
+ isBuiltinConstraintName
427
+ } from "@formspec/core";
428
+ var TAGS_REQUIRING_RAW_TEXT = /* @__PURE__ */ new Set(["pattern", "enumOptions", "defaultValue"]);
429
+ function createFormSpecTSDocConfig(extensionTagNames = []) {
430
+ const config = new TSDocConfiguration();
431
+ for (const tagName of Object.keys(BUILTIN_CONSTRAINT_DEFINITIONS)) {
432
+ config.addTagDefinition(
433
+ new TSDocTagDefinition({
434
+ tagName: "@" + tagName,
435
+ syntaxKind: TSDocTagSyntaxKind.BlockTag,
436
+ allowMultiple: true
437
+ })
438
+ );
439
+ }
440
+ for (const tagName of ["displayName", "description", "format", "placeholder"]) {
441
+ config.addTagDefinition(
442
+ new TSDocTagDefinition({
443
+ tagName: "@" + tagName,
444
+ syntaxKind: TSDocTagSyntaxKind.BlockTag,
445
+ allowMultiple: true
446
+ })
447
+ );
448
+ }
449
+ for (const tagName of extensionTagNames) {
450
+ config.addTagDefinition(
451
+ new TSDocTagDefinition({
452
+ tagName: "@" + tagName,
453
+ syntaxKind: TSDocTagSyntaxKind.BlockTag,
454
+ allowMultiple: true
455
+ })
456
+ );
457
+ }
458
+ return config;
459
+ }
460
+ function sharedCommentSyntaxOptions(options, offset) {
461
+ const extensions = options?.extensionRegistry?.extensions;
462
+ return {
463
+ ...offset !== void 0 ? { offset } : {},
464
+ ...extensions !== void 0 ? { extensions } : {}
465
+ };
466
+ }
467
+ function sharedTagValueOptions(options) {
468
+ return {
469
+ ...options?.extensionRegistry !== void 0 ? { registry: options.extensionRegistry } : {},
470
+ ...options?.fieldType !== void 0 ? { fieldType: options.fieldType } : {}
471
+ };
472
+ }
473
+ var SYNTHETIC_TYPE_FORMAT_FLAGS = ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope;
474
+ function buildSupportingDeclarations(sourceFile) {
475
+ return sourceFile.statements.filter(
476
+ (statement) => !ts.isImportDeclaration(statement) && !ts.isImportEqualsDeclaration(statement) && !(ts.isExportDeclaration(statement) && statement.moduleSpecifier !== void 0)
477
+ ).map((statement) => statement.getText(sourceFile));
478
+ }
479
+ function renderSyntheticArgumentExpression(valueKind, argumentText) {
480
+ const trimmed = argumentText.trim();
481
+ if (trimmed === "") {
482
+ return null;
483
+ }
484
+ switch (valueKind) {
485
+ case "number":
486
+ case "integer":
487
+ case "signedInteger":
488
+ return Number.isFinite(Number(trimmed)) ? trimmed : JSON.stringify(trimmed);
489
+ case "string":
490
+ return JSON.stringify(argumentText);
491
+ case "json":
492
+ try {
493
+ JSON.parse(trimmed);
494
+ return `(${trimmed})`;
495
+ } catch {
496
+ return JSON.stringify(trimmed);
497
+ }
498
+ case "boolean":
499
+ return trimmed === "true" || trimmed === "false" ? trimmed : JSON.stringify(trimmed);
500
+ case "condition":
501
+ return "undefined as unknown as FormSpecCondition";
502
+ case null:
503
+ return null;
504
+ default: {
505
+ return String(valueKind);
506
+ }
507
+ }
508
+ }
509
+ function getArrayElementType(type, checker) {
510
+ if (!checker.isArrayType(type)) {
511
+ return null;
512
+ }
513
+ return checker.getTypeArguments(type)[0] ?? null;
514
+ }
515
+ function supportsConstraintCapability(type, checker, capability) {
516
+ if (capability === void 0) {
517
+ return true;
518
+ }
519
+ if (hasTypeSemanticCapability(type, checker, capability)) {
520
+ return true;
521
+ }
522
+ if (capability === "string-like") {
523
+ const itemType = getArrayElementType(type, checker);
524
+ return itemType !== null && hasTypeSemanticCapability(itemType, checker, capability);
525
+ }
526
+ return false;
527
+ }
528
+ function makeDiagnostic(code, message, provenance) {
529
+ return {
530
+ code,
531
+ message,
532
+ severity: "error",
533
+ primaryLocation: provenance,
534
+ relatedLocations: []
535
+ };
536
+ }
537
+ function placementLabel(placement) {
538
+ switch (placement) {
539
+ case "class":
540
+ return "class declarations";
541
+ case "class-field":
542
+ return "class fields";
543
+ case "class-method":
544
+ return "class methods";
545
+ case "interface":
546
+ return "interface declarations";
547
+ case "interface-field":
548
+ return "interface fields";
549
+ case "type-alias":
550
+ return "type aliases";
551
+ case "type-alias-field":
552
+ return "type-alias properties";
553
+ case "variable":
554
+ return "variables";
555
+ case "function":
556
+ return "functions";
557
+ case "function-parameter":
558
+ return "function parameters";
559
+ case "method-parameter":
560
+ return "method parameters";
561
+ default: {
562
+ const exhaustive = placement;
563
+ return String(exhaustive);
564
+ }
565
+ }
566
+ }
567
+ function capabilityLabel(capability) {
568
+ switch (capability) {
569
+ case "numeric-comparable":
570
+ return "number";
571
+ case "string-like":
572
+ return "string";
573
+ case "array-like":
574
+ return "array";
575
+ case "enum-member-addressable":
576
+ return "enum";
577
+ case "json-like":
578
+ return "JSON-compatible";
579
+ case "object-like":
580
+ return "object";
581
+ case "condition-like":
582
+ return "conditional";
583
+ case void 0:
584
+ return "compatible";
585
+ default:
586
+ return capability;
587
+ }
588
+ }
589
+ function getBroadenedCustomTypeId(fieldType) {
590
+ if (fieldType?.kind === "custom") {
591
+ return fieldType.typeId;
592
+ }
593
+ if (fieldType?.kind !== "union") {
594
+ return void 0;
595
+ }
596
+ const customMembers = fieldType.members.filter(
597
+ (member) => member.kind === "custom"
598
+ );
599
+ if (customMembers.length !== 1) {
600
+ return void 0;
601
+ }
602
+ const nonCustomMembers = fieldType.members.filter((member) => member.kind !== "custom");
603
+ const allOtherMembersAreNull = nonCustomMembers.every(
604
+ (member) => member.kind === "primitive" && member.primitiveKind === "null"
605
+ );
606
+ const customMember = customMembers[0];
607
+ return allOtherMembersAreNull && customMember !== void 0 ? customMember.typeId : void 0;
608
+ }
609
+ function hasBuiltinConstraintBroadening(tagName, options) {
610
+ const broadenedTypeId = getBroadenedCustomTypeId(options?.fieldType);
611
+ return broadenedTypeId !== void 0 && options?.extensionRegistry?.findBuiltinConstraintBroadening(broadenedTypeId, tagName) !== void 0;
612
+ }
613
+ function buildCompilerBackedConstraintDiagnostics(node, sourceFile, tagName, parsedTag, provenance, supportingDeclarations, options) {
614
+ if (!isBuiltinConstraintName(tagName)) {
615
+ return [];
616
+ }
617
+ const checker = options?.checker;
618
+ const subjectType = options?.subjectType;
619
+ if (checker === void 0 || subjectType === void 0) {
620
+ return [];
621
+ }
622
+ const placement = resolveDeclarationPlacement(node);
623
+ if (placement === null) {
624
+ return [];
625
+ }
626
+ const definition = getTagDefinition(tagName, options?.extensionRegistry?.extensions);
627
+ if (definition === null) {
628
+ return [];
629
+ }
630
+ if (!definition.placements.includes(placement)) {
631
+ return [
632
+ makeDiagnostic(
633
+ "INVALID_TAG_PLACEMENT",
634
+ `Tag "@${tagName}" is not allowed on ${placementLabel(placement)}.`,
635
+ provenance
636
+ )
637
+ ];
638
+ }
639
+ const target = parsedTag?.target ?? null;
640
+ const hasBroadening = target === null && hasBuiltinConstraintBroadening(tagName, options);
641
+ if (target !== null) {
642
+ if (target.kind !== "path") {
643
+ return [
644
+ makeDiagnostic(
645
+ "UNSUPPORTED_TARGETING_SYNTAX",
646
+ `Tag "@${tagName}" does not support ${target.kind} targeting syntax.`,
647
+ provenance
648
+ )
649
+ ];
650
+ }
651
+ if (!target.valid || target.path === null) {
652
+ return [
653
+ makeDiagnostic(
654
+ "UNSUPPORTED_TARGETING_SYNTAX",
655
+ `Tag "@${tagName}" has invalid path targeting syntax.`,
656
+ provenance
657
+ )
658
+ ];
659
+ }
660
+ const resolution = resolvePathTargetType(subjectType, checker, target.path.segments);
661
+ if (resolution.kind === "missing-property") {
662
+ return [
663
+ makeDiagnostic(
664
+ "UNKNOWN_PATH_TARGET",
665
+ `Target "${target.rawText}": path-targeted constraint "${tagName}" references unknown path segment "${resolution.segment}"`,
666
+ provenance
667
+ )
668
+ ];
669
+ }
670
+ if (resolution.kind === "unresolvable") {
671
+ const actualType = checker.typeToString(resolution.type, node, SYNTHETIC_TYPE_FORMAT_FLAGS);
672
+ return [
673
+ makeDiagnostic(
674
+ "TYPE_MISMATCH",
675
+ `Target "${target.rawText}": path-targeted constraint "${tagName}" is invalid because type "${actualType}" cannot be traversed`,
676
+ provenance
677
+ )
678
+ ];
679
+ }
680
+ const requiredCapability = definition.capabilities[0];
681
+ if (requiredCapability !== void 0 && !supportsConstraintCapability(resolution.type, checker, requiredCapability)) {
682
+ const actualType = checker.typeToString(resolution.type, node, SYNTHETIC_TYPE_FORMAT_FLAGS);
683
+ return [
684
+ makeDiagnostic(
685
+ "TYPE_MISMATCH",
686
+ `Target "${target.rawText}": constraint "${tagName}" is only valid on ${capabilityLabel(requiredCapability)} targets, but field type is "${actualType}"`,
687
+ provenance
688
+ )
689
+ ];
690
+ }
691
+ } else if (!hasBroadening) {
692
+ const requiredCapability = definition.capabilities[0];
693
+ if (requiredCapability !== void 0 && !supportsConstraintCapability(subjectType, checker, requiredCapability)) {
694
+ const actualType = checker.typeToString(subjectType, node, SYNTHETIC_TYPE_FORMAT_FLAGS);
695
+ return [
696
+ makeDiagnostic(
697
+ "TYPE_MISMATCH",
698
+ `Target "${node.getText(sourceFile)}": constraint "${tagName}" is only valid on ${capabilityLabel(requiredCapability)} targets, but field type is "${actualType}"`,
699
+ provenance
700
+ )
701
+ ];
702
+ }
703
+ }
704
+ const argumentExpression = renderSyntheticArgumentExpression(
705
+ definition.valueKind,
706
+ parsedTag?.argumentText ?? ""
707
+ );
708
+ if (definition.requiresArgument && argumentExpression === null) {
709
+ return [];
710
+ }
711
+ if (hasBroadening) {
712
+ return [];
713
+ }
714
+ const subjectTypeText = checker.typeToString(subjectType, node, SYNTHETIC_TYPE_FORMAT_FLAGS);
715
+ const hostType = options?.hostType ?? subjectType;
716
+ const hostTypeText = checker.typeToString(hostType, node, SYNTHETIC_TYPE_FORMAT_FLAGS);
717
+ const result = checkSyntheticTagApplication({
718
+ tagName,
719
+ placement,
720
+ hostType: hostTypeText,
721
+ subjectType: subjectTypeText,
722
+ ...target?.kind === "path" ? { target: { kind: "path", text: target.rawText } } : {},
723
+ ...argumentExpression !== null ? { argumentExpression } : {},
724
+ supportingDeclarations,
725
+ ...options?.extensionRegistry !== void 0 ? {
726
+ extensions: options.extensionRegistry.extensions.map((extension) => ({
727
+ extensionId: extension.extensionId,
728
+ ...extension.constraintTags !== void 0 ? {
729
+ constraintTags: extension.constraintTags.map((tag) => ({ tagName: tag.tagName }))
730
+ } : {}
731
+ }))
732
+ } : {}
733
+ });
734
+ if (result.diagnostics.length === 0) {
735
+ return [];
736
+ }
737
+ const expectedLabel = definition.valueKind === null ? "compatible argument" : capabilityLabel(definition.valueKind);
738
+ return [
739
+ makeDiagnostic(
740
+ "TYPE_MISMATCH",
741
+ `Tag "@${tagName}" received an invalid argument for ${expectedLabel}.`,
742
+ provenance
743
+ )
744
+ ];
745
+ }
746
+ var parserCache = /* @__PURE__ */ new Map();
747
+ var parseResultCache = /* @__PURE__ */ new Map();
748
+ function getParser(options) {
749
+ const extensionTagNames = [
750
+ ...options?.extensionRegistry?.extensions.flatMap(
751
+ (extension) => (extension.constraintTags ?? []).map((tag) => tag.tagName)
752
+ ) ?? []
753
+ ].sort();
754
+ const cacheKey = extensionTagNames.join("|");
755
+ const existing = parserCache.get(cacheKey);
756
+ if (existing) {
757
+ return existing;
758
+ }
759
+ const parser = new TSDocParser(createFormSpecTSDocConfig(extensionTagNames));
760
+ parserCache.set(cacheKey, parser);
761
+ return parser;
762
+ }
763
+ function getExtensionRegistryCacheKey(registry) {
764
+ if (registry === void 0) {
765
+ return "";
766
+ }
767
+ return registry.extensions.map(
768
+ (extension) => JSON.stringify({
769
+ extensionId: extension.extensionId,
770
+ typeNames: extension.types?.map((type) => type.typeName) ?? [],
771
+ constraintTags: extension.constraintTags?.map((tag) => tag.tagName) ?? []
772
+ })
773
+ ).join("|");
774
+ }
775
+ function getParseCacheKey(node, file, options) {
776
+ const sourceFile = node.getSourceFile();
777
+ const checker = options?.checker;
778
+ return JSON.stringify({
779
+ file,
780
+ sourceFile: sourceFile.fileName,
781
+ sourceText: sourceFile.text,
782
+ start: node.getFullStart(),
783
+ end: node.getEnd(),
784
+ fieldType: options?.fieldType ?? null,
785
+ subjectType: checker !== void 0 && options?.subjectType !== void 0 ? checker.typeToString(options.subjectType, node, SYNTHETIC_TYPE_FORMAT_FLAGS) : null,
786
+ hostType: checker !== void 0 && options?.hostType !== void 0 ? checker.typeToString(options.hostType, node, SYNTHETIC_TYPE_FORMAT_FLAGS) : null,
787
+ extensions: getExtensionRegistryCacheKey(options?.extensionRegistry)
788
+ });
789
+ }
790
+ function parseTSDocTags(node, file = "", options) {
791
+ const cacheKey = getParseCacheKey(node, file, options);
792
+ const cached = parseResultCache.get(cacheKey);
793
+ if (cached !== void 0) {
794
+ return cached;
795
+ }
796
+ const constraints = [];
797
+ const annotations = [];
798
+ const diagnostics = [];
799
+ let displayName;
800
+ let description;
801
+ let placeholder;
802
+ let displayNameProvenance;
803
+ let descriptionProvenance;
804
+ let placeholderProvenance;
805
+ const rawTextTags = [];
806
+ const sourceFile = node.getSourceFile();
807
+ const sourceText = sourceFile.getFullText();
808
+ const supportingDeclarations = buildSupportingDeclarations(sourceFile);
809
+ const commentRanges = ts.getLeadingCommentRanges(sourceText, node.getFullStart());
810
+ const rawTextFallbacks = collectRawTextFallbacks(node, file);
811
+ if (commentRanges) {
812
+ for (const range of commentRanges) {
813
+ if (range.kind !== ts.SyntaxKind.MultiLineCommentTrivia) {
814
+ continue;
815
+ }
816
+ const commentText = sourceText.substring(range.pos, range.end);
817
+ if (!commentText.startsWith("/**")) {
818
+ continue;
819
+ }
820
+ const parser = getParser(options);
821
+ const parserContext = parser.parseRange(
822
+ TextRange.fromStringRange(sourceText, range.pos, range.end)
823
+ );
824
+ const docComment = parserContext.docComment;
825
+ const parsedComment = parseCommentBlock(
826
+ commentText,
827
+ sharedCommentSyntaxOptions(options, range.pos)
828
+ );
829
+ let parsedTagCursor = 0;
830
+ const nextParsedTag = (normalizedTagName) => {
831
+ while (parsedTagCursor < parsedComment.tags.length) {
832
+ const candidate = parsedComment.tags[parsedTagCursor];
833
+ parsedTagCursor += 1;
834
+ if (candidate?.normalizedTagName === normalizedTagName) {
835
+ return candidate;
836
+ }
837
+ }
838
+ return null;
839
+ };
840
+ for (const parsedTag of parsedComment.tags) {
841
+ if (TAGS_REQUIRING_RAW_TEXT.has(parsedTag.normalizedTagName)) {
842
+ rawTextTags.push({ tag: parsedTag, commentText, commentOffset: range.pos });
843
+ }
844
+ }
845
+ for (const block of docComment.customBlocks) {
846
+ const tagName = normalizeConstraintTagName(block.blockTag.tagName.substring(1));
847
+ const parsedTag = nextParsedTag(tagName);
848
+ if (tagName === "displayName" || tagName === "description" || tagName === "format" || tagName === "placeholder") {
849
+ const text2 = getBestBlockPayloadText(parsedTag, commentText, range.pos, block);
850
+ if (text2 === "") continue;
851
+ const provenance2 = parsedTag !== null ? provenanceForParsedTag(parsedTag, sourceFile, file) : provenanceForComment(range, sourceFile, file, tagName);
852
+ switch (tagName) {
853
+ case "displayName":
854
+ if (!isMemberTargetDisplayName(text2) && displayName === void 0) {
855
+ displayName = text2;
856
+ displayNameProvenance = provenance2;
857
+ }
858
+ break;
859
+ case "format":
860
+ annotations.push({
861
+ kind: "annotation",
862
+ annotationKind: "format",
863
+ value: text2,
864
+ provenance: provenance2
865
+ });
866
+ break;
867
+ case "description":
868
+ description = text2;
869
+ descriptionProvenance = provenance2;
870
+ break;
871
+ case "placeholder":
872
+ if (placeholder === void 0) {
873
+ placeholder = text2;
874
+ placeholderProvenance = provenance2;
875
+ }
876
+ break;
877
+ }
878
+ continue;
879
+ }
880
+ if (TAGS_REQUIRING_RAW_TEXT.has(tagName)) continue;
881
+ const text = getBestBlockPayloadText(parsedTag, commentText, range.pos, block);
882
+ const expectedType = isBuiltinConstraintName(tagName) ? BUILTIN_CONSTRAINT_DEFINITIONS[tagName] : void 0;
883
+ if (text === "" && expectedType !== "boolean") continue;
884
+ const provenance = parsedTag !== null ? provenanceForParsedTag(parsedTag, sourceFile, file) : provenanceForComment(range, sourceFile, file, tagName);
885
+ const compilerDiagnostics = buildCompilerBackedConstraintDiagnostics(
886
+ node,
887
+ sourceFile,
888
+ tagName,
889
+ parsedTag,
890
+ provenance,
891
+ supportingDeclarations,
892
+ options
893
+ );
894
+ if (compilerDiagnostics.length > 0) {
895
+ diagnostics.push(...compilerDiagnostics);
896
+ continue;
897
+ }
898
+ const constraintNode = parseConstraintTagValue(
899
+ tagName,
900
+ text,
901
+ provenance,
902
+ sharedTagValueOptions(options)
903
+ );
904
+ if (constraintNode) {
905
+ constraints.push(constraintNode);
906
+ }
907
+ }
908
+ if (docComment.deprecatedBlock !== void 0) {
909
+ const message = extractBlockText(docComment.deprecatedBlock).trim();
910
+ annotations.push({
911
+ kind: "annotation",
912
+ annotationKind: "deprecated",
913
+ ...message !== "" && { message },
914
+ provenance: provenanceForComment(range, sourceFile, file, "deprecated")
915
+ });
916
+ }
917
+ if (description === void 0 && docComment.remarksBlock !== void 0) {
918
+ const remarks = extractBlockText(docComment.remarksBlock).trim();
919
+ if (remarks !== "") {
920
+ description = remarks;
921
+ descriptionProvenance = provenanceForComment(range, sourceFile, file, "remarks");
922
+ }
923
+ }
924
+ if (description === void 0) {
925
+ const summary = extractPlainText(docComment.summarySection).trim();
926
+ if (summary !== "") {
927
+ description = summary;
928
+ descriptionProvenance = provenanceForComment(range, sourceFile, file, "summary");
929
+ }
930
+ }
931
+ }
932
+ }
933
+ if (displayName !== void 0 && displayNameProvenance !== void 0) {
934
+ annotations.push({
935
+ kind: "annotation",
936
+ annotationKind: "displayName",
937
+ value: displayName,
938
+ provenance: displayNameProvenance
939
+ });
940
+ }
941
+ if (description !== void 0 && descriptionProvenance !== void 0) {
942
+ annotations.push({
943
+ kind: "annotation",
944
+ annotationKind: "description",
945
+ value: description,
946
+ provenance: descriptionProvenance
947
+ });
948
+ }
949
+ if (placeholder !== void 0 && placeholderProvenance !== void 0) {
950
+ annotations.push({
951
+ kind: "annotation",
952
+ annotationKind: "placeholder",
953
+ value: placeholder,
954
+ provenance: placeholderProvenance
955
+ });
956
+ }
957
+ if (rawTextTags.length > 0) {
958
+ for (const rawTextTag of rawTextTags) {
959
+ const fallbackQueue = rawTextFallbacks.get(rawTextTag.tag.normalizedTagName);
960
+ const fallback = fallbackQueue?.shift();
961
+ const text = choosePreferredPayloadText(
962
+ getSharedPayloadText(rawTextTag.tag, rawTextTag.commentText, rawTextTag.commentOffset),
963
+ fallback?.text ?? ""
964
+ );
965
+ if (text === "") continue;
966
+ const provenance = provenanceForParsedTag(rawTextTag.tag, sourceFile, file);
967
+ if (rawTextTag.tag.normalizedTagName === "defaultValue") {
968
+ const defaultValueNode = parseDefaultValueTagValue(text, provenance);
969
+ annotations.push(defaultValueNode);
970
+ continue;
971
+ }
972
+ const compilerDiagnostics = buildCompilerBackedConstraintDiagnostics(
973
+ node,
974
+ sourceFile,
975
+ rawTextTag.tag.normalizedTagName,
976
+ rawTextTag.tag,
977
+ provenance,
978
+ supportingDeclarations,
979
+ options
980
+ );
981
+ if (compilerDiagnostics.length > 0) {
982
+ diagnostics.push(...compilerDiagnostics);
983
+ continue;
984
+ }
985
+ const constraintNode = parseConstraintTagValue(
986
+ rawTextTag.tag.normalizedTagName,
987
+ text,
988
+ provenance,
989
+ sharedTagValueOptions(options)
990
+ );
991
+ if (constraintNode) {
992
+ constraints.push(constraintNode);
993
+ }
994
+ }
995
+ }
996
+ for (const [tagName, fallbacks] of rawTextFallbacks) {
997
+ for (const fallback of fallbacks) {
998
+ const text = fallback.text.trim();
999
+ if (text === "") continue;
1000
+ const provenance = fallback.provenance;
1001
+ if (tagName === "defaultValue") {
1002
+ const defaultValueNode = parseDefaultValueTagValue(text, provenance);
1003
+ annotations.push(defaultValueNode);
1004
+ continue;
1005
+ }
1006
+ const compilerDiagnostics = buildCompilerBackedConstraintDiagnostics(
1007
+ node,
1008
+ sourceFile,
1009
+ tagName,
1010
+ null,
1011
+ provenance,
1012
+ supportingDeclarations,
1013
+ options
1014
+ );
1015
+ if (compilerDiagnostics.length > 0) {
1016
+ diagnostics.push(...compilerDiagnostics);
1017
+ continue;
1018
+ }
1019
+ const constraintNode = parseConstraintTagValue(
1020
+ tagName,
1021
+ text,
1022
+ provenance,
1023
+ sharedTagValueOptions(options)
1024
+ );
1025
+ if (constraintNode) {
1026
+ constraints.push(constraintNode);
1027
+ }
1028
+ }
1029
+ }
1030
+ const result = { constraints, annotations, diagnostics };
1031
+ parseResultCache.set(cacheKey, result);
1032
+ return result;
1033
+ }
1034
+ function extractDisplayNameMetadata(node) {
1035
+ let displayName;
1036
+ const memberDisplayNames = /* @__PURE__ */ new Map();
1037
+ const sourceFile = node.getSourceFile();
1038
+ const sourceText = sourceFile.getFullText();
1039
+ const commentRanges = ts.getLeadingCommentRanges(sourceText, node.getFullStart());
1040
+ if (commentRanges) {
1041
+ for (const range of commentRanges) {
1042
+ if (range.kind !== ts.SyntaxKind.MultiLineCommentTrivia) continue;
1043
+ const commentText = sourceText.substring(range.pos, range.end);
1044
+ if (!commentText.startsWith("/**")) continue;
1045
+ const parsed = parseCommentBlock(commentText);
1046
+ for (const tag of parsed.tags) {
1047
+ if (tag.normalizedTagName !== "displayName") {
1048
+ continue;
1049
+ }
1050
+ if (tag.target !== null && tag.argumentText !== "") {
1051
+ memberDisplayNames.set(tag.target.rawText, tag.argumentText);
1052
+ continue;
1053
+ }
1054
+ if (tag.argumentText !== "") {
1055
+ displayName ??= tag.argumentText;
1056
+ }
1057
+ }
1058
+ }
1059
+ }
1060
+ return {
1061
+ ...displayName !== void 0 && { displayName },
1062
+ memberDisplayNames
1063
+ };
1064
+ }
1065
+ function extractBlockText(block) {
1066
+ return extractPlainText(block.content);
1067
+ }
1068
+ function extractPlainText(node) {
1069
+ let result = "";
1070
+ if (node instanceof DocPlainText) {
1071
+ return node.text;
1072
+ }
1073
+ if (node instanceof DocSoftBreak) {
1074
+ return " ";
1075
+ }
1076
+ if (typeof node.getChildNodes === "function") {
1077
+ for (const child of node.getChildNodes()) {
1078
+ result += extractPlainText(child);
1079
+ }
1080
+ }
1081
+ return result;
1082
+ }
1083
+ function choosePreferredPayloadText(primary, fallback) {
1084
+ const preferred = primary.trim();
1085
+ const alternate = fallback.trim();
1086
+ if (preferred === "") return alternate;
1087
+ if (alternate === "") return preferred;
1088
+ if (alternate.includes("\n")) return alternate;
1089
+ if (alternate.length > preferred.length && alternate.startsWith(preferred)) {
1090
+ return alternate;
1091
+ }
1092
+ return preferred;
1093
+ }
1094
+ function getSharedPayloadText(tag, commentText, commentOffset) {
1095
+ if (tag.payloadSpan === null) {
1096
+ return "";
1097
+ }
1098
+ return sliceCommentSpan(commentText, tag.payloadSpan, {
1099
+ offset: commentOffset
1100
+ }).trim();
1101
+ }
1102
+ function getBestBlockPayloadText(tag, commentText, commentOffset, block) {
1103
+ const sharedText = tag === null ? "" : getSharedPayloadText(tag, commentText, commentOffset);
1104
+ const blockText = extractBlockText(block).replace(/\s+/g, " ").trim();
1105
+ return choosePreferredPayloadText(sharedText, blockText);
1106
+ }
1107
+ function collectRawTextFallbacks(node, file) {
1108
+ const fallbacks = /* @__PURE__ */ new Map();
1109
+ for (const tag of ts.getJSDocTags(node)) {
1110
+ const tagName = normalizeConstraintTagName(tag.tagName.text);
1111
+ if (!TAGS_REQUIRING_RAW_TEXT.has(tagName)) continue;
1112
+ const commentText = getTagCommentText(tag)?.trim() ?? "";
1113
+ if (commentText === "") continue;
1114
+ const entries = fallbacks.get(tagName) ?? [];
1115
+ entries.push({
1116
+ text: commentText,
1117
+ provenance: provenanceForJSDocTag(tag, file)
1118
+ });
1119
+ fallbacks.set(tagName, entries);
1120
+ }
1121
+ return fallbacks;
1122
+ }
1123
+ function isMemberTargetDisplayName(text) {
1124
+ return parseTagSyntax("displayName", text).target !== null;
1125
+ }
1126
+ function provenanceForComment(range, sourceFile, file, tagName) {
1127
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(range.pos);
1128
+ return {
1129
+ surface: "tsdoc",
1130
+ file,
1131
+ line: line + 1,
1132
+ column: character,
1133
+ tagName: "@" + tagName
1134
+ };
1135
+ }
1136
+ function provenanceForParsedTag(tag, sourceFile, file) {
1137
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(tag.tagNameSpan.start);
1138
+ return {
1139
+ surface: "tsdoc",
1140
+ file,
1141
+ line: line + 1,
1142
+ column: character,
1143
+ tagName: "@" + tag.normalizedTagName
1144
+ };
1145
+ }
1146
+ function provenanceForJSDocTag(tag, file) {
1147
+ const sourceFile = tag.getSourceFile();
1148
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(tag.getStart());
1149
+ return {
1150
+ surface: "tsdoc",
1151
+ file,
1152
+ line: line + 1,
1153
+ column: character,
1154
+ tagName: "@" + tag.tagName.text
1155
+ };
1156
+ }
1157
+ function getTagCommentText(tag) {
1158
+ if (tag.comment === void 0) {
1159
+ return void 0;
1160
+ }
1161
+ if (typeof tag.comment === "string") {
1162
+ return tag.comment;
1163
+ }
1164
+ return ts.getTextOfJSDocComment(tag.comment);
1165
+ }
1166
+
1167
+ // src/analyzer/jsdoc-constraints.ts
1168
+ function extractJSDocParseResult(node, file = "", options) {
1169
+ return parseTSDocTags(node, file, options);
1170
+ }
1171
+ function extractJSDocConstraintNodes(node, file = "", options) {
1172
+ const result = extractJSDocParseResult(node, file, options);
1173
+ return [...result.constraints];
1174
+ }
1175
+ function extractJSDocAnnotationNodes(node, file = "", options) {
1176
+ const result = extractJSDocParseResult(node, file, options);
1177
+ return [...result.annotations];
1178
+ }
1179
+ function extractDefaultValueAnnotation(initializer, file = "") {
1180
+ if (!initializer) return null;
1181
+ let value;
1182
+ if (ts2.isStringLiteral(initializer)) {
1183
+ value = initializer.text;
1184
+ } else if (ts2.isNumericLiteral(initializer)) {
1185
+ value = Number(initializer.text);
1186
+ } else if (initializer.kind === ts2.SyntaxKind.TrueKeyword) {
1187
+ value = true;
1188
+ } else if (initializer.kind === ts2.SyntaxKind.FalseKeyword) {
1189
+ value = false;
1190
+ } else if (initializer.kind === ts2.SyntaxKind.NullKeyword) {
1191
+ value = null;
1192
+ } else if (ts2.isPrefixUnaryExpression(initializer)) {
1193
+ if (initializer.operator === ts2.SyntaxKind.MinusToken && ts2.isNumericLiteral(initializer.operand)) {
1194
+ value = -Number(initializer.operand.text);
1195
+ }
1196
+ }
1197
+ if (value === void 0) return null;
1198
+ const sourceFile = initializer.getSourceFile();
1199
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(initializer.getStart());
1200
+ return {
1201
+ kind: "annotation",
1202
+ annotationKind: "defaultValue",
1203
+ value,
1204
+ provenance: {
1205
+ surface: "tsdoc",
1206
+ file,
1207
+ line: line + 1,
1208
+ column: character
1209
+ }
1210
+ };
1211
+ }
1212
+
1213
+ // src/analyzer/class-analyzer.ts
1214
+ function isObjectType(type) {
1215
+ return !!(type.flags & ts3.TypeFlags.Object);
1216
+ }
1217
+ function isTypeReference(type) {
1218
+ return !!(type.flags & ts3.TypeFlags.Object) && !!(type.objectFlags & ts3.ObjectFlags.Reference);
1219
+ }
1220
+ var RESOLVING_TYPE_PLACEHOLDER = {
1221
+ kind: "object",
1222
+ properties: [],
1223
+ additionalProperties: true
1224
+ };
1225
+ function makeParseOptions(extensionRegistry, fieldType, checker, subjectType, hostType) {
1226
+ if (extensionRegistry === void 0 && fieldType === void 0 && checker === void 0 && subjectType === void 0 && hostType === void 0) {
1227
+ return void 0;
1228
+ }
1229
+ return {
1230
+ ...extensionRegistry !== void 0 && { extensionRegistry },
1231
+ ...fieldType !== void 0 && { fieldType },
1232
+ ...checker !== void 0 && { checker },
1233
+ ...subjectType !== void 0 && { subjectType },
1234
+ ...hostType !== void 0 && { hostType }
1235
+ };
1236
+ }
1237
+ function analyzeClassToIR(classDecl, checker, file = "", extensionRegistry) {
1238
+ const name = classDecl.name?.text ?? "AnonymousClass";
1239
+ const fields = [];
1240
+ const fieldLayouts = [];
1241
+ const typeRegistry = {};
1242
+ const diagnostics = [];
1243
+ const classType = checker.getTypeAtLocation(classDecl);
1244
+ const classDoc = extractJSDocParseResult(
1245
+ classDecl,
1246
+ file,
1247
+ makeParseOptions(extensionRegistry, void 0, checker, classType, classType)
1248
+ );
1249
+ const annotations = [...classDoc.annotations];
1250
+ diagnostics.push(...classDoc.diagnostics);
1251
+ const visiting = /* @__PURE__ */ new Set();
1252
+ const instanceMethods = [];
1253
+ const staticMethods = [];
1254
+ for (const member of classDecl.members) {
1255
+ if (ts3.isPropertyDeclaration(member)) {
1256
+ const fieldNode = analyzeFieldToIR(
1257
+ member,
1258
+ checker,
1259
+ file,
1260
+ typeRegistry,
1261
+ visiting,
1262
+ diagnostics,
1263
+ classType,
1264
+ extensionRegistry
1265
+ );
1266
+ if (fieldNode) {
1267
+ fields.push(fieldNode);
1268
+ fieldLayouts.push({});
1269
+ }
1270
+ } else if (ts3.isMethodDeclaration(member)) {
1271
+ const methodInfo = analyzeMethod(member, checker);
1272
+ if (methodInfo) {
1273
+ const isStatic = member.modifiers?.some((m) => m.kind === ts3.SyntaxKind.StaticKeyword);
1274
+ if (isStatic) {
1275
+ staticMethods.push(methodInfo);
1276
+ } else {
1277
+ instanceMethods.push(methodInfo);
1278
+ }
1279
+ }
1280
+ }
1281
+ }
1282
+ return {
1283
+ name,
1284
+ fields,
1285
+ fieldLayouts,
1286
+ typeRegistry,
1287
+ ...annotations.length > 0 && { annotations },
1288
+ ...diagnostics.length > 0 && { diagnostics },
1289
+ instanceMethods,
1290
+ staticMethods
1291
+ };
1292
+ }
1293
+ function analyzeInterfaceToIR(interfaceDecl, checker, file = "", extensionRegistry) {
1294
+ const name = interfaceDecl.name.text;
1295
+ const fields = [];
1296
+ const typeRegistry = {};
1297
+ const diagnostics = [];
1298
+ const interfaceType = checker.getTypeAtLocation(interfaceDecl);
1299
+ const interfaceDoc = extractJSDocParseResult(
1300
+ interfaceDecl,
1301
+ file,
1302
+ makeParseOptions(extensionRegistry, void 0, checker, interfaceType, interfaceType)
1303
+ );
1304
+ const annotations = [...interfaceDoc.annotations];
1305
+ diagnostics.push(...interfaceDoc.diagnostics);
1306
+ const visiting = /* @__PURE__ */ new Set();
1307
+ for (const member of interfaceDecl.members) {
1308
+ if (ts3.isPropertySignature(member)) {
1309
+ const fieldNode = analyzeInterfacePropertyToIR(
1310
+ member,
1311
+ checker,
1312
+ file,
1313
+ typeRegistry,
1314
+ visiting,
1315
+ diagnostics,
1316
+ interfaceType,
1317
+ extensionRegistry
1318
+ );
1319
+ if (fieldNode) {
1320
+ fields.push(fieldNode);
1321
+ }
1322
+ }
1323
+ }
1324
+ const fieldLayouts = fields.map(() => ({}));
1325
+ return {
1326
+ name,
1327
+ fields,
1328
+ fieldLayouts,
1329
+ typeRegistry,
1330
+ ...annotations.length > 0 && { annotations },
1331
+ ...diagnostics.length > 0 && { diagnostics },
1332
+ instanceMethods: [],
1333
+ staticMethods: []
1334
+ };
1335
+ }
1336
+ function analyzeTypeAliasToIR(typeAlias, checker, file = "", extensionRegistry) {
1337
+ if (!ts3.isTypeLiteralNode(typeAlias.type)) {
1338
+ const sourceFile = typeAlias.getSourceFile();
1339
+ const { line } = sourceFile.getLineAndCharacterOfPosition(typeAlias.getStart());
1340
+ const kindDesc = ts3.SyntaxKind[typeAlias.type.kind] ?? "unknown";
1341
+ return {
1342
+ ok: false,
1343
+ error: `Type alias "${typeAlias.name.text}" at line ${String(line + 1)} is not an object type literal (found ${kindDesc})`
1344
+ };
1345
+ }
1346
+ const name = typeAlias.name.text;
1347
+ const fields = [];
1348
+ const typeRegistry = {};
1349
+ const diagnostics = [];
1350
+ const aliasType = checker.getTypeAtLocation(typeAlias);
1351
+ const typeAliasDoc = extractJSDocParseResult(
1352
+ typeAlias,
1353
+ file,
1354
+ makeParseOptions(extensionRegistry, void 0, checker, aliasType, aliasType)
1355
+ );
1356
+ const annotations = [...typeAliasDoc.annotations];
1357
+ diagnostics.push(...typeAliasDoc.diagnostics);
1358
+ const visiting = /* @__PURE__ */ new Set();
1359
+ for (const member of typeAlias.type.members) {
1360
+ if (ts3.isPropertySignature(member)) {
1361
+ const fieldNode = analyzeInterfacePropertyToIR(
1362
+ member,
1363
+ checker,
1364
+ file,
1365
+ typeRegistry,
1366
+ visiting,
1367
+ diagnostics,
1368
+ aliasType,
1369
+ extensionRegistry
1370
+ );
1371
+ if (fieldNode) {
1372
+ fields.push(fieldNode);
1373
+ }
1374
+ }
1375
+ }
1376
+ return {
1377
+ ok: true,
1378
+ analysis: {
1379
+ name,
1380
+ fields,
1381
+ fieldLayouts: fields.map(() => ({})),
1382
+ typeRegistry,
1383
+ ...annotations.length > 0 && { annotations },
1384
+ ...diagnostics.length > 0 && { diagnostics },
1385
+ instanceMethods: [],
1386
+ staticMethods: []
1387
+ }
1388
+ };
1389
+ }
1390
+ function analyzeFieldToIR(prop, checker, file, typeRegistry, visiting, diagnostics, hostType, extensionRegistry) {
1391
+ if (!ts3.isIdentifier(prop.name)) {
1392
+ return null;
1393
+ }
1394
+ const name = prop.name.text;
1395
+ const tsType = checker.getTypeAtLocation(prop);
1396
+ const optional = prop.questionToken !== void 0;
1397
+ const provenance = provenanceForNode(prop, file);
1398
+ let type = resolveTypeNode(
1399
+ tsType,
1400
+ checker,
1401
+ file,
1402
+ typeRegistry,
1403
+ visiting,
1404
+ prop,
1405
+ extensionRegistry,
1406
+ diagnostics
1407
+ );
1408
+ const constraints = [];
1409
+ if (prop.type && !shouldEmitPrimitiveAliasDefinition(prop.type, checker)) {
1410
+ constraints.push(
1411
+ ...extractTypeAliasConstraintNodes(prop.type, checker, file, extensionRegistry)
1412
+ );
1413
+ }
1414
+ const docResult = extractJSDocParseResult(
1415
+ prop,
1416
+ file,
1417
+ makeParseOptions(extensionRegistry, type, checker, tsType, hostType)
1418
+ );
1419
+ constraints.push(...docResult.constraints);
1420
+ diagnostics.push(...docResult.diagnostics);
1421
+ let annotations = [];
1422
+ annotations.push(...docResult.annotations);
1423
+ const defaultAnnotation = extractDefaultValueAnnotation(prop.initializer, file);
1424
+ if (defaultAnnotation && !annotations.some((a) => a.annotationKind === "defaultValue")) {
1425
+ annotations.push(defaultAnnotation);
1426
+ }
1427
+ ({ type, annotations } = applyEnumMemberDisplayNames(type, annotations));
1428
+ return {
1429
+ kind: "field",
1430
+ name,
1431
+ type,
1432
+ required: !optional,
1433
+ constraints,
1434
+ annotations,
1435
+ provenance
1436
+ };
1437
+ }
1438
+ function analyzeInterfacePropertyToIR(prop, checker, file, typeRegistry, visiting, diagnostics, hostType, extensionRegistry) {
1439
+ if (!ts3.isIdentifier(prop.name)) {
1440
+ return null;
1441
+ }
1442
+ const name = prop.name.text;
1443
+ const tsType = checker.getTypeAtLocation(prop);
1444
+ const optional = prop.questionToken !== void 0;
1445
+ const provenance = provenanceForNode(prop, file);
1446
+ let type = resolveTypeNode(
1447
+ tsType,
1448
+ checker,
1449
+ file,
1450
+ typeRegistry,
1451
+ visiting,
1452
+ prop,
1453
+ extensionRegistry,
1454
+ diagnostics
1455
+ );
1456
+ const constraints = [];
1457
+ if (prop.type && !shouldEmitPrimitiveAliasDefinition(prop.type, checker)) {
1458
+ constraints.push(
1459
+ ...extractTypeAliasConstraintNodes(prop.type, checker, file, extensionRegistry)
1460
+ );
1461
+ }
1462
+ const docResult = extractJSDocParseResult(
1463
+ prop,
1464
+ file,
1465
+ makeParseOptions(extensionRegistry, type, checker, tsType, hostType)
1466
+ );
1467
+ constraints.push(...docResult.constraints);
1468
+ diagnostics.push(...docResult.diagnostics);
1469
+ let annotations = [];
1470
+ annotations.push(...docResult.annotations);
1471
+ ({ type, annotations } = applyEnumMemberDisplayNames(type, annotations));
1472
+ return {
1473
+ kind: "field",
1474
+ name,
1475
+ type,
1476
+ required: !optional,
1477
+ constraints,
1478
+ annotations,
1479
+ provenance
1480
+ };
1481
+ }
1482
+ function applyEnumMemberDisplayNames(type, annotations) {
1483
+ if (!annotations.some(
1484
+ (annotation) => annotation.annotationKind === "displayName" && annotation.value.trim().startsWith(":")
1485
+ )) {
1486
+ return { type, annotations: [...annotations] };
1487
+ }
1488
+ const consumed = /* @__PURE__ */ new Set();
1489
+ const nextType = rewriteEnumDisplayNames(type, annotations, consumed);
1490
+ if (consumed.size === 0) {
1491
+ return { type, annotations: [...annotations] };
1492
+ }
1493
+ return {
1494
+ type: nextType,
1495
+ annotations: annotations.filter((annotation) => !consumed.has(annotation))
1496
+ };
1497
+ }
1498
+ function rewriteEnumDisplayNames(type, annotations, consumed) {
1499
+ switch (type.kind) {
1500
+ case "enum":
1501
+ return applyEnumMemberDisplayNamesToEnum(type, annotations, consumed);
1502
+ case "union": {
1503
+ return {
1504
+ ...type,
1505
+ members: type.members.map(
1506
+ (member) => rewriteEnumDisplayNames(member, annotations, consumed)
1507
+ )
1508
+ };
1509
+ }
1510
+ default:
1511
+ return type;
1512
+ }
1513
+ }
1514
+ function applyEnumMemberDisplayNamesToEnum(type, annotations, consumed) {
1515
+ const displayNames = /* @__PURE__ */ new Map();
1516
+ for (const annotation of annotations) {
1517
+ if (annotation.annotationKind !== "displayName") continue;
1518
+ const parsed = parseEnumMemberDisplayName(annotation.value);
1519
+ if (!parsed) continue;
1520
+ consumed.add(annotation);
1521
+ const member = type.members.find((m) => String(m.value) === parsed.value);
1522
+ if (!member) continue;
1523
+ displayNames.set(String(member.value), parsed.label);
1524
+ }
1525
+ if (displayNames.size === 0) {
1526
+ return type;
1527
+ }
1528
+ return {
1529
+ ...type,
1530
+ members: type.members.map((member) => {
1531
+ const displayName = displayNames.get(String(member.value));
1532
+ return displayName !== void 0 ? { ...member, displayName } : member;
1533
+ })
1534
+ };
1535
+ }
1536
+ function parseEnumMemberDisplayName(value) {
1537
+ const trimmed = value.trim();
1538
+ const match = /^:([^\s]+)\s+([\s\S]+)$/.exec(trimmed);
1539
+ if (!match?.[1] || !match[2]) return null;
1540
+ const label = match[2].trim();
1541
+ if (label === "") return null;
1542
+ return { value: match[1], label };
1543
+ }
1544
+ function resolveRegisteredCustomType(sourceNode, extensionRegistry, checker) {
1545
+ if (sourceNode === void 0 || extensionRegistry === void 0) {
1546
+ return null;
1547
+ }
1548
+ const typeNode = extractTypeNodeFromSource(sourceNode);
1549
+ if (typeNode === void 0) {
1550
+ return null;
1551
+ }
1552
+ return resolveRegisteredCustomTypeFromTypeNode(typeNode, extensionRegistry, checker);
1553
+ }
1554
+ function resolveRegisteredCustomTypeFromTypeNode(typeNode, extensionRegistry, checker) {
1555
+ if (ts3.isParenthesizedTypeNode(typeNode)) {
1556
+ return resolveRegisteredCustomTypeFromTypeNode(typeNode.type, extensionRegistry, checker);
1557
+ }
1558
+ const typeName = getTypeNodeRegistrationName(typeNode);
1559
+ if (typeName === null) {
1560
+ return null;
1561
+ }
1562
+ const registration = extensionRegistry.findTypeByName(typeName);
1563
+ if (registration !== void 0) {
1564
+ return {
1565
+ kind: "custom",
1566
+ typeId: `${registration.extensionId}/${registration.registration.typeName}`,
1567
+ payload: null
1568
+ };
1569
+ }
1570
+ if (ts3.isTypeReferenceNode(typeNode) && ts3.isIdentifier(typeNode.typeName)) {
1571
+ const aliasDecl = checker.getSymbolAtLocation(typeNode.typeName)?.declarations?.find(ts3.isTypeAliasDeclaration);
1572
+ if (aliasDecl !== void 0) {
1573
+ return resolveRegisteredCustomTypeFromTypeNode(aliasDecl.type, extensionRegistry, checker);
1574
+ }
1575
+ }
1576
+ return null;
1577
+ }
1578
+ function extractTypeNodeFromSource(sourceNode) {
1579
+ if (ts3.isPropertyDeclaration(sourceNode) || ts3.isPropertySignature(sourceNode) || ts3.isParameter(sourceNode) || ts3.isTypeAliasDeclaration(sourceNode)) {
1580
+ return sourceNode.type;
1581
+ }
1582
+ if (ts3.isTypeNode(sourceNode)) {
1583
+ return sourceNode;
1584
+ }
1585
+ return void 0;
1586
+ }
1587
+ function getTypeNodeRegistrationName(typeNode) {
1588
+ if (ts3.isTypeReferenceNode(typeNode)) {
1589
+ return ts3.isIdentifier(typeNode.typeName) ? typeNode.typeName.text : typeNode.typeName.right.text;
1590
+ }
1591
+ if (ts3.isParenthesizedTypeNode(typeNode)) {
1592
+ return getTypeNodeRegistrationName(typeNode.type);
1593
+ }
1594
+ if (typeNode.kind === ts3.SyntaxKind.BigIntKeyword || typeNode.kind === ts3.SyntaxKind.StringKeyword || typeNode.kind === ts3.SyntaxKind.NumberKeyword || typeNode.kind === ts3.SyntaxKind.BooleanKeyword) {
1595
+ return typeNode.getText();
1596
+ }
1597
+ return null;
1598
+ }
1599
+ function resolveTypeNode(type, checker, file, typeRegistry, visiting, sourceNode, extensionRegistry, diagnostics) {
1600
+ const customType = resolveRegisteredCustomType(sourceNode, extensionRegistry, checker);
1601
+ if (customType) {
1602
+ return customType;
1603
+ }
1604
+ const primitiveAlias = tryResolveNamedPrimitiveAlias(
1605
+ type,
1606
+ checker,
1607
+ file,
1608
+ typeRegistry,
1609
+ visiting,
1610
+ sourceNode,
1611
+ extensionRegistry,
1612
+ diagnostics
1613
+ );
1614
+ if (primitiveAlias) {
1615
+ return primitiveAlias;
1616
+ }
1617
+ if (type.flags & ts3.TypeFlags.String) {
1618
+ return { kind: "primitive", primitiveKind: "string" };
1619
+ }
1620
+ if (type.flags & ts3.TypeFlags.Number) {
1621
+ return { kind: "primitive", primitiveKind: "number" };
1622
+ }
1623
+ if (type.flags & (ts3.TypeFlags.BigInt | ts3.TypeFlags.BigIntLiteral)) {
1624
+ return { kind: "primitive", primitiveKind: "bigint" };
1625
+ }
1626
+ if (type.flags & ts3.TypeFlags.Boolean) {
1627
+ return { kind: "primitive", primitiveKind: "boolean" };
1628
+ }
1629
+ if (type.flags & ts3.TypeFlags.Null) {
1630
+ return { kind: "primitive", primitiveKind: "null" };
1631
+ }
1632
+ if (type.flags & ts3.TypeFlags.Undefined) {
1633
+ return { kind: "primitive", primitiveKind: "null" };
1634
+ }
1635
+ if (type.isStringLiteral()) {
1636
+ return {
1637
+ kind: "enum",
1638
+ members: [{ value: type.value }]
1639
+ };
1640
+ }
1641
+ if (type.isNumberLiteral()) {
1642
+ return {
1643
+ kind: "enum",
1644
+ members: [{ value: type.value }]
1645
+ };
1646
+ }
1647
+ if (type.isUnion()) {
1648
+ return resolveUnionType(
1649
+ type,
1650
+ checker,
1651
+ file,
1652
+ typeRegistry,
1653
+ visiting,
1654
+ sourceNode,
1655
+ extensionRegistry,
1656
+ diagnostics
1657
+ );
1658
+ }
1659
+ if (checker.isArrayType(type)) {
1660
+ return resolveArrayType(
1661
+ type,
1662
+ checker,
1663
+ file,
1664
+ typeRegistry,
1665
+ visiting,
1666
+ sourceNode,
1667
+ extensionRegistry,
1668
+ diagnostics
1669
+ );
1670
+ }
1671
+ if (isObjectType(type)) {
1672
+ return resolveObjectType(
1673
+ type,
1674
+ checker,
1675
+ file,
1676
+ typeRegistry,
1677
+ visiting,
1678
+ extensionRegistry,
1679
+ diagnostics
1680
+ );
1681
+ }
1682
+ return { kind: "primitive", primitiveKind: "string" };
1683
+ }
1684
+ function tryResolveNamedPrimitiveAlias(type, checker, file, typeRegistry, visiting, sourceNode, extensionRegistry, diagnostics) {
1685
+ if (!(type.flags & (ts3.TypeFlags.String | ts3.TypeFlags.Number | ts3.TypeFlags.BigInt | ts3.TypeFlags.BigIntLiteral | ts3.TypeFlags.Boolean | ts3.TypeFlags.Null))) {
1686
+ return null;
1687
+ }
1688
+ const aliasDecl = type.aliasSymbol?.declarations?.find(ts3.isTypeAliasDeclaration) ?? getReferencedTypeAliasDeclaration(sourceNode, checker);
1689
+ if (!aliasDecl) {
1690
+ return null;
1691
+ }
1692
+ const aliasName = aliasDecl.name.text;
1693
+ if (!typeRegistry[aliasName]) {
1694
+ const aliasType = checker.getTypeFromTypeNode(aliasDecl.type);
1695
+ const constraints = [
1696
+ ...extractJSDocConstraintNodes(aliasDecl, file, makeParseOptions(extensionRegistry)),
1697
+ ...extractTypeAliasConstraintNodes(aliasDecl.type, checker, file, extensionRegistry)
1698
+ ];
1699
+ const annotations = extractJSDocAnnotationNodes(
1700
+ aliasDecl,
1701
+ file,
1702
+ makeParseOptions(extensionRegistry)
1703
+ );
1704
+ typeRegistry[aliasName] = {
1705
+ name: aliasName,
1706
+ type: resolveAliasedPrimitiveTarget(
1707
+ aliasType,
1708
+ checker,
1709
+ file,
1710
+ typeRegistry,
1711
+ visiting,
1712
+ extensionRegistry,
1713
+ diagnostics
1714
+ ),
1715
+ ...constraints.length > 0 && { constraints },
1716
+ ...annotations.length > 0 && { annotations },
1717
+ provenance: provenanceForDeclaration(aliasDecl, file)
1718
+ };
1719
+ }
1720
+ return { kind: "reference", name: aliasName, typeArguments: [] };
1721
+ }
1722
+ function getReferencedTypeAliasDeclaration(sourceNode, checker) {
1723
+ const typeNode = sourceNode && (ts3.isPropertyDeclaration(sourceNode) || ts3.isPropertySignature(sourceNode) || ts3.isParameter(sourceNode)) ? sourceNode.type : void 0;
1724
+ if (!typeNode || !ts3.isTypeReferenceNode(typeNode)) {
1725
+ return void 0;
1726
+ }
1727
+ return checker.getSymbolAtLocation(typeNode.typeName)?.declarations?.find(ts3.isTypeAliasDeclaration);
1728
+ }
1729
+ function shouldEmitPrimitiveAliasDefinition(typeNode, checker) {
1730
+ if (!ts3.isTypeReferenceNode(typeNode)) {
1731
+ return false;
1732
+ }
1733
+ const aliasDecl = checker.getSymbolAtLocation(typeNode.typeName)?.declarations?.find(ts3.isTypeAliasDeclaration);
1734
+ if (!aliasDecl) {
1735
+ return false;
1736
+ }
1737
+ const resolved = checker.getTypeFromTypeNode(aliasDecl.type);
1738
+ return !!(resolved.flags & (ts3.TypeFlags.String | ts3.TypeFlags.Number | ts3.TypeFlags.BigInt | ts3.TypeFlags.BigIntLiteral | ts3.TypeFlags.Boolean | ts3.TypeFlags.Null));
1739
+ }
1740
+ function resolveAliasedPrimitiveTarget(type, checker, file, typeRegistry, visiting, extensionRegistry, diagnostics) {
1741
+ const nestedAliasDecl = type.aliasSymbol?.declarations?.find(ts3.isTypeAliasDeclaration);
1742
+ if (nestedAliasDecl !== void 0) {
1743
+ return resolveAliasedPrimitiveTarget(
1744
+ checker.getTypeFromTypeNode(nestedAliasDecl.type),
1745
+ checker,
1746
+ file,
1747
+ typeRegistry,
1748
+ visiting,
1749
+ extensionRegistry,
1750
+ diagnostics
1751
+ );
1752
+ }
1753
+ return resolveTypeNode(
1754
+ type,
1755
+ checker,
1756
+ file,
1757
+ typeRegistry,
1758
+ visiting,
1759
+ void 0,
1760
+ extensionRegistry,
1761
+ diagnostics
1762
+ );
1763
+ }
1764
+ function resolveUnionType(type, checker, file, typeRegistry, visiting, sourceNode, extensionRegistry, diagnostics) {
1765
+ const typeName = getNamedTypeName(type);
1766
+ const namedDecl = getNamedTypeDeclaration(type);
1767
+ if (typeName && typeName in typeRegistry) {
1768
+ return { kind: "reference", name: typeName, typeArguments: [] };
1769
+ }
1770
+ const allTypes = type.types;
1771
+ const unionMemberTypeNodes = extractUnionMemberTypeNodes(sourceNode, checker);
1772
+ const nonNullSourceNodes = unionMemberTypeNodes.filter(
1773
+ (memberTypeNode) => !isNullishTypeNode(resolveAliasedTypeNode(memberTypeNode, checker))
1774
+ );
1775
+ const nonNullTypes = allTypes.filter(
1776
+ (memberType) => !(memberType.flags & (ts3.TypeFlags.Null | ts3.TypeFlags.Undefined))
1777
+ );
1778
+ const nonNullMembers = nonNullTypes.map((memberType, index) => ({
1779
+ memberType,
1780
+ sourceNode: nonNullSourceNodes.length === nonNullTypes.length ? nonNullSourceNodes[index] : void 0
1781
+ }));
1782
+ const hasNull = allTypes.some((t) => t.flags & ts3.TypeFlags.Null);
1783
+ const memberDisplayNames = /* @__PURE__ */ new Map();
1784
+ if (namedDecl) {
1785
+ for (const [value, label] of extractDisplayNameMetadata(namedDecl).memberDisplayNames) {
1786
+ memberDisplayNames.set(value, label);
1787
+ }
1788
+ }
1789
+ if (sourceNode) {
1790
+ for (const [value, label] of extractDisplayNameMetadata(sourceNode).memberDisplayNames) {
1791
+ memberDisplayNames.set(value, label);
1792
+ }
1793
+ }
1794
+ const registerNamed = (result) => {
1795
+ if (!typeName) {
1796
+ return result;
1797
+ }
1798
+ const annotations = namedDecl ? extractJSDocAnnotationNodes(namedDecl, file, makeParseOptions(extensionRegistry)) : void 0;
1799
+ typeRegistry[typeName] = {
1800
+ name: typeName,
1801
+ type: result,
1802
+ ...annotations !== void 0 && annotations.length > 0 && { annotations },
1803
+ provenance: provenanceForDeclaration(namedDecl ?? sourceNode, file)
1804
+ };
1805
+ return { kind: "reference", name: typeName, typeArguments: [] };
1806
+ };
1807
+ const applyMemberLabels = (members2) => members2.map((value) => {
1808
+ const displayName = memberDisplayNames.get(String(value));
1809
+ return displayName !== void 0 ? { value, displayName } : { value };
1810
+ });
1811
+ const isBooleanUnion2 = nonNullTypes.length === 2 && nonNullTypes.every((t) => t.flags & ts3.TypeFlags.BooleanLiteral);
1812
+ if (isBooleanUnion2) {
1813
+ const boolNode = { kind: "primitive", primitiveKind: "boolean" };
1814
+ const result = hasNull ? {
1815
+ kind: "union",
1816
+ members: [boolNode, { kind: "primitive", primitiveKind: "null" }]
1817
+ } : boolNode;
1818
+ return registerNamed(result);
1819
+ }
1820
+ const allStringLiterals = nonNullTypes.every((t) => t.isStringLiteral());
1821
+ if (allStringLiterals && nonNullTypes.length > 0) {
1822
+ const stringTypes = nonNullTypes.filter((t) => t.isStringLiteral());
1823
+ const enumNode = {
1824
+ kind: "enum",
1825
+ members: applyMemberLabels(stringTypes.map((t) => t.value))
1826
+ };
1827
+ const result = hasNull ? {
1828
+ kind: "union",
1829
+ members: [enumNode, { kind: "primitive", primitiveKind: "null" }]
1830
+ } : enumNode;
1831
+ return registerNamed(result);
1832
+ }
1833
+ const allNumberLiterals = nonNullTypes.every((t) => t.isNumberLiteral());
1834
+ if (allNumberLiterals && nonNullTypes.length > 0) {
1835
+ const numberTypes = nonNullTypes.filter((t) => t.isNumberLiteral());
1836
+ const enumNode = {
1837
+ kind: "enum",
1838
+ members: applyMemberLabels(numberTypes.map((t) => t.value))
1839
+ };
1840
+ const result = hasNull ? {
1841
+ kind: "union",
1842
+ members: [enumNode, { kind: "primitive", primitiveKind: "null" }]
1843
+ } : enumNode;
1844
+ return registerNamed(result);
1845
+ }
1846
+ if (nonNullMembers.length === 1 && nonNullMembers[0]) {
1847
+ const inner = resolveTypeNode(
1848
+ nonNullMembers[0].memberType,
1849
+ checker,
1850
+ file,
1851
+ typeRegistry,
1852
+ visiting,
1853
+ nonNullMembers[0].sourceNode ?? sourceNode,
1854
+ extensionRegistry,
1855
+ diagnostics
1856
+ );
1857
+ const result = hasNull ? {
1858
+ kind: "union",
1859
+ members: [inner, { kind: "primitive", primitiveKind: "null" }]
1860
+ } : inner;
1861
+ return registerNamed(result);
1862
+ }
1863
+ const members = nonNullMembers.map(
1864
+ ({ memberType, sourceNode: memberSourceNode }) => resolveTypeNode(
1865
+ memberType,
1866
+ checker,
1867
+ file,
1868
+ typeRegistry,
1869
+ visiting,
1870
+ memberSourceNode ?? sourceNode,
1871
+ extensionRegistry,
1872
+ diagnostics
1873
+ )
1874
+ );
1875
+ if (hasNull) {
1876
+ members.push({ kind: "primitive", primitiveKind: "null" });
1877
+ }
1878
+ return registerNamed({ kind: "union", members });
1879
+ }
1880
+ function resolveArrayType(type, checker, file, typeRegistry, visiting, sourceNode, extensionRegistry, diagnostics) {
1881
+ const typeArgs = isTypeReference(type) ? type.typeArguments : void 0;
1882
+ const elementType = typeArgs?.[0];
1883
+ const elementSourceNode = extractArrayElementTypeNode(sourceNode, checker);
1884
+ const items = elementType ? resolveTypeNode(
1885
+ elementType,
1886
+ checker,
1887
+ file,
1888
+ typeRegistry,
1889
+ visiting,
1890
+ elementSourceNode,
1891
+ extensionRegistry,
1892
+ diagnostics
1893
+ ) : { kind: "primitive", primitiveKind: "string" };
1894
+ return { kind: "array", items };
1895
+ }
1896
+ function tryResolveRecordType(type, checker, file, typeRegistry, visiting, extensionRegistry, diagnostics) {
1897
+ if (type.getProperties().length > 0) {
1898
+ return null;
1899
+ }
1900
+ const indexInfo = checker.getIndexInfoOfType(type, ts3.IndexKind.String);
1901
+ if (!indexInfo) {
1902
+ return null;
1903
+ }
1904
+ const valueType = resolveTypeNode(
1905
+ indexInfo.type,
1906
+ checker,
1907
+ file,
1908
+ typeRegistry,
1909
+ visiting,
1910
+ void 0,
1911
+ extensionRegistry,
1912
+ diagnostics
1913
+ );
1914
+ return { kind: "record", valueType };
1915
+ }
1916
+ function typeNodeContainsReference(type, targetName) {
1917
+ switch (type.kind) {
1918
+ case "reference":
1919
+ return type.name === targetName;
1920
+ case "array":
1921
+ return typeNodeContainsReference(type.items, targetName);
1922
+ case "record":
1923
+ return typeNodeContainsReference(type.valueType, targetName);
1924
+ case "union":
1925
+ return type.members.some((member) => typeNodeContainsReference(member, targetName));
1926
+ case "object":
1927
+ return type.properties.some(
1928
+ (property) => typeNodeContainsReference(property.type, targetName)
1929
+ );
1930
+ case "primitive":
1931
+ case "enum":
1932
+ case "dynamic":
1933
+ case "custom":
1934
+ return false;
1935
+ default: {
1936
+ const _exhaustive = type;
1937
+ return _exhaustive;
1938
+ }
1939
+ }
1940
+ }
1941
+ function resolveObjectType(type, checker, file, typeRegistry, visiting, extensionRegistry, diagnostics) {
1942
+ const typeName = getNamedTypeName(type);
1943
+ const namedTypeName = typeName ?? void 0;
1944
+ const namedDecl = getNamedTypeDeclaration(type);
1945
+ const shouldRegisterNamedType = namedTypeName !== void 0 && !(namedTypeName === "Record" && namedDecl?.getSourceFile().fileName !== file);
1946
+ const clearNamedTypeRegistration = () => {
1947
+ if (namedTypeName === void 0 || !shouldRegisterNamedType) {
1948
+ return;
1949
+ }
1950
+ Reflect.deleteProperty(typeRegistry, namedTypeName);
1951
+ };
1952
+ if (visiting.has(type)) {
1953
+ if (namedTypeName !== void 0 && shouldRegisterNamedType) {
1954
+ return { kind: "reference", name: namedTypeName, typeArguments: [] };
1955
+ }
1956
+ return { kind: "object", properties: [], additionalProperties: false };
1957
+ }
1958
+ if (namedTypeName !== void 0 && shouldRegisterNamedType && !typeRegistry[namedTypeName]) {
1959
+ typeRegistry[namedTypeName] = {
1960
+ name: namedTypeName,
1961
+ type: RESOLVING_TYPE_PLACEHOLDER,
1962
+ provenance: provenanceForDeclaration(namedDecl, file)
1963
+ };
1964
+ }
1965
+ visiting.add(type);
1966
+ if (namedTypeName !== void 0 && shouldRegisterNamedType && typeRegistry[namedTypeName]?.type !== void 0) {
1967
+ if (typeRegistry[namedTypeName].type !== RESOLVING_TYPE_PLACEHOLDER) {
1968
+ visiting.delete(type);
1969
+ return { kind: "reference", name: namedTypeName, typeArguments: [] };
1970
+ }
1971
+ }
1972
+ const recordNode = tryResolveRecordType(
1973
+ type,
1974
+ checker,
1975
+ file,
1976
+ typeRegistry,
1977
+ visiting,
1978
+ extensionRegistry,
1979
+ diagnostics
1980
+ );
1981
+ if (recordNode) {
1982
+ visiting.delete(type);
1983
+ if (namedTypeName !== void 0 && shouldRegisterNamedType) {
1984
+ const isRecursiveRecord = typeNodeContainsReference(recordNode.valueType, namedTypeName);
1985
+ if (!isRecursiveRecord) {
1986
+ clearNamedTypeRegistration();
1987
+ return recordNode;
1988
+ }
1989
+ const annotations = namedDecl ? extractJSDocAnnotationNodes(namedDecl, file, makeParseOptions(extensionRegistry)) : void 0;
1990
+ typeRegistry[namedTypeName] = {
1991
+ name: namedTypeName,
1992
+ type: recordNode,
1993
+ ...annotations !== void 0 && annotations.length > 0 && { annotations },
1994
+ provenance: provenanceForDeclaration(namedDecl, file)
1995
+ };
1996
+ return { kind: "reference", name: namedTypeName, typeArguments: [] };
1997
+ }
1998
+ return recordNode;
1999
+ }
2000
+ const properties = [];
2001
+ const fieldInfoMap = getNamedTypeFieldNodeInfoMap(
2002
+ type,
2003
+ checker,
2004
+ file,
2005
+ typeRegistry,
2006
+ visiting,
2007
+ diagnostics ?? [],
2008
+ extensionRegistry
2009
+ );
2010
+ for (const prop of type.getProperties()) {
2011
+ const declaration = prop.valueDeclaration ?? prop.declarations?.[0];
2012
+ if (!declaration) continue;
2013
+ const propType = checker.getTypeOfSymbolAtLocation(prop, declaration);
2014
+ const optional = !!(prop.flags & ts3.SymbolFlags.Optional);
2015
+ const propTypeNode = resolveTypeNode(
2016
+ propType,
2017
+ checker,
2018
+ file,
2019
+ typeRegistry,
2020
+ visiting,
2021
+ declaration,
2022
+ extensionRegistry,
2023
+ diagnostics
2024
+ );
2025
+ const fieldNodeInfo = fieldInfoMap?.get(prop.name);
2026
+ properties.push({
2027
+ name: prop.name,
2028
+ type: propTypeNode,
2029
+ optional,
2030
+ constraints: fieldNodeInfo?.constraints ?? [],
2031
+ annotations: fieldNodeInfo?.annotations ?? [],
2032
+ provenance: fieldNodeInfo?.provenance ?? provenanceForFile(file)
2033
+ });
2034
+ }
2035
+ visiting.delete(type);
2036
+ const objectNode = {
2037
+ kind: "object",
2038
+ properties,
2039
+ additionalProperties: true
2040
+ };
2041
+ if (namedTypeName !== void 0 && shouldRegisterNamedType) {
2042
+ const annotations = namedDecl ? extractJSDocAnnotationNodes(namedDecl, file, makeParseOptions(extensionRegistry)) : void 0;
2043
+ typeRegistry[namedTypeName] = {
2044
+ name: namedTypeName,
2045
+ type: objectNode,
2046
+ ...annotations !== void 0 && annotations.length > 0 && { annotations },
2047
+ provenance: provenanceForDeclaration(namedDecl, file)
2048
+ };
2049
+ return { kind: "reference", name: namedTypeName, typeArguments: [] };
2050
+ }
2051
+ return objectNode;
2052
+ }
2053
+ function getNamedTypeFieldNodeInfoMap(type, checker, file, typeRegistry, visiting, diagnostics, extensionRegistry) {
2054
+ const symbols = [type.getSymbol(), type.aliasSymbol].filter(
2055
+ (s) => s?.declarations != null && s.declarations.length > 0
2056
+ );
2057
+ for (const symbol of symbols) {
2058
+ const declarations = symbol.declarations;
2059
+ if (!declarations) continue;
2060
+ const classDecl = declarations.find(ts3.isClassDeclaration);
2061
+ if (classDecl) {
2062
+ const map = /* @__PURE__ */ new Map();
2063
+ const hostType = checker.getTypeAtLocation(classDecl);
2064
+ for (const member of classDecl.members) {
2065
+ if (ts3.isPropertyDeclaration(member) && ts3.isIdentifier(member.name)) {
2066
+ const fieldNode = analyzeFieldToIR(
2067
+ member,
2068
+ checker,
2069
+ file,
2070
+ typeRegistry,
2071
+ visiting,
2072
+ diagnostics,
2073
+ hostType,
2074
+ extensionRegistry
2075
+ );
2076
+ if (fieldNode) {
2077
+ map.set(fieldNode.name, {
2078
+ constraints: [...fieldNode.constraints],
2079
+ annotations: [...fieldNode.annotations],
2080
+ provenance: fieldNode.provenance
2081
+ });
2082
+ }
2083
+ }
2084
+ }
2085
+ return map;
2086
+ }
2087
+ const interfaceDecl = declarations.find(ts3.isInterfaceDeclaration);
2088
+ if (interfaceDecl) {
2089
+ return buildFieldNodeInfoMap(
2090
+ interfaceDecl.members,
2091
+ checker,
2092
+ file,
2093
+ typeRegistry,
2094
+ visiting,
2095
+ checker.getTypeAtLocation(interfaceDecl),
2096
+ diagnostics,
2097
+ extensionRegistry
2098
+ );
2099
+ }
2100
+ const typeAliasDecl = declarations.find(ts3.isTypeAliasDeclaration);
2101
+ if (typeAliasDecl && ts3.isTypeLiteralNode(typeAliasDecl.type)) {
2102
+ return buildFieldNodeInfoMap(
2103
+ typeAliasDecl.type.members,
2104
+ checker,
2105
+ file,
2106
+ typeRegistry,
2107
+ visiting,
2108
+ checker.getTypeAtLocation(typeAliasDecl),
2109
+ diagnostics,
2110
+ extensionRegistry
2111
+ );
2112
+ }
2113
+ }
2114
+ return null;
2115
+ }
2116
+ function extractArrayElementTypeNode(sourceNode, checker) {
2117
+ const typeNode = sourceNode === void 0 ? void 0 : extractTypeNodeFromSource(sourceNode);
2118
+ if (typeNode === void 0) {
2119
+ return void 0;
2120
+ }
2121
+ const resolvedTypeNode = resolveAliasedTypeNode(typeNode, checker);
2122
+ if (ts3.isArrayTypeNode(resolvedTypeNode)) {
2123
+ return resolvedTypeNode.elementType;
2124
+ }
2125
+ if (ts3.isTypeReferenceNode(resolvedTypeNode) && ts3.isIdentifier(resolvedTypeNode.typeName) && resolvedTypeNode.typeName.text === "Array" && resolvedTypeNode.typeArguments?.[0]) {
2126
+ return resolvedTypeNode.typeArguments[0];
2127
+ }
2128
+ return void 0;
2129
+ }
2130
+ function extractUnionMemberTypeNodes(sourceNode, checker) {
2131
+ const typeNode = sourceNode === void 0 ? void 0 : extractTypeNodeFromSource(sourceNode);
2132
+ if (!typeNode) {
2133
+ return [];
2134
+ }
2135
+ const resolvedTypeNode = resolveAliasedTypeNode(typeNode, checker);
2136
+ return ts3.isUnionTypeNode(resolvedTypeNode) ? [...resolvedTypeNode.types] : [];
2137
+ }
2138
+ function resolveAliasedTypeNode(typeNode, checker, visited = /* @__PURE__ */ new Set()) {
2139
+ if (ts3.isParenthesizedTypeNode(typeNode)) {
2140
+ return resolveAliasedTypeNode(typeNode.type, checker, visited);
2141
+ }
2142
+ if (!ts3.isTypeReferenceNode(typeNode) || !ts3.isIdentifier(typeNode.typeName)) {
2143
+ return typeNode;
2144
+ }
2145
+ const symbol = checker.getSymbolAtLocation(typeNode.typeName);
2146
+ const aliasDecl = symbol?.declarations?.find(ts3.isTypeAliasDeclaration);
2147
+ if (aliasDecl === void 0 || visited.has(aliasDecl)) {
2148
+ return typeNode;
2149
+ }
2150
+ visited.add(aliasDecl);
2151
+ return resolveAliasedTypeNode(aliasDecl.type, checker, visited);
2152
+ }
2153
+ function isNullishTypeNode(typeNode) {
2154
+ if (typeNode.kind === ts3.SyntaxKind.NullKeyword || typeNode.kind === ts3.SyntaxKind.UndefinedKeyword) {
2155
+ return true;
2156
+ }
2157
+ return ts3.isLiteralTypeNode(typeNode) && (typeNode.literal.kind === ts3.SyntaxKind.NullKeyword || typeNode.literal.kind === ts3.SyntaxKind.UndefinedKeyword);
2158
+ }
2159
+ function buildFieldNodeInfoMap(members, checker, file, typeRegistry, visiting, hostType, diagnostics, extensionRegistry) {
2160
+ const map = /* @__PURE__ */ new Map();
2161
+ for (const member of members) {
2162
+ if (ts3.isPropertySignature(member)) {
2163
+ const fieldNode = analyzeInterfacePropertyToIR(
2164
+ member,
2165
+ checker,
2166
+ file,
2167
+ typeRegistry,
2168
+ visiting,
2169
+ diagnostics,
2170
+ hostType,
2171
+ extensionRegistry
2172
+ );
2173
+ if (fieldNode) {
2174
+ map.set(fieldNode.name, {
2175
+ constraints: [...fieldNode.constraints],
2176
+ annotations: [...fieldNode.annotations],
2177
+ provenance: fieldNode.provenance
2178
+ });
2179
+ }
2180
+ }
2181
+ }
2182
+ return map;
2183
+ }
2184
+ var MAX_ALIAS_CHAIN_DEPTH = 8;
2185
+ function extractTypeAliasConstraintNodes(typeNode, checker, file, extensionRegistry, depth = 0) {
2186
+ if (!ts3.isTypeReferenceNode(typeNode)) return [];
2187
+ if (depth >= MAX_ALIAS_CHAIN_DEPTH) {
2188
+ const aliasName = typeNode.typeName.getText();
2189
+ throw new Error(
2190
+ `Type alias chain exceeds maximum depth of ${String(MAX_ALIAS_CHAIN_DEPTH)} at alias "${aliasName}" in ${file}. Simplify the alias chain or check for circular references.`
2191
+ );
2192
+ }
2193
+ const symbol = checker.getSymbolAtLocation(typeNode.typeName);
2194
+ if (!symbol?.declarations) return [];
2195
+ const aliasDecl = symbol.declarations.find(ts3.isTypeAliasDeclaration);
2196
+ if (!aliasDecl) return [];
2197
+ if (ts3.isTypeLiteralNode(aliasDecl.type)) return [];
2198
+ const aliasFieldType = resolveTypeNode(
2199
+ checker.getTypeAtLocation(aliasDecl.type),
2200
+ checker,
2201
+ file,
2202
+ {},
2203
+ /* @__PURE__ */ new Set(),
2204
+ aliasDecl.type,
2205
+ extensionRegistry
2206
+ );
2207
+ const constraints = extractJSDocConstraintNodes(
2208
+ aliasDecl,
2209
+ file,
2210
+ makeParseOptions(extensionRegistry, aliasFieldType)
2211
+ );
2212
+ constraints.push(
2213
+ ...extractTypeAliasConstraintNodes(aliasDecl.type, checker, file, extensionRegistry, depth + 1)
2214
+ );
2215
+ return constraints;
2216
+ }
2217
+ function provenanceForNode(node, file) {
2218
+ const sourceFile = node.getSourceFile();
2219
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2220
+ return {
2221
+ surface: "tsdoc",
2222
+ file,
2223
+ line: line + 1,
2224
+ column: character
2225
+ };
2226
+ }
2227
+ function provenanceForFile(file) {
2228
+ return { surface: "tsdoc", file, line: 0, column: 0 };
2229
+ }
2230
+ function provenanceForDeclaration(node, file) {
2231
+ if (!node) {
2232
+ return provenanceForFile(file);
2233
+ }
2234
+ return provenanceForNode(node, file);
2235
+ }
2236
+ function getNamedTypeName(type) {
2237
+ const symbol = type.getSymbol();
2238
+ if (symbol?.declarations) {
2239
+ const decl = symbol.declarations[0];
2240
+ if (decl && (ts3.isClassDeclaration(decl) || ts3.isInterfaceDeclaration(decl) || ts3.isTypeAliasDeclaration(decl))) {
2241
+ const name = ts3.isClassDeclaration(decl) ? decl.name?.text : decl.name.text;
2242
+ if (name) return name;
2243
+ }
2244
+ }
2245
+ const aliasSymbol = type.aliasSymbol;
2246
+ if (aliasSymbol?.declarations) {
2247
+ const aliasDecl = aliasSymbol.declarations.find(ts3.isTypeAliasDeclaration);
2248
+ if (aliasDecl) {
2249
+ return aliasDecl.name.text;
2250
+ }
2251
+ }
2252
+ return null;
2253
+ }
2254
+ function getNamedTypeDeclaration(type) {
2255
+ const symbol = type.getSymbol();
2256
+ if (symbol?.declarations) {
2257
+ const decl = symbol.declarations[0];
2258
+ if (decl && (ts3.isClassDeclaration(decl) || ts3.isInterfaceDeclaration(decl) || ts3.isTypeAliasDeclaration(decl))) {
2259
+ return decl;
2260
+ }
2261
+ }
2262
+ const aliasSymbol = type.aliasSymbol;
2263
+ if (aliasSymbol?.declarations) {
2264
+ return aliasSymbol.declarations.find(ts3.isTypeAliasDeclaration);
2265
+ }
2266
+ return void 0;
2267
+ }
2268
+ function analyzeMethod(method, checker) {
2269
+ if (!ts3.isIdentifier(method.name)) {
2270
+ return null;
2271
+ }
2272
+ const name = method.name.text;
2273
+ const parameters = [];
2274
+ for (const param of method.parameters) {
2275
+ if (ts3.isIdentifier(param.name)) {
2276
+ const paramInfo = analyzeParameter(param, checker);
2277
+ parameters.push(paramInfo);
2278
+ }
2279
+ }
2280
+ const returnTypeNode = method.type;
2281
+ const signature = checker.getSignatureFromDeclaration(method);
2282
+ const returnType = signature ? checker.getReturnTypeOfSignature(signature) : checker.getTypeAtLocation(method);
2283
+ return { name, parameters, returnTypeNode, returnType };
2284
+ }
2285
+ function analyzeParameter(param, checker) {
2286
+ const name = ts3.isIdentifier(param.name) ? param.name.text : "param";
2287
+ const typeNode = param.type;
2288
+ const type = checker.getTypeAtLocation(param);
2289
+ const formSpecExportName = detectFormSpecReference(typeNode);
2290
+ const optional = param.questionToken !== void 0 || param.initializer !== void 0;
2291
+ return { name, typeNode, type, formSpecExportName, optional };
2292
+ }
2293
+ function detectFormSpecReference(typeNode) {
2294
+ if (!typeNode) return null;
2295
+ if (!ts3.isTypeReferenceNode(typeNode)) return null;
2296
+ const typeName = ts3.isIdentifier(typeNode.typeName) ? typeNode.typeName.text : ts3.isQualifiedName(typeNode.typeName) ? typeNode.typeName.right.text : null;
2297
+ if (typeName !== "InferSchema" && typeName !== "InferFormSchema") return null;
2298
+ const typeArg = typeNode.typeArguments?.[0];
2299
+ if (!typeArg || !ts3.isTypeQueryNode(typeArg)) return null;
2300
+ if (ts3.isIdentifier(typeArg.exprName)) {
2301
+ return typeArg.exprName.text;
2302
+ }
2303
+ if (ts3.isQualifiedName(typeArg.exprName)) {
2304
+ return typeArg.exprName.right.text;
2305
+ }
2306
+ return null;
2307
+ }
2308
+
2309
+ // src/analyzer/program.ts
2310
+ function createProgramContext(filePath) {
2311
+ const absolutePath = path.resolve(filePath);
2312
+ const fileDir = path.dirname(absolutePath);
2313
+ const configPath = ts4.findConfigFile(fileDir, ts4.sys.fileExists.bind(ts4.sys), "tsconfig.json");
2314
+ let compilerOptions;
2315
+ let fileNames;
2316
+ if (configPath) {
2317
+ const configFile = ts4.readConfigFile(configPath, ts4.sys.readFile.bind(ts4.sys));
2318
+ if (configFile.error) {
2319
+ throw new Error(
2320
+ `Error reading tsconfig.json: ${ts4.flattenDiagnosticMessageText(configFile.error.messageText, "\n")}`
2321
+ );
2322
+ }
2323
+ const parsed = ts4.parseJsonConfigFileContent(
2324
+ configFile.config,
2325
+ ts4.sys,
2326
+ path.dirname(configPath)
2327
+ );
2328
+ if (parsed.errors.length > 0) {
2329
+ const errorMessages = parsed.errors.map((e) => ts4.flattenDiagnosticMessageText(e.messageText, "\n")).join("\n");
2330
+ throw new Error(`Error parsing tsconfig.json: ${errorMessages}`);
2331
+ }
2332
+ compilerOptions = parsed.options;
2333
+ fileNames = parsed.fileNames.includes(absolutePath) ? parsed.fileNames : [...parsed.fileNames, absolutePath];
2334
+ } else {
2335
+ compilerOptions = {
2336
+ target: ts4.ScriptTarget.ES2022,
2337
+ module: ts4.ModuleKind.NodeNext,
2338
+ moduleResolution: ts4.ModuleResolutionKind.NodeNext,
2339
+ strict: true,
2340
+ skipLibCheck: true,
2341
+ declaration: true
2342
+ };
2343
+ fileNames = [absolutePath];
2344
+ }
2345
+ const program = ts4.createProgram(fileNames, compilerOptions);
2346
+ const sourceFile = program.getSourceFile(absolutePath);
2347
+ if (!sourceFile) {
2348
+ throw new Error(`Could not find source file: ${absolutePath}`);
2349
+ }
2350
+ return {
2351
+ program,
2352
+ checker: program.getTypeChecker(),
2353
+ sourceFile
2354
+ };
2355
+ }
2356
+ function findNodeByName(sourceFile, name, predicate, getName) {
2357
+ let result = null;
2358
+ function visit(node) {
2359
+ if (result) return;
2360
+ if (predicate(node) && getName(node) === name) {
2361
+ result = node;
2362
+ return;
2363
+ }
2364
+ ts4.forEachChild(node, visit);
2365
+ }
2366
+ visit(sourceFile);
2367
+ return result;
2368
+ }
2369
+ function findClassByName(sourceFile, className) {
2370
+ return findNodeByName(sourceFile, className, ts4.isClassDeclaration, (n) => n.name?.text);
2371
+ }
2372
+ function findInterfaceByName(sourceFile, interfaceName) {
2373
+ return findNodeByName(sourceFile, interfaceName, ts4.isInterfaceDeclaration, (n) => n.name.text);
2374
+ }
2375
+ function findTypeAliasByName(sourceFile, aliasName) {
2376
+ return findNodeByName(sourceFile, aliasName, ts4.isTypeAliasDeclaration, (n) => n.name.text);
2377
+ }
2378
+
2379
+ // src/json-schema/ir-generator.ts
2380
+ function makeContext(options) {
2381
+ const vendorPrefix = options?.vendorPrefix ?? "x-formspec";
2382
+ if (!vendorPrefix.startsWith("x-")) {
2383
+ throw new Error(
2384
+ `Invalid vendorPrefix "${vendorPrefix}". Extension JSON Schema keywords must start with "x-".`
2385
+ );
2386
+ }
2387
+ return {
2388
+ defs: {},
2389
+ extensionRegistry: options?.extensionRegistry,
2390
+ vendorPrefix
2391
+ };
2392
+ }
2393
+ function generateJsonSchemaFromIR(ir, options) {
2394
+ const ctx = makeContext(options);
2395
+ for (const [name, typeDef] of Object.entries(ir.typeRegistry)) {
2396
+ ctx.defs[name] = generateTypeNode(typeDef.type, ctx);
2397
+ if (typeDef.constraints && typeDef.constraints.length > 0) {
2398
+ applyConstraints(ctx.defs[name], typeDef.constraints, ctx);
2399
+ }
2400
+ if (typeDef.annotations && typeDef.annotations.length > 0) {
2401
+ applyAnnotations(ctx.defs[name], typeDef.annotations, ctx);
2402
+ }
2403
+ }
2404
+ const properties = {};
2405
+ const required = [];
2406
+ collectFields(ir.elements, properties, required, ctx);
2407
+ const uniqueRequired = [...new Set(required)];
2408
+ const result = {
2409
+ $schema: "https://json-schema.org/draft/2020-12/schema",
2410
+ type: "object",
2411
+ properties,
2412
+ ...uniqueRequired.length > 0 && { required: uniqueRequired }
2413
+ };
2414
+ if (ir.annotations && ir.annotations.length > 0) {
2415
+ applyAnnotations(result, ir.annotations, ctx);
2416
+ }
2417
+ if (Object.keys(ctx.defs).length > 0) {
2418
+ result.$defs = ctx.defs;
2419
+ }
2420
+ return result;
2421
+ }
2422
+ function collectFields(elements, properties, required, ctx) {
2423
+ for (const element of elements) {
2424
+ switch (element.kind) {
2425
+ case "field":
2426
+ properties[element.name] = generateFieldSchema(element, ctx);
2427
+ if (element.required) {
2428
+ required.push(element.name);
2429
+ }
2430
+ break;
2431
+ case "group":
2432
+ collectFields(element.elements, properties, required, ctx);
2433
+ break;
2434
+ case "conditional":
2435
+ collectFields(element.elements, properties, required, ctx);
2436
+ break;
2437
+ default: {
2438
+ const _exhaustive = element;
2439
+ void _exhaustive;
2440
+ }
2441
+ }
2442
+ }
2443
+ }
2444
+ function generateFieldSchema(field, ctx) {
2445
+ const schema = generateTypeNode(field.type, ctx);
2446
+ const itemStringSchema = schema.type === "array" && schema.items?.type === "string" ? schema.items : void 0;
2447
+ const directConstraints = [];
2448
+ const itemConstraints = [];
2449
+ const pathConstraints = [];
2450
+ for (const c of field.constraints) {
2451
+ if (c.path) {
2452
+ pathConstraints.push(c);
2453
+ } else if (itemStringSchema !== void 0 && isStringItemConstraint(c)) {
2454
+ itemConstraints.push(c);
2455
+ } else {
2456
+ directConstraints.push(c);
2457
+ }
2458
+ }
2459
+ applyConstraints(schema, directConstraints, ctx);
2460
+ if (itemStringSchema !== void 0) {
2461
+ applyConstraints(itemStringSchema, itemConstraints, ctx);
2462
+ }
2463
+ const rootAnnotations = [];
2464
+ const itemAnnotations = [];
2465
+ for (const annotation of field.annotations) {
2466
+ if (itemStringSchema !== void 0 && annotation.annotationKind === "format") {
2467
+ itemAnnotations.push(annotation);
2468
+ } else {
2469
+ rootAnnotations.push(annotation);
2470
+ }
2471
+ }
2472
+ applyAnnotations(schema, rootAnnotations, ctx);
2473
+ if (itemStringSchema !== void 0) {
2474
+ applyAnnotations(itemStringSchema, itemAnnotations, ctx);
2475
+ }
2476
+ if (pathConstraints.length === 0) {
2477
+ return schema;
2478
+ }
2479
+ return applyPathTargetedConstraints(schema, pathConstraints, ctx);
2480
+ }
2481
+ function isStringItemConstraint(constraint) {
2482
+ switch (constraint.constraintKind) {
2483
+ case "minLength":
2484
+ case "maxLength":
2485
+ case "pattern":
2486
+ return true;
2487
+ default:
2488
+ return false;
2489
+ }
2490
+ }
2491
+ function applyPathTargetedConstraints(schema, pathConstraints, ctx) {
2492
+ if (schema.type === "array" && schema.items) {
2493
+ schema.items = applyPathTargetedConstraints(schema.items, pathConstraints, ctx);
2494
+ return schema;
2495
+ }
2496
+ const byTarget = /* @__PURE__ */ new Map();
2497
+ for (const c of pathConstraints) {
2498
+ const target = c.path?.segments[0];
2499
+ if (!target) continue;
2500
+ const group = byTarget.get(target) ?? [];
2501
+ group.push(c);
2502
+ byTarget.set(target, group);
2503
+ }
2504
+ const propertyOverrides = {};
2505
+ for (const [target, constraints] of byTarget) {
2506
+ const subSchema = {};
2507
+ applyConstraints(subSchema, constraints, ctx);
2508
+ propertyOverrides[target] = subSchema;
2509
+ }
2510
+ if (schema.$ref) {
2511
+ const { $ref, ...rest } = schema;
2512
+ const refPart = { $ref };
2513
+ const overridePart = {
2514
+ properties: propertyOverrides,
2515
+ ...rest
2516
+ };
2517
+ return { allOf: [refPart, overridePart] };
2518
+ }
2519
+ if (schema.type === "object" && schema.properties) {
2520
+ const missingOverrides = {};
2521
+ for (const [target, overrideSchema] of Object.entries(propertyOverrides)) {
2522
+ if (schema.properties[target]) {
2523
+ Object.assign(schema.properties[target], overrideSchema);
2524
+ } else {
2525
+ missingOverrides[target] = overrideSchema;
2526
+ }
2527
+ }
2528
+ if (Object.keys(missingOverrides).length === 0) {
2529
+ return schema;
2530
+ }
2531
+ return {
2532
+ allOf: [schema, { properties: missingOverrides }]
2533
+ };
2534
+ }
2535
+ if (schema.allOf) {
2536
+ schema.allOf = [...schema.allOf, { properties: propertyOverrides }];
2537
+ return schema;
2538
+ }
2539
+ return schema;
2540
+ }
2541
+ function generateTypeNode(type, ctx) {
2542
+ switch (type.kind) {
2543
+ case "primitive":
2544
+ return generatePrimitiveType(type);
2545
+ case "enum":
2546
+ return generateEnumType(type);
2547
+ case "array":
2548
+ return generateArrayType(type, ctx);
2549
+ case "object":
2550
+ return generateObjectType(type, ctx);
2551
+ case "record":
2552
+ return generateRecordType(type, ctx);
2553
+ case "union":
2554
+ return generateUnionType(type, ctx);
2555
+ case "reference":
2556
+ return generateReferenceType(type);
2557
+ case "dynamic":
2558
+ return generateDynamicType(type);
2559
+ case "custom":
2560
+ return generateCustomType(type, ctx);
2561
+ default: {
2562
+ const _exhaustive = type;
2563
+ return _exhaustive;
2564
+ }
2565
+ }
2566
+ }
2567
+ function generatePrimitiveType(type) {
2568
+ return {
2569
+ type: type.primitiveKind === "integer" || type.primitiveKind === "bigint" ? "integer" : type.primitiveKind
2570
+ };
2571
+ }
2572
+ function generateEnumType(type) {
2573
+ const hasDisplayNames = type.members.some((m) => m.displayName !== void 0);
2574
+ if (hasDisplayNames) {
2575
+ return {
2576
+ oneOf: type.members.map((m) => {
2577
+ const entry = { const: m.value };
2578
+ if (m.displayName !== void 0) {
2579
+ entry.title = m.displayName;
2580
+ }
2581
+ return entry;
2582
+ })
2583
+ };
2584
+ }
2585
+ return { enum: type.members.map((m) => m.value) };
2586
+ }
2587
+ function generateArrayType(type, ctx) {
2588
+ return {
2589
+ type: "array",
2590
+ items: generateTypeNode(type.items, ctx)
2591
+ };
2592
+ }
2593
+ function generateObjectType(type, ctx) {
2594
+ const properties = {};
2595
+ const required = [];
2596
+ for (const prop of type.properties) {
2597
+ properties[prop.name] = generatePropertySchema(prop, ctx);
2598
+ if (!prop.optional) {
2599
+ required.push(prop.name);
2600
+ }
2601
+ }
2602
+ const schema = { type: "object", properties };
2603
+ if (required.length > 0) {
2604
+ schema.required = required;
2605
+ }
2606
+ if (!type.additionalProperties) {
2607
+ schema.additionalProperties = false;
2608
+ }
2609
+ return schema;
2610
+ }
2611
+ function generateRecordType(type, ctx) {
2612
+ return {
2613
+ type: "object",
2614
+ additionalProperties: generateTypeNode(type.valueType, ctx)
2615
+ };
2616
+ }
2617
+ function generatePropertySchema(prop, ctx) {
2618
+ const schema = generateTypeNode(prop.type, ctx);
2619
+ applyConstraints(schema, prop.constraints, ctx);
2620
+ applyAnnotations(schema, prop.annotations, ctx);
2621
+ return schema;
2622
+ }
2623
+ function generateUnionType(type, ctx) {
2624
+ if (isBooleanUnion(type)) {
2625
+ return { type: "boolean" };
2626
+ }
2627
+ if (isNullableUnion(type)) {
2628
+ return {
2629
+ oneOf: type.members.map((m) => generateTypeNode(m, ctx))
2630
+ };
2631
+ }
2632
+ return {
2633
+ anyOf: type.members.map((m) => generateTypeNode(m, ctx))
2634
+ };
2635
+ }
2636
+ function isBooleanUnion(type) {
2637
+ if (type.members.length !== 2) return false;
2638
+ const kinds = type.members.map((m) => m.kind);
2639
+ return kinds.every((k) => k === "primitive") && type.members.every((m) => m.kind === "primitive" && m.primitiveKind === "boolean");
2640
+ }
2641
+ function isNullableUnion(type) {
2642
+ if (type.members.length !== 2) return false;
2643
+ const nullCount = type.members.filter(
2644
+ (m) => m.kind === "primitive" && m.primitiveKind === "null"
2645
+ ).length;
2646
+ return nullCount === 1;
2647
+ }
2648
+ function generateReferenceType(type) {
2649
+ return { $ref: `#/$defs/${type.name}` };
2650
+ }
2651
+ function generateDynamicType(type) {
2652
+ if (type.dynamicKind === "enum") {
2653
+ const schema = {
2654
+ type: "string",
2655
+ "x-formspec-source": type.sourceKey
2656
+ };
2657
+ if (type.parameterFields.length > 0) {
2658
+ schema["x-formspec-params"] = [...type.parameterFields];
2659
+ }
2660
+ return schema;
2661
+ }
2662
+ return {
2663
+ type: "object",
2664
+ additionalProperties: true,
2665
+ "x-formspec-schemaSource": type.sourceKey
2666
+ };
2667
+ }
2668
+ function applyConstraints(schema, constraints, ctx) {
2669
+ for (const constraint of constraints) {
2670
+ switch (constraint.constraintKind) {
2671
+ case "minimum":
2672
+ schema.minimum = constraint.value;
2673
+ break;
2674
+ case "maximum":
2675
+ schema.maximum = constraint.value;
2676
+ break;
2677
+ case "exclusiveMinimum":
2678
+ schema.exclusiveMinimum = constraint.value;
2679
+ break;
2680
+ case "exclusiveMaximum":
2681
+ schema.exclusiveMaximum = constraint.value;
2682
+ break;
2683
+ case "multipleOf": {
2684
+ const { value } = constraint;
2685
+ if (value === 1 && schema.type === "number") {
2686
+ schema.type = "integer";
2687
+ } else {
2688
+ schema.multipleOf = value;
2689
+ }
2690
+ break;
2691
+ }
2692
+ case "minLength":
2693
+ schema.minLength = constraint.value;
2694
+ break;
2695
+ case "maxLength":
2696
+ schema.maxLength = constraint.value;
2697
+ break;
2698
+ case "minItems":
2699
+ schema.minItems = constraint.value;
2700
+ break;
2701
+ case "maxItems":
2702
+ schema.maxItems = constraint.value;
2703
+ break;
2704
+ case "pattern":
2705
+ schema.pattern = constraint.pattern;
2706
+ break;
2707
+ case "uniqueItems":
2708
+ schema.uniqueItems = constraint.value;
2709
+ break;
2710
+ case "const":
2711
+ schema.const = constraint.value;
2712
+ break;
2713
+ case "allowedMembers":
2714
+ break;
2715
+ case "custom":
2716
+ applyCustomConstraint(schema, constraint, ctx);
2717
+ break;
2718
+ default: {
2719
+ const _exhaustive = constraint;
2720
+ void _exhaustive;
2721
+ }
2722
+ }
2723
+ }
2724
+ }
2725
+ function applyAnnotations(schema, annotations, ctx) {
2726
+ for (const annotation of annotations) {
2727
+ switch (annotation.annotationKind) {
2728
+ case "displayName":
2729
+ schema.title = annotation.value;
2730
+ break;
2731
+ case "description":
2732
+ schema.description = annotation.value;
2733
+ break;
2734
+ case "defaultValue":
2735
+ schema.default = annotation.value;
2736
+ break;
2737
+ case "format":
2738
+ schema.format = annotation.value;
2739
+ break;
2740
+ case "deprecated":
2741
+ schema.deprecated = true;
2742
+ if (annotation.message !== void 0 && annotation.message !== "") {
2743
+ schema[`${ctx.vendorPrefix}-deprecation-description`] = annotation.message;
2744
+ }
2745
+ break;
2746
+ case "placeholder":
2747
+ break;
2748
+ case "formatHint":
2749
+ break;
2750
+ case "custom":
2751
+ applyCustomAnnotation(schema, annotation, ctx);
2752
+ break;
2753
+ default: {
2754
+ const _exhaustive = annotation;
2755
+ void _exhaustive;
2756
+ }
2757
+ }
2758
+ }
2759
+ }
2760
+ function generateCustomType(type, ctx) {
2761
+ const registration = ctx.extensionRegistry?.findType(type.typeId);
2762
+ if (registration === void 0) {
2763
+ throw new Error(
2764
+ `Cannot generate JSON Schema for custom type "${type.typeId}" without a matching extension registration`
2765
+ );
2766
+ }
2767
+ return registration.toJsonSchema(type.payload, ctx.vendorPrefix);
2768
+ }
2769
+ function applyCustomConstraint(schema, constraint, ctx) {
2770
+ const registration = ctx.extensionRegistry?.findConstraint(constraint.constraintId);
2771
+ if (registration === void 0) {
2772
+ throw new Error(
2773
+ `Cannot generate JSON Schema for custom constraint "${constraint.constraintId}" without a matching extension registration`
2774
+ );
2775
+ }
2776
+ assignVendorPrefixedExtensionKeywords(
2777
+ schema,
2778
+ registration.toJsonSchema(constraint.payload, ctx.vendorPrefix),
2779
+ ctx.vendorPrefix,
2780
+ `custom constraint "${constraint.constraintId}"`
2781
+ );
2782
+ }
2783
+ function applyCustomAnnotation(schema, annotation, ctx) {
2784
+ const registration = ctx.extensionRegistry?.findAnnotation(annotation.annotationId);
2785
+ if (registration === void 0) {
2786
+ throw new Error(
2787
+ `Cannot generate JSON Schema for custom annotation "${annotation.annotationId}" without a matching extension registration`
2788
+ );
2789
+ }
2790
+ if (registration.toJsonSchema === void 0) {
2791
+ return;
2792
+ }
2793
+ assignVendorPrefixedExtensionKeywords(
2794
+ schema,
2795
+ registration.toJsonSchema(annotation.value, ctx.vendorPrefix),
2796
+ ctx.vendorPrefix,
2797
+ `custom annotation "${annotation.annotationId}"`
2798
+ );
2799
+ }
2800
+ function assignVendorPrefixedExtensionKeywords(schema, extensionSchema, vendorPrefix, source) {
2801
+ for (const [key, value] of Object.entries(extensionSchema)) {
2802
+ if (!key.startsWith(`${vendorPrefix}-`)) {
2803
+ throw new Error(
2804
+ `Cannot apply ${source}: extension hooks may only emit "${vendorPrefix}-*" JSON Schema keywords`
2805
+ );
2806
+ }
2807
+ schema[key] = value;
2808
+ }
2809
+ }
2810
+
2811
+ // src/ui-schema/schema.ts
2812
+ import { z } from "zod";
2813
+ var jsonPointerSchema = z.string();
2814
+ var ruleEffectSchema = z.enum(["SHOW", "HIDE", "ENABLE", "DISABLE"]);
2815
+ var uiSchemaElementTypeSchema = z.enum([
2816
+ "Control",
2817
+ "VerticalLayout",
2818
+ "HorizontalLayout",
2819
+ "Group",
2820
+ "Categorization",
2821
+ "Category",
2822
+ "Label"
2823
+ ]);
2824
+ var ruleConditionSchema = z.lazy(
2825
+ () => z.object({
2826
+ const: z.unknown().optional(),
2827
+ enum: z.array(z.unknown()).readonly().optional(),
2828
+ type: z.string().optional(),
2829
+ not: ruleConditionSchema.optional(),
2830
+ minimum: z.number().optional(),
2831
+ maximum: z.number().optional(),
2832
+ exclusiveMinimum: z.number().optional(),
2833
+ exclusiveMaximum: z.number().optional(),
2834
+ minLength: z.number().optional(),
2835
+ properties: z.record(z.string(), ruleConditionSchema).optional(),
2836
+ required: z.array(z.string()).optional(),
2837
+ allOf: z.array(ruleConditionSchema).optional()
2838
+ }).strict()
2839
+ );
2840
+ var schemaBasedConditionSchema = z.object({
2841
+ scope: jsonPointerSchema,
2842
+ schema: ruleConditionSchema
2843
+ }).strict();
2844
+ var ruleSchema = z.object({
2845
+ effect: ruleEffectSchema,
2846
+ condition: schemaBasedConditionSchema
2847
+ }).strict();
2848
+ var uiSchemaElementSchema = z.lazy(
2849
+ () => z.union([
2850
+ controlSchema,
2851
+ verticalLayoutSchema,
2852
+ horizontalLayoutSchema,
2853
+ groupLayoutSchema,
2854
+ categorizationSchema,
2855
+ categorySchema,
2856
+ labelElementSchema
2857
+ ])
2858
+ );
2859
+ var controlSchema = z.object({
2860
+ type: z.literal("Control"),
2861
+ scope: jsonPointerSchema,
2862
+ label: z.union([z.string(), z.literal(false)]).optional(),
2863
+ rule: ruleSchema.optional(),
2864
+ options: z.record(z.string(), z.unknown()).optional()
2865
+ }).passthrough();
2866
+ var verticalLayoutSchema = z.lazy(
2867
+ () => z.object({
2868
+ type: z.literal("VerticalLayout"),
2869
+ elements: z.array(uiSchemaElementSchema),
2870
+ rule: ruleSchema.optional(),
2871
+ options: z.record(z.string(), z.unknown()).optional()
2872
+ }).passthrough()
2873
+ );
2874
+ var horizontalLayoutSchema = z.lazy(
2875
+ () => z.object({
2876
+ type: z.literal("HorizontalLayout"),
2877
+ elements: z.array(uiSchemaElementSchema),
2878
+ rule: ruleSchema.optional(),
2879
+ options: z.record(z.string(), z.unknown()).optional()
2880
+ }).passthrough()
2881
+ );
2882
+ var groupLayoutSchema = z.lazy(
2883
+ () => z.object({
2884
+ type: z.literal("Group"),
2885
+ label: z.string(),
2886
+ elements: z.array(uiSchemaElementSchema),
2887
+ rule: ruleSchema.optional(),
2888
+ options: z.record(z.string(), z.unknown()).optional()
2889
+ }).passthrough()
2890
+ );
2891
+ var categorySchema = z.lazy(
2892
+ () => z.object({
2893
+ type: z.literal("Category"),
2894
+ label: z.string(),
2895
+ elements: z.array(uiSchemaElementSchema),
2896
+ rule: ruleSchema.optional(),
2897
+ options: z.record(z.string(), z.unknown()).optional()
2898
+ }).passthrough()
2899
+ );
2900
+ var categorizationSchema = z.lazy(
2901
+ () => z.object({
2902
+ type: z.literal("Categorization"),
2903
+ elements: z.array(categorySchema),
2904
+ label: z.string().optional(),
2905
+ rule: ruleSchema.optional(),
2906
+ options: z.record(z.string(), z.unknown()).optional()
2907
+ }).passthrough()
2908
+ );
2909
+ var labelElementSchema = z.object({
2910
+ type: z.literal("Label"),
2911
+ text: z.string(),
2912
+ rule: ruleSchema.optional(),
2913
+ options: z.record(z.string(), z.unknown()).optional()
2914
+ }).passthrough();
2915
+ var uiSchema = z.lazy(
2916
+ () => z.union([verticalLayoutSchema, horizontalLayoutSchema, groupLayoutSchema, categorizationSchema])
2917
+ );
2918
+
2919
+ // src/ui-schema/ir-generator.ts
2920
+ import { z as z2 } from "zod";
2921
+ function parseOrThrow(schema, value, label) {
2922
+ try {
2923
+ return schema.parse(value);
2924
+ } catch (error) {
2925
+ if (error instanceof z2.ZodError) {
2926
+ throw new Error(
2927
+ `Generated ${label} failed validation:
2928
+ ${error.issues.map((i) => ` ${i.path.join(".")}: ${i.message}`).join("\n")}`
2929
+ );
2930
+ }
2931
+ throw error;
2932
+ }
2933
+ }
2934
+ function fieldToScope(fieldName) {
2935
+ return `#/properties/${fieldName}`;
2936
+ }
2937
+ function createShowRule(fieldName, value) {
2938
+ return {
2939
+ effect: "SHOW",
2940
+ condition: {
2941
+ scope: fieldToScope(fieldName),
2942
+ schema: { const: value }
2943
+ }
2944
+ };
2945
+ }
2946
+ function flattenConditionSchema(scope, schema) {
2947
+ if (schema.allOf === void 0) {
2948
+ if (scope === "#") {
2949
+ return [schema];
2950
+ }
2951
+ const fieldName = scope.replace("#/properties/", "");
2952
+ return [
2953
+ {
2954
+ properties: {
2955
+ [fieldName]: schema
2956
+ }
2957
+ }
2958
+ ];
2959
+ }
2960
+ return schema.allOf.flatMap((member) => flattenConditionSchema(scope, member));
2961
+ }
2962
+ function combineRules(parentRule, childRule) {
2963
+ return {
2964
+ effect: "SHOW",
2965
+ condition: {
2966
+ scope: "#",
2967
+ schema: {
2968
+ allOf: [
2969
+ ...flattenConditionSchema(parentRule.condition.scope, parentRule.condition.schema),
2970
+ ...flattenConditionSchema(childRule.condition.scope, childRule.condition.schema)
2971
+ ]
2972
+ }
2973
+ }
2974
+ };
2975
+ }
2976
+ function fieldNodeToControl(field, parentRule) {
2977
+ const displayNameAnnotation = field.annotations.find((a) => a.annotationKind === "displayName");
2978
+ const placeholderAnnotation = field.annotations.find((a) => a.annotationKind === "placeholder");
2979
+ const control = {
2980
+ type: "Control",
2981
+ scope: fieldToScope(field.name),
2982
+ ...displayNameAnnotation !== void 0 && { label: displayNameAnnotation.value },
2983
+ ...placeholderAnnotation !== void 0 && {
2984
+ options: { placeholder: placeholderAnnotation.value }
2985
+ },
2986
+ ...parentRule !== void 0 && { rule: parentRule }
2987
+ };
2988
+ return control;
2989
+ }
2990
+ function groupNodeToLayout(group, parentRule) {
2991
+ return {
2992
+ type: "Group",
2993
+ label: group.label,
2994
+ elements: irElementsToUiSchema(group.elements, parentRule),
2995
+ ...parentRule !== void 0 && { rule: parentRule }
2996
+ };
2997
+ }
2998
+ function irElementsToUiSchema(elements, parentRule) {
2999
+ const result = [];
3000
+ for (const element of elements) {
3001
+ switch (element.kind) {
3002
+ case "field": {
3003
+ result.push(fieldNodeToControl(element, parentRule));
3004
+ break;
3005
+ }
3006
+ case "group": {
3007
+ result.push(groupNodeToLayout(element, parentRule));
3008
+ break;
3009
+ }
3010
+ case "conditional": {
3011
+ const newRule = createShowRule(element.fieldName, element.value);
3012
+ const combinedRule = parentRule !== void 0 ? combineRules(parentRule, newRule) : newRule;
3013
+ const childElements = irElementsToUiSchema(element.elements, combinedRule);
3014
+ result.push(...childElements);
3015
+ break;
3016
+ }
3017
+ default: {
3018
+ const _exhaustive = element;
3019
+ void _exhaustive;
3020
+ throw new Error("Unhandled IR element kind");
3021
+ }
3022
+ }
3023
+ }
3024
+ return result;
3025
+ }
3026
+ function generateUiSchemaFromIR(ir) {
3027
+ const result = {
3028
+ type: "VerticalLayout",
3029
+ elements: irElementsToUiSchema(ir.elements)
3030
+ };
3031
+ return parseOrThrow(uiSchema, result, "UI Schema");
3032
+ }
3033
+
3034
+ // src/validate/constraint-validator.ts
3035
+ import {
3036
+ analyzeConstraintTargets
3037
+ } from "@formspec/analysis";
3038
+ function validateFieldNode(ctx, field) {
3039
+ const analysis = analyzeConstraintTargets(
3040
+ field.name,
3041
+ field.type,
3042
+ field.constraints,
3043
+ ctx.typeRegistry,
3044
+ ctx.extensionRegistry === void 0 ? void 0 : {
3045
+ extensionRegistry: ctx.extensionRegistry
3046
+ }
3047
+ );
3048
+ ctx.diagnostics.push(...analysis.diagnostics);
3049
+ if (field.type.kind === "object") {
3050
+ for (const property of field.type.properties) {
3051
+ validateObjectProperty(ctx, field.name, property);
3052
+ }
3053
+ }
3054
+ }
3055
+ function validateObjectProperty(ctx, parentName, property) {
3056
+ const qualifiedName = `${parentName}.${property.name}`;
3057
+ const analysis = analyzeConstraintTargets(
3058
+ qualifiedName,
3059
+ property.type,
3060
+ property.constraints,
3061
+ ctx.typeRegistry,
3062
+ ctx.extensionRegistry === void 0 ? void 0 : {
3063
+ extensionRegistry: ctx.extensionRegistry
3064
+ }
3065
+ );
3066
+ ctx.diagnostics.push(...analysis.diagnostics);
3067
+ if (property.type.kind === "object") {
3068
+ for (const nestedProperty of property.type.properties) {
3069
+ validateObjectProperty(ctx, qualifiedName, nestedProperty);
3070
+ }
3071
+ }
3072
+ }
3073
+ function validateElement(ctx, element) {
3074
+ switch (element.kind) {
3075
+ case "field":
3076
+ validateFieldNode(ctx, element);
3077
+ break;
3078
+ case "group":
3079
+ for (const child of element.elements) {
3080
+ validateElement(ctx, child);
3081
+ }
3082
+ break;
3083
+ case "conditional":
3084
+ for (const child of element.elements) {
3085
+ validateElement(ctx, child);
3086
+ }
3087
+ break;
3088
+ default: {
3089
+ const exhaustive = element;
3090
+ throw new Error(`Unhandled element kind: ${String(exhaustive)}`);
3091
+ }
3092
+ }
3093
+ }
3094
+ function validateIR(ir, options) {
3095
+ const ctx = {
3096
+ diagnostics: [],
3097
+ extensionRegistry: options?.extensionRegistry,
3098
+ typeRegistry: ir.typeRegistry
3099
+ };
3100
+ for (const element of ir.elements) {
3101
+ validateElement(ctx, element);
3102
+ }
3103
+ return {
3104
+ diagnostics: ctx.diagnostics,
3105
+ valid: ctx.diagnostics.every((diagnostic) => diagnostic.severity !== "error")
3106
+ };
3107
+ }
3108
+
3109
+ // src/generators/class-schema.ts
3110
+ function generateClassSchemas(analysis, source, options) {
3111
+ const errorDiagnostics = analysis.diagnostics?.filter(
3112
+ (diagnostic) => diagnostic.severity === "error"
3113
+ );
3114
+ if (errorDiagnostics !== void 0 && errorDiagnostics.length > 0) {
3115
+ throw new Error(formatValidationError(errorDiagnostics));
3116
+ }
3117
+ const ir = canonicalizeTSDoc(analysis, source);
3118
+ const validationResult = validateIR(ir, {
3119
+ ...options?.extensionRegistry !== void 0 && {
3120
+ extensionRegistry: options.extensionRegistry
3121
+ },
3122
+ ...options?.vendorPrefix !== void 0 && { vendorPrefix: options.vendorPrefix }
3123
+ });
3124
+ if (!validationResult.valid) {
3125
+ throw new Error(formatValidationError(validationResult.diagnostics));
3126
+ }
3127
+ return {
3128
+ jsonSchema: generateJsonSchemaFromIR(ir, options),
3129
+ uiSchema: generateUiSchemaFromIR(ir)
3130
+ };
3131
+ }
3132
+ function formatValidationError(diagnostics) {
3133
+ const lines = diagnostics.map((diagnostic) => {
3134
+ const primary = formatLocation(diagnostic.primaryLocation);
3135
+ const related = diagnostic.relatedLocations.length > 0 ? ` [related: ${diagnostic.relatedLocations.map(formatLocation).join(", ")}]` : "";
3136
+ return `${diagnostic.code}: ${diagnostic.message} (${primary})${related}`;
3137
+ });
3138
+ return `FormSpec validation failed:
3139
+ ${lines.map((line) => `- ${line}`).join("\n")}`;
3140
+ }
3141
+ function formatLocation(location) {
3142
+ return `${location.file}:${String(location.line)}:${String(location.column)}`;
3143
+ }
3144
+
3145
+ // src/extensions/registry.ts
3146
+ function createExtensionRegistry(extensions) {
3147
+ const typeMap = /* @__PURE__ */ new Map();
3148
+ const typeNameMap = /* @__PURE__ */ new Map();
3149
+ const constraintMap = /* @__PURE__ */ new Map();
3150
+ const constraintTagMap = /* @__PURE__ */ new Map();
3151
+ const builtinBroadeningMap = /* @__PURE__ */ new Map();
3152
+ const annotationMap = /* @__PURE__ */ new Map();
3153
+ for (const ext of extensions) {
3154
+ if (ext.types !== void 0) {
3155
+ for (const type of ext.types) {
3156
+ const qualifiedId = `${ext.extensionId}/${type.typeName}`;
3157
+ if (typeMap.has(qualifiedId)) {
3158
+ throw new Error(`Duplicate custom type ID: "${qualifiedId}"`);
3159
+ }
3160
+ typeMap.set(qualifiedId, type);
3161
+ for (const sourceTypeName of type.tsTypeNames ?? [type.typeName]) {
3162
+ if (typeNameMap.has(sourceTypeName)) {
3163
+ throw new Error(`Duplicate custom type source name: "${sourceTypeName}"`);
3164
+ }
3165
+ typeNameMap.set(sourceTypeName, {
3166
+ extensionId: ext.extensionId,
3167
+ registration: type
3168
+ });
3169
+ }
3170
+ if (type.builtinConstraintBroadenings !== void 0) {
3171
+ for (const broadening of type.builtinConstraintBroadenings) {
3172
+ const key = `${qualifiedId}:${broadening.tagName}`;
3173
+ if (builtinBroadeningMap.has(key)) {
3174
+ throw new Error(`Duplicate built-in constraint broadening: "${key}"`);
3175
+ }
3176
+ builtinBroadeningMap.set(key, {
3177
+ extensionId: ext.extensionId,
3178
+ registration: broadening
3179
+ });
3180
+ }
3181
+ }
3182
+ }
3183
+ }
3184
+ if (ext.constraints !== void 0) {
3185
+ for (const constraint of ext.constraints) {
3186
+ const qualifiedId = `${ext.extensionId}/${constraint.constraintName}`;
3187
+ if (constraintMap.has(qualifiedId)) {
3188
+ throw new Error(`Duplicate custom constraint ID: "${qualifiedId}"`);
3189
+ }
3190
+ constraintMap.set(qualifiedId, constraint);
3191
+ }
3192
+ }
3193
+ if (ext.constraintTags !== void 0) {
3194
+ for (const tag of ext.constraintTags) {
3195
+ if (constraintTagMap.has(tag.tagName)) {
3196
+ throw new Error(`Duplicate custom constraint tag: "@${tag.tagName}"`);
3197
+ }
3198
+ constraintTagMap.set(tag.tagName, {
3199
+ extensionId: ext.extensionId,
3200
+ registration: tag
3201
+ });
3202
+ }
3203
+ }
3204
+ if (ext.annotations !== void 0) {
3205
+ for (const annotation of ext.annotations) {
3206
+ const qualifiedId = `${ext.extensionId}/${annotation.annotationName}`;
3207
+ if (annotationMap.has(qualifiedId)) {
3208
+ throw new Error(`Duplicate custom annotation ID: "${qualifiedId}"`);
3209
+ }
3210
+ annotationMap.set(qualifiedId, annotation);
3211
+ }
3212
+ }
3213
+ }
3214
+ return {
3215
+ extensions,
3216
+ findType: (typeId) => typeMap.get(typeId),
3217
+ findTypeByName: (typeName) => typeNameMap.get(typeName),
3218
+ findConstraint: (constraintId) => constraintMap.get(constraintId),
3219
+ findConstraintTag: (tagName) => constraintTagMap.get(tagName),
3220
+ findBuiltinConstraintBroadening: (typeId, tagName) => builtinBroadeningMap.get(`${typeId}:${tagName}`),
3221
+ findAnnotation: (annotationId) => annotationMap.get(annotationId)
3222
+ };
3223
+ }
3224
+
3225
+ // src/generators/method-schema.ts
3226
+ import { IR_VERSION as IR_VERSION3 } from "@formspec/core";
3227
+ function typeToJsonSchema(type, checker) {
3228
+ const typeRegistry = {};
3229
+ const visiting = /* @__PURE__ */ new Set();
3230
+ const typeNode = resolveTypeNode(type, checker, "", typeRegistry, visiting);
3231
+ const fieldProvenance = { surface: "tsdoc", file: "", line: 0, column: 0 };
3232
+ const ir = {
3233
+ kind: "form-ir",
3234
+ irVersion: IR_VERSION3,
3235
+ elements: [
3236
+ {
3237
+ kind: "field",
3238
+ name: "__result",
3239
+ type: typeNode,
3240
+ required: true,
3241
+ constraints: [],
3242
+ annotations: [],
3243
+ provenance: fieldProvenance
3244
+ }
3245
+ ],
3246
+ rootAnnotations: [],
3247
+ typeRegistry,
3248
+ provenance: fieldProvenance
3249
+ };
3250
+ const schema = generateJsonSchemaFromIR(ir);
3251
+ const fieldSchema = schema.properties?.["__result"];
3252
+ if (fieldSchema) {
3253
+ if (schema.$defs && Object.keys(schema.$defs).length > 0) {
3254
+ return { ...fieldSchema, $defs: schema.$defs };
3255
+ }
3256
+ return fieldSchema;
3257
+ }
3258
+ return { type: "object" };
3259
+ }
3260
+ function generateMethodSchemas(method, checker, loadedFormSpecs) {
3261
+ const returnType = typeToJsonSchema(method.returnType, checker);
3262
+ const params = generateParamsSchemas(method.parameters, checker, loadedFormSpecs);
3263
+ return {
3264
+ name: method.name,
3265
+ params,
3266
+ returnType
3267
+ };
3268
+ }
3269
+ function generateParamsSchemas(parameters, checker, loadedFormSpecs) {
3270
+ if (parameters.length === 0) {
3271
+ return null;
3272
+ }
3273
+ for (const param of parameters) {
3274
+ if (param.formSpecExportName) {
3275
+ const formSpec = loadedFormSpecs.get(param.formSpecExportName);
3276
+ if (formSpec) {
3277
+ return {
3278
+ jsonSchema: formSpec.jsonSchema,
3279
+ uiSchema: formSpec.uiSchema,
3280
+ formSpecExport: param.formSpecExportName
3281
+ };
3282
+ }
3283
+ console.warn(
3284
+ `Warning: FormSpec export "${param.formSpecExportName}" not found, using static analysis`
3285
+ );
3286
+ }
3287
+ }
3288
+ if (parameters.length === 1 && parameters[0]) {
3289
+ const param = parameters[0];
3290
+ const jsonSchema = typeToJsonSchema(param.type, checker);
3291
+ return {
3292
+ jsonSchema,
3293
+ uiSchema: null,
3294
+ formSpecExport: null
3295
+ };
3296
+ }
3297
+ const properties = {};
3298
+ const required = [];
3299
+ for (const param of parameters) {
3300
+ const paramSchema = typeToJsonSchema(param.type, checker);
3301
+ properties[param.name] = paramSchema;
3302
+ if (!param.optional) {
3303
+ required.push(param.name);
3304
+ }
3305
+ }
3306
+ return {
3307
+ jsonSchema: {
3308
+ type: "object",
3309
+ properties,
3310
+ ...required.length > 0 ? { required } : {}
3311
+ },
3312
+ uiSchema: null,
3313
+ formSpecExport: null
3314
+ };
3315
+ }
3316
+ function collectFormSpecReferences(methods) {
3317
+ const references = /* @__PURE__ */ new Set();
3318
+ for (const method of methods) {
3319
+ for (const param of method.parameters) {
3320
+ if (param.formSpecExportName) {
3321
+ references.add(param.formSpecExportName);
3322
+ }
3323
+ }
3324
+ }
3325
+ return references;
3326
+ }
3327
+ export {
3328
+ analyzeClassToIR,
3329
+ analyzeInterfaceToIR,
3330
+ analyzeTypeAliasToIR,
3331
+ canonicalizeChainDSL,
3332
+ canonicalizeTSDoc,
3333
+ collectFormSpecReferences,
3334
+ createExtensionRegistry,
3335
+ createProgramContext,
3336
+ findClassByName,
3337
+ findInterfaceByName,
3338
+ findTypeAliasByName,
3339
+ generateClassSchemas,
3340
+ generateJsonSchemaFromIR,
3341
+ generateMethodSchemas,
3342
+ generateUiSchemaFromIR,
3343
+ validateIR
3344
+ };
3345
+ //# sourceMappingURL=internals.js.map