@formspec/build 0.1.0-alpha.4 → 0.1.0-alpha.41

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 (113) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +238 -93
  3. package/dist/analyzer/class-analyzer.d.ts +135 -0
  4. package/dist/analyzer/class-analyzer.d.ts.map +1 -0
  5. package/dist/analyzer/jsdoc-constraints.d.ts +53 -0
  6. package/dist/analyzer/jsdoc-constraints.d.ts.map +1 -0
  7. package/dist/analyzer/program.d.ts +94 -0
  8. package/dist/analyzer/program.d.ts.map +1 -0
  9. package/dist/analyzer/tsdoc-parser.d.ts +126 -0
  10. package/dist/analyzer/tsdoc-parser.d.ts.map +1 -0
  11. package/dist/browser.cjs +2113 -0
  12. package/dist/browser.cjs.map +1 -0
  13. package/dist/browser.d.ts +74 -0
  14. package/dist/browser.d.ts.map +1 -0
  15. package/dist/browser.js +2070 -0
  16. package/dist/browser.js.map +1 -0
  17. package/dist/build-alpha.d.ts +1501 -0
  18. package/dist/build-beta.d.ts +1501 -0
  19. package/dist/build-internal.d.ts +1501 -0
  20. package/dist/build.d.ts +1194 -43
  21. package/dist/canonicalize/chain-dsl-canonicalizer.d.ts +22 -0
  22. package/dist/canonicalize/chain-dsl-canonicalizer.d.ts.map +1 -0
  23. package/dist/canonicalize/index.d.ts +8 -0
  24. package/dist/canonicalize/index.d.ts.map +1 -0
  25. package/dist/canonicalize/tsdoc-canonicalizer.d.ts +38 -0
  26. package/dist/canonicalize/tsdoc-canonicalizer.d.ts.map +1 -0
  27. package/dist/cli.cjs +6715 -0
  28. package/dist/cli.cjs.map +1 -0
  29. package/dist/cli.js +6687 -103
  30. package/dist/cli.js.map +1 -1
  31. package/dist/extensions/index.d.ts +8 -0
  32. package/dist/extensions/index.d.ts.map +1 -0
  33. package/dist/extensions/registry.d.ts +83 -0
  34. package/dist/extensions/registry.d.ts.map +1 -0
  35. package/dist/generators/class-schema.d.ts +347 -0
  36. package/dist/generators/class-schema.d.ts.map +1 -0
  37. package/dist/generators/discovered-schema.d.ts +152 -0
  38. package/dist/generators/discovered-schema.d.ts.map +1 -0
  39. package/dist/generators/method-schema.d.ts +72 -0
  40. package/dist/generators/method-schema.d.ts.map +1 -0
  41. package/dist/generators/mixed-authoring.d.ts +52 -0
  42. package/dist/generators/mixed-authoring.d.ts.map +1 -0
  43. package/dist/index.cjs +6412 -0
  44. package/dist/index.cjs.map +1 -0
  45. package/dist/index.d.ts +50 -8
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +6387 -107
  48. package/dist/index.js.map +1 -1
  49. package/dist/internals.cjs +5573 -0
  50. package/dist/internals.cjs.map +1 -0
  51. package/dist/internals.d.ts +32 -0
  52. package/dist/internals.d.ts.map +1 -0
  53. package/dist/internals.js +5554 -0
  54. package/dist/internals.js.map +1 -0
  55. package/dist/json-schema/generator.d.ts +32 -6
  56. package/dist/json-schema/generator.d.ts.map +1 -1
  57. package/dist/json-schema/ir-generator.d.ts +149 -0
  58. package/dist/json-schema/ir-generator.d.ts.map +1 -0
  59. package/dist/json-schema/schema.d.ts +23 -0
  60. package/dist/json-schema/schema.d.ts.map +1 -0
  61. package/dist/json-schema/types.d.ts +76 -2
  62. package/dist/json-schema/types.d.ts.map +1 -1
  63. package/dist/metadata/collision-guards.d.ts +3 -0
  64. package/dist/metadata/collision-guards.d.ts.map +1 -0
  65. package/dist/metadata/index.d.ts +7 -0
  66. package/dist/metadata/index.d.ts.map +1 -0
  67. package/dist/metadata/policy.d.ts +12 -0
  68. package/dist/metadata/policy.d.ts.map +1 -0
  69. package/dist/metadata/resolve.d.ts +21 -0
  70. package/dist/metadata/resolve.d.ts.map +1 -0
  71. package/dist/static-build.d.ts +61 -0
  72. package/dist/static-build.d.ts.map +1 -0
  73. package/dist/ui-schema/generator.d.ts +18 -2
  74. package/dist/ui-schema/generator.d.ts.map +1 -1
  75. package/dist/ui-schema/ir-generator.d.ts +54 -0
  76. package/dist/ui-schema/ir-generator.d.ts.map +1 -0
  77. package/dist/ui-schema/schema.d.ts +429 -0
  78. package/dist/ui-schema/schema.d.ts.map +1 -0
  79. package/dist/ui-schema/types.d.ts +179 -35
  80. package/dist/ui-schema/types.d.ts.map +1 -1
  81. package/dist/validate/constraint-validator.d.ts +85 -0
  82. package/dist/validate/constraint-validator.d.ts.map +1 -0
  83. package/dist/validate/index.d.ts +9 -0
  84. package/dist/validate/index.d.ts.map +1 -0
  85. package/package.json +31 -11
  86. package/dist/__tests__/cli.test.d.ts +0 -2
  87. package/dist/__tests__/cli.test.d.ts.map +0 -1
  88. package/dist/__tests__/cli.test.js +0 -178
  89. package/dist/__tests__/cli.test.js.map +0 -1
  90. package/dist/__tests__/edge-cases.test.d.ts +0 -7
  91. package/dist/__tests__/edge-cases.test.d.ts.map +0 -1
  92. package/dist/__tests__/edge-cases.test.js +0 -217
  93. package/dist/__tests__/edge-cases.test.js.map +0 -1
  94. package/dist/__tests__/generator.test.d.ts +0 -2
  95. package/dist/__tests__/generator.test.d.ts.map +0 -1
  96. package/dist/__tests__/generator.test.js +0 -225
  97. package/dist/__tests__/generator.test.js.map +0 -1
  98. package/dist/__tests__/integration.test.d.ts +0 -8
  99. package/dist/__tests__/integration.test.d.ts.map +0 -1
  100. package/dist/__tests__/integration.test.js +0 -163
  101. package/dist/__tests__/integration.test.js.map +0 -1
  102. package/dist/__tests__/write-schemas.test.d.ts +0 -2
  103. package/dist/__tests__/write-schemas.test.d.ts.map +0 -1
  104. package/dist/__tests__/write-schemas.test.js +0 -196
  105. package/dist/__tests__/write-schemas.test.js.map +0 -1
  106. package/dist/json-schema/generator.js +0 -161
  107. package/dist/json-schema/generator.js.map +0 -1
  108. package/dist/json-schema/types.js +0 -7
  109. package/dist/json-schema/types.js.map +0 -1
  110. package/dist/ui-schema/generator.js +0 -150
  111. package/dist/ui-schema/generator.js.map +0 -1
  112. package/dist/ui-schema/types.js +0 -8
  113. package/dist/ui-schema/types.js.map +0 -1
@@ -0,0 +1,2070 @@
1
+ // src/canonicalize/chain-dsl-canonicalizer.ts
2
+ import { IR_VERSION, _getFormSpecMetadataPolicy } from "@formspec/core/internals";
3
+
4
+ // src/metadata/policy.ts
5
+ var NOOP_INFLECT = () => "";
6
+ function normalizePluralization(input) {
7
+ if (input?.mode === "infer-if-missing") {
8
+ return {
9
+ mode: "infer-if-missing",
10
+ infer: () => "",
11
+ inflect: input.inflect
12
+ };
13
+ }
14
+ if (input?.mode === "require-explicit") {
15
+ return {
16
+ mode: "require-explicit",
17
+ infer: () => "",
18
+ inflect: NOOP_INFLECT
19
+ };
20
+ }
21
+ return {
22
+ mode: "disabled",
23
+ infer: () => "",
24
+ inflect: NOOP_INFLECT
25
+ };
26
+ }
27
+ function normalizeScalarPolicy(input) {
28
+ if (input?.mode === "infer-if-missing") {
29
+ return {
30
+ mode: "infer-if-missing",
31
+ infer: input.infer,
32
+ pluralization: normalizePluralization(input.pluralization)
33
+ };
34
+ }
35
+ if (input?.mode === "require-explicit") {
36
+ return {
37
+ mode: "require-explicit",
38
+ infer: () => "",
39
+ pluralization: normalizePluralization(input.pluralization)
40
+ };
41
+ }
42
+ return {
43
+ mode: "disabled",
44
+ infer: () => "",
45
+ pluralization: normalizePluralization(input?.pluralization)
46
+ };
47
+ }
48
+ function normalizeDeclarationPolicy(input) {
49
+ return {
50
+ apiName: normalizeScalarPolicy(input?.apiName),
51
+ displayName: normalizeScalarPolicy(input?.displayName)
52
+ };
53
+ }
54
+ function normalizeEnumMemberDisplayNamePolicy(input) {
55
+ if (input?.mode === "infer-if-missing") {
56
+ return {
57
+ mode: "infer-if-missing",
58
+ infer: input.infer
59
+ };
60
+ }
61
+ if (input?.mode === "require-explicit") {
62
+ return {
63
+ mode: "require-explicit",
64
+ infer: () => ""
65
+ };
66
+ }
67
+ return {
68
+ mode: "disabled",
69
+ infer: () => ""
70
+ };
71
+ }
72
+ function normalizeEnumMemberPolicy(input) {
73
+ return {
74
+ displayName: normalizeEnumMemberDisplayNamePolicy(input?.displayName)
75
+ };
76
+ }
77
+ function normalizeMetadataPolicy(input) {
78
+ return {
79
+ type: normalizeDeclarationPolicy(input?.type),
80
+ field: normalizeDeclarationPolicy(input?.field),
81
+ method: normalizeDeclarationPolicy(input?.method),
82
+ enumMember: normalizeEnumMemberPolicy(input?.enumMember)
83
+ };
84
+ }
85
+ function getDeclarationMetadataPolicy(policy, declarationKind) {
86
+ return policy[declarationKind];
87
+ }
88
+ function makeMetadataContext(surface, declarationKind, logicalName, buildContext) {
89
+ return {
90
+ surface,
91
+ declarationKind,
92
+ logicalName,
93
+ ...buildContext !== void 0 && { buildContext }
94
+ };
95
+ }
96
+
97
+ // src/metadata/resolve.ts
98
+ function toExplicitScalar(value) {
99
+ return value !== void 0 && value.trim() !== "" ? { value, source: "explicit" } : void 0;
100
+ }
101
+ function toExplicitResolvedMetadata(explicit) {
102
+ if (explicit === void 0) {
103
+ return void 0;
104
+ }
105
+ const apiName = toExplicitScalar(explicit.apiName);
106
+ const displayName = toExplicitScalar(explicit.displayName);
107
+ const apiNamePlural = toExplicitScalar(explicit.apiNamePlural);
108
+ const displayNamePlural = toExplicitScalar(explicit.displayNamePlural);
109
+ const metadata = {
110
+ ...apiName !== void 0 && { apiName },
111
+ ...displayName !== void 0 && { displayName },
112
+ ...apiNamePlural !== void 0 && { apiNamePlural },
113
+ ...displayNamePlural !== void 0 && { displayNamePlural }
114
+ };
115
+ return Object.keys(metadata).length > 0 ? metadata : void 0;
116
+ }
117
+ function resolveScalar(current, policy, context, metadataLabel) {
118
+ if (current !== void 0) {
119
+ return current;
120
+ }
121
+ if (policy.mode === "require-explicit") {
122
+ throw new Error(
123
+ `Metadata policy requires explicit ${metadataLabel} for ${context.declarationKind} "${context.logicalName}" on the ${context.surface} surface.`
124
+ );
125
+ }
126
+ if (policy.mode !== "infer-if-missing") {
127
+ return void 0;
128
+ }
129
+ const inferredValue = policy.infer(context);
130
+ return inferredValue.trim() !== "" ? { value: inferredValue, source: "inferred" } : void 0;
131
+ }
132
+ function resolvePlural(current, singular, policy, context, metadataLabel) {
133
+ if (current !== void 0) {
134
+ return current;
135
+ }
136
+ if (policy.mode === "require-explicit") {
137
+ throw new Error(
138
+ `Metadata policy requires explicit ${metadataLabel} for ${context.declarationKind} "${context.logicalName}" on the ${context.surface} surface.`
139
+ );
140
+ }
141
+ if (singular === void 0 || policy.mode !== "infer-if-missing") {
142
+ return void 0;
143
+ }
144
+ const pluralValue = policy.inflect({ ...context, singular: singular.value });
145
+ return pluralValue.trim() !== "" ? { value: pluralValue, source: "inferred" } : void 0;
146
+ }
147
+ function resolveResolvedMetadata(current, policy, context) {
148
+ const apiName = resolveScalar(current?.apiName, policy.apiName, context, "apiName");
149
+ const displayName = resolveScalar(
150
+ current?.displayName,
151
+ policy.displayName,
152
+ context,
153
+ "displayName"
154
+ );
155
+ const apiNamePlural = resolvePlural(
156
+ current?.apiNamePlural,
157
+ apiName,
158
+ policy.apiName.pluralization,
159
+ context,
160
+ "apiNamePlural"
161
+ );
162
+ const displayNamePlural = resolvePlural(
163
+ current?.displayNamePlural,
164
+ displayName,
165
+ policy.displayName.pluralization,
166
+ context,
167
+ "displayNamePlural"
168
+ );
169
+ if (apiName === void 0 && displayName === void 0 && apiNamePlural === void 0 && displayNamePlural === void 0) {
170
+ return void 0;
171
+ }
172
+ return {
173
+ ...apiName !== void 0 && { apiName },
174
+ ...displayName !== void 0 && { displayName },
175
+ ...apiNamePlural !== void 0 && { apiNamePlural },
176
+ ...displayNamePlural !== void 0 && { displayNamePlural }
177
+ };
178
+ }
179
+ function resolveEnumMemberDisplayName(current, policy, context) {
180
+ if (current !== void 0) {
181
+ return current;
182
+ }
183
+ if (policy.mode === "require-explicit") {
184
+ throw new Error(
185
+ `Metadata policy requires explicit displayName for enum member "${context.logicalName}" on the ${context.surface} surface.`
186
+ );
187
+ }
188
+ if (policy.mode !== "infer-if-missing") {
189
+ return void 0;
190
+ }
191
+ const inferredValue = policy.infer(context).trim();
192
+ return inferredValue !== "" ? inferredValue : void 0;
193
+ }
194
+ function resolveEnumTypeMetadata(type, options) {
195
+ const members = type.members.map((member) => {
196
+ const displayName = resolveEnumMemberDisplayName(
197
+ member.displayName,
198
+ options.policy.enumMember.displayName,
199
+ {
200
+ surface: options.surface,
201
+ logicalName: String(member.value),
202
+ memberValue: member.value,
203
+ ...options.buildContext !== void 0 && { buildContext: options.buildContext }
204
+ }
205
+ );
206
+ if (displayName === member.displayName) {
207
+ return member;
208
+ }
209
+ return displayName === void 0 ? { value: member.value } : { value: member.value, displayName };
210
+ });
211
+ return members.some((member, index) => member !== type.members[index]) ? { ...type, members } : type;
212
+ }
213
+ function resolveTypeNodeMetadata(type, options) {
214
+ switch (type.kind) {
215
+ case "array":
216
+ return {
217
+ ...type,
218
+ items: resolveTypeNodeMetadata(type.items, options)
219
+ };
220
+ case "object":
221
+ return {
222
+ ...type,
223
+ properties: type.properties.map((property) => resolveObjectPropertyMetadata(property, options))
224
+ };
225
+ case "record":
226
+ return {
227
+ ...type,
228
+ valueType: resolveTypeNodeMetadata(type.valueType, options)
229
+ };
230
+ case "union":
231
+ return {
232
+ ...type,
233
+ members: type.members.map((member) => resolveTypeNodeMetadata(member, options))
234
+ };
235
+ case "enum":
236
+ return resolveEnumTypeMetadata(type, options);
237
+ case "reference":
238
+ case "primitive":
239
+ case "dynamic":
240
+ case "custom":
241
+ return type;
242
+ default: {
243
+ const _exhaustive = type;
244
+ return _exhaustive;
245
+ }
246
+ }
247
+ }
248
+ function resolveObjectPropertyMetadata(property, options) {
249
+ const metadata = resolveResolvedMetadata(property.metadata, options.policy.field, {
250
+ surface: options.surface,
251
+ declarationKind: "field",
252
+ logicalName: property.name,
253
+ ...options.buildContext !== void 0 && { buildContext: options.buildContext }
254
+ });
255
+ return {
256
+ ...property,
257
+ ...metadata !== void 0 && { metadata },
258
+ type: resolveTypeNodeMetadata(property.type, options)
259
+ };
260
+ }
261
+ function resolveFieldMetadataNode(field, options) {
262
+ const metadata = resolveResolvedMetadata(field.metadata, options.policy.field, {
263
+ surface: options.surface,
264
+ declarationKind: "field",
265
+ logicalName: field.name,
266
+ ...options.buildContext !== void 0 && { buildContext: options.buildContext }
267
+ });
268
+ return {
269
+ ...field,
270
+ ...metadata !== void 0 && { metadata },
271
+ type: resolveTypeNodeMetadata(field.type, options)
272
+ };
273
+ }
274
+ function resolveFormElementMetadata(element, options) {
275
+ switch (element.kind) {
276
+ case "field":
277
+ return resolveFieldMetadataNode(element, options);
278
+ case "group":
279
+ return {
280
+ ...element,
281
+ elements: element.elements.map((child) => resolveFormElementMetadata(child, options))
282
+ };
283
+ case "conditional":
284
+ return {
285
+ ...element,
286
+ elements: element.elements.map((child) => resolveFormElementMetadata(child, options))
287
+ };
288
+ default: {
289
+ const _exhaustive = element;
290
+ return _exhaustive;
291
+ }
292
+ }
293
+ }
294
+ function resolveTypeDefinitionMetadata(typeDefinition, options) {
295
+ const metadata = resolveResolvedMetadata(typeDefinition.metadata, options.policy.type, {
296
+ surface: options.surface,
297
+ declarationKind: "type",
298
+ logicalName: typeDefinition.name,
299
+ ...options.buildContext !== void 0 && { buildContext: options.buildContext }
300
+ });
301
+ return {
302
+ ...typeDefinition,
303
+ ...metadata !== void 0 && { metadata },
304
+ type: resolveTypeNodeMetadata(typeDefinition.type, options)
305
+ };
306
+ }
307
+ function resolveMetadata(explicit, policy, context) {
308
+ return resolveResolvedMetadata(toExplicitResolvedMetadata(explicit), policy, context);
309
+ }
310
+ function getSerializedName(logicalName, metadata) {
311
+ return metadata?.apiName?.value ?? logicalName;
312
+ }
313
+ function getDisplayName(metadata) {
314
+ return metadata?.displayName?.value;
315
+ }
316
+ function resolveFormIRMetadata(ir, options) {
317
+ const metadata = options.resolveRootTypeMetadata === false ? ir.metadata : resolveResolvedMetadata(ir.metadata, options.policy.type, {
318
+ surface: options.surface,
319
+ declarationKind: "type",
320
+ logicalName: options.rootLogicalName ?? ir.name ?? "FormSpec",
321
+ ...options.buildContext !== void 0 && { buildContext: options.buildContext }
322
+ });
323
+ return {
324
+ ...ir,
325
+ ...metadata !== void 0 && { metadata },
326
+ elements: ir.elements.map((element) => resolveFormElementMetadata(element, options)),
327
+ typeRegistry: Object.fromEntries(
328
+ Object.entries(ir.typeRegistry).map(([name, definition]) => [
329
+ name,
330
+ resolveTypeDefinitionMetadata(definition, options)
331
+ ])
332
+ )
333
+ };
334
+ }
335
+
336
+ // src/canonicalize/chain-dsl-canonicalizer.ts
337
+ var CHAIN_DSL_PROVENANCE = {
338
+ surface: "chain-dsl",
339
+ file: "",
340
+ line: 0,
341
+ column: 0
342
+ };
343
+ function isGroup(el) {
344
+ return el._type === "group";
345
+ }
346
+ function isConditional(el) {
347
+ return el._type === "conditional";
348
+ }
349
+ function isField(el) {
350
+ return el._type === "field";
351
+ }
352
+ function canonicalizeChainDSL(form, options) {
353
+ const metadataPolicy = normalizeMetadataPolicy(
354
+ options?.metadata ?? _getFormSpecMetadataPolicy(form)
355
+ );
356
+ const ir = {
357
+ kind: "form-ir",
358
+ irVersion: IR_VERSION,
359
+ elements: canonicalizeElements(form.elements, metadataPolicy),
360
+ rootAnnotations: [],
361
+ typeRegistry: {},
362
+ provenance: CHAIN_DSL_PROVENANCE
363
+ };
364
+ return resolveFormIRMetadata(ir, {
365
+ policy: metadataPolicy,
366
+ surface: "chain-dsl",
367
+ // Chain DSL has no root/type-metadata authoring surface, so only resolve
368
+ // field/type-registry metadata and enum-member labels here.
369
+ resolveRootTypeMetadata: false
370
+ });
371
+ }
372
+ function canonicalizeElements(elements, metadataPolicy) {
373
+ return elements.map((element) => canonicalizeElement(element, metadataPolicy));
374
+ }
375
+ function canonicalizeElement(element, metadataPolicy) {
376
+ if (isField(element)) {
377
+ return canonicalizeField(element, metadataPolicy);
378
+ }
379
+ if (isGroup(element)) {
380
+ return canonicalizeGroup(element, metadataPolicy);
381
+ }
382
+ if (isConditional(element)) {
383
+ return canonicalizeConditional(element, metadataPolicy);
384
+ }
385
+ const _exhaustive = element;
386
+ throw new Error(`Unknown element type: ${JSON.stringify(_exhaustive)}`);
387
+ }
388
+ function canonicalizeField(field, metadataPolicy) {
389
+ switch (field._field) {
390
+ case "text":
391
+ return canonicalizeTextField(field, metadataPolicy);
392
+ case "number":
393
+ return canonicalizeNumberField(field, metadataPolicy);
394
+ case "boolean":
395
+ return canonicalizeBooleanField(field, metadataPolicy);
396
+ case "enum":
397
+ return canonicalizeStaticEnumField(field, metadataPolicy);
398
+ case "dynamic_enum":
399
+ return canonicalizeDynamicEnumField(field, metadataPolicy);
400
+ case "dynamic_schema":
401
+ return canonicalizeDynamicSchemaField(field, metadataPolicy);
402
+ case "array":
403
+ return canonicalizeArrayField(field, metadataPolicy);
404
+ case "object":
405
+ return canonicalizeObjectField(field, metadataPolicy);
406
+ default: {
407
+ const _exhaustive = field;
408
+ throw new Error(`Unknown field type: ${JSON.stringify(_exhaustive)}`);
409
+ }
410
+ }
411
+ }
412
+ function canonicalizeTextField(field, metadataPolicy) {
413
+ const type = { kind: "primitive", primitiveKind: "string" };
414
+ const constraints = [];
415
+ if (field.minLength !== void 0) {
416
+ const c = {
417
+ kind: "constraint",
418
+ constraintKind: "minLength",
419
+ value: field.minLength,
420
+ provenance: CHAIN_DSL_PROVENANCE
421
+ };
422
+ constraints.push(c);
423
+ }
424
+ if (field.maxLength !== void 0) {
425
+ const c = {
426
+ kind: "constraint",
427
+ constraintKind: "maxLength",
428
+ value: field.maxLength,
429
+ provenance: CHAIN_DSL_PROVENANCE
430
+ };
431
+ constraints.push(c);
432
+ }
433
+ if (field.pattern !== void 0) {
434
+ const c = {
435
+ kind: "constraint",
436
+ constraintKind: "pattern",
437
+ pattern: field.pattern,
438
+ provenance: CHAIN_DSL_PROVENANCE
439
+ };
440
+ constraints.push(c);
441
+ }
442
+ return buildFieldNode(
443
+ field.name,
444
+ resolveFieldMetadata(field.name, field, metadataPolicy),
445
+ type,
446
+ field.required,
447
+ buildAnnotations(getExplicitDisplayName(field), field.placeholder),
448
+ constraints
449
+ );
450
+ }
451
+ function canonicalizeNumberField(field, metadataPolicy) {
452
+ const type = { kind: "primitive", primitiveKind: "number" };
453
+ const constraints = [];
454
+ if (field.min !== void 0) {
455
+ const c = {
456
+ kind: "constraint",
457
+ constraintKind: "minimum",
458
+ value: field.min,
459
+ provenance: CHAIN_DSL_PROVENANCE
460
+ };
461
+ constraints.push(c);
462
+ }
463
+ if (field.max !== void 0) {
464
+ const c = {
465
+ kind: "constraint",
466
+ constraintKind: "maximum",
467
+ value: field.max,
468
+ provenance: CHAIN_DSL_PROVENANCE
469
+ };
470
+ constraints.push(c);
471
+ }
472
+ if (field.multipleOf !== void 0) {
473
+ const c = {
474
+ kind: "constraint",
475
+ constraintKind: "multipleOf",
476
+ value: field.multipleOf,
477
+ provenance: CHAIN_DSL_PROVENANCE
478
+ };
479
+ constraints.push(c);
480
+ }
481
+ return buildFieldNode(
482
+ field.name,
483
+ resolveFieldMetadata(field.name, field, metadataPolicy),
484
+ type,
485
+ field.required,
486
+ buildAnnotations(getExplicitDisplayName(field)),
487
+ constraints
488
+ );
489
+ }
490
+ function canonicalizeBooleanField(field, metadataPolicy) {
491
+ const type = { kind: "primitive", primitiveKind: "boolean" };
492
+ return buildFieldNode(
493
+ field.name,
494
+ resolveFieldMetadata(field.name, field, metadataPolicy),
495
+ type,
496
+ field.required,
497
+ buildAnnotations(getExplicitDisplayName(field))
498
+ );
499
+ }
500
+ function canonicalizeStaticEnumField(field, metadataPolicy) {
501
+ const members = field.options.map((opt) => {
502
+ if (typeof opt === "string") {
503
+ return { value: opt };
504
+ }
505
+ return { value: opt.id, displayName: opt.label };
506
+ });
507
+ const type = { kind: "enum", members };
508
+ return buildFieldNode(
509
+ field.name,
510
+ resolveFieldMetadata(field.name, field, metadataPolicy),
511
+ type,
512
+ field.required,
513
+ buildAnnotations(getExplicitDisplayName(field))
514
+ );
515
+ }
516
+ function canonicalizeDynamicEnumField(field, metadataPolicy) {
517
+ const type = {
518
+ kind: "dynamic",
519
+ dynamicKind: "enum",
520
+ sourceKey: field.source,
521
+ parameterFields: field.params ? [...field.params] : []
522
+ };
523
+ return buildFieldNode(
524
+ field.name,
525
+ resolveFieldMetadata(field.name, field, metadataPolicy),
526
+ type,
527
+ field.required,
528
+ buildAnnotations(getExplicitDisplayName(field))
529
+ );
530
+ }
531
+ function canonicalizeDynamicSchemaField(field, metadataPolicy) {
532
+ const type = {
533
+ kind: "dynamic",
534
+ dynamicKind: "schema",
535
+ sourceKey: field.schemaSource,
536
+ parameterFields: []
537
+ };
538
+ return buildFieldNode(
539
+ field.name,
540
+ resolveFieldMetadata(field.name, field, metadataPolicy),
541
+ type,
542
+ field.required,
543
+ buildAnnotations(getExplicitDisplayName(field))
544
+ );
545
+ }
546
+ function canonicalizeArrayField(field, metadataPolicy) {
547
+ const itemProperties = buildObjectProperties(field.items, metadataPolicy);
548
+ const itemsType = {
549
+ kind: "object",
550
+ properties: itemProperties,
551
+ additionalProperties: true
552
+ };
553
+ const type = { kind: "array", items: itemsType };
554
+ const constraints = [];
555
+ if (field.minItems !== void 0) {
556
+ const c = {
557
+ kind: "constraint",
558
+ constraintKind: "minItems",
559
+ value: field.minItems,
560
+ provenance: CHAIN_DSL_PROVENANCE
561
+ };
562
+ constraints.push(c);
563
+ }
564
+ if (field.maxItems !== void 0) {
565
+ const c = {
566
+ kind: "constraint",
567
+ constraintKind: "maxItems",
568
+ value: field.maxItems,
569
+ provenance: CHAIN_DSL_PROVENANCE
570
+ };
571
+ constraints.push(c);
572
+ }
573
+ return buildFieldNode(
574
+ field.name,
575
+ resolveFieldMetadata(field.name, field, metadataPolicy),
576
+ type,
577
+ field.required,
578
+ buildAnnotations(getExplicitDisplayName(field)),
579
+ constraints
580
+ );
581
+ }
582
+ function canonicalizeObjectField(field, metadataPolicy) {
583
+ const properties = buildObjectProperties(field.properties, metadataPolicy);
584
+ const type = {
585
+ kind: "object",
586
+ properties,
587
+ additionalProperties: true
588
+ };
589
+ return buildFieldNode(
590
+ field.name,
591
+ resolveFieldMetadata(field.name, field, metadataPolicy),
592
+ type,
593
+ field.required,
594
+ buildAnnotations(getExplicitDisplayName(field))
595
+ );
596
+ }
597
+ function canonicalizeGroup(g, metadataPolicy) {
598
+ return {
599
+ kind: "group",
600
+ label: g.label,
601
+ elements: canonicalizeElements(g.elements, metadataPolicy),
602
+ provenance: CHAIN_DSL_PROVENANCE
603
+ };
604
+ }
605
+ function canonicalizeConditional(c, metadataPolicy) {
606
+ return {
607
+ kind: "conditional",
608
+ fieldName: c.field,
609
+ // Conditional values from the chain DSL are JSON-serializable primitives
610
+ // (strings, numbers, booleans) produced by the `is()` predicate helper.
611
+ value: assertJsonValue(c.value),
612
+ elements: canonicalizeElements(c.elements, metadataPolicy),
613
+ provenance: CHAIN_DSL_PROVENANCE
614
+ };
615
+ }
616
+ function assertJsonValue(v) {
617
+ if (v === null || typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
618
+ return v;
619
+ }
620
+ if (Array.isArray(v)) {
621
+ return v.map(assertJsonValue);
622
+ }
623
+ if (typeof v === "object") {
624
+ const result = {};
625
+ for (const [key, val] of Object.entries(v)) {
626
+ result[key] = assertJsonValue(val);
627
+ }
628
+ return result;
629
+ }
630
+ throw new TypeError(`Conditional value is not a valid JsonValue: ${typeof v}`);
631
+ }
632
+ function buildFieldNode(name, metadata, type, required, annotations, constraints = []) {
633
+ return {
634
+ kind: "field",
635
+ name,
636
+ ...metadata !== void 0 && { metadata },
637
+ type,
638
+ required: required === true,
639
+ constraints,
640
+ annotations,
641
+ provenance: CHAIN_DSL_PROVENANCE
642
+ };
643
+ }
644
+ function buildAnnotations(label, placeholder) {
645
+ const annotations = [];
646
+ if (label !== void 0) {
647
+ const a = {
648
+ kind: "annotation",
649
+ annotationKind: "displayName",
650
+ value: label,
651
+ provenance: CHAIN_DSL_PROVENANCE
652
+ };
653
+ annotations.push(a);
654
+ }
655
+ if (placeholder !== void 0) {
656
+ const a = {
657
+ kind: "annotation",
658
+ annotationKind: "placeholder",
659
+ value: placeholder,
660
+ provenance: CHAIN_DSL_PROVENANCE
661
+ };
662
+ annotations.push(a);
663
+ }
664
+ return annotations;
665
+ }
666
+ function buildObjectProperties(elements, metadataPolicy, insideConditional = false) {
667
+ const properties = [];
668
+ for (const el of elements) {
669
+ if (isField(el)) {
670
+ const fieldNode = canonicalizeField(el, metadataPolicy);
671
+ properties.push({
672
+ name: fieldNode.name,
673
+ ...fieldNode.metadata !== void 0 && { metadata: fieldNode.metadata },
674
+ type: fieldNode.type,
675
+ // Fields inside a conditional branch are always optional in the
676
+ // data schema, regardless of their `required` flag — the condition
677
+ // may not be met, so the field may be absent.
678
+ optional: insideConditional || !fieldNode.required,
679
+ constraints: fieldNode.constraints,
680
+ annotations: fieldNode.annotations,
681
+ provenance: CHAIN_DSL_PROVENANCE
682
+ });
683
+ } else if (isGroup(el)) {
684
+ properties.push(...buildObjectProperties(el.elements, metadataPolicy, insideConditional));
685
+ } else if (isConditional(el)) {
686
+ properties.push(...buildObjectProperties(el.elements, metadataPolicy, true));
687
+ }
688
+ }
689
+ return properties;
690
+ }
691
+ function getExplicitDisplayName(field) {
692
+ if (field.label !== void 0 && field.displayName !== void 0) {
693
+ throw new Error('Chain DSL fields cannot specify both "label" and "displayName".');
694
+ }
695
+ return field.displayName ?? field.label;
696
+ }
697
+ function resolveFieldMetadata(logicalName, field, metadataPolicy) {
698
+ const displayName = getExplicitDisplayName(field);
699
+ return resolveMetadata(
700
+ {
701
+ ...field.apiName !== void 0 && { apiName: field.apiName },
702
+ ...displayName !== void 0 && { displayName }
703
+ },
704
+ getDeclarationMetadataPolicy(metadataPolicy, "field"),
705
+ makeMetadataContext("chain-dsl", "field", logicalName)
706
+ );
707
+ }
708
+
709
+ // src/canonicalize/tsdoc-canonicalizer.ts
710
+ import { IR_VERSION as IR_VERSION2 } from "@formspec/core/internals";
711
+
712
+ // src/metadata/collision-guards.ts
713
+ function assertUniqueSerializedNames(entries, scope) {
714
+ const seen = /* @__PURE__ */ new Map();
715
+ for (const entry of entries) {
716
+ const previous = seen.get(entry.serializedName);
717
+ if (previous !== void 0) {
718
+ if (previous.logicalName === entry.logicalName && previous.category === entry.category) {
719
+ continue;
720
+ }
721
+ throw new Error(
722
+ `Serialized name collision in ${scope}: ${previous.category} "${previous.logicalName}" and ${entry.category} "${entry.logicalName}" both resolve to "${entry.serializedName}".`
723
+ );
724
+ }
725
+ seen.set(entry.serializedName, entry);
726
+ }
727
+ }
728
+ function collectFlattenedFields(elements) {
729
+ const fields = [];
730
+ for (const element of elements) {
731
+ switch (element.kind) {
732
+ case "field":
733
+ fields.push(element);
734
+ break;
735
+ case "group":
736
+ case "conditional":
737
+ fields.push(...collectFlattenedFields(element.elements));
738
+ break;
739
+ default: {
740
+ const exhaustive = element;
741
+ void exhaustive;
742
+ }
743
+ }
744
+ }
745
+ return fields;
746
+ }
747
+ function validateObjectProperties(properties, scope) {
748
+ assertUniqueSerializedNames(
749
+ properties.map((property) => ({
750
+ logicalName: property.name,
751
+ serializedName: getSerializedName(property.name, property.metadata),
752
+ category: "object property"
753
+ })),
754
+ scope
755
+ );
756
+ for (const property of properties) {
757
+ validateTypeNode(
758
+ property.type,
759
+ `${scope}.${getSerializedName(property.name, property.metadata)}`
760
+ );
761
+ }
762
+ }
763
+ function validateTypeNode(type, scope) {
764
+ switch (type.kind) {
765
+ case "array":
766
+ validateTypeNode(type.items, `${scope}[]`);
767
+ break;
768
+ case "object":
769
+ validateObjectProperties(type.properties, scope);
770
+ break;
771
+ case "record":
772
+ validateTypeNode(type.valueType, `${scope}.*`);
773
+ break;
774
+ case "union":
775
+ type.members.forEach((member, index) => {
776
+ validateTypeNode(member, `${scope}|${String(index)}`);
777
+ });
778
+ break;
779
+ case "reference":
780
+ case "primitive":
781
+ case "enum":
782
+ case "dynamic":
783
+ case "custom":
784
+ break;
785
+ default: {
786
+ const exhaustive = type;
787
+ void exhaustive;
788
+ }
789
+ }
790
+ }
791
+ function validateTypeDefinitions(typeRegistry) {
792
+ const definitions = Object.values(typeRegistry);
793
+ assertUniqueSerializedNames(
794
+ definitions.map((definition) => ({
795
+ logicalName: definition.name,
796
+ serializedName: getSerializedName(definition.name, definition.metadata),
797
+ category: "type definition"
798
+ })),
799
+ "$defs"
800
+ );
801
+ for (const definition of definitions) {
802
+ validateTypeDefinition(definition);
803
+ }
804
+ }
805
+ function validateTypeDefinition(definition) {
806
+ validateTypeNode(
807
+ definition.type,
808
+ `type "${getSerializedName(definition.name, definition.metadata)}"`
809
+ );
810
+ }
811
+ function assertNoSerializedNameCollisions(ir) {
812
+ assertUniqueSerializedNames(
813
+ collectFlattenedFields(ir.elements).map((field) => ({
814
+ logicalName: field.name,
815
+ serializedName: getSerializedName(field.name, field.metadata),
816
+ category: "field"
817
+ })),
818
+ "form root"
819
+ );
820
+ for (const field of collectFlattenedFields(ir.elements)) {
821
+ validateTypeNode(field.type, `field "${getSerializedName(field.name, field.metadata)}"`);
822
+ }
823
+ validateTypeDefinitions(ir.typeRegistry);
824
+ }
825
+
826
+ // src/json-schema/ir-generator.ts
827
+ function makeContext(options) {
828
+ const vendorPrefix = options?.vendorPrefix ?? "x-formspec";
829
+ const rawEnumSerialization = options?.enumSerialization;
830
+ if (!vendorPrefix.startsWith("x-")) {
831
+ throw new Error(
832
+ `Invalid vendorPrefix "${vendorPrefix}". Extension JSON Schema keywords must start with "x-".`
833
+ );
834
+ }
835
+ if (rawEnumSerialization !== void 0 && rawEnumSerialization !== "enum" && rawEnumSerialization !== "oneOf") {
836
+ throw new Error(
837
+ `Invalid enumSerialization "${rawEnumSerialization}". Expected "enum" or "oneOf".`
838
+ );
839
+ }
840
+ const enumSerialization = rawEnumSerialization ?? "enum";
841
+ return {
842
+ defs: {},
843
+ typeNameMap: {},
844
+ typeRegistry: {},
845
+ extensionRegistry: options?.extensionRegistry,
846
+ vendorPrefix,
847
+ enumSerialization
848
+ };
849
+ }
850
+ function generateJsonSchemaFromIR(ir, options) {
851
+ assertNoSerializedNameCollisions(ir);
852
+ const ctx = {
853
+ ...makeContext(options),
854
+ typeRegistry: ir.typeRegistry,
855
+ typeNameMap: Object.fromEntries(
856
+ Object.entries(ir.typeRegistry).map(([name, typeDef]) => [
857
+ name,
858
+ getSerializedName(name, typeDef.metadata)
859
+ ])
860
+ )
861
+ };
862
+ for (const [name, typeDef] of Object.entries(ir.typeRegistry)) {
863
+ const schemaName = ctx.typeNameMap[name] ?? name;
864
+ ctx.defs[schemaName] = generateTypeNode(typeDef.type, ctx);
865
+ applyResolvedMetadata(ctx.defs[schemaName], typeDef.metadata);
866
+ if (typeDef.constraints && typeDef.constraints.length > 0) {
867
+ applyConstraints(ctx.defs[schemaName], typeDef.constraints, ctx);
868
+ }
869
+ if (typeDef.annotations && typeDef.annotations.length > 0) {
870
+ applyAnnotations(ctx.defs[schemaName], typeDef.annotations, ctx);
871
+ }
872
+ }
873
+ const properties = {};
874
+ const required = [];
875
+ collectFields(ir.elements, properties, required, ctx);
876
+ const uniqueRequired = [...new Set(required)];
877
+ const result = {
878
+ $schema: "https://json-schema.org/draft/2020-12/schema",
879
+ type: "object",
880
+ properties,
881
+ ...uniqueRequired.length > 0 && { required: uniqueRequired }
882
+ };
883
+ applyResolvedMetadata(result, ir.metadata);
884
+ if (ir.annotations && ir.annotations.length > 0) {
885
+ applyAnnotations(result, ir.annotations, ctx);
886
+ }
887
+ if (Object.keys(ctx.defs).length > 0) {
888
+ result.$defs = ctx.defs;
889
+ }
890
+ return result;
891
+ }
892
+ function collectFields(elements, properties, required, ctx) {
893
+ for (const element of elements) {
894
+ switch (element.kind) {
895
+ case "field":
896
+ properties[getSerializedFieldName(element)] = generateFieldSchema(element, ctx);
897
+ if (element.required) {
898
+ required.push(getSerializedFieldName(element));
899
+ }
900
+ break;
901
+ case "group":
902
+ collectFields(element.elements, properties, required, ctx);
903
+ break;
904
+ case "conditional":
905
+ collectFields(element.elements, properties, required, ctx);
906
+ break;
907
+ default: {
908
+ const _exhaustive = element;
909
+ void _exhaustive;
910
+ }
911
+ }
912
+ }
913
+ }
914
+ function generateFieldSchema(field, ctx) {
915
+ const schema = generateTypeNode(field.type, ctx);
916
+ const itemStringSchema = schema.type === "array" && schema.items?.type === "string" ? schema.items : void 0;
917
+ const directConstraints = [];
918
+ const itemConstraints = [];
919
+ const pathConstraints = [];
920
+ for (const c of field.constraints) {
921
+ if (c.path) {
922
+ pathConstraints.push(c);
923
+ } else if (itemStringSchema !== void 0 && isStringItemConstraint(c)) {
924
+ itemConstraints.push(c);
925
+ } else {
926
+ directConstraints.push(c);
927
+ }
928
+ }
929
+ applyConstraints(schema, directConstraints, ctx);
930
+ if (itemStringSchema !== void 0) {
931
+ applyConstraints(itemStringSchema, itemConstraints, ctx);
932
+ }
933
+ const rootAnnotations = [];
934
+ const itemAnnotations = [];
935
+ for (const annotation of field.annotations) {
936
+ if (itemStringSchema !== void 0 && annotation.annotationKind === "format") {
937
+ itemAnnotations.push(annotation);
938
+ } else {
939
+ rootAnnotations.push(annotation);
940
+ }
941
+ }
942
+ applyResolvedMetadata(schema, field.metadata);
943
+ applyAnnotations(schema, rootAnnotations, ctx);
944
+ if (itemStringSchema !== void 0) {
945
+ applyAnnotations(itemStringSchema, itemAnnotations, ctx);
946
+ }
947
+ if (pathConstraints.length === 0) {
948
+ return schema;
949
+ }
950
+ return applyPathTargetedConstraints(schema, pathConstraints, ctx, field.type);
951
+ }
952
+ function isStringItemConstraint(constraint) {
953
+ switch (constraint.constraintKind) {
954
+ case "minLength":
955
+ case "maxLength":
956
+ case "pattern":
957
+ return true;
958
+ default:
959
+ return false;
960
+ }
961
+ }
962
+ function applyPathTargetedConstraints(schema, pathConstraints, ctx, typeNode) {
963
+ if (schema.type === "array" && schema.items) {
964
+ const referencedType = typeNode?.kind === "reference" ? resolveReferencedType(typeNode, ctx) : void 0;
965
+ const nestedType = typeNode?.kind === "array" ? typeNode.items : referencedType?.kind === "array" ? referencedType.items : void 0;
966
+ schema.items = applyPathTargetedConstraints(schema.items, pathConstraints, ctx, nestedType);
967
+ return schema;
968
+ }
969
+ const propertyOverrides = buildPropertyOverrides(pathConstraints, typeNode, ctx);
970
+ const nullableValueBranch = getNullableUnionValueSchema(schema);
971
+ if (nullableValueBranch !== void 0) {
972
+ const updatedNullableValueBranch = applyPathTargetedConstraints(
973
+ nullableValueBranch,
974
+ pathConstraints,
975
+ ctx,
976
+ resolveTraversableTypeNode(typeNode, ctx)
977
+ );
978
+ if (schema.oneOf !== void 0) {
979
+ schema.oneOf = schema.oneOf.map(
980
+ (branch) => branch === nullableValueBranch ? updatedNullableValueBranch : branch
981
+ );
982
+ }
983
+ return schema;
984
+ }
985
+ if (schema.$ref) {
986
+ const { $ref, ...rest } = schema;
987
+ const refPart = { $ref };
988
+ const overridePart = {
989
+ properties: propertyOverrides,
990
+ ...rest
991
+ };
992
+ return { allOf: [refPart, overridePart] };
993
+ }
994
+ if (schema.type === "object" && schema.properties) {
995
+ const missingOverrides = {};
996
+ for (const [target, overrideSchema] of Object.entries(propertyOverrides)) {
997
+ if (schema.properties[target]) {
998
+ mergeSchemaOverride(schema.properties[target], overrideSchema);
999
+ } else {
1000
+ missingOverrides[target] = overrideSchema;
1001
+ }
1002
+ }
1003
+ if (Object.keys(missingOverrides).length === 0) {
1004
+ return schema;
1005
+ }
1006
+ return {
1007
+ allOf: [schema, { properties: missingOverrides }]
1008
+ };
1009
+ }
1010
+ if (schema.allOf) {
1011
+ schema.allOf = [...schema.allOf, { properties: propertyOverrides }];
1012
+ return schema;
1013
+ }
1014
+ return schema;
1015
+ }
1016
+ function generateTypeNode(type, ctx) {
1017
+ switch (type.kind) {
1018
+ case "primitive":
1019
+ return generatePrimitiveType(type);
1020
+ case "enum":
1021
+ return generateEnumType(type, ctx);
1022
+ case "array":
1023
+ return generateArrayType(type, ctx);
1024
+ case "object":
1025
+ return generateObjectType(type, ctx);
1026
+ case "record":
1027
+ return generateRecordType(type, ctx);
1028
+ case "union":
1029
+ return generateUnionType(type, ctx);
1030
+ case "reference":
1031
+ return generateReferenceType(type, ctx);
1032
+ case "dynamic":
1033
+ return generateDynamicType(type);
1034
+ case "custom":
1035
+ return generateCustomType(type, ctx);
1036
+ default: {
1037
+ const _exhaustive = type;
1038
+ return _exhaustive;
1039
+ }
1040
+ }
1041
+ }
1042
+ function generatePrimitiveType(type) {
1043
+ return {
1044
+ type: type.primitiveKind === "integer" || type.primitiveKind === "bigint" ? "integer" : type.primitiveKind
1045
+ };
1046
+ }
1047
+ function generateEnumType(type, ctx) {
1048
+ if (ctx.enumSerialization === "oneOf") {
1049
+ return {
1050
+ oneOf: type.members.map((m) => ({
1051
+ const: m.value,
1052
+ title: m.displayName ?? String(m.value)
1053
+ }))
1054
+ };
1055
+ }
1056
+ const schema = { enum: type.members.map((m) => m.value) };
1057
+ const displayNames = buildEnumDisplayNameExtension(type);
1058
+ if (displayNames !== void 0) {
1059
+ schema[`${ctx.vendorPrefix}-display-names`] = displayNames;
1060
+ }
1061
+ return schema;
1062
+ }
1063
+ function buildEnumDisplayNameExtension(type) {
1064
+ if (!type.members.some((member) => member.displayName !== void 0)) {
1065
+ return void 0;
1066
+ }
1067
+ const displayNames = /* @__PURE__ */ Object.create(null);
1068
+ for (const member of type.members) {
1069
+ const key = String(member.value);
1070
+ if (Object.hasOwn(displayNames, key)) {
1071
+ throw new Error(
1072
+ `Enum display-name key "${key}" is ambiguous after stringification. Use oneOf serialization for mixed string/number enum values that collide.`
1073
+ );
1074
+ }
1075
+ displayNames[key] = member.displayName ?? key;
1076
+ }
1077
+ return displayNames;
1078
+ }
1079
+ function generateArrayType(type, ctx) {
1080
+ return {
1081
+ type: "array",
1082
+ items: generateTypeNode(type.items, ctx)
1083
+ };
1084
+ }
1085
+ function generateObjectType(type, ctx) {
1086
+ const properties = {};
1087
+ const required = [];
1088
+ for (const prop of type.properties) {
1089
+ const propertyName = getSerializedObjectPropertyName(prop);
1090
+ properties[propertyName] = generatePropertySchema(prop, ctx);
1091
+ if (!prop.optional) {
1092
+ required.push(propertyName);
1093
+ }
1094
+ }
1095
+ const schema = { type: "object", properties };
1096
+ if (required.length > 0) {
1097
+ schema.required = required;
1098
+ }
1099
+ if (!type.additionalProperties) {
1100
+ schema.additionalProperties = false;
1101
+ }
1102
+ return schema;
1103
+ }
1104
+ function generateRecordType(type, ctx) {
1105
+ return {
1106
+ type: "object",
1107
+ additionalProperties: generateTypeNode(type.valueType, ctx)
1108
+ };
1109
+ }
1110
+ function generatePropertySchema(prop, ctx) {
1111
+ const schema = generateTypeNode(prop.type, ctx);
1112
+ applyConstraints(schema, prop.constraints, ctx);
1113
+ applyResolvedMetadata(schema, prop.metadata);
1114
+ applyAnnotations(schema, prop.annotations, ctx);
1115
+ return schema;
1116
+ }
1117
+ function generateUnionType(type, ctx) {
1118
+ if (isBooleanUnion(type)) {
1119
+ return { type: "boolean" };
1120
+ }
1121
+ if (isNullableUnion(type)) {
1122
+ return {
1123
+ oneOf: type.members.map((m) => generateTypeNode(m, ctx))
1124
+ };
1125
+ }
1126
+ return {
1127
+ anyOf: type.members.map((m) => generateTypeNode(m, ctx))
1128
+ };
1129
+ }
1130
+ function isBooleanUnion(type) {
1131
+ if (type.members.length !== 2) return false;
1132
+ const kinds = type.members.map((m) => m.kind);
1133
+ return kinds.every((k) => k === "primitive") && type.members.every((m) => m.kind === "primitive" && m.primitiveKind === "boolean");
1134
+ }
1135
+ function isNullableUnion(type) {
1136
+ if (type.members.length !== 2) return false;
1137
+ const nullCount = type.members.filter(
1138
+ (m) => m.kind === "primitive" && m.primitiveKind === "null"
1139
+ ).length;
1140
+ return nullCount === 1;
1141
+ }
1142
+ function generateReferenceType(type, ctx) {
1143
+ return { $ref: `#/$defs/${getSerializedTypeName(type.name, ctx)}` };
1144
+ }
1145
+ function getSerializedFieldName(field) {
1146
+ return getSerializedName(field.name, field.metadata);
1147
+ }
1148
+ function getSerializedObjectPropertyName(property) {
1149
+ return getSerializedName(property.name, property.metadata);
1150
+ }
1151
+ function getSerializedTypeName(logicalName, ctx) {
1152
+ return ctx.typeNameMap[logicalName] ?? logicalName;
1153
+ }
1154
+ function applyResolvedMetadata(schema, metadata) {
1155
+ const displayName = getDisplayName(metadata);
1156
+ if (displayName !== void 0) {
1157
+ schema.title = displayName;
1158
+ }
1159
+ }
1160
+ function resolveReferencedType(type, ctx) {
1161
+ return ctx.typeRegistry[type.name]?.type;
1162
+ }
1163
+ function dereferenceTypeNode(typeNode, ctx) {
1164
+ if (typeNode?.kind !== "reference") {
1165
+ return typeNode;
1166
+ }
1167
+ return resolveReferencedType(typeNode, ctx);
1168
+ }
1169
+ function unwrapNullableTypeNode(typeNode) {
1170
+ if (typeNode?.kind !== "union" || !isNullableUnion(typeNode)) {
1171
+ return typeNode;
1172
+ }
1173
+ return typeNode.members.find(
1174
+ (member) => !(member.kind === "primitive" && member.primitiveKind === "null")
1175
+ );
1176
+ }
1177
+ function resolveTraversableTypeNode(typeNode, ctx) {
1178
+ const dereferenced = dereferenceTypeNode(typeNode, ctx);
1179
+ const unwrapped = unwrapNullableTypeNode(dereferenced);
1180
+ if (unwrapped !== dereferenced) {
1181
+ return resolveTraversableTypeNode(unwrapped, ctx);
1182
+ }
1183
+ return dereferenced;
1184
+ }
1185
+ function resolveSerializedPropertyName(logicalName, typeNode, ctx) {
1186
+ const effectiveType = resolveTraversableTypeNode(typeNode, ctx);
1187
+ if (effectiveType?.kind === "array") {
1188
+ return resolveSerializedPropertyName(logicalName, effectiveType.items, ctx);
1189
+ }
1190
+ if (effectiveType?.kind === "object") {
1191
+ const property = effectiveType.properties.find((candidate) => candidate.name === logicalName);
1192
+ return property === void 0 ? logicalName : getSerializedObjectPropertyName(property);
1193
+ }
1194
+ return logicalName;
1195
+ }
1196
+ function resolveTargetTypeNode(logicalName, typeNode, ctx) {
1197
+ const effectiveType = resolveTraversableTypeNode(typeNode, ctx);
1198
+ if (effectiveType?.kind === "array") {
1199
+ return resolveTargetTypeNode(logicalName, effectiveType.items, ctx);
1200
+ }
1201
+ if (effectiveType?.kind !== "object") {
1202
+ return void 0;
1203
+ }
1204
+ return effectiveType.properties.find((candidate) => candidate.name === logicalName)?.type;
1205
+ }
1206
+ function buildPropertyOverrides(pathConstraints, typeNode, ctx) {
1207
+ const byTarget = /* @__PURE__ */ new Map();
1208
+ for (const constraint of pathConstraints) {
1209
+ const target = constraint.path?.segments[0];
1210
+ if (!target) {
1211
+ continue;
1212
+ }
1213
+ const grouped = byTarget.get(target) ?? [];
1214
+ grouped.push(constraint);
1215
+ byTarget.set(target, grouped);
1216
+ }
1217
+ const overrides = {};
1218
+ for (const [target, constraints] of byTarget) {
1219
+ overrides[resolveSerializedPropertyName(target, typeNode, ctx)] = buildPathOverrideSchema(
1220
+ constraints.map(stripLeadingPathSegment),
1221
+ resolveTargetTypeNode(target, typeNode, ctx),
1222
+ ctx
1223
+ );
1224
+ }
1225
+ return overrides;
1226
+ }
1227
+ function buildPathOverrideSchema(constraints, typeNode, ctx) {
1228
+ const schema = {};
1229
+ const directConstraints = [];
1230
+ const nestedConstraints = [];
1231
+ for (const constraint of constraints) {
1232
+ if (constraint.path === void 0 || constraint.path.segments.length === 0) {
1233
+ directConstraints.push(constraint);
1234
+ } else {
1235
+ nestedConstraints.push(constraint);
1236
+ }
1237
+ }
1238
+ applyConstraints(schema, directConstraints, ctx);
1239
+ if (nestedConstraints.length === 0) {
1240
+ return schema;
1241
+ }
1242
+ const effectiveType = resolveTraversableTypeNode(typeNode, ctx);
1243
+ if (effectiveType?.kind === "array") {
1244
+ schema.items = buildPathOverrideSchema(nestedConstraints, effectiveType.items, ctx);
1245
+ return schema;
1246
+ }
1247
+ schema.properties = buildPropertyOverrides(nestedConstraints, effectiveType, ctx);
1248
+ return schema;
1249
+ }
1250
+ function mergeSchemaOverride(target, override) {
1251
+ const nullableValueBranch = getNullableUnionValueSchema(target);
1252
+ if (nullableValueBranch !== void 0) {
1253
+ mergeSchemaOverride(nullableValueBranch, override);
1254
+ return;
1255
+ }
1256
+ if (override.properties !== void 0) {
1257
+ const mergedProperties = target.properties ?? {};
1258
+ for (const [name, propertyOverride] of Object.entries(override.properties)) {
1259
+ const existing = mergedProperties[name];
1260
+ if (existing === void 0) {
1261
+ mergedProperties[name] = propertyOverride;
1262
+ } else {
1263
+ mergeSchemaOverride(existing, propertyOverride);
1264
+ }
1265
+ }
1266
+ target.properties = mergedProperties;
1267
+ }
1268
+ if (override.items !== void 0) {
1269
+ if (target.items === void 0) {
1270
+ target.items = override.items;
1271
+ } else {
1272
+ mergeSchemaOverride(target.items, override.items);
1273
+ }
1274
+ }
1275
+ for (const [key, value] of Object.entries(override)) {
1276
+ if (key === "properties" || key === "items") {
1277
+ continue;
1278
+ }
1279
+ target[key] = value;
1280
+ }
1281
+ }
1282
+ function stripLeadingPathSegment(constraint) {
1283
+ const segments = constraint.path?.segments;
1284
+ if (segments === void 0 || segments.length === 0) {
1285
+ return constraint;
1286
+ }
1287
+ const [, ...rest] = segments;
1288
+ if (rest.length === 0) {
1289
+ const { path: _path, ...stripped } = constraint;
1290
+ return stripped;
1291
+ }
1292
+ return {
1293
+ ...constraint,
1294
+ path: { segments: rest }
1295
+ };
1296
+ }
1297
+ function getNullableUnionValueSchema(schema) {
1298
+ if (schema.oneOf?.length !== 2) {
1299
+ return void 0;
1300
+ }
1301
+ const valueSchema = schema.oneOf.find((branch) => branch.type !== "null");
1302
+ const nullSchema = schema.oneOf.find((branch) => branch.type === "null");
1303
+ return valueSchema !== void 0 && nullSchema !== void 0 ? valueSchema : void 0;
1304
+ }
1305
+ function generateDynamicType(type) {
1306
+ if (type.dynamicKind === "enum") {
1307
+ const schema = {
1308
+ type: "string",
1309
+ "x-formspec-source": type.sourceKey
1310
+ };
1311
+ if (type.parameterFields.length > 0) {
1312
+ schema["x-formspec-params"] = [...type.parameterFields];
1313
+ }
1314
+ return schema;
1315
+ }
1316
+ return {
1317
+ type: "object",
1318
+ additionalProperties: true,
1319
+ "x-formspec-schemaSource": type.sourceKey
1320
+ };
1321
+ }
1322
+ function applyConstraints(schema, constraints, ctx) {
1323
+ for (const constraint of constraints) {
1324
+ switch (constraint.constraintKind) {
1325
+ case "minimum":
1326
+ schema.minimum = constraint.value;
1327
+ break;
1328
+ case "maximum":
1329
+ schema.maximum = constraint.value;
1330
+ break;
1331
+ case "exclusiveMinimum":
1332
+ schema.exclusiveMinimum = constraint.value;
1333
+ break;
1334
+ case "exclusiveMaximum":
1335
+ schema.exclusiveMaximum = constraint.value;
1336
+ break;
1337
+ case "multipleOf": {
1338
+ const { value } = constraint;
1339
+ if (value === 1 && schema.type === "number") {
1340
+ schema.type = "integer";
1341
+ } else {
1342
+ schema.multipleOf = value;
1343
+ }
1344
+ break;
1345
+ }
1346
+ case "minLength":
1347
+ schema.minLength = constraint.value;
1348
+ break;
1349
+ case "maxLength":
1350
+ schema.maxLength = constraint.value;
1351
+ break;
1352
+ case "minItems":
1353
+ schema.minItems = constraint.value;
1354
+ break;
1355
+ case "maxItems":
1356
+ schema.maxItems = constraint.value;
1357
+ break;
1358
+ case "pattern":
1359
+ schema.pattern = constraint.pattern;
1360
+ break;
1361
+ case "uniqueItems":
1362
+ schema.uniqueItems = constraint.value;
1363
+ break;
1364
+ case "const":
1365
+ schema.const = constraint.value;
1366
+ break;
1367
+ case "allowedMembers":
1368
+ break;
1369
+ case "custom":
1370
+ applyCustomConstraint(schema, constraint, ctx);
1371
+ break;
1372
+ default: {
1373
+ const _exhaustive = constraint;
1374
+ void _exhaustive;
1375
+ }
1376
+ }
1377
+ }
1378
+ }
1379
+ function applyAnnotations(schema, annotations, ctx) {
1380
+ for (const annotation of annotations) {
1381
+ switch (annotation.annotationKind) {
1382
+ case "displayName":
1383
+ schema.title ??= annotation.value;
1384
+ break;
1385
+ case "description":
1386
+ schema.description = annotation.value;
1387
+ break;
1388
+ case "remarks":
1389
+ schema[`${ctx.vendorPrefix}-remarks`] = annotation.value;
1390
+ break;
1391
+ case "defaultValue":
1392
+ schema.default = annotation.value;
1393
+ break;
1394
+ case "format":
1395
+ schema.format = annotation.value;
1396
+ break;
1397
+ case "deprecated":
1398
+ schema.deprecated = true;
1399
+ if (annotation.message !== void 0 && annotation.message !== "") {
1400
+ schema[`${ctx.vendorPrefix}-deprecation-description`] = annotation.message;
1401
+ }
1402
+ break;
1403
+ case "placeholder":
1404
+ break;
1405
+ case "formatHint":
1406
+ break;
1407
+ case "custom":
1408
+ applyCustomAnnotation(schema, annotation, ctx);
1409
+ break;
1410
+ default: {
1411
+ const _exhaustive = annotation;
1412
+ void _exhaustive;
1413
+ }
1414
+ }
1415
+ }
1416
+ }
1417
+ function generateCustomType(type, ctx) {
1418
+ const registration = ctx.extensionRegistry?.findType(type.typeId);
1419
+ if (registration === void 0) {
1420
+ throw new Error(
1421
+ `Cannot generate JSON Schema for custom type "${type.typeId}" without a matching extension registration`
1422
+ );
1423
+ }
1424
+ return registration.toJsonSchema(type.payload, ctx.vendorPrefix);
1425
+ }
1426
+ function applyCustomConstraint(schema, constraint, ctx) {
1427
+ const registration = ctx.extensionRegistry?.findConstraint(constraint.constraintId);
1428
+ if (registration === void 0) {
1429
+ throw new Error(
1430
+ `Cannot generate JSON Schema for custom constraint "${constraint.constraintId}" without a matching extension registration`
1431
+ );
1432
+ }
1433
+ assignVendorPrefixedExtensionKeywords(
1434
+ schema,
1435
+ registration.toJsonSchema(constraint.payload, ctx.vendorPrefix),
1436
+ ctx.vendorPrefix,
1437
+ `custom constraint "${constraint.constraintId}"`
1438
+ );
1439
+ }
1440
+ function applyCustomAnnotation(schema, annotation, ctx) {
1441
+ const registration = ctx.extensionRegistry?.findAnnotation(annotation.annotationId);
1442
+ if (registration === void 0) {
1443
+ throw new Error(
1444
+ `Cannot generate JSON Schema for custom annotation "${annotation.annotationId}" without a matching extension registration`
1445
+ );
1446
+ }
1447
+ if (registration.toJsonSchema === void 0) {
1448
+ return;
1449
+ }
1450
+ assignVendorPrefixedExtensionKeywords(
1451
+ schema,
1452
+ registration.toJsonSchema(annotation.value, ctx.vendorPrefix),
1453
+ ctx.vendorPrefix,
1454
+ `custom annotation "${annotation.annotationId}"`
1455
+ );
1456
+ }
1457
+ function assignVendorPrefixedExtensionKeywords(schema, extensionSchema, vendorPrefix, source) {
1458
+ for (const [key, value] of Object.entries(extensionSchema)) {
1459
+ if (!key.startsWith(`${vendorPrefix}-`)) {
1460
+ throw new Error(
1461
+ `Cannot apply ${source}: extension hooks may only emit "${vendorPrefix}-*" JSON Schema keywords`
1462
+ );
1463
+ }
1464
+ schema[key] = value;
1465
+ }
1466
+ }
1467
+
1468
+ // src/json-schema/generator.ts
1469
+ function generateJsonSchema(form, options) {
1470
+ const metadata = options?.metadata;
1471
+ const vendorPrefix = options?.vendorPrefix;
1472
+ const enumSerialization = options?.enumSerialization;
1473
+ const ir = canonicalizeChainDSL(
1474
+ form,
1475
+ metadata !== void 0 ? { metadata } : void 0
1476
+ );
1477
+ const internalOptions = vendorPrefix === void 0 && enumSerialization === void 0 ? void 0 : {
1478
+ ...vendorPrefix !== void 0 && { vendorPrefix },
1479
+ ...enumSerialization !== void 0 && { enumSerialization }
1480
+ };
1481
+ return generateJsonSchemaFromIR(ir, internalOptions);
1482
+ }
1483
+
1484
+ // src/ui-schema/schema.ts
1485
+ import { z } from "zod";
1486
+ var jsonPointerSchema = z.string();
1487
+ var ruleEffectSchema = z.enum(["SHOW", "HIDE", "ENABLE", "DISABLE"]);
1488
+ var uiSchemaElementTypeSchema = z.enum([
1489
+ "Control",
1490
+ "VerticalLayout",
1491
+ "HorizontalLayout",
1492
+ "Group",
1493
+ "Categorization",
1494
+ "Category",
1495
+ "Label"
1496
+ ]);
1497
+ var ruleConditionSchema = z.lazy(
1498
+ () => z.object({
1499
+ const: z.unknown().optional(),
1500
+ enum: z.array(z.unknown()).readonly().optional(),
1501
+ type: z.string().optional(),
1502
+ not: ruleConditionSchema.optional(),
1503
+ minimum: z.number().optional(),
1504
+ maximum: z.number().optional(),
1505
+ exclusiveMinimum: z.number().optional(),
1506
+ exclusiveMaximum: z.number().optional(),
1507
+ minLength: z.number().optional(),
1508
+ properties: z.record(z.string(), ruleConditionSchema).optional(),
1509
+ required: z.array(z.string()).optional(),
1510
+ allOf: z.array(ruleConditionSchema).optional()
1511
+ }).strict()
1512
+ );
1513
+ var schemaBasedConditionSchema = z.object({
1514
+ scope: jsonPointerSchema,
1515
+ schema: ruleConditionSchema
1516
+ }).strict();
1517
+ var ruleSchema = z.object({
1518
+ effect: ruleEffectSchema,
1519
+ condition: schemaBasedConditionSchema
1520
+ }).strict();
1521
+ var uiSchemaElementSchema = z.lazy(
1522
+ () => z.union([
1523
+ controlSchema,
1524
+ verticalLayoutSchema,
1525
+ horizontalLayoutSchema,
1526
+ groupLayoutSchema,
1527
+ categorizationSchema,
1528
+ categorySchema,
1529
+ labelElementSchema
1530
+ ])
1531
+ );
1532
+ var controlSchema = z.object({
1533
+ type: z.literal("Control"),
1534
+ scope: jsonPointerSchema,
1535
+ label: z.union([z.string(), z.literal(false)]).optional(),
1536
+ rule: ruleSchema.optional(),
1537
+ options: z.record(z.string(), z.unknown()).optional()
1538
+ }).passthrough();
1539
+ var verticalLayoutSchema = z.lazy(
1540
+ () => z.object({
1541
+ type: z.literal("VerticalLayout"),
1542
+ elements: z.array(uiSchemaElementSchema),
1543
+ rule: ruleSchema.optional(),
1544
+ options: z.record(z.string(), z.unknown()).optional()
1545
+ }).passthrough()
1546
+ );
1547
+ var horizontalLayoutSchema = z.lazy(
1548
+ () => z.object({
1549
+ type: z.literal("HorizontalLayout"),
1550
+ elements: z.array(uiSchemaElementSchema),
1551
+ rule: ruleSchema.optional(),
1552
+ options: z.record(z.string(), z.unknown()).optional()
1553
+ }).passthrough()
1554
+ );
1555
+ var groupLayoutSchema = z.lazy(
1556
+ () => z.object({
1557
+ type: z.literal("Group"),
1558
+ label: z.string(),
1559
+ elements: z.array(uiSchemaElementSchema),
1560
+ rule: ruleSchema.optional(),
1561
+ options: z.record(z.string(), z.unknown()).optional()
1562
+ }).passthrough()
1563
+ );
1564
+ var categorySchema = z.lazy(
1565
+ () => z.object({
1566
+ type: z.literal("Category"),
1567
+ label: z.string(),
1568
+ elements: z.array(uiSchemaElementSchema),
1569
+ rule: ruleSchema.optional(),
1570
+ options: z.record(z.string(), z.unknown()).optional()
1571
+ }).passthrough()
1572
+ );
1573
+ var categorizationSchema = z.lazy(
1574
+ () => z.object({
1575
+ type: z.literal("Categorization"),
1576
+ elements: z.array(categorySchema),
1577
+ label: z.string().optional(),
1578
+ rule: ruleSchema.optional(),
1579
+ options: z.record(z.string(), z.unknown()).optional()
1580
+ }).passthrough()
1581
+ );
1582
+ var labelElementSchema = z.object({
1583
+ type: z.literal("Label"),
1584
+ text: z.string(),
1585
+ rule: ruleSchema.optional(),
1586
+ options: z.record(z.string(), z.unknown()).optional()
1587
+ }).passthrough();
1588
+ var uiSchema = z.lazy(
1589
+ () => z.union([verticalLayoutSchema, horizontalLayoutSchema, groupLayoutSchema, categorizationSchema])
1590
+ );
1591
+
1592
+ // src/ui-schema/ir-generator.ts
1593
+ import { z as z2 } from "zod";
1594
+ function parseOrThrow(schema, value, label) {
1595
+ try {
1596
+ return schema.parse(value);
1597
+ } catch (error) {
1598
+ if (error instanceof z2.ZodError) {
1599
+ throw new Error(
1600
+ `Generated ${label} failed validation:
1601
+ ${error.issues.map((i) => ` ${i.path.join(".")}: ${i.message}`).join("\n")}`
1602
+ );
1603
+ }
1604
+ throw error;
1605
+ }
1606
+ }
1607
+ function fieldToScope(fieldName) {
1608
+ return `#/properties/${fieldName}`;
1609
+ }
1610
+ function createShowRule(fieldName, value) {
1611
+ return {
1612
+ effect: "SHOW",
1613
+ condition: {
1614
+ scope: fieldToScope(fieldName),
1615
+ schema: { const: value }
1616
+ }
1617
+ };
1618
+ }
1619
+ function flattenConditionSchema(scope, schema) {
1620
+ if (schema.allOf === void 0) {
1621
+ if (scope === "#") {
1622
+ return [schema];
1623
+ }
1624
+ const fieldName = scope.replace("#/properties/", "");
1625
+ return [
1626
+ {
1627
+ properties: {
1628
+ [fieldName]: schema
1629
+ }
1630
+ }
1631
+ ];
1632
+ }
1633
+ return schema.allOf.flatMap((member) => flattenConditionSchema(scope, member));
1634
+ }
1635
+ function combineRules(parentRule, childRule) {
1636
+ return {
1637
+ effect: "SHOW",
1638
+ condition: {
1639
+ scope: "#",
1640
+ schema: {
1641
+ allOf: [
1642
+ ...flattenConditionSchema(parentRule.condition.scope, parentRule.condition.schema),
1643
+ ...flattenConditionSchema(childRule.condition.scope, childRule.condition.schema)
1644
+ ]
1645
+ }
1646
+ }
1647
+ };
1648
+ }
1649
+ function getFieldDisplayName(field) {
1650
+ const resolvedDisplayName = getDisplayName(field.metadata);
1651
+ if (resolvedDisplayName !== void 0) {
1652
+ return resolvedDisplayName;
1653
+ }
1654
+ return field.annotations.find((annotation) => annotation.annotationKind === "displayName")?.value;
1655
+ }
1656
+ function fieldNodeToControl(field, fieldNameMap, parentRule) {
1657
+ const placeholderAnnotation = field.annotations.find((a) => a.annotationKind === "placeholder");
1658
+ const serializedName = fieldNameMap.get(field.name) ?? getSerializedName(field.name, field.metadata);
1659
+ const displayName = getFieldDisplayName(field);
1660
+ const control = {
1661
+ type: "Control",
1662
+ scope: fieldToScope(serializedName),
1663
+ ...displayName !== void 0 && { label: displayName },
1664
+ ...placeholderAnnotation !== void 0 && {
1665
+ options: { placeholder: placeholderAnnotation.value }
1666
+ },
1667
+ ...parentRule !== void 0 && { rule: parentRule }
1668
+ };
1669
+ return control;
1670
+ }
1671
+ function groupNodeToLayout(group, fieldNameMap, parentRule) {
1672
+ return {
1673
+ type: "Group",
1674
+ label: group.label,
1675
+ elements: irElementsToUiSchema(group.elements, fieldNameMap, parentRule),
1676
+ ...parentRule !== void 0 && { rule: parentRule }
1677
+ };
1678
+ }
1679
+ function irElementsToUiSchema(elements, fieldNameMap, parentRule) {
1680
+ const result = [];
1681
+ for (const element of elements) {
1682
+ switch (element.kind) {
1683
+ case "field": {
1684
+ result.push(fieldNodeToControl(element, fieldNameMap, parentRule));
1685
+ break;
1686
+ }
1687
+ case "group": {
1688
+ result.push(groupNodeToLayout(element, fieldNameMap, parentRule));
1689
+ break;
1690
+ }
1691
+ case "conditional": {
1692
+ const newRule = createShowRule(fieldNameMap.get(element.fieldName) ?? element.fieldName, element.value);
1693
+ const combinedRule = parentRule !== void 0 ? combineRules(parentRule, newRule) : newRule;
1694
+ const childElements = irElementsToUiSchema(element.elements, fieldNameMap, combinedRule);
1695
+ result.push(...childElements);
1696
+ break;
1697
+ }
1698
+ default: {
1699
+ const _exhaustive = element;
1700
+ void _exhaustive;
1701
+ throw new Error("Unhandled IR element kind");
1702
+ }
1703
+ }
1704
+ }
1705
+ return result;
1706
+ }
1707
+ function generateUiSchemaFromIR(ir) {
1708
+ assertNoSerializedNameCollisions(ir);
1709
+ const fieldNameMap = collectFieldNameMap(ir.elements);
1710
+ const result = {
1711
+ type: "VerticalLayout",
1712
+ elements: irElementsToUiSchema(ir.elements, fieldNameMap)
1713
+ };
1714
+ return parseOrThrow(uiSchema, result, "UI Schema");
1715
+ }
1716
+ function collectFieldNameMap(elements) {
1717
+ const map = /* @__PURE__ */ new Map();
1718
+ for (const element of elements) {
1719
+ switch (element.kind) {
1720
+ case "field":
1721
+ map.set(element.name, getSerializedName(element.name, element.metadata));
1722
+ break;
1723
+ case "group":
1724
+ case "conditional":
1725
+ for (const [key, value] of collectFieldNameMap(element.elements)) {
1726
+ map.set(key, value);
1727
+ }
1728
+ break;
1729
+ default: {
1730
+ const _exhaustive = element;
1731
+ void _exhaustive;
1732
+ }
1733
+ }
1734
+ }
1735
+ return map;
1736
+ }
1737
+
1738
+ // src/ui-schema/generator.ts
1739
+ function generateUiSchema(form, options) {
1740
+ const ir = canonicalizeChainDSL(
1741
+ form,
1742
+ options?.metadata !== void 0 ? { metadata: options.metadata } : void 0
1743
+ );
1744
+ return generateUiSchemaFromIR(ir);
1745
+ }
1746
+
1747
+ // src/json-schema/types.ts
1748
+ function setSchemaExtension(schema, key, value) {
1749
+ schema[key] = value;
1750
+ }
1751
+ function getSchemaExtension(schema, key) {
1752
+ return schema[key];
1753
+ }
1754
+
1755
+ // src/extensions/registry.ts
1756
+ import {
1757
+ BUILTIN_CONSTRAINT_DEFINITIONS,
1758
+ normalizeConstraintTagName
1759
+ } from "@formspec/core/internals";
1760
+ import {
1761
+ getTagDefinition,
1762
+ normalizeFormSpecTagName
1763
+ } from "@formspec/analysis/internal";
1764
+ var BUILTIN_METADATA_TAGS = /* @__PURE__ */ new Set(["apiName", "displayName"]);
1765
+ function buildConstraintTagSources(extensions) {
1766
+ return extensions.map((extension) => ({
1767
+ extensionId: extension.extensionId,
1768
+ ...extension.constraintTags !== void 0 ? {
1769
+ constraintTags: extension.constraintTags.map((tag) => ({
1770
+ tagName: normalizeFormSpecTagName(tag.tagName)
1771
+ }))
1772
+ } : {}
1773
+ }));
1774
+ }
1775
+ function createExtensionRegistry(extensions) {
1776
+ const reservedTagSources = buildConstraintTagSources(extensions);
1777
+ const typeMap = /* @__PURE__ */ new Map();
1778
+ const typeNameMap = /* @__PURE__ */ new Map();
1779
+ const constraintMap = /* @__PURE__ */ new Map();
1780
+ const constraintTagMap = /* @__PURE__ */ new Map();
1781
+ const builtinBroadeningMap = /* @__PURE__ */ new Map();
1782
+ const annotationMap = /* @__PURE__ */ new Map();
1783
+ const metadataSlotMap = /* @__PURE__ */ new Map();
1784
+ const metadataTagMap = /* @__PURE__ */ new Map();
1785
+ for (const ext of extensions) {
1786
+ if (ext.types !== void 0) {
1787
+ for (const type of ext.types) {
1788
+ const qualifiedId = `${ext.extensionId}/${type.typeName}`;
1789
+ if (typeMap.has(qualifiedId)) {
1790
+ throw new Error(`Duplicate custom type ID: "${qualifiedId}"`);
1791
+ }
1792
+ typeMap.set(qualifiedId, type);
1793
+ for (const sourceTypeName of type.tsTypeNames ?? [type.typeName]) {
1794
+ if (typeNameMap.has(sourceTypeName)) {
1795
+ throw new Error(`Duplicate custom type source name: "${sourceTypeName}"`);
1796
+ }
1797
+ typeNameMap.set(sourceTypeName, {
1798
+ extensionId: ext.extensionId,
1799
+ registration: type
1800
+ });
1801
+ }
1802
+ if (type.builtinConstraintBroadenings !== void 0) {
1803
+ for (const broadening of type.builtinConstraintBroadenings) {
1804
+ const key = `${qualifiedId}:${broadening.tagName}`;
1805
+ if (builtinBroadeningMap.has(key)) {
1806
+ throw new Error(`Duplicate built-in constraint broadening: "${key}"`);
1807
+ }
1808
+ builtinBroadeningMap.set(key, {
1809
+ extensionId: ext.extensionId,
1810
+ registration: broadening
1811
+ });
1812
+ }
1813
+ }
1814
+ }
1815
+ }
1816
+ if (ext.constraints !== void 0) {
1817
+ for (const constraint of ext.constraints) {
1818
+ const qualifiedId = `${ext.extensionId}/${constraint.constraintName}`;
1819
+ if (constraintMap.has(qualifiedId)) {
1820
+ throw new Error(`Duplicate custom constraint ID: "${qualifiedId}"`);
1821
+ }
1822
+ constraintMap.set(qualifiedId, constraint);
1823
+ }
1824
+ }
1825
+ if (ext.constraintTags !== void 0) {
1826
+ for (const tag of ext.constraintTags) {
1827
+ const canonicalTagName = normalizeFormSpecTagName(tag.tagName);
1828
+ if (constraintTagMap.has(canonicalTagName)) {
1829
+ throw new Error(`Duplicate custom constraint tag: "@${canonicalTagName}"`);
1830
+ }
1831
+ constraintTagMap.set(canonicalTagName, {
1832
+ extensionId: ext.extensionId,
1833
+ registration: tag
1834
+ });
1835
+ }
1836
+ }
1837
+ if (ext.annotations !== void 0) {
1838
+ for (const annotation of ext.annotations) {
1839
+ const qualifiedId = `${ext.extensionId}/${annotation.annotationName}`;
1840
+ if (annotationMap.has(qualifiedId)) {
1841
+ throw new Error(`Duplicate custom annotation ID: "${qualifiedId}"`);
1842
+ }
1843
+ annotationMap.set(qualifiedId, annotation);
1844
+ }
1845
+ }
1846
+ if (ext.metadataSlots !== void 0) {
1847
+ for (const slot of ext.metadataSlots) {
1848
+ if (metadataSlotMap.has(slot.slotId)) {
1849
+ throw new Error(`Duplicate metadata slot ID: "${slot.slotId}"`);
1850
+ }
1851
+ metadataSlotMap.set(slot.slotId, true);
1852
+ const canonicalTagName = normalizeFormSpecTagName(slot.tagName);
1853
+ if (slot.allowBare === false && (slot.qualifiers?.length ?? 0) === 0) {
1854
+ throw new Error(
1855
+ `Metadata tag "@${canonicalTagName}" must allow bare usage or declare at least one qualifier.`
1856
+ );
1857
+ }
1858
+ if (metadataTagMap.has(canonicalTagName)) {
1859
+ throw new Error(`Duplicate metadata tag: "@${canonicalTagName}"`);
1860
+ }
1861
+ if (BUILTIN_METADATA_TAGS.has(canonicalTagName)) {
1862
+ throw new Error(
1863
+ `Metadata tag "@${canonicalTagName}" conflicts with built-in metadata tags.`
1864
+ );
1865
+ }
1866
+ if (constraintTagMap.has(canonicalTagName)) {
1867
+ throw new Error(
1868
+ `Metadata tag "@${canonicalTagName}" conflicts with existing FormSpec tag "@${canonicalTagName}".`
1869
+ );
1870
+ }
1871
+ if (Object.hasOwn(BUILTIN_CONSTRAINT_DEFINITIONS, normalizeConstraintTagName(canonicalTagName))) {
1872
+ throw new Error(
1873
+ `Metadata tag "@${canonicalTagName}" conflicts with existing FormSpec tag "@${normalizeConstraintTagName(canonicalTagName)}".`
1874
+ );
1875
+ }
1876
+ const existingTag = getTagDefinition(canonicalTagName, reservedTagSources);
1877
+ if (existingTag !== null) {
1878
+ throw BUILTIN_METADATA_TAGS.has(existingTag.canonicalName) ? new Error(
1879
+ `Metadata tag "@${canonicalTagName}" conflicts with built-in metadata tags.`
1880
+ ) : new Error(
1881
+ `Metadata tag "@${canonicalTagName}" conflicts with existing FormSpec tag "@${existingTag.canonicalName}".`
1882
+ );
1883
+ }
1884
+ metadataTagMap.set(canonicalTagName, true);
1885
+ }
1886
+ }
1887
+ }
1888
+ return {
1889
+ extensions,
1890
+ findType: (typeId) => typeMap.get(typeId),
1891
+ findTypeByName: (typeName) => typeNameMap.get(typeName),
1892
+ findConstraint: (constraintId) => constraintMap.get(constraintId),
1893
+ findConstraintTag: (tagName) => constraintTagMap.get(normalizeFormSpecTagName(tagName)),
1894
+ findBuiltinConstraintBroadening: (typeId, tagName) => builtinBroadeningMap.get(`${typeId}:${tagName}`),
1895
+ findAnnotation: (annotationId) => annotationMap.get(annotationId)
1896
+ };
1897
+ }
1898
+
1899
+ // src/json-schema/schema.ts
1900
+ import { z as z3 } from "zod";
1901
+ var jsonSchemaTypeSchema = z3.enum([
1902
+ "string",
1903
+ "number",
1904
+ "integer",
1905
+ "boolean",
1906
+ "object",
1907
+ "array",
1908
+ "null"
1909
+ ]);
1910
+ var jsonSchema7Schema = z3.lazy(
1911
+ () => z3.object({
1912
+ $schema: z3.string().optional(),
1913
+ $id: z3.string().optional(),
1914
+ $ref: z3.string().optional(),
1915
+ // Metadata
1916
+ title: z3.string().optional(),
1917
+ description: z3.string().optional(),
1918
+ deprecated: z3.boolean().optional(),
1919
+ // Type
1920
+ type: z3.union([jsonSchemaTypeSchema, z3.array(jsonSchemaTypeSchema)]).optional(),
1921
+ // String validation
1922
+ minLength: z3.number().optional(),
1923
+ maxLength: z3.number().optional(),
1924
+ pattern: z3.string().optional(),
1925
+ // Number validation
1926
+ minimum: z3.number().optional(),
1927
+ maximum: z3.number().optional(),
1928
+ exclusiveMinimum: z3.number().optional(),
1929
+ exclusiveMaximum: z3.number().optional(),
1930
+ // Enum
1931
+ enum: z3.array(z3.union([z3.string(), z3.number(), z3.boolean(), z3.null()])).readonly().optional(),
1932
+ const: z3.union([z3.string(), z3.number(), z3.boolean(), z3.null()]).optional(),
1933
+ // Object
1934
+ properties: z3.record(z3.string(), jsonSchema7Schema).optional(),
1935
+ required: z3.array(z3.string()).optional(),
1936
+ additionalProperties: z3.union([z3.boolean(), jsonSchema7Schema]).optional(),
1937
+ // Array
1938
+ items: z3.union([jsonSchema7Schema, z3.array(jsonSchema7Schema)]).optional(),
1939
+ minItems: z3.number().optional(),
1940
+ maxItems: z3.number().optional(),
1941
+ // Composition
1942
+ allOf: z3.array(jsonSchema7Schema).optional(),
1943
+ anyOf: z3.array(jsonSchema7Schema).optional(),
1944
+ oneOf: z3.array(jsonSchema7Schema).optional(),
1945
+ not: jsonSchema7Schema.optional(),
1946
+ // Conditional
1947
+ if: jsonSchema7Schema.optional(),
1948
+ then: jsonSchema7Schema.optional(),
1949
+ else: jsonSchema7Schema.optional(),
1950
+ // Format
1951
+ format: z3.string().optional(),
1952
+ // Default
1953
+ default: z3.unknown().optional(),
1954
+ // FormSpec extensions
1955
+ "x-formspec-source": z3.string().optional(),
1956
+ "x-formspec-params": z3.array(z3.string()).readonly().optional(),
1957
+ "x-formspec-schemaSource": z3.string().optional()
1958
+ }).passthrough()
1959
+ );
1960
+
1961
+ // src/validate/constraint-validator.ts
1962
+ import {
1963
+ analyzeConstraintTargets
1964
+ } from "@formspec/analysis/internal";
1965
+ function validateFieldNode(ctx, field) {
1966
+ const analysis = analyzeConstraintTargets(
1967
+ field.name,
1968
+ field.type,
1969
+ field.constraints,
1970
+ ctx.typeRegistry,
1971
+ ctx.extensionRegistry === void 0 ? void 0 : {
1972
+ extensionRegistry: ctx.extensionRegistry
1973
+ }
1974
+ );
1975
+ ctx.diagnostics.push(...analysis.diagnostics);
1976
+ if (field.type.kind === "object") {
1977
+ for (const property of field.type.properties) {
1978
+ validateObjectProperty(ctx, field.name, property);
1979
+ }
1980
+ }
1981
+ }
1982
+ function validateObjectProperty(ctx, parentName, property) {
1983
+ const qualifiedName = `${parentName}.${property.name}`;
1984
+ const analysis = analyzeConstraintTargets(
1985
+ qualifiedName,
1986
+ property.type,
1987
+ property.constraints,
1988
+ ctx.typeRegistry,
1989
+ ctx.extensionRegistry === void 0 ? void 0 : {
1990
+ extensionRegistry: ctx.extensionRegistry
1991
+ }
1992
+ );
1993
+ ctx.diagnostics.push(...analysis.diagnostics);
1994
+ if (property.type.kind === "object") {
1995
+ for (const nestedProperty of property.type.properties) {
1996
+ validateObjectProperty(ctx, qualifiedName, nestedProperty);
1997
+ }
1998
+ }
1999
+ }
2000
+ function validateElement(ctx, element) {
2001
+ switch (element.kind) {
2002
+ case "field":
2003
+ validateFieldNode(ctx, element);
2004
+ break;
2005
+ case "group":
2006
+ for (const child of element.elements) {
2007
+ validateElement(ctx, child);
2008
+ }
2009
+ break;
2010
+ case "conditional":
2011
+ for (const child of element.elements) {
2012
+ validateElement(ctx, child);
2013
+ }
2014
+ break;
2015
+ default: {
2016
+ const exhaustive = element;
2017
+ throw new Error(`Unhandled element kind: ${String(exhaustive)}`);
2018
+ }
2019
+ }
2020
+ }
2021
+ function validateIR(ir, options) {
2022
+ const ctx = {
2023
+ diagnostics: [],
2024
+ extensionRegistry: options?.extensionRegistry,
2025
+ typeRegistry: ir.typeRegistry
2026
+ };
2027
+ for (const element of ir.elements) {
2028
+ validateElement(ctx, element);
2029
+ }
2030
+ return {
2031
+ diagnostics: ctx.diagnostics,
2032
+ valid: ctx.diagnostics.every((diagnostic) => diagnostic.severity !== "error")
2033
+ };
2034
+ }
2035
+
2036
+ // src/browser.ts
2037
+ function buildFormSchemas(form, options) {
2038
+ return {
2039
+ jsonSchema: generateJsonSchema(form, options),
2040
+ uiSchema: generateUiSchema(form, options)
2041
+ };
2042
+ }
2043
+ export {
2044
+ buildFormSchemas,
2045
+ canonicalizeChainDSL,
2046
+ categorizationSchema,
2047
+ categorySchema,
2048
+ controlSchema,
2049
+ createExtensionRegistry,
2050
+ generateJsonSchema,
2051
+ generateJsonSchemaFromIR,
2052
+ generateUiSchema,
2053
+ getSchemaExtension,
2054
+ groupLayoutSchema,
2055
+ horizontalLayoutSchema,
2056
+ jsonSchema7Schema,
2057
+ jsonSchemaTypeSchema,
2058
+ labelElementSchema,
2059
+ ruleConditionSchema,
2060
+ ruleEffectSchema,
2061
+ ruleSchema,
2062
+ schemaBasedConditionSchema,
2063
+ setSchemaExtension,
2064
+ uiSchemaElementSchema,
2065
+ uiSchemaElementTypeSchema,
2066
+ uiSchema as uiSchemaSchema,
2067
+ validateIR,
2068
+ verticalLayoutSchema
2069
+ };
2070
+ //# sourceMappingURL=browser.js.map