@nanobpm/workflow 0.8.1 → 0.9.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 (62) hide show
  1. package/README.md +1 -1
  2. package/dist/declarative.d.ts +172 -10
  3. package/dist/declarative.js +213 -355
  4. package/dist/nodes/branch.d.ts +11 -0
  5. package/dist/nodes/branch.js +40 -0
  6. package/dist/nodes/break.d.ts +8 -0
  7. package/dist/nodes/break.js +19 -0
  8. package/dist/nodes/continue.d.ts +8 -0
  9. package/dist/nodes/continue.js +18 -0
  10. package/dist/nodes/forEach.d.ts +24 -0
  11. package/dist/nodes/forEach.js +104 -0
  12. package/dist/nodes/index.d.ts +11 -0
  13. package/dist/nodes/index.js +18 -0
  14. package/dist/nodes/loop.d.ts +9 -0
  15. package/dist/nodes/loop.js +25 -0
  16. package/dist/nodes/parallel.d.ts +9 -0
  17. package/dist/nodes/parallel.js +40 -0
  18. package/dist/nodes/registry.d.ts +33 -0
  19. package/dist/nodes/registry.js +71 -0
  20. package/dist/nodes/run.d.ts +10 -0
  21. package/dist/nodes/run.js +21 -0
  22. package/dist/nodes/signal.d.ts +11 -0
  23. package/dist/nodes/signal.js +21 -0
  24. package/dist/nodes/switch.d.ts +11 -0
  25. package/dist/nodes/switch.js +51 -0
  26. package/dist/nodes/task.d.ts +11 -0
  27. package/dist/nodes/task.js +21 -0
  28. package/dist/nodes/timer.d.ts +9 -0
  29. package/dist/nodes/timer.js +34 -0
  30. package/dist/test-support/diff.d.ts +8 -0
  31. package/dist/test-support/diff.js +70 -0
  32. package/dist/test-support/index.d.ts +8 -0
  33. package/dist/test-support/index.js +49 -0
  34. package/dist/test-support/normalize.d.ts +19 -0
  35. package/dist/test-support/normalize.js +245 -0
  36. package/dist/test-support/parity.d.ts +28 -0
  37. package/dist/test-support/parity.js +61 -0
  38. package/dist/test-support/xml.d.ts +17 -0
  39. package/dist/test-support/xml.js +135 -0
  40. package/dist/types.d.ts +20 -56
  41. package/package.json +14 -6
  42. package/src/declarative.ts +327 -359
  43. package/src/nodes/README.md +123 -0
  44. package/src/nodes/branch.ts +48 -0
  45. package/src/nodes/break.ts +25 -0
  46. package/src/nodes/continue.ts +24 -0
  47. package/src/nodes/forEach.ts +137 -0
  48. package/src/nodes/index.ts +19 -0
  49. package/src/nodes/loop.ts +34 -0
  50. package/src/nodes/parallel.ts +48 -0
  51. package/src/nodes/registry.ts +105 -0
  52. package/src/nodes/run.ts +29 -0
  53. package/src/nodes/signal.ts +29 -0
  54. package/src/nodes/switch.ts +56 -0
  55. package/src/nodes/task.ts +29 -0
  56. package/src/nodes/timer.ts +42 -0
  57. package/src/test-support/diff.ts +69 -0
  58. package/src/test-support/index.ts +53 -0
  59. package/src/test-support/normalize.ts +274 -0
  60. package/src/test-support/parity.ts +85 -0
  61. package/src/test-support/xml.ts +140 -0
  62. package/src/types.ts +20 -30
@@ -0,0 +1,123 @@
1
+ # `src/nodes/` — the flow-node kind extension seam
2
+
3
+ Every flow-node **kind** in the declarative surface (`run`, `task`, `signal`,
4
+ `timer`, `switch`, `branch`, `loop`, `break`, `continue`, `parallel`, `forEach`,
5
+ and any kind a feature slice adds) lives in its **own module** here. Adding a
6
+ kind is: **drop one `src/nodes/<kind>.ts` file.** You never edit a shared union,
7
+ a central `switch`, or the barrel.
8
+
9
+ This exists so the four wave-1 slices (S1–S4, #316–#319) can each add a kind in
10
+ parallel without textually colliding on — and without any single PR's CI failing
11
+ to exercise — the dispatch that used to be a hand-edited `switch` in two files.
12
+
13
+ ## What a kind module contributes (three things, one file)
14
+
15
+ A kind module `src/nodes/<kind>.ts` declaration-merges its type surface and
16
+ registers its runtime behaviour with a single `registerNodeKind(...)` call:
17
+
18
+ 1. **Its `FlowNode` variant** — by declaration-merging one property into the
19
+ augmentable `FlowNodeRegistry` interface (in `../types.js`). `FlowNode` is
20
+ derived from that registry (`FlowNodeRegistry[keyof FlowNodeRegistry]`), so
21
+ the union grows automatically — no edit to a central union.
22
+ - **Invariant:** the property value MUST be an object type whose `kind`
23
+ discriminant equals the property key, so `FlowNode` stays a discriminated
24
+ union.
25
+
26
+ 2. **Its builder method** — by declaration-merging the method signature into the
27
+ `FlowBuilder<C>` interface (in `../declarative.js`) **and** returning a
28
+ `build` factory from `registerNodeKind`. The factory receives the per-body
29
+ `BuildApi` and returns the method installed on the builder as
30
+ `w.<builderMethod ?? kind>(…)`.
31
+
32
+ 3. **Its `walk` + `emit` handlers** — registered in the same call. `walkNodes`
33
+ and the BPMN emitter DISPATCH through this table instead of a central switch:
34
+ - `walk(node, recurse)` — recurse into the node's nested bodies (omit for a
35
+ leaf kind with no nested `FlowNode[]`).
36
+ - `emit(node, incoming, loop, api)` — place the node's BPMN element(s) via the
37
+ `EmitApi` primitives and return the outgoing (dangling) `Edge[]` its
38
+ continuation attaches to.
39
+
40
+ ## The canonical example — `run.ts`
41
+
42
+ ```ts
43
+ import type { NodeEnvelopes, StepHandler } from "../types.js";
44
+ import { registerNodeKind } from "./registry.js";
45
+
46
+ // (1) the FlowNode variant — declaration-merged into the open registry
47
+ declare module "../types.js" {
48
+ interface FlowNodeRegistry {
49
+ run: { kind: "run"; name: string; envelopes?: NodeEnvelopes };
50
+ }
51
+ }
52
+
53
+ registerNodeKind("run", {
54
+ // (2) the builder method — installed as `w.run(...)`
55
+ build: (api) => (name: string, handler: StepHandler) => {
56
+ api.claim(name);
57
+ if (typeof handler !== "function") throw new Error(`run("${name}") needs a handler`);
58
+ api.handlers[name] = handler;
59
+ api.out.push({ kind: "run", name, envelopes: api.contractEnvelopes(name) });
60
+ return api.self();
61
+ },
62
+ // (3a) walk — omitted here: `run` is a leaf (no nested bodies)
63
+ // (3b) emit — place the BPMN element, wire the edges
64
+ emit: (node, incoming, _loop, api) => {
65
+ api.addServiceTask(node);
66
+ api.connect(incoming, node.name);
67
+ return [api.newEdge(node.name)];
68
+ },
69
+ });
70
+ ```
71
+
72
+ A kind with its OWN richer, generically-typed builder signature (like the
73
+ built-ins) also augments `FlowBuilder<C>`:
74
+
75
+ ```ts
76
+ declare module "../declarative.js" {
77
+ interface FlowBuilder<C extends object> {
78
+ myKind<K extends string>(name: K, opts: MyOpts): FlowBuilder<C>;
79
+ }
80
+ }
81
+ ```
82
+
83
+ A kind with nested bodies (like `switch`/`branch`/`loop`) supplies `walk` and
84
+ uses `api.child(fn, inLoop)` / `api.childScoped(fn)` in its `build`, and
85
+ `api.emitList(body, incoming, loop)` in its `emit` — see `switch.ts`, `loop.ts`,
86
+ `forEach.ts`.
87
+
88
+ ## The APIs you get
89
+
90
+ - **`BuildApi`** (authoring time, in `build`): `id`, `isRoot`, `out`,
91
+ `contracts`, `handlers`, `loopDepth`, `self()`, `child(fn, inLoop)`,
92
+ `childScoped(fn)`, `claim(name)`, `contractEnvelopes(name)`, `setStartTimer(t)`.
93
+ - **`EmitApi`** (compile time, in `emit`): `flowId`, `newEdge`, `connect`,
94
+ `recordEnvelope`, `emitList`, `addNode`, `addServiceTask`, `addCatchEvent`,
95
+ `addTimerCatchEvent`, `addGateway`, `addParallelGateway`, `addSubProcess`,
96
+ `addPlainStart`, `addPlainEnd`, `nextGw()`, `currentScope()`, `pushScope`,
97
+ `popScope`. Node-render string helpers (`incomingOutgoing`, `escapeXml`, …) are
98
+ exported from `../declarative.js` / `../xml.js` for a custom `RenderNode.render`.
99
+
100
+ All are exported from `../declarative.js`; the registration function and its
101
+ `NodeKindHandlers<N>` type are in `./registry.js`.
102
+
103
+ ## Rules
104
+
105
+ - **Never** edit `FlowNodeRegistry` in `types.ts`, the `FlowBuilder<C>` interface
106
+ outside your own `declare module`, or `index.ts` (it is generated — see below).
107
+ - **Import types with `import type`** (the package uses
108
+ `verbatimModuleSyntax`).
109
+ - **No `as T` assertions** (repo-wide ban — see the root `AGENTS.md`); narrow with
110
+ a type guard, an annotation, or `satisfies`.
111
+ - Register **exactly once** per kind (`registerNodeKind` throws on a duplicate
112
+ kind; builder assembly in `makeBuilder` additionally throws when two kinds
113
+ contribute the same duplicate builder-method name).
114
+
115
+ ## The generated barrel
116
+
117
+ `index.ts` is **generated** by `scripts/gen-node-registry.mjs` (a `build`/
118
+ `typecheck` prebuild step): it scans this directory and emits a sorted list of
119
+ side-effect imports so every kind's `registerNodeKind(...)` runs. Because it is
120
+ regenerated and alphabetically ordered, two slices that each add a different
121
+ `<kind>.ts` file merge without conflict and are wired automatically — **do not
122
+ hand-edit `index.ts`.** (`package.json`'s `sideEffects` allowlist keeps a
123
+ downstream bundler from tree-shaking these registrations away.)
@@ -0,0 +1,48 @@
1
+ // Built-in flow-node kind: `branch` — a two-way exclusive choice on a FEEL
2
+ // boolean condition (a BPMN exclusive gateway); the `then` arm is guarded, the
3
+ // `else` arm is the gateway default. Contributed through the extension seam.
4
+
5
+ import type { FlowNode } from "../types.js";
6
+ import type { Block } from "../declarative.js";
7
+ import { feel } from "../declarative.js";
8
+ import { registerNodeKind } from "./registry.js";
9
+
10
+ declare module "../types.js" {
11
+ interface FlowNodeRegistry {
12
+ branch: { kind: "branch"; condition: string; then: FlowNode[]; else?: FlowNode[] };
13
+ }
14
+ }
15
+
16
+ registerNodeKind("branch", {
17
+ build: (api) => (condition: string, arms: { then: Block; else?: Block }) => {
18
+ if (typeof condition !== "string" || condition.trim() === "") {
19
+ throw new Error(`branch() needs a non-empty FEEL condition`);
20
+ }
21
+ if (!arms || typeof arms.then !== "function") throw new Error(`branch("${condition}") needs a then arm`);
22
+ if (arms.else !== undefined && typeof arms.else !== "function") {
23
+ throw new Error(`branch("${condition}") else arm must be a block (b) => {…}`);
24
+ }
25
+ api.out.push({
26
+ kind: "branch",
27
+ condition,
28
+ then: api.child(arms.then, false),
29
+ else: arms.else ? api.child(arms.else, false) : undefined,
30
+ });
31
+ return api.self();
32
+ },
33
+ walk: (node, recurse) => {
34
+ recurse(node.then);
35
+ if (node.else) recurse(node.else);
36
+ },
37
+ emit: (node, incoming, loop, api) => {
38
+ const id = `Gw_${api.nextGw()}`;
39
+ const gw = api.addGateway(id);
40
+ api.connect(incoming, id);
41
+ const te = api.newEdge(id, { condition: feel(node.condition), name: "then" });
42
+ const out = api.emitList(node.then, [te], loop);
43
+ const ee = api.newEdge(id, { name: "else" });
44
+ gw.defaultFlow = ee.id;
45
+ out.push(...api.emitList(node.else ?? [], [ee], loop));
46
+ return out;
47
+ },
48
+ });
@@ -0,0 +1,25 @@
1
+ // Built-in flow-node kind: `break` — exit the enclosing loop (routes to whatever
2
+ // follows it). Only valid inside a `loop`. Contributed through the extension seam.
3
+
4
+ import { registerNodeKind } from "./registry.js";
5
+
6
+ declare module "../types.js" {
7
+ interface FlowNodeRegistry {
8
+ break: { kind: "break" };
9
+ }
10
+ }
11
+
12
+ registerNodeKind("break", {
13
+ build: (api) => () => {
14
+ if (api.loopDepth === 0) throw new Error(`break() is only valid inside a loop`);
15
+ api.out.push({ kind: "break" });
16
+ return api.self();
17
+ },
18
+ emit: (_node, incoming, loop, api) => {
19
+ if (!loop) throw new Error(`break outside a loop in flow "${api.flowId}"`);
20
+ // The incoming edges (from the previous node) become the loop's exit
21
+ // danglers; this path does not fall through.
22
+ loop.breaks.push(...incoming);
23
+ return [];
24
+ },
25
+ });
@@ -0,0 +1,24 @@
1
+ // Built-in flow-node kind: `continue` — jump straight back to the top of the
2
+ // enclosing loop, skipping the rest of the body. Only valid inside a `loop`.
3
+ // Contributed through the extension seam (epic #314, S0/#315).
4
+
5
+ import { registerNodeKind } from "./registry.js";
6
+
7
+ declare module "../types.js" {
8
+ interface FlowNodeRegistry {
9
+ continue: { kind: "continue" };
10
+ }
11
+ }
12
+
13
+ registerNodeKind("continue", {
14
+ build: (api) => () => {
15
+ if (api.loopDepth === 0) throw new Error(`continue() is only valid inside a loop`);
16
+ api.out.push({ kind: "continue" });
17
+ return api.self();
18
+ },
19
+ emit: (_node, incoming, loop, api) => {
20
+ if (!loop) throw new Error(`continue outside a loop in flow "${api.flowId}"`);
21
+ api.connect(incoming, loop.headId);
22
+ return [];
23
+ },
24
+ });
@@ -0,0 +1,137 @@
1
+ // Built-in flow-node kind: `forEach` — a data-driven fan-out over a runtime
2
+ // collection (a BPMN parallel/sequential multi-instance activity). A single
3
+ // service-task body lifts the MI characteristics directly; a multi-step body is
4
+ // wrapped in an embedded MI sub-process. Contributed through the extension seam.
5
+
6
+ import type { FlowNode } from "../types.js";
7
+ import type { Block } from "../declarative.js";
8
+ import { assertIdent, escapeXml } from "../xml.js";
9
+ import { registerNodeKind } from "./registry.js";
10
+
11
+ /** The `forEach` node shape (its `FlowNode` variant). */
12
+ interface ForEachNode {
13
+ kind: "forEach";
14
+ /** FEEL expression evaluating to the list to fan out over. */
15
+ collection: string;
16
+ /** Variable each item is bound to in the child's scope (`inputElement`). */
17
+ itemVar: string;
18
+ body: FlowNode[];
19
+ /** Run children one at a time (sequential MI) instead of all at once. */
20
+ sequential?: boolean;
21
+ /** List variable that each child's `outputElement` is collected into. */
22
+ outputCollection?: string;
23
+ /** FEEL expression producing each child's contribution to `outputCollection`. */
24
+ outputElement?: string;
25
+ /** FEEL boolean that, once true, completes the body early. */
26
+ completionCondition?: string;
27
+ }
28
+
29
+ declare module "../types.js" {
30
+ interface FlowNodeRegistry {
31
+ forEach: ForEachNode;
32
+ }
33
+ }
34
+
35
+ interface ForEachOpts {
36
+ sequential?: boolean;
37
+ outputCollection?: string;
38
+ outputElement?: string;
39
+ completionCondition?: string;
40
+ }
41
+
42
+ /** The `<bpmn:multiInstanceLoopCharacteristics>` block for a `forEach` node — the
43
+ * same shape whether lifted onto a leaf service task or a sub-process. */
44
+ function miCharacteristics(node: ForEachNode): string {
45
+ const seq = node.sequential ? "true" : "false";
46
+ const attrs = [
47
+ `inputCollection="${escapeXml(`=${node.collection}`)}"`,
48
+ `inputElement="${escapeXml(node.itemVar)}"`,
49
+ ];
50
+ if (node.outputCollection) attrs.push(`outputCollection="${escapeXml(node.outputCollection)}"`);
51
+ if (node.outputElement) attrs.push(`outputElement="${escapeXml(`=${node.outputElement}`)}"`);
52
+ const completion = node.completionCondition
53
+ ? ` <bpmn:completionCondition>${escapeXml(`=${node.completionCondition}`)}</bpmn:completionCondition>\n`
54
+ : "";
55
+ return (
56
+ ` <bpmn:multiInstanceLoopCharacteristics isSequential="${seq}">\n` +
57
+ ` <bpmn:extensionElements>\n` +
58
+ ` <zeebe:loopCharacteristics ${attrs.join(" ")} />\n` +
59
+ ` </bpmn:extensionElements>\n` +
60
+ completion +
61
+ ` </bpmn:multiInstanceLoopCharacteristics>\n`
62
+ );
63
+ }
64
+
65
+ registerNodeKind("forEach", {
66
+ build: (api) => (collection: string, itemVar: string, body: Block, opts?: ForEachOpts) => {
67
+ if (typeof collection !== "string" || collection.trim() === "") {
68
+ throw new Error(`forEach() needs a non-empty FEEL collection expression`);
69
+ }
70
+ // Authors may paste a leading "=" (common in Zeebe FEEL examples). Strip it
71
+ // so the emitter's own "=" prefix never produces an invalid "==...".
72
+ const collExpr = collection.trim().replace(/^=/, "").trim();
73
+ if (collExpr === "") {
74
+ throw new Error(`forEach() collection expression is empty after stripping the leading "="`);
75
+ }
76
+ assertIdent("forEach itemVar", itemVar);
77
+ if (typeof body !== "function") throw new Error(`forEach("${itemVar}") needs a body function`);
78
+ const nodes = api.childScoped(body);
79
+ if (nodes.length === 0) throw new Error(`forEach("${itemVar}") body declared no steps`);
80
+ const node: ForEachNode = { kind: "forEach", collection: collExpr, itemVar, body: nodes };
81
+ if (opts?.sequential) node.sequential = true;
82
+ if (opts?.outputCollection !== undefined) {
83
+ assertIdent("forEach outputCollection", opts.outputCollection);
84
+ node.outputCollection = opts.outputCollection;
85
+ }
86
+ if (opts?.outputElement !== undefined) {
87
+ if (typeof opts.outputElement !== "string" || opts.outputElement.trim() === "") {
88
+ throw new Error(`forEach("${itemVar}") outputElement must be a non-empty FEEL expression`);
89
+ }
90
+ const outEl = opts.outputElement.trim().replace(/^=/, "").trim();
91
+ if (outEl === "") {
92
+ throw new Error(`forEach("${itemVar}") outputElement is empty after stripping the leading "="`);
93
+ }
94
+ node.outputElement = outEl;
95
+ }
96
+ if (opts?.completionCondition !== undefined) {
97
+ if (typeof opts.completionCondition !== "string" || opts.completionCondition.trim() === "") {
98
+ throw new Error(`forEach("${itemVar}") completionCondition must be a non-empty FEEL expression`);
99
+ }
100
+ const compCond = opts.completionCondition.trim().replace(/^=/, "").trim();
101
+ if (compCond === "") {
102
+ throw new Error(`forEach("${itemVar}") completionCondition is empty after stripping the leading "="`);
103
+ }
104
+ node.completionCondition = compCond;
105
+ }
106
+ if (node.outputElement && !node.outputCollection) {
107
+ throw new Error(`forEach("${itemVar}") outputElement needs an outputCollection to collect into`);
108
+ }
109
+ api.out.push(node);
110
+ return api.self();
111
+ },
112
+ walk: (node, recurse) => recurse(node.body),
113
+ emit: (node, incoming, _loop, api) => {
114
+ const mi = miCharacteristics(node);
115
+ const only = node.body.length === 1 ? node.body[0] : undefined;
116
+ // A single service-task body carries the MI characteristics directly; a
117
+ // multi-step body is wrapped in an embedded MI sub-process (its own token
118
+ // scope, with its own start/end).
119
+ if (only && (only.kind === "run" || only.kind === "task")) {
120
+ api.addServiceTask(only, mi);
121
+ api.connect(incoming, only.name);
122
+ return [api.newEdge(only.name)];
123
+ }
124
+ const subId = `Sub_${api.nextGw()}`;
125
+ api.addSubProcess(subId, mi);
126
+ api.connect(incoming, subId);
127
+ api.pushScope(subId);
128
+ const startId = `${subId}_start`;
129
+ api.addPlainStart(startId);
130
+ const innerOut = api.emitList(node.body, [api.newEdge(startId)], null);
131
+ const endId = `${subId}_end`;
132
+ api.addPlainEnd(endId);
133
+ api.connect(innerOut, endId);
134
+ api.popScope();
135
+ return [api.newEdge(subId)];
136
+ },
137
+ });
@@ -0,0 +1,19 @@
1
+ // GENERATED by scripts/gen-node-registry.mjs — do not edit by hand.
2
+ //
3
+ // The barrel of built-in flow-node kind modules. Importing this module runs
4
+ // every kind's `registerNodeKind(...)` side effect, populating the dispatch
5
+ // table `makeBuilder`/`walkNodes`/the emitter route through. A new kind is
6
+ // picked up automatically by re-running the generator (a prebuild step) — no
7
+ // hand-edit here.
8
+
9
+ import "./branch.js";
10
+ import "./break.js";
11
+ import "./continue.js";
12
+ import "./forEach.js";
13
+ import "./loop.js";
14
+ import "./parallel.js";
15
+ import "./run.js";
16
+ import "./signal.js";
17
+ import "./switch.js";
18
+ import "./task.js";
19
+ import "./timer.js";
@@ -0,0 +1,34 @@
1
+ // Built-in flow-node kind: `loop` — a durable loop (a back-edge to the loop
2
+ // head): the body runs, then control returns to the top unless a branch calls
3
+ // `break()`. Contributed through the extension seam (epic #314, S0/#315).
4
+
5
+ import type { FlowNode } from "../types.js";
6
+ import type { Block, LoopCtx } from "../declarative.js";
7
+ import { registerNodeKind } from "./registry.js";
8
+
9
+ declare module "../types.js" {
10
+ interface FlowNodeRegistry {
11
+ loop: { kind: "loop"; body: FlowNode[] };
12
+ }
13
+ }
14
+
15
+ registerNodeKind("loop", {
16
+ build: (api) => (body: Block) => {
17
+ if (typeof body !== "function") throw new Error(`loop() needs a body function`);
18
+ api.out.push({ kind: "loop", body: api.child(body, true) });
19
+ return api.self();
20
+ },
21
+ walk: (node, recurse) => recurse(node.body),
22
+ emit: (node, incoming, _loop, api) => {
23
+ const headId = `Loop_${api.nextGw()}`;
24
+ api.addGateway(headId);
25
+ api.connect(incoming, headId);
26
+ const ctx: LoopCtx = { headId, breaks: [] };
27
+ const headOut = api.newEdge(headId);
28
+ const bodyOut = api.emitList(node.body, [headOut], ctx);
29
+ // Normal fall-through of the body loops back to the head (continue).
30
+ api.connect(bodyOut, headId);
31
+ // The loop exits only via break edges.
32
+ return ctx.breaks;
33
+ },
34
+ });
@@ -0,0 +1,48 @@
1
+ // Built-in flow-node kind: `parallel` — a static parallel fork/join (a pair of
2
+ // BPMN parallel gateways): every block runs concurrently on its own branch, and
3
+ // control continues only once ALL branches reach the AND-join. Contributed
4
+ // through the extension seam (epic #314, S0/#315).
5
+
6
+ import type { FlowNode } from "../types.js";
7
+ import type { Block } from "../declarative.js";
8
+ import { registerNodeKind } from "./registry.js";
9
+
10
+ declare module "../types.js" {
11
+ interface FlowNodeRegistry {
12
+ parallel: { kind: "parallel"; branches: FlowNode[][] };
13
+ }
14
+ }
15
+
16
+ registerNodeKind("parallel", {
17
+ build: (api) => (branches: Block[]) => {
18
+ if (!Array.isArray(branches) || branches.length < 2) {
19
+ throw new Error(`parallel() needs at least two branch blocks`);
20
+ }
21
+ for (const fn of branches) {
22
+ if (typeof fn !== "function") throw new Error(`parallel() branches must all be blocks (b) => {…}`);
23
+ }
24
+ // Each branch runs in its own token scope up to the AND-join, so a
25
+ // `break`/`continue` must not escape into an enclosing loop. Scope branches
26
+ // (loopDepth resets to 0) so cross-boundary break/continue is rejected.
27
+ api.out.push({ kind: "parallel", branches: branches.map((fn) => api.childScoped(fn)) });
28
+ return api.self();
29
+ },
30
+ walk: (node, recurse) => {
31
+ for (const branch of node.branches) recurse(branch);
32
+ },
33
+ emit: (node, incoming, loop, api) => {
34
+ // A diverging parallel gateway forks a token onto every branch; a converging
35
+ // one joins them (AND-join) into a single continuation.
36
+ const splitId = `Gw_${api.nextGw()}`;
37
+ api.addParallelGateway(splitId);
38
+ api.connect(incoming, splitId);
39
+ const joinId = `Gw_${api.nextGw()}`;
40
+ api.addParallelGateway(joinId);
41
+ for (const branch of node.branches) {
42
+ const e = api.newEdge(splitId);
43
+ const branchOut = api.emitList(branch, [e], loop);
44
+ api.connect(branchOut, joinId);
45
+ }
46
+ return [api.newEdge(joinId)];
47
+ },
48
+ });
@@ -0,0 +1,105 @@
1
+ // The builder-extension seam (epic #314, S0/#315).
2
+ //
3
+ // Every flow-node KIND (`run`/`task`/`signal`/`timer`/`switch`/… and any kind a
4
+ // feature slice adds) contributes THREE things from its own module under
5
+ // `src/nodes/`, and NOTHING is edited centrally:
6
+ //
7
+ // 1. a `FlowNode` variant — by declaration-merging its shape into the
8
+ // augmentable `FlowNodeRegistry` interface (see `types.ts`), so the
9
+ // `FlowNode` union grows without editing a central union;
10
+ // 2. a builder method — by declaration-merging its signature into the
11
+ // `FlowBuilder<C>` interface (see `declarative.ts`) and registering a
12
+ // `build` factory here, so `w.<method>(…)` is contributed from the module;
13
+ // 3. `walk` + `emit` handlers — registered here, so the tree walker and the
14
+ // BPMN emitter DISPATCH through this table instead of a central `switch`.
15
+ //
16
+ // A module registers all three with a single `registerNodeKind(kind, {…})` call
17
+ // at import time; the generated barrel `src/nodes/index.ts` imports every kind
18
+ // module for its registration side effect. Adding a kind is therefore: drop one
19
+ // `src/nodes/<kind>.ts` file — no edit to the union, the dispatch, or the barrel.
20
+ //
21
+ // See `src/nodes/README.md` for the exact pattern a slice follows.
22
+
23
+ import type { FlowNode } from "../types.js";
24
+ import type { BuildApi, BuilderMethod, Edge, EmitApi, LoopCtx } from "../declarative.js";
25
+
26
+ /** Recurse the tree walker into a node's nested bodies (see `walkNodes`). */
27
+ export type WalkRecurse = (body: FlowNode[]) => void;
28
+
29
+ /** The three handlers a flow-node kind contributes. `N` is the kind's own
30
+ * `FlowNode` variant (narrowed from the union by the registry key). */
31
+ export interface NodeKindHandlers<N extends FlowNode = FlowNode> {
32
+ /** Factory for the `FlowBuilder` method that appends this kind's node. Given
33
+ * the per-body {@link BuildApi}, returns the method installed on the builder
34
+ * as `w.<builderMethod ?? kind>`. Omit for a kind with no authoring method. */
35
+ build?: (api: BuildApi) => BuilderMethod;
36
+ /** The builder method name, when it differs from the kind (defaults to the
37
+ * kind). */
38
+ builderMethod?: string;
39
+ /** Depth-first recursion into the node's nested bodies. Omit for a leaf. */
40
+ walk?: (node: N, recurse: WalkRecurse) => void;
41
+ /** Emit this node into the BPMN graph, returning the outgoing (dangling)
42
+ * edges its continuation attaches to. */
43
+ emit: (node: N, incoming: Edge[], loop: LoopCtx | null, api: EmitApi) => Edge[];
44
+ }
45
+
46
+ // The dispatcher always looks a handler up by `node.kind` before calling it, so
47
+ // each stored handler only ever receives a node of its own kind. Storing the
48
+ // widened `NodeKindHandlers<FlowNode>` is therefore sound; a kind registers with
49
+ // its own narrowed variant type for authoring ergonomics.
50
+ const kinds = new Map<string, NodeKindHandlers>();
51
+
52
+ /** Register the handlers for one flow-node kind. Called once, at module import
53
+ * time, from `src/nodes/<kind>.ts`. */
54
+ export function registerNodeKind<K extends FlowNode["kind"]>(
55
+ kind: K,
56
+ handlers: NodeKindHandlers<Extract<FlowNode, { kind: K }>>,
57
+ ): void {
58
+ if (kinds.has(kind)) {
59
+ throw new Error(`flow-node kind "${kind}" is already registered`);
60
+ }
61
+ const walk = handlers.walk;
62
+ const emit = handlers.emit;
63
+ kinds.set(kind, {
64
+ builderMethod: handlers.builderMethod,
65
+ build: handlers.build,
66
+ walk: walk ? (node, recurse) => walk(narrow(node, kind), recurse) : undefined,
67
+ emit: (node, incoming, loop, api) => emit(narrow(node, kind), incoming, loop, api),
68
+ });
69
+ }
70
+
71
+ /** Narrow a dispatched node back to a kind's own variant. The discriminant
72
+ * check is the proof — no `as` cast. The dispatcher guarantees `node.kind ===
73
+ * kind`, so the throw is unreachable in practice. */
74
+ function narrow<K extends FlowNode["kind"]>(node: FlowNode, kind: K): Extract<FlowNode, { kind: K }> {
75
+ if (isKind(node, kind)) return node;
76
+ throw new Error(`internal: node of kind "${node.kind}" dispatched to handler for "${kind}"`);
77
+ }
78
+
79
+ function isKind<K extends FlowNode["kind"]>(node: FlowNode, kind: K): node is Extract<FlowNode, { kind: K }> {
80
+ return node.kind === kind;
81
+ }
82
+
83
+ /** The handlers registered for a kind, or `undefined` if none. */
84
+ export function nodeKind(kind: string): NodeKindHandlers | undefined {
85
+ return kinds.get(kind);
86
+ }
87
+
88
+ /** The registered kind, or a thrown error naming the unknown kind — used by the
89
+ * emitter, which cannot proceed without a handler. */
90
+ export function requireNodeKind(kind: string): NodeKindHandlers {
91
+ const h = kinds.get(kind);
92
+ if (!h) {
93
+ throw new Error(
94
+ `no handler registered for flow-node kind "${kind}" — ` +
95
+ `did its module under src/nodes/ import and call registerNodeKind()?`,
96
+ );
97
+ }
98
+ return h;
99
+ }
100
+
101
+ /** Every registered kind + its handlers, in registration order. Used by
102
+ * `makeBuilder` to install each kind's builder method. */
103
+ export function eachNodeKind(): Iterable<[string, NodeKindHandlers]> {
104
+ return kinds.entries();
105
+ }
@@ -0,0 +1,29 @@
1
+ // Built-in flow-node kind: `run` — a durable service task served by a worker
2
+ // THIS program hosts (its handler runs in the in-process `Worker`). Contributed
3
+ // entirely from this module through the extension seam (epic #314, S0/#315):
4
+ // its `FlowNode` variant, its `w.run(...)` builder method, and its walk/emit
5
+ // handlers — with NO edit to the shared union or a central dispatch switch.
6
+
7
+ import type { NodeEnvelopes, StepHandler } from "../types.js";
8
+ import { registerNodeKind } from "./registry.js";
9
+
10
+ declare module "../types.js" {
11
+ interface FlowNodeRegistry {
12
+ run: { kind: "run"; name: string; envelopes?: NodeEnvelopes };
13
+ }
14
+ }
15
+
16
+ registerNodeKind("run", {
17
+ build: (api) => (name: string, handler: StepHandler) => {
18
+ api.claim(name);
19
+ if (typeof handler !== "function") throw new Error(`run("${name}") needs a handler function`);
20
+ api.handlers[name] = handler;
21
+ api.out.push({ kind: "run", name, envelopes: api.contractEnvelopes(name) });
22
+ return api.self();
23
+ },
24
+ emit: (node, incoming, _loop, api) => {
25
+ api.addServiceTask(node);
26
+ api.connect(incoming, node.name);
27
+ return [api.newEdge(node.name)];
28
+ },
29
+ });
@@ -0,0 +1,29 @@
1
+ // Built-in flow-node kind: `signal` — a durable wait for an external/human event
2
+ // correlated on a process variable (a BPMN message intermediate catch event).
3
+ // Contributed from this module through the extension seam (epic #314, S0/#315).
4
+
5
+ import type { Envelope } from "../envelope.js";
6
+ import { assertIdent } from "../xml.js";
7
+ import { registerNodeKind } from "./registry.js";
8
+
9
+ declare module "../types.js" {
10
+ interface FlowNodeRegistry {
11
+ signal: { kind: "signal"; name: string; correlationKey: string; payload?: Envelope };
12
+ }
13
+ }
14
+
15
+ registerNodeKind("signal", {
16
+ build: (api) => (name: string, opts: { correlationKey: string }) => {
17
+ api.claim(name);
18
+ if (!opts || !opts.correlationKey) throw new Error(`signal("${name}") needs { correlationKey }`);
19
+ assertIdent("correlationKey", opts.correlationKey);
20
+ api.out.push({ kind: "signal", name, correlationKey: opts.correlationKey, payload: api.contracts[name]?.in });
21
+ return api.self();
22
+ },
23
+ emit: (node, incoming, _loop, api) => {
24
+ api.addCatchEvent(node);
25
+ api.connect(incoming, node.name);
26
+ api.recordEnvelope(node.payload);
27
+ return [api.newEdge(node.name)];
28
+ },
29
+ });