@sincpro/web-framework 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -1
- package/dist/codegen/cli.d.ts +2 -0
- package/dist/codegen/cli.js +82 -0
- package/dist/codegen/client.d.ts +14 -0
- package/dist/codegen/client.js +178 -0
- package/dist/codegen/domain.d.ts +14 -0
- package/dist/codegen/domain.js +195 -0
- package/dist/codegen/entities.d.ts +14 -0
- package/dist/codegen/entities.js +158 -0
- package/dist/codegen/index.d.ts +11 -0
- package/dist/codegen/index.js +9 -0
- package/dist/codegen/metamodel.d.ts +89 -0
- package/dist/codegen/metamodel.js +1 -0
- package/dist/codegen/names.d.ts +40 -0
- package/dist/codegen/names.js +114 -0
- package/dist/codegen/rest.d.ts +31 -0
- package/dist/codegen/rest.js +27 -0
- package/dist/core/cache.js +7 -0
- package/dist/core/contract.d.ts +34 -0
- package/dist/core/contract.js +41 -0
- package/dist/core/entity.d.ts +77 -9
- package/dist/core/entity.js +51 -6
- package/dist/core/index.d.ts +4 -3
- package/dist/core/index.js +4 -3
- package/dist/core/memory.d.ts +3 -0
- package/dist/core/memory.js +9 -0
- package/dist/core/relation.d.ts +11 -1
- package/dist/core/relation.js +30 -2
- package/dist/core/rest.d.ts +15 -0
- package/dist/core/rest.js +16 -0
- package/dist/core/transport.d.ts +11 -0
- package/dist/core/transport.js +9 -0
- package/dist/react/index.d.ts +2 -1
- package/dist/react/index.js +1 -0
- package/dist/react/useCommand.d.ts +15 -5
- package/dist/react/useCommand.js +7 -4
- package/dist/react/useListing.d.ts +5 -4
- package/dist/react/useListing.js +3 -2
- package/dist/react/useNameOf.d.ts +13 -0
- package/dist/react/useNameOf.js +44 -0
- package/dist/web/list/EntityList.d.ts +5 -4
- package/dist/web/list/EntityList.js +1 -1
- package/dist/web/list/presentation.d.ts +3 -3
- package/dist/web/list/presentation.js +1 -0
- package/dist/web/list/rowCommands.d.ts +16 -12
- package/dist/web/list/rowCommands.js +3 -2
- package/dist/web/record/CommandButton.d.ts +9 -6
- package/dist/web/record/edit.js +19 -7
- package/dist/web/record/lines.js +7 -1
- package/package.json +16 -5
package/README.md
CHANGED
|
@@ -392,7 +392,35 @@ Three folders, one direction — `make doctor` keeps the arrows:
|
|
|
392
392
|
| `web/record` | one record: `RecordField`, `factsOf`, `RelatedList`, `EntityPicker`, `cardOf` | works outside a workspace (no composer) |
|
|
393
393
|
| `web/workspace` | the composer: `entityView`, `openIn`, `RelatedRecord`, `<SincproApp>` | where it opens, the application context |
|
|
394
394
|
|
|
395
|
-
Everything is imported from `@sincpro/web-framework`.
|
|
395
|
+
Everything is imported from `@sincpro/web-framework`. Code that draws nothing — a script, a
|
|
396
|
+
test in Node, a generated client — imports `@sincpro/web-framework/core`, which loads no React.
|
|
397
|
+
|
|
398
|
+
A fourth folder, `codegen`, is a build step: no screen loads it (`make doctor`).
|
|
399
|
+
|
|
400
|
+
### From the contract
|
|
401
|
+
|
|
402
|
+
A service built on sincpro_framework exports what it publishes — its models and every operation,
|
|
403
|
+
what each one is for its entity and how each wire reaches it — as one client contract per
|
|
404
|
+
bounded context. `sincpro-web generate` writes, from it, what the screens used to declare by
|
|
405
|
+
hand:
|
|
406
|
+
|
|
407
|
+
```bash
|
|
408
|
+
python -m sincpro_framework.entrypoints export-client-contract app.http:gateways contracts/
|
|
409
|
+
npx sincpro-web generate contracts/project.contract.json --out src/generated/project --base /v1
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
| File | What it holds |
|
|
413
|
+
| --------------- | --------------------------------------------------------------------------------------------------- |
|
|
414
|
+
| `domain.ts` | the DTOs — every model, every operation's input and answer — with the server's own docs. Types only |
|
|
415
|
+
| `client.ts` | every operation as data, and `clientOf(transport)`: a typed method per page, record and write |
|
|
416
|
+
| `entities.ts` | an `entity<T, C>()` per model a screen lists: its routes and Commands, read off what each one is |
|
|
417
|
+
| `contract.json` | the snapshot they came from: `metasOf(contract, "project")` preloads the definitions |
|
|
418
|
+
|
|
419
|
+
What is generated is never edited; a screen extends it (`presented(issues, { row })`, a type
|
|
420
|
+
with `&`). Keep the folder out of prettier and eslint, and let CI regenerate and compare it.
|
|
421
|
+
At runtime nothing is closed: the transport keeps reading the live definitions. How an
|
|
422
|
+
application adopts it — where each file goes, what is written by hand, how a hand-written screen
|
|
423
|
+
moves to the generated one — is [`docs/ADOPCION.md`](docs/ADOPCION.md) (in Spanish).
|
|
396
424
|
|
|
397
425
|
## Where it stands
|
|
398
426
|
|
|
@@ -406,6 +434,13 @@ Everything is imported from `@sincpro/web-framework`.
|
|
|
406
434
|
| `useLookup`, `EntityPicker` | Literal search: a many2one select, ⌘K | ✅ |
|
|
407
435
|
| `useRecord` + `RecordField`, `dirtyOf` | Editing: hints evaluated live, preview, save with version (409), server drafts | ✅ |
|
|
408
436
|
| `useCommand`, `CommandButton` | An entity's actions, with a dry run before what destroys | ✅ |
|
|
437
|
+
| `entity<T, C>` (`CommandBodies`) | Typed Commands: a name the entity does not declare, or a wrong body, does not compile | ✅ |
|
|
438
|
+
| `entity<T, C, A>` (`CommandAnswers`) | What each Command answers, typed: `run(…)` returns it with no type argument written | ✅ |
|
|
439
|
+
| `readRoute`, `Transport.read` | A GET of the context's own (`/me`), neither a page nor a record | ✅ |
|
|
440
|
+
| A key alone (`EntityID`), `useNameOf` | A key that names whose record it is, drawn as a many2one: a picker, and the name when read | ✅ |
|
|
441
|
+
| `versionsOf`, `onVersionDrift` | A snapshot behind the server is told once per model — never an error | ✅ |
|
|
442
|
+
| `sincpro-web generate` | A context's DTOs, client and entities out of its exported client contract | ✅ |
|
|
443
|
+
| `metasOf`, `bodyFor` (`target`) | Definitions preloaded from that snapshot; a Command's record written where its body names it | ✅ |
|
|
409
444
|
| `useHistory` | Business events in `Record.Activity` (comments: backend first) | ✅ |
|
|
410
445
|
| `entityView` | An entity as a composer view: list, record, ⌘K search | ✅ |
|
|
411
446
|
| `<SincproApp>` | The application context in one place, the workspace dressed as web-ui (`webUiSkin`) | ✅ |
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { clientFileOf } from "./client.js";
|
|
5
|
+
import { domainFileOf } from "./domain.js";
|
|
6
|
+
import { entitiesFileOf } from "./entities.js";
|
|
7
|
+
import { aliasOf } from "./names.js";
|
|
8
|
+
/**
|
|
9
|
+
* `sincpro-web generate <contract.json> --out <dir> [--domain <name>] [--base <path>]` — what an
|
|
10
|
+
* application's `make client` runs, once per bounded context, over the client contract
|
|
11
|
+
* sincpro_framework exported (`export-client-contract`):
|
|
12
|
+
*
|
|
13
|
+
* - `domain.ts`: the DTOs, only types;
|
|
14
|
+
* - `client.ts`: every operation as data, and `clientOf(transport)`;
|
|
15
|
+
* - `entities.ts`: an `entity<T, C>()` per model a screen can list;
|
|
16
|
+
* - `contract.json`: the snapshot they were written from, for `metasOf`.
|
|
17
|
+
*
|
|
18
|
+
* A bare metamodel (`export_metamodel`, no bindings) writes `domain.ts` and `contract.json` only.
|
|
19
|
+
*
|
|
20
|
+
* Context: it writes only into `--out`, and the same bytes for the same contract, so `make
|
|
21
|
+
* verify-client` regenerates and fails on any difference. The folder is the generator's: keep
|
|
22
|
+
* it out of the application's prettier and eslint, or a formatter rewrites what was generated.
|
|
23
|
+
*/
|
|
24
|
+
const USAGE = "usage: sincpro-web generate <contract.json> --out <dir> [--domain <name>] [--base <path>]";
|
|
25
|
+
/** JSON with every key sorted: the snapshot reads the same however the server ordered it. */
|
|
26
|
+
function canonical(value) {
|
|
27
|
+
if (Array.isArray(value))
|
|
28
|
+
return value.map(canonical);
|
|
29
|
+
if (value === null || typeof value !== "object")
|
|
30
|
+
return value;
|
|
31
|
+
return Object.fromEntries(Object.keys(value)
|
|
32
|
+
.sort()
|
|
33
|
+
.map((key) => [key, canonical(value[key])]));
|
|
34
|
+
}
|
|
35
|
+
/** The command, its source and its flags — or `undefined` when they do not read as usage says. */
|
|
36
|
+
function parsed(args) {
|
|
37
|
+
const [command, source, ...rest] = args;
|
|
38
|
+
if (command !== "generate" || source === undefined)
|
|
39
|
+
return undefined;
|
|
40
|
+
const flags = new Map();
|
|
41
|
+
for (let at = 0; at < rest.length; at += 2) {
|
|
42
|
+
const flag = rest[at];
|
|
43
|
+
const value = rest[at + 1];
|
|
44
|
+
if (flag === undefined || value === undefined || !flag.startsWith("--"))
|
|
45
|
+
return undefined;
|
|
46
|
+
flags.set(flag, value);
|
|
47
|
+
}
|
|
48
|
+
const out = flags.get("--out");
|
|
49
|
+
const known = new Set(["--out", "--domain", "--base"]);
|
|
50
|
+
if (out === undefined || [...flags.keys()].some((one) => !known.has(one)))
|
|
51
|
+
return undefined;
|
|
52
|
+
const domain = flags.get("--domain");
|
|
53
|
+
const base = flags.get("--base");
|
|
54
|
+
return {
|
|
55
|
+
source,
|
|
56
|
+
out,
|
|
57
|
+
options: {
|
|
58
|
+
...(domain === undefined ? {} : { domain }),
|
|
59
|
+
...(base === undefined ? {} : { base }),
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function main(args) {
|
|
64
|
+
const asked = parsed(args);
|
|
65
|
+
if (asked === undefined) {
|
|
66
|
+
console.error(USAGE);
|
|
67
|
+
return 2;
|
|
68
|
+
}
|
|
69
|
+
const metamodel = JSON.parse(readFileSync(asked.source, "utf8"));
|
|
70
|
+
const files = { "domain.ts": domainFileOf(metamodel) };
|
|
71
|
+
if (metamodel.bindings !== undefined) {
|
|
72
|
+
files["client.ts"] = clientFileOf(metamodel, asked.options);
|
|
73
|
+
files["entities.ts"] = entitiesFileOf(metamodel, asked.options);
|
|
74
|
+
}
|
|
75
|
+
files["contract.json"] = `${JSON.stringify(canonical(metamodel), null, 2)}\n`;
|
|
76
|
+
mkdirSync(asked.out, { recursive: true });
|
|
77
|
+
for (const [name, source] of Object.entries(files))
|
|
78
|
+
writeFileSync(join(asked.out, name), source);
|
|
79
|
+
console.log(`✓ ${aliasOf(metamodel)} → ${asked.out} (${Object.keys(files).join(", ")})`);
|
|
80
|
+
return 0;
|
|
81
|
+
}
|
|
82
|
+
process.exitCode = main(process.argv.slice(2));
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { Metamodel } from "./metamodel.js";
|
|
2
|
+
import { type GenerateOptions } from "./rest.js";
|
|
3
|
+
/**
|
|
4
|
+
* The TypeScript of the client of `metamodel`, as the text of one file next to its `domain.ts`.
|
|
5
|
+
*
|
|
6
|
+
* 1. Every operation, by its local name, as data: identity, role, `query`, entities, targets
|
|
7
|
+
* and the binding of each wire that publishes it.
|
|
8
|
+
* 2. Per operation REST reaches, how a transport calls it (`callOf`): a page, a record, a write
|
|
9
|
+
* — or none, said in the client's own doc.
|
|
10
|
+
* 3. The routes of the writes, read once (`writeRoute`).
|
|
11
|
+
* Final: `clientOf(transport)`, a method per operation reached, named by `methodOf`; two with
|
|
12
|
+
* one name are refused, naming both.
|
|
13
|
+
*/
|
|
14
|
+
export declare function clientFileOf(metamodel: Metamodel, options?: GenerateOptions): string;
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { aliasOf, claimed, deprecationOf, docOf, DOMAIN_MODULE, FRAMEWORK_CORE, headerOf, identifierOf, localOf, methodOf, recordLiteral, sorted, } from "./names.js";
|
|
2
|
+
import { ownerOf, restOf, WRITES, } from "./rest.js";
|
|
3
|
+
/**
|
|
4
|
+
* The client of a bounded context as TypeScript: every operation as data, and a method for each
|
|
5
|
+
* one REST reaches the way a `Transport` sends — over `@sincpro/web-framework/core`, so a script,
|
|
6
|
+
* a test or a hook of its own calls the service typed, with no screen.
|
|
7
|
+
*
|
|
8
|
+
* Context: a method only writes down the route the contract published and hands the call to the
|
|
9
|
+
* transport, which keeps the rules — the `Idempotency-Key`, the `Problem`, the model's version.
|
|
10
|
+
* A GET is a page (`list`), one record (`one`), or — a Query of the context's own, `GET /me` —
|
|
11
|
+
* a read of its answer as it came (`readRoute`, over a transport that has `read`). A GET's
|
|
12
|
+
* keys in its path are required parameters; every other field is an optional one.
|
|
13
|
+
*/
|
|
14
|
+
/** A search's fields a page asks with, not the screen: the criteria, and its cursor inside it. */
|
|
15
|
+
const PAGED = new Set(["criteria", "cursor"]);
|
|
16
|
+
/** A GET's parameters: the path's keys, and the rest of its input but what a page asks with. */
|
|
17
|
+
function askedOf(operation, rest, paged) {
|
|
18
|
+
const path = [...rest.fields].sort();
|
|
19
|
+
const query = Object.keys(operation.input.properties ?? {})
|
|
20
|
+
.filter((one) => !path.includes(one) && !(paged && PAGED.has(one)))
|
|
21
|
+
.sort();
|
|
22
|
+
return { path, query };
|
|
23
|
+
}
|
|
24
|
+
function callOf(metamodel, operation, rest) {
|
|
25
|
+
if (rest === undefined)
|
|
26
|
+
return { kind: "none", why: "REST does not publish it" };
|
|
27
|
+
if (WRITES.has(rest.method))
|
|
28
|
+
return { kind: "send" };
|
|
29
|
+
const owner = ownerOf(metamodel, operation);
|
|
30
|
+
if (operation.role === "search" && owner !== undefined && owner in metamodel.models)
|
|
31
|
+
return { kind: "list", entity: owner, ...askedOf(operation, rest, true) };
|
|
32
|
+
const field = owner === undefined ? undefined : operation.targets[owner];
|
|
33
|
+
const record = rest.fields.length === 1 && rest.fields[0] === field;
|
|
34
|
+
if (operation.role === "get" && owner !== undefined && field !== undefined && record)
|
|
35
|
+
return { kind: "one", entity: owner, field };
|
|
36
|
+
// Any other GET — a Query of the context's own, `GET /me` — is read as it answers.
|
|
37
|
+
return { kind: "read", ...askedOf(operation, rest, false) };
|
|
38
|
+
}
|
|
39
|
+
/** A parameter list's TypeScript: the path's keys required, the rest optional, all as text. */
|
|
40
|
+
function paramsOf(asked) {
|
|
41
|
+
const union = (names) => names.map((one) => JSON.stringify(one)).join(" | ");
|
|
42
|
+
if (asked.path.length === 0 && asked.query.length === 0)
|
|
43
|
+
return { signature: "", route: (path) => JSON.stringify(path) };
|
|
44
|
+
const required = asked.path.length === 0 ? "" : `Readonly<Record<${union(asked.path)}, string>>`;
|
|
45
|
+
const optional = asked.query.length === 0 ? "" : `Partial<Record<${union(asked.query)}, string>>`;
|
|
46
|
+
const type = [required, optional].filter((one) => one !== "").join(" & ");
|
|
47
|
+
return {
|
|
48
|
+
signature: `params${asked.path.length === 0 ? "?" : ""}: ${type}`,
|
|
49
|
+
route: (path) => `listRoute(${JSON.stringify(path)}, params)`,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/** The data of one operation: what it is, and how each wire reaches it. */
|
|
53
|
+
function dataOf(metamodel, identity, operation, rest) {
|
|
54
|
+
const lines = [
|
|
55
|
+
` identity: ${JSON.stringify(identity)},`,
|
|
56
|
+
` role: ${JSON.stringify(operation.role)},`,
|
|
57
|
+
` query: ${operation.query},`,
|
|
58
|
+
` entities: ${JSON.stringify(operation.entities)},`,
|
|
59
|
+
` targets: ${recordLiteral(operation.targets)},`,
|
|
60
|
+
];
|
|
61
|
+
if (rest !== undefined)
|
|
62
|
+
lines.push(` rest: { method: ${JSON.stringify(rest.method)}, path: ${JSON.stringify(rest.path)} },`);
|
|
63
|
+
const rpc = metamodel.bindings?.rpc?.[identity];
|
|
64
|
+
if (rpc !== undefined)
|
|
65
|
+
lines.push(` rpc: { method: ${JSON.stringify(rpc.method)} },`);
|
|
66
|
+
const grpc = metamodel.bindings?.grpc?.[identity];
|
|
67
|
+
if (grpc !== undefined)
|
|
68
|
+
lines.push(` grpc: { method: ${JSON.stringify(grpc.method)} },`);
|
|
69
|
+
const mcp = metamodel.bindings?.mcp?.[identity];
|
|
70
|
+
if (mcp !== undefined)
|
|
71
|
+
lines.push(` mcp: { tool: ${JSON.stringify(mcp.tool)} },`);
|
|
72
|
+
return ` ${localOf(metamodel, identity)}: {\n${lines.join("\n")}\n },`;
|
|
73
|
+
}
|
|
74
|
+
function methodSourceOf(local, method, call, rest, doc) {
|
|
75
|
+
if (call.kind === "list") {
|
|
76
|
+
const entity = `dto.${identifierOf(call.entity)}`;
|
|
77
|
+
const params = paramsOf(call);
|
|
78
|
+
const signature = params.signature === "" ? "" : `, ${params.signature}`;
|
|
79
|
+
return `${doc} ${method}: (criteria: Criteria<${entity}>${signature}) =>\n transport.list<${entity}>(${params.route(rest.path)}, criteria),`;
|
|
80
|
+
}
|
|
81
|
+
if (call.kind === "read") {
|
|
82
|
+
const params = paramsOf(call);
|
|
83
|
+
return `${doc} ${method}: (${params.signature}) =>\n readRoute<dto.${local}Answer>(transport, ${params.route(rest.path)}),`;
|
|
84
|
+
}
|
|
85
|
+
if (call.kind === "one") {
|
|
86
|
+
const path = rest.path.replace(`{${call.field}}`, "${encodeURIComponent(id)}");
|
|
87
|
+
return `${doc} ${method}: (id: string) =>\n transport.one<dto.${identifierOf(call.entity)}>(\`${path}\`),`;
|
|
88
|
+
}
|
|
89
|
+
const id = rest.fields.includes("id")
|
|
90
|
+
? "body.id === undefined ? undefined : String(body.id)"
|
|
91
|
+
: "undefined";
|
|
92
|
+
return [
|
|
93
|
+
`${doc} ${method}: (body: dto.${local}, options?: SendOptions) =>`,
|
|
94
|
+
` transport.send<dto.${local}Answer>(`,
|
|
95
|
+
` ${JSON.stringify(rest.method)},`,
|
|
96
|
+
` pathFor(routes.${method}, ${id}, body),`,
|
|
97
|
+
` body,`,
|
|
98
|
+
` undefined,`,
|
|
99
|
+
` options,`,
|
|
100
|
+
` ),`,
|
|
101
|
+
].join("\n");
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The TypeScript of the client of `metamodel`, as the text of one file next to its `domain.ts`.
|
|
105
|
+
*
|
|
106
|
+
* 1. Every operation, by its local name, as data: identity, role, `query`, entities, targets
|
|
107
|
+
* and the binding of each wire that publishes it.
|
|
108
|
+
* 2. Per operation REST reaches, how a transport calls it (`callOf`): a page, a record, a write
|
|
109
|
+
* — or none, said in the client's own doc.
|
|
110
|
+
* 3. The routes of the writes, read once (`writeRoute`).
|
|
111
|
+
* Final: `clientOf(transport)`, a method per operation reached, named by `methodOf`; two with
|
|
112
|
+
* one name are refused, naming both.
|
|
113
|
+
*/
|
|
114
|
+
export function clientFileOf(metamodel, options = {}) {
|
|
115
|
+
const claim = claimed();
|
|
116
|
+
const operations = sorted(metamodel.operations);
|
|
117
|
+
const data = [];
|
|
118
|
+
const routes = [];
|
|
119
|
+
const methods = [];
|
|
120
|
+
const unreached = [];
|
|
121
|
+
let lists = false;
|
|
122
|
+
let paged = false;
|
|
123
|
+
let reads = false;
|
|
124
|
+
let sends = false;
|
|
125
|
+
for (const [identity, operation] of operations) {
|
|
126
|
+
const local = localOf(metamodel, identity);
|
|
127
|
+
const rest = restOf(metamodel, identity, options);
|
|
128
|
+
data.push(dataOf(metamodel, identity, operation, rest));
|
|
129
|
+
const call = callOf(metamodel, operation, rest);
|
|
130
|
+
if (call.kind === "none" || rest === undefined) {
|
|
131
|
+
unreached.push(`\`${local}\`: ${call.kind === "none" ? call.why : ""}.`);
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
const method = methodOf(local);
|
|
135
|
+
claim(method, `operation ${identity}`);
|
|
136
|
+
const doc = docOf([operation.description, deprecationOf(metamodel, operation)], " ");
|
|
137
|
+
methods.push(methodSourceOf(local, method, call, rest, doc));
|
|
138
|
+
if (call.kind === "list" || call.kind === "read") {
|
|
139
|
+
paged ||= call.kind === "list";
|
|
140
|
+
reads ||= call.kind === "read";
|
|
141
|
+
lists ||= call.path.length + call.query.length > 0;
|
|
142
|
+
}
|
|
143
|
+
if (call.kind === "send") {
|
|
144
|
+
sends = true;
|
|
145
|
+
routes.push(` ${method}: writeRoute(${JSON.stringify(`${rest.method} ${rest.path}`)}),`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const core = [
|
|
149
|
+
...(lists ? ["listRoute"] : []),
|
|
150
|
+
...(sends ? ["pathFor"] : []),
|
|
151
|
+
...(reads ? ["readRoute"] : []),
|
|
152
|
+
...(sends ? ["type SendOptions"] : []),
|
|
153
|
+
"type Transport",
|
|
154
|
+
...(sends ? ["writeRoute"] : []),
|
|
155
|
+
];
|
|
156
|
+
const imports = [
|
|
157
|
+
...(paged ? ['import type { Criteria } from "@sincpro/criteria";'] : []),
|
|
158
|
+
`import { ${core.join(", ")} } from "${FRAMEWORK_CORE}";`,
|
|
159
|
+
"",
|
|
160
|
+
`import type * as dto from "${DOMAIN_MODULE}";`,
|
|
161
|
+
].join("\n");
|
|
162
|
+
const client = [
|
|
163
|
+
"/**",
|
|
164
|
+
` * «${aliasOf(metamodel)}» over a transport: a method for each operation REST reaches as a`,
|
|
165
|
+
" * page, a record, a read of its own or a write.",
|
|
166
|
+
...(unreached.length === 0
|
|
167
|
+
? []
|
|
168
|
+
: [" *", " * Without a method here:", ...unreached.map((one) => ` * - ${one}`)]),
|
|
169
|
+
" */",
|
|
170
|
+
].join("\n");
|
|
171
|
+
return `${[
|
|
172
|
+
headerOf("The client", metamodel),
|
|
173
|
+
imports,
|
|
174
|
+
`/** Every operation of «${aliasOf(metamodel)}», as data: what it is, and how each wire reaches it. */\nexport const operations = {\n${data.join("\n")}\n} as const;`,
|
|
175
|
+
...(routes.length === 0 ? [] : [`const routes = {\n${routes.join("\n")}\n};`]),
|
|
176
|
+
`${client}\nexport function clientOf(transport: Transport) {\n return {\n${methods.join("\n")}\n };\n}`,
|
|
177
|
+
].join("\n\n")}\n`;
|
|
178
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { Metamodel } from "./metamodel.js";
|
|
2
|
+
/**
|
|
3
|
+
* The TypeScript of every DTO of `metamodel`, as the text of one file.
|
|
4
|
+
*
|
|
5
|
+
* 1. The models, by name: an entity's contract, a related model by its own name.
|
|
6
|
+
* 2. Each operation, by its local name (its identity without `<context>.`): its input as
|
|
7
|
+
* `<Name>` and its answer as `<Name>Answer`.
|
|
8
|
+
* 3. The shared definitions those reach — and the ones those reach, until none is new —, but
|
|
9
|
+
* never one a package of the stack already types (`Criteria`).
|
|
10
|
+
* Final: a header that says where it came from and not to edit it, the imports, then models,
|
|
11
|
+
* definitions and operations, each sorted by name; two of them with one TypeScript name are
|
|
12
|
+
* refused, naming both.
|
|
13
|
+
*/
|
|
14
|
+
export declare function domainFileOf(metamodel: Metamodel): string;
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { claimed, contextOf, deprecationOf, docOf, headerOf, identifierOf, keyOf, localOf, sorted, } from "./names.js";
|
|
2
|
+
/**
|
|
3
|
+
* The DTOs of a bounded context as TypeScript, out of the contract sincpro_framework exports:
|
|
4
|
+
* a type per model, per shared definition a model or an operation reaches, and per operation's
|
|
5
|
+
* input and answer. Only types — nothing in the file runs.
|
|
6
|
+
*
|
|
7
|
+
* Context: the file is a snapshot for whoever writes code — a person, or an agent reading the
|
|
8
|
+
* repository —, never the truth at runtime: the transport keeps reading the live definition and
|
|
9
|
+
* revalidates it by `model_version`. So it is written the same way for the same contract (every
|
|
10
|
+
* key sorted, byte for byte, which is what `make verify-client` compares) and never edited; an
|
|
11
|
+
* application extends a type by composition (`Wire & {…}`).
|
|
12
|
+
*
|
|
13
|
+
* criteria's grammar comes with every metamodel (`$defs.Criteria`); `@sincpro/criteria` already
|
|
14
|
+
* types it, so it is imported, never written a second time.
|
|
15
|
+
*
|
|
16
|
+
* domainFileOf(JSON.parse(readFileSync("project.contract.json", "utf8")))
|
|
17
|
+
*/
|
|
18
|
+
const MODELS = "#/models/";
|
|
19
|
+
const DEFINITIONS = "#/$defs/";
|
|
20
|
+
/** A shared definition a package of the stack already types: imported, never written again. */
|
|
21
|
+
const IMPORTED = {
|
|
22
|
+
Criteria: { name: "Criteria", from: "@sincpro/criteria" },
|
|
23
|
+
};
|
|
24
|
+
/** The field types whose value is the record itself, not a key that names it. */
|
|
25
|
+
const RELATIONAL = new Set(["many2one", "one2many", "many2many", "embedded"]);
|
|
26
|
+
/** A related record: in an answer only when the read expands it. */
|
|
27
|
+
const EXPANDED = new Set(["many2one", "one2many", "many2many"]);
|
|
28
|
+
const SIMPLE_TYPE = /^[A-Za-z0-9_$.]+$/;
|
|
29
|
+
function union(members) {
|
|
30
|
+
const distinct = [...new Set(members)];
|
|
31
|
+
if (distinct.includes("unknown"))
|
|
32
|
+
return "unknown";
|
|
33
|
+
return distinct.join(" | ");
|
|
34
|
+
}
|
|
35
|
+
function arrayOf(item) {
|
|
36
|
+
return SIMPLE_TYPE.test(item) ? `${item}[]` : `Array<${item}>`;
|
|
37
|
+
}
|
|
38
|
+
/** Whose record a key names — `EntityID[Customer]` on the server —, said where it is written. */
|
|
39
|
+
function keyNote(schema) {
|
|
40
|
+
const said = schema["x-sincpro"];
|
|
41
|
+
if (said?.relation == null || RELATIONAL.has(said.type ?? ""))
|
|
42
|
+
return undefined;
|
|
43
|
+
return `The key of a \`${said.relation}\`.`;
|
|
44
|
+
}
|
|
45
|
+
function scopeOf(metamodel) {
|
|
46
|
+
const definitions = metamodel.$defs ?? {};
|
|
47
|
+
const scope = {
|
|
48
|
+
reached: new Set(),
|
|
49
|
+
imports: new Set(),
|
|
50
|
+
refer: (ref) => {
|
|
51
|
+
const model = ref.startsWith(MODELS);
|
|
52
|
+
if (!model && !ref.startsWith(DEFINITIONS))
|
|
53
|
+
throw new Error(`"${ref}" points outside the metamodel of ${contextOf(metamodel)}`);
|
|
54
|
+
const name = ref.slice(model ? MODELS.length : DEFINITIONS.length);
|
|
55
|
+
// A model's own contract names a related model as a definition (`#/$defs/Run`).
|
|
56
|
+
if (model || name in metamodel.models) {
|
|
57
|
+
if (!(name in metamodel.models))
|
|
58
|
+
throw new Error(`"${ref}" names no model of ${contextOf(metamodel)}`);
|
|
59
|
+
return identifierOf(name);
|
|
60
|
+
}
|
|
61
|
+
const imported = IMPORTED[name];
|
|
62
|
+
if (imported !== undefined) {
|
|
63
|
+
scope.imports.add(name);
|
|
64
|
+
return imported.name;
|
|
65
|
+
}
|
|
66
|
+
if (!(name in definitions))
|
|
67
|
+
throw new Error(`"${ref}" names no definition of ${contextOf(metamodel)}`);
|
|
68
|
+
scope.reached.add(name);
|
|
69
|
+
return identifierOf(name);
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
return scope;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Whether a property may be absent. In a record a model describes, every field comes but a
|
|
76
|
+
* related record, which comes only when the read expands it: the server writes the whole record,
|
|
77
|
+
* and its contract lists as required only what has no default (most fields have one). Anywhere
|
|
78
|
+
* else — an operation's input or answer, a shared definition — `required` says it.
|
|
79
|
+
*/
|
|
80
|
+
function optional(name, property, schema, record) {
|
|
81
|
+
if (record)
|
|
82
|
+
return EXPANDED.has(property["x-sincpro"]?.type ?? "");
|
|
83
|
+
return !(schema.required ?? []).includes(name);
|
|
84
|
+
}
|
|
85
|
+
function objectOf(schema, scope, depth, record) {
|
|
86
|
+
const properties = sorted(schema.properties ?? {});
|
|
87
|
+
if (properties.length === 0) {
|
|
88
|
+
const extra = schema.additionalProperties;
|
|
89
|
+
if (extra === false)
|
|
90
|
+
return "Record<string, never>";
|
|
91
|
+
const value = extra === undefined || extra === true ? "unknown" : typeOf(extra, scope, depth, record);
|
|
92
|
+
return `Record<string, ${value}>`;
|
|
93
|
+
}
|
|
94
|
+
const pad = " ".repeat(depth + 1);
|
|
95
|
+
const lines = properties.map(([name, property]) => {
|
|
96
|
+
const doc = docOf([property.description, keyNote(property)], pad);
|
|
97
|
+
const mark = optional(name, property, schema, record) ? "?" : "";
|
|
98
|
+
return `${doc}${pad}${keyOf(name)}${mark}: ${typeOf(property, scope, depth + 1, record)};`;
|
|
99
|
+
});
|
|
100
|
+
return `{\n${lines.join("\n")}\n${" ".repeat(depth)}}`;
|
|
101
|
+
}
|
|
102
|
+
/** The TypeScript of `schema`; `record` when it is (inside) a record a model describes. */
|
|
103
|
+
function typeOf(schema, scope, depth, record) {
|
|
104
|
+
if (schema.$ref !== undefined)
|
|
105
|
+
return scope.refer(schema.$ref);
|
|
106
|
+
const options = schema.anyOf ?? schema.oneOf;
|
|
107
|
+
if (options !== undefined)
|
|
108
|
+
return union(options.map((one) => typeOf(one, scope, depth, record)));
|
|
109
|
+
if ("const" in schema)
|
|
110
|
+
return JSON.stringify(schema.const);
|
|
111
|
+
if (schema.enum !== undefined)
|
|
112
|
+
return union(schema.enum.map((one) => JSON.stringify(one)));
|
|
113
|
+
const types = typeof schema.type === "string" ? [schema.type] : (schema.type ?? []);
|
|
114
|
+
if (types.length > 1)
|
|
115
|
+
return union(types.map((one) => typeOf({ ...schema, type: one }, scope, depth, record)));
|
|
116
|
+
switch (types[0]) {
|
|
117
|
+
case "string":
|
|
118
|
+
return "string";
|
|
119
|
+
case "integer":
|
|
120
|
+
case "number":
|
|
121
|
+
return "number";
|
|
122
|
+
case "boolean":
|
|
123
|
+
return "boolean";
|
|
124
|
+
case "null":
|
|
125
|
+
return "null";
|
|
126
|
+
case "array":
|
|
127
|
+
return arrayOf(schema.items === undefined ? "unknown" : typeOf(schema.items, scope, depth, record));
|
|
128
|
+
case "object":
|
|
129
|
+
return objectOf(schema, scope, depth, record);
|
|
130
|
+
default:
|
|
131
|
+
return schema.properties === undefined
|
|
132
|
+
? "unknown"
|
|
133
|
+
: objectOf(schema, scope, depth, record);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/** What the server says of an operation: its words, then what it is, for whom, on which field. */
|
|
137
|
+
function operationDoc(metamodel, local, operation) {
|
|
138
|
+
const runsOn = sorted(operation.targets).map(([entity, field]) => `\`${entity}\` in \`${field}\``);
|
|
139
|
+
const whose = operation.entities.map((one) => `\`${one}\``).join(", ");
|
|
140
|
+
const facts = [
|
|
141
|
+
`\`${operation.role}\`${whose === "" ? "" : ` of ${whose}`}`,
|
|
142
|
+
operation.query ? "reads only" : undefined,
|
|
143
|
+
operation.dry_run ? "may run dry" : undefined,
|
|
144
|
+
runsOn.length === 0 ? undefined : `its record: ${runsOn.join(", ")}`,
|
|
145
|
+
].filter((one) => one !== undefined);
|
|
146
|
+
return (docOf([operation.description, `${facts.join(" · ")}.`, deprecationOf(metamodel, operation)], "") || `/** ${local} */\n`);
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* The TypeScript of every DTO of `metamodel`, as the text of one file.
|
|
150
|
+
*
|
|
151
|
+
* 1. The models, by name: an entity's contract, a related model by its own name.
|
|
152
|
+
* 2. Each operation, by its local name (its identity without `<context>.`): its input as
|
|
153
|
+
* `<Name>` and its answer as `<Name>Answer`.
|
|
154
|
+
* 3. The shared definitions those reach — and the ones those reach, until none is new —, but
|
|
155
|
+
* never one a package of the stack already types (`Criteria`).
|
|
156
|
+
* Final: a header that says where it came from and not to edit it, the imports, then models,
|
|
157
|
+
* definitions and operations, each sorted by name; two of them with one TypeScript name are
|
|
158
|
+
* refused, naming both.
|
|
159
|
+
*/
|
|
160
|
+
export function domainFileOf(metamodel) {
|
|
161
|
+
const scope = scopeOf(metamodel);
|
|
162
|
+
const definitions = metamodel.$defs ?? {};
|
|
163
|
+
const claim = claimed();
|
|
164
|
+
const models = sorted(metamodel.models).map(([name, schema]) => {
|
|
165
|
+
claim(identifierOf(name), `model ${name}`);
|
|
166
|
+
return `${docOf([schema.description], "")}export type ${identifierOf(name)} = ${typeOf(schema, scope, 0, true)};`;
|
|
167
|
+
});
|
|
168
|
+
const operations = sorted(metamodel.operations).flatMap(([identity, operation]) => {
|
|
169
|
+
const local = localOf(metamodel, identity);
|
|
170
|
+
claim(local, `operation ${identity}`);
|
|
171
|
+
claim(`${local}Answer`, `the answer of ${identity}`);
|
|
172
|
+
const answer = operation.output === null ? "unknown" : typeOf(operation.output, scope, 0, false);
|
|
173
|
+
return [
|
|
174
|
+
`${operationDoc(metamodel, local, operation)}export type ${local} = ${typeOf(operation.input, scope, 0, false)};`,
|
|
175
|
+
`/** What \`${local}\` answers. */\nexport type ${local}Answer = ${answer};`,
|
|
176
|
+
];
|
|
177
|
+
});
|
|
178
|
+
const written = new Map();
|
|
179
|
+
for (let pending = [...scope.reached]; pending.length > 0;) {
|
|
180
|
+
for (const name of pending) {
|
|
181
|
+
const schema = definitions[name];
|
|
182
|
+
written.set(name, `${docOf([schema.description], "")}export type ${identifierOf(name)} = ${typeOf(schema, scope, 0, false)};`);
|
|
183
|
+
}
|
|
184
|
+
pending = [...scope.reached].filter((name) => !written.has(name));
|
|
185
|
+
}
|
|
186
|
+
const shared = [...written.keys()].sort().map((name) => {
|
|
187
|
+
claim(identifierOf(name), `definition ${name}`);
|
|
188
|
+
return written.get(name);
|
|
189
|
+
});
|
|
190
|
+
const imports = [...scope.imports].sort().map((name) => {
|
|
191
|
+
const imported = IMPORTED[name];
|
|
192
|
+
return `import type { ${imported.name} } from "${imported.from}";`;
|
|
193
|
+
});
|
|
194
|
+
return `${[headerOf("The DTOs", metamodel), ...(imports.length === 0 ? [] : [imports.join("\n")]), ...models, ...shared, ...operations].join("\n\n")}\n`;
|
|
195
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { Metamodel } from "./metamodel.js";
|
|
2
|
+
import { type GenerateOptions } from "./rest.js";
|
|
3
|
+
/**
|
|
4
|
+
* The TypeScript of the entities of `metamodel`, as the text of one file next to its `domain.ts`.
|
|
5
|
+
*
|
|
6
|
+
* 1. Per model, by name: the one `search` a transport reads for it (`own` when there are
|
|
7
|
+
* several) — none, and the model gets no entity, said in the file's own doc.
|
|
8
|
+
* 2. Its `get`, `edit` and `preview` the same way, the record's field written `{id}`.
|
|
9
|
+
* 3. Every write of role `command` that concerns it: with `target` when its body names the
|
|
10
|
+
* record, as it is when it creates one; its body typed without that field.
|
|
11
|
+
* Final: an `entity<T, C>()` per model listed, keyed `<domain>:<kind>`, and `entities`, all of
|
|
12
|
+
* them, for `FrameworkProvider entities`.
|
|
13
|
+
*/
|
|
14
|
+
export declare function entitiesFileOf(metamodel: Metamodel, options?: GenerateOptions): string;
|