@pylonts/dsl 1.1.6 → 1.1.12

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 (88) hide show
  1. package/README.md +4 -0
  2. package/dist/action.d.ts +32 -0
  3. package/dist/action.js +14 -0
  4. package/dist/aggregate.d.ts +38 -0
  5. package/dist/aggregate.js +46 -0
  6. package/dist/business-flow.d.ts +9 -0
  7. package/dist/business-flow.js +72 -0
  8. package/dist/controller.d.ts +17 -9
  9. package/dist/controller.js +8 -2
  10. package/dist/convert.d.ts +28 -10
  11. package/dist/convert.js +16 -5
  12. package/dist/curd.d.ts +7 -10
  13. package/dist/curd.js +3 -1
  14. package/dist/dao.d.ts +81 -53
  15. package/dist/dao.js +291 -12
  16. package/dist/db.d.ts +6 -0
  17. package/dist/db.js +10 -0
  18. package/dist/domain-event.d.ts +48 -0
  19. package/dist/domain-event.js +24 -0
  20. package/dist/dsl.d.ts +17 -2
  21. package/dist/dsl.js +7 -0
  22. package/dist/dto.d.ts +6 -4
  23. package/dist/dto.js +5 -4
  24. package/dist/entity.d.ts +29 -0
  25. package/dist/entity.js +13 -0
  26. package/dist/exception.d.ts +9 -3
  27. package/dist/exception.js +25 -1
  28. package/dist/expr.d.ts +45 -0
  29. package/dist/expr.js +32 -0
  30. package/dist/filter.d.ts +45 -0
  31. package/dist/filter.js +21 -0
  32. package/dist/flow-script.d.ts +108 -0
  33. package/dist/flow-script.js +505 -0
  34. package/dist/flow.d.ts +294 -17
  35. package/dist/flow.js +803 -18
  36. package/dist/index.d.ts +6 -2
  37. package/dist/index.js +6 -2
  38. package/dist/mermaid-driver.js +264 -24
  39. package/dist/mysql-driver.js +3 -0
  40. package/dist/project.d.ts +10 -6
  41. package/dist/project.js +35 -4
  42. package/dist/repository.d.ts +26 -0
  43. package/dist/repository.js +8 -0
  44. package/dist/service.d.ts +14 -2
  45. package/dist/service.js +49 -0
  46. package/dist/third-service.d.ts +5 -0
  47. package/dist/third-service.js +1 -0
  48. package/dist/typebox-driver.js +4 -0
  49. package/dist/utils.d.ts +9 -2
  50. package/dist/utils.js +4 -0
  51. package/docs/aggregate.md +110 -0
  52. package/docs/curd.md +146 -111
  53. package/docs/dao-generation.md +478 -0
  54. package/docs/ddd-principles.md +75 -0
  55. package/docs/domain-event.md +137 -0
  56. package/docs/keyword-matcher.md +182 -0
  57. package/docs/project.md +17 -9
  58. package/docs/token.md +327 -0
  59. package/docs/trans-reentrant.md +85 -0
  60. package/package.json +25 -6
  61. package/src/action.ts +51 -10
  62. package/src/aggregate.ts +104 -0
  63. package/src/business-flow.ts +80 -0
  64. package/src/controller.ts +25 -11
  65. package/src/convert.ts +51 -15
  66. package/src/curd.ts +12 -6
  67. package/src/dao.ts +377 -63
  68. package/src/db.ts +13 -0
  69. package/src/domain-event.ts +74 -0
  70. package/src/dsl.ts +23 -2
  71. package/src/dto.ts +9 -6
  72. package/src/entity.ts +43 -0
  73. package/src/exception.ts +30 -5
  74. package/src/expr.ts +65 -0
  75. package/src/filter.ts +70 -0
  76. package/src/flow-script.ts +696 -0
  77. package/src/flow.ts +1129 -46
  78. package/src/index.ts +6 -2
  79. package/src/mermaid-driver.ts +256 -29
  80. package/src/mysql-driver.ts +3 -0
  81. package/src/project.ts +138 -97
  82. package/src/repository.ts +35 -0
  83. package/src/service.ts +68 -3
  84. package/src/third-service.ts +6 -0
  85. package/src/typebox-driver.ts +4 -0
  86. package/src/utils.ts +13 -2
  87. package/src/endpoint.ts +0 -18
  88. package/src/provider.ts +0 -68
package/src/flow.ts CHANGED
@@ -1,70 +1,539 @@
1
- import { SchemaBase } from './dsl.js';
1
+ import type { EnumDef, EnumValue, SchemaBase } from './dsl.js';
2
+ import type { DtoMessage } from './dto.js';
3
+ import type { DomainEventSchema } from './domain-event.js';
4
+ import { UnexpectedException } from './exception.js';
5
+ import type { ExceptionSchema } from './exception.js';
2
6
  import type { MethodSchema } from './method.js';
3
- import type { ConvertSchema } from './convert.js';
7
+ import type { ConvertMethodSchema } from './convert.js';
4
8
  import type { DaoMethodSchema } from './dao.js';
5
9
  import type { ServiceMethodSchema } from './service.js';
6
10
  import type { ThirdServiceMethodSchema } from './third-service.js';
7
11
  import type { UtilsMethodSchema } from './utils.js';
8
12
 
9
- // Flow model: nodes and edges are separate entities. A FlowNode is a plain
10
- // named step; a FlowEdge references its start/end node objects directly (no
11
- // ids). Because a node object may appear in many edges, the graph can share
12
- // nodes, merge branches, and form cycles (e.g. poll-and-retry loops).
13
+ // Flow model: nodes are executors, control flow lives on edges. A FlowNode is
14
+ // an ordered sequence of method invocations (a basic block); when a method in
15
+ // the sequence throws, the rest does not run. A GuardNode is a gate executor:
16
+ // its checks are ordered decisions, the first check that holds routes out
17
+ // (return or throw). A TryNode is a protected region: its body, every catch
18
+ // handler, and the optional finally are all sub-flows — the body's exception
19
+ // ends are matched against the catches by name, a handler's exception ends
20
+ // rethrow out of the region, and all fall-through paths continue via the
21
+ // TryNode's outgoing edges.
22
+ //
23
+ // Every flow has a built-in return exit (flow.returnEnd) plus any number of
24
+ // exception exits: explicit defineExceptionEnd nodes (targets of typed throws
25
+ // edges) or ends synthesized from guard checks. A guard exits implicitly — a
26
+ // check returning routes to the return end, a check throwing routes to the
27
+ // flow's exception end carrying the same name; no edges needed. A step's
28
+ // declared exceptions (methods' contracts and TryNode rethrows) must be
29
+ // routed by a typed throws edge or an untyped exception edge (catch-all).
30
+ //
31
+ // Data flows through slots (a compiler-like register file): the built-in args
32
+ // slot carries the flow input and needs no registration, named slots carry
33
+ // derived objects and are declared via defineSlots, and calls bind slots to
34
+ // method args/results (converting implicitly when contracts differ).
13
35
 
14
- /** A method a flow node can invoke: contract references, or a pure descriptor
36
+ /** A method a flow step can invoke: contract references, or a pure descriptor
15
37
  * (MethodSchema) for the period before the contract file exists. */
16
38
  export type FlowMethodRef =
17
39
  | MethodSchema
18
- | ConvertSchema
40
+ | ConvertMethodSchema
19
41
  | DaoMethodSchema
20
42
  | ServiceMethodSchema
21
43
  | ThirdServiceMethodSchema
22
44
  | UtilsMethodSchema;
23
45
 
46
+ /** One named data slot of a flow — a register holding a whole object (like a
47
+ * compiler's register file). The built-in args slot carries the flow input
48
+ * (flow.args) and needs no registration: parameters exist in every flow.
49
+ * Named slots carry derived objects and are declared by binding a method's
50
+ * args/results message. The declared type is documentation — passing a slot
51
+ * to a method with a different contract converts implicitly. Slots are scoped
52
+ * to their flow: they cross into a sub-flow only through the shared input
53
+ * (flow.args) and out of it only through the wrapping node's reads/writes
54
+ * declarations. */
55
+ export interface FlowSlot {
56
+ name: string;
57
+ /** The contract message this slot was declared with (documentation only —
58
+ * call sites convert implicitly). */
59
+ type?: unknown;
60
+ description?: string;
61
+ /** Field access (e.g. slots.args.amt): resolved at access time against the
62
+ * slot's declared message fields, returning a SlotFieldRef for the
63
+ * comparison builders. Unknown fields throw with the declared field list. */
64
+ [field: string]: unknown;
65
+ }
66
+
67
+ /** A field access on a slot (slots.args.amt): the slot plus the resolved
68
+ * field object from the slot's declared message. */
69
+ export interface SlotFieldRef {
70
+ slot: FlowSlot;
71
+ /** The resolved field (DtoField | Field) — carries its schema for codegen. */
72
+ field: unknown;
73
+ }
74
+
75
+ /** A flow's slot registers: the built-in args slot plus named slots. */
76
+ export type FlowSlots = { args: FlowSlot } & Record<string, FlowSlot>;
77
+
78
+ /** Declare a flow's named slots — each bound to the message of a method's
79
+ * args/results (the slot's type). The built-in args slot (the flow input)
80
+ * is added automatically: parameters need no registration. To make its
81
+ * fields accessible (slots.args.amt), declare its input message via the
82
+ * `args` key — that declares the slot's type, not a new slot. */
83
+ export function defineSlots<T extends Record<string, unknown>>(
84
+ slots: T,
85
+ ): { [K in keyof T]: FlowSlot & { name: K } } & { args: FlowSlot } {
86
+ const wrap = (slot: FlowSlot): FlowSlot => {
87
+ const proxy = new Proxy(slot, {
88
+ get(target, prop, receiver) {
89
+ if (typeof prop === 'symbol') return Reflect.get(target, prop, receiver);
90
+ // Slot metadata wins over same-named message fields; reflection keys
91
+ // (then/toJSON and Object.prototype members) keep plain object
92
+ // behavior so serialization, promises, and console output never throw.
93
+ if (
94
+ prop === 'type' ||
95
+ prop === 'description' ||
96
+ prop === 'then' ||
97
+ prop === 'toJSON' ||
98
+ prop in target
99
+ ) {
100
+ return Reflect.get(target, prop, receiver);
101
+ }
102
+ const fields = (target.type as { fields?: Record<string, unknown> } | undefined)?.fields;
103
+ if (fields !== undefined && Object.prototype.hasOwnProperty.call(fields, prop)) {
104
+ return { slot: proxy, field: fields[prop] };
105
+ }
106
+ throw new Error(
107
+ `slot "${target.name}" has no field "${prop}" — its type declares: ${
108
+ fields ? Object.keys(fields).join(', ') : 'no fields'
109
+ }`,
110
+ );
111
+ },
112
+ });
113
+ return proxy;
114
+ };
115
+ const registry: Record<string, FlowSlot> = Object.create(null);
116
+ for (const key of Object.keys(slots)) {
117
+ if (key === 'args') {
118
+ registry.args = wrap({ name: 'args', type: slots.args, description: 'flow input (flow.args)' });
119
+ warnShadowedFields(registry.args);
120
+ continue;
121
+ }
122
+ registry[key] = wrap({ name: key, type: slots[key] });
123
+ warnShadowedFields(registry[key]);
124
+ }
125
+ if (registry.args === undefined) {
126
+ registry.args = wrap({ name: 'args', description: 'flow input (flow.args)' });
127
+ }
128
+ return registry as { [K in keyof T]: FlowSlot & { name: K } } & { args: FlowSlot };
129
+ }
130
+
131
+ // A message field named type/name/description is shadowed by slot metadata and
132
+ // unreachable via dot access (slots.args.type reads the message, not the
133
+ // field) — warn instead of failing: the field may never be needed.
134
+ function warnShadowedFields(slot: FlowSlot): void {
135
+ const fields = (slot.type as { fields?: Record<string, unknown> } | undefined)?.fields;
136
+ if (fields === undefined) return;
137
+ const shadowed = ['type', 'name', 'description'].filter((k) => k in fields);
138
+ if (shadowed.length > 0) {
139
+ console.warn(
140
+ `slot "${slot.name}": message fields ${shadowed.join(', ')} are shadowed by slot metadata and unreachable via field access`,
141
+ );
142
+ }
143
+ }
144
+
145
+ /** A method call with slot bindings: the arg slots are passed to the method
146
+ * (converted implicitly when the contract differs), the result is assigned
147
+ * to the result slot. A plain method ref (or an invoke with no bindings) is
148
+ * a call with args = [slots.args] and no result — the common case. */
149
+ export interface FlowCall {
150
+ method: FlowMethodRef;
151
+ /** Slots passed as the method's args — the input slot or derived slots.
152
+ * A single-message contract takes the one slot; multiple slots are for
153
+ * multi-param signatures (not modeled yet). */
154
+ args?: FlowSlot[];
155
+ /** Slot assigned from the method's results. */
156
+ result?: FlowSlot;
157
+ }
158
+
159
+ export function invoke(
160
+ method: FlowMethodRef,
161
+ options: { args?: FlowSlot[]; result?: FlowSlot } = {},
162
+ ): FlowCall {
163
+ return { method, args: options.args, result: options.result };
164
+ }
165
+
166
+ /** A node method: a plain contract reference or a call with slot bindings. */
167
+ export type FlowNodeMethodRef = FlowMethodRef | FlowCall;
168
+
169
+ export function isCall(m: FlowNodeMethodRef | GuardCondition): m is FlowCall {
170
+ return 'method' in m;
171
+ }
172
+
173
+ /** The underlying method of a (possibly bound) reference. */
174
+ export function methodOf(m: FlowNodeMethodRef): FlowMethodRef {
175
+ return isCall(m) ? m.method : m;
176
+ }
177
+
178
+ /** Comparison operators of a structured condition: ordering, (in)equality
179
+ * against a literal or enum value, and null checks. */
180
+ export type CompareOp = 'lt' | 'le' | 'gt' | 'ge' | 'eq' | 'ne' | 'isNull' | 'isNotNull';
181
+
182
+ /** A field comparison: a slot field (slots.args.amt) against a literal or an
183
+ * enum value — the machine-readable form of a when text. isNull/isNotNull
184
+ * take no value; the others require one. */
185
+ export interface Comparison {
186
+ kind: 'comparison';
187
+ op: CompareOp;
188
+ field: SlotFieldRef;
189
+ /** Compared-against value; null checks take none. */
190
+ value?: string | number | EnumValue;
191
+ }
192
+
193
+ /** The machine-readable condition behind a guard check or a branch edge
194
+ * (optional): a utils predicate call (its boolean result decides) or a field
195
+ * comparison. */
196
+ export type GuardCondition = FlowCall | Comparison;
197
+
198
+ function comparison(op: CompareOp, field: unknown, value?: string | number | EnumValue): Comparison {
199
+ const ref = field as Partial<SlotFieldRef> | null;
200
+ if (typeof ref !== 'object' || ref === null || typeof ref.slot !== 'object' || typeof ref.field !== 'object') {
201
+ throw new Error(`${op}: field must be a slot field access like slots.args.amt`);
202
+ }
203
+ const nullOp = op === 'isNull' || op === 'isNotNull';
204
+ if (nullOp !== (value === undefined)) {
205
+ throw new Error(`${op}: ${nullOp ? 'takes no' : 'requires a'} value`);
206
+ }
207
+ return { kind: 'comparison', op, field: { slot: ref.slot, field: ref.field }, value };
208
+ }
209
+
210
+ export function lt(field: unknown, value: string | number): Comparison {
211
+ return comparison('lt', field, value);
212
+ }
213
+ export function le(field: unknown, value: string | number): Comparison {
214
+ return comparison('le', field, value);
215
+ }
216
+ export function gt(field: unknown, value: string | number): Comparison {
217
+ return comparison('gt', field, value);
218
+ }
219
+ export function ge(field: unknown, value: string | number): Comparison {
220
+ return comparison('ge', field, value);
221
+ }
222
+ export function eq(field: unknown, value: string | number | EnumValue): Comparison {
223
+ return comparison('eq', field, value);
224
+ }
225
+ export function ne(field: unknown, value: string | number | EnumValue): Comparison {
226
+ return comparison('ne', field, value);
227
+ }
228
+ export function isNull(field: unknown): Comparison {
229
+ return comparison('isNull', field);
230
+ }
231
+ export function isNotNull(field: unknown): Comparison {
232
+ return comparison('isNotNull', field);
233
+ }
234
+
235
+ /** An enum value referenced by symbol — the compared-against target of eq/ne
236
+ * (e.g. eq(slots.args.state, enumValue(PayState, 'success'))). */
237
+ export function enumValue(def: EnumDef, symbol: string): EnumValue {
238
+ const v = def.values.find((v) => v.symbol === symbol);
239
+ if (v === undefined) {
240
+ throw new Error(`enum ${def.jsName} has no value "${symbol}"`);
241
+ }
242
+ return v;
243
+ }
244
+
245
+ /** Event publication: a flow node may publish one domain event. The outbox
246
+ * write joins the node's surrounding transaction — the event is durable with
247
+ * the node's other side effects. The payload slot defaults to the flow input
248
+ * (slots.args) when omitted. */
249
+ export interface FlowPublish {
250
+ event: DomainEventSchema;
251
+ /** The slot carrying the event payload. */
252
+ payload?: FlowSlot;
253
+ }
254
+
24
255
  export interface FlowNode extends SchemaBase {
25
256
  /** Optional sub-flow. When present, entering this node runs the sub-flow;
26
257
  * after the sub-flow reaches any terminal node, the outer flow continues
27
- * via this node's outgoing edges. Sub-flows nest recursively. */
258
+ * via this node's outgoing edges. Sub-flows nest recursively. A plain
259
+ * sub-flow may not declare exception ends — it is structure only; use a
260
+ * tryNode for a protected region. */
28
261
  flow?: FlowSchema;
29
- /** Methods this node invokes contract references or pure descriptors
30
- * (rendered under the node label). */
31
- methods?: FlowMethodRef[];
262
+ /** Ordered execution sequence (basic block): methods run in order; if one
263
+ * throws, the remaining methods are skipped. A plain reference is a call
264
+ * receiving the input slot (slots.args) — the common case. */
265
+ methods?: FlowNodeMethodRef[];
266
+ /** A domain event published by this node (same transaction as its methods). */
267
+ publish?: FlowPublish;
268
+ /** Slots this node reads to decide its outgoing branches — a semantic
269
+ * declaration, not enforced per branch. */
270
+ reads?: FlowSlot[];
271
+ /** Slots this node assigns without a method call (constructions). */
272
+ writes?: FlowSlot[];
273
+ }
274
+
275
+ // Plain FlowNodes carry no `type` field — the discriminant against
276
+ // GuardNode/TryNode/FlowEnd is its absence (see the is* predicates).
277
+
278
+ /** One gate check: when the condition holds, either return (early return to
279
+ * the flow's returnEnd) or throw the given exception (routed implicitly to
280
+ * the flow's exception end carrying the same name). Exactly one of
281
+ * return/exception must be set. */
282
+ export interface GuardCheck {
283
+ /** Condition description shown on the branch edge. */
284
+ when: string;
285
+ /** The check returns early (to the flow's returnEnd) — no edge needed. */
286
+ return?: boolean;
287
+ /** The check throws this exception — routed implicitly to the flow's
288
+ * exception end carrying the same name (no edge needed). */
289
+ exception?: ExceptionSchema;
290
+ /** Slots the check reads to decide. */
291
+ reads?: FlowSlot[];
292
+ /** Machine-readable condition behind `when` (optional): a utils predicate
293
+ * call or a field comparison. Omitted when the condition stays descriptive. */
294
+ check?: GuardCondition;
295
+ }
296
+
297
+ /** Gate executor: an ordered set of checks. The first check whose condition
298
+ * holds routes out implicitly (return to the flow's return end, throw to the
299
+ * matching exception end); when none holds, the guard falls through its
300
+ * normal outgoing edges (linked with edge like any node). A guard is the
301
+ * graph form of a run of `if (bad) throw / return` guards. */
302
+ export interface GuardNode extends SchemaBase {
303
+ type: 'guard';
304
+ /** Ordered decision sequence: methods run in order; if one throws, the
305
+ * remaining methods are skipped. */
306
+ methods?: FlowNodeMethodRef[];
307
+ /** Ordered checks — first hit wins. */
308
+ checks: GuardCheck[];
309
+ }
310
+
311
+ /** One catch route of a TryNode: body exception type → handler sub-flow.
312
+ * First match wins, UnexpectedException is the catch-all and must come
313
+ * last. The handler's exception ends rethrow out of the TryNode. */
314
+ export interface TryCatch {
315
+ /** Exception this catch handles — must match a body exception end. */
316
+ exception: ExceptionSchema;
317
+ /** Handler sub-flow: its return end falls through, its exception ends
318
+ * rethrow (declared as the TryNode's own throws). */
319
+ handler: FlowSchema;
320
+ description?: string;
321
+ }
322
+
323
+ /** Protected region: body, catch handlers, and optional finally are all
324
+ * sub-flows. Entering the TryNode runs the body; the body's exception ends
325
+ * are matched against the catches, every catch handler and the body's normal
326
+ * completion pass through finally (when present), then continue via the
327
+ * TryNode's outgoing edges. Handler exception ends rethrow out of the region. */
328
+ export interface TryNode extends SchemaBase {
329
+ type: 'try';
330
+ /** The protected region. Its exception ends are the region's throw sites. */
331
+ body: FlowSchema;
332
+ /** Ordered catch routes; UnexpectedException (catch-all) must be last. */
333
+ catches: TryCatch[];
334
+ /** Cleanup sub-flow: may not declare exception ends (Java finally rules). */
335
+ finally?: FlowSchema;
336
+ }
337
+
338
+ /** One branch of an ifNode: when the check holds, control moves to `to`. */
339
+ export interface IfCase {
340
+ /** Branch label (rendered on the branch line). */
341
+ when: string;
342
+ /** Machine-readable condition — required (the ifNode's whole purpose). */
343
+ check: GuardCondition;
344
+ /** Jump target: a step (node/guard/tryNode/ifNode). Flow exits — return
345
+ * and throw — belong to guard checks, so ends are rejected. */
346
+ to: FlowNodeOrEnd;
347
+ }
348
+
349
+ /** Decision node — the jump twin of a guard: ordered cases evaluated
350
+ * first-hit, the first check that holds routes to its target; when none
351
+ * holds, control goes to `else`. All exits are internal (cases and else),
352
+ * so the node has no outgoing edges. A guard decides exits (return/throw),
353
+ * an ifNode decides where control goes next (steps only). */
354
+ export interface IfNode extends SchemaBase {
355
+ type: 'if';
356
+ /** Ordered branches — first hit wins. */
357
+ cases: IfCase[];
358
+ /** Default branch: a step (never a flow exit). */
359
+ else: FlowNodeOrEnd;
360
+ }
361
+
362
+ /** Decision node: ordered cases (check → target) plus a default branch. */
363
+ export function ifNode(
364
+ name: string,
365
+ options: {
366
+ cases: IfCase[];
367
+ else: FlowNodeOrEnd;
368
+ description?: string;
369
+ },
370
+ ): IfNode {
371
+ return {
372
+ type: 'if',
373
+ name,
374
+ description: options.description,
375
+ cases: options.cases,
376
+ else: options.else,
377
+ };
378
+ }
379
+
380
+ /** Any node an edge can start from. */
381
+ export type FlowStep = FlowNode | GuardNode | TryNode | IfNode;
382
+
383
+ /** Any node an edge can point at: a step or a flow exit. */
384
+ export type FlowNodeOrEnd = FlowStep | FlowEnd;
385
+
386
+ /** A flow exit: normal return or uncaught exception. Never an edge start. */
387
+ export interface FlowEnd extends SchemaBase {
388
+ type: 'return' | 'exception';
389
+ /** Uncaught exception this exit throws — set when type='exception'. */
390
+ exception?: ExceptionSchema;
391
+ }
392
+
393
+ /** The flow's exception end carrying the given exception name — the implicit
394
+ * target of a guard check throwing it. Undefined when the flow has no such
395
+ * end (guard checks synthesize one at definition time, so this only happens
396
+ * for hand-assembled flows). */
397
+ export function findExceptionEnd(schema: FlowSchema, exceptionName: string): FlowEnd | undefined {
398
+ return schema.nodes.find(
399
+ (n): n is FlowEnd => isEnd(n) && n.type === 'exception' && n.exception?.name === exceptionName,
400
+ );
401
+ }
402
+
403
+ /** Where a throw of `exceptionName` from step `n` lands: the target of a typed
404
+ * throws edge (first match), or an untyped exception edge as catch-all.
405
+ * Undefined when no route exists (validation error). Guards route implicitly
406
+ * — see findExceptionEnd.
407
+ * @deprecated no internal use remains; kept for API compatibility. */
408
+ export function resolveThrowTarget(schema: FlowSchema, n: FlowStep, exceptionName: string): FlowNodeOrEnd | undefined {
409
+ for (const e of schema.edges) {
410
+ if (e.start !== n) continue;
411
+ if (e.throws && e.throws.name === exceptionName) return e.end;
412
+ }
413
+ for (const e of schema.edges) {
414
+ if (e.start === n && e.exception === true && e.throws === undefined) return e.end;
415
+ }
416
+ return undefined;
32
417
  }
33
418
 
34
419
  export interface FlowEdge extends SchemaBase {
35
420
  /** Trigger condition; undefined = default path (success/normal). */
36
421
  when?: string;
37
- start: FlowNode;
38
- end: FlowNode;
39
- /** Exception path (rendered dashed); defaults to normal. */
422
+ start: FlowStep;
423
+ end: FlowNodeOrEnd;
424
+ /** Exception path (rendered dashed); without `throws` it is a catch-all. */
40
425
  exception?: boolean;
426
+ /** Typed exception propagation: this edge carries the named exception
427
+ * (rendered dashed with a `throw X` label). Must target an exception end.
428
+ * Carrying one of a guard's own check exceptions is rejected — guards
429
+ * route those implicitly. */
430
+ throws?: ExceptionSchema;
431
+ /** Machine-readable condition behind `when` (optional): a utils predicate
432
+ * call or a field comparison. */
433
+ check?: GuardCondition;
41
434
  }
42
435
 
43
436
  export interface FlowSchema extends SchemaBase {
44
437
  /** Entry node. */
45
- start: FlowNode;
438
+ start: FlowStep;
439
+ /** Default exit — every flow has one; edge(node, flow.returnEnd) is a return. */
440
+ returnEnd: FlowEnd;
46
441
  /** All nodes, collected from edges (deduplicated by object identity). */
47
- nodes: FlowNode[];
442
+ nodes: FlowNodeOrEnd[];
48
443
  /** Independent edges; a node may be start of many edges, so cycles are expressible. */
49
444
  edges: FlowEdge[];
445
+ /** Input contract — mirrors a service method's args. */
446
+ args?: DtoMessage;
447
+ /** Output contract — mirrors a service method's results. */
448
+ results?: DtoMessage;
449
+ /** Declared slot registers of this flow (named slots + the built-in args
450
+ * slot). Sub-flows analyze their own slots; sharing happens through the
451
+ * same input object (args) or the wrapping node's reads/writes. */
452
+ slots?: FlowSlots;
453
+ /** Slots the enclosing flow has already produced before this sub-flow's
454
+ * entry (input inheritance). Only meaningful for sub-flows (try bodies,
455
+ * catch handlers, named sub-flows) — a top-level flow has none. */
456
+ entrySlots?: FlowSlot[];
50
457
  }
51
458
 
459
+ /** Executor node: an ordered sequence of method invocations (and optionally
460
+ * one event publication). */
52
461
  export function node(
53
462
  name: string,
54
- options: { flow?: FlowSchema; description?: string; methods?: FlowMethodRef[] } = {},
463
+ options: {
464
+ flow?: FlowSchema;
465
+ description?: string;
466
+ methods?: FlowNodeMethodRef[];
467
+ publish?: FlowPublish;
468
+ reads?: FlowSlot[];
469
+ writes?: FlowSlot[];
470
+ } = {},
55
471
  ): FlowNode {
56
472
  return {
57
473
  name,
58
474
  flow: options.flow,
59
475
  description: options.description,
60
476
  methods: options.methods,
477
+ publish: options.publish,
478
+ reads: options.reads,
479
+ writes: options.writes,
480
+ };
481
+ }
482
+
483
+ /** Guard node: a gate executor — ordered checks, first hit routes out;
484
+ * all misses fall through the guard's normal outgoing edges. */
485
+ export function guard(
486
+ name: string,
487
+ options: {
488
+ checks: GuardCheck[];
489
+ methods?: FlowNodeMethodRef[];
490
+ description?: string;
491
+ },
492
+ ): GuardNode {
493
+ return {
494
+ type: 'guard',
495
+ name,
496
+ description: options.description,
497
+ methods: options.methods,
498
+ checks: options.checks,
61
499
  };
62
500
  }
63
501
 
502
+ /** Try node: a protected region whose body, catch handlers, and optional
503
+ * finally are sub-flows. */
504
+ export function tryNode(
505
+ name: string,
506
+ options: {
507
+ body: FlowSchema;
508
+ catches: TryCatch[];
509
+ finally?: FlowSchema;
510
+ description?: string;
511
+ },
512
+ ): TryNode {
513
+ return {
514
+ type: 'try',
515
+ name,
516
+ description: options.description,
517
+ body: options.body,
518
+ catches: options.catches,
519
+ finally: options.finally,
520
+ };
521
+ }
522
+
523
+ export function defineExceptionEnd(exception: ExceptionSchema, description?: string): FlowEnd {
524
+ return { type: 'exception', name: `throw ${exception.name}`, exception, description };
525
+ }
526
+
64
527
  export function edge(
65
- start: FlowNode,
66
- end: FlowNode,
67
- options: { when?: string; description?: string; exception?: boolean } = {},
528
+ start: FlowStep,
529
+ end: FlowNodeOrEnd,
530
+ options: {
531
+ when?: string;
532
+ description?: string;
533
+ exception?: boolean;
534
+ throws?: ExceptionSchema;
535
+ check?: GuardCondition;
536
+ } = {},
68
537
  ): FlowEdge {
69
538
  // Auto name for uniformity with SchemaBase; `when` stays the branch marker.
70
539
  return {
@@ -74,54 +543,143 @@ export function edge(
74
543
  when: options.when,
75
544
  description: options.description,
76
545
  exception: options.exception,
546
+ throws: options.throws,
547
+ check: options.check,
77
548
  };
78
549
  }
79
550
 
80
551
  export function defineFlow(
81
552
  name: string,
82
553
  schema: {
83
- start: FlowNode;
84
- edges: FlowEdge[];
554
+ start: FlowStep;
555
+ edges: (flow: FlowSchema) => FlowEdge[];
556
+ args?: DtoMessage;
557
+ results?: DtoMessage;
558
+ slots?: FlowSlots;
559
+ entrySlots?: FlowSlot[];
85
560
  description?: string;
86
561
  },
87
562
  ): FlowSchema {
88
- const seen = new Set<FlowNode>();
89
- const nodes: FlowNode[] = [];
90
- for (const e of schema.edges) {
91
- for (const n of [e.start, e.end]) {
92
- if (!seen.has(n)) {
93
- seen.add(n);
94
- nodes.push(n);
563
+ const flow: FlowSchema = {
564
+ name,
565
+ description: schema.description,
566
+ start: schema.start,
567
+ returnEnd: { type: 'return', name: 'return' },
568
+ nodes: [],
569
+ edges: [],
570
+ args: schema.args,
571
+ results: schema.results,
572
+ slots: schema.slots,
573
+ entrySlots: schema.entrySlots,
574
+ };
575
+ // The input slot's type is the flow's args message: stamp it on first use,
576
+ // and refuse a registry already bound to a different input contract (slot
577
+ // registries belong to one call tree). Same-name messages are the same
578
+ // contract regardless of instance identity.
579
+ if (schema.args !== undefined && schema.slots !== undefined) {
580
+ const t = schema.slots.args.type;
581
+ if (t === undefined) {
582
+ schema.slots.args.type = schema.args;
583
+ warnShadowedFields(schema.slots.args);
584
+ } else if (messageName(t) !== schema.args.name) {
585
+ throw new Error(
586
+ `flow ${name}: the slots args slot carries ${messageName(t)} but the flow declares ${schema.args.name}`,
587
+ );
588
+ }
589
+ }
590
+ const edges = schema.edges(flow);
591
+ flow.edges = edges; // before node collection: guard check targets resolve through it
592
+ const seen = new Set<FlowNodeOrEnd>();
593
+ const nodes: FlowNodeOrEnd[] = [];
594
+ const addNode = (n: FlowNodeOrEnd): void => {
595
+ if (seen.has(n)) return;
596
+ seen.add(n);
597
+ nodes.push(n);
598
+ };
599
+ const addGuardTargets = (n: FlowStep): void => {
600
+ if (!isGuard(n)) return;
601
+ for (const c of n.checks) {
602
+ const ex = c.exception;
603
+ if (c.return) {
604
+ addNode(flow.returnEnd);
605
+ } else if (ex) {
606
+ // Guard checks exit implicitly: reuse the flow's exception end of the
607
+ // same name (declared by an edge or another guard), else synthesize it.
608
+ let t = nodes.find(
609
+ (x): x is FlowEnd => isEnd(x) && x.type === 'exception' && x.exception?.name === ex.name,
610
+ );
611
+ if (!t) {
612
+ t = {
613
+ type: 'exception',
614
+ name: `throw ${ex.name}`,
615
+ exception: ex,
616
+ description: 'guard implicit exit',
617
+ };
618
+ }
619
+ addNode(t);
95
620
  }
96
621
  }
622
+ };
623
+ for (const e of edges) {
624
+ addNode(e.start);
625
+ addNode(e.end);
97
626
  }
98
- if (!seen.has(schema.start)) {
99
- seen.add(schema.start);
100
- nodes.push(schema.start);
627
+ addNode(schema.start);
628
+ // Guard targets resolve after every edge endpoint is collected, so an
629
+ // exception end referenced by any edge is reused before synthesis. ifNode
630
+ // targets (cases and else) are collected the same way — an ifNode has no
631
+ // outgoing edges, so its targets enter the flow only here. Targets chain
632
+ // (an ifNode may target another ifNode, or a guard whose implicit exit
633
+ // ends need collecting), so the loop runs over the growing list to a
634
+ // fixpoint instead of a snapshot.
635
+ for (let i = 0; i < nodes.length; i++) {
636
+ const n = nodes[i];
637
+ addGuardTargets(n);
638
+ if (isIfNode(n)) {
639
+ for (const c of n.cases) addNode(c.to);
640
+ addNode(n.else);
641
+ }
101
642
  }
102
- const flow: FlowSchema = { name, description: schema.description, start: schema.start, nodes, edges: schema.edges };
643
+ flow.nodes = nodes;
103
644
  validate(flow);
104
645
  return flow;
105
646
  }
106
647
 
107
- // Nodes that never appear as an edge start are terminals. Reverse BFS from all
108
- // terminals marks every node that can reach a terminal; unmarked nodes sit on
109
- // a path that never ends (e.g. a cycle without an exit) reject them at
110
- // definition time.
648
+ // Reverse BFS from every FlowEnd marks all nodes that can reach an exit;
649
+ // unmarked nodes sit on a path that never ends (e.g. a cycle without an exit)
650
+ // reject them at definition time. Guard checks count as implicit edges of
651
+ // the guard itself; TryNode internals are validated inside their own flows.
111
652
  function validate(schema: FlowSchema): void {
112
- const starts = new Set<FlowNode>();
113
- for (const e of schema.edges) starts.add(e.start);
114
-
115
- const reverse = new Map<FlowNode, FlowNode[]>();
653
+ const reverse = new Map<FlowNodeOrEnd, FlowNodeOrEnd[]>();
116
654
  for (const n of schema.nodes) reverse.set(n, []);
117
655
  for (const e of schema.edges) {
118
656
  reverse.get(e.end)!.push(e.start);
119
657
  }
658
+ // guard checks are implicit edges of the guard node itself (return checks
659
+ // to the return end, exception checks to the matching exception end)
660
+ for (const n of schema.nodes) {
661
+ if (!isGuard(n)) continue;
662
+ for (const c of n.checks) {
663
+ if (c.return) {
664
+ const arr = reverse.get(schema.returnEnd);
665
+ if (arr) arr.push(n); // returnEnd is absent when no edge targets it; the guard is then unreachable anyway
666
+ } else if (c.exception) {
667
+ const t = findExceptionEnd(schema, c.exception.name);
668
+ if (t) reverse.get(t)!.push(n);
669
+ }
670
+ }
671
+ }
672
+ // ifNode branches are implicit edges of the decision node itself
673
+ for (const n of schema.nodes) {
674
+ if (!isIfNode(n)) continue;
675
+ for (const c of n.cases) reverse.get(c.to)!.push(n);
676
+ reverse.get(n.else)!.push(n);
677
+ }
120
678
 
121
- const reached = new Set<FlowNode>();
122
- const queue: FlowNode[] = [];
679
+ const reached = new Set<FlowNodeOrEnd>();
680
+ const queue: FlowNodeOrEnd[] = [];
123
681
  for (const n of schema.nodes) {
124
- if (!starts.has(n)) {
682
+ if (isEnd(n)) {
125
683
  reached.add(n);
126
684
  queue.push(n);
127
685
  }
@@ -138,7 +696,532 @@ function validate(schema: FlowSchema): void {
138
696
 
139
697
  for (const n of schema.nodes) {
140
698
  if (!reached.has(n)) {
141
- throw new Error(`flow ${schema.name}: node "${n.name}" cannot reach a terminal`);
699
+ throw new Error(`flow ${schema.name}: node "${n.name}" cannot reach an end node`);
700
+ }
701
+ }
702
+
703
+ // Forward BFS from the start: every node must be reachable, so dead regions
704
+ // cannot silently pollute the escape set (or the catch matching).
705
+ const fromStart = new Set<FlowNodeOrEnd>();
706
+ const forward: FlowNodeOrEnd[] = [schema.start];
707
+ while (forward.length > 0) {
708
+ const cur = forward.shift()!;
709
+ if (fromStart.has(cur)) continue;
710
+ fromStart.add(cur);
711
+ for (const e of schema.edges) {
712
+ if (e.start === cur) forward.push(e.end);
713
+ }
714
+ if (isGuard(cur)) {
715
+ for (const c of cur.checks) {
716
+ if (c.return) {
717
+ forward.push(schema.returnEnd);
718
+ } else if (c.exception) {
719
+ const t = findExceptionEnd(schema, c.exception.name);
720
+ if (t) forward.push(t);
721
+ }
722
+ }
723
+ }
724
+ if (isIfNode(cur)) {
725
+ for (const c of cur.cases) forward.push(c.to);
726
+ forward.push(cur.else);
727
+ }
728
+ }
729
+ for (const n of schema.nodes) {
730
+ if (!fromStart.has(n)) {
731
+ throw new Error(`flow ${schema.name}: node "${n.name}" is not reachable from the start node`);
732
+ }
733
+ }
734
+
735
+ validateGuardChecks(schema);
736
+ for (const e of schema.edges) {
737
+ if (e.check !== undefined) {
738
+ validateCondition(`flow ${schema.name}: edge "${e.name}"`, e.check);
739
+ }
740
+ }
741
+ for (const n of schema.nodes) {
742
+ if (isIfNode(n)) validateIfNode(n, schema);
743
+ }
744
+ validateSlots(schema);
745
+ for (const n of schema.nodes) {
746
+ if (isEnd(n)) continue;
747
+ validateThrowsCoverage(n, schema);
748
+ if (isTryNode(n)) validateTryNode(n, schema);
749
+ }
750
+
751
+ // Guard check exceptions exit implicitly — a typed throws edge carrying
752
+ // one of the guard's own check exceptions would duplicate the route. Edges
753
+ // carrying other exceptions (or catch-all edges) stay legal: they route
754
+ // throws declared by the guard's methods.
755
+ for (const e of schema.edges) {
756
+ if (!isGuard(e.start)) continue;
757
+ if (e.throws !== undefined && e.start.checks.some((c) => c.exception?.name === e.throws!.name)) {
758
+ throw new Error(
759
+ `flow ${schema.name}: edge "${e.name}" from guard "${e.start.name}" duplicates the implicit route of check exception ${e.throws.name} — guard checks route implicitly to the matching exception end`,
760
+ );
761
+ }
762
+ }
763
+
764
+ // An ifNode owns its exits internally (cases and else) — outgoing edges
765
+ // would be a second way out of the decision.
766
+ for (const e of schema.edges) {
767
+ if (!isIfNode(e.start)) continue;
768
+ throw new Error(
769
+ `flow ${schema.name}: edge "${e.name}" from ifNode "${e.start.name}" is redundant — ifNode exits are internal (cases and else)`,
770
+ );
771
+ }
772
+
773
+ // Typed throws edges land on an exception end carrying the same exception
774
+ // (escape) — never on a plain step, and no silent renames.
775
+ for (const e of schema.edges) {
776
+ if (e.throws === undefined) continue;
777
+ if (!isEnd(e.end) || e.end.type !== 'exception') {
778
+ throw new Error(
779
+ `flow ${schema.name}: edge "${e.name}" carries throw ${e.throws.name} but its target is not an exception end`,
780
+ );
781
+ }
782
+ if (!e.end.exception) {
783
+ throw new Error(
784
+ `flow ${schema.name}: edge "${e.name}" targets exception end "${e.end.name}" with no exception type`,
785
+ );
786
+ }
787
+ if (e.end.exception.name !== e.throws.name) {
788
+ throw new Error(
789
+ `flow ${schema.name}: edge "${e.name}" carries throw ${e.throws.name} but targets the ${e.end.exception.name} exception end`,
790
+ );
791
+ }
792
+ }
793
+
794
+ // Untyped catch-all edges also escape — the target must be an exception end.
795
+ for (const e of schema.edges) {
796
+ if (e.exception !== true || e.throws !== undefined) continue;
797
+ if (!isEnd(e.end) || e.end.type !== 'exception') {
798
+ throw new Error(
799
+ `flow ${schema.name}: edge "${e.name}" catch-all exception path must target an exception end`,
800
+ );
801
+ }
802
+ }
803
+
804
+ // Plain sub-flows are structure only — exceptions must go through a tryNode.
805
+ for (const n of schema.nodes) {
806
+ if (!isFlowNode(n) || !n.flow) continue;
807
+ const ends = exceptionEndNames(n.flow);
808
+ if (ends.size > 0) {
809
+ throw new Error(
810
+ `flow ${schema.name}: node "${n.name}" sub-flow must not declare exception ends (${[...ends].join(', ')}) — a guard check exception also creates one; use a tryNode for a protected region`,
811
+ );
812
+ }
813
+ }
814
+ }
815
+
816
+ // Every guard check must choose exactly one of return / exception; its
817
+ // optional machine-readable condition must be well-formed.
818
+ function validateGuardChecks(schema: FlowSchema): void {
819
+ for (const n of schema.nodes) {
820
+ if (!isGuard(n)) continue;
821
+ for (const c of n.checks) {
822
+ const hasReturn = c.return === true;
823
+ const hasException = c.exception !== undefined;
824
+ if (hasReturn === hasException) {
825
+ throw new Error(
826
+ `flow ${schema.name}: guard "${n.name}" check "${c.when}" must have exactly one of return/exception`,
827
+ );
828
+ }
829
+ if (c.check !== undefined) {
830
+ validateCondition(`flow ${schema.name}: guard "${n.name}" check "${c.when}"`, c.check);
831
+ }
832
+ }
833
+ }
834
+ }
835
+
836
+ // A condition must be a utils predicate call (boolean result, no result
837
+ // slot) or a field comparison whose op is known and whose value presence and
838
+ // type match the operator.
839
+ const COMPARE_OPS: readonly CompareOp[] = ['lt', 'le', 'gt', 'ge', 'eq', 'ne', 'isNull', 'isNotNull'];
840
+
841
+ function validateCondition(where: string, c: GuardCondition): void {
842
+ if (!isCall(c)) {
843
+ const f = c.field as Partial<SlotFieldRef> | null;
844
+ if (typeof f !== 'object' || f === null || typeof f.slot !== 'object' || typeof f.field !== 'object') {
845
+ throw new Error(`${where}: ${c.op} field must be a slot field access like slots.args.amt`);
846
+ }
847
+ if (!(COMPARE_OPS as readonly unknown[]).includes(c.op)) {
848
+ throw new Error(`${where}: unknown comparison op ${String(c.op)}`);
849
+ }
850
+ const nullOp = c.op === 'isNull' || c.op === 'isNotNull';
851
+ if (nullOp && c.value !== undefined) {
852
+ throw new Error(`${where}: ${c.op} takes no value`);
142
853
  }
854
+ if (!nullOp && c.value === undefined) {
855
+ throw new Error(`${where}: ${c.op} requires a value`);
856
+ }
857
+ const v = c.value;
858
+ if (v !== undefined && typeof v !== 'string' && typeof v !== 'number') {
859
+ const ev = v as Partial<EnumValue> | null;
860
+ if (typeof ev !== 'object' || ev === null || ev.value === undefined || ev.symbol === undefined || ev.label === undefined) {
861
+ throw new Error(`${where}: ${c.op} value must be a string, number, or enum value`);
862
+ }
863
+ }
864
+ return;
865
+ }
866
+ const m = c.method as { type?: string; name: string };
867
+ if (m.type !== 'utilsMethod') {
868
+ throw new Error(`${where}: check call must be a utils predicate, got ${m.type ?? m.name}`);
869
+ }
870
+ if (c.result !== undefined) {
871
+ throw new Error(`${where}: a predicate call cannot bind a result slot`);
872
+ }
873
+ }
874
+
875
+ /** Slots a condition reads: a comparison's field slot or a predicate call's arg slots. */
876
+ function conditionSlots(c: GuardCondition): FlowSlot[] {
877
+ if (!isCall(c)) return [c.field.slot];
878
+ return c.args ?? [];
879
+ }
880
+
881
+ // ifNode rules: at least one case, every condition well-formed, and targets
882
+ // are steps — flow exits (return/throw) belong to guard checks, not to
883
+ // conditional jumps.
884
+ function validateIfNode(n: IfNode, schema: FlowSchema): void {
885
+ if (n.cases.length === 0) {
886
+ throw new Error(`flow ${schema.name}: ifNode "${n.name}" must have at least one case`);
887
+ }
888
+ for (const c of n.cases) {
889
+ validateCondition(`flow ${schema.name}: ifNode "${n.name}" case "${c.when}"`, c.check);
890
+ validateIfTarget(schema, n, c.to, `case "${c.when}"`);
891
+ }
892
+ validateIfTarget(schema, n, n.else, 'else');
893
+ }
894
+
895
+ function validateIfTarget(schema: FlowSchema, n: IfNode, t: FlowNodeOrEnd, where: string): void {
896
+ if (isEnd(t)) {
897
+ throw new Error(
898
+ `flow ${schema.name}: ifNode "${n.name}" ${where} must target a step — flow exits (return/throw) belong to guard checks`,
899
+ );
900
+ }
901
+ }
902
+
903
+ // Slots: every referenced slot must be declared in this flow's registers
904
+ // (sub-flows analyze their own slots), every declared named slot must be
905
+ // used, and a slot may only be consumed when every path from the start has
906
+ // produced it (must-analysis over the control graph). The built-in args slot
907
+ // is the flow input: it needs no registration and is available on entry.
908
+ // Within one node, calls run in order, so an earlier call's result feeds a
909
+ // later call's args; the node's own writes feed everything after them.
910
+ // Slot/contract type differences convert implicitly and are not validated.
911
+ function validateSlots(schema: FlowSchema): void {
912
+ const registry = schema.slots;
913
+ const argsSlot = registry?.args;
914
+ const declared = new Set<FlowSlot>(registry === undefined ? [] : Object.values(registry));
915
+ const used = new Set<FlowSlot>();
916
+
917
+ const produced = new Map<FlowNodeOrEnd, Set<FlowSlot>>();
918
+ for (const n of schema.nodes) {
919
+ const p = new Set<FlowSlot>();
920
+ if (!isEnd(n) && !isTryNode(n)) {
921
+ if (isIfNode(n)) {
922
+ for (const c of n.cases) {
923
+ for (const t of conditionSlots(c.check)) used.add(t);
924
+ }
925
+ } else {
926
+ for (const ref of n.methods ?? []) {
927
+ if (!isCall(ref)) continue;
928
+ for (const t of ref.args ?? []) used.add(t);
929
+ if (ref.result) {
930
+ used.add(ref.result);
931
+ p.add(ref.result);
932
+ }
933
+ }
934
+ if (isFlowNode(n)) {
935
+ for (const t of n.reads ?? []) used.add(t);
936
+ if (n.publish?.payload) used.add(n.publish.payload);
937
+ for (const t of n.writes ?? []) {
938
+ used.add(t);
939
+ p.add(t);
940
+ }
941
+ }
942
+ if (isGuard(n)) {
943
+ for (const ch of n.checks) {
944
+ for (const t of ch.reads ?? []) used.add(t);
945
+ if (ch.check) {
946
+ for (const t of conditionSlots(ch.check)) used.add(t);
947
+ }
948
+ }
949
+ }
950
+ }
951
+ }
952
+ produced.set(n, p);
143
953
  }
954
+ // a branch edge's condition is decided at its start node
955
+ for (const e of schema.edges) {
956
+ if (!e.check) continue;
957
+ for (const t of conditionSlots(e.check)) used.add(t);
958
+ }
959
+
960
+ for (const t of used) {
961
+ if (!declared.has(t)) {
962
+ if (t.name === 'args') {
963
+ throw new Error(
964
+ `flow ${schema.name}: slot "args" is not declared — declare the flow's slots via defineSlots (its built-in args slot)`,
965
+ );
966
+ }
967
+ throw new Error(`flow ${schema.name}: slot "${t.name}" is not declared in the flow's slots`);
968
+ }
969
+ }
970
+ for (const t of declared) {
971
+ if (t === argsSlot) continue; // the input slot needs no use
972
+ if (!used.has(t)) {
973
+ throw new Error(`flow ${schema.name}: slot "${t.name}" is declared but never used`);
974
+ }
975
+ }
976
+
977
+ // Fixpoint over the graph: available(n) = intersection over all incoming
978
+ // edges of (available(start) ∪ produced(start)). The input slot is seeded
979
+ // at the start. Sets only grow, so the fixpoint terminates. Incoming edges
980
+ // include the implicit ones (ifNode cases/else), so availability flows
981
+ // through decision nodes the same way reachability does.
982
+ const reverse = new Map<FlowNodeOrEnd, FlowNodeOrEnd[]>();
983
+ for (const n of schema.nodes) reverse.set(n, []);
984
+ for (const e of schema.edges) reverse.get(e.end)!.push(e.start);
985
+ for (const n of schema.nodes) {
986
+ if (!isIfNode(n)) continue;
987
+ for (const c of n.cases) reverse.get(c.to)!.push(n);
988
+ reverse.get(n.else)!.push(n);
989
+ }
990
+ const avail = new Map<FlowNodeOrEnd, Set<FlowSlot>>();
991
+ for (const n of schema.nodes) avail.set(n, new Set<FlowSlot>());
992
+ const seeded = new Set<FlowSlot>();
993
+ if (argsSlot) seeded.add(argsSlot);
994
+ for (const t of schema.entrySlots ?? []) {
995
+ if (!declared.has(t)) {
996
+ throw new Error(`flow ${schema.name}: entry slot "${t.name}" is not declared in the flow's slots`);
997
+ }
998
+ seeded.add(t);
999
+ }
1000
+ // add one by one: this engine's Set.prototype.add takes a single value
1001
+ for (const t of seeded) avail.get(schema.start)!.add(t);
1002
+ let changed = true;
1003
+ while (changed) {
1004
+ changed = false;
1005
+ for (const n of schema.nodes) {
1006
+ if (n === schema.start) continue;
1007
+ const incoming = reverse.get(n)!;
1008
+ if (incoming.length === 0) continue;
1009
+ let intersection: Set<FlowSlot> | undefined;
1010
+ for (const srcN of incoming) {
1011
+ const src = new Set(avail.get(srcN)!);
1012
+ for (const t of produced.get(srcN)!) src.add(t);
1013
+ intersection = intersection === undefined ? src : new Set([...intersection].filter((t) => src.has(t)));
1014
+ }
1015
+ if (intersection === undefined) continue;
1016
+ for (const t of intersection) {
1017
+ if (!avail.get(n)!.has(t)) {
1018
+ avail.get(n)!.add(t);
1019
+ changed = true;
1020
+ }
1021
+ }
1022
+ }
1023
+ }
1024
+
1025
+ // Consumption check walks each node's ordered sequence: writes
1026
+ // (constructions) first, then calls in order, then branch reads/checks.
1027
+ const missing = (n: FlowStep, t: FlowSlot): Error => {
1028
+ if (n === schema.start) {
1029
+ return new Error(
1030
+ `flow ${schema.name}: start node "${n.name}" cannot consume slot "${t.name}" — nothing else is produced before entry`,
1031
+ );
1032
+ }
1033
+ return new Error(`flow ${schema.name}: node "${n.name}" reads slot "${t.name}" that may not be written on every path`);
1034
+ };
1035
+ for (const n of schema.nodes) {
1036
+ if (isEnd(n) || isTryNode(n)) continue;
1037
+ const inner = new Set(avail.get(n)!);
1038
+ if (isFlowNode(n)) {
1039
+ for (const t of n.writes ?? []) inner.add(t);
1040
+ }
1041
+ if (!isIfNode(n)) {
1042
+ for (const ref of n.methods ?? []) {
1043
+ if (!isCall(ref)) continue;
1044
+ for (const t of ref.args ?? []) {
1045
+ if (!inner.has(t)) throw missing(n, t);
1046
+ }
1047
+ if (ref.result) inner.add(ref.result);
1048
+ }
1049
+ }
1050
+ if (isFlowNode(n)) {
1051
+ for (const t of n.reads ?? []) {
1052
+ if (!inner.has(t)) throw missing(n, t);
1053
+ }
1054
+ if (n.publish?.payload && !inner.has(n.publish.payload)) throw missing(n, n.publish.payload);
1055
+ }
1056
+ if (isGuard(n)) {
1057
+ for (const ch of n.checks) {
1058
+ for (const t of ch.reads ?? []) {
1059
+ if (!inner.has(t)) throw missing(n, t);
1060
+ }
1061
+ if (ch.check) {
1062
+ for (const t of conditionSlots(ch.check)) {
1063
+ if (!inner.has(t)) throw missing(n, t);
1064
+ }
1065
+ }
1066
+ }
1067
+ }
1068
+ if (isIfNode(n)) {
1069
+ for (const c of n.cases) {
1070
+ for (const t of conditionSlots(c.check)) {
1071
+ if (!inner.has(t)) throw missing(n, t);
1072
+ }
1073
+ }
1074
+ }
1075
+ // branch decisions read their slots at the end of the node
1076
+ for (const e of schema.edges) {
1077
+ if (e.start !== n || !e.check) continue;
1078
+ for (const t of conditionSlots(e.check)) {
1079
+ if (!inner.has(t)) throw missing(n, t);
1080
+ }
1081
+ }
1082
+ }
1083
+ }
1084
+
1085
+ // Every exception a step declares (methods throws, TryNode rethrows) must be
1086
+ // routed: typed throws edges or an untyped exception edge (catch-all). Guard
1087
+ // check exceptions route implicitly to the matching exception end and are not
1088
+ // covered here. The reverse direction (routed ⊆ declared) is intentionally
1089
+ // not validated while steps carry pure descriptors — a MethodSchema has no
1090
+ // throws field yet, so typed edges may document throws the descriptor cannot
1091
+ // express. Once contract refs replace the descriptors, the reverse check can
1092
+ // be enforced.
1093
+ function validateThrowsCoverage(n: FlowStep, schema: FlowSchema): void {
1094
+ const declared = new Set<string>();
1095
+ if (!isTryNode(n) && !isIfNode(n)) {
1096
+ for (const ref of n.methods ?? []) {
1097
+ const m = methodOf(ref);
1098
+ if ('throws' in m && m.throws) {
1099
+ for (const e of m.throws) declared.add(e.name);
1100
+ }
1101
+ }
1102
+ }
1103
+ if (isTryNode(n)) {
1104
+ for (const c of n.catches) {
1105
+ for (const name of exceptionEndNames(c.handler)) declared.add(name);
1106
+ }
1107
+ }
1108
+ if (declared.size === 0) return;
1109
+
1110
+ const routed = new Set<string>();
1111
+ for (const e of schema.edges) {
1112
+ if (e.start !== n) continue;
1113
+ if (e.throws) {
1114
+ routed.add(e.throws.name);
1115
+ } else if (e.exception === true) {
1116
+ return; // untyped exception edge: catch-all
1117
+ }
1118
+ }
1119
+ for (const d of declared) {
1120
+ if (!routed.has(d)) {
1121
+ throw new Error(
1122
+ `flow ${schema.name}: node "${n.name}" declares throw ${d} but has no typed throws edge for it`,
1123
+ );
1124
+ }
1125
+ }
1126
+ }
1127
+
1128
+ // TryNode rules: catches must be unique with UnexpectedException last, every
1129
+ // body exception end needs a catch, every catch must match a body exception
1130
+ // end (no dead catches), and finally must be pure cleanup (no exception ends).
1131
+ // Body end names must be unique so catch matching is unambiguous. Catch
1132
+ // matching works on declared end names — reachability of a body end from the
1133
+ // body start is not analyzed (a dead region's end would still count).
1134
+ function validateTryNode(n: TryNode, schema: FlowSchema): void {
1135
+ const seen = new Set<string>();
1136
+ let catchAll = false;
1137
+ for (const c of n.catches) {
1138
+ if (seen.has(c.exception.name)) {
1139
+ throw new Error(
1140
+ `flow ${schema.name}: tryNode "${n.name}" has duplicate catch ${c.exception.name}`,
1141
+ );
1142
+ }
1143
+ seen.add(c.exception.name);
1144
+ if (catchAll) {
1145
+ throw new Error(
1146
+ `flow ${schema.name}: tryNode "${n.name}" catch ${c.exception.name} must precede the ${UnexpectedException.name} catch`,
1147
+ );
1148
+ }
1149
+ if (c.exception.name === UnexpectedException.name) catchAll = true;
1150
+ }
1151
+
1152
+ const bodyEndCounts = new Map<string, number>();
1153
+ for (const node of n.body.nodes) {
1154
+ if (isEnd(node) && node.type === 'exception' && node.exception) {
1155
+ bodyEndCounts.set(node.exception.name, (bodyEndCounts.get(node.exception.name) ?? 0) + 1);
1156
+ }
1157
+ }
1158
+ for (const [name, count] of bodyEndCounts) {
1159
+ if (count > 1) {
1160
+ throw new Error(
1161
+ `flow ${schema.name}: tryNode "${n.name}" body has ${count} exception ends named ${name}`,
1162
+ );
1163
+ }
1164
+ }
1165
+ const bodyEnds = new Set(bodyEndCounts.keys());
1166
+ for (const name of bodyEnds) {
1167
+ if (!seen.has(name)) {
1168
+ throw new Error(
1169
+ `flow ${schema.name}: tryNode "${n.name}" body exception end ${name} has no catch`,
1170
+ );
1171
+ }
1172
+ }
1173
+ for (const c of n.catches) {
1174
+ if (!bodyEnds.has(c.exception.name)) {
1175
+ throw new Error(
1176
+ `flow ${schema.name}: tryNode "${n.name}" catch ${c.exception.name} matches no body exception end`,
1177
+ );
1178
+ }
1179
+ }
1180
+
1181
+ if (n.finally) {
1182
+ const f = exceptionEndNames(n.finally);
1183
+ if (f.size > 0) {
1184
+ throw new Error(
1185
+ `flow ${schema.name}: tryNode "${n.name}" finally must not declare exception ends: ${[...f].join(', ')}`,
1186
+ );
1187
+ }
1188
+ }
1189
+ }
1190
+
1191
+ /** Exception names declared by a flow's exception ends — the flow's escape
1192
+ * set (throws that reach the caller unless caught by an outer tryNode). */
1193
+ export function exceptionEndNames(flow: FlowSchema): Set<string> {
1194
+ const names = new Set<string>();
1195
+ for (const n of flow.nodes) {
1196
+ if (!isEnd(n) || n.type !== 'exception') continue;
1197
+ if (!n.exception) {
1198
+ throw new Error(`flow ${flow.name}: exception end "${n.name}" has no exception type`);
1199
+ }
1200
+ names.add(n.exception.name);
1201
+ }
1202
+ return names;
1203
+ }
1204
+
1205
+ export function isEnd(n: FlowNodeOrEnd): n is FlowEnd {
1206
+ return 'type' in n && (n.type === 'return' || n.type === 'exception');
1207
+ }
1208
+
1209
+ function messageName(t: unknown): string {
1210
+ return (t as { name?: string } | null | undefined)?.name ?? 'an unnamed message';
1211
+ }
1212
+
1213
+ export function isFlowNode(n: FlowNodeOrEnd): n is FlowNode {
1214
+ return !('type' in n);
1215
+ }
1216
+
1217
+ export function isGuard(n: FlowNodeOrEnd): n is GuardNode {
1218
+ return 'type' in n && n.type === 'guard';
1219
+ }
1220
+
1221
+ export function isTryNode(n: FlowNodeOrEnd): n is TryNode {
1222
+ return 'type' in n && n.type === 'try';
1223
+ }
1224
+
1225
+ export function isIfNode(n: FlowNodeOrEnd): n is IfNode {
1226
+ return 'type' in n && n.type === 'if';
144
1227
  }