micro-contracts 0.20.2 → 0.20.4

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 (84) hide show
  1. package/README.md +72 -27
  2. package/cli-contract.yaml +1 -31
  3. package/dist/cli/templates.d.ts.map +1 -1
  4. package/dist/cli/templates.js +124 -4
  5. package/dist/cli/templates.js.map +1 -1
  6. package/dist/cli.js +51 -114
  7. package/dist/cli.js.map +1 -1
  8. package/dist/commands/audit-guardrails.js +2 -2
  9. package/dist/commands/audit-guardrails.js.map +1 -1
  10. package/dist/commands/audit-openapi.js +2 -2
  11. package/dist/commands/audit-openapi.js.map +1 -1
  12. package/dist/commands/propose-overlays.js +2 -2
  13. package/dist/commands/propose-overlays.js.map +1 -1
  14. package/dist/commands/review-published.js +2 -2
  15. package/dist/commands/review-published.js.map +1 -1
  16. package/dist/generated/contract.d.ts.map +1 -1
  17. package/dist/generated/contract.js +2 -2
  18. package/dist/generated/contract.js.map +1 -1
  19. package/dist/generated/dsl/handoffs.d.ts +2 -2
  20. package/dist/generated/policy.d.ts +0 -24
  21. package/dist/generated/policy.d.ts.map +1 -1
  22. package/dist/generated/policy.js +0 -28
  23. package/dist/generated/policy.js.map +1 -1
  24. package/dist/generated/program.d.ts +0 -4
  25. package/dist/generated/program.d.ts.map +1 -1
  26. package/dist/generated/program.js +0 -6
  27. package/dist/generated/program.js.map +1 -1
  28. package/dist/generated/types.d.ts +0 -4
  29. package/dist/generated/types.d.ts.map +1 -1
  30. package/dist/generator/index.d.ts +0 -1
  31. package/dist/generator/index.d.ts.map +1 -1
  32. package/dist/generator/index.js +87 -6
  33. package/dist/generator/index.js.map +1 -1
  34. package/dist/generator/overlayProcessor.js +2 -2
  35. package/dist/generator/overlayProcessor.js.map +1 -1
  36. package/dist/generator/specLoader.d.ts +0 -5
  37. package/dist/generator/specLoader.d.ts.map +1 -1
  38. package/dist/generator/specLoader.js +0 -13
  39. package/dist/generator/specLoader.js.map +1 -1
  40. package/dist/generator/templateProcessor.d.ts +18 -1
  41. package/dist/generator/templateProcessor.d.ts.map +1 -1
  42. package/dist/generator/templateProcessor.js +20 -4
  43. package/dist/generator/templateProcessor.js.map +1 -1
  44. package/dist/generator/typeGenerator.d.ts +12 -1
  45. package/dist/generator/typeGenerator.d.ts.map +1 -1
  46. package/dist/generator/typeGenerator.js +26 -9
  47. package/dist/generator/typeGenerator.js.map +1 -1
  48. package/dist/glob.d.ts +24 -2
  49. package/dist/glob.d.ts.map +1 -1
  50. package/dist/glob.js +90 -2
  51. package/dist/glob.js.map +1 -1
  52. package/dist/guardrails/config.d.ts +5 -1
  53. package/dist/guardrails/config.d.ts.map +1 -1
  54. package/dist/guardrails/config.js +9 -2
  55. package/dist/guardrails/config.js.map +1 -1
  56. package/dist/guardrails/index.d.ts +1 -1
  57. package/dist/guardrails/index.d.ts.map +1 -1
  58. package/dist/guardrails/index.js +1 -1
  59. package/dist/guardrails/index.js.map +1 -1
  60. package/dist/guardrails/lint.js +2 -2
  61. package/dist/guardrails/lint.js.map +1 -1
  62. package/dist/guardrails/manifest.d.ts +0 -23
  63. package/dist/guardrails/manifest.d.ts.map +1 -1
  64. package/dist/guardrails/manifest.js +5 -75
  65. package/dist/guardrails/manifest.js.map +1 -1
  66. package/dist/guardrails/types.d.ts +0 -2
  67. package/dist/guardrails/types.d.ts.map +1 -1
  68. package/dist/index.d.ts +1 -1
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +1 -1
  71. package/dist/index.js.map +1 -1
  72. package/dist/micro-contracts.bundle.mjs +853 -927
  73. package/dist/micro-contracts.bundle.mjs.map +4 -4
  74. package/dist/types.d.ts +34 -3
  75. package/dist/types.d.ts.map +1 -1
  76. package/dist/types.js +100 -6
  77. package/dist/types.js.map +1 -1
  78. package/docs/cli-reference.md +2 -9
  79. package/docs/development-guardrails.md +3 -1
  80. package/package.json +8 -20
  81. package/dist/generator/inputHash.d.ts +0 -23
  82. package/dist/generator/inputHash.d.ts.map +0 -1
  83. package/dist/generator/inputHash.js +0 -84
  84. package/dist/generator/inputHash.js.map +0 -1
package/README.md CHANGED
@@ -47,7 +47,7 @@ The core architecture is organized along two axes:
47
47
 
48
48
  ## Quick Start
49
49
 
50
- > **Prerequisites**: Node.js 18+, TypeScript 5.0+, ESM (`"type": "module"`).
50
+ > **Prerequisites**: Node.js 20.12+, TypeScript 5.0+, ESM (`"type": "module"`).
51
51
 
52
52
  ```bash
53
53
  # 1. Install
@@ -397,22 +397,13 @@ Generate code from OpenAPI specifications.
397
397
  | `--skip-lint` | Skip linting before generation |
398
398
  | `--no-manifest` | Skip manifest generation |
399
399
  | `--manifest-dir <path>` | Directory for manifest (default: the deepest directory holding every configured output) |
400
- | `--force` | Bypass input hash cache and always regenerate |
401
- | `--no-cache` | Run without reading or writing input hash cache |
402
-
403
- A run that generates a subset (`--output`, `--module`, or any `--*-only`) does not
404
- record the input hash, so the next full run regenerates rather than reporting no
405
- changes.
406
400
 
407
401
  The manifest (`.generated-manifest.json`) lives in the deepest directory holding every
408
402
  location the config generates to — the project root when outputs sit both in
409
403
  `packages/` and next to the server code — and records the files there that the
410
- `generated:` patterns of `micro-contracts.guardrails.yaml` match. A full run records the input hash
411
- only when the manifest records every file of every configured output, so an output
412
- outside that directory or outside the `generated:` patterns leaves the hash out and
413
- generate names the file that did. The cache skips a run only when the manifest
414
- carries the input hash and finds each recorded file intact; without the hash, every
415
- run regenerates.
404
+ `generated:` patterns of `micro-contracts.guardrails.yaml` match. Every run generates:
405
+ the manifest is a committed file, part of the change a check reads, so it is never
406
+ taken as a record that the outputs need no regenerating.
416
407
 
417
408
  ### init \<module\>
418
409
 
@@ -447,10 +438,11 @@ An operation's success response is its lowest 2xx status code, else its `2XX` ra
447
438
  `default`: the service returns that response's body and the generated route answers with
448
439
  that status (200 for `2XX` and `default`). An operation that declares none of them is an
449
440
  error: declare the response a successful call returns. Its request body must be
450
- `application/json`, and its success response `application/json` or a stream —
451
- `text/event-stream`, `application/x-ndjson` or `application/jsonl` — since a body in any other
452
- media type would be dropped from every generated artifact; one declared otherwise is an
453
- error: remove that media type, and declare the body in one of them. A stream declares the
441
+ `application/json` or a form (`multipart/form-data`, see [Form Bodies](#form-bodies)), and its
442
+ success response `application/json` or a stream — `text/event-stream`, `application/x-ndjson`
443
+ or `application/jsonl` — since a body in any other media type would be dropped from every
444
+ generated artifact; one declared otherwise is an error: remove that media type, and declare
445
+ the body in one of them. A stream declares the
454
446
  schema of one event under `x-stream-event`, as a `oneOf` with `discriminator.propertyName`:
455
447
  a stream without `x-stream-event`, or whose events have no discriminator, is an error. A
456
448
  response of any other status, which documents an error, may use any media type; generated
@@ -495,14 +487,6 @@ Run full guardrails pipeline: **Gate 1,2 → Generate → Gate 3,4,5**.
495
487
  | `--output <ids>` | Output ids to generate, comma-separated; glob patterns allowed (e.g. `'*routes*'`). Fails when a pattern matches no output |
496
488
  | `--server-only` | Generate the built-in `server` section only (not valid with an `outputs` configuration) |
497
489
  | `--frontend-only` | Generate the built-in `frontend` section only (not valid with an `outputs` configuration) |
498
- | `--force` | Bypass input hash cache and always regenerate |
499
- | `--no-cache` | Run without reading or writing input hash cache |
500
-
501
- A run that generates a subset (`--output`, `--module`, or any `--*-only`) does not
502
- record the input hash, so the next full run regenerates rather than reporting no
503
- changes.
504
-
505
- The cache reads the same manifest as `generate`, under the same conditions.
506
490
 
507
491
  > See **[Enforceable Guardrails](docs/development-guardrails.md)** for gate details and CI configuration.
508
492
 
@@ -671,6 +655,65 @@ the client goes away, the service's iterator is closed at its next yield: a serv
671
655
  between events keeps running until it yields again. The starter fetch client returns the
672
656
  events as an `AsyncIterable` to read with `for await`.
673
657
 
658
+ ### Form Bodies
659
+
660
+ An operation whose request body is `multipart/form-data` takes a form. Its schema is an
661
+ object whose properties are its parts: a property that is a binary string — `format: binary`,
662
+ `contentEncoding: binary`, or a `contentMediaType` without `contentEncoding` — is a file, and
663
+ any other is a field, a string, number, integer or boolean (by its `type`, or by the values of
664
+ its `enum` or `const`). An array of either is a list, one part per item. A form schema that is
665
+ not an object of properties, or a property that is neither a field nor a file (an object, or a
666
+ nullable value), is an error.
667
+
668
+ ```yaml
669
+ requestBody:
670
+ required: true
671
+ content:
672
+ multipart/form-data:
673
+ schema:
674
+ type: object
675
+ required: [caption, photo]
676
+ properties:
677
+ caption: { type: string }
678
+ photo: { type: string, contentMediaType: image/jpeg, maxLength: 2097152 }
679
+ ```
680
+
681
+ The schema keeps its own type in `schemas/types.ts` and among the validators, a file being a
682
+ string there. The service receives the form as `<Service>_<method>Form`, the same properties
683
+ with each file as its bytes (`Uint8Array`, or `Uint8Array[]` for a list); a form without files
684
+ is received as its schema's type.
685
+
686
+ ```typescript
687
+ export interface Photo_uploadForm {
688
+ caption: string;
689
+ photo: Uint8Array;
690
+ }
691
+ export type Photo_uploadInput = { data: Photo_uploadForm };
692
+ ```
693
+
694
+ The contract package of a module with a form carries `forms/index.ts`: routes read a form's
695
+ parts with `readForm`. It validates the form against its schema with each file as a binary
696
+ string — one character per byte, so `maxLength` bounds a file's size — and gives the service
697
+ each file as its bytes. A file under a property that is not a file, a field under one that is,
698
+ or a second file for a property that takes one, is answered with 400 before the service runs,
699
+ as is a form its schema refuses.
700
+
701
+ The starter Fastify routes read a form with [`@fastify/multipart`](https://github.com/fastify/fastify-multipart):
702
+ register it, without `attachFieldsToBody`, before the routes, which refuse to register
703
+ otherwise. Its limits apply: a file or field it cuts at a limit is answered with 413. The
704
+ route reads the form once the operation's overlays admit the request, and validates it with
705
+ the validator Fastify validates the rest with (`request.compileValidationSchema`).
706
+
707
+ ```typescript
708
+ import multipart from '@fastify/multipart';
709
+
710
+ await fastify.register(multipart, { limits: { fileSize: 2 * 1024 * 1024 } });
711
+ await registerRoutes(fastify);
712
+ ```
713
+
714
+ The starter fetch client sends each property as a part — a list as one part per item, a file's
715
+ bytes as a file — in a `FormData` body.
716
+
674
717
  ### Validators
675
718
 
676
719
  `schemas/validators.ts` holds every schema as the JSON Schema Fastify validates requests and
@@ -787,8 +830,10 @@ The handler answers as the starter Fastify routes do:
787
830
  `removeAdditional: false` (see [Validators](#validators)), and words a refusal (400) as
788
831
  Fastify does (`querystring/limit must be integer`). The query is read from
789
832
  `rawQueryString`, a key given more than once being an array; headers in lower case; cookies
790
- from the event's `cookies`. A body is JSON — decoded first when `isBase64Encoded` — and
791
- another content type is answered with 415.
833
+ from the event's `cookies`. A body is JSON, or for an operation taking a
834
+ [form](#form-bodies), `multipart/form-data` read as the Fetch API reads one — decoded first
835
+ when `isBase64Encoded` — and another content type is answered with 415. A form is read once
836
+ the operation's overlays admit the request, as the Fastify route reads it.
792
837
  - It runs the operation's overlays (`overlayAdapter.generated.ts`), then the service, and
793
838
  answers with the success status and the body serialized by the schema declared for it.
794
839
 
package/cli-contract.yaml CHANGED
@@ -3,7 +3,7 @@ cli_contracts: 0.1.0
3
3
 
4
4
  info:
5
5
  title: micro-contracts CLI
6
- version: 0.20.2
6
+ version: 0.20.4
7
7
  description: >-
8
8
  Contract-first OpenAPI toolchain for TypeScript Web/API systems.
9
9
  Generates contract packages, server routes, and frontend clients
@@ -58,13 +58,11 @@ command_sets:
58
58
  the lint command (unless skipped), applies overlays, and generates
59
59
  contract packages, server routes, frontend clients, and
60
60
  documentation from OpenAPI specs.
61
- Supports input-hash caching to skip unnecessary regeneration.
62
61
  usage:
63
62
  - micro-contracts generate
64
63
  - micro-contracts generate -c my-config.yaml
65
64
  - micro-contracts generate -m core,billing
66
65
  - micro-contracts generate --contracts-only
67
- - micro-contracts generate --force
68
66
 
69
67
  options:
70
68
  - name: config
@@ -141,20 +139,6 @@ command_sets:
141
139
  schema:
142
140
  type: string
143
141
 
144
- - name: force
145
- description: Bypass input hash cache and always regenerate.
146
- schema:
147
- type: boolean
148
- default: false
149
-
150
- - name: cache
151
- description: >-
152
- Enable input hash caching. Enabled by default.
153
- Use --no-cache to disable both reading and writing cache.
154
- schema:
155
- type: boolean
156
- default: true
157
-
158
142
  exits:
159
143
  '0':
160
144
  description: Generation succeeded.
@@ -560,20 +544,6 @@ command_sets:
560
544
  type: boolean
561
545
  default: false
562
546
 
563
- - name: force
564
- description: Bypass input hash cache and always regenerate.
565
- schema:
566
- type: boolean
567
- default: false
568
-
569
- - name: cache
570
- description: >-
571
- Enable input hash caching. Enabled by default.
572
- Use --no-cache to disable both reading and writing cache.
573
- schema:
574
- type: boolean
575
- default: true
576
-
577
547
  exits:
578
548
  '0':
579
549
  description: Pipeline completed successfully. All gates passed and generation succeeded.
@@ -1 +1 @@
1
- {"version":3,"file":"templates.d.ts","sourceRoot":"","sources":["../../src/cli/templates.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAk8BH;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQ5D;AAED;;GAEG;AACH,wBAAgB,yBAAyB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAIlE;AAED;;GAEG;AACH,wBAAgB,yBAAyB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAKlE"}
1
+ {"version":3,"file":"templates.d.ts","sourceRoot":"","sources":["../../src/cli/templates.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AA0jCH;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQ5D;AAED;;GAEG;AACH,wBAAgB,yBAAyB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAIlE;AAED;;GAEG;AACH,wBAAgB,yBAAyB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAKlE"}
@@ -23,9 +23,35 @@ import { runOverlays, type HttpRequest } from './overlayAdapter.generated.js';
23
23
  import { Readable } from 'node:stream';
24
24
  import { encodeStream } from '{{contractPackage}}/streams/index.js';
25
25
  {{/if}}
26
+ {{#if forms}}
27
+ import type { Multipart } from '@fastify/multipart';
28
+ import { readForm, type FormPart } from '{{contractPackage}}/forms/index.js';
29
+ {{/if}}
26
30
  {{#if readsCookies}}
27
31
  import { parseCookies } from '{{contractPackage}}/http/index.js';
28
32
  {{/if}}
33
+ {{#if forms}}
34
+
35
+ /** An error answered with 413 */
36
+ function tooLarge(message: string): Error {
37
+ return Object.assign(new Error(message), { statusCode: 413 });
38
+ }
39
+
40
+ /** A form's parts as readForm reads them: a field's value, a file's bytes in full */
41
+ async function* formParts(parts: AsyncIterable<Multipart>): AsyncGenerator<FormPart> {
42
+ for await (const part of parts) {
43
+ if (part.type === 'file') {
44
+ const file = await part.toBuffer();
45
+ {{!-- With throwFileSizeLimit off, @fastify/multipart cuts a file at its limit instead of refusing it --}}
46
+ if (part.file.truncated) throw tooLarge(\`body/\${part.fieldname} exceeds the file size limit\`);
47
+ yield { name: part.fieldname, file };
48
+ } else {
49
+ if (part.fieldnameTruncated || part.valueTruncated) throw tooLarge(\`body/\${part.fieldname} exceeds the field size limit\`);
50
+ yield { name: part.fieldname, value: part.value };
51
+ }
52
+ }
53
+ }
54
+ {{/if}}
29
55
  {{#if extensionInfo.length}}
30
56
 
31
57
  /** The request as the overlays read it */
@@ -46,6 +72,12 @@ function sendError(reply: FastifyReply, error: types.ProblemDetails): FastifyRep
46
72
  {{/if}}
47
73
 
48
74
  export async function registerRoutes(fastify: FastifyInstance): Promise<void> {
75
+ {{#if forms}}
76
+ if (!fastify.hasContentTypeParser('multipart/form-data')) {
77
+ throw new Error('These routes read multipart/form-data bodies with @fastify/multipart: register it before them');
78
+ }
79
+
80
+ {{/if}}
49
81
  // A component referenced from a shared file is a schema of every module that
50
82
  // references it: the first module registers it, and a module defining a
51
83
  // different schema under the same id is an error.
@@ -72,6 +104,10 @@ export async function registerRoutes(fastify: FastifyInstance): Promise<void> {
72
104
  {{#if stream}}
73
105
  {{!-- Events are serialized as a JSON response is: by the schema of one event --}}
74
106
  const {{typeNameBase}}EventSchema = { $ref: '{{stream.eventType}}#' };
107
+ {{/if}}
108
+ {{#if form}}
109
+ {{!-- Fastify parses no form: the route reads it, and validates it with the validator Fastify validates the rest with --}}
110
+ const {{typeNameBase}}FormSchema = { $ref: '{{form.schemaName}}#' };
75
111
  {{/if}}
76
112
  fastify.{{method}}('{{fastifyPath}}', {
77
113
  schema: {
@@ -113,20 +149,38 @@ export async function registerRoutes(fastify: FastifyInstance): Promise<void> {
113
149
  {{#if extensions.length}}
114
150
  const result = await runOverlays('{{operationId}}', handlers, toHttpRequest(req, cookies));
115
151
  if (!result.success) return sendError(reply, result.error);
152
+ {{/if}}
153
+ {{#if form}}
154
+ const validateForm = req.compileValidationSchema({{typeNameBase}}FormSchema);
155
+ const form = await readForm(formParts(req.parts()), [{{#each form.files}}{ name: {{{json name}}}, many: {{many}} }, {{/each~}} ], body => {
156
+ if (!validateForm(body)) {
157
+ throw Object.assign(
158
+ new Error((validateForm.errors ?? []).map(e => \`body\${e.instancePath} \${e.message}\`).join(', ')),
159
+ { statusCode: 400, code: 'FST_ERR_VALIDATION', validation: validateForm.errors, validationContext: 'body' },
160
+ );
161
+ }
162
+ });
116
163
  {{/if}}
117
164
  // Build input object (always required, even if empty)
165
+ {{!-- Each parameter from where it is declared: a query key of another parameter's name would replace that parameter --}}
118
166
  const input: types.{{inputType}} = {
119
167
  {{#if pathParams.length}}
120
168
  ...(req.params as types.{{typeNameBase}}Params),
121
169
  {{/if}}
122
170
  {{#if queryParams.length}}
123
- ...(req.query as types.{{typeNameBase}}Params),
171
+ ...(Object.fromEntries([{{#each queryParams}}'{{name}}', {{/each~}} ].flatMap(name => {
172
+ const query = req.query as Record<string, unknown>;
173
+ return Object.hasOwn(query, name) ? [[name, query[name]]] : [];
174
+ })) as unknown as types.{{typeNameBase}}Params),
124
175
  {{/if}}
125
176
  {{#if cookieParams.length}}
126
177
  ...(cookieParams as unknown as types.{{typeNameBase}}Params),
127
178
  {{/if}}
128
179
  {{#if requestBody}}
129
180
  data: req.body as types.{{requestBody.schemaName}},
181
+ {{/if}}
182
+ {{#if form}}
183
+ data: form as types.{{form.type}},
130
184
  {{/if}}
131
185
  };
132
186
  {{!-- The success status is set once the service has returned: an error it throws keeps its own status. --}}
@@ -217,6 +271,22 @@ async function* bodyText(res: Response): AsyncGenerator<string> {
217
271
  }
218
272
  }
219
273
  {{/if}}
274
+ {{#if forms}}
275
+
276
+ /** A form as a multipart/form-data body: each property a part, a list one part per item, a file's bytes a file */
277
+ function formBody(data: object): FormData {
278
+ const body = new FormData();
279
+ const entries: Array<[string, unknown]> = Object.entries(data);
280
+ for (const [name, value] of entries) {
281
+ for (const item of Array.isArray(value) ? value : [value]) {
282
+ if (item === undefined) continue;
283
+ if (item instanceof Uint8Array) body.append(name, new Blob([new Uint8Array(item)]), name);
284
+ else body.append(name, String(item));
285
+ }
286
+ }
287
+ return body;
288
+ }
289
+ {{/if}}
220
290
 
221
291
  {{#each services}}
222
292
  // ==========================================================================
@@ -227,7 +297,7 @@ export const {{key}}Api = {
227
297
  {{#if (eq service ../name)}}
228
298
  /**
229
299
  * {{httpMethod}} {{path}}
230
- {{#if summary}}* {{summary}}{{/if}}
300
+ {{#if summary}}* {{comment summary}}{{/if}}
231
301
  {{#if isPublished}}* @published{{/if}}
232
302
  */
233
303
  async {{#if stream}}*{{/if}}{{serviceMethod}}(input: {{clientInputType}}): {{#if stream}}AsyncGenerator<{{stream.eventType}}>{{else}}Promise<{{responseType}}>{{/if}} {
@@ -244,6 +314,8 @@ export const {{key}}Api = {
244
314
  {{/if}}
245
315
  {{#if (eq httpMethod "GET")}}
246
316
  const res = await fetch(url);
317
+ {{else if form}}
318
+ const res = await fetch(url, { method: '{{httpMethod}}', body: formBody(input.data) });
247
319
  {{else if requestType}}
248
320
  const res = await fetch(url, {
249
321
  method: '{{httpMethod}}',
@@ -285,7 +357,7 @@ export class {{name}}Service implements {{name}}ServiceApi {
285
357
  {{#each ../routes}}
286
358
  {{#if (eq service ../name)}}
287
359
  /**
288
- * {{httpMethod}} {{path}}{{#if summary}}: {{summary}}{{/if}}
360
+ * {{httpMethod}} {{path}}{{#if summary}}: {{comment summary}}{{/if}}
289
361
  */
290
362
  async {{#if stream}}*{{/if}}{{serviceMethod}}(input: types.{{inputType}}): {{#if stream}}AsyncGenerator<types.{{stream.eventType}}>{{else}}Promise<{{#if (eq responseType "void")}}void{{else}}types.{{responseType}}{{/if}}>{{/if}} {
291
363
  // TODO: Implement {{serviceMethod}}
@@ -499,6 +571,9 @@ import { Readable, type Writable } from 'node:stream';
499
571
  import { pipeline } from 'node:stream/promises';
500
572
  import { encodeStream } from '{{contractPackage}}/streams/index.js';
501
573
  {{/if}}
574
+ {{#if forms}}
575
+ import { readForm, type FormPart } from '{{contractPackage}}/forms/index.js';
576
+ {{/if}}
502
577
 
503
578
  // ==========================================================================
504
579
  // Events
@@ -546,6 +621,10 @@ interface RouteRequest {
546
621
  /** The route's cookie parameters, by name */
547
622
  cookieParams: Record<string, string>;
548
623
  body: unknown;
624
+ {{#if forms}}
625
+ /** The parts of a form body (multipart/form-data) */
626
+ parts(): Promise<FormPart[]>;
627
+ {{/if}}
549
628
  }
550
629
 
551
630
  /** A response: its body whole, or (a stream operation's) as the service yields it */
@@ -692,6 +771,29 @@ function parseBody(event: HttpApiEvent, contentType: string | undefined): unknow
692
771
  if (forbidden) throw httpError(400, 'Object contains forbidden prototype property');
693
772
  return body;
694
773
  }
774
+ {{#if forms}}
775
+
776
+ /** The parts of an event's form body (multipart/form-data), parsed as the Fetch API parses one */
777
+ async function formParts(event: HttpApiEvent, contentType: string | undefined): Promise<FormPart[]> {
778
+ if (contentType === undefined || contentType.split(';')[0].trim().toLowerCase() !== 'multipart/form-data') {
779
+ throw httpError(415, 'Unsupported Media Type');
780
+ }
781
+ const body = Buffer.from(event.body ?? '', event.isBase64Encoded ? 'base64' : 'utf-8');
782
+ let form: FormData;
783
+ try {
784
+ form = await new Response(body, { headers: { 'content-type': contentType } }).formData();
785
+ } catch {
786
+ throw httpError(400, 'Body is not valid multipart/form-data');
787
+ }
788
+ const parts: Array<Promise<FormPart>> = [];
789
+ form.forEach((value, name) => {
790
+ parts.push(typeof value === 'string'
791
+ ? Promise.resolve({ name, value })
792
+ : value.arrayBuffer().then(buffer => ({ name, file: new Uint8Array(buffer) })));
793
+ });
794
+ return Promise.all(parts);
795
+ }
796
+ {{/if}}
695
797
 
696
798
  /** Validate a part of the request, coercing it to its schema in place: one that fails is answered with 400 */
697
799
  function check(validate: ValidateFunction | undefined, data: unknown, part: string): void {
@@ -718,6 +820,9 @@ async function answer(route: Route, values: string[], event: HttpApiEvent): Prom
718
820
  }),
719
821
  ),
720
822
  body: route.body ? parseBody(event, headers['content-type']) : undefined,
823
+ {{#if forms}}
824
+ parts: () => formParts(event, headers['content-type']),
825
+ {{/if}}
721
826
  };
722
827
  check(route.params, request.params, 'params');
723
828
  check(route.body, request.body, 'body');
@@ -756,6 +861,11 @@ function createDispatcher(options: HandlerOptions): (event: HttpApiEvent) => Pro
756
861
  const { overlays } = options;
757
862
  {{/if}}
758
863
 
864
+ {{#each routes}}
865
+ {{#if form}}
866
+ const {{typeNameBase}}FormValidator = ajv.compile({ $ref: '{{form.schemaName}}#' });
867
+ {{/if}}
868
+ {{/each}}
759
869
  const routes: Route[] = [
760
870
  {{#each routes}}
761
871
  // {{httpMethod}} {{path}}{{#if isPublished}} [PUBLISHED]{{/if}}
@@ -784,18 +894,28 @@ function createDispatcher(options: HandlerOptions): (event: HttpApiEvent) => Pro
784
894
  const result = await runOverlays('{{operationId}}', overlays, request);
785
895
  if (!result.success) return reply.send(result.error.status, result.error);
786
896
  {{/if}}
897
+ {{#if form}}
898
+ {{!-- The form is read once the overlays admit the request, as the Fastify route reads it --}}
899
+ const form = await readForm(await request.parts(), [{{#each form.files}}{ name: {{{json name}}}, many: {{many}} }, {{/each~}} ], body => check({{typeNameBase}}FormValidator, body, 'body'));
900
+ {{/if}}
901
+ {{!-- Each parameter from where it is declared: a query key of another parameter's name would replace that parameter --}}
787
902
  const input: types.{{inputType}} = {
788
903
  {{#if pathParams.length}}
789
904
  ...(request.params as unknown as types.{{typeNameBase}}Params),
790
905
  {{/if}}
791
906
  {{#if queryParams.length}}
792
- ...(request.query as unknown as types.{{typeNameBase}}Params),
907
+ ...(Object.fromEntries([{{#each queryParams}}'{{name}}', {{/each~}} ].flatMap(name =>
908
+ Object.hasOwn(request.query, name) ? [[name, request.query[name]]] : [],
909
+ )) as unknown as types.{{typeNameBase}}Params),
793
910
  {{/if}}
794
911
  {{#if cookieParams.length}}
795
912
  ...(request.cookieParams as unknown as types.{{typeNameBase}}Params),
796
913
  {{/if}}
797
914
  {{#if requestBody}}
798
915
  data: request.body as types.{{requestBody.schemaName}},
916
+ {{/if}}
917
+ {{#if form}}
918
+ data: form as types.{{form.type}},
799
919
  {{/if}}
800
920
  };
801
921
  {{#if stream}}
@@ -1 +1 @@
1
- {"version":3,"file":"templates.js","sourceRoot":"","sources":["../../src/cli/templates.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,MAAM,+BAA+B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+IvC,CAAC;AAEF,MAAM,6BAA6B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuHrC,CAAC;AAEF,MAAM,8BAA8B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BtC,CAAC;AAEF,MAAM,gCAAgC,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkIxC,CAAC;AAEF,MAAM,8BAA8B,G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