simpler-forms 0.1.0-alpha.1 → 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 (89) hide show
  1. package/README.md +300 -76
  2. package/dist/src/casing.d.ts +43 -0
  3. package/dist/src/casing.js +146 -0
  4. package/dist/src/casing.js.map +1 -0
  5. package/dist/src/decorators/index.d.ts +1 -0
  6. package/dist/src/decorators/index.js +1 -0
  7. package/dist/src/decorators/index.js.map +1 -1
  8. package/dist/src/decorators/mapping.d.ts +17 -0
  9. package/dist/src/decorators/mapping.js +122 -0
  10. package/dist/src/decorators/mapping.js.map +1 -0
  11. package/dist/src/decorators/meta.d.ts +15 -5
  12. package/dist/src/decorators/meta.js +31 -4
  13. package/dist/src/decorators/meta.js.map +1 -1
  14. package/dist/src/decorators/shared.d.ts +2 -2
  15. package/dist/src/decorators/shared.js.map +1 -1
  16. package/dist/src/decorators/ui.d.ts +14 -12
  17. package/dist/src/decorators/ui.js +20 -43
  18. package/dist/src/decorators/ui.js.map +1 -1
  19. package/dist/src/emitter.d.ts +8 -0
  20. package/dist/src/emitter.js +55 -16
  21. package/dist/src/emitter.js.map +1 -1
  22. package/dist/src/emitters/block-ui.d.ts +14 -3
  23. package/dist/src/emitters/block-ui.js +81 -119
  24. package/dist/src/emitters/block-ui.js.map +1 -1
  25. package/dist/src/emitters/layout-ui.d.ts +12 -0
  26. package/dist/src/emitters/layout-ui.js +225 -0
  27. package/dist/src/emitters/layout-ui.js.map +1 -0
  28. package/dist/src/emitters/overlay.d.ts +10 -8
  29. package/dist/src/emitters/overlay.js +30 -105
  30. package/dist/src/emitters/overlay.js.map +1 -1
  31. package/dist/src/forms.d.ts +23 -0
  32. package/dist/src/forms.js +54 -0
  33. package/dist/src/forms.js.map +1 -0
  34. package/dist/src/index.d.ts +22 -8
  35. package/dist/src/index.js +17 -3
  36. package/dist/src/index.js.map +1 -1
  37. package/dist/src/layout.d.ts +50 -0
  38. package/dist/src/layout.js +397 -0
  39. package/dist/src/layout.js.map +1 -0
  40. package/dist/src/lib.d.ts +585 -39
  41. package/dist/src/lib.js +258 -15
  42. package/dist/src/lib.js.map +1 -1
  43. package/dist/src/linter.js +8 -43
  44. package/dist/src/linter.js.map +1 -1
  45. package/dist/src/mapping-from.d.ts +21 -0
  46. package/dist/src/mapping-from.js +169 -0
  47. package/dist/src/mapping-from.js.map +1 -0
  48. package/dist/src/mapping.d.ts +65 -0
  49. package/dist/src/mapping.js +209 -0
  50. package/dist/src/mapping.js.map +1 -0
  51. package/dist/src/model.d.ts +143 -23
  52. package/dist/src/model.js +108 -21
  53. package/dist/src/model.js.map +1 -1
  54. package/dist/src/public.d.ts +20 -4
  55. package/dist/src/public.js +28 -4
  56. package/dist/src/public.js.map +1 -1
  57. package/dist/src/validate.d.ts +2 -1
  58. package/dist/src/validate.js +208 -58
  59. package/dist/src/validate.js.map +1 -1
  60. package/lib/main.tsp +1 -0
  61. package/lib/mapping.tsp +173 -0
  62. package/lib/meta.tsp +25 -6
  63. package/lib/types.tsp +24 -63
  64. package/lib/ui.tsp +34 -17
  65. package/package.json +17 -11
  66. package/src/casing.ts +172 -0
  67. package/src/decorators/index.ts +1 -0
  68. package/src/decorators/mapping.ts +200 -0
  69. package/src/decorators/meta.ts +56 -13
  70. package/src/decorators/shared.ts +6 -1
  71. package/src/decorators/ui.ts +43 -59
  72. package/src/emitter.ts +76 -16
  73. package/src/emitters/block-ui.ts +83 -135
  74. package/src/emitters/layout-ui.ts +280 -0
  75. package/src/emitters/overlay.ts +43 -116
  76. package/src/forms.ts +82 -0
  77. package/src/index.ts +17 -3
  78. package/src/layout.ts +592 -0
  79. package/src/lib.ts +264 -15
  80. package/src/linter.ts +17 -49
  81. package/src/mapping-from.ts +216 -0
  82. package/src/mapping.ts +358 -0
  83. package/src/model.ts +287 -46
  84. package/src/public.ts +60 -6
  85. package/src/validate.ts +221 -60
  86. package/dist/src/emitters/override-condition.d.ts +0 -12
  87. package/dist/src/emitters/override-condition.js +0 -25
  88. package/dist/src/emitters/override-condition.js.map +0 -1
  89. package/src/emitters/override-condition.ts +0 -37
package/README.md CHANGED
@@ -1,110 +1,334 @@
1
1
  # simpler-forms
2
2
 
3
- A [TypeSpec](https://typespec.io) library for specifying grant application forms once and
4
- emitting portable form artifacts — a JSON Schema for the data, a UI schema for the layout,
5
- and an index describing how the two relate.
3
+ A [TypeSpec](https://typespec.io) library for specifying forms once and emitting portable form
4
+ artifacts: a JSON Schema for the data, a UI schema for the layout, and an index describing how
5
+ the two relate.
6
6
 
7
- The library holds no form content and no vocabulary specific to any consuming application.
8
- Form definitions, a shared question bank, and target-specific emitters live in the
9
- repositories that consume this package.
7
+ The library holds no form content and no vocabulary of its own. Your program supplies the
8
+ questions, the forms, and the widgets, tags and mapping targets they use.
10
9
 
11
- ## Status
10
+ ## Install
11
+
12
+ ```bash
13
+ pnpm add -D simpler-forms @typespec/compiler @typespec/json-schema
14
+ ```
12
15
 
13
- Pre-release, published from `main` as `simpler-forms`, unscoped.
16
+ `@typespec/compiler` and `@typespec/json-schema` are peer dependencies, so you control the
17
+ compiler version.
14
18
 
15
- Versions stay below 1.0 for now. release-please is configured with `bump-minor-pre-major`,
16
- so a breaking change moves the minor — 0.1.0 to 0.2.0 — instead of jumping to 1.0.0. Read any
17
- minor bump as potentially breaking until this section says otherwise.
19
+ ## Quick start
18
20
 
19
- The library name is passed to `createTypeSpecLibrary` as both `name` and `alias`, and it is
20
- the alias that prefixes every diagnostic code and lint rule id. So a suppression in a form
21
- specification reads:
21
+ `tspconfig.yaml`:
22
+
23
+ ```yaml
24
+ emit:
25
+ - simpler-forms
26
+ options:
27
+ simpler-forms:
28
+ property-casing: snake
29
+ linter:
30
+ extends:
31
+ - simpler-forms/recommended
32
+ ```
33
+
34
+ `main.tsp`:
22
35
 
23
36
  ```tsp
24
- #suppress "simpler-forms/no-orphan-question"
37
+ import "@typespec/json-schema";
38
+ import "simpler-forms";
39
+
40
+ using SimplerForms;
41
+
42
+ @Meta.tags(Tag)
43
+ @Meta.entities(Entity)
44
+ namespace Catalogue {
45
+ enum Tag { name, contact }
46
+ enum Entity { poc }
47
+ }
48
+
49
+ @UI.widgets(Widget)
50
+ namespace Rendering {
51
+ enum Widget { Text, TextArea }
52
+ }
53
+
54
+ @JsonSchema.jsonSchema
55
+ namespace Questions {
56
+ /** The name of the person to contact. */
57
+ @Meta.question(#{ id: "poc/name", entity: Catalogue.Entity.poc })
58
+ @Meta.tag(Catalogue.Tag.name, Catalogue.Tag.contact)
59
+ model PersonName {
60
+ @UI.label("First Name") firstName: string;
61
+ @UI.label("Last Name") lastName: string;
62
+ }
63
+ }
64
+
65
+ @JsonSchema.jsonSchema
66
+ namespace Forms {
67
+ /** Who to contact about this application. */
68
+ @Meta.form(#{ id: "point-of-contact", formName: "POINT OF CONTACT" })
69
+ model PointOfContact {
70
+ @UI.label("Contact Name")
71
+ name: Questions.PersonName;
72
+
73
+ @UI.label("Notes")
74
+ @UI.widget(Rendering.Widget.TextArea)
75
+ notes?: string;
76
+ }
77
+ }
25
78
  ```
26
79
 
27
- Because that prefix comes from the alias and not from the package name, moving the package
28
- into an npm scope later — `@agilesix/simpler-forms`, say — leaves every suppression already
29
- written in a specification working. What such a move does change is the import specifier in a
30
- consumer's specs and its dependency entry, one line each.
80
+ `tsp compile main.tsp` writes:
31
81
 
32
- ## Install
82
+ ```
83
+ tsp-output/simpler-forms/
84
+ question-bank/poc/name/ schema.json ui.json index.json
85
+ forms/point-of-contact/ schema.json ui.json index.json manifest.json
86
+ ```
33
87
 
34
- ```bash
35
- pnpm add -D simpler-forms @typespec/compiler @typespec/json-schema
88
+ | Artifact | What it holds |
89
+ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
90
+ | `schema.json` | The JSON Schema for the data, with its validation |
91
+ | `ui.json` | A [JSON Forms](https://jsonforms.io) UI schema laying the data out |
92
+ | `index.json` | A catalogue entry: name, description and tags; for a question, its entity and what it composes; for a form, where each field occurs |
93
+ | `manifest.json` | The form's identity and the artifacts in its package |
94
+
95
+ Where the artifacts go from there is up to you: the emitter writes the same layout to
96
+ `emitter-output-dir` regardless of where your application installs them.
97
+
98
+ ## Questions
99
+
100
+ A question is a reusable block of a form, given a stable id with `@Meta.question`. It is
101
+ published under `question-bank/<id>/`, and a form that composes it refers to its schema.
102
+
103
+ - `entity` names what the question is asked about, and is the first segment of its id.
104
+ - `@Meta.tag` files it under headings in a question catalogue.
105
+ - Its doc comment is its description; `@UI.label` and `@UI.helpText` are how it reads in a form.
106
+ - A property whose type is a question takes the question's label unless it sets its own.
107
+
108
+ A question can be an object (a model), a single value (a scalar) or a code list (an enum). A
109
+ code list published as a question, such as a list of states, is written once, and the
110
+ questions that use it refer to it. An enum without `@Meta.question` is copied into each
111
+ schema that uses it, as before.
112
+
113
+ ## Forms
114
+
115
+ `@Meta.form` goes on the model holding the data an applicant submits, and publishes it under
116
+ `forms/<id>/`. Its fields' `@UI.*` decorators lay it out, and each object field becomes a
117
+ labeled group.
118
+
119
+ Validation lives on the form and its questions, in the `@Validation.*` decorators:
120
+ conditional requiredness (`@Validation.requiredPaths`, `@Validation.requiredWhen`), constraints
121
+ that apply under a condition, calculated values and more. See `lib/validation.tsp` for the
122
+ full set.
123
+
124
+ A platform's own identity for a form, such as the name and version a submission system knows it
125
+ by, belongs in that platform's TypeSpec library, as a decorator of its own on the same model.
126
+
127
+ ## Layouts
128
+
129
+ A `@UI.layout` model presents a form differently from how its data is shaped, and is published
130
+ as the form's `ui.json`. It points at the form's fields with typed references, so a misspelled
131
+ field is a compiler error.
132
+
133
+ ```tsp
134
+ @UI.layout(PointOfContact)
135
+ model PointOfContactLayout {
136
+ /** Enter the contact's name. */
137
+ @UI.label("Contact")
138
+ contact: {
139
+ name: PointOfContact.name;
140
+ };
141
+
142
+ @UI.label("Other")
143
+ other: {
144
+ notes: PointOfContact.notes;
145
+ };
146
+ }
36
147
  ```
37
148
 
38
- `@typespec/compiler` and `@typespec/json-schema` are peer dependencies, so a consumer
39
- controls its own compiler version.
149
+ - Its top-level properties are sections, in order, and a doc comment is a section's description.
150
+ - A field reference places that field as its own model lays it out.
151
+ - An entry typed as a model with `@UI.field(ref)` lays out that field's contents, listing only
152
+ what changes and keeping the rest in their declared order. References inside it are relative
153
+ to the field, so one entry model can serve several fields.
154
+ - An entry can set a label, help text, a widget, `@UI.omit`, `@UI.flatten` (place a field's
155
+ children without their group) and one display condition.
156
+ - Validation stays on the form, so a `@Validation.*` decorator on a layout entry is an error.
40
157
 
41
- ## Develop
158
+ A form has at most one layout.
42
159
 
43
- ```bash
44
- pnpm install
45
- pnpm build # required before anything else — see below
46
- pnpm test
47
- pnpm checks # format, lint, types, tests
160
+ ## Your program's vocabulary
161
+
162
+ Which widgets your renderers provide, which tags and entities your question bank uses, and
163
+ which representations your forms map to are yours to declare. Declare each set once, on a
164
+ namespace, and the decorators that use them take its members:
165
+
166
+ | Declare | Used by |
167
+ | ------------------------ | ------------------------------ |
168
+ | `@UI.widgets(Enum)` | `@UI.widget` |
169
+ | `@Meta.tags(Enum)` | `@Meta.tag` |
170
+ | `@Meta.entities(Enum)` | `@Meta.question`'s `entity` |
171
+ | `@Mapping.targets(Enum)` | `@Mapping.to`, `@Mapping.from` |
172
+
173
+ A member of an enum no namespace declares is an error. Where a member is emitted, its string
174
+ value is used when it has one, and its name otherwise.
175
+
176
+ ## Mappings
177
+
178
+ A response often has to be written in another shape too, such as an XML document or a CSV row.
179
+ A mapping links a form to a TypeSpec model of that shape, the mapping target. Wire details
180
+ such as element names and namespaces stay on the target, in whatever vocabulary its
181
+ representation uses.
182
+
183
+ Declare the links on the target with `@Mapping.from`. The target's root names the form, and
184
+ each property names the field it is filled from, relative to its parent's field. A target type
185
+ shared by many forms is annotated once, against the questions that fill it:
186
+
187
+ ```tsp
188
+ @Mapping.targets(Target)
189
+ namespace Mappings {
190
+ enum Target { xml }
191
+ }
192
+
193
+ model Name {
194
+ @Mapping.from(Mappings.Target.xml, Questions.PersonName.firstName) first: string;
195
+ @Mapping.from(Mappings.Target.xml, Questions.PersonName.lastName) last: string;
196
+ }
197
+
198
+ @Mapping.from(Mappings.Target.xml, Forms.PointOfContact)
199
+ model Root {
200
+ @Mapping.from(Mappings.Target.xml, Forms.PointOfContact.name) contactName: Name;
201
+ @Mapping.from(Mappings.Target.xml, Forms.PointOfContact.notes) notes?: string;
202
+ }
48
203
  ```
49
204
 
50
- **Build before you type-check.** Each `lib/*.tsp` file imports `dist/src/index.js` to resolve
51
- the `extern dec` declarations it makes, so the TypeSpec sources do not type-check until the
52
- compiled JavaScript exists. This is why CI runs `pnpm build` ahead of `pnpm checks`, and why
53
- a fresh clone reports unimplemented decorators until the first build.
205
+ A target can be filled from some of a list field's items. Name the field with `Mapping.Item`
206
+ for one item, counting from 0 (`-1` is the last), or `Mapping.Slice` for a range, its end
207
+ excluded. That fits a target that numbers its elements instead of repeating one:
54
208
 
55
- ## Release
209
+ ```tsp
210
+ model Root {
211
+ @Mapping.from(Mappings.Target.xml, Mapping.Item<Forms.Application.types, 0>) typeCode1: string;
212
+ @Mapping.from(Mappings.Target.xml, Mapping.Item<Forms.Application.types, 1>) typeCode2?: string;
213
+ @Mapping.from(Mappings.Target.xml, Mapping.Item<Forms.Application.sites, 0>) primarySite: Site;
214
+ @Mapping.from(Mappings.Target.xml, Mapping.Slice<Forms.Application.sites, 1>) otherSites?: Site[];
215
+ }
216
+ ```
56
217
 
57
- `main` is released by [release-please](https://github.com/googleapis/release-please). Pushing a
58
- conventional commit opens or updates a release pull request; merging that pull request tags the
59
- release and publishes the tarball to npm.
218
+ ### Changing a value on its way through
60
219
 
61
- Publication authenticates through npm trusted publishing, so this repository holds no npm
62
- token. The workflow exchanges a GitHub OIDC token for a short-lived credential, and npm
63
- attaches a provenance attestation to the version it accepts. The trusted publisher is
64
- configured against `.github/workflows/release.yml` by path, so renaming or moving that file
65
- stops publication until the publisher is updated to match.
220
+ A target property can change the value it reads. `@Mapping.transform` names a transformation
221
+ the target emitter's runtime implements. The program declares the ones it uses in an enum, as
222
+ it does its mappings, with the name the runtime implements each under as its value:
66
223
 
67
- ## Layout
224
+ ```tsp
225
+ @Mapping.transforms(Transformation)
226
+ namespace Transforms {
227
+ enum Transformation { yesNo: "boolean_to_yes_no", truncate: "truncate_string" }
228
+ }
68
229
 
230
+ model Root {
231
+ @Mapping.from(Mappings.Target.xml, Forms.Application.title)
232
+ @Mapping.transform(Transforms.Transformation.truncate, #{ max_length: 60 })
233
+ title: string;
234
+ }
235
+ ```
236
+
237
+ A lookup can be spelled out instead, with `@Mapping.match`, so every emitter applies it the
238
+ same way. A value it doesn't list is written as the default: a fixed value, or a field.
239
+ Naming the field the property is filled from passes other values through unchanged:
240
+
241
+ ```tsp
242
+ model Root {
243
+ @Mapping.from(Mappings.Target.xml, Forms.Application.agrees)
244
+ @Mapping.match(#{ `true`: "Y: Yes", `false`: "N: No" })
245
+ agrees: string;
246
+
247
+ @Mapping.from(Mappings.Target.xml, Forms.Application.review)
248
+ @Mapping.match(#{ `b. … by the state`: "b. … by the State" }, Forms.Application.review)
249
+ stateReview: string;
250
+ }
251
+ ```
252
+
253
+ An empty value is left out of the target. `@Mapping.required` writes it anyway, as an empty
254
+ element, for one the target requires but the form may leave unanswered:
255
+
256
+ ```tsp
257
+ model Root {
258
+ @Mapping.from(Mappings.Target.xml, Forms.Application.dateReceived)
259
+ @Mapping.required
260
+ dateReceived: plainDate;
261
+ }
69
262
  ```
70
- lib/ TypeSpec declarations — the decorator vocabulary
71
- main.tsp the entry point a consumer imports
72
- meta.tsp @Meta.* — question, form, tag, role
73
- ui.tsp @UI.* — labels, sections, widgets, overrides
74
- validation.tsp @Validation.*
75
- types.tsp shared scalars and enums
76
- src/ the library implementation
77
- public.ts the API a target emitter reads — the only semver-governed surface
78
- decorators/ decorator entry points, one module per namespace
79
- model.ts typed accessors over decorator state
80
- validate.ts $onValidate — cross-cutting checks reported as diagnostics
81
- linter.ts lint rules
82
- emitter.ts $onEmit — writes the canonical artifacts
83
- emitters/ one module per emitted artifact
84
- lib.ts createTypeSpecLibrary — diagnostics, lint rules, emitter options
85
- test/ vitest suites, driven by the compiler's createTester
263
+
264
+ `@Mapping.when` writes a target property only while a condition holds, so an answer the
265
+ form keeps after it stops applying, such as an explanation for an option the applicant has
266
+ since changed, isn't written. It compares the answer at a field with a value, using an
267
+ `Operator`: `equals`, `notEquals`, `in` (a list of values), `contains` (for a list answer) or
268
+ `exists` (no value). Every condition on a property must hold:
269
+
270
+ ```tsp
271
+ model Root {
272
+ @Mapping.from(Mappings.Target.xml, Forms.Application.revisionExplanation)
273
+ @Mapping.when(Forms.Application.applicationType, Operator.equals, "Revision")
274
+ @Mapping.when(Forms.Application.revisionCodes, Operator.contains, "E")
275
+ revisionOtherExplanation?: string;
276
+ }
277
+ ```
278
+
279
+ The same links can be declared from the form's side with `@Mapping.to`, plus `@Mapping.path`
280
+ for nested paths. Every link is checked as it resolves, against the target's type and
281
+ cardinality.
282
+
283
+ simpler-forms emits no mapping artifact itself: an emitter for the target format reads the
284
+ links (see [Writing a target emitter](#writing-a-target-emitter)).
285
+
286
+ ## Options
287
+
288
+ Set under `options: simpler-forms:` in `tspconfig.yaml`.
289
+
290
+ | Option | Default | Effect |
291
+ | ----------------- | ---------- | ------------------------------------------------------------ |
292
+ | `base-uri` | none | Makes every `$id` and cross-block `$ref` absolute |
293
+ | `property-casing` | `preserve` | `snake` writes `firstName` as `first_name` in every artifact |
294
+
295
+ With `snake`, specifications are still written in TypeSpec names, including string paths such as
296
+ `@Validation.requiredPaths("contact.name.firstName")`. A run of capitals is one word
297
+ (`OMBNumber` becomes `omb_number`), and digits stay with the word before them (`street1` is
298
+ unchanged). For a name the rule converts badly, set `@encodedName("application/json", "...")`
299
+ on every property with that name.
300
+
301
+ ## Diagnostics
302
+
303
+ Checks run as you type in an editor with the TypeSpec extension, as well as on compile. Extend
304
+ `simpler-forms/recommended` in `tspconfig.yaml` for the lint rules, and suppress a diagnostic by
305
+ its code:
306
+
307
+ ```tsp
308
+ #suppress "simpler-forms/no-orphan-question" "Asked only by forms in another repository"
309
+ ```
310
+
311
+ ## Writing a target emitter
312
+
313
+ An emitter for another format, such as the XML a mapping target describes, is a TypeSpec
314
+ library of its own, listed beside this one in `tspconfig.yaml`. It reads forms, layouts and
315
+ mappings through the package's JavaScript API:
316
+
317
+ ```ts
318
+ import { resolveForms, resolveMappingFrom } from "simpler-forms";
86
319
  ```
87
320
 
88
- Only `src/public.ts` is public API. The decorator implementations, emitters and validators
89
- are internal, and a target emitter reaching past that module depends on something that can
90
- change in a patch.
321
+ That API, from `src/public.ts`, is the supported surface. Anything else in the package is
322
+ internal and can change in any release.
91
323
 
92
- ## Design notes
324
+ ## Versioning
93
325
 
94
- **Diagnostics are live in the editor.** `$onValidate` runs in the standard compile pipeline
95
- before the linter and is not gated by `noEmit`, and the language server routes through that
96
- same pipeline. A custom diagnostic therefore appears as a squiggle while an author types,
97
- not only in CI.
326
+ simpler-forms is below 1.0. A breaking change bumps the minor version (0.1.0 to 0.2.0), so
327
+ treat every minor release as potentially breaking. The changelog lists breaking changes first.
98
328
 
99
- **Where artifacts land is the consumer's decision.** The emitter writes to
100
- `emitter-output-dir` in a stable layout of its own. It deliberately knows nothing about any
101
- consuming application's directory conventions; installing artifacts into a particular tree is
102
- a separate step owned by the consumer, so that a downstream layout change is not a breaking
103
- change here.
329
+ ## Contributing
104
330
 
105
- **Target vocabulary belongs downstream.** A consuming application's own decorators, state,
106
- validation and emitted files are contributed by its own TypeSpec library listed alongside
107
- this one in `tspconfig.yaml`, rather than by a plugin interface here.
331
+ See [CONTRIBUTING.md](./CONTRIBUTING.md).
108
332
 
109
333
  ## License
110
334
 
@@ -0,0 +1,43 @@
1
+ import type { ModelProperty, Program } from "@typespec/compiler";
2
+ /** How a property's TypeSpec name becomes its name in every emitted artifact. */
3
+ export type PropertyCasing = "preserve" | "snake";
4
+ /**
5
+ * `firstName` to `first_name`.
6
+ *
7
+ * A word starts at each capital that follows a lowercase letter or a digit, and at the last
8
+ * capital of a run that a lowercase letter follows, so an acronym is one word: `ombNumber`
9
+ * and `OMBNumber` both become `omb_number`, and `HTTPServer` becomes `http_server`. Digits
10
+ * stay with the word before them, so `street1` and `sf424Version` become `street1` and
11
+ * `sf424_version`. A name that is already snake case is unchanged.
12
+ */
13
+ export declare function snakeCase(name: string): string;
14
+ /**
15
+ * The name a property is emitted under.
16
+ *
17
+ * `@encodedName("application/json", ...)` wins over the casing, so a name the rule
18
+ * converts badly can be stated outright.
19
+ */
20
+ export declare function jsonPropertyName(program: Program, property: ModelProperty, casing: PropertyCasing): string;
21
+ /**
22
+ * Renames properties in a finished artifact.
23
+ *
24
+ * The emitters build every artifact in TypeSpec names, which is also what an author writes in
25
+ * a string path, so the casing is applied once, after everything that resolves a path has run.
26
+ * One table maps each TypeSpec name to its emitted name across the whole program. That keeps
27
+ * renaming independent of where in an artifact a name appears, at the cost of requiring a name
28
+ * to be emitted the same way everywhere it is declared.
29
+ */
30
+ export declare class Casing {
31
+ private readonly casing;
32
+ private readonly names;
33
+ constructor(program: Program, casing: PropertyCasing);
34
+ /** The name a property named `key` in TypeSpec is emitted under. */
35
+ name(key: string): string;
36
+ /** A JSON Schema or JSON Forms layout. */
37
+ json<T>(node: T): T;
38
+ /** A JSON Pointer such as `/keyContacts/[]/name`. */
39
+ pointer(path: string): string;
40
+ /** Data shaped like the schema, such as an `@example` value. */
41
+ private instance;
42
+ private keys;
43
+ }
@@ -0,0 +1,146 @@
1
+ import { resolveEncodedName } from "@typespec/compiler";
2
+ import { reportDiagnostic } from "./lib.js";
3
+ import { modelProperties } from "./model.js";
4
+ /**
5
+ * `firstName` to `first_name`.
6
+ *
7
+ * A word starts at each capital that follows a lowercase letter or a digit, and at the last
8
+ * capital of a run that a lowercase letter follows, so an acronym is one word: `ombNumber`
9
+ * and `OMBNumber` both become `omb_number`, and `HTTPServer` becomes `http_server`. Digits
10
+ * stay with the word before them, so `street1` and `sf424Version` become `street1` and
11
+ * `sf424_version`. A name that is already snake case is unchanged.
12
+ */
13
+ export function snakeCase(name) {
14
+ return name
15
+ .replace(/([a-z\d])([A-Z])/g, "$1_$2")
16
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
17
+ .toLowerCase();
18
+ }
19
+ /**
20
+ * The name a property is emitted under.
21
+ *
22
+ * `@encodedName("application/json", ...)` wins over the casing, so a name the rule
23
+ * converts badly can be stated outright.
24
+ */
25
+ export function jsonPropertyName(program, property, casing) {
26
+ const encoded = resolveEncodedName(program, property, "application/json");
27
+ if (encoded !== property.name)
28
+ return encoded;
29
+ return casing === "snake" ? snakeCase(property.name) : property.name;
30
+ }
31
+ /**
32
+ * Renames properties in a finished artifact.
33
+ *
34
+ * The emitters build every artifact in TypeSpec names, which is also what an author writes in
35
+ * a string path, so the casing is applied once, after everything that resolves a path has run.
36
+ * One table maps each TypeSpec name to its emitted name across the whole program. That keeps
37
+ * renaming independent of where in an artifact a name appears, at the cost of requiring a name
38
+ * to be emitted the same way everywhere it is declared.
39
+ */
40
+ export class Casing {
41
+ casing;
42
+ names = new Map();
43
+ constructor(program, casing) {
44
+ this.casing = casing;
45
+ const declared = new Map();
46
+ const visit = (namespace) => {
47
+ for (const model of namespace.models.values()) {
48
+ const claimed = new Map();
49
+ for (const property of modelProperties(model)) {
50
+ const name = jsonPropertyName(program, property, casing);
51
+ const sibling = claimed.get(name);
52
+ if (sibling) {
53
+ reportDiagnostic(program, {
54
+ code: "property-casing-collision",
55
+ target: property,
56
+ format: {
57
+ model: model.name,
58
+ first: sibling.name,
59
+ second: property.name,
60
+ name,
61
+ },
62
+ });
63
+ }
64
+ else
65
+ claimed.set(name, property);
66
+ const elsewhere = declared.get(property.name);
67
+ const previous = this.names.get(property.name);
68
+ if (elsewhere && previous !== name) {
69
+ reportDiagnostic(program, {
70
+ code: "property-casing-inconsistent",
71
+ target: property,
72
+ format: {
73
+ property: property.name,
74
+ name,
75
+ other: `${elsewhere.model?.name}.${elsewhere.name}`,
76
+ otherName: previous,
77
+ },
78
+ });
79
+ }
80
+ else if (!elsewhere) {
81
+ declared.set(property.name, property);
82
+ this.names.set(property.name, name);
83
+ }
84
+ }
85
+ }
86
+ for (const child of namespace.namespaces.values())
87
+ visit(child);
88
+ };
89
+ visit(program.getGlobalNamespaceType());
90
+ // The stock emitter serializes an `@example` with encoded names already applied.
91
+ for (const name of [...this.names.values()])
92
+ this.names.set(name, name);
93
+ }
94
+ /** The name a property named `key` in TypeSpec is emitted under. */
95
+ name(key) {
96
+ return (this.names.get(key) ?? (this.casing === "snake" ? snakeCase(key) : key));
97
+ }
98
+ /** A JSON Schema or JSON Forms layout. */
99
+ json(node) {
100
+ if (Array.isArray(node))
101
+ return node.map((entry) => this.json(entry));
102
+ if (!isObject(node))
103
+ return node;
104
+ return Object.fromEntries(Object.entries(node).map(([key, value]) => {
105
+ if (key === "properties" && isObject(value))
106
+ return [key, this.keys(value, (entry) => this.json(entry))];
107
+ if (key === "required" && Array.isArray(value))
108
+ return [key, value.map((name) => this.name(name))];
109
+ if (key === "scope" && typeof value === "string")
110
+ return [
111
+ key,
112
+ value.replace(/(?<=properties\/)[^/]+/g, (name) => this.name(name)),
113
+ ];
114
+ if (key === "examples" || key === "default" || key === "const")
115
+ return [key, this.instance(value)];
116
+ return [key, this.json(value)];
117
+ }));
118
+ }
119
+ /** A JSON Pointer such as `/keyContacts/[]/name`. */
120
+ pointer(path) {
121
+ return path
122
+ .split("/")
123
+ .map((token, index) => index === 0 || token === "[]"
124
+ ? token
125
+ : escapePointer(this.name(unescapePointer(token))))
126
+ .join("/");
127
+ }
128
+ /** Data shaped like the schema, such as an `@example` value. */
129
+ instance(value) {
130
+ if (Array.isArray(value))
131
+ return value.map((entry) => this.instance(entry));
132
+ return isObject(value)
133
+ ? this.keys(value, (entry) => this.instance(entry))
134
+ : value;
135
+ }
136
+ keys(value, inner) {
137
+ return Object.fromEntries(Object.entries(value).map(([name, entry]) => [
138
+ this.name(name),
139
+ inner(entry),
140
+ ]));
141
+ }
142
+ }
143
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
144
+ const unescapePointer = (token) => token.replaceAll("~1", "/").replaceAll("~0", "~");
145
+ const escapePointer = (token) => token.replaceAll("~", "~0").replaceAll("/", "~1");
146
+ //# sourceMappingURL=casing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"casing.js","sourceRoot":"","sources":["../../src/casing.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAK7C;;;;;;;;GAQG;AACH,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,OAAO,IAAI;SACR,OAAO,CAAC,mBAAmB,EAAE,OAAO,CAAC;SACrC,OAAO,CAAC,uBAAuB,EAAE,OAAO,CAAC;SACzC,WAAW,EAAE,CAAC;AACnB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB,CAC9B,OAAgB,EAChB,QAAuB,EACvB,MAAsB;IAEtB,MAAM,OAAO,GAAG,kBAAkB,CAAC,OAAO,EAAE,QAAQ,EAAE,kBAAkB,CAAC,CAAC;IAC1E,IAAI,OAAO,KAAK,QAAQ,CAAC,IAAI;QAAE,OAAO,OAAO,CAAC;IAC9C,OAAO,MAAM,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC;AACvE,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,OAAO,MAAM;IAKE;IAJF,KAAK,GAAG,IAAI,GAAG,EAAkB,CAAC;IAEnD,YACE,OAAgB,EACC,MAAsB;QAAtB,WAAM,GAAN,MAAM,CAAgB;QAEvC,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAyB,CAAC;QAClD,MAAM,KAAK,GAAG,CAAC,SAAoB,EAAQ,EAAE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I,CAAC,CAAC"}
@@ -2,3 +2,4 @@ export { blockSchemaRef } from "./shared.js";
2
2
  export * from "./meta.js";
3
3
  export * from "./ui.js";
4
4
  export * from "./validation.js";
5
+ export * from "./mapping.js";
@@ -4,4 +4,5 @@ export { blockSchemaRef } from "./shared.js";
4
4
  export * from "./meta.js";
5
5
  export * from "./ui.js";
6
6
  export * from "./validation.js";
7
+ export * from "./mapping.js";
7
8
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/decorators/index.ts"],"names":[],"mappings":"AAAA,mFAAmF;AACnF,yDAAyD;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC;AACxB,cAAc,iBAAiB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/decorators/index.ts"],"names":[],"mappings":"AAAA,mFAAmF;AACnF,yDAAyD;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC;AACxB,cAAc,iBAAiB,CAAC;AAChC,cAAc,cAAc,CAAC"}
@@ -0,0 +1,17 @@
1
+ import { type Enum, type EnumMember, type Model, type ModelProperty, type Namespace } from "@typespec/compiler";
2
+ import { type Ctx } from "./shared.js";
3
+ export declare const $targets: (ctx: Ctx, target: Namespace, targets: Enum) => void;
4
+ export declare const $transforms: (ctx: Ctx, target: Namespace, transforms: Enum) => void;
5
+ export declare const $transform: (ctx: Ctx, target: ModelProperty, transform: EnumMember, params?: Record<string, unknown>) => void;
6
+ /**
7
+ * Accumulated rather than overwritten: one model or property carries a link per mapping.
8
+ * Two links for the same mapping are reported by `$onValidate`, not here, so the check sees
9
+ * every decorator before it decides which one is the duplicate.
10
+ */
11
+ export declare const $to: (ctx: Ctx, target: Model | ModelProperty, mapping: EnumMember, mappedTo: Model | ModelProperty) => void;
12
+ export declare const $path: (ctx: Ctx, target: Model, mapping: EnumMember, sourcePath: string, mappedTo: ModelProperty) => void;
13
+ export declare const $match: (ctx: Ctx, target: ModelProperty, cases: Record<string, string | number | boolean>, fallback?: ModelProperty | string | number | boolean) => void;
14
+ export declare const $required: (ctx: Ctx, target: ModelProperty) => Set<import("@typespec/compiler").Type>;
15
+ export declare const $when: (ctx: Ctx, target: ModelProperty, source: ModelProperty | Model, operator: unknown, value?: unknown) => void;
16
+ /** A source named with `Mapping.Item` or `Mapping.Slice` is stored as its field and selection. */
17
+ export declare const $from: (ctx: Ctx, target: Model | ModelProperty, mapping: EnumMember, source: Model | ModelProperty) => void;