@nanobpm/urban 0.17.0 → 0.18.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.
Files changed (37) hide show
  1. package/dist/cli.js +69 -5
  2. package/dist/toolkit/derivers/domain.d.ts +69 -0
  3. package/dist/toolkit/derivers/domain.js +243 -0
  4. package/dist/toolkit/derivers/messages.d.ts +36 -0
  5. package/dist/toolkit/derivers/messages.js +134 -0
  6. package/dist/toolkit/derivers/meta.d.ts +34 -0
  7. package/dist/toolkit/derivers/meta.js +106 -0
  8. package/dist/toolkit/derivers/migrations.d.ts +34 -1
  9. package/dist/toolkit/derivers/migrations.js +37 -8
  10. package/dist/toolkit/derivers/worker-io.d.ts +14 -0
  11. package/dist/toolkit/derivers/worker-io.js +13 -2
  12. package/dist/toolkit/fsio.js +31 -2
  13. package/dist/toolkit/gen.d.ts +28 -0
  14. package/dist/toolkit/gen.js +60 -11
  15. package/dist/toolkit/index.d.ts +18 -4
  16. package/dist/toolkit/index.js +12 -3
  17. package/dist/toolkit/models.d.ts +63 -0
  18. package/dist/toolkit/models.js +142 -0
  19. package/package.json +1 -1
  20. package/src/cli.ts +70 -5
  21. package/src/toolkit/derivers/domain.test.ts +140 -0
  22. package/src/toolkit/derivers/domain.ts +317 -0
  23. package/src/toolkit/derivers/messages.test.ts +174 -0
  24. package/src/toolkit/derivers/messages.ts +166 -0
  25. package/src/toolkit/derivers/meta.test.ts +140 -0
  26. package/src/toolkit/derivers/meta.ts +128 -0
  27. package/src/toolkit/derivers/migrations.test.ts +42 -4
  28. package/src/toolkit/derivers/migrations.ts +61 -9
  29. package/src/toolkit/derivers/worker-io.test.ts +10 -0
  30. package/src/toolkit/derivers/worker-io.ts +14 -2
  31. package/src/toolkit/fsio.test.ts +23 -0
  32. package/src/toolkit/fsio.ts +22 -2
  33. package/src/toolkit/gen.test.ts +84 -2
  34. package/src/toolkit/gen.ts +86 -12
  35. package/src/toolkit/index.ts +66 -3
  36. package/src/toolkit/models.test.ts +159 -0
  37. package/src/toolkit/models.ts +193 -0
@@ -0,0 +1,317 @@
1
+ // Deriver: manifest `types` → `domain-rows.d.ts`, the domain row-type contract (ADR 0029 §4.1/§6,
2
+ // ADR 0053). Two blocks compose into one generated `.d.ts`:
3
+ // • the **table spine** — one `interface` per persisted table plus a `DomainTables` lookup
4
+ // keyed by wire name, so a worker types `DomainTables["greetings"]`; and
5
+ // • the **`DomainTypes` registry** — the declared (transient) manifest types keyed by id, so
6
+ // envelope/worker/message refs resolve to `DomainTypes["<id>"]` (see `typeRefFor`).
7
+ //
8
+ // Byte-faithful port of the console's `emitDomainModel`/`emitDomainDts…`/`emitDomainTypeRegistry`
9
+ // (server `domain_types.ts`), so the toolkit is a drop-in for the IDE's codegen. The emitters are
10
+ // pure; the table spine is derived from the manifest (code-first, ADR 0054) via the *same*
11
+ // canonical `tableSchemaForType` the SQL migration uses — one schema truth, no drift surface.
12
+
13
+ import type { DerivedArtifact, Deriver } from "../artifact.ts";
14
+ import { GENERATED_DIR } from "../artifact.ts";
15
+ import { DOMAIN_DTS } from "./worker-io.ts";
16
+ import type { ColumnMeta, TableMeta } from "../../runtime/core/modules/gateway.ts";
17
+ import {
18
+ groupTypesBySource,
19
+ tableSchemaForType,
20
+ type ToolkitManifest,
21
+ type ToolkitType,
22
+ } from "./migrations.ts";
23
+
24
+ // The introspected-schema types (`ColumnMeta`/`TableMeta`) are the runtime gateway's canonical
25
+ // definitions — the single source of truth the driver introspection, the page runtime, and this
26
+ // domain projection all share (no parallel schema shape). Re-exported for convenience.
27
+ export type { ColumnMeta, TableMeta };
28
+
29
+ /** One datasource's tables, paired with its manifest alias. */
30
+ export interface SourceSchema {
31
+ source: string;
32
+ tables: TableMeta[];
33
+ }
34
+
35
+ // --- table spine emitters (port of domain_types.ts) ------------------------------------------
36
+
37
+ /**
38
+ * Map a SQLite declared column type to a TypeScript field type. SQLite is dynamically typed but
39
+ * assigns each column a *type affinity* from its declared name, so we apply the affinity rules
40
+ * (https://sqlite.org/datatype3.html §3.1) with two maker-friendly overrides: `BOOLEAN` →
41
+ * `boolean` and date/time types → `string` (ISO text), matching how Urban surfaces them.
42
+ */
43
+ export function sqliteAffinityToTs(declaredType: string): string {
44
+ const t = declaredType.toUpperCase();
45
+ if (t.length === 0) return "unknown"; // NONE affinity — opaque
46
+ if (t.includes("BOOL")) return "boolean";
47
+ if (t.includes("DATE") || t.includes("TIME")) return "string";
48
+ if (t.includes("INT")) return "number";
49
+ if (t.includes("CHAR") || t.includes("CLOB") || t.includes("TEXT")) return "string";
50
+ if (t.includes("BLOB")) return "Uint8Array";
51
+ if (t.includes("REAL") || t.includes("FLOA") || t.includes("DOUB")) return "number";
52
+ return "number"; // NUMERIC affinity
53
+ }
54
+
55
+ /** A TS identifier is safe to use bare as a property name / type name. */
56
+ function isIdent(name: string): boolean {
57
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
58
+ }
59
+
60
+ /** PascalCase a table name into an interface name, sanitised to an identifier. */
61
+ export function interfaceName(table: string): string {
62
+ const pascal = table
63
+ .replace(/[^A-Za-z0-9]+/g, " ")
64
+ .trim()
65
+ .split(/\s+/)
66
+ .map((w) => (w ? w[0].toUpperCase() + w.slice(1) : ""))
67
+ .join("");
68
+ const safe = pascal.replace(/[^A-Za-z0-9_$]/g, "");
69
+ return /^[A-Za-z_$]/.test(safe) ? safe : `T_${safe}`;
70
+ }
71
+
72
+ /** The TS field type for a column: nullable columns widen with `| null`. */
73
+ function fieldType(col: ColumnMeta): string {
74
+ const base = sqliteAffinityToTs(col.type);
75
+ // A NOT NULL column (or the INTEGER PRIMARY KEY rowid alias) is never null.
76
+ return col.notNull || col.primaryKey ? base : `${base} | null`;
77
+ }
78
+
79
+ /** One `export interface` block for a table under an explicit interface name. */
80
+ function tableInterfaceNamed(name: string, t: TableMeta): string {
81
+ const fields = t.columns
82
+ .map((c) => {
83
+ const key = isIdent(c.name) ? c.name : JSON.stringify(c.name);
84
+ const pk = c.primaryKey ? " (primary key)" : "";
85
+ return ` /** ${c.type || "?"}${pk} */\n ${key}: ${fieldType(c)};`;
86
+ })
87
+ .join("\n");
88
+ return `export interface ${name} {\n${fields}\n}`;
89
+ }
90
+
91
+ /** One `export interface` block for a table (name derived from the table). */
92
+ function tableInterface(t: TableMeta): string {
93
+ return tableInterfaceNamed(interfaceName(t.name), t);
94
+ }
95
+
96
+ /**
97
+ * Emit the full `domain-rows.d.ts` from a datasource's tables: one `interface` per table plus a
98
+ * `DomainTables` lookup keyed by the *raw* table name, so callers write `DomainTables["customers"]`.
99
+ */
100
+ export function emitDomainDts(tables: TableMeta[]): string {
101
+ const header =
102
+ "// AUTO-GENERATED by nanobpmn from the datasource schema (ADR 0029 §4.1).\n" +
103
+ "// Do not edit — regenerated from the live tables. Erased at `deno compile`.\n" +
104
+ "// eslint-disable\n";
105
+ if (tables.length === 0) {
106
+ return `${header}\nexport interface DomainTables {}\n`;
107
+ }
108
+ const interfaces = tables.map(tableInterface).join("\n\n");
109
+ const map = tables
110
+ .map((t) => ` ${JSON.stringify(t.name)}: ${interfaceName(t.name)};`)
111
+ .join("\n");
112
+ 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`;
113
+ }
114
+
115
+ /**
116
+ * The interface name for a table in a multi-source union: the source alias is PascalCased and
117
+ * prefixed to the table's interface name so tables that share a name across datasources get
118
+ * distinct, collision-free interfaces (`AppCustomers`, `AnalyticsCustomers`).
119
+ */
120
+ function prefixedInterfaceName(source: string, table: string): string {
121
+ return `${interfaceName(source)}${interfaceName(table)}`;
122
+ }
123
+
124
+ /**
125
+ * Emit `domain-rows.d.ts` for an App that declares *multiple* datasources: one `interface` per
126
+ * (source, table), a `DomainSources` map keyed by alias then wire table name, and a `DomainTables`
127
+ * alias to the default source. When there is one source (or none) this is byte-identical to
128
+ * `emitDomainDts` so the common case stays stable.
129
+ */
130
+ export function emitDomainDtsForSources(
131
+ sources: SourceSchema[],
132
+ defaultSource?: string,
133
+ ): string {
134
+ if (sources.length <= 1) {
135
+ return emitDomainDts(sources[0]?.tables ?? []);
136
+ }
137
+ const header =
138
+ "// AUTO-GENERATED by nanobpmn from the datasource schemas (ADR 0029 §4.1/§6).\n" +
139
+ "// Do not edit — regenerated from the live tables. Erased at `deno compile`.\n" +
140
+ "// eslint-disable\n";
141
+
142
+ const interfaces = sources
143
+ .flatMap((s) =>
144
+ s.tables.map((t) =>
145
+ tableInterfaceNamed(prefixedInterfaceName(s.source, t.name), t)
146
+ )
147
+ )
148
+ .join("\n\n");
149
+
150
+ const sourceMap = sources
151
+ .map((s) => {
152
+ if (s.tables.length === 0) return ` ${JSON.stringify(s.source)}: {};`;
153
+ const tableMap = s.tables
154
+ .map((t) =>
155
+ ` ${JSON.stringify(t.name)}: ${prefixedInterfaceName(s.source, t.name)};`
156
+ )
157
+ .join("\n");
158
+ return ` ${JSON.stringify(s.source)}: {\n${tableMap}\n };`;
159
+ })
160
+ .join("\n");
161
+
162
+ const def = defaultSource && sources.some((s) => s.source === defaultSource)
163
+ ? defaultSource
164
+ : sources[0].source;
165
+
166
+ return `${header}\n${interfaces}\n\n` +
167
+ `/** Every datasource keyed by alias, then table by wire name. */\n` +
168
+ `export interface DomainSources {\n${sourceMap}\n}\n\n` +
169
+ `/** The default datasource's tables — index by wire name. */\n` +
170
+ `export type DomainTables = DomainSources[${JSON.stringify(def)}];\n`;
171
+ }
172
+
173
+ // --- manifest `types` registry (ADR 0029 §4.2) -----------------------------------------------
174
+
175
+ /** One field of a declared domain type in the manifest `types` registry. */
176
+ export interface DomainFieldDef {
177
+ /** A primitive keyword or the id of another registry type (nominal ref). */
178
+ type: string;
179
+ optional?: boolean;
180
+ list?: boolean;
181
+ }
182
+
183
+ /** A declared (transient) domain record type from the manifest `types` block. */
184
+ export interface DomainTypeDef {
185
+ name?: string;
186
+ match?: string;
187
+ table?: string;
188
+ fields: Record<string, DomainFieldDef>;
189
+ }
190
+
191
+ /** The manifest `types` registry: type id → declared record type. */
192
+ export type DomainTypeRegistry = Record<string, DomainTypeDef>;
193
+
194
+ /** Manifest primitive field keywords → TS types (ADR 0029 §4.2 / schema). */
195
+ const PRIMITIVE_TS: Record<string, string> = {
196
+ string: "string",
197
+ number: "number",
198
+ integer: "number",
199
+ boolean: "boolean",
200
+ date: "string",
201
+ datetime: "string",
202
+ json: "unknown",
203
+ };
204
+
205
+ /**
206
+ * The TS type for a registry field. A primitive keyword maps directly (and takes precedence over
207
+ * an identically named type, per the schema); anything else is a nominal reference to another
208
+ * registry type, emitted as an indexed access into `DomainTypes`. An unresolved reference degrades
209
+ * to `unknown`. `list` wraps the base type in `[]`.
210
+ */
211
+ function fieldTsType(field: DomainFieldDef, ids: Set<string>): string {
212
+ const base = PRIMITIVE_TS[field.type] ??
213
+ (ids.has(field.type) ? `DomainTypes[${JSON.stringify(field.type)}]` : "unknown");
214
+ return field.list ? `${base}[]` : base;
215
+ }
216
+
217
+ /**
218
+ * Emit the `DomainTypes` block for the manifest `types` registry: an inline map keyed by type id.
219
+ * Returns `""` when the registry is empty, so the table spine stays byte-identical when no types
220
+ * are declared. `optional` widens the key with `?`.
221
+ */
222
+ export function emitDomainTypeRegistry(types: DomainTypeRegistry): string {
223
+ const ids = new Set(Object.keys(types));
224
+ if (ids.size === 0) return "";
225
+ const entries = Object.entries(types)
226
+ .map(([id, def]) => {
227
+ const fields = Object.entries(def.fields ?? {})
228
+ .map(([fname, field]) => {
229
+ const key = isIdent(fname) ? fname : JSON.stringify(fname);
230
+ const opt = field.optional ? "?" : "";
231
+ return ` ${key}${opt}: ${fieldTsType(field, ids)};`;
232
+ })
233
+ .join("\n");
234
+ const body = fields.length > 0 ? `{\n${fields}\n }` : "{}";
235
+ return ` ${JSON.stringify(id)}: ${body};`;
236
+ })
237
+ .join("\n");
238
+ return `/** Declared (transient) domain types from the manifest \`types\` registry (ADR 0029 §4.2), keyed by id. */\nexport interface DomainTypes {\n${entries}\n}\n`;
239
+ }
240
+
241
+ /**
242
+ * Compose the full `domain-rows.d.ts`: the datasource table spine (every source, ADR 0029 §6)
243
+ * followed by the manifest `types` registry (§4.2).
244
+ */
245
+ export function emitDomainModel(
246
+ sources: SourceSchema[],
247
+ defaultSource: string | undefined,
248
+ types: DomainTypeRegistry,
249
+ ): string {
250
+ const spine = emitDomainDtsForSources(sources, defaultSource);
251
+ const registry = emitDomainTypeRegistry(types);
252
+ return registry ? `${spine}\n${registry}` : spine;
253
+ }
254
+
255
+ // --- manifest bridge (code-first, ADR 0054) --------------------------------------------------
256
+
257
+ /** Project one manifest type's canonical schema into a `TableMeta` for the row-type spine. Reuses
258
+ * the *same* `tableSchemaForType` the SQL migration uses, so the row types can't drift from the DB. */
259
+ function tableMetaFromType(typeName: string, def: ToolkitType): TableMeta {
260
+ const { table, columns } = tableSchemaForType(typeName, def);
261
+ return {
262
+ name: table,
263
+ columns: columns.map((c) => ({
264
+ name: c.name,
265
+ type: c.sqlType,
266
+ notNull: c.notNull,
267
+ primaryKey: c.primaryKey,
268
+ })),
269
+ indexes: [],
270
+ foreignKeys: [],
271
+ };
272
+ }
273
+
274
+ /** The datasource table spine derived from the manifest types, grouped by source (same grouping
275
+ * and order as the SQL migration). */
276
+ export function sourcesFromManifest(manifest: ToolkitManifest): SourceSchema[] {
277
+ return [...groupTypesBySource(manifest)].map(([source, list]) => ({
278
+ source,
279
+ tables: list.map(([name, def]) => tableMetaFromType(name, def)),
280
+ }));
281
+ }
282
+
283
+ /** The `DomainTypes` registry derived from the manifest types (declared fields only — the
284
+ * persisted `id` belongs to the table row, not the logical type). */
285
+ export function registryFromManifest(manifest: ToolkitManifest): DomainTypeRegistry {
286
+ const out: DomainTypeRegistry = {};
287
+ for (const [id, def] of Object.entries(manifest.types ?? {})) {
288
+ const fields: Record<string, DomainFieldDef> = {};
289
+ for (const [fname, f] of Object.entries(def.fields ?? {})) {
290
+ fields[fname] = { type: f.type ?? "string", optional: f.optional, list: f.list };
291
+ }
292
+ out[id] = { table: def.table, fields };
293
+ }
294
+ return out;
295
+ }
296
+
297
+ /** Emit the `domain-rows.d.ts` content for an app manifest. */
298
+ export function emitDomain(manifest: ToolkitManifest): string {
299
+ return emitDomainModel(
300
+ sourcesFromManifest(manifest),
301
+ manifest.data?.default ?? "app",
302
+ registryFromManifest(manifest),
303
+ );
304
+ }
305
+
306
+ /** Derive `nano-generated/domain-rows.d.ts` from the manifest types. Empty when the app declares
307
+ * no types (no tables, no registry, and nothing references `DomainTypes`). */
308
+ export function deriveDomain(manifest: ToolkitManifest): DerivedArtifact[] {
309
+ if (!manifest.types || Object.keys(manifest.types).length === 0) return [];
310
+ return [{ path: `${GENERATED_DIR}/${DOMAIN_DTS}`, content: emitDomain(manifest) }];
311
+ }
312
+
313
+ export const domainDeriver: Deriver<ToolkitManifest> = {
314
+ id: "types->domain",
315
+ describe: "Derive domain row types (DomainTables spine + DomainTypes registry) from manifest types.",
316
+ derive: deriveDomain,
317
+ };
@@ -0,0 +1,174 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import {
4
+ deriveMessageBindings,
5
+ emitMessageBindings,
6
+ scanModelMessages,
7
+ type MessageIo,
8
+ } from "./messages.ts";
9
+
10
+ // Goldens captured byte-for-byte from the console's canonical `emitMessageBindings`
11
+ // (server/src/console/domain_types.ts) so this port is provably a drop-in (ADR 0053).
12
+ const GOLD_EMPTY =
13
+ "// AUTO-GENERATED by nanobpmn from the process model (ADR 0040 slice 2).\n" +
14
+ "// The bridge from a `bpmn:message`'s data envelope to the message type system:\n" +
15
+ "// each named message maps to the TS type of its payload, so the typed\n" +
16
+ "// `publishMessage` types a call by its message name. Do not edit — regenerated\n" +
17
+ "// from the model. Erased to plain JS at compile.\n" +
18
+ "// eslint-disable\n" +
19
+ "\n" +
20
+ "\n" +
21
+ "/** Untyped fallback payload for a message that declares no envelope type. */\n" +
22
+ "export type MessageVars = Record<string, unknown>;\n" +
23
+ "\n" +
24
+ "/** Every declared message `name` (ADR 0040 slice 2): the model-derived set the\n" +
25
+ " * typed `publishMessage` accepts, so `name` autocompletes and rejects unknown messages. */\n" +
26
+ "export type MessageName = string;\n" +
27
+ "\n" +
28
+ "/** Payload (`variables`) per declared message, keyed by `name`. */\n" +
29
+ "export interface MessagePayloads {}\n";
30
+
31
+ const GOLD_NAMESONLY =
32
+ "// AUTO-GENERATED by nanobpmn from the process model (ADR 0040 slice 2).\n" +
33
+ "// The bridge from a `bpmn:message`'s data envelope to the message type system:\n" +
34
+ "// each named message maps to the TS type of its payload, so the typed\n" +
35
+ "// `publishMessage` types a call by its message name. Do not edit — regenerated\n" +
36
+ "// from the model. Erased to plain JS at compile.\n" +
37
+ "// eslint-disable\n" +
38
+ "\n" +
39
+ "\n" +
40
+ "/** Untyped fallback payload for a message that declares no envelope type. */\n" +
41
+ "export type MessageVars = Record<string, unknown>;\n" +
42
+ "\n" +
43
+ "/** Every declared message `name` (ADR 0040 slice 2): the model-derived set the\n" +
44
+ " * typed `publishMessage` accepts, so `name` autocompletes and rejects unknown messages. */\n" +
45
+ "export type MessageName = \"OrderPlaced\" | \"OrderShipped\";\n" +
46
+ "\n" +
47
+ "/** Payload (`variables`) per declared message, keyed by `name`. */\n" +
48
+ "export interface MessagePayloads {}\n";
49
+
50
+ const GOLD_TYPED =
51
+ "// AUTO-GENERATED by nanobpmn from the process model (ADR 0040 slice 2).\n" +
52
+ "// The bridge from a `bpmn:message`'s data envelope to the message type system:\n" +
53
+ "// each named message maps to the TS type of its payload, so the typed\n" +
54
+ "// `publishMessage` types a call by its message name. Do not edit — regenerated\n" +
55
+ "// from the model. Erased to plain JS at compile.\n" +
56
+ "// eslint-disable\n" +
57
+ "\n" +
58
+ "import type { DomainTypes } from \"./domain-rows.d.ts\";\n" +
59
+ "\n" +
60
+ "/** Untyped fallback payload for a message that declares no envelope type. */\n" +
61
+ "export type MessageVars = Record<string, unknown>;\n" +
62
+ "\n" +
63
+ "/** Every declared message `name` (ADR 0040 slice 2): the model-derived set the\n" +
64
+ " * typed `publishMessage` accepts, so `name` autocompletes and rejects unknown messages. */\n" +
65
+ "export type MessageName = \"OrderPlaced\";\n" +
66
+ "\n" +
67
+ "/** Payload (`variables`) per declared message, keyed by `name`. */\n" +
68
+ "export interface MessagePayloads {\n" +
69
+ " \"OrderPlaced\": DomainTypes[\"Order\"];\n" +
70
+ "}\n";
71
+
72
+ const GOLD_MIXED =
73
+ "// AUTO-GENERATED by nanobpmn from the process model (ADR 0040 slice 2).\n" +
74
+ "// The bridge from a `bpmn:message`'s data envelope to the message type system:\n" +
75
+ "// each named message maps to the TS type of its payload, so the typed\n" +
76
+ "// `publishMessage` types a call by its message name. Do not edit — regenerated\n" +
77
+ "// from the model. Erased to plain JS at compile.\n" +
78
+ "// eslint-disable\n" +
79
+ "\n" +
80
+ "import type { DomainTypes } from \"./domain-rows.d.ts\";\n" +
81
+ "\n" +
82
+ "/** Untyped fallback payload for a message that declares no envelope type. */\n" +
83
+ "export type MessageVars = Record<string, unknown>;\n" +
84
+ "\n" +
85
+ "/** Every declared message `name` (ADR 0040 slice 2): the model-derived set the\n" +
86
+ " * typed `publishMessage` accepts, so `name` autocompletes and rejects unknown messages. */\n" +
87
+ "export type MessageName = \"OrderPlaced\" | \"Ping\";\n" +
88
+ "\n" +
89
+ "/** Payload (`variables`) per declared message, keyed by `name`. */\n" +
90
+ "export interface MessagePayloads {\n" +
91
+ " \"OrderPlaced\": DomainTypes[\"Order\"];\n" +
92
+ "}\n";
93
+
94
+ test("emitMessageBindings: no messages → string union + empty payloads (matches console)", () => {
95
+ assert.equal(emitMessageBindings([], []), GOLD_EMPTY);
96
+ });
97
+
98
+ test("emitMessageBindings: names-only → finite union, no import (matches console)", () => {
99
+ const out = emitMessageBindings(
100
+ [{ messageName: "OrderPlaced" }, { messageName: "OrderShipped" }],
101
+ [],
102
+ );
103
+ assert.equal(out, GOLD_NAMESONLY);
104
+ });
105
+
106
+ test("emitMessageBindings: a declared envelope maps to DomainTypes (matches console)", () => {
107
+ const out = emitMessageBindings([{ messageName: "OrderPlaced", inputType: "Order" }], ["Order"]);
108
+ assert.equal(out, GOLD_TYPED);
109
+ });
110
+
111
+ test("emitMessageBindings: an undeclared envelope type is omitted from payloads (matches console)", () => {
112
+ const out = emitMessageBindings(
113
+ [
114
+ { messageName: "OrderPlaced", inputType: "Order" },
115
+ { messageName: "Ping", inputType: "NotDeclared" },
116
+ ],
117
+ ["Order", "Receipt"],
118
+ );
119
+ assert.equal(out, GOLD_MIXED);
120
+ });
121
+
122
+ const XML = `<?xml version="1.0"?>
123
+ <bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL"
124
+ xmlns:zeebe="http://camunda.org/schema/zeebe/1.0">
125
+ <bpmn:message id="M1" name="OrderPlaced">
126
+ <bpmn:extensionElements>
127
+ <zeebe:properties>
128
+ <zeebe:property name="io.nanobpm.dataEnvelope.in" value="Order" />
129
+ </zeebe:properties>
130
+ </bpmn:extensionElements>
131
+ </bpmn:message>
132
+ <bpmn:message id="M2" name="Ping" />
133
+ </bpmn:definitions>`;
134
+
135
+ test("scanModelMessages extracts message name + envelope; a self-closing message is name-only", () => {
136
+ const m = scanModelMessages(XML);
137
+ const placed = m.find((x) => x.messageName === "OrderPlaced") as MessageIo;
138
+ assert.ok(placed);
139
+ assert.equal(placed.inputType, "Order");
140
+ const ping = m.find((x) => x.messageName === "Ping") as MessageIo;
141
+ assert.ok(ping);
142
+ assert.equal(ping.inputType, undefined);
143
+ });
144
+
145
+ test("scanModelMessages drops a message with an empty/absent name", () => {
146
+ assert.deepEqual(scanModelMessages(`<bpmn:message name="" />`), []);
147
+ assert.deepEqual(scanModelMessages(`<bpmn:message id="x" />`), []);
148
+ });
149
+
150
+ test("deriveMessageBindings is deterministic and emits message-io.d.ts", () => {
151
+ const models = [{ path: "processes/orders.bpmn", xml: XML }];
152
+ const a1 = deriveMessageBindings(models, ["Order"]);
153
+ const a2 = deriveMessageBindings(models, ["Order"]);
154
+ assert.deepEqual(a1, a2);
155
+ assert.equal(a1[0].path, "nano-generated/message-io.d.ts");
156
+ assert.match(a1[0].content, /"OrderPlaced": DomainTypes\["Order"\]/);
157
+ });
158
+
159
+ test("deriveMessageBindings sorts by name and merges envelopes first-wins across models", () => {
160
+ // Same message declared in two models: the first (path order) carries the envelope,
161
+ // the later re-declaration (no envelope) must not clear it (mirrors the Rust fill).
162
+ const a = `<bpmn:message name="Zebra" />`;
163
+ const b1 = `<bpmn:message name="Alpha"><zeebe:property name="io.nanobpm.dataEnvelope.in" value="Order" /></bpmn:message>`;
164
+ const b2 = `<bpmn:message name="Alpha" />`;
165
+ const models = [
166
+ { path: "processes/2-second.bpmn", xml: b2 },
167
+ { path: "processes/1-first.bpmn", xml: b1 + a },
168
+ ];
169
+ const content = deriveMessageBindings(models, ["Order"])[0].content;
170
+ // Sorted by name: Alpha before Zebra.
171
+ assert.match(content, /export type MessageName = "Alpha" \| "Zebra";/);
172
+ // First-wins: Alpha keeps its Order envelope despite the later name-only re-declaration.
173
+ assert.match(content, /"Alpha": DomainTypes\["Order"\]/);
174
+ });
@@ -0,0 +1,166 @@
1
+ // Deriver: BPMN models → `message-io.d.ts`, the message-payload type map (ADR 0040 slice 2).
2
+ // Scans each process for `bpmn:message` envelopes and maps each message name to its declared
3
+ // payload type. It emits the SAME `message-io.d.ts` the console generates (a faithful port of
4
+ // `emitMessageBindings` in the server's domain_types.ts), so the toolkit is a drop-in for the
5
+ // IDE's codegen (ADR 0053). The static typed-`publishMessage` wrapper (`messages.ts`) never
6
+ // changes with the model, so — like the worker SDK — it is a package/runtime concern, not a
7
+ // derived artifact; only the model-derived `message-io.d.ts` is emitted here.
8
+
9
+ import type { DerivedArtifact, Deriver } from "../artifact.ts";
10
+ import { GENERATED_DIR } from "../artifact.ts";
11
+ import { byModelPath, DOMAIN_DTS, typeRefFor, type ModelSource } from "./worker-io.ts";
12
+
13
+ /** Filename the console uses for the derived message-payload map; kept identical (drop-in). */
14
+ export const MESSAGE_BINDINGS_DTS = "message-io.d.ts";
15
+
16
+ const ENVELOPE_IN = "io.nanobpm.dataEnvelope.in";
17
+ const ENVELOPE_OUT = "io.nanobpm.dataEnvelope.out";
18
+
19
+ /** One message-IO entry scanned from a model: a `bpmn:message` name plus the envelope
20
+ * type refs it carries. `inputType` is the received payload (what a `publishMessage`
21
+ * caller sends); `outputType` is reserved. Mirrors the Rust `MessageIo`. */
22
+ export interface MessageIo {
23
+ messageName: string;
24
+ inputType?: string;
25
+ outputType?: string;
26
+ }
27
+
28
+ /** The binding shape the emitter reads. Identical to a scanned `MessageIo`, so it is an
29
+ * alias — one canonical shape, no second declaration to drift (the console keeps the two
30
+ * apart only because its scan output is Rust and its emitter input is TS). */
31
+ export type MessageBindingDecl = MessageIo;
32
+
33
+ function attr(tag: string, name: string): string | undefined {
34
+ const m = tag.match(new RegExp(`\\b${name}\\s*=\\s*"([^"]*)"`));
35
+ return m ? m[1] : undefined;
36
+ }
37
+
38
+ /** An envelope ref is trimmed; an empty/whitespace value contributes nothing (mirrors the
39
+ * Rust `envelope_ref`). A message name, by contrast, is a correlation identity matched
40
+ * verbatim by the engine, so it is NOT trimmed — only an absent/empty name is dropped. */
41
+ function envelopeRef(value: string | undefined): string | undefined {
42
+ const v = value?.trim();
43
+ return v ? v : undefined;
44
+ }
45
+
46
+ /** Scan one BPMN document for `bpmn:message` envelopes. Handles both a self-closing
47
+ * `<bpmn:message name=.. />` (name only — completes the `MessageName` union) and an open
48
+ * message whose body carries the `io.nanobpm.dataEnvelope.in/out` `zeebe:property`. */
49
+ export function scanModelMessages(xml: string): MessageIo[] {
50
+ const out: MessageIo[] = [];
51
+ const blockRe = /<bpmn:message\b([^>]*?)(?:\/>|>([\s\S]*?)<\/bpmn:message>)/g;
52
+ let m: RegExpExecArray | null;
53
+ while ((m = blockRe.exec(xml)) !== null) {
54
+ const name = attr(`<x ${m[1]}>`, "name");
55
+ if (name == null || name.length === 0) continue;
56
+ const io: MessageIo = { messageName: name };
57
+ const body = m[2] ?? "";
58
+ const propRe = /<zeebe:property\b[^>]*>/g;
59
+ let p: RegExpExecArray | null;
60
+ while ((p = propRe.exec(body)) !== null) {
61
+ const pname = attr(p[0], "name");
62
+ if (pname === ENVELOPE_IN) io.inputType = envelopeRef(attr(p[0], "value"));
63
+ else if (pname === ENVELOPE_OUT) io.outputType = envelopeRef(attr(p[0], "value"));
64
+ }
65
+ out.push(io);
66
+ }
67
+ return out;
68
+ }
69
+
70
+ // --- Faithful port of the console's emitMessageBindings (domain_types.ts) so the emitted
71
+ // message-io.d.ts is byte-compatible with the IDE's own codegen. ---
72
+
73
+ /** Emit `message-io.d.ts` from message bindings + the set of declared domain type ids.
74
+ * Each named message joins the `MessageName` union; a message whose envelope names a
75
+ * declared type also maps to it in `MessagePayloads` (else falls back to `MessageVars`). */
76
+ export function emitMessageBindings(
77
+ messages: MessageBindingDecl[],
78
+ declaredTypeIds: Iterable<string>,
79
+ ): string {
80
+ const declared = new Set(declaredTypeIds);
81
+ const propKey = (m: string) => JSON.stringify(m);
82
+ const names = [
83
+ ...new Set(
84
+ messages
85
+ .map((m) => m?.messageName)
86
+ .filter((n): n is string => typeof n === "string" && n.length > 0),
87
+ ),
88
+ ];
89
+ const nameUnion = names.length > 0
90
+ ? names.map((n) => JSON.stringify(n)).join(" | ")
91
+ : "string";
92
+ const payloads: string[] = [];
93
+ for (const m of messages) {
94
+ if (typeof m?.messageName !== "string" || m.messageName.length === 0) continue;
95
+ const ref = typeRefFor(m.inputType, declared);
96
+ if (ref) payloads.push(` ${propKey(m.messageName)}: ${ref};`);
97
+ }
98
+
99
+ const header =
100
+ "// AUTO-GENERATED by nanobpmn from the process model (ADR 0040 slice 2).\n" +
101
+ "// The bridge from a `bpmn:message`'s data envelope to the message type system:\n" +
102
+ "// each named message maps to the TS type of its payload, so the typed\n" +
103
+ "// `publishMessage` types a call by its message name. Do not edit — regenerated\n" +
104
+ "// from the model. Erased to plain JS at compile.\n" +
105
+ "// eslint-disable\n";
106
+
107
+ const needsRegistry = payloads.length > 0;
108
+ const importTypes = needsRegistry
109
+ ? `import type { DomainTypes } from "./${DOMAIN_DTS}";\n`
110
+ : "";
111
+
112
+ const payloadsIface = payloads.length > 0
113
+ ? `export interface MessagePayloads {\n${payloads.join("\n")}\n}\n`
114
+ : `export interface MessagePayloads {}\n`;
115
+
116
+ return `${header}\n` +
117
+ importTypes +
118
+ `\n/** Untyped fallback payload for a message that declares no envelope type. */\n` +
119
+ `export type MessageVars = Record<string, unknown>;\n\n` +
120
+ `/** Every declared message \`name\` (ADR 0040 slice 2): the model-derived set the\n` +
121
+ ` * typed \`publishMessage\` accepts, so \`name\` autocompletes and rejects unknown messages. */\n` +
122
+ `export type MessageName = ${nameUnion};\n\n` +
123
+ `/** Payload (\`variables\`) per declared message, keyed by \`name\`. */\n` +
124
+ payloadsIface;
125
+ }
126
+
127
+ /**
128
+ * Derive `nano-generated/message-io.d.ts` from BPMN models. Messages are aggregated the way
129
+ * the console's Rust scan does (a `BTreeMap` keyed by name): deduped by name, sorted by name,
130
+ * with the envelope type refs merged first-wins across models — so the derived output matches
131
+ * the host's `derivedMessages` for the same models. `declaredTypeIds` is the manifest `types`
132
+ * key set; a message only gets a typed payload when its envelope names a declared type.
133
+ */
134
+ export function deriveMessageBindings(
135
+ models: ModelSource[],
136
+ declaredTypeIds: Iterable<string> = [],
137
+ ): DerivedArtifact[] {
138
+ const byName = new Map<string, MessageBindingDecl>();
139
+ for (const model of [...models].sort(byModelPath)) {
140
+ for (const msg of scanModelMessages(model.xml)) {
141
+ const existing = byName.get(msg.messageName);
142
+ if (!existing) {
143
+ byName.set(msg.messageName, {
144
+ messageName: msg.messageName,
145
+ inputType: msg.inputType,
146
+ outputType: msg.outputType,
147
+ });
148
+ } else {
149
+ // First-wins merge of the envelope refs (mirrors the Rust `fill`).
150
+ if (existing.inputType == null) existing.inputType = msg.inputType;
151
+ if (existing.outputType == null) existing.outputType = msg.outputType;
152
+ }
153
+ }
154
+ }
155
+ const messages = [...byName.values()].sort((a, b) =>
156
+ a.messageName < b.messageName ? -1 : a.messageName > b.messageName ? 1 : 0
157
+ );
158
+ const content = emitMessageBindings(messages, declaredTypeIds);
159
+ return [{ path: `${GENERATED_DIR}/${MESSAGE_BINDINGS_DTS}`, content }];
160
+ }
161
+
162
+ export const messagesDeriver: Deriver<{ models: ModelSource[]; declaredTypeIds: Iterable<string> }> = {
163
+ id: "model->message-io",
164
+ describe: "Derive message-io.d.ts (bpmn:message name + envelope payload) from BPMN models.",
165
+ derive: ({ models, declaredTypeIds }) => deriveMessageBindings(models, declaredTypeIds),
166
+ };