@20baht/cli 0.3.0 → 0.3.2

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.
package/README.md CHANGED
@@ -27,6 +27,7 @@ steps.
27
27
  | `20baht update [version]` | Existing repo: `@20baht/*` to the latest or a chosen version |
28
28
  | `20baht g model <domain>` | `libs/domain/<domain>/model` package |
29
29
  | `20baht g form <domain>/<name> --fields` | Engine-validated `FormDefinition` JSON inside that model package |
30
+ | `20baht g types <file.json> …` | A form or workflow JSON as a typed TypeScript module beside it |
30
31
  | `20baht g remote <name>` | Federation workspace: another remote, wired into the host and checks |
31
32
  | `20baht g deploy [nginx]` | Federation workspace: nginx + systemd deploy, release/deploy/preview |
32
33
 
@@ -78,9 +79,11 @@ Add a matching entry to `knip.ts` so dead-code checks cover it.
78
79
  Same flags as `new`. The `new` toolchain, plus an app on the family's main stack:
79
80
 
80
81
  ```
81
- apps/web Angular (:4200): @20baht/angular app shell and navigator, one page calling
82
- GET /api/hello, a not-found page
83
- apps/server Elysia under /api (:3001); exports `type App`, emitted to dist/types for the web app
82
+ apps/web Angular (:4200): @20baht/angular app shell and navigator, a page calling
83
+ GET /api/hello, a Contact page (a <baht-form> from the server's schema), a
84
+ not-found page
85
+ apps/server Elysia under /api (:3001); exports `type App`, emitted to dist/types for the web app.
86
+ One form as data (src/forms/contact.form.ts): served, and validated on submit
84
87
  packages/kit typed ngx-eden client + error text, compiled into the app as @<name>/kit
85
88
  bahtui.json { "frontend": "angular", "apps": { "web": "apps/web", ... } }
86
89
  ```
@@ -243,6 +246,41 @@ Field DSL — comma-separated `key:type[:modifier…]`:
243
246
  Invalid DSL (unknown type, empty options, non-numeric `min`) fails before anything is
244
247
  written.
245
248
 
249
+
250
+ ### `20baht g types <file.json> …`
251
+
252
+ A schema kept as JSON has no types: TypeScript reads an imported `.json` field `type` as `string`.
253
+ `g types` writes each form or workflow JSON out as a TypeScript module beside it
254
+ (`order.form.json` → `order.form.ts`) that declares it with `defineForm` / `defineWorkflow`, so
255
+ its data is typed exactly like a schema written by hand. It works in any repo; no `bahtui.json`.
256
+
257
+ ```sh
258
+ 20baht g types src/forms/order.form.json src/forms/leave.workflow.json
259
+ ```
260
+
261
+ ```ts
262
+ import { orderForm, type OrderFormSubmission, type OrderFormValues } from './forms/order.form';
263
+
264
+ app.post('/orders', ({ body }) => save(body), { body: formBody(orderForm) }); // body: OrderFormSubmission
265
+ ```
266
+
267
+ A form exports the schema (`orderForm`), `…Values` (the data as held) and `…Submission` (after
268
+ validation: required fields never null). A workflow exports the schema and `…Values`, by form
269
+ name. The names come from the file name and always end in `Form` / `Workflow`.
270
+
271
+ - The JSON is checked by the engine (`parseSchema`) first: one refused file and nothing is written.
272
+ - `--check` writes nothing and fails when a module is missing or differs from its JSON: put it
273
+ in the project's check (`20baht g types src/forms/*.json --check`).
274
+ - A `.ts` file the command did not write is never replaced without `--force`.
275
+ - `--from @20baht/ui` imports `defineForm` from there (a web app that has no `@20baht/engine`).
276
+ - `--field-types money,colour` names the field types of the app's own that the schemas use; the
277
+ app still names them for TypeScript itself (`CustomFieldTypes`, `CustomFieldValues`).
278
+ - Every statement carries `// prettier-ignore`, so the project's formatter leaves the file as
279
+ written and `--check` stays a byte comparison.
280
+
281
+ The generator does not work out any type. It writes the schema down, and the engine's `FormValues`
282
+ maps it: there is one such map, not two to keep in step.
283
+
246
284
  ## Global flags
247
285
 
248
286
  ```
@@ -2,6 +2,7 @@ import { buildFormDefinition, FormDslError } from '../domain/form-dsl.js';
2
2
  import { DEFAULT_CONFIG, modelDir, planForm, planInit, planModel, validateDomainName, } from '../domain/generate-plan.js';
3
3
  import { DEFAULT_API_PORT, DeployPlanError, planDeploy } from '../domain/deploy-plan.js';
4
4
  import { nextRemotePort, planRemoteFiles, remoteFor, RemoteWiringError, validateRemoteName, wireRemote, wiringPaths, } from '../domain/remote-plan.js';
5
+ import { GENERATED_MARK, TypesPlanError, typesModule, typesPath } from '../domain/types-plan.js';
5
6
  export class GenerateError extends Error {
6
7
  }
7
8
  /**
@@ -11,15 +12,17 @@ export class GenerateError extends Error {
11
12
  * join (defense in depth alongside DiskFileWriter's own root confinement).
12
13
  */
13
14
  const SAFE_RELATIVE_PATH = /^[A-Za-z0-9._/-]+$/;
15
+ /** A bahtui.json field, or (with a space in it) a description of what the path is. */
16
+ const label = (field) => (field.includes(' ') ? field : `bahtui.json "${field}"`);
14
17
  function validateConfigPath(field, value) {
15
18
  if (!SAFE_RELATIVE_PATH.test(value)) {
16
- throw new GenerateError(`bahtui.json "${field}" contains invalid characters: ${JSON.stringify(value)}.`);
19
+ throw new GenerateError(`${label(field)} contains invalid characters: ${JSON.stringify(value)}.`);
17
20
  }
18
21
  if (value.startsWith('/')) {
19
- throw new GenerateError(`bahtui.json "${field}" must be a relative path: ${JSON.stringify(value)}.`);
22
+ throw new GenerateError(`${label(field)} must be a relative path: ${JSON.stringify(value)}.`);
20
23
  }
21
24
  if (value.split('/').includes('..')) {
22
- throw new GenerateError(`bahtui.json "${field}" must not contain ".." segments: ${JSON.stringify(value)}.`);
25
+ throw new GenerateError(`${label(field)} must not contain ".." segments: ${JSON.stringify(value)}.`);
23
26
  }
24
27
  }
25
28
  function isPlainObject(value) {
@@ -137,6 +140,46 @@ export function runGenerate(input, deps) {
137
140
  }
138
141
  emit(planForm(input.root, config, domain, name, form), input.dryRun, deps);
139
142
  }
143
+ /**
144
+ * `20baht g types <file.json>…`: each form or workflow JSON as a typed TypeScript module beside
145
+ * it (`order.form.json` -> `order.form.ts`). Needs no bahtui.json. Every file is read and checked
146
+ * by the engine before any is written: one refused file means zero files.
147
+ */
148
+ export function runGenerateTypes(input, deps) {
149
+ if (input.paths.length === 0) {
150
+ throw new GenerateError('g types needs a file: 20baht g types <path/to/schema.json> …');
151
+ }
152
+ const files = input.paths.map((path) => {
153
+ validateConfigPath('g types path', path);
154
+ if (!/\.json$/i.test(path)) {
155
+ throw new GenerateError(`g types reads .json files: ${JSON.stringify(path)} is not one.`);
156
+ }
157
+ const json = deps.reader.read(`${input.root}/${path}`);
158
+ if (json === null)
159
+ throw new GenerateError(`${path} does not exist.`);
160
+ const base = path.split('/').pop() ?? path;
161
+ const { contents } = planned(TypesPlanError, () => typesModule(base, json, { from: input.from, fieldTypes: input.fieldTypes }));
162
+ return { path: typesPath(path), contents };
163
+ });
164
+ const current = (path) => deps.reader.read(`${input.root}/${path}`);
165
+ if (input.check) {
166
+ const stale = files.filter((file) => current(file.path) !== file.contents);
167
+ if (stale.length > 0) {
168
+ throw new GenerateError(`out of date: ${stale.map((file) => file.path).join(', ')}. Run 20baht g types ${input.paths.join(' ')}`);
169
+ }
170
+ deps.log.info(`${String(files.length)} generated module(s) are current.`);
171
+ return;
172
+ }
173
+ if (!input.force) {
174
+ for (const file of files) {
175
+ const existing = current(file.path);
176
+ if (existing !== null && !existing.startsWith(GENERATED_MARK)) {
177
+ throw new GenerateError(`${file.path} was not generated by this command — use --force to replace it.`);
178
+ }
179
+ }
180
+ }
181
+ emit({ root: input.root, files, postCommands: [] }, input.dryRun, deps);
182
+ }
140
183
  function readWiring(root, host, reader) {
141
184
  const paths = wiringPaths(host);
142
185
  const read = (path) => {
package/dist/args.js CHANGED
@@ -12,6 +12,7 @@ export const KNOWN_FLAGS = new Set([
12
12
  '--skip-git',
13
13
  '--federation',
14
14
  '--react',
15
+ '--check',
15
16
  // No longer a choice (Angular is what `create` makes); kept known so `create` can say so.
16
17
  '--angular',
17
18
  ]);
@@ -45,8 +46,10 @@ export function parseArgs(rawArgv) {
45
46
  const fields = takeOption(argv, '--fields');
46
47
  const frontend = takeOption(argv, '--frontend');
47
48
  const backend = takeOption(argv, '--backend');
49
+ const from = takeOption(argv, '--from');
50
+ const fieldTypes = takeOption(argv, '--field-types');
48
51
  const args = argv.filter((a) => !a.startsWith('-'));
49
52
  const flags = new Set(argv.filter((a) => a.startsWith('-')));
50
- const [command, name, sub] = args;
51
- return { fields, frontend, backend, flags, command, name, sub };
53
+ const [command, name, sub, ...rest] = args;
54
+ return { fields, frontend, backend, from, fieldTypes, flags, command, name, sub, rest };
52
55
  }
package/dist/cli.js CHANGED
@@ -3,7 +3,7 @@ import { resolve } from 'node:path';
3
3
  import { readFileSync } from 'node:fs';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { runCreate, CreateError } from './application/create.js';
6
- import { runGenerate, runGenerateDeploy, runGenerateRemote, runInit, GenerateError, } from './application/generate.js';
6
+ import { runGenerate, runGenerateDeploy, runGenerateRemote, runGenerateTypes, runInit, GenerateError, } from './application/generate.js';
7
7
  import { DiskTemplateSource } from './infrastructure/template-source.js';
8
8
  import { TemplateRenderer } from './infrastructure/template-renderer.js';
9
9
  import { DiskFileWriter } from './infrastructure/fs-writer.js';
@@ -29,6 +29,8 @@ Usage:
29
29
  20baht g model <domain> libs/domain/<d>/model package
30
30
  20baht g form <domain>/<name> --fields "key:type:mod,…"
31
31
  engine-validated FormDefinition JSON
32
+ 20baht g types <file.json> … a form or workflow JSON as a typed TypeScript module beside it
33
+ (order.form.json -> order.form.ts): its data typed, no hand-written types
32
34
  20baht g remote <name> federation workspace: apps/<name>-web remote, added to the
33
35
  host manifests, eslint, knip and dependency-cruiser
34
36
  20baht g deploy [nginx] federation workspace: deploy/ (nginx, systemd, install.sh)
@@ -38,6 +40,9 @@ Field DSL:
38
40
 
39
41
  Options:
40
42
  --fields <dsl> g form: the field list (required)
43
+ --check g types: write nothing, fail when a generated module is missing or stale
44
+ --from <module> g types: where defineForm is imported from (default @20baht/engine)
45
+ --field-types <a,b> g types: field types of the app's own that the schemas use
41
46
  --federation create: a Native Federation dynamic host and a remote instead of one app
42
47
  --react create: the React scaffold instead of Angular
43
48
  --frontend <react|none> init: default react
@@ -147,8 +152,10 @@ function commandGenerate(a, generateDeps) {
147
152
  return commandRemote(a, generateDeps);
148
153
  if (name === 'deploy')
149
154
  return commandDeploy(a, generateDeps);
155
+ if (name === 'types')
156
+ return commandTypes(a, generateDeps);
150
157
  if (name !== 'model' && name !== 'form') {
151
- log.error('Unknown generator — 20baht g model <domain> | g form <domain>/<name> | g remote <name> | g deploy.');
158
+ log.error('Unknown generator — 20baht g model <domain> | g form <domain>/<name> | g types <file.json> | g remote <name> | g deploy.');
152
159
  return 1;
153
160
  }
154
161
  if (!sub) {
@@ -165,6 +172,18 @@ function commandGenerate(a, generateDeps) {
165
172
  }, generateDeps);
166
173
  return 0;
167
174
  }
175
+ function commandTypes(a, generateDeps) {
176
+ runGenerateTypes({
177
+ root: process.cwd(),
178
+ paths: a.sub === undefined ? [] : [a.sub, ...a.rest],
179
+ check: a.flags.has('--check'),
180
+ dryRun: a.flags.has('--dry-run'),
181
+ force: a.flags.has('--force'),
182
+ from: a.from,
183
+ fieldTypes: (a.fieldTypes ?? '').split(',').filter((type) => type !== ''),
184
+ }, generateDeps);
185
+ return 0;
186
+ }
168
187
  function commandRemote(a, generateDeps) {
169
188
  if (!a.sub) {
170
189
  log.error('g remote needs a name: 20baht g remote <name>');
@@ -0,0 +1,100 @@
1
+ import { isWorkflowDefinition, parseSchema } from '@20baht/validator';
2
+ /**
3
+ * `20baht g types`: a form or workflow kept as JSON, as a TypeScript module. JSON has no literal
4
+ * types (an imported `.json` reads `type` as `string`), so the module writes the schema down
5
+ * inside `defineForm` / `defineWorkflow` and lets the engine's own types (`FormValues`, …) say
6
+ * what its data is. Nothing here maps a field type to a TypeScript type: there is one such map,
7
+ * the engine's.
8
+ */
9
+ export class TypesPlanError extends Error {
10
+ }
11
+ /** The first line of every module this writes: how a later run knows the file is its own. */
12
+ export const GENERATED_MARK = '// Generated by `20baht g types';
13
+ const DEFAULT_FROM = '@20baht/engine';
14
+ const MODULE_NAME = /^[@A-Za-z0-9._/-]+$/;
15
+ /** `create-ticket.form.json` -> `createTicketForm`; always ends in the kind, so never a keyword. */
16
+ function schemaName(file, kind) {
17
+ const words = file
18
+ .replace(/\.json$/i, '')
19
+ .split(/[^A-Za-z0-9]+/)
20
+ .filter((word) => word !== '');
21
+ const camel = words
22
+ .map((word, i) => i === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
23
+ .join('');
24
+ if (!/^[a-z]/.test(camel)) {
25
+ throw new TypesPlanError(`${file}: the file name must start with a letter (it names the export).`);
26
+ }
27
+ return camel.toLowerCase().endsWith(kind.toLowerCase()) ? camel : `${camel}${kind}`;
28
+ }
29
+ const pascal = (name) => name.charAt(0).toUpperCase() + name.slice(1);
30
+ function parse(file, json, fieldTypes) {
31
+ let raw;
32
+ try {
33
+ raw = JSON.parse(json);
34
+ }
35
+ catch {
36
+ throw new TypesPlanError(`${file} is not valid JSON.`);
37
+ }
38
+ try {
39
+ return parseSchema(raw, {
40
+ fieldTypes: Object.fromEntries(fieldTypes.map((type) => [type, {}])),
41
+ });
42
+ }
43
+ catch (err) {
44
+ const message = err instanceof Error ? err.message : String(err);
45
+ const hint = /field type/i.test(message)
46
+ ? " (a field type of the app's own? name it: --field-types <a,b>)"
47
+ : '';
48
+ throw new TypesPlanError(`${file}: ${message}${hint}`);
49
+ }
50
+ }
51
+ /**
52
+ * The module for the schema in `json`, read from a file named `file` (its base name: it names
53
+ * the exports and is quoted in the header). Throws `TypesPlanError` for JSON the engine refuses.
54
+ */
55
+ export function typesModule(file, json, options = {}) {
56
+ const from = options.from ?? DEFAULT_FROM;
57
+ if (!MODULE_NAME.test(from)) {
58
+ throw new TypesPlanError(`--from ${JSON.stringify(from)} is not a module name.`);
59
+ }
60
+ const schema = parse(file, json, options.fieldTypes ?? []);
61
+ const workflow = isWorkflowDefinition(schema);
62
+ const name = schemaName(file, workflow ? 'Workflow' : 'Form');
63
+ const type = pascal(name);
64
+ const literal = JSON.stringify(schema, null, 2);
65
+ // `// prettier-ignore` on every statement: the host's prettier (quotes, semicolons, width)
66
+ // would otherwise rewrite the file, and `--check` compares it byte for byte.
67
+ const head = `${GENERATED_MARK} ${file}\`. Do not edit: change the JSON and run it again.\n` +
68
+ `// prettier-ignore\n`;
69
+ if (workflow) {
70
+ return {
71
+ names: { schema: name, types: [`${type}Values`] },
72
+ contents: head +
73
+ `import { defineWorkflow, type WorkflowValues } from '${from}';\n\n` +
74
+ `/** \`${file}\`, typed: hand it to \`<baht-workflow>\`, \`validateSubmission\`, \`runsOf\`. */\n` +
75
+ `// prettier-ignore\n` +
76
+ `export const ${name} = defineWorkflow(${literal});\n\n` +
77
+ `/** The workflow's data by form name; a form or field a rule hides is absent. */\n` +
78
+ `// prettier-ignore\n` +
79
+ `export type ${type}Values = WorkflowValues<typeof ${name}>;\n`,
80
+ };
81
+ }
82
+ return {
83
+ names: { schema: name, types: [`${type}Values`, `${type}Submission`] },
84
+ contents: head +
85
+ `import { defineForm, type FormValues, type ValidValues } from '${from}';\n\n` +
86
+ `/** \`${file}\`, typed: hand it to \`<baht-form>\`, \`validateSubmission\`, \`formBody\`. */\n` +
87
+ `// prettier-ignore\n` +
88
+ `export const ${name} = defineForm(${literal});\n\n` +
89
+ `/** The form's data as held (\`getData()\`, \`baht-change\`): a required field may still be empty. */\n` +
90
+ `// prettier-ignore\n` +
91
+ `export type ${type}Values = FormValues<typeof ${name}>;\n\n` +
92
+ `/** The data of a submission that passed validation: a required field is never null. */\n` +
93
+ `// prettier-ignore\n` +
94
+ `export type ${type}Submission = ValidValues<typeof ${name}>;\n`,
95
+ };
96
+ }
97
+ /** Where the module of `path` (a `.json` file) goes: beside it, `.ts` for `.json`. */
98
+ export function typesPath(path) {
99
+ return path.replace(/\.json$/i, '.ts');
100
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@20baht/cli",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "type": "module",
5
5
  "description": "Scaffold apps on the @20baht libraries: Angular + Elysia (20baht create), optionally as Native Federation microfrontends, a bare bun workspace (20baht new), plus bahtui generators.",
6
6
  "license": "MIT",
@@ -51,6 +51,7 @@
51
51
  "@20baht/validator": ">=0.3.0 <0.4.0"
52
52
  },
53
53
  "devDependencies": {
54
+ "@20baht/engine": "workspace:*",
54
55
  "@types/node": "^22",
55
56
  "typescript": "^5.9.3",
56
57
  "vitest": "^3.2.4"
@@ -20,6 +20,8 @@
20
20
  "test:coverage": "bun test --coverage"
21
21
  },
22
22
  "dependencies": {
23
+ "@20baht/engine": "0.3.2",
24
+ "@20baht/validator": "^0.3.2",
23
25
  "@elysiajs/cors": "^1.4.3",
24
26
  "elysia": "^1.4.31"
25
27
  },
@@ -1,5 +1,7 @@
1
1
  import { cors } from '@elysiajs/cors'
2
+ import { formBody } from '@20baht/validator/elysia'
2
3
  import { Elysia } from 'elysia'
4
+ import { contactForm } from './forms/contact.form'
3
5
 
4
6
  /** In dev the host and the remotes run on their own localhost ports; deployed, all share one origin. */
5
7
  const DEV_ORIGIN = /^http:\/\/localhost:\d+$/
@@ -12,3 +14,8 @@ export const buildApp = () =>
12
14
  new Elysia({ prefix: '/api' })
13
15
  .use(cors({ origin: DEV_ORIGIN, credentials: true }))
14
16
  .get('/hello', () => ({ message: 'Hello from the server' }))
17
+ // A form: the schema the browser renders, and the same schema checking what comes back.
18
+ .get('/contact/form', () => contactForm)
19
+ // `formBody` is the form as the route's body: a refused one answers `422 { issues }` before
20
+ // the handler; `body` is what to keep (defaults filled, unknown keys dropped), typed from the form.
21
+ .post('/contact', ({ body }) => ({ received: body }), { body: formBody(contactForm) })
@@ -0,0 +1,38 @@
1
+ import { defineForm, type ValidValues } from '@20baht/engine'
2
+
3
+ /**
4
+ * One form, as JSON-shaped data: the web app renders it with `<baht-form>` and `POST /api/contact`
5
+ * validates a submission against it with the same rules. Add a field here and both sides have it:
6
+ * `defineForm` keeps the keys and field types, so the data is typed from this declaration too.
7
+ */
8
+ export const contactForm = defineForm({
9
+ form_id: 'contact',
10
+ form_name: 'Contact',
11
+ fields: [
12
+ {
13
+ order: 1,
14
+ type: 'text',
15
+ key: 'name',
16
+ label: 'Name',
17
+ validators: [{ type: 'required' }],
18
+ },
19
+ {
20
+ order: 2,
21
+ type: 'email',
22
+ key: 'email',
23
+ label: 'Email',
24
+ validators: [{ type: 'required' }],
25
+ },
26
+ {
27
+ order: 3,
28
+ type: 'textarea',
29
+ key: 'message',
30
+ label: 'Message',
31
+ max_length: 500,
32
+ validators: [{ type: 'required' }],
33
+ },
34
+ ],
35
+ })
36
+
37
+ /** What a submission that passed validation holds: `{ name: string; email: string; message: string }`. */
38
+ export type ContactMessage = ValidValues<typeof contactForm>
@@ -6,3 +6,6 @@ console.log(`server on http://localhost:${String(app.server?.port)}`)
6
6
 
7
7
  /** What the web apps type their client with (through `dist/types`, `bun run build:types`). */
8
8
  export type App = typeof app
9
+
10
+ /** The data of the forms the web apps send, derived from their schemas. */
11
+ export type { ContactMessage } from './forms/contact.form'
@@ -2,6 +2,15 @@ import { describe, expect, test } from 'bun:test'
2
2
 
3
3
  import { buildApp } from '../src/app'
4
4
 
5
+ const post = (body: unknown) =>
6
+ buildApp().handle(
7
+ new Request('http://localhost/api/contact', {
8
+ method: 'POST',
9
+ headers: { 'content-type': 'application/json' },
10
+ body: JSON.stringify(body),
11
+ }),
12
+ )
13
+
5
14
  describe('api', () => {
6
15
  test('says hello', async () => {
7
16
  const response = await buildApp().handle(new Request('http://localhost/api/hello'))
@@ -9,4 +18,24 @@ describe('api', () => {
9
18
  expect(response.status).toBe(200)
10
19
  expect(await response.json()).toEqual({ message: 'Hello from the server' })
11
20
  })
21
+
22
+ test('serves the contact form the browser renders', async () => {
23
+ const response = await buildApp().handle(new Request('http://localhost/api/contact/form'))
24
+
25
+ expect(response.status).toBe(200)
26
+ expect(await response.json()).toMatchObject({ form_name: 'Contact' })
27
+ })
28
+
29
+ test('keeps a valid submission and refuses an invalid one with the field at fault', async () => {
30
+ const good = await post({ name: 'Ada', email: 'ada@example.com', message: 'Hello' })
31
+ expect(good.status).toBe(200)
32
+ expect(await good.json()).toEqual({
33
+ received: { name: 'Ada', email: 'ada@example.com', message: 'Hello' },
34
+ })
35
+
36
+ const bad = await post({ name: 'Ada', email: 'not-an-email' })
37
+ expect(bad.status).toBe(422)
38
+ const refused = (await bad.json()) as { issues: { ref: string }[] }
39
+ expect(refused.issues.map((issue) => issue.ref).sort()).toEqual(['email', 'message'])
40
+ })
12
41
  })
@@ -34,7 +34,7 @@
34
34
  "@eslint/js": "^10.0.1",
35
35
  "@types/bun": "^1.3.0",
36
36
  "angular-eslint": "22.5.0",
37
- "@20baht/strict": "0.3.0",
37
+ "@20baht/strict": "0.3.2",
38
38
  "dependency-cruiser": "^18.3.1",
39
39
  "eslint": "^10.10.0",
40
40
  "eslint-config-prettier": "^10.1.8",
@@ -12,9 +12,19 @@ const bodyOf = (error: Record<string, unknown>): Record<string, unknown> => {
12
12
  return error
13
13
  }
14
14
 
15
+ /** A form the server refused, `{ issues: [{ ref, message }] }`: the first thing wrong with it. */
16
+ const firstIssue = (body: Record<string, unknown>): string | null => {
17
+ const issues = body['issues']
18
+ const first: unknown = Array.isArray(issues) ? issues[0] : undefined
19
+ if (!isRecord(first)) return null
20
+ const { ref, message } = first
21
+ return typeof ref === 'string' && typeof message === 'string' ? `${ref}: ${message}` : null
22
+ }
23
+
15
24
  /**
16
- * The sentence to show for a failed API call: the server's `{ message }` or Elysia's validator
17
- * `{ summary }`, as ngx-eden's `unwrap()` or a resource's `error()` carries it.
25
+ * The sentence to show for a failed API call: the server's `{ message }`, Elysia's validator
26
+ * `{ summary }` or a refused form's first issue, as ngx-eden's `unwrap()` or a resource's
27
+ * `error()` carries it.
18
28
  */
19
29
  export const describeError = (error: unknown): string => {
20
30
  if (!isRecord(error)) return FALLBACK
@@ -24,5 +34,5 @@ export const describeError = (error: unknown): string => {
24
34
  const text = body[key]
25
35
  if (typeof text === 'string' && text !== '') return text
26
36
  }
27
- return FALLBACK
37
+ return firstIssue(body) ?? FALLBACK
28
38
  }
@@ -1,2 +1,4 @@
1
1
  export { API_BASE, Api } from './api'
2
2
  export { describeError } from './errors'
3
+ /** The data of the server's forms, derived from their schemas (`defineForm`). */
4
+ export type { ContactMessage } from 'server'
@@ -19,6 +19,17 @@ describe('describeError', () => {
19
19
  )
20
20
  })
21
21
 
22
+ test('reads the first issue of a form the server refused', () => {
23
+ const issues = [
24
+ { ref: 'email', message: 'Invalid email' },
25
+ { ref: 'message', message: 'This field is required' },
26
+ ]
27
+ expect(describeError({ status: 422, value: { issues } })).toBe('email: Invalid email')
28
+ expect(describeError({ status: 422, value: { issues: [] } })).toBe(
29
+ 'Something went wrong. Try again.',
30
+ )
31
+ })
32
+
22
33
  test('reads a plain Error and falls back', () => {
23
34
  expect(describeError(new Error('boom'))).toBe('boom')
24
35
  expect(describeError({ status: 0 })).toBe('The server cannot be reached.')
@@ -9,7 +9,7 @@
9
9
  },
10
10
  "dependencies": {
11
11
  "@{{name}}/eden": "workspace:*",
12
- "@20baht/ui": "^0.3.0",
12
+ "@20baht/ui": "^0.3.2",
13
13
  "react": "^19.1.0",
14
14
  "react-dom": "^19.1.0"
15
15
  },
@@ -19,9 +19,9 @@
19
19
  "@angular/core": "^22.2.0",
20
20
  "@angular/platform-browser": "^22.2.0",
21
21
  "@angular/router": "^22.2.0",
22
- "@20baht/engine": "0.3.0",
23
- "@20baht/ui": "0.3.0",
24
- "@20baht/angular": "0.3.0",
22
+ "@20baht/engine": "0.3.2",
23
+ "@20baht/ui": "0.3.2",
24
+ "@20baht/angular": "0.3.2",
25
25
  "dompurify": "3.4.17",
26
26
  "es-module-shims": "^2.8.0",
27
27
  "flatpickr": "4.6.13",
@@ -33,7 +33,7 @@
33
33
  "@eslint/css": "^2.0.0",
34
34
  "@eslint/js": "^10.0.1",
35
35
  "@types/bun": "^1.3.0",
36
- "@20baht/strict": "0.3.0",
36
+ "@20baht/strict": "0.3.2",
37
37
  "dependency-cruiser": "^18.3.1",
38
38
  "eslint": "^10.10.0",
39
39
  "eslint-config-prettier": "^10.1.8",
@@ -17,9 +17,9 @@
17
17
  "@angular/core": "^22.2.0",
18
18
  "@angular/platform-browser": "^22.2.0",
19
19
  "@angular/router": "^22.2.0",
20
- "@20baht/engine": "0.3.0",
21
- "@20baht/ui": "0.3.0",
22
- "@20baht/angular": "0.3.0",
20
+ "@20baht/engine": "0.3.2",
21
+ "@20baht/ui": "0.3.2",
22
+ "@20baht/angular": "0.3.2",
23
23
  "dompurify": "3.4.17",
24
24
  "es-module-shims": "^2.8.0",
25
25
  "flatpickr": "4.6.13",
@@ -17,6 +17,16 @@ bun run dev # every apps/* dev script in parallel
17
17
  bun run check # lint, format, typecheck, madge, boundaries, knip, dup, build, test
18
18
  ```
19
19
 
20
+ ## The form
21
+
22
+ `apps/server/src/forms/contact.form.ts` is one form as data. The server serves it
23
+ (`GET /api/contact/form`) and validates a submission against it (`POST /api/contact`, the form as
24
+ the route's body: `formBody`); `apps/web/src/app/modules/contact` renders it with `<baht-form>`. That
25
+ is all a form needs: no workflow, no approval step. Add a field to the schema and both sides have it.
26
+ The schema is declared with `defineForm`, so its data is typed from it on both sides (`ContactMessage`):
27
+ rename a field and the server's handler and the page stop compiling until they agree. For the next
28
+ form, copy the three pieces.
29
+
20
30
  ## Add a page
21
31
 
22
32
  A component under `apps/web/src/app/modules/<page>/`, a route in `app.routes.ts`, an entry in
@@ -18,8 +18,8 @@
18
18
  "@angular/core": "^22.2.0",
19
19
  "@angular/platform-browser": "^22.2.0",
20
20
  "@angular/router": "^22.2.0",
21
- "@20baht/ui": "0.3.0",
22
- "@20baht/angular": "0.3.0",
21
+ "@20baht/ui": "0.3.2",
22
+ "@20baht/angular": "0.3.2",
23
23
  "dompurify": "3.4.17",
24
24
  "flatpickr": "4.6.13",
25
25
  "marked": "18.1.3",
@@ -8,6 +8,12 @@ export const routes: Routes = [
8
8
  title: '{{name}}',
9
9
  loadComponent: () => import('./modules/home/home.component').then((m) => m.HomeComponent),
10
10
  },
11
+ {
12
+ path: 'contact',
13
+ title: 'Contact · {{name}}',
14
+ loadComponent: () =>
15
+ import('./modules/contact/contact.component').then((m) => m.ContactComponent),
16
+ },
11
17
  {
12
18
  path: '**',
13
19
  title: 'Not found · {{name}}',
@@ -1,7 +1,10 @@
1
1
  import type { ShellNavItem } from '@20baht/ui'
2
2
 
3
3
  /** The navigator: one entry per page. `key` is the page's path, without the leading slash. */
4
- export const NAV: ShellNavItem[] = [{ key: '', label: 'Home', href: '/' }]
4
+ export const NAV: ShellNavItem[] = [
5
+ { key: '', label: 'Home', href: '/' },
6
+ { key: 'contact', label: 'Contact', href: '/contact' },
7
+ ]
5
8
 
6
9
  /** The key of the entry `url` sits under, the longest one first; `''` (Home) when none does. */
7
10
  export const currentKey = (url: string, keys: string[]): string => {
@@ -0,0 +1,91 @@
1
+ import { ChangeDetectionStrategy, Component, computed, inject, signal } from '@angular/core'
2
+ import { describeError, type ContactMessage } from '@{{name}}/kit'
3
+ import { BAHT_UI } from '@20baht/angular'
4
+ import { ContactService } from '../../services/contact.service'
5
+
6
+ /**
7
+ * A form from a schema: `<baht-form>` renders and checks it in the browser, the server checks
8
+ * the same schema again. This is the whole of "a form" in this app; nothing else is needed.
9
+ *
10
+ * The schema is typed where it is declared (`defineForm`, in the server), and the type comes
11
+ * along: `$event.data` of `(bahtSubmit)` is `ContactMessage`, so a field renamed in the schema
12
+ * is a compile error here, not a surprise in production.
13
+ */
14
+ @Component({
15
+ changeDetection: ChangeDetectionStrategy.OnPush,
16
+ imports: [BAHT_UI],
17
+ selector: 'web-contact',
18
+ styles: `
19
+ .actions {
20
+ display: flex;
21
+ gap: var(--baht-space-3);
22
+ margin-top: var(--baht-space-4);
23
+ }
24
+ `,
25
+ template: `
26
+ <div class="app-page">
27
+ <baht-page-header
28
+ heading="Contact"
29
+ description="One schema: rendered here, validated again on the server."
30
+ ></baht-page-header>
31
+ <baht-card heading="Send a message">
32
+ @if (schema.error(); as error) {
33
+ <baht-error-state
34
+ heading="The form could not be loaded"
35
+ [message]="describeError(error)"
36
+ retry-label="Try again"
37
+ (bahtRetry)="schema.reload()"
38
+ ></baht-error-state>
39
+ } @else if (schema.value(); as form) {
40
+ <baht-form
41
+ #contact="bahtForm"
42
+ [form]="form"
43
+ [busy]="sending()"
44
+ submit-on-enter
45
+ (bahtSubmit)="send($event.data)"
46
+ ></baht-form>
47
+ <div class="actions">
48
+ <baht-button [loading]="sending()" (click)="contact.element.submit()">Send</baht-button>
49
+ </div>
50
+ } @else {
51
+ <baht-skeleton variant="text"></baht-skeleton>
52
+ }
53
+ </baht-card>
54
+ @if (failed(); as message) {
55
+ <baht-alert tone="danger" [message]="message"></baht-alert>
56
+ }
57
+ @if (received(); as text) {
58
+ <baht-card heading="What the server kept">
59
+ <pre [textContent]="text"></pre>
60
+ </baht-card>
61
+ }
62
+ </div>
63
+ `,
64
+ })
65
+ export class ContactComponent {
66
+ private readonly contact = inject(ContactService)
67
+ protected readonly schema = this.contact.form()
68
+ protected readonly describeError = describeError
69
+ protected readonly sending = signal(false)
70
+ protected readonly failed = signal<string | null>(null)
71
+ private readonly kept = signal<ContactMessage | null>(null)
72
+ protected readonly received = computed(() => {
73
+ const kept = this.kept()
74
+ return kept === null ? null : JSON.stringify(kept, null, 2)
75
+ })
76
+
77
+ protected send(data: ContactMessage): void {
78
+ this.sending.set(true)
79
+ this.failed.set(null)
80
+ this.contact.send(data).subscribe({
81
+ next: (answer) => {
82
+ this.kept.set(answer.received)
83
+ this.sending.set(false)
84
+ },
85
+ error: (error: unknown) => {
86
+ this.failed.set(describeError(error))
87
+ this.sending.set(false)
88
+ },
89
+ })
90
+ }
91
+ }
@@ -0,0 +1,22 @@
1
+ import { Injectable, inject } from '@angular/core'
2
+ import { Api, type ContactMessage } from '@{{name}}/kit'
3
+ import { edenResource } from '@20baht/ngx-eden'
4
+
5
+ /** The contact form: its schema from the server, and a submission back to it. */
6
+ @Injectable({ providedIn: 'root' })
7
+ export class ContactService {
8
+ private readonly api = inject(Api).client.api
9
+
10
+ /** `GET /api/contact/form` as a resource; create it in an injection context (a field initializer). */
11
+ form() {
12
+ return edenResource(() => this.api.contact.form.get.$request())
13
+ }
14
+
15
+ /**
16
+ * `POST /api/contact`: the server validates with the schema the form was rendered from.
17
+ * `ContactMessage` is derived from that schema, so a field added there is asked for here.
18
+ */
19
+ send(data: ContactMessage) {
20
+ return this.api.contact.post(data)
21
+ }
22
+ }