simpler-forms 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +79 -0
  2. package/dist/src/decorators/mapping.d.ts +7 -1
  3. package/dist/src/decorators/mapping.js +103 -3
  4. package/dist/src/decorators/mapping.js.map +1 -1
  5. package/dist/src/decorators/meta.d.ts +3 -3
  6. package/dist/src/decorators/meta.js.map +1 -1
  7. package/dist/src/decorators/shared.d.ts +2 -2
  8. package/dist/src/decorators/shared.js.map +1 -1
  9. package/dist/src/emitter.js +7 -3
  10. package/dist/src/emitter.js.map +1 -1
  11. package/dist/src/emitters/overlay.d.ts +7 -2
  12. package/dist/src/emitters/overlay.js +27 -19
  13. package/dist/src/emitters/overlay.js.map +1 -1
  14. package/dist/src/index.d.ts +8 -3
  15. package/dist/src/index.js +5 -0
  16. package/dist/src/index.js.map +1 -1
  17. package/dist/src/lib.d.ts +104 -4
  18. package/dist/src/lib.js +43 -0
  19. package/dist/src/lib.js.map +1 -1
  20. package/dist/src/linter.js +6 -2
  21. package/dist/src/linter.js.map +1 -1
  22. package/dist/src/mapping-from.d.ts +2 -1
  23. package/dist/src/mapping-from.js +30 -10
  24. package/dist/src/mapping-from.js.map +1 -1
  25. package/dist/src/mapping.d.ts +7 -0
  26. package/dist/src/mapping.js.map +1 -1
  27. package/dist/src/model.d.ts +76 -8
  28. package/dist/src/model.js +43 -2
  29. package/dist/src/model.js.map +1 -1
  30. package/dist/src/public.d.ts +1 -1
  31. package/dist/src/public.js +1 -1
  32. package/dist/src/public.js.map +1 -1
  33. package/dist/src/validate.js +29 -1
  34. package/dist/src/validate.js.map +1 -1
  35. package/lib/mapping.tsp +102 -0
  36. package/lib/meta.tsp +3 -3
  37. package/lib/types.tsp +13 -0
  38. package/package.json +11 -11
  39. package/src/decorators/mapping.ts +152 -9
  40. package/src/decorators/meta.ts +7 -3
  41. package/src/decorators/shared.ts +6 -1
  42. package/src/emitter.ts +17 -3
  43. package/src/emitters/overlay.ts +40 -13
  44. package/src/index.ts +5 -0
  45. package/src/lib.ts +43 -0
  46. package/src/linter.ts +16 -7
  47. package/src/mapping-from.ts +33 -10
  48. package/src/mapping.ts +7 -0
  49. package/src/model.ts +119 -11
  50. package/src/public.ts +10 -0
  51. package/src/validate.ts +33 -1
package/lib/mapping.tsp CHANGED
@@ -23,6 +23,75 @@ namespace SimplerForms.Mapping;
23
23
  */
24
24
  extern dec targets(target: Namespace, targets: Enum);
25
25
 
26
+ /**
27
+ * Declare the value transformations `@Mapping.transform` can name, as `@Mapping.targets`
28
+ * declares the mappings. Each member is one transformation an emitter's runtime implements,
29
+ * with the name it implements it under as its value.
30
+ */
31
+ extern dec transforms(target: Namespace, transforms: Enum);
32
+
33
+ /**
34
+ * Transform this target property's value with `transform` before it is written: a member of
35
+ * an enum declared with `@Mapping.transforms`. `params` are passed to it by name, e.g.
36
+ * `#{ max_length: 60 }` for a transformation that truncates.
37
+ */
38
+ extern dec transform(
39
+ target: ModelProperty,
40
+ transform: EnumMember,
41
+ params?: valueof Record<unknown>
42
+ );
43
+
44
+ /**
45
+ * Write this target property's value as the entry `cases` gives it: a lookup spelled out in
46
+ * the spec, so every emitter applies it the same way. A value is looked up as JSON writes it,
47
+ * so a boolean matches `true` or `false` and a number its digits. A key that isn't an
48
+ * identifier is written in backticks.
49
+ *
50
+ * A value `cases` doesn't list is written as `default`: a fixed value, or a field. Naming the
51
+ * field this property is filled from passes the value through unchanged, to change only some
52
+ * values. Without a default, an unlisted value is an error. A property takes
53
+ * `@Mapping.match` or `@Mapping.transform`, not both.
54
+ *
55
+ * ```typespec
56
+ * @Mapping.from(xml, Form.reviewStatus)
57
+ * @Mapping.match(#{ `b. … the state …`: "b. … the State …" }, Form.reviewStatus)
58
+ * stateReview: string;
59
+ * ```
60
+ */
61
+ extern dec match(
62
+ target: ModelProperty,
63
+ cases: valueof Record<string | numeric | boolean>,
64
+ default?: ModelProperty | (valueof string | numeric | boolean)
65
+ );
66
+
67
+ /**
68
+ * Write this target property even when its value is empty, as an empty element: for one the
69
+ * target requires but the form may leave unanswered, such as a date filled in on submission.
70
+ * By default, an empty value is left out.
71
+ */
72
+ extern dec required(target: ModelProperty);
73
+
74
+ /**
75
+ * Write this target property only while the condition holds: the answer at `source`
76
+ * compared with `value` by `operator`. For an answer the form keeps while it no longer
77
+ * applies, such as an explanation for an option the applicant has since changed.
78
+ * Repeatable: every condition must hold. `source` is a field of the form, or one item of a
79
+ * list field with `Item`.
80
+ *
81
+ * ```typespec
82
+ * @Mapping.from(xml, Form.revisionExplanation)
83
+ * @Mapping.when(Form.applicationType, Operator.equals, "Revision")
84
+ * @Mapping.when(Form.revisionCodes, Operator.contains, "E")
85
+ * revisionOtherExplanation?: string;
86
+ * ```
87
+ */
88
+ extern dec when(
89
+ target: ModelProperty,
90
+ source: ModelProperty | Model,
91
+ operator: valueof Operator,
92
+ value?: valueof unknown
93
+ );
94
+
26
95
  /**
27
96
  * In mapping `mapping`, this model or property corresponds to `mappedTo`.
28
97
  *
@@ -63,9 +132,42 @@ extern dec path(
63
132
  * to the field its parent is filled from; a property with none is structure, and its own
64
133
  * properties are filled relative to its parent's field. Repeatable, so a target shared by
65
134
  * several forms names the field each one fills it from.
135
+ *
136
+ * To fill it from some of a list field's items, name the field with `Item` or `Slice`:
137
+ * `@Mapping.from(xml, Form.types, …)` reads the whole list, `Item<Form.types, 0>` its first
138
+ * item, and `Slice<Form.sites, 1>` the items after the first.
66
139
  */
67
140
  extern dec from(
68
141
  target: Model | ModelProperty,
69
142
  mapping: EnumMember,
70
143
  source: Model | ModelProperty
71
144
  );
145
+
146
+ /**
147
+ * One item of the list field `Source`, as the source of a `@Mapping.from`: for a target that
148
+ * numbers its elements (`ApplicantTypeCode1` to `3`) instead of repeating one. `Index` counts
149
+ * from 0, and a negative one counts back from the end: `-1` is the last item.
150
+ *
151
+ * ```typespec
152
+ * @Mapping.from(xml, Mapping.Item<Form.applicantTypes, 0>)
153
+ * applicantTypeCode1: string;
154
+ * ```
155
+ */
156
+ model Item<Source extends ModelProperty, Index extends valueof int32> {}
157
+
158
+ /**
159
+ * The items of the list field `Source` from `Start`, included, to `Stop`, excluded, or to the
160
+ * end without one, as the source of a `@Mapping.from`. A negative bound counts back from the
161
+ * end. The target is a list, filled with those items: e.g. the items after the first, when
162
+ * `Item<…, 0>` fills an element of its own.
163
+ *
164
+ * ```typespec
165
+ * @Mapping.from(xml, Mapping.Item<Form.sites, 0>) primarySite: Site;
166
+ * @Mapping.from(xml, Mapping.Slice<Form.sites, 1>) otherSites?: Site[];
167
+ * ```
168
+ */
169
+ model Slice<
170
+ Source extends ModelProperty,
171
+ Start extends valueof int32,
172
+ Stop extends valueof int32 | null = null
173
+ > {}
package/lib/meta.tsp CHANGED
@@ -12,7 +12,7 @@ namespace SimplerForms.Meta;
12
12
  * A question's portable identity. The `entity` field and the first segment of `id`
13
13
  * describe the same thing and must agree.
14
14
  */
15
- extern dec question(target: Model | Scalar, meta: valueof QuestionMeta);
15
+ extern dec question(target: Model | Scalar | Enum, meta: valueof QuestionMeta);
16
16
 
17
17
  /**
18
18
  * A form an applicant opens: the data it collects and submits. Publishes the model's JSON
@@ -40,13 +40,13 @@ extern dec entities(target: Namespace, entities: Enum);
40
40
  * own — a money-shaped string, a bounded count. A member's string value, when it has one, is
41
41
  * the tag emitted; otherwise its name is.
42
42
  */
43
- extern dec tag(target: Model | Scalar, ...tags: EnumMember[]);
43
+ extern dec tag(target: Model | Scalar | Enum, ...tags: EnumMember[]);
44
44
 
45
45
  /**
46
46
  * Why a block or field exists in a response. Deliberately separate from semantic
47
47
  * question identity, capture mechanism, UI behavior, and delivery targets.
48
48
  */
49
49
  extern dec role(
50
- target: Model | Scalar | ModelProperty,
50
+ target: Model | Scalar | Enum | ModelProperty,
51
51
  role: valueof ResponseRole
52
52
  );
package/lib/types.tsp CHANGED
@@ -75,6 +75,19 @@ model ValidationConstraints {
75
75
  pattern?: string;
76
76
  }
77
77
 
78
+ /**
79
+ * How a condition compares the answer at its source with its value. `exists` takes no value,
80
+ * and `in` takes a list: the answer is one of its entries. `contains` holds when the answer is
81
+ * a list with the value among its entries.
82
+ */
83
+ enum Operator {
84
+ equals,
85
+ notEquals,
86
+ in,
87
+ contains,
88
+ exists,
89
+ }
90
+
78
91
  enum Op {
79
92
  Sum,
80
93
  Subtract,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "simpler-forms",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "A TypeSpec library for specifying forms once and emitting portable form artifacts.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -30,20 +30,20 @@
30
30
  "node": ">=22"
31
31
  },
32
32
  "peerDependencies": {
33
- "@typespec/compiler": "^1.13.0",
34
- "@typespec/json-schema": "^1.13.0"
33
+ "@typespec/compiler": "^1.16.0",
34
+ "@typespec/json-schema": "^1.16.0"
35
35
  },
36
36
  "devDependencies": {
37
- "@typespec/compiler": "^1.13.0",
38
- "@typespec/json-schema": "^1.13.0",
39
- "@vitest/coverage-v8": "^4.1.11",
37
+ "@eslint/js": "^9.39.5",
38
+ "@typespec/compiler": "^1.18.0",
39
+ "@typespec/json-schema": "^1.18.0",
40
+ "@vitest/coverage-v8": "^4.1.12",
40
41
  "ajv": "^8.20.0",
41
42
  "eslint": "^9.39.5",
42
- "prettier": "^3.4.2",
43
- "typescript": "^5.6.0",
44
- "typescript-eslint": "^8.24.0",
45
- "vitest": "^4.1.11",
46
- "@eslint/js": "^9.20.0"
43
+ "prettier": "^3.10.1",
44
+ "typescript": "^5.9.3",
45
+ "typescript-eslint": "^8.72.2",
46
+ "vitest": "^4.1.12"
47
47
  },
48
48
  "scripts": {
49
49
  "build": "tsc -p .",
@@ -1,21 +1,39 @@
1
- import type {
2
- Enum,
3
- EnumMember,
4
- Model,
5
- ModelProperty,
6
- Namespace,
1
+ import {
2
+ getNamespaceFullName,
3
+ type Enum,
4
+ type EnumMember,
5
+ type Model,
6
+ type ModelProperty,
7
+ type Namespace,
7
8
  } from "@typespec/compiler";
8
- import { stateKeys } from "../lib.js";
9
+ import { reportDiagnostic, stateKeys } from "../lib.js";
9
10
  import type {
11
+ MappingCondition,
10
12
  MappingFromLink,
11
13
  MappingLink,
14
+ MappingMatch,
12
15
  MappingPathLink,
16
+ MappingSelection,
13
17
  } from "../model.js";
14
- import { type Ctx, push, set } from "./shared.js";
18
+ import { type Ctx, enumName, push, set } from "./shared.js";
15
19
 
16
20
  export const $targets = (ctx: Ctx, target: Namespace, targets: Enum) =>
17
21
  set(ctx, stateKeys.mappingTargets, target, targets);
18
22
 
23
+ export const $transforms = (ctx: Ctx, target: Namespace, transforms: Enum) =>
24
+ set(ctx, stateKeys.mappingTransformSets, target, transforms);
25
+
26
+ export const $transform = (
27
+ ctx: Ctx,
28
+ target: ModelProperty,
29
+ transform: EnumMember,
30
+ params?: Record<string, unknown>,
31
+ ) =>
32
+ set(ctx, stateKeys.mappingTransform, target, {
33
+ member: transform,
34
+ ...(params ? { params } : {}),
35
+ });
36
+
19
37
  /**
20
38
  * Accumulated rather than overwritten: one model or property carries a link per mapping.
21
39
  * Two links for the same mapping are reported by `$onValidate`, not here, so the check sees
@@ -45,6 +63,92 @@ export const $path = (
45
63
  mappedTo,
46
64
  } satisfies MappingPathLink);
47
65
 
66
+ export const $match = (
67
+ ctx: Ctx,
68
+ target: ModelProperty,
69
+ cases: Record<string, string | number | boolean>,
70
+ fallback?: ModelProperty | string | number | boolean,
71
+ ) =>
72
+ set(ctx, stateKeys.mappingMatch, target, {
73
+ cases: Object.fromEntries(
74
+ Object.entries(cases).map(([key, value]) => [key, literal(value)]),
75
+ ),
76
+ ...(fallback === undefined
77
+ ? {}
78
+ : {
79
+ default: isField(fallback)
80
+ ? { field: fallback }
81
+ : { value: literal(fallback) },
82
+ }),
83
+ } satisfies MappingMatch);
84
+
85
+ /** A `valueof numeric` arrives as TypeSpec's arbitrary-precision `Numeric`: as a JS number. */
86
+ const literal = (value: unknown) =>
87
+ typeof value === "object" && value !== null && "asNumber" in value
88
+ ? ((value as { asNumber(): number | null }).asNumber() ?? Number.NaN)
89
+ : (value as string | number | boolean);
90
+
91
+ export const $required = (ctx: Ctx, target: ModelProperty) =>
92
+ ctx.program.stateSet(stateKeys.mappingRequired).add(target);
93
+
94
+ export const $when = (
95
+ ctx: Ctx,
96
+ target: ModelProperty,
97
+ source: ModelProperty | Model,
98
+ operator: unknown,
99
+ value?: unknown,
100
+ ) => {
101
+ const name = enumName(operator) as MappingCondition["operator"];
102
+ const picked =
103
+ source.kind === "ModelProperty" ? { source } : selection(source);
104
+ if (!picked) {
105
+ reportDiagnostic(ctx.program, {
106
+ code: "mapping-when-source",
107
+ target: ctx.getArgumentTarget(0) ?? target,
108
+ format: { name: target.name },
109
+ });
110
+ return;
111
+ }
112
+ const given = value !== undefined;
113
+ const fail =
114
+ name === "exists"
115
+ ? given && "exists"
116
+ : name === "in"
117
+ ? !Array.isArray(value) && "in"
118
+ : !given && "default";
119
+ if (fail) {
120
+ reportDiagnostic(ctx.program, {
121
+ code: "mapping-when-value",
122
+ messageId: fail,
123
+ target: ctx.getArgumentTarget(given ? 2 : 1) ?? target,
124
+ format: { name: target.name, source: picked.source.name, operator: name },
125
+ });
126
+ return;
127
+ }
128
+ push(ctx, stateKeys.mappingWhen, target, {
129
+ ...picked,
130
+ operator: name,
131
+ ...(given ? { value: plainValue(value) } : {}),
132
+ } satisfies MappingCondition);
133
+ };
134
+
135
+ /** A condition's value as plain JSON: lists entry by entry, numbers as JS numbers, enum members as their value. */
136
+ function plainValue(value: unknown): unknown {
137
+ if (Array.isArray(value)) return value.map(plainValue);
138
+ if (typeof value === "object" && value !== null) {
139
+ const v = value as { kind?: string; value?: unknown; name?: string };
140
+ if (v.kind === "EnumMember") return v.value ?? v.name;
141
+ if ("asNumber" in value) return literal(value);
142
+ }
143
+ return value;
144
+ }
145
+
146
+ const isField = (value: unknown): value is ModelProperty =>
147
+ typeof value === "object" &&
148
+ value !== null &&
149
+ (value as ModelProperty).kind === "ModelProperty";
150
+
151
+ /** A source named with `Mapping.Item` or `Mapping.Slice` is stored as its field and selection. */
48
152
  export const $from = (
49
153
  ctx: Ctx,
50
154
  target: Model | ModelProperty,
@@ -53,5 +157,44 @@ export const $from = (
53
157
  ) =>
54
158
  push(ctx, stateKeys.mappedFrom, target, {
55
159
  mapping,
56
- source,
160
+ ...(selection(source) ?? { source }),
57
161
  } satisfies MappingFromLink);
162
+
163
+ /** The field and selection `Mapping.Item<…>` or `Mapping.Slice<…>` names, or undefined for any other source. */
164
+ function selection(
165
+ source: Model | ModelProperty,
166
+ ): { source: ModelProperty; select: MappingSelection } | undefined {
167
+ if (source.kind !== "Model" || !source.templateMapper || !source.namespace)
168
+ return undefined;
169
+ if (getNamespaceFullName(source.namespace) !== "SimplerForms.Mapping")
170
+ return undefined;
171
+ const [field, ...bounds] = source.templateMapper.args;
172
+ if (field?.entityKind !== "Type" || field.kind !== "ModelProperty")
173
+ return undefined;
174
+ const [first, second] = bounds.map(numberOf);
175
+ if (source.name === "Item" && first !== undefined)
176
+ return { source: field, select: { index: first } };
177
+ if (source.name === "Slice" && first !== undefined)
178
+ return {
179
+ source: field,
180
+ select:
181
+ second === undefined
182
+ ? { start: first }
183
+ : { start: first, stop: second },
184
+ };
185
+ return undefined;
186
+ }
187
+
188
+ /** The number a template's `valueof int32` argument holds, or undefined (as for `null`). */
189
+ function numberOf(arg: unknown): number | undefined {
190
+ const entity = arg as {
191
+ entityKind?: string;
192
+ valueKind?: string;
193
+ value?: { asNumber(): number | null };
194
+ type?: { kind: string; value?: number };
195
+ };
196
+ if (entity.entityKind === "Value" && entity.valueKind === "NumericValue")
197
+ return entity.value?.asNumber() ?? undefined;
198
+ if (entity.type?.kind === "Number") return entity.type.value;
199
+ return undefined;
200
+ }
@@ -21,7 +21,11 @@ const memberName = (member: EnumMember) =>
21
21
  * The entity is recorded as its name now and as the member itself for `$onValidate`, which
22
22
  * checks it against the declared sets once every `@Meta.entities` has run.
23
23
  */
24
- export const $question = (ctx: Ctx, target: Model | Scalar, meta: unknown) => {
24
+ export const $question = (
25
+ ctx: Ctx,
26
+ target: Model | Scalar | Enum,
27
+ meta: unknown,
28
+ ) => {
25
29
  const m = plain(ctx, meta) as {
26
30
  id: string;
27
31
  entity?: unknown;
@@ -72,7 +76,7 @@ export const $form = (ctx: Ctx, target: Model, meta: unknown) => {
72
76
  */
73
77
  export const $tag = (
74
78
  ctx: Ctx,
75
- target: Model | Scalar,
79
+ target: Model | Scalar | Enum,
76
80
  ...tags: EnumMember[]
77
81
  ) => {
78
82
  set(ctx, stateKeys.tags, target, tags.map(memberName));
@@ -86,6 +90,6 @@ export const $tag = (
86
90
  */
87
91
  export const $role = (
88
92
  ctx: Ctx,
89
- target: Model | Scalar | ModelProperty,
93
+ target: Model | Scalar | Enum | ModelProperty,
90
94
  role: unknown,
91
95
  ) => set(ctx, stateKeys.responseRole, target, enumName(role));
@@ -1,5 +1,6 @@
1
1
  import type {
2
2
  DecoratorContext,
3
+ Enum,
3
4
  Model,
4
5
  ModelProperty,
5
6
  Scalar,
@@ -74,7 +75,11 @@ export const blockSchemaRef = (id: string) => `${id}/schema.json`;
74
75
  * Delegate to the stock JSON Schema library, which resolves this relative id
75
76
  * against the namespace base and uses it for both `$id` and every `$ref` target.
76
77
  */
77
- export function publishAs(ctx: Ctx, target: Model | Scalar, id: string): void {
78
+ export function publishAs(
79
+ ctx: Ctx,
80
+ target: Model | Scalar | Enum,
81
+ id: string,
82
+ ): void {
78
83
  $jsonSchemaId(ctx as any, target as any, blockSchemaRef(id));
79
84
  }
80
85
 
package/src/emitter.ts CHANGED
@@ -14,7 +14,11 @@ import { allBlocks, type Block } from "./model.js";
14
14
  import { type PublishedForm, resolveForms } from "./forms.js";
15
15
  import { reportDiagnostic } from "./lib.js";
16
16
  import { blockSchemaRef } from "./decorators/index.js";
17
- import { emitModelOverlay, emitSchemaOverlay } from "./emitters/overlay.js";
17
+ import {
18
+ emitModelOverlay,
19
+ emitSchemaOverlay,
20
+ type OwnsDefinition,
21
+ } from "./emitters/overlay.js";
18
22
  import { emitBlockUi } from "./emitters/block-ui.js";
19
23
  import { emitLayoutUi } from "./emitters/layout-ui.js";
20
24
  import { resolveLayout } from "./layout.js";
@@ -90,6 +94,10 @@ export async function $onEmit(
90
94
  const blocks = allBlocks(program);
91
95
  const { forms } = resolveForms(program);
92
96
  const modelsByName = indexModels(program.getGlobalNamespaceType());
97
+ // A local model with a staged schema of its own is inlined into `$defs` with its overlay
98
+ // (see `resolveRefs`), so the overlays of models that use it don't repeat it.
99
+ const ownsDefinition = (model: Model) =>
100
+ modelsByName.get(model.name) === model && byFile.has(`${model.name}.json`);
93
101
  const refToDir = new Map(
94
102
  blocks.map((b) => [
95
103
  blockSchemaRef(b.id),
@@ -126,11 +134,12 @@ export async function $onEmit(
126
134
  from: dir,
127
135
  program,
128
136
  modelsByName,
137
+ ownsDefinition,
129
138
  });
130
139
  if (Object.keys(defs).length) schema = { ...schema, $defs: defs };
131
140
 
132
141
  // 4. Fold in the conditional requiredness only we can know about.
133
- const overlay = emitSchemaOverlay(program, block);
142
+ const overlay = emitSchemaOverlay(program, block, ownsDefinition);
134
143
  if (overlay) schema = mergeSchema(schema, overlay);
135
144
 
136
145
  const index = emitBlockIndex(program, block);
@@ -202,6 +211,7 @@ interface RefCtx {
202
211
  from: string;
203
212
  program: EmitContext<FormSpecOptions>["program"];
204
213
  modelsByName: Map<string, Model>;
214
+ ownsDefinition: OwnsDefinition;
205
215
  }
206
216
 
207
217
  /** Rewrite every `$ref`: published blocks keep their identity, others become `$defs`. */
@@ -231,7 +241,11 @@ function resolveRefs(node: any, ctx: RefCtx, seen = new Set<string>()): any {
231
241
  seen.add(name);
232
242
  const { $schema, $id, ...body } = target;
233
243
  const overlay = ctx.modelsByName.has(name)
234
- ? emitModelOverlay(ctx.program, ctx.modelsByName.get(name)!)
244
+ ? emitModelOverlay(
245
+ ctx.program,
246
+ ctx.modelsByName.get(name)!,
247
+ ctx.ownsDefinition,
248
+ )
235
249
  : undefined;
236
250
  ctx.defs[name] = resolveRefs(
237
251
  overlay ? mergeSchema(body, overlay) : body,
@@ -18,6 +18,12 @@ import {
18
18
  readBlock,
19
19
  } from "../model.js";
20
20
 
21
+ /**
22
+ * Whether a model's schema has a definition of its own in `$defs`, written with its own
23
+ * overlay, so what it requires shouldn't be repeated beside each `$ref` to it.
24
+ */
25
+ export type OwnsDefinition = (model: Model) => boolean;
26
+
21
27
  /**
22
28
  * The parts of a block's JSON Schema that `@typespec/json-schema` cannot produce: what the
23
29
  * `@Validation.*` decorators require, and the help text, read-only status and choice
@@ -29,6 +35,7 @@ import {
29
35
  export function emitSchemaOverlay(
30
36
  program: Program,
31
37
  block: Block,
38
+ ownsDefinition: OwnsDefinition = () => false,
32
39
  ): Record<string, unknown> | undefined {
33
40
  if (block.model.kind !== "Model") return undefined;
34
41
  const model = block.model;
@@ -39,9 +46,13 @@ export function emitSchemaOverlay(
39
46
  const readOnly = readOnlyAnnotations(program, model);
40
47
  const helpText = helpTextAnnotations(program, model);
41
48
  const constraints = constraintAnnotations(program, model);
42
- const cardinality = cardinalityAnnotations(program, model);
49
+ const cardinality = cardinalityAnnotations(program, model, ownsDefinition);
43
50
  const encodedCheckboxes = encodedCheckboxAnnotations(program, model);
44
- const exclusiveValues = exclusiveValueAnnotations(program, model);
51
+ const exclusiveValues = exclusiveValueAnnotations(
52
+ program,
53
+ model,
54
+ ownsDefinition,
55
+ );
45
56
  const alternatives = atLeastOneAnnotations(program, model);
46
57
  const parts = [
47
58
  conditionals,
@@ -61,15 +72,16 @@ export function emitSchemaOverlay(
61
72
  export function emitModelOverlay(
62
73
  program: Program,
63
74
  model: Model,
75
+ ownsDefinition: OwnsDefinition = () => false,
64
76
  ): Record<string, unknown> | undefined {
65
77
  const parts = [
66
78
  conditionalValidation(program, [...model.properties.values()]),
67
79
  readOnlyAnnotations(program, model),
68
80
  helpTextAnnotations(program, model),
69
81
  constraintAnnotations(program, model),
70
- cardinalityAnnotations(program, model),
82
+ cardinalityAnnotations(program, model, ownsDefinition),
71
83
  encodedCheckboxAnnotations(program, model),
72
- exclusiveValueAnnotations(program, model),
84
+ exclusiveValueAnnotations(program, model, ownsDefinition),
73
85
  atLeastOneAnnotations(program, model),
74
86
  ].filter(Boolean) as Record<string, unknown>[];
75
87
  return parts.length ? parts.reduce(merge, {}) : undefined;
@@ -83,6 +95,7 @@ export function emitModelOverlay(
83
95
  function exclusiveValueAnnotations(
84
96
  program: Program,
85
97
  model: Model,
98
+ ownsDefinition: OwnsDefinition,
86
99
  seen = new Set<Model>(),
87
100
  ): Record<string, unknown> | undefined {
88
101
  if (seen.has(model)) return undefined;
@@ -101,13 +114,18 @@ function exclusiveValueAnnotations(
101
114
  };
102
115
  }
103
116
  const child = childModel(property.type);
104
- // Published questions own intrinsic exclusivity in their own schema. Do not repeat the
105
- // same constraint beside each form occurrence's $ref; only local unpublished capture
106
- // models need recursive projection.
107
- if (child && !readBlock(program, child.model)) {
117
+ // Published questions, and local models with a `$defs` definition of their own, carry
118
+ // their exclusivity in that schema. Don't repeat it beside each `$ref`; only a model
119
+ // inlined where it's used needs it projected.
120
+ if (
121
+ child &&
122
+ !readBlock(program, child.model) &&
123
+ !ownsDefinition(child.model)
124
+ ) {
108
125
  const nested = exclusiveValueAnnotations(
109
126
  program,
110
127
  child.model,
128
+ ownsDefinition,
111
129
  new Set(seen),
112
130
  );
113
131
  if (nested)
@@ -142,6 +160,7 @@ function atLeastOneAnnotations(
142
160
  function cardinalityAnnotations(
143
161
  program: Program,
144
162
  model: Model,
163
+ ownsDefinition: OwnsDefinition,
145
164
  seen = new Set<Model>(),
146
165
  ): Record<string, unknown> | undefined {
147
166
  if (seen.has(model)) return undefined;
@@ -189,14 +208,22 @@ function cardinalityAnnotations(
189
208
  ),
190
209
  );
191
210
  const child = childModel(property.type);
192
- // A published question owns its intrinsic cardinality in its own schema. Crossing
193
- // that reference boundary would copy the same constraints beside every occurrence
194
- // `$ref`, causing validators to report each missing path twice. Local unpublished
195
- // models still need recursive projection because they have no standalone artifact.
196
- if (child && !readBlock(program, child.model)) {
211
+ // The paths of a list's own decorators name fields of its items, so its patch
212
+ // constrains each item, as its nested patch below does.
213
+ if (child?.repeated && Object.keys(patch).length) patch = { items: patch };
214
+ // A published question, or a local model with a `$defs` definition of its own, owns its
215
+ // cardinality in that schema. Crossing that reference boundary would copy the same
216
+ // constraints beside every `$ref`, causing validators to report each missing path
217
+ // twice. Only a model inlined where it's used needs them projected.
218
+ if (
219
+ child &&
220
+ !readBlock(program, child.model) &&
221
+ !ownsDefinition(child.model)
222
+ ) {
197
223
  const nested = cardinalityAnnotations(
198
224
  program,
199
225
  child.model,
226
+ ownsDefinition,
200
227
  new Set(seen),
201
228
  );
202
229
  if (nested)
package/src/index.ts CHANGED
@@ -63,6 +63,11 @@ export const $decorators = {
63
63
  },
64
64
  "SimplerForms.Mapping": {
65
65
  targets: d.$targets,
66
+ transforms: d.$transforms,
67
+ transform: d.$transform,
68
+ match: d.$match,
69
+ required: d.$required,
70
+ when: d.$when,
66
71
  to: d.$to,
67
72
  path: d.$path,
68
73
  from: d.$from,