@nanobpm/urban-pr-review-codefirst 0.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 +141 -0
- package/components/review-round.json +69 -0
- package/db/migrations/001_init.sql +46 -0
- package/db/migrations/002_transcript.sql +7 -0
- package/db/migrations/003_open_escalation.sql +8 -0
- package/deno.json +22 -0
- package/deno.lock +77 -0
- package/main.ts +352 -0
- package/nano-generated/app-pages.ts +676 -0
- package/nano-generated/data-cli.ts +552 -0
- package/nano-generated/data-sdk.ts +536 -0
- package/nano-generated/domain-rows.d.ts +87 -0
- package/nano-generated/domain-types.ts +1418 -0
- package/nano-generated/domain.ts +36 -0
- package/nano-generated/llm-worker.ts +403 -0
- package/nano-generated/message-io.d.ts +17 -0
- package/nano-generated/messages.ts +26 -0
- package/nano-generated/meta.ts +18 -0
- package/nano-generated/node-deno-shim.mjs +250 -0
- package/nano-generated/node-loader.mjs +60 -0
- package/nano-generated/node-register.mjs +11 -0
- package/nano-generated/worker-io.d.ts +28 -0
- package/nano-generated/worker-sdk.ts +468 -0
- package/nano-generated/workers.ts +29 -0
- package/nano.app.json +17 -0
- package/nanobpm.project.json +22 -0
- package/package.json +28 -0
- package/pages/home.page.json +127 -0
- package/prompts/review-round.md +119 -0
- package/scripts/answer.ts +20 -0
- package/scripts/purge-db.ts +70 -0
- package/scripts/review-ready.ts +20 -0
- package/scripts/submit.ts +32 -0
- package/tsconfig.json +14 -0
- package/workflows/convergence-loop.ts +299 -0
|
@@ -0,0 +1,1418 @@
|
|
|
1
|
+
// Urban domain-type reifier — ADR 0029 §4.1 + §6 (spike).
|
|
2
|
+
//
|
|
3
|
+
// The datasource schema is the *spine* of the domain model: a table is already a
|
|
4
|
+
// declared record type, so `DataSource.schema()`'s `TableMeta` reifies straight
|
|
5
|
+
// into a named TypeScript record. This module turns those tables into a generated
|
|
6
|
+
// `domain-rows.d.ts` (the "models directory" makers asked for — but generated, never
|
|
7
|
+
// hand-edited, so it can't drift from the DB), and the worker SDK + App loader
|
|
8
|
+
// type against it. Types are a compile/boot-time contract only: they are erased
|
|
9
|
+
// at `deno compile`, and the shipped App is still untyped JSON on the wire
|
|
10
|
+
// (ADR 0029 §3) — the engine stays Zeebe-pure.
|
|
11
|
+
//
|
|
12
|
+
// import { emitDomainDts } from "./domain-types.ts";
|
|
13
|
+
// const tables = await (await openDataSource("app")).schema();
|
|
14
|
+
// await Deno.writeTextFile("nano-generated/domain-rows.d.ts", emitDomainDts(tables));
|
|
15
|
+
//
|
|
16
|
+
// then a worker is typed end-to-end:
|
|
17
|
+
//
|
|
18
|
+
// import type { DomainTables } from "./nano-generated/domain-rows.d.ts";
|
|
19
|
+
// const rows = await db.query<DomainTables["customers"]>("SELECT * FROM customers");
|
|
20
|
+
// rows[0].tier // string | null — checked while authoring
|
|
21
|
+
//
|
|
22
|
+
// The manifest `types` registry (ADR 0029 §4.2, transient/non-persisted shapes)
|
|
23
|
+
// is the *other* source: `emitDomainTypeRegistry` renders it as a `DomainTypes`
|
|
24
|
+
// map keyed by type id, and `emitDomainModel` composes the table spine + the
|
|
25
|
+
// registry into the single generated file.
|
|
26
|
+
//
|
|
27
|
+
// This module is a **pure emitter**: it imports only the `TableMeta`/`ColumnMeta`
|
|
28
|
+
// *types* from the data SDK (a type-only import, erased at runtime), so it is
|
|
29
|
+
// materialised verbatim next to `data-cli.ts` as `nano-generated/domain-types.ts` and
|
|
30
|
+
// the data CLI's `domaintypes` op imports `emitDomainDts` from it. Opening the
|
|
31
|
+
// datasource, running `schema()`, and writing the file are the CLI op's job
|
|
32
|
+
// (`data_cli.ts`), which already owns the datasource seam and the file writer.
|
|
33
|
+
|
|
34
|
+
import type { ColumnMeta, TableMeta } from "./data_sdk.ts";
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The per-project generated-SDK directory. Visible (not dot-hidden) so makers
|
|
38
|
+
* can read the generated accessors. Single source of truth for the TS side;
|
|
39
|
+
* the Rust scaffolder (`projects.rs::GEN_DIR`) must agree.
|
|
40
|
+
*/
|
|
41
|
+
export const GEN_DIR = "nano-generated";
|
|
42
|
+
|
|
43
|
+
/** The generated file's basename, written under a project's `nano-generated/`. */
|
|
44
|
+
// Distinct stem from the runtime accessor `domain.ts`: TypeScript otherwise pairs
|
|
45
|
+
// `domain-rows.d.ts` as the *declaration of* `domain.ts`, so the accessor importing its
|
|
46
|
+
// own row types reads as a circular self-import (TS2303/TS2459) under a project
|
|
47
|
+
// `tsconfig.json` `paths` map. `-rows` also avoids colliding with the emitter
|
|
48
|
+
// module `domain-types.ts`. See the scaffolder's `PROJECT_TSCONFIG_JSON`.
|
|
49
|
+
export const DOMAIN_DTS = "domain-rows.d.ts";
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Map a SQLite declared column type to a TypeScript field type. SQLite is
|
|
53
|
+
* dynamically typed but assigns each column a *type affinity* from its declared
|
|
54
|
+
* name (the CREATE TABLE text), so we apply the affinity rules
|
|
55
|
+
* (https://sqlite.org/datatype3.html §3.1) with two maker-friendly overrides the
|
|
56
|
+
* DB Manager's type list implies: `BOOLEAN` → `boolean` and date/time types →
|
|
57
|
+
* `string` (ISO text), matching how Urban surfaces them.
|
|
58
|
+
*/
|
|
59
|
+
export function sqliteAffinityToTs(declaredType: string): string {
|
|
60
|
+
const t = declaredType.toUpperCase();
|
|
61
|
+
if (t.length === 0) return "unknown"; // NONE affinity — opaque
|
|
62
|
+
if (t.includes("BOOL")) return "boolean";
|
|
63
|
+
if (t.includes("DATE") || t.includes("TIME")) return "string";
|
|
64
|
+
if (t.includes("INT")) return "number";
|
|
65
|
+
if (t.includes("CHAR") || t.includes("CLOB") || t.includes("TEXT")) return "string";
|
|
66
|
+
if (t.includes("BLOB")) return "Uint8Array";
|
|
67
|
+
if (t.includes("REAL") || t.includes("FLOA") || t.includes("DOUB")) return "number";
|
|
68
|
+
return "number"; // NUMERIC affinity
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** A TS identifier is safe to use bare as a property name / type name. */
|
|
72
|
+
function isIdent(name: string): boolean {
|
|
73
|
+
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** PascalCase a table name into an interface name, sanitised to an identifier. */
|
|
77
|
+
export function interfaceName(table: string): string {
|
|
78
|
+
const pascal = table
|
|
79
|
+
.replace(/[^A-Za-z0-9]+/g, " ")
|
|
80
|
+
.trim()
|
|
81
|
+
.split(/\s+/)
|
|
82
|
+
.map((w) => (w ? w[0].toUpperCase() + w.slice(1) : ""))
|
|
83
|
+
.join("");
|
|
84
|
+
const safe = pascal.replace(/[^A-Za-z0-9_$]/g, "");
|
|
85
|
+
return /^[A-Za-z_$]/.test(safe) ? safe : `T_${safe}`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** The TS field type for a column: nullable columns widen with `| null`. */
|
|
89
|
+
function fieldType(col: ColumnMeta): string {
|
|
90
|
+
const base = sqliteAffinityToTs(col.type);
|
|
91
|
+
// A NOT NULL column (or the INTEGER PRIMARY KEY rowid alias) is never null.
|
|
92
|
+
return col.notNull || col.primaryKey ? base : `${base} | null`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** One `export interface` block for a table under an explicit interface name. */
|
|
96
|
+
function tableInterfaceNamed(name: string, t: TableMeta): string {
|
|
97
|
+
const fields = t.columns
|
|
98
|
+
.map((c) => {
|
|
99
|
+
const key = isIdent(c.name) ? c.name : JSON.stringify(c.name);
|
|
100
|
+
const pk = c.primaryKey ? " (primary key)" : "";
|
|
101
|
+
return ` /** ${c.type || "?"}${pk} */\n ${key}: ${fieldType(c)};`;
|
|
102
|
+
})
|
|
103
|
+
.join("\n");
|
|
104
|
+
return `export interface ${name} {\n${fields}\n}`;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** One `export interface` block for a table (name derived from the table). */
|
|
108
|
+
function tableInterface(t: TableMeta): string {
|
|
109
|
+
return tableInterfaceNamed(interfaceName(t.name), t);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Emit the full `domain-rows.d.ts` from a datasource's tables: one `interface` per
|
|
114
|
+
* table plus a `DomainTables` lookup keyed by the *raw* table name (the stable
|
|
115
|
+
* wire identifier), so callers write `DomainTables["customers"]`.
|
|
116
|
+
*/
|
|
117
|
+
export function emitDomainDts(tables: TableMeta[]): string {
|
|
118
|
+
const header =
|
|
119
|
+
"// AUTO-GENERATED by nanobpmn from the datasource schema (ADR 0029 §4.1).\n" +
|
|
120
|
+
"// Do not edit — regenerated from the live tables. Erased at `deno compile`.\n" +
|
|
121
|
+
"// eslint-disable\n";
|
|
122
|
+
if (tables.length === 0) {
|
|
123
|
+
return `${header}\nexport interface DomainTables {}\n`;
|
|
124
|
+
}
|
|
125
|
+
const interfaces = tables.map(tableInterface).join("\n\n");
|
|
126
|
+
const map = tables
|
|
127
|
+
.map((t) => ` ${JSON.stringify(t.name)}: ${interfaceName(t.name)};`)
|
|
128
|
+
.join("\n");
|
|
129
|
+
return `${header}\n${interfaces}\n\n/** Every table keyed by its wire name — index it for a row type. */\nexport interface DomainTables {\n${map}\n}\n`;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** One datasource's introspected tables, paired with its manifest alias. */
|
|
133
|
+
export interface SourceSchema {
|
|
134
|
+
source: string;
|
|
135
|
+
tables: TableMeta[];
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* The interface name for a table in a multi-source union: the source alias is
|
|
140
|
+
* PascalCased and prefixed to the table's interface name so tables that share a
|
|
141
|
+
* name across datasources (e.g. `app.customers` and `analytics.customers`) get
|
|
142
|
+
* distinct, collision-free interfaces (`AppCustomers`, `AnalyticsCustomers`).
|
|
143
|
+
*/
|
|
144
|
+
function prefixedInterfaceName(source: string, table: string): string {
|
|
145
|
+
return `${interfaceName(source)}${interfaceName(table)}`;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Emit `domain-rows.d.ts` for an App that declares *multiple* datasources: one
|
|
150
|
+
* `interface` per (source, table), a `DomainSources` map keyed by alias then
|
|
151
|
+
* wire table name, and a `DomainTables` alias to the default source so the
|
|
152
|
+
* single-source convention (`DomainTables["customers"]`) keeps working. When
|
|
153
|
+
* there is one source (or none) this is byte-identical to `emitDomainDts` so the
|
|
154
|
+
* common case stays stable.
|
|
155
|
+
*/
|
|
156
|
+
export function emitDomainDtsForSources(
|
|
157
|
+
sources: SourceSchema[],
|
|
158
|
+
defaultSource?: string,
|
|
159
|
+
): string {
|
|
160
|
+
if (sources.length <= 1) {
|
|
161
|
+
return emitDomainDts(sources[0]?.tables ?? []);
|
|
162
|
+
}
|
|
163
|
+
const header =
|
|
164
|
+
"// AUTO-GENERATED by nanobpmn from the datasource schemas (ADR 0029 §4.1/§6).\n" +
|
|
165
|
+
"// Do not edit — regenerated from the live tables. Erased at `deno compile`.\n" +
|
|
166
|
+
"// eslint-disable\n";
|
|
167
|
+
|
|
168
|
+
const interfaces = sources
|
|
169
|
+
.flatMap((s) =>
|
|
170
|
+
s.tables.map((t) =>
|
|
171
|
+
tableInterfaceNamed(prefixedInterfaceName(s.source, t.name), t)
|
|
172
|
+
)
|
|
173
|
+
)
|
|
174
|
+
.join("\n\n");
|
|
175
|
+
|
|
176
|
+
const sourceMap = sources
|
|
177
|
+
.map((s) => {
|
|
178
|
+
if (s.tables.length === 0) return ` ${JSON.stringify(s.source)}: {};`;
|
|
179
|
+
const tableMap = s.tables
|
|
180
|
+
.map((t) =>
|
|
181
|
+
` ${JSON.stringify(t.name)}: ${prefixedInterfaceName(s.source, t.name)};`
|
|
182
|
+
)
|
|
183
|
+
.join("\n");
|
|
184
|
+
return ` ${JSON.stringify(s.source)}: {\n${tableMap}\n };`;
|
|
185
|
+
})
|
|
186
|
+
.join("\n");
|
|
187
|
+
|
|
188
|
+
const def = defaultSource && sources.some((s) => s.source === defaultSource)
|
|
189
|
+
? defaultSource
|
|
190
|
+
: sources[0].source;
|
|
191
|
+
|
|
192
|
+
return `${header}\n${interfaces}\n\n` +
|
|
193
|
+
`/** Every datasource keyed by alias, then table by wire name. */\n` +
|
|
194
|
+
`export interface DomainSources {\n${sourceMap}\n}\n\n` +
|
|
195
|
+
`/** The default datasource's tables — index by wire name. */\n` +
|
|
196
|
+
`export type DomainTables = DomainSources[${JSON.stringify(def)}];\n`;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// --- manifest `types` registry (ADR 0029 §4.2) ------------------------------
|
|
200
|
+
|
|
201
|
+
/** One field of a declared domain type in the manifest `types` registry. */
|
|
202
|
+
export interface DomainFieldDef {
|
|
203
|
+
/** A primitive keyword or the id of another registry type (nominal ref). */
|
|
204
|
+
type: string;
|
|
205
|
+
optional?: boolean;
|
|
206
|
+
list?: boolean;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** A declared (transient) domain record type from the manifest `types` block. */
|
|
210
|
+
export interface DomainTypeDef {
|
|
211
|
+
name?: string;
|
|
212
|
+
match?: string;
|
|
213
|
+
table?: string;
|
|
214
|
+
fields: Record<string, DomainFieldDef>;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** The manifest `types` registry: type id → declared record type. */
|
|
218
|
+
export type DomainTypeRegistry = Record<string, DomainTypeDef>;
|
|
219
|
+
|
|
220
|
+
/** Manifest primitive field keywords → TS types (ADR 0029 §4.2 / schema). */
|
|
221
|
+
const PRIMITIVE_TS: Record<string, string> = {
|
|
222
|
+
string: "string",
|
|
223
|
+
number: "number",
|
|
224
|
+
integer: "number",
|
|
225
|
+
boolean: "boolean",
|
|
226
|
+
date: "string",
|
|
227
|
+
datetime: "string",
|
|
228
|
+
json: "unknown",
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* The TS type for a registry field. A primitive keyword maps directly (and takes
|
|
233
|
+
* precedence over an identically named type, per the schema); anything else is a
|
|
234
|
+
* nominal reference to another registry type, emitted as an indexed access into
|
|
235
|
+
* `DomainTypes` (self-contained, so no top-level interface names can collide with
|
|
236
|
+
* table interfaces). An unresolved reference degrades to `unknown`. `list` wraps
|
|
237
|
+
* the base type in `[]`.
|
|
238
|
+
*/
|
|
239
|
+
function fieldTsType(field: DomainFieldDef, ids: Set<string>): string {
|
|
240
|
+
const base = PRIMITIVE_TS[field.type] ??
|
|
241
|
+
(ids.has(field.type) ? `DomainTypes[${JSON.stringify(field.type)}]` : "unknown");
|
|
242
|
+
return field.list ? `${base}[]` : base;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Emit the `DomainTypes` block for the manifest `types` registry: an inline map
|
|
247
|
+
* keyed by type id, so a worker/form types against `DomainTypes["taxSubmission"]`
|
|
248
|
+
* exactly as it types against `DomainTables["customers"]`. Returns `""` when the
|
|
249
|
+
* registry is empty, so the table spine stays byte-identical when no types are
|
|
250
|
+
* declared. Field references resolve to `DomainTypes[<id>]`; `optional` widens
|
|
251
|
+
* the key with `?`.
|
|
252
|
+
*/
|
|
253
|
+
export function emitDomainTypeRegistry(types: DomainTypeRegistry): string {
|
|
254
|
+
const ids = new Set(Object.keys(types));
|
|
255
|
+
if (ids.size === 0) return "";
|
|
256
|
+
const entries = Object.entries(types)
|
|
257
|
+
.map(([id, def]) => {
|
|
258
|
+
const fields = Object.entries(def.fields ?? {})
|
|
259
|
+
.map(([fname, field]) => {
|
|
260
|
+
const key = isIdent(fname) ? fname : JSON.stringify(fname);
|
|
261
|
+
const opt = field.optional ? "?" : "";
|
|
262
|
+
return ` ${key}${opt}: ${fieldTsType(field, ids)};`;
|
|
263
|
+
})
|
|
264
|
+
.join("\n");
|
|
265
|
+
const body = fields.length > 0 ? `{\n${fields}\n }` : "{}";
|
|
266
|
+
return ` ${JSON.stringify(id)}: ${body};`;
|
|
267
|
+
})
|
|
268
|
+
.join("\n");
|
|
269
|
+
return `/** Declared (transient) domain types from the manifest \`types\` registry (ADR 0029 §4.2), keyed by id. */\nexport interface DomainTypes {\n${entries}\n}\n`;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Compose the full `domain-rows.d.ts`: the datasource table spine (every source,
|
|
274
|
+
* ADR 0029 §6) followed by the manifest `types` registry (§4.2). This is the
|
|
275
|
+
* single entry point the `domaintypes` op uses.
|
|
276
|
+
*/
|
|
277
|
+
export function emitDomainModel(
|
|
278
|
+
sources: SourceSchema[],
|
|
279
|
+
defaultSource: string | undefined,
|
|
280
|
+
types: DomainTypeRegistry,
|
|
281
|
+
): string {
|
|
282
|
+
const spine = emitDomainDtsForSources(sources, defaultSource);
|
|
283
|
+
const registry = emitDomainTypeRegistry(types);
|
|
284
|
+
return registry ? `${spine}\n${registry}` : spine;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// --- domain bindings: the typed data-object accessor (ADR 0029 §6) ----------
|
|
288
|
+
|
|
289
|
+
/** The generated bindings file's basename — the typed `openDomain()` accessor
|
|
290
|
+
* materialised next to `domain-rows.d.ts` under a project's `nano-generated/`. */
|
|
291
|
+
export const DOMAIN_BINDINGS = "domain.ts";
|
|
292
|
+
|
|
293
|
+
/** The primary-key column for a table's `Table` gateway: its first declared PK
|
|
294
|
+
* column, or `id` when the table declares none. */
|
|
295
|
+
function primaryKeyOf(t: TableMeta): string {
|
|
296
|
+
return t.columns.find((c) => c.primaryKey)?.name ?? "id";
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Emit `domain.ts`: a typed data-object accessor over the App's default
|
|
301
|
+
* datasource, so a worker writes `db.orders.insert({...})` / `db.orders.get(id)`
|
|
302
|
+
* instead of hand-writing SQL (ADR 0029 §6 — the Delphi data-module idea). The
|
|
303
|
+
* generic `Table<T>` runtime lives in `data-sdk.ts`; this generated module only
|
|
304
|
+
* binds each table name to its row type (from `domain-rows.d.ts`) and primary key, so
|
|
305
|
+
* it imports nothing but the sibling SDK (relative) and a type-only `domain-rows.d.ts`
|
|
306
|
+
* — staying dual-runtime (Node + Deno) and erased at `deno compile`. When the App
|
|
307
|
+
* declares multiple datasources this emits a *keyed* `openDomain<K>(source?)` whose
|
|
308
|
+
* returned accessor is typed against that source's tables (defaulting to the default
|
|
309
|
+
* source); `db.raw` is the per-source escape hatch. Single-source apps keep the
|
|
310
|
+
* zero-arg `openDomain()` concrete form (byte-stable).
|
|
311
|
+
*/
|
|
312
|
+
/** Members `openDomain()` reserves on the returned handle — the `DomainBase`
|
|
313
|
+
* escape hatch (`raw`/`close`). A table whose wire name is one of these would
|
|
314
|
+
* clobber the escape hatch (or the type intersection), so it is dropped from
|
|
315
|
+
* the typed table surface; it stays reachable via `db.raw.table("<name>", pk)`. */
|
|
316
|
+
const RESERVED_DOMAIN_MEMBERS = new Set(["raw", "close"]);
|
|
317
|
+
|
|
318
|
+
export function emitDomainBindings(
|
|
319
|
+
sources: SourceSchema[],
|
|
320
|
+
defaultSource?: string,
|
|
321
|
+
): string { const header =
|
|
322
|
+
"// AUTO-GENERATED by nanobpmn from the datasource schema (ADR 0029 §4.1/§6).\n" +
|
|
323
|
+
"// The typed data-object layer: `openDomain()` → one `Table<T>` per table, so\n" +
|
|
324
|
+
"// workers manipulate typed rows instead of hand-writing SQL. Do not edit —\n" +
|
|
325
|
+
"// regenerated from the live tables. Erased to plain JS at `deno compile`.\n" +
|
|
326
|
+
"// eslint-disable\n";
|
|
327
|
+
|
|
328
|
+
const multi = sources.length > 1;
|
|
329
|
+
const def = defaultSource && sources.some((s) => s.source === defaultSource)
|
|
330
|
+
? defaultSource
|
|
331
|
+
: sources[0]?.source;
|
|
332
|
+
const primary = sources.find((s) => s.source === def);
|
|
333
|
+
const tables = (primary?.tables ?? []).filter(
|
|
334
|
+
(t) => !RESERVED_DOMAIN_MEMBERS.has(t.name),
|
|
335
|
+
);
|
|
336
|
+
|
|
337
|
+
// Multi-source apps: emit a *keyed* accessor so `openDomain("analytics")` is
|
|
338
|
+
// typed against that source's tables, not the default's. The row-type spine
|
|
339
|
+
// (`DomainSources`, keyed by alias then wire table name) is already emitted in
|
|
340
|
+
// `domain-rows.d.ts`; here we bind a runtime table-descriptor map per source and
|
|
341
|
+
// a generic `openDomain<K>` that indexes it. Single-source apps keep the
|
|
342
|
+
// zero-arg concrete form below (byte-stable).
|
|
343
|
+
if (multi) {
|
|
344
|
+
return emitKeyedDomainBindings(header, sources, def!);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// Interface names must match `domain-rows.d.ts` exactly (prefixed when multi-source).
|
|
348
|
+
const typeName = (table: string) =>
|
|
349
|
+
multi ? prefixedInterfaceName(primary!.source, table) : interfaceName(table);
|
|
350
|
+
const propKey = (table: string) =>
|
|
351
|
+
isIdent(table) ? table : JSON.stringify(table);
|
|
352
|
+
|
|
353
|
+
const typeImports = [...new Set(tables.map((t) => typeName(t.name)))].sort();
|
|
354
|
+
const importTypes = typeImports.length > 0
|
|
355
|
+
? `import type { ${typeImports.join(", ")} } from "./${DOMAIN_DTS}";\n`
|
|
356
|
+
: "";
|
|
357
|
+
|
|
358
|
+
const fields = tables
|
|
359
|
+
.map((t) => ` readonly ${propKey(t.name)}: Table<${typeName(t.name)}>;`)
|
|
360
|
+
.join("\n");
|
|
361
|
+
const binds = tables
|
|
362
|
+
.map((t) =>
|
|
363
|
+
` ${propKey(t.name)}: raw.table<${typeName(t.name)}>(` +
|
|
364
|
+
`${JSON.stringify(t.name)}, ${JSON.stringify(primaryKeyOf(t))}),`
|
|
365
|
+
)
|
|
366
|
+
.join("\n");
|
|
367
|
+
|
|
368
|
+
const domainIface = `export interface Domain {\n` +
|
|
369
|
+
` /** The underlying datasource handle — the raw-SQL escape hatch. */\n` +
|
|
370
|
+
` readonly raw: DataSource;\n` +
|
|
371
|
+
(fields ? `${fields}\n` : "") +
|
|
372
|
+
` /** Close the underlying connection. */\n close(): void;\n}`;
|
|
373
|
+
|
|
374
|
+
const openFn = `/**\n` +
|
|
375
|
+
` * Open the App's ${multi ? `default (\`${def}\`) ` : ""}datasource as a typed domain: each table is\n` +
|
|
376
|
+
` * a \`Table<T>\` gateway (\`db.orders.insert(...)\`, \`db.orders.get(id)\`), with the\n` +
|
|
377
|
+
` * raw \`DataSource\` at \`db.raw\` for anything the gateway doesn't cover.\n` +
|
|
378
|
+
` */\n` +
|
|
379
|
+
`export async function openDomain(source?: string): Promise<Domain> {\n` +
|
|
380
|
+
` const raw = await openDataSource(source);\n` +
|
|
381
|
+
` return {\n raw,\n` +
|
|
382
|
+
(binds ? `${binds}\n` : "") +
|
|
383
|
+
` close: () => raw.close(),\n };\n}`;
|
|
384
|
+
|
|
385
|
+
return `${header}\n` +
|
|
386
|
+
`import { openDataSource, type DataSource, type Table } from "./data-sdk.ts";\n` +
|
|
387
|
+
importTypes +
|
|
388
|
+
`\n${domainIface}\n\n${openFn}\n\nexport type { Table };\n`;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Emit the *keyed* `domain.ts` for a multi-datasource App. `openDomain(source)`
|
|
393
|
+
* is runtime-polymorphic (it opens whichever source you name) but was previously
|
|
394
|
+
* type-*mono*morphic — always typed as the default source's `Domain`, so
|
|
395
|
+
* `openDomain("analytics").customers` was mistyped against `app`'s tables. Here
|
|
396
|
+
* `openDomain<K extends DomainSource>(source?: K)` selects the row-type map for
|
|
397
|
+
* the requested source from `DomainSources` (emitted in `domain-rows.d.ts`), and a
|
|
398
|
+
* runtime per-source table-descriptor map binds the matching `Table<T>` gateways.
|
|
399
|
+
* Zero-arg / default-source calls keep resolving to the default source.
|
|
400
|
+
*/
|
|
401
|
+
function emitKeyedDomainBindings(
|
|
402
|
+
header: string,
|
|
403
|
+
sources: SourceSchema[],
|
|
404
|
+
def: string,
|
|
405
|
+
): string {
|
|
406
|
+
const tableDescriptors = sources
|
|
407
|
+
.map((s) => {
|
|
408
|
+
const rows = s.tables
|
|
409
|
+
.filter((t) => !RESERVED_DOMAIN_MEMBERS.has(t.name))
|
|
410
|
+
.map((t) =>
|
|
411
|
+
`{ name: ${JSON.stringify(t.name)}, pk: ${JSON.stringify(primaryKeyOf(t))} }`
|
|
412
|
+
)
|
|
413
|
+
.join(", ");
|
|
414
|
+
return ` ${JSON.stringify(s.source)}: [${rows}],`;
|
|
415
|
+
})
|
|
416
|
+
.join("\n");
|
|
417
|
+
|
|
418
|
+
const runtimeMap =
|
|
419
|
+
`const DOMAIN_TABLES: Record<string, { name: string; pk: string }[]> = {\n` +
|
|
420
|
+
`${tableDescriptors}\n};\n` +
|
|
421
|
+
`const DEFAULT_SOURCE = ${JSON.stringify(def)};`;
|
|
422
|
+
|
|
423
|
+
const types =
|
|
424
|
+
`/** The App's datasource aliases (ADR 0024). */\n` +
|
|
425
|
+
`export type DomainSource = keyof DomainSources;\n\n` +
|
|
426
|
+
`interface DomainBase {\n` +
|
|
427
|
+
` /** The underlying datasource handle — the raw-SQL escape hatch. */\n` +
|
|
428
|
+
` readonly raw: DataSource;\n` +
|
|
429
|
+
` /** Close the underlying connection. */\n close(): void;\n}\n\n` +
|
|
430
|
+
`type DomainTablesOf<M extends Record<string, object>> = { readonly [K in keyof M as K extends "raw" | "close" ? never : K]: Table<M[K]> };\n\n` +
|
|
431
|
+
`/** A datasource opened as a typed domain: one \`Table<T>\` per table, plus\n` +
|
|
432
|
+
` * \`raw\`/\`close\`. Defaults to the default source (\`${def}\`) when unparameterised. */\n` +
|
|
433
|
+
`export type Domain<M extends Record<string, object> = DomainSources[${JSON.stringify(def)}]> =\n` +
|
|
434
|
+
` DomainBase & DomainTablesOf<M>;`;
|
|
435
|
+
|
|
436
|
+
const openFn =
|
|
437
|
+
`/**\n` +
|
|
438
|
+
` * Open one of the App's datasources as a typed domain. The \`source\` key\n` +
|
|
439
|
+
` * selects that source's tables (\`openDomain("analytics").customers\`); omit it\n` +
|
|
440
|
+
` * for the default source (\`${def}\`). \`db.raw\` is the raw-SQL escape hatch.\n` +
|
|
441
|
+
` */\n` +
|
|
442
|
+
`export async function openDomain<K extends DomainSource = ${JSON.stringify(def)}>(\n` +
|
|
443
|
+
` source?: K,\n` +
|
|
444
|
+
`): Promise<Domain<DomainSources[K]>> {\n` +
|
|
445
|
+
` const key = (source ?? DEFAULT_SOURCE) as string;\n` +
|
|
446
|
+
` const raw = await openDataSource(key);\n` +
|
|
447
|
+
` const db: Record<string, unknown> = { raw, close: () => raw.close() };\n` +
|
|
448
|
+
` for (const t of DOMAIN_TABLES[key] ?? []) db[t.name] = raw.table(t.name, t.pk);\n` +
|
|
449
|
+
` return db as Domain<DomainSources[K]>;\n}`;
|
|
450
|
+
|
|
451
|
+
return `${header}\n` +
|
|
452
|
+
`import { openDataSource, type DataSource, type Table } from "./data-sdk.ts";\n` +
|
|
453
|
+
`import type { DomainSources } from "./${DOMAIN_DTS}";\n\n` +
|
|
454
|
+
`${runtimeMap}\n\n${types}\n\n${openFn}\n\nexport type { Table };\n`;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
/** The generated worker-IO type map's basename — the `taskType → {in,out}` map
|
|
459
|
+
* materialised next to `domain-rows.d.ts` under a project's `nano-generated/`. */
|
|
460
|
+
// Distinct stem from the runtime wrapper `workers.ts` (same pairing hazard as
|
|
461
|
+
// `DOMAIN_DTS`): a `worker-io.d.ts` reads as the declaration of `workers.ts`.
|
|
462
|
+
export const WORKER_BINDINGS_DTS = "worker-io.d.ts";
|
|
463
|
+
|
|
464
|
+
/** The generated typed-`defineWorker` wrapper's basename — re-exports the worker
|
|
465
|
+
* SDK and overrides `defineWorker` with a taskType-keyed typed signature. */
|
|
466
|
+
export const WORKER_BINDINGS_TS = "workers.ts";
|
|
467
|
+
|
|
468
|
+
/** One `workers[]` declaration the codegen reads: the join `taskType` plus the
|
|
469
|
+
* declared input/output domain-type ids (ADR 0033 §3). */
|
|
470
|
+
export interface WorkerBindingDecl {
|
|
471
|
+
taskType: string;
|
|
472
|
+
inputType?: string;
|
|
473
|
+
outputType?: string;
|
|
474
|
+
/** The `zeebe:header` keys declared on the task; reified into a typed
|
|
475
|
+
* `job.customHeaders` shape (known keys, `string` values — headers are strings
|
|
476
|
+
* on the wire). Empty/absent leaves `customHeaders` the untyped fallback. */
|
|
477
|
+
headerKeys?: string[];
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** The TS type expression for a worker's declared input/output type id: an index
|
|
481
|
+
* into the `DomainTypes` registry when the id is declared, else `undefined` (the
|
|
482
|
+
* caller omits the entry so the taskType falls back to `WorkerVars`). */
|
|
483
|
+
function typeRefFor(id: string | undefined, declared: Set<string>): string | undefined {
|
|
484
|
+
return id != null && declared.has(id) ? `DomainTypes[${JSON.stringify(id)}]` : undefined;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/** The TS type expression for a worker's declared custom-header keys: an object
|
|
488
|
+
* type mapping each declared key to `string` (Zeebe headers are strings on the
|
|
489
|
+
* wire) plus a `string` index signature so undeclared headers stay accessible
|
|
490
|
+
* with the same honest wire type. Returns `undefined` when no keys are declared
|
|
491
|
+
* (the caller omits the entry so the taskType falls back to `WorkerHdrs`). */
|
|
492
|
+
function headerRefFor(keys: string[] | undefined): string | undefined {
|
|
493
|
+
const clean = [
|
|
494
|
+
...new Set(
|
|
495
|
+
(keys ?? []).filter((k) => typeof k === "string").map((k) => k.trim()).filter((k) =>
|
|
496
|
+
k.length > 0
|
|
497
|
+
),
|
|
498
|
+
),
|
|
499
|
+
];
|
|
500
|
+
if (clean.length === 0) return undefined;
|
|
501
|
+
const fields = clean.map((k) => `${JSON.stringify(k)}: string`).join("; ");
|
|
502
|
+
return `{ ${fields}; [key: string]: string }`;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* Emit `worker-io.d.ts`: the machine-readable bridge from the process model to the
|
|
507
|
+
* worker type system (ADR 0033 §3). Each declared worker's `taskType` maps to the
|
|
508
|
+
* TS type of its input payload (`job.variables`, from `inputType`) and its result
|
|
509
|
+
* (from `outputType`), resolved against the `DomainTypes` registry in
|
|
510
|
+
* `domain-rows.d.ts`. Only entries whose type is actually declared are emitted; a
|
|
511
|
+
* taskType with no declared type is absent and falls back to `WorkerVars` in the
|
|
512
|
+
* typed `defineWorker`. Imports `DomainTypes` type-only (so it erases at compile
|
|
513
|
+
* and stays dual-runtime) — and only when at least one entry references it, so an
|
|
514
|
+
* app with no declared types still yields a valid (empty) map.
|
|
515
|
+
*/
|
|
516
|
+
export function emitWorkerBindings(
|
|
517
|
+
workers: WorkerBindingDecl[],
|
|
518
|
+
declaredTypeIds: Iterable<string>,
|
|
519
|
+
): string {
|
|
520
|
+
const declared = new Set(declaredTypeIds);
|
|
521
|
+
const propKey = (t: string) => JSON.stringify(t);
|
|
522
|
+
const taskTypes = [
|
|
523
|
+
...new Set(
|
|
524
|
+
workers
|
|
525
|
+
.map((w) => w?.taskType)
|
|
526
|
+
.filter((t): t is string => typeof t === "string" && t.length > 0),
|
|
527
|
+
),
|
|
528
|
+
];
|
|
529
|
+
// The model-derived set of job types the typed `defineWorker` accepts. A finite
|
|
530
|
+
// union when workers are declared (so `type:` autocompletes and rejects typos);
|
|
531
|
+
// `string` for an app with none, so `defineWorker` stays usable pre-declaration.
|
|
532
|
+
const taskTypeUnion = taskTypes.length > 0
|
|
533
|
+
? taskTypes.map((t) => JSON.stringify(t)).join(" | ")
|
|
534
|
+
: "string";
|
|
535
|
+
const inputs: string[] = [];
|
|
536
|
+
const outputs: string[] = [];
|
|
537
|
+
const headers: string[] = [];
|
|
538
|
+
for (const w of workers) {
|
|
539
|
+
if (typeof w?.taskType !== "string" || w.taskType.length === 0) continue;
|
|
540
|
+
const inRef = typeRefFor(w.inputType, declared);
|
|
541
|
+
if (inRef) inputs.push(` ${propKey(w.taskType)}: ${inRef};`);
|
|
542
|
+
const outRef = typeRefFor(w.outputType, declared);
|
|
543
|
+
if (outRef) outputs.push(` ${propKey(w.taskType)}: ${outRef};`);
|
|
544
|
+
const hdrRef = headerRefFor(w.headerKeys);
|
|
545
|
+
if (hdrRef) headers.push(` ${propKey(w.taskType)}: ${hdrRef};`);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
const header =
|
|
549
|
+
"// AUTO-GENERATED by nanobpmn from the App manifest (ADR 0033 §3).\n" +
|
|
550
|
+
"// The bridge from the process model to the worker type system: each declared\n" +
|
|
551
|
+
"// worker's `taskType` maps to the TS type of its input payload (`job.variables`)\n" +
|
|
552
|
+
"// and result, so the typed `defineWorker` types a handler by its job type. Do\n" +
|
|
553
|
+
"// not edit — regenerated from the manifest. Erased to plain JS at compile.\n" +
|
|
554
|
+
"// eslint-disable\n";
|
|
555
|
+
|
|
556
|
+
const needsRegistry = inputs.length > 0 || outputs.length > 0;
|
|
557
|
+
const importTypes = needsRegistry
|
|
558
|
+
? `import type { DomainTypes } from "./${DOMAIN_DTS}";\n`
|
|
559
|
+
: "";
|
|
560
|
+
|
|
561
|
+
const inputsIface = inputs.length > 0
|
|
562
|
+
? `export interface WorkerInputs {\n${inputs.join("\n")}\n}\n`
|
|
563
|
+
: `export interface WorkerInputs {}\n`;
|
|
564
|
+
const outputsIface = outputs.length > 0
|
|
565
|
+
? `export interface WorkerOutputs {\n${outputs.join("\n")}\n}\n`
|
|
566
|
+
: `export interface WorkerOutputs {}\n`;
|
|
567
|
+
const headersIface = headers.length > 0
|
|
568
|
+
? `export interface WorkerHeaders {\n${headers.join("\n")}\n}\n`
|
|
569
|
+
: `export interface WorkerHeaders {}\n`;
|
|
570
|
+
|
|
571
|
+
return `${header}\n` +
|
|
572
|
+
importTypes +
|
|
573
|
+
`\n/** Untyped fallback for a job whose worker declares no input/output type. */\n` +
|
|
574
|
+
`export type WorkerVars = Record<string, unknown>;\n\n` +
|
|
575
|
+
`/** Untyped fallback for a job whose worker declares no custom headers. */\n` +
|
|
576
|
+
`export type WorkerHdrs = Record<string, unknown>;\n\n` +
|
|
577
|
+
`/** Every declared worker \`taskType\` (ADR 0033 §3): the model-derived set the\n` +
|
|
578
|
+
` * typed \`defineWorker\` accepts, so \`type\` autocompletes and rejects unknown jobs. */\n` +
|
|
579
|
+
`export type WorkerTaskType = ${taskTypeUnion};\n\n` +
|
|
580
|
+
`/** Input payload (\`job.variables\`) per declared worker, keyed by \`taskType\`. */\n` +
|
|
581
|
+
inputsIface +
|
|
582
|
+
`\n/** Output payload (worker result) per declared worker, keyed by \`taskType\`. */\n` +
|
|
583
|
+
outputsIface +
|
|
584
|
+
`\n/** Custom headers (\`job.customHeaders\`) per declared worker, keyed by \`taskType\`.\n` +
|
|
585
|
+
` * Header values are strings on the wire, so each declared key maps to \`string\`;\n` +
|
|
586
|
+
` * the extra index signature keeps undeclared headers accessible (non-breaking). */\n` +
|
|
587
|
+
headersIface;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* The static typed-`defineWorker` wrapper (`workers.ts`). It re-exports the whole
|
|
592
|
+
* worker SDK and overrides `defineWorker` with a signature that keys off the
|
|
593
|
+
* `type:` string literal: when a job type is present in the generated
|
|
594
|
+
* `WorkerInputs`/`WorkerOutputs` (ADR 0033 §3), the handler's `job.variables` and
|
|
595
|
+
* result are typed from the declared domain type; otherwise they fall back to
|
|
596
|
+
* `WorkerVars`. The body is a pass-through — the wire stays untyped JSON (ADR 0029
|
|
597
|
+
* §3). This file never changes with the schema, so it is written verbatim (unlike
|
|
598
|
+
* the regenerated `worker-io.d.ts`). Dual-runtime: only type-level constructs +
|
|
599
|
+
* `export *` + a type assertion, so Node's strip-only mode accepts it (ADR 0036).
|
|
600
|
+
*/
|
|
601
|
+
export function emitWorkerBindingsRuntime(): string {
|
|
602
|
+
return "// AUTO-GENERATED by nanobpmn (ADR 0033 §3): the typed `defineWorker`.\n" +
|
|
603
|
+
"// Re-exports the worker SDK and overrides `defineWorker` with a taskType-keyed\n" +
|
|
604
|
+
"// typed signature (job.variables, job.customHeaders + result typed from the\n" +
|
|
605
|
+
"// worker's declared input/output/header contract). Erased to a pass-through at\n" +
|
|
606
|
+
"// runtime. Do not edit.\n" +
|
|
607
|
+
"// eslint-disable\n\n" +
|
|
608
|
+
`import { defineWorker as defineWorkerRaw } from "./worker-sdk.ts";\n` +
|
|
609
|
+
`import type { WorkerOptions } from "./worker-sdk.ts";\n` +
|
|
610
|
+
`import type { WorkerInputs, WorkerOutputs, WorkerHeaders, WorkerTaskType, WorkerVars, WorkerHdrs } from "./${WORKER_BINDINGS_DTS}";\n\n` +
|
|
611
|
+
`export * from "./worker-sdk.ts";\n\n` +
|
|
612
|
+
`type InFor<K extends WorkerTaskType> = K extends keyof WorkerInputs ? WorkerInputs[K] : WorkerVars;\n` +
|
|
613
|
+
`type OutFor<K extends WorkerTaskType> = K extends keyof WorkerOutputs ? WorkerOutputs[K] : WorkerVars;\n` +
|
|
614
|
+
`type HdrFor<K extends WorkerTaskType> = K extends keyof WorkerHeaders ? WorkerHeaders[K] : WorkerHdrs;\n\n` +
|
|
615
|
+
`/**\n` +
|
|
616
|
+
` * Typed \`defineWorker\`: \`type\` is constrained to the model's declared job types\n` +
|
|
617
|
+
` * (\`WorkerTaskType\`, ADR 0033 §3) so it autocompletes and rejects unknown jobs,\n` +
|
|
618
|
+
` * and the handler's \`job.variables\`, \`job.customHeaders\` + result are typed from\n` +
|
|
619
|
+
` * the worker's declared \`inputType\`/\`outputType\`/header keys. A declared job type\n` +
|
|
620
|
+
` * with no declared type falls back to WorkerVars / WorkerHdrs.\n` +
|
|
621
|
+
` */\n` +
|
|
622
|
+
`export function defineWorker<K extends WorkerTaskType>(\n` +
|
|
623
|
+
` opts: { type: K } & WorkerOptions<InFor<K> & object, OutFor<K> & object, HdrFor<K> & object>,\n` +
|
|
624
|
+
`): void {\n` +
|
|
625
|
+
` defineWorkerRaw(opts as unknown as WorkerOptions);\n` +
|
|
626
|
+
`}\n`;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// --- message-carried envelopes (ADR 0040 slice 2) --------------------------
|
|
630
|
+
|
|
631
|
+
/** The generated message-payload type map's basename. Distinct stem from the
|
|
632
|
+
* runtime wrapper `messages.ts` (same pairing hazard as `DOMAIN_DTS`): a
|
|
633
|
+
* `message-io.d.ts` reads as the declaration of `messages.ts`. */
|
|
634
|
+
export const MESSAGE_BINDINGS_DTS = "message-io.d.ts";
|
|
635
|
+
|
|
636
|
+
/** The generated typed-`publishMessage` wrapper's basename — re-exports the
|
|
637
|
+
* worker SDK's `publishMessage` with a messageName-keyed typed signature. */
|
|
638
|
+
export const MESSAGE_BINDINGS_TS = "messages.ts";
|
|
639
|
+
|
|
640
|
+
/** One message binding the codegen reads: the message `name` plus the declared
|
|
641
|
+
* envelope type ids (ADR 0040 slice 2). `inputType` is the *received* payload —
|
|
642
|
+
* i.e. what a `publishMessage` caller sends. `outputType` is reserved. */
|
|
643
|
+
export interface MessageBindingDecl {
|
|
644
|
+
messageName: string;
|
|
645
|
+
inputType?: string;
|
|
646
|
+
outputType?: string;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/**
|
|
650
|
+
* Emit `message-io.d.ts`: the machine-readable bridge from the process model's
|
|
651
|
+
* `bpmn:message` envelopes to the message type system (ADR 0040 slice 2). Each
|
|
652
|
+
* named message contributes to the `MessageName` union (so `publishMessage`
|
|
653
|
+
* autocompletes and rejects unknown messages); a message whose envelope declares
|
|
654
|
+
* an `inputType` also maps its name to that payload type in `MessagePayloads`, so
|
|
655
|
+
* `publishMessage(name, { variables })` is typed. Only entries whose type is
|
|
656
|
+
* actually declared are emitted; a message with no declared type is absent from
|
|
657
|
+
* `MessagePayloads` and its payload falls back to `MessageVars`. Imports
|
|
658
|
+
* `DomainTypes` type-only, and only when at least one entry references it.
|
|
659
|
+
*/
|
|
660
|
+
export function emitMessageBindings(
|
|
661
|
+
messages: MessageBindingDecl[],
|
|
662
|
+
declaredTypeIds: Iterable<string>,
|
|
663
|
+
): string {
|
|
664
|
+
const declared = new Set(declaredTypeIds);
|
|
665
|
+
const propKey = (m: string) => JSON.stringify(m);
|
|
666
|
+
const names = [
|
|
667
|
+
...new Set(
|
|
668
|
+
messages
|
|
669
|
+
.map((m) => m?.messageName)
|
|
670
|
+
.filter((n): n is string => typeof n === "string" && n.length > 0),
|
|
671
|
+
),
|
|
672
|
+
];
|
|
673
|
+
// The model-derived set of message names the typed `publishMessage` accepts. A
|
|
674
|
+
// finite union when messages are declared; `string` for a model with none, so
|
|
675
|
+
// `publishMessage` stays usable pre-declaration.
|
|
676
|
+
const nameUnion = names.length > 0
|
|
677
|
+
? names.map((n) => JSON.stringify(n)).join(" | ")
|
|
678
|
+
: "string";
|
|
679
|
+
const payloads: string[] = [];
|
|
680
|
+
for (const m of messages) {
|
|
681
|
+
if (typeof m?.messageName !== "string" || m.messageName.length === 0) continue;
|
|
682
|
+
const ref = typeRefFor(m.inputType, declared);
|
|
683
|
+
if (ref) payloads.push(` ${propKey(m.messageName)}: ${ref};`);
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
const header =
|
|
687
|
+
"// AUTO-GENERATED by nanobpmn from the process model (ADR 0040 slice 2).\n" +
|
|
688
|
+
"// The bridge from a `bpmn:message`'s data envelope to the message type system:\n" +
|
|
689
|
+
"// each named message maps to the TS type of its payload, so the typed\n" +
|
|
690
|
+
"// `publishMessage` types a call by its message name. Do not edit — regenerated\n" +
|
|
691
|
+
"// from the model. Erased to plain JS at compile.\n" +
|
|
692
|
+
"// eslint-disable\n";
|
|
693
|
+
|
|
694
|
+
const needsRegistry = payloads.length > 0;
|
|
695
|
+
const importTypes = needsRegistry
|
|
696
|
+
? `import type { DomainTypes } from "./${DOMAIN_DTS}";\n`
|
|
697
|
+
: "";
|
|
698
|
+
|
|
699
|
+
const payloadsIface = payloads.length > 0
|
|
700
|
+
? `export interface MessagePayloads {\n${payloads.join("\n")}\n}\n`
|
|
701
|
+
: `export interface MessagePayloads {}\n`;
|
|
702
|
+
|
|
703
|
+
return `${header}\n` +
|
|
704
|
+
importTypes +
|
|
705
|
+
`\n/** Untyped fallback payload for a message that declares no envelope type. */\n` +
|
|
706
|
+
`export type MessageVars = Record<string, unknown>;\n\n` +
|
|
707
|
+
`/** Every declared message \`name\` (ADR 0040 slice 2): the model-derived set the\n` +
|
|
708
|
+
` * typed \`publishMessage\` accepts, so \`name\` autocompletes and rejects unknown messages. */\n` +
|
|
709
|
+
`export type MessageName = ${nameUnion};\n\n` +
|
|
710
|
+
`/** Payload (\`variables\`) per declared message, keyed by \`name\`. */\n` +
|
|
711
|
+
payloadsIface;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
/**
|
|
715
|
+
* The static typed-`publishMessage` wrapper (`messages.ts`). It re-exports the
|
|
716
|
+
* worker SDK's `publishMessage` (and its option/result types) and overrides
|
|
717
|
+
* `publishMessage` with a signature that keys off the `name` string literal: when
|
|
718
|
+
* a message is present in the generated `MessagePayloads` (ADR 0040 slice 2), the
|
|
719
|
+
* call's `variables` are typed from the declared domain type; otherwise they fall
|
|
720
|
+
* back to `MessageVars`. The body is a pass-through — the wire stays untyped JSON.
|
|
721
|
+
* This file never changes with the model, so it is written verbatim (unlike the
|
|
722
|
+
* regenerated `message-io.d.ts`). Dual-runtime: only type-level constructs + a
|
|
723
|
+
* type assertion, so Node's strip-only mode accepts it (ADR 0036).
|
|
724
|
+
*/
|
|
725
|
+
export function emitMessageBindingsRuntime(): string {
|
|
726
|
+
return "// AUTO-GENERATED by nanobpmn (ADR 0040 slice 2): the typed `publishMessage`.\n" +
|
|
727
|
+
"// Re-exports the worker SDK's `publishMessage` and overrides it with a\n" +
|
|
728
|
+
"// messageName-keyed typed signature (variables typed from the message's declared\n" +
|
|
729
|
+
"// envelope). Erased to a pass-through at runtime. Do not edit.\n" +
|
|
730
|
+
"// eslint-disable\n\n" +
|
|
731
|
+
`import { publishMessage as publishMessageRaw } from "./worker-sdk.ts";\n` +
|
|
732
|
+
`import type { PublishMessageOptions, PublishMessageResult } from "./worker-sdk.ts";\n` +
|
|
733
|
+
`import type { MessageName, MessagePayloads, MessageVars } from "./${MESSAGE_BINDINGS_DTS}";\n\n` +
|
|
734
|
+
`export type { PublishMessageOptions, PublishMessageResult } from "./worker-sdk.ts";\n\n` +
|
|
735
|
+
`type PayloadFor<K extends MessageName> = K extends keyof MessagePayloads ? MessagePayloads[K] : MessageVars;\n\n` +
|
|
736
|
+
`/**\n` +
|
|
737
|
+
` * Typed \`publishMessage\`: \`name\` is constrained to the model's declared message\n` +
|
|
738
|
+
` * names (\`MessageName\`, ADR 0040 slice 2) so it autocompletes and rejects unknown\n` +
|
|
739
|
+
` * messages, and \`variables\` are typed from the message's declared envelope. A\n` +
|
|
740
|
+
` * declared message with no domain type falls back to MessageVars.\n` +
|
|
741
|
+
` */\n` +
|
|
742
|
+
`export function publishMessage<K extends MessageName>(\n` +
|
|
743
|
+
` name: K,\n` +
|
|
744
|
+
` opts?: PublishMessageOptions<PayloadFor<K> & object>,\n` +
|
|
745
|
+
`): Promise<PublishMessageResult> {\n` +
|
|
746
|
+
` return publishMessageRaw(name, opts as unknown as PublishMessageOptions);\n` +
|
|
747
|
+
`}\n`;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// --- composed motion shapes: the fuse composition algebra (ADR 0040 §9/§10) ---
|
|
751
|
+
//
|
|
752
|
+
// A composed shape is a named, model-scoped declaration authored in the Modeller
|
|
753
|
+
// and carried in the `.bpmn` as a `nano:shape` (see `console/src/lib/shapeCarrier.ts`
|
|
754
|
+
// and the Rust scan `envelope_scan.rs`). It composes existing fused entities — DB
|
|
755
|
+
// tables, manifest `types`, and other shapes — via four ordered operations:
|
|
756
|
+
//
|
|
757
|
+
// carry(ref) spread every field of `ref`
|
|
758
|
+
// project(ref, fields, via) spread only the named fields of `ref`
|
|
759
|
+
// extend(name, type, ...) add a process-authored field
|
|
760
|
+
// reference(name, ref, ...) nest (or spread) another shape
|
|
761
|
+
//
|
|
762
|
+
// Resolution folds the ops, in author (XML) order, into a flat `DomainTypeDef`, so
|
|
763
|
+
// a composed shape enters the same `DomainTypes` registry a manifest `type` does —
|
|
764
|
+
// every downstream consumer (envelope pickers, `defineWorker`, `publishMessage`,
|
|
765
|
+
// FEEL scopes) types against `DomainTypes["ApprovedOrder"]` with no new codegen
|
|
766
|
+
// path. Broken shapes are omitted (degrade to untyped) and reported as diagnostics.
|
|
767
|
+
|
|
768
|
+
/** One composition operation of a `nano:shape`, in author (XML) order. */
|
|
769
|
+
export type ShapeOp =
|
|
770
|
+
| { op: "carry"; ref: string }
|
|
771
|
+
| { op: "project"; ref: string; fields: string[]; via?: string }
|
|
772
|
+
| { op: "extend"; name: string; type: string; optional?: boolean; list?: boolean }
|
|
773
|
+
| { op: "reference"; name: string; ref: string; spread?: boolean; list?: boolean };
|
|
774
|
+
|
|
775
|
+
/** A composed motion-shape declaration lifted from the model (ADR 0040 §9). */
|
|
776
|
+
export interface ShapeDecl {
|
|
777
|
+
/** The fuse identity; also the `DomainTypes` key the resolved shape lands under. */
|
|
778
|
+
id: string;
|
|
779
|
+
/** Optional human label (`nano:shape name`). */
|
|
780
|
+
name?: string;
|
|
781
|
+
/** The defining process id, for the `model:<processId>` provenance tag. */
|
|
782
|
+
process?: string;
|
|
783
|
+
/** The ordered composition operations. */
|
|
784
|
+
ops: ShapeOp[];
|
|
785
|
+
/** Model-level metadata (`nano:meta`), free-form key/value (ADR 0040 §5). */
|
|
786
|
+
meta?: Record<string, string>;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/** A scan/resolve-time problem with a shape, surfaced like the `workers[]` drift
|
|
790
|
+
* warning (never a silent merge). A shape with any `error` diagnostic is omitted
|
|
791
|
+
* from the fuse; a `warning` (e.g. a deliberate field shadow) still resolves. */
|
|
792
|
+
export interface ShapeDiagnostic {
|
|
793
|
+
/** The offending shape id. */
|
|
794
|
+
shape: string;
|
|
795
|
+
kind:
|
|
796
|
+
| "unresolved-reference"
|
|
797
|
+
| "reference-cycle"
|
|
798
|
+
| "field-conflict"
|
|
799
|
+
| "unknown-field"
|
|
800
|
+
| "duplicate-id"
|
|
801
|
+
| "ambiguous-reference"
|
|
802
|
+
| "nominal-table-ref"
|
|
803
|
+
| "same-id-collision";
|
|
804
|
+
severity: "error" | "warning";
|
|
805
|
+
message: string;
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/** The result of resolving the project's shapes against the leaf fuse. */
|
|
809
|
+
export interface ShapeResolution {
|
|
810
|
+
/** The resolved shapes as registry entries, keyed by shape id, ready to fold
|
|
811
|
+
* into the manifest `types` registry before `emitDomainModel`. */
|
|
812
|
+
types: DomainTypeRegistry;
|
|
813
|
+
diagnostics: ShapeDiagnostic[];
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
/** An entity the fuse can resolve a `carry`/`project`/`reference` against: its
|
|
817
|
+
* field map, plus (DB tables only) its FK columns for `via`-path validation. */
|
|
818
|
+
interface FuseEntity {
|
|
819
|
+
fields: Record<string, DomainFieldDef>;
|
|
820
|
+
/** FK column name → referenced table, for `project via` validation. */
|
|
821
|
+
fks?: Record<string, string>;
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/** Map one datasource column to a domain field. A nullable column widens to
|
|
825
|
+
* `optional` (the composed shape is a motion snapshot: an absent value reads as
|
|
826
|
+
* undefined, not SQL NULL). The manifest keyword is inferred from the column's
|
|
827
|
+
* SQLite affinity so it flows through `fieldTsType` like any declared field;
|
|
828
|
+
* affinities with no keyword (BLOB/opaque) fall back to `json`. */
|
|
829
|
+
function columnToField(col: ColumnMeta): DomainFieldDef {
|
|
830
|
+
const ts = sqliteAffinityToTs(col.type);
|
|
831
|
+
const keyword = ts === "string" || ts === "number" || ts === "boolean" ? ts : "json";
|
|
832
|
+
const nullable = !(col.notNull || col.primaryKey);
|
|
833
|
+
return nullable ? { type: keyword, optional: true } : { type: keyword };
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/** Build the leaf entity index the shape fold resolves references against: every
|
|
837
|
+
* datasource table (by raw wire name, and by `source.table` to disambiguate a
|
|
838
|
+
* name shared across sources) and every manifest `type` (by id). A raw table name
|
|
839
|
+
* shared across sources keeps the first (default-source-first) binding; the
|
|
840
|
+
* qualified `source.table` alias is always unambiguous.
|
|
841
|
+
*
|
|
842
|
+
* When a manifest `type` id collides with a bare table name, the **type wins** the
|
|
843
|
+
* unqualified id (it is the more first-class, `DomainTypes`-visible entity) and the
|
|
844
|
+
* collision is surfaced via `ambiguousIds` so resolution can warn; the table stays
|
|
845
|
+
* reachable through its `source.table` alias. `tableIds` records every id (bare +
|
|
846
|
+
* qualified) that resolves to a DB table, so a nominal reference (which the emitter
|
|
847
|
+
* can only express against `DomainTypes` keys) can be rejected. */
|
|
848
|
+
function leafEntityIndex(
|
|
849
|
+
sources: SourceSchema[],
|
|
850
|
+
types: DomainTypeRegistry,
|
|
851
|
+
): { index: Map<string, FuseEntity>; tableIds: Set<string>; ambiguousIds: Set<string> } {
|
|
852
|
+
const index = new Map<string, FuseEntity>();
|
|
853
|
+
const tableIds = new Set<string>();
|
|
854
|
+
for (const s of sources) {
|
|
855
|
+
for (const t of s.tables) {
|
|
856
|
+
const fields: Record<string, DomainFieldDef> = {};
|
|
857
|
+
const fks: Record<string, string> = {};
|
|
858
|
+
for (const c of t.columns) fields[c.name] = columnToField(c);
|
|
859
|
+
// Store FK targets as the unambiguous `source.table` id (FKs are intra-source)
|
|
860
|
+
// so `via`-path following resolves the intended table, never a same-named
|
|
861
|
+
// table in another source or a type-preferred bare id.
|
|
862
|
+
for (const fk of t.foreignKeys ?? []) fks[fk.column] = `${s.source}.${fk.refTable}`;
|
|
863
|
+
const entity: FuseEntity = { fields, fks };
|
|
864
|
+
index.set(`${s.source}.${t.name}`, entity);
|
|
865
|
+
tableIds.add(`${s.source}.${t.name}`);
|
|
866
|
+
if (!index.has(t.name)) {
|
|
867
|
+
index.set(t.name, entity);
|
|
868
|
+
tableIds.add(t.name);
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
const ambiguousIds = new Set<string>();
|
|
873
|
+
for (const [id, def] of Object.entries(types)) {
|
|
874
|
+
// The manifest type wins an unqualified id that also names a table; the table
|
|
875
|
+
// remains reachable by its `source.table` alias.
|
|
876
|
+
if (tableIds.has(id)) ambiguousIds.add(id);
|
|
877
|
+
index.set(id, { fields: { ...def.fields } });
|
|
878
|
+
}
|
|
879
|
+
return { index, tableIds, ambiguousIds };
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
/** Whether a manifest field keyword resolves to a primitive (vs a nominal ref). */
|
|
883
|
+
function isPrimitiveKeyword(type: string): boolean {
|
|
884
|
+
return Object.prototype.hasOwnProperty.call(PRIMITIVE_TS, type);
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
/** The shape ids a shape references (carry/project/reference targets, and an
|
|
888
|
+
* `extend` whose type names a shape) — the edges of the shape dependency graph. */
|
|
889
|
+
function referencedShapeIds(shape: ShapeDecl, shapeIds: Set<string>): string[] {
|
|
890
|
+
const refs = new Set<string>();
|
|
891
|
+
for (const op of shape.ops) {
|
|
892
|
+
if (op.op === "carry" || op.op === "project" || op.op === "reference") {
|
|
893
|
+
if (shapeIds.has(op.ref)) refs.add(op.ref);
|
|
894
|
+
} else if (op.op === "extend" && shapeIds.has(op.type)) {
|
|
895
|
+
refs.add(op.type);
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
return [...refs];
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
/** Structural equality of two domain field defs (`type` + normalized optional/list
|
|
902
|
+
* flags), so a differing property insertion order does not read as a conflict. */
|
|
903
|
+
function sameFieldDef(a: DomainFieldDef, b: DomainFieldDef): boolean {
|
|
904
|
+
return (
|
|
905
|
+
a.type === b.type &&
|
|
906
|
+
!!a.optional === !!b.optional &&
|
|
907
|
+
!!a.list === !!b.list
|
|
908
|
+
);
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
/**
|
|
912
|
+
* Resolve the project's composed shapes into `DomainTypeDef`s and diagnostics
|
|
913
|
+
* (ADR 0040 §10). Leaves (DB tables, manifest types) fuse first; shapes resolve in
|
|
914
|
+
* dependency order so a shape can carry another shape regardless of declaration
|
|
915
|
+
* order. A shape in a reference cycle, or one that names an unresolvable id, is
|
|
916
|
+
* omitted (degrades to untyped) with an `error` diagnostic; a deliberate field
|
|
917
|
+
* shadow with a differing type resolves with a `field-conflict` warning.
|
|
918
|
+
*/
|
|
919
|
+
export function resolveShapes(
|
|
920
|
+
shapes: ShapeDecl[],
|
|
921
|
+
types: DomainTypeRegistry,
|
|
922
|
+
sources: SourceSchema[] = [],
|
|
923
|
+
): ShapeResolution {
|
|
924
|
+
const diagnostics: ShapeDiagnostic[] = [];
|
|
925
|
+
const resolved: DomainTypeRegistry = {};
|
|
926
|
+
if (shapes.length === 0) return { types: resolved, diagnostics };
|
|
927
|
+
|
|
928
|
+
const { index, tableIds, ambiguousIds } = leafEntityIndex(sources, types);
|
|
929
|
+
// A nominal reference (an `extend` type or a non-spread `reference`) must resolve
|
|
930
|
+
// to a `DomainTypes` key at emit time — a manifest type or a resolved shape id.
|
|
931
|
+
// DB tables are spread-only (their fields flatten via carry/project); nominally
|
|
932
|
+
// referencing one would degrade to `unknown` in the emitted `.d.ts`, so we reject.
|
|
933
|
+
const nominalIds = new Set<string>(Object.keys(types));
|
|
934
|
+
// Duplicate shape ids are fuse-identity collisions: since resolution keys by id,
|
|
935
|
+
// a later declaration would silently shadow an earlier one. Report every id that
|
|
936
|
+
// appears more than once and omit all of its declarations from resolution.
|
|
937
|
+
const idCounts = new Map<string, number>();
|
|
938
|
+
for (const s of shapes) if (s.id) idCounts.set(s.id, (idCounts.get(s.id) ?? 0) + 1);
|
|
939
|
+
const duplicated = new Set<string>();
|
|
940
|
+
for (const [id, n] of idCounts) {
|
|
941
|
+
if (n > 1) {
|
|
942
|
+
duplicated.add(id);
|
|
943
|
+
diagnostics.push({
|
|
944
|
+
shape: id,
|
|
945
|
+
kind: "duplicate-id",
|
|
946
|
+
severity: "error",
|
|
947
|
+
message: `shape id "${id}" is declared ${n} times; ids are fuse identities and must be unique`,
|
|
948
|
+
});
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
const byId = new Map<string, ShapeDecl>();
|
|
952
|
+
for (const s of shapes) if (s.id && !duplicated.has(s.id)) byId.set(s.id, s);
|
|
953
|
+
const shapeIds = new Set(byId.keys());
|
|
954
|
+
|
|
955
|
+
// Cycle detection over the shape-only dependency graph (DFS three-colour). Every
|
|
956
|
+
// shape on a back edge is failed; the reported path aids the maker's fix.
|
|
957
|
+
const failed = new Set<string>();
|
|
958
|
+
const colour = new Map<string, 0 | 1 | 2>(); // 0=unvisited 1=on-stack 2=done
|
|
959
|
+
const visit = (id: string, stack: string[]): void => {
|
|
960
|
+
colour.set(id, 1);
|
|
961
|
+
stack.push(id);
|
|
962
|
+
for (const dep of referencedShapeIds(byId.get(id)!, shapeIds)) {
|
|
963
|
+
const c = colour.get(dep) ?? 0;
|
|
964
|
+
if (c === 1) {
|
|
965
|
+
const cycle = stack.slice(stack.indexOf(dep)).concat(dep);
|
|
966
|
+
for (const n of cycle) {
|
|
967
|
+
if (!failed.has(n)) {
|
|
968
|
+
failed.add(n);
|
|
969
|
+
diagnostics.push({
|
|
970
|
+
shape: n,
|
|
971
|
+
kind: "reference-cycle",
|
|
972
|
+
severity: "error",
|
|
973
|
+
message: `shape "${n}" is part of a reference cycle: ${cycle.join(" → ")}`,
|
|
974
|
+
});
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
} else if (c === 0) {
|
|
978
|
+
visit(dep, stack);
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
stack.pop();
|
|
982
|
+
colour.set(id, 2);
|
|
983
|
+
};
|
|
984
|
+
for (const id of byId.keys()) if ((colour.get(id) ?? 0) === 0) visit(id, []);
|
|
985
|
+
|
|
986
|
+
// Topological resolution: resolve a shape only after its (non-failed) shape
|
|
987
|
+
// dependencies, adding each resolved shape to the index so later shapes see it.
|
|
988
|
+
const done = new Set<string>();
|
|
989
|
+
const resolveOne = (shape: ShapeDecl): void => {
|
|
990
|
+
if (done.has(shape.id) || failed.has(shape.id)) return;
|
|
991
|
+
// Resolve shape dependencies first (they may themselves be pending).
|
|
992
|
+
for (const dep of referencedShapeIds(shape, shapeIds)) {
|
|
993
|
+
const d = byId.get(dep);
|
|
994
|
+
if (d && !done.has(dep) && !failed.has(dep)) resolveOne(d);
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
const fields: Record<string, DomainFieldDef> = {};
|
|
998
|
+
let broken = false;
|
|
999
|
+
const addField = (name: string, field: DomainFieldDef): void => {
|
|
1000
|
+
const existing = fields[name];
|
|
1001
|
+
if (existing && !sameFieldDef(existing, field)) {
|
|
1002
|
+
diagnostics.push({
|
|
1003
|
+
shape: shape.id,
|
|
1004
|
+
kind: "field-conflict",
|
|
1005
|
+
severity: "warning",
|
|
1006
|
+
message:
|
|
1007
|
+
`field "${name}" is contributed twice with differing types; the later value wins (author-order fold)`,
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
fields[name] = field; // last (author-order) wins
|
|
1011
|
+
};
|
|
1012
|
+
const lookup = (ref: string): FuseEntity | undefined => index.get(ref);
|
|
1013
|
+
const unresolved = (ref: string): void => {
|
|
1014
|
+
broken = true;
|
|
1015
|
+
diagnostics.push({
|
|
1016
|
+
shape: shape.id,
|
|
1017
|
+
kind: "unresolved-reference",
|
|
1018
|
+
severity: "error",
|
|
1019
|
+
message: `shape "${shape.id}" references unknown entity "${ref}"`,
|
|
1020
|
+
});
|
|
1021
|
+
};
|
|
1022
|
+
// A bare id that names both a manifest type and a table resolves to the type;
|
|
1023
|
+
// warn so the (silent) precedence is visible and the maker can qualify.
|
|
1024
|
+
const noteAmbiguity = (ref: string): void => {
|
|
1025
|
+
if (ambiguousIds.has(ref)) {
|
|
1026
|
+
diagnostics.push({
|
|
1027
|
+
shape: shape.id,
|
|
1028
|
+
kind: "ambiguous-reference",
|
|
1029
|
+
severity: "warning",
|
|
1030
|
+
message:
|
|
1031
|
+
`"${ref}" names both a manifest type and a table; resolved to the type — qualify as "<source>.${ref}" to target the table`,
|
|
1032
|
+
});
|
|
1033
|
+
}
|
|
1034
|
+
};
|
|
1035
|
+
// Report a nominal reference (extend type / non-spread reference) that targets a
|
|
1036
|
+
// DB table, which cannot be expressed as a `DomainTypes` ref (it would degrade to
|
|
1037
|
+
// `unknown`); the maker should spread it instead (carry/project or spread=true).
|
|
1038
|
+
const nominalTableRef = (kind: string, ref: string): void => {
|
|
1039
|
+
broken = true;
|
|
1040
|
+
diagnostics.push({
|
|
1041
|
+
shape: shape.id,
|
|
1042
|
+
kind: "nominal-table-ref",
|
|
1043
|
+
severity: "error",
|
|
1044
|
+
message:
|
|
1045
|
+
`${kind} nominally references table "${ref}", which is not a DomainTypes entity; spread its fields (carry/project or reference spread="true") instead`,
|
|
1046
|
+
});
|
|
1047
|
+
};
|
|
1048
|
+
|
|
1049
|
+
for (const op of shape.ops) {
|
|
1050
|
+
switch (op.op) {
|
|
1051
|
+
case "carry": {
|
|
1052
|
+
const e = lookup(op.ref);
|
|
1053
|
+
if (!e) { unresolved(op.ref); break; }
|
|
1054
|
+
noteAmbiguity(op.ref);
|
|
1055
|
+
for (const [k, f] of Object.entries(e.fields)) addField(k, f);
|
|
1056
|
+
break;
|
|
1057
|
+
}
|
|
1058
|
+
case "project": {
|
|
1059
|
+
const e = lookup(op.ref);
|
|
1060
|
+
if (!e) { unresolved(op.ref); break; }
|
|
1061
|
+
noteAmbiguity(op.ref);
|
|
1062
|
+
for (const fname of op.fields) {
|
|
1063
|
+
const f = e.fields[fname];
|
|
1064
|
+
if (!f) {
|
|
1065
|
+
broken = true;
|
|
1066
|
+
diagnostics.push({
|
|
1067
|
+
shape: shape.id,
|
|
1068
|
+
kind: "unknown-field",
|
|
1069
|
+
severity: "error",
|
|
1070
|
+
message: `projected field "${fname}" is not a field of "${op.ref}"`,
|
|
1071
|
+
});
|
|
1072
|
+
continue;
|
|
1073
|
+
}
|
|
1074
|
+
addField(fname, f);
|
|
1075
|
+
}
|
|
1076
|
+
if (op.via) validateVia(shape.id, op.via, index, diagnostics);
|
|
1077
|
+
break;
|
|
1078
|
+
}
|
|
1079
|
+
case "extend": {
|
|
1080
|
+
if (!isPrimitiveKeyword(op.type)) {
|
|
1081
|
+
if (nominalIds.has(op.type)) {
|
|
1082
|
+
// ok — a manifest type or an already-resolved shape id
|
|
1083
|
+
} else if (tableIds.has(op.type)) {
|
|
1084
|
+
nominalTableRef(`extend field "${op.name}"`, op.type);
|
|
1085
|
+
break;
|
|
1086
|
+
} else {
|
|
1087
|
+
broken = true;
|
|
1088
|
+
diagnostics.push({
|
|
1089
|
+
shape: shape.id,
|
|
1090
|
+
kind: "unresolved-reference",
|
|
1091
|
+
severity: "error",
|
|
1092
|
+
message:
|
|
1093
|
+
`extend field "${op.name}" has type "${op.type}", which is neither a scalar keyword nor a fused entity`,
|
|
1094
|
+
});
|
|
1095
|
+
break;
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
const field: DomainFieldDef = { type: op.type };
|
|
1099
|
+
if (op.optional) field.optional = true;
|
|
1100
|
+
if (op.list) field.list = true;
|
|
1101
|
+
addField(op.name, field);
|
|
1102
|
+
break;
|
|
1103
|
+
}
|
|
1104
|
+
case "reference": {
|
|
1105
|
+
const e = lookup(op.ref);
|
|
1106
|
+
if (!e) { unresolved(op.ref); break; }
|
|
1107
|
+
if (op.spread) {
|
|
1108
|
+
noteAmbiguity(op.ref);
|
|
1109
|
+
for (const [k, f] of Object.entries(e.fields)) addField(k, f);
|
|
1110
|
+
} else if (!nominalIds.has(op.ref)) {
|
|
1111
|
+
// `e` exists but the id is not a DomainTypes key — it is a DB table.
|
|
1112
|
+
nominalTableRef(`reference "${op.name}"`, op.ref);
|
|
1113
|
+
} else {
|
|
1114
|
+
const field: DomainFieldDef = { type: op.ref };
|
|
1115
|
+
if (op.list) field.list = true;
|
|
1116
|
+
addField(op.name, field);
|
|
1117
|
+
}
|
|
1118
|
+
break;
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
// same-id collision: the shape id shadows a leaf entity it does not source.
|
|
1124
|
+
const sourcesRef = new Set(
|
|
1125
|
+
shape.ops.flatMap((o) => (o.op === "extend" ? [] : [o.ref])),
|
|
1126
|
+
);
|
|
1127
|
+
if (index.has(shape.id) && !sourcesRef.has(shape.id)) {
|
|
1128
|
+
diagnostics.push({
|
|
1129
|
+
shape: shape.id,
|
|
1130
|
+
kind: "same-id-collision",
|
|
1131
|
+
severity: "error",
|
|
1132
|
+
message:
|
|
1133
|
+
`shape id "${shape.id}" collides with an existing fused entity it does not compose`,
|
|
1134
|
+
});
|
|
1135
|
+
broken = true;
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
done.add(shape.id);
|
|
1139
|
+
if (broken) {
|
|
1140
|
+
failed.add(shape.id);
|
|
1141
|
+
return;
|
|
1142
|
+
}
|
|
1143
|
+
const def: DomainTypeDef = { name: shape.name, fields };
|
|
1144
|
+
resolved[shape.id] = def;
|
|
1145
|
+
// Later shapes may carry this one; expose its resolved fields to the index and
|
|
1146
|
+
// mark it nominal-referenceable (it will be a `DomainTypes` key).
|
|
1147
|
+
index.set(shape.id, { fields });
|
|
1148
|
+
nominalIds.add(shape.id);
|
|
1149
|
+
};
|
|
1150
|
+
for (const s of shapes) if (s.id && !duplicated.has(s.id)) resolveOne(s);
|
|
1151
|
+
|
|
1152
|
+
return { types: resolved, diagnostics };
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
/** Validate a `project via` FK path (`Entity.column[.column...]`): the leading
|
|
1156
|
+
* entity must resolve and carry the named column (an FK column on a DB table, or
|
|
1157
|
+
* any field on a manifest type/shape). Deeper hops are validated leniently — the
|
|
1158
|
+
* FK target is followed when the leading entity is a DB table with that FK. */
|
|
1159
|
+
function validateVia(
|
|
1160
|
+
shape: string,
|
|
1161
|
+
via: string,
|
|
1162
|
+
index: Map<string, FuseEntity>,
|
|
1163
|
+
diagnostics: ShapeDiagnostic[],
|
|
1164
|
+
): void {
|
|
1165
|
+
const parts = via.split(".");
|
|
1166
|
+
if (parts.length < 2) {
|
|
1167
|
+
diagnostics.push({
|
|
1168
|
+
shape,
|
|
1169
|
+
kind: "unknown-field",
|
|
1170
|
+
severity: "warning",
|
|
1171
|
+
message: `via path "${via}" is not of the form Entity.column`,
|
|
1172
|
+
});
|
|
1173
|
+
return;
|
|
1174
|
+
}
|
|
1175
|
+
// Resolve the starting entity as the *longest* dotted prefix present in the index
|
|
1176
|
+
// (so a qualified `source.table` start works, not just a bare id), leaving at least
|
|
1177
|
+
// one trailing segment as a hop column. The remaining segments are hop columns.
|
|
1178
|
+
let entity: FuseEntity | undefined;
|
|
1179
|
+
let start = 0;
|
|
1180
|
+
for (let p = 1; p < parts.length; p++) {
|
|
1181
|
+
const candidate = parts.slice(0, p).join(".");
|
|
1182
|
+
const hit = index.get(candidate);
|
|
1183
|
+
if (hit) {
|
|
1184
|
+
entity = hit;
|
|
1185
|
+
start = p;
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
if (!entity) {
|
|
1189
|
+
diagnostics.push({
|
|
1190
|
+
shape,
|
|
1191
|
+
kind: "unknown-field",
|
|
1192
|
+
severity: "warning",
|
|
1193
|
+
message: `via path "${via}" starts at unknown entity "${parts.slice(0, -1).join(".")}"`,
|
|
1194
|
+
});
|
|
1195
|
+
return;
|
|
1196
|
+
}
|
|
1197
|
+
let cursor: FuseEntity = entity;
|
|
1198
|
+
for (let i = start; i < parts.length; i++) {
|
|
1199
|
+
const col = parts[i];
|
|
1200
|
+
const hasField = Object.prototype.hasOwnProperty.call(cursor.fields, col);
|
|
1201
|
+
const fkTarget: string | undefined = cursor.fks?.[col];
|
|
1202
|
+
if (!hasField && !fkTarget) {
|
|
1203
|
+
diagnostics.push({
|
|
1204
|
+
shape,
|
|
1205
|
+
kind: "unknown-field",
|
|
1206
|
+
severity: "warning",
|
|
1207
|
+
message: `via path "${via}" hops through unknown column "${col}"`,
|
|
1208
|
+
});
|
|
1209
|
+
return;
|
|
1210
|
+
}
|
|
1211
|
+
// Follow the FK to the next entity when we can; otherwise stop (lenient).
|
|
1212
|
+
const next: FuseEntity | undefined = fkTarget ? index.get(fkTarget) : undefined;
|
|
1213
|
+
if (!next) return;
|
|
1214
|
+
cursor = next;
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
// --- model-level metadata: the typed accessor (ADR 0040 §5) ------------------
|
|
1219
|
+
//
|
|
1220
|
+
// A model carries free-form governance/state metadata *about the process itself*
|
|
1221
|
+
// (e.g. `classification=internal`) as `nano:meta` key/value siblings of the
|
|
1222
|
+
// `nano:shapes` container (see `console/src/lib/shapeCarrier.ts` and the Rust scan
|
|
1223
|
+
// `envelope_scan.rs`). The scan lifts these into `derivedMeta`; the `domaintypes`
|
|
1224
|
+
// op folds them into a typed `meta.ts` accessor so app code can query them
|
|
1225
|
+
// app-wide (`@nanobpm/meta`) without a second store, and into the structured fuse
|
|
1226
|
+
// (`domain.json`) tagged with their `model:<processId>` provenance.
|
|
1227
|
+
|
|
1228
|
+
/** The basename of the generated typed model-metadata accessor (`@nanobpm/meta`). */
|
|
1229
|
+
export const META_TS = "meta.ts";
|
|
1230
|
+
|
|
1231
|
+
/** One model-level metadata entry (`nano:meta`), tagged with its defining process
|
|
1232
|
+
* for the `model:<processId>` provenance (ADR 0040 §5). */
|
|
1233
|
+
export interface MetaDecl {
|
|
1234
|
+
/** The defining process id, for provenance. */
|
|
1235
|
+
process?: string;
|
|
1236
|
+
key: string;
|
|
1237
|
+
value: string;
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
/** Fold the scanned model-level metadata into a single key→value record. When two
|
|
1241
|
+
* models declare the same key the last (scan order) wins — the fold is a flat
|
|
1242
|
+
* app-wide view where a later declaration overrides an earlier one (matching the
|
|
1243
|
+
* editor's "last write wins" affordance and JS object semantics). Empty keys are
|
|
1244
|
+
* ignored. The accumulator is a **null-prototype** dict: keys are user-authored, so
|
|
1245
|
+
* a plain `{}` would route a `__proto__` key through the `Object.prototype` setter
|
|
1246
|
+
* (creating no own property → silently dropped from `Object.keys`) and let inherited
|
|
1247
|
+
* members shadow real ones. `Object.create(null)` makes every assignment an own data
|
|
1248
|
+
* property, so all keys (including `__proto__`) round-trip deterministically. */
|
|
1249
|
+
export function foldMeta(metas: MetaDecl[]): Record<string, string> {
|
|
1250
|
+
const out: Record<string, string> = Object.create(null);
|
|
1251
|
+
for (const m of metas) {
|
|
1252
|
+
const key = (m?.key ?? "").trim();
|
|
1253
|
+
if (!key) continue;
|
|
1254
|
+
out[key] = m.value ?? "";
|
|
1255
|
+
}
|
|
1256
|
+
return out;
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
/**
|
|
1260
|
+
* Emit `meta.ts`: the typed model-metadata accessor (`@nanobpm/meta`, ADR 0040
|
|
1261
|
+
* §5). `AppMeta` keys the declared metadata as string-literal properties so
|
|
1262
|
+
* `meta("classification")` autocompletes and is checked; `appMeta` is the concrete
|
|
1263
|
+
* record; the overloaded `meta()` returns the typed value for a known key and
|
|
1264
|
+
* `string | undefined` for a dynamic one. Dual-runtime: only type-level constructs
|
|
1265
|
+
* plus a plain object, so Node's strip-only mode accepts it (ADR 0036).
|
|
1266
|
+
*/
|
|
1267
|
+
export function emitMeta(metas: MetaDecl[]): string {
|
|
1268
|
+
const folded = foldMeta(metas);
|
|
1269
|
+
const keys = Object.keys(folded);
|
|
1270
|
+
const propKey = (k: string) => (isIdent(k) ? k : JSON.stringify(k));
|
|
1271
|
+
const header =
|
|
1272
|
+
"// AUTO-GENERATED by nanobpmn from the process model (ADR 0040 §5): the typed\n" +
|
|
1273
|
+
"// model-metadata accessor. Each `nano:meta` key/value the models declare becomes\n" +
|
|
1274
|
+
"// a checked `AppMeta` property, so `meta(key)` is typed and app-wide queryable\n" +
|
|
1275
|
+
"// without a second store. Do not edit — regenerated from the model.\n" +
|
|
1276
|
+
"// eslint-disable\n\n";
|
|
1277
|
+
const iface = keys.length > 0
|
|
1278
|
+
? `export interface AppMeta {\n${keys.map((k) => ` ${propKey(k)}: string;`).join("\n")}\n}\n`
|
|
1279
|
+
: `export interface AppMeta {}\n`;
|
|
1280
|
+
// `appMeta` is a **null-prototype** dict populated by bracket assignment: meta
|
|
1281
|
+
// keys are user-authored, so a prototype chain would let `meta("toString")` /
|
|
1282
|
+
// `meta("constructor")` return an inherited function instead of `undefined`, and
|
|
1283
|
+
// a literal `__proto__` key would corrupt the object. `Object.create(null)` +
|
|
1284
|
+
// `m[key] = …` makes every lookup an own-property read and every write a plain
|
|
1285
|
+
// data property (safe even for a `__proto__` key). Strip-safe (plain JS + erased
|
|
1286
|
+
// annotations, ADR 0036).
|
|
1287
|
+
const constDecl = keys.length > 0
|
|
1288
|
+
? `export const appMeta: AppMeta = (() => {\n` +
|
|
1289
|
+
` const m: Record<string, string> = Object.create(null);\n` +
|
|
1290
|
+
keys.map((k) => ` m[${JSON.stringify(k)}] = ${JSON.stringify(folded[k])};`).join("\n") +
|
|
1291
|
+
`\n return m as AppMeta;\n})();\n`
|
|
1292
|
+
: `export const appMeta: AppMeta = Object.create(null) as AppMeta;\n`;
|
|
1293
|
+
const accessor =
|
|
1294
|
+
`\n/** Read a model-level metadata value. A declared key is typed; a dynamic key\n` +
|
|
1295
|
+
` * returns \`string | undefined\`. */\n` +
|
|
1296
|
+
`export function meta<K extends keyof AppMeta>(key: K): AppMeta[K];\n` +
|
|
1297
|
+
`export function meta(key: string): string | undefined;\n` +
|
|
1298
|
+
`export function meta(key: string): string | undefined {\n` +
|
|
1299
|
+
` return (appMeta as Record<string, string>)[key];\n` +
|
|
1300
|
+
`}\n`;
|
|
1301
|
+
return `${header}/** Every model-level metadata key the App's models declare (ADR 0040 §5). */\n` +
|
|
1302
|
+
iface + "\n" + constDecl + accessor;
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
// --- the structured fused domain model: domain.json (ADR 0040 §1, OQ1) -------
|
|
1306
|
+
//
|
|
1307
|
+
// The computed fuse is persisted as a generated, git-ignored `nano-generated/
|
|
1308
|
+
// domain.json` — a fast-read structured index for the IDE/codegen so a reader need
|
|
1309
|
+
// not re-scan every model + datasource. It is a *cache*, never a source: the
|
|
1310
|
+
// `domaintypes` op regenerates it write-through on any source change, and an
|
|
1311
|
+
// `inputsHash` over its own content lets a reader detect staleness cheaply.
|
|
1312
|
+
|
|
1313
|
+
/** The basename of the generated structured fuse cache (ADR 0040 §1). */
|
|
1314
|
+
export const DOMAIN_MODEL_JSON = "domain.json";
|
|
1315
|
+
|
|
1316
|
+
/** A field of a fused entity in `domain.json`: the resolved domain field plus its
|
|
1317
|
+
* name. `type` is a primitive keyword or the id of another fused entity. */
|
|
1318
|
+
interface FusedFieldJson extends DomainFieldDef {
|
|
1319
|
+
name: string;
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
/** One fused entity in `domain.json`, tagged with its provenance and kind. */
|
|
1323
|
+
interface FusedEntityJson {
|
|
1324
|
+
id: string;
|
|
1325
|
+
kind: "table" | "type" | "shape";
|
|
1326
|
+
/** `db:<source>.<table>` | `manifest:<id>` | `model:<processId>`. */
|
|
1327
|
+
provenance: string;
|
|
1328
|
+
name?: string;
|
|
1329
|
+
fields: FusedFieldJson[];
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
/** FNV-1a (32-bit) hex of a string — a small, dependency-free content tag for the
|
|
1333
|
+
* fuse cache's `inputsHash` (staleness detection, not security). */
|
|
1334
|
+
function fnv1aHex(s: string): string {
|
|
1335
|
+
let h = 0x811c9dc5;
|
|
1336
|
+
for (let i = 0; i < s.length; i++) {
|
|
1337
|
+
h ^= s.charCodeAt(i);
|
|
1338
|
+
h = Math.imul(h, 0x01000193);
|
|
1339
|
+
}
|
|
1340
|
+
return (h >>> 0).toString(16).padStart(8, "0");
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
/** Convert a resolved field map to the ordered `domain.json` field list. */
|
|
1344
|
+
function fieldsJson(fields: Record<string, DomainFieldDef>): FusedFieldJson[] {
|
|
1345
|
+
return Object.entries(fields ?? {}).map(([name, f]) => {
|
|
1346
|
+
const out: FusedFieldJson = { name, type: f.type };
|
|
1347
|
+
if (f.optional) out.optional = true;
|
|
1348
|
+
if (f.list) out.list = true;
|
|
1349
|
+
return out;
|
|
1350
|
+
});
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
/**
|
|
1354
|
+
* Emit `domain.json`: the structured Fused Domain Model (ADR 0040 §1). Assembles
|
|
1355
|
+
* every fused entity — DB tables (`db:` provenance), manifest `types` (`manifest:`),
|
|
1356
|
+
* and composed motion shapes (`model:<processId>`, or bare `model` for an unsaved
|
|
1357
|
+
* editor shape with no process) — with its resolved fields, plus
|
|
1358
|
+
* the model-level metadata and the shape diagnostics. An `inputsHash` — FNV-1a
|
|
1359
|
+
* (hex) over the compact `JSON.stringify` of the model object with `inputsHash`
|
|
1360
|
+
* omitted (property-insertion order, not the pretty-printed bytes) — tags the
|
|
1361
|
+
* cache for staleness.
|
|
1362
|
+
*/
|
|
1363
|
+
export function emitDomainModelJson(input: {
|
|
1364
|
+
sources: SourceSchema[];
|
|
1365
|
+
default?: string;
|
|
1366
|
+
manifestTypes: DomainTypeRegistry;
|
|
1367
|
+
/** Resolved shapes paired with their declaration (for provenance/label). */
|
|
1368
|
+
shapes: { decl: ShapeDecl; def: DomainTypeDef }[];
|
|
1369
|
+
meta: MetaDecl[];
|
|
1370
|
+
diagnostics: ShapeDiagnostic[];
|
|
1371
|
+
}): string {
|
|
1372
|
+
const entities: FusedEntityJson[] = [];
|
|
1373
|
+
for (const s of input.sources) {
|
|
1374
|
+
for (const t of s.tables) {
|
|
1375
|
+
const fields: Record<string, DomainFieldDef> = {};
|
|
1376
|
+
for (const c of t.columns) fields[c.name] = columnToField(c);
|
|
1377
|
+
entities.push({
|
|
1378
|
+
id: `${s.source}.${t.name}`,
|
|
1379
|
+
kind: "table",
|
|
1380
|
+
provenance: `db:${s.source}.${t.name}`,
|
|
1381
|
+
fields: fieldsJson(fields),
|
|
1382
|
+
});
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
for (const [id, def] of Object.entries(input.manifestTypes)) {
|
|
1386
|
+
entities.push({
|
|
1387
|
+
id,
|
|
1388
|
+
kind: "type",
|
|
1389
|
+
provenance: `manifest:${id}`,
|
|
1390
|
+
...(def.name ? { name: def.name } : {}),
|
|
1391
|
+
fields: fieldsJson(def.fields),
|
|
1392
|
+
});
|
|
1393
|
+
}
|
|
1394
|
+
for (const { decl, def } of input.shapes) {
|
|
1395
|
+
entities.push({
|
|
1396
|
+
id: decl.id,
|
|
1397
|
+
kind: "shape",
|
|
1398
|
+
provenance: decl.process ? `model:${decl.process}` : "model",
|
|
1399
|
+
...(def.name ?? decl.name ? { name: def.name ?? decl.name } : {}),
|
|
1400
|
+
fields: fieldsJson(def.fields),
|
|
1401
|
+
});
|
|
1402
|
+
}
|
|
1403
|
+
const meta = input.meta
|
|
1404
|
+
.filter((m) => (m?.key ?? "").trim().length > 0)
|
|
1405
|
+
.map((m) => ({ ...(m.process ? { process: m.process } : {}), key: m.key, value: m.value ?? "" }));
|
|
1406
|
+
const model = {
|
|
1407
|
+
$generated: "nanobpmn ADR 0040 §1 Fused Domain Model — do not edit; regenerated by the domaintypes op",
|
|
1408
|
+
version: 1,
|
|
1409
|
+
...(input.default ? { default: input.default } : {}),
|
|
1410
|
+
sources: input.sources.map((s) => s.source),
|
|
1411
|
+
entities,
|
|
1412
|
+
meta,
|
|
1413
|
+
diagnostics: input.diagnostics,
|
|
1414
|
+
inputsHash: "",
|
|
1415
|
+
};
|
|
1416
|
+
model.inputsHash = fnv1aHex(JSON.stringify({ ...model, inputsHash: undefined }));
|
|
1417
|
+
return `${JSON.stringify(model, null, 2)}\n`;
|
|
1418
|
+
}
|