@20baht/cli 0.3.1 → 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 +36 -0
- package/dist/application/generate.js +46 -3
- package/dist/args.js +5 -2
- package/dist/cli.js +21 -2
- package/dist/domain/types-plan.js +100 -0
- package/package.json +2 -1
- package/templates/angular/apps/server/package.json +2 -2
- package/templates/angular/apps/server/src/app.ts +4 -7
- package/templates/angular/apps/server/src/forms/contact.form.ts +8 -4
- package/templates/angular/apps/server/src/index.ts +3 -0
- package/templates/angular/package.json.hbs +1 -1
- package/templates/angular/packages/kit/src/errors.ts +13 -3
- package/templates/angular/packages/kit/src/index.ts +2 -0
- package/templates/angular/packages/kit/test/errors.test.ts +11 -0
- package/templates/create/apps/web/package.json.hbs +1 -1
- package/templates/federation/apps/shell/package.json +3 -3
- package/templates/new/package.json.hbs +1 -1
- package/templates/remote/package.json.hbs +3 -3
- package/templates/standalone/README.md.hbs +6 -4
- package/templates/standalone/apps/web/package.json +2 -2
- package/templates/standalone/apps/web/src/app/modules/contact/contact.component.ts.hbs +7 -3
- package/templates/standalone/apps/web/src/app/services/contact.service.ts.hbs +6 -3
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
|
|
|
@@ -245,6 +246,41 @@ Field DSL — comma-separated `key:type[:modifier…]`:
|
|
|
245
246
|
Invalid DSL (unknown type, empty options, non-numeric `min`) fails before anything is
|
|
246
247
|
written.
|
|
247
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
|
+
|
|
248
284
|
## Global flags
|
|
249
285
|
|
|
250
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(
|
|
19
|
+
throw new GenerateError(`${label(field)} contains invalid characters: ${JSON.stringify(value)}.`);
|
|
17
20
|
}
|
|
18
21
|
if (value.startsWith('/')) {
|
|
19
|
-
throw new GenerateError(
|
|
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(
|
|
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.
|
|
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,8 +20,8 @@
|
|
|
20
20
|
"test:coverage": "bun test --coverage"
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@20baht/engine": "0.3.
|
|
24
|
-
"@20baht/validator": "^0.3.
|
|
23
|
+
"@20baht/engine": "0.3.2",
|
|
24
|
+
"@20baht/validator": "^0.3.2",
|
|
25
25
|
"@elysiajs/cors": "^1.4.3",
|
|
26
26
|
"elysia": "^1.4.31"
|
|
27
27
|
},
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { cors } from '@elysiajs/cors'
|
|
2
|
-
import {
|
|
2
|
+
import { formBody } from '@20baht/validator/elysia'
|
|
3
3
|
import { Elysia } from 'elysia'
|
|
4
4
|
import { contactForm } from './forms/contact.form'
|
|
5
5
|
|
|
@@ -16,9 +16,6 @@ export const buildApp = () =>
|
|
|
16
16
|
.get('/hello', () => ({ message: 'Hello from the server' }))
|
|
17
17
|
// A form: the schema the browser renders, and the same schema checking what comes back.
|
|
18
18
|
.get('/contact/form', () => contactForm)
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
// `result.data` is what to keep: defaults filled, anything the rules hide cleared.
|
|
23
|
-
return { received: result.data }
|
|
24
|
-
})
|
|
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) })
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { defineForm, type ValidValues } from '@20baht/engine'
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
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
|
|
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.
|
|
6
7
|
*/
|
|
7
|
-
export const contactForm
|
|
8
|
+
export const contactForm = defineForm({
|
|
8
9
|
form_id: 'contact',
|
|
9
10
|
form_name: 'Contact',
|
|
10
11
|
fields: [
|
|
@@ -31,4 +32,7 @@ export const contactForm: FormDefinition = {
|
|
|
31
32
|
validators: [{ type: 'required' }],
|
|
32
33
|
},
|
|
33
34
|
],
|
|
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'
|
|
@@ -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 }
|
|
17
|
-
* `{ summary }
|
|
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
|
}
|
|
@@ -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.')
|
|
@@ -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.
|
|
23
|
-
"@20baht/ui": "0.3.
|
|
24
|
-
"@20baht/angular": "0.3.
|
|
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",
|
|
@@ -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.
|
|
21
|
-
"@20baht/ui": "0.3.
|
|
22
|
-
"@20baht/angular": "0.3.
|
|
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",
|
|
@@ -20,10 +20,12 @@ bun run check # lint, format, typecheck, madge, boundaries, knip, dup, buil
|
|
|
20
20
|
## The form
|
|
21
21
|
|
|
22
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`,
|
|
24
|
-
`
|
|
25
|
-
a form needs: no workflow, no approval step. Add a field to the schema and both sides have it.
|
|
26
|
-
|
|
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.
|
|
27
29
|
|
|
28
30
|
## Add a page
|
|
29
31
|
|
|
@@ -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.
|
|
22
|
-
"@20baht/angular": "0.3.
|
|
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",
|
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import { ChangeDetectionStrategy, Component, computed, inject, signal } from '@angular/core'
|
|
2
|
-
import { describeError } from '@{{name}}/kit'
|
|
2
|
+
import { describeError, type ContactMessage } from '@{{name}}/kit'
|
|
3
3
|
import { BAHT_UI } from '@20baht/angular'
|
|
4
4
|
import { ContactService } from '../../services/contact.service'
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* A form from a schema: `<baht-form>` renders and checks it in the browser, the server checks
|
|
8
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.
|
|
9
13
|
*/
|
|
10
14
|
@Component({
|
|
11
15
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
|
@@ -64,13 +68,13 @@ export class ContactComponent {
|
|
|
64
68
|
protected readonly describeError = describeError
|
|
65
69
|
protected readonly sending = signal(false)
|
|
66
70
|
protected readonly failed = signal<string | null>(null)
|
|
67
|
-
private readonly kept = signal<
|
|
71
|
+
private readonly kept = signal<ContactMessage | null>(null)
|
|
68
72
|
protected readonly received = computed(() => {
|
|
69
73
|
const kept = this.kept()
|
|
70
74
|
return kept === null ? null : JSON.stringify(kept, null, 2)
|
|
71
75
|
})
|
|
72
76
|
|
|
73
|
-
protected send(data:
|
|
77
|
+
protected send(data: ContactMessage): void {
|
|
74
78
|
this.sending.set(true)
|
|
75
79
|
this.failed.set(null)
|
|
76
80
|
this.contact.send(data).subscribe({
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Injectable, inject } from '@angular/core'
|
|
2
|
-
import { Api } from '@{{name}}/kit'
|
|
2
|
+
import { Api, type ContactMessage } from '@{{name}}/kit'
|
|
3
3
|
import { edenResource } from '@20baht/ngx-eden'
|
|
4
4
|
|
|
5
5
|
/** The contact form: its schema from the server, and a submission back to it. */
|
|
@@ -12,8 +12,11 @@ export class ContactService {
|
|
|
12
12
|
return edenResource(() => this.api.contact.form.get.$request())
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
-
/**
|
|
16
|
-
|
|
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) {
|
|
17
20
|
return this.api.contact.post(data)
|
|
18
21
|
}
|
|
19
22
|
}
|