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

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