@fbp/evaluator 1.1.0 → 1.3.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.
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Boundary node types. These are satisfied by the runtime (graphInput/graphProp
3
+ * receive values from the execution payload; graphOutput is a pass-through), so
4
+ * they are never checked for required inputs/props.
5
+ */
6
+ const BOUNDARY_TYPES = new Set(['graphInput', 'graphOutput', 'graphProp']);
7
+ function defKey(context, category, name) {
8
+ return `${context}:${category}:${name}`;
9
+ }
10
+ /**
11
+ * Parse a node type (e.g., 'math:add' or 'const/string') into [category, name].
12
+ * Mirrors the evaluator's resolution so pre-flight and evaluation stay aligned.
13
+ */
14
+ function parseTaskIdentifier(type) {
15
+ const colonIdx = type.indexOf(':');
16
+ if (colonIdx !== -1)
17
+ return [type.slice(0, colonIdx), type.slice(colonIdx + 1)];
18
+ const slashIdx = type.indexOf('/');
19
+ if (slashIdx !== -1)
20
+ return [type.slice(0, slashIdx), type.slice(slashIdx + 1)];
21
+ return ['core', type];
22
+ }
23
+ /** Build "dst node -> dst port -> has at least one incoming edge". */
24
+ function connectedPorts(edges) {
25
+ const map = new Map();
26
+ for (const edge of edges) {
27
+ let ports = map.get(edge.dst.node);
28
+ if (!ports) {
29
+ ports = new Set();
30
+ map.set(edge.dst.node, ports);
31
+ }
32
+ ports.add(edge.dst.port);
33
+ }
34
+ return map;
35
+ }
36
+ function nodeHasProp(node, propName) {
37
+ const p = node.props?.find(pr => pr.name === propName);
38
+ return p !== undefined && p.value !== undefined && p.value !== null;
39
+ }
40
+ /**
41
+ * Statically validate a flow graph before publish/execution.
42
+ *
43
+ * Heuristic (intentionally not a proof — see the caveats below) that mirrors the
44
+ * SQL `validate_function_graph` definition-aware pass:
45
+ *
46
+ * - For every non-boundary node whose definition resolves, each **declared**
47
+ * input port that is required (`optional !== true`) and non-`multi` must have
48
+ * at least one incoming edge, else `MISSING_REQUIRED_INPUT`.
49
+ * - Each definition prop that is `required` and has no `default` must be
50
+ * supplied by a node instance prop value, else `MISSING_REQUIRED_PROP`.
51
+ * - Inline `subnet` nodes are checked against their declared interface inputs
52
+ * and recursed into.
53
+ * - Digital-asset definitions (definitions carrying an internal `graph`) are
54
+ * recursed into.
55
+ *
56
+ * Deliberately NOT flagged (kept consistent with the evaluator + SQL):
57
+ * - `graphInput` / `graphProp` boundaries — supplied at runtime.
58
+ * - `multi` inputs — zero-or-more, never required.
59
+ * - Dynamic/undeclared input ports — the evaluator accepts them, so requiredness
60
+ * is only enforced for declared ports.
61
+ * - Nodes with no resolvable definition — treated as opaque (may be a runtime
62
+ * handler), exactly as the SQL validator and evaluator do.
63
+ *
64
+ * @returns the list of validation errors; an empty array means the graph is
65
+ * statically valid. Never throws.
66
+ */
67
+ export function validateGraph(graph, options = {}) {
68
+ const errors = [];
69
+ const defMap = new Map();
70
+ const registerDefs = (defs) => {
71
+ if (!defs)
72
+ return;
73
+ for (const def of defs) {
74
+ const category = def.category ?? 'core';
75
+ defMap.set(defKey(def.context, category, def.name), def);
76
+ }
77
+ };
78
+ registerDefs(options.definitions);
79
+ const visit = (g, pathPrefix) => {
80
+ // Definitions can be embedded per-graph (digital assets carry their own).
81
+ registerDefs(g.definitions);
82
+ const graphContext = g.context || '';
83
+ const connected = connectedPorts(g.edges ?? []);
84
+ for (const node of g.nodes ?? []) {
85
+ if (BOUNDARY_TYPES.has(node.type))
86
+ continue;
87
+ const qualifiedName = pathPrefix ? `${pathPrefix}/${node.name}` : node.name;
88
+ const nodeConnected = connected.get(node.name) ?? new Set();
89
+ // Inline subnet: validate against its declared interface, then recurse.
90
+ if (node.type === 'subnet' && node.nodes) {
91
+ for (const port of node.inputs ?? []) {
92
+ if (port.optional === true || port.multi === true)
93
+ continue;
94
+ if (!nodeConnected.has(port.name)) {
95
+ errors.push({
96
+ code: 'MISSING_REQUIRED_INPUT',
97
+ node: qualifiedName,
98
+ port: port.name,
99
+ message: `Required input "${port.name}" of subnet "${qualifiedName}" is not connected`,
100
+ });
101
+ }
102
+ }
103
+ visit({ name: `${node.name}_subnet`, context: graphContext || undefined, nodes: node.nodes, edges: node.edges ?? [] }, qualifiedName);
104
+ continue;
105
+ }
106
+ const nodeContext = node.context || graphContext;
107
+ const [category, name] = parseTaskIdentifier(node.type);
108
+ const definition = defMap.get(defKey(nodeContext, category, name));
109
+ // Unknown definition: opaque node (possibly a runtime handler). Skip —
110
+ // matches the SQL validator + evaluator, which do not require a definition.
111
+ if (!definition)
112
+ continue;
113
+ for (const port of definition.inputs ?? []) {
114
+ if (port.optional === true || port.multi === true)
115
+ continue;
116
+ if (!nodeConnected.has(port.name)) {
117
+ errors.push({
118
+ code: 'MISSING_REQUIRED_INPUT',
119
+ node: qualifiedName,
120
+ port: port.name,
121
+ message: `Required input "${port.name}" of node "${qualifiedName}" (${node.type}) is not connected`,
122
+ });
123
+ }
124
+ }
125
+ for (const prop of definition.props ?? []) {
126
+ if (prop.required !== true)
127
+ continue;
128
+ if (prop.default !== undefined)
129
+ continue;
130
+ if (!nodeHasProp(node, prop.name)) {
131
+ errors.push({
132
+ code: 'MISSING_REQUIRED_PROP',
133
+ node: qualifiedName,
134
+ prop: prop.name,
135
+ message: `Required prop "${prop.name}" of node "${qualifiedName}" (${node.type}) is not set`,
136
+ });
137
+ }
138
+ }
139
+ // Digital asset: recurse into the definition's internal graph.
140
+ if (definition.graph) {
141
+ visit(definition.graph, qualifiedName);
142
+ }
143
+ }
144
+ };
145
+ visit(graph, '');
146
+ return errors;
147
+ }
package/evaluate.js CHANGED
@@ -2,10 +2,24 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.evaluate = evaluate;
4
4
  /**
5
- * Build a definition map key from context and name.
5
+ * Build a definition map key from context, category, and name.
6
6
  */
7
- function defKey(context, name) {
8
- return `${context}:${name}`;
7
+ function defKey(context, category, name) {
8
+ return `${context}:${category}:${name}`;
9
+ }
10
+ /**
11
+ * Parse a node type (e.g., 'math:add' or 'const/string') into [category, name].
12
+ * Colon is the canonical separator (category:name); slash is checked as fallback
13
+ * for legacy graph files. Boundary nodes (no separator) default to ['core', type].
14
+ */
15
+ function parseTaskIdentifier(type) {
16
+ const colonIdx = type.indexOf(':');
17
+ if (colonIdx !== -1)
18
+ return [type.slice(0, colonIdx), type.slice(colonIdx + 1)];
19
+ const slashIdx = type.indexOf('/');
20
+ if (slashIdx !== -1)
21
+ return [type.slice(0, slashIdx), type.slice(slashIdx + 1)];
22
+ return ['core', type];
9
23
  }
10
24
  /**
11
25
  * Evaluate a graph starting from the specified output node/port.
@@ -25,7 +39,7 @@ async function evaluate(graph, options) {
25
39
  }
26
40
  const defMap = new Map();
27
41
  for (const def of definitions) {
28
- defMap.set(defKey(def.context, def.name), def);
42
+ defMap.set(defKey(def.context, def.category, def.name), def);
29
43
  }
30
44
  // Graph-level context used as default for node lookups
31
45
  const graphContext = graph.context || '';
@@ -146,29 +160,73 @@ async function evaluate(graph, options) {
146
160
  }
147
161
  // Get the definition for this node — resolve context from node override or graph default
148
162
  const nodeContext = node.context || graphContext;
149
- const definition = defMap.get(defKey(nodeContext, node.type));
163
+ const [nodeCategory, nodeDefName] = parseTaskIdentifier(node.type);
164
+ const definition = defMap.get(defKey(nodeContext, nodeCategory, nodeDefName));
150
165
  if (!definition) {
151
166
  throw new Error(`No definition found for node: ${nodeContext}:${node.type}`);
152
167
  }
153
168
  // Collect inputs by evaluating upstream nodes
154
169
  const nodeInputs = {};
155
170
  const portEdges = edgesByDst.get(nodeName);
171
+ /**
172
+ * A branch emits only the port it took, so an edge out of the arm it did not
173
+ * take is an edge whose source port is *absent* — not one carrying
174
+ * `undefined`, which a node may legitimately produce. A node fed by such an
175
+ * edge on a required input is not runnable, and the preview says so the way
176
+ * the runtime does: the node produces no outputs at all, which leaves the
177
+ * arm dark for everything downstream of it and lets a `flow:merge` further
178
+ * on run on whichever arm did arrive. Optional inputs absorb the absence
179
+ * instead, which is what makes reconvergence expressible.
180
+ */
181
+ const notTaken = (outputs, port) => !(port in outputs);
182
+ const skipped = {};
183
+ const declaredPortNames = new Set();
156
184
  if (definition.inputs) {
157
185
  for (const inputPort of definition.inputs) {
186
+ declaredPortNames.add(inputPort.name);
158
187
  const edges = portEdges?.get(inputPort.name) ?? [];
159
188
  if (inputPort.multi) {
160
- const values = await Promise.all(edges.map(async (edge) => {
189
+ const arrived = await Promise.all(edges.map(async (edge) => {
161
190
  const upstreamOutputs = await evaluateNode(edge.src.node);
162
- return upstreamOutputs[edge.src.port];
191
+ return notTaken(upstreamOutputs, edge.src.port)
192
+ ? undefined
193
+ : { value: upstreamOutputs[edge.src.port] };
163
194
  }));
164
- nodeInputs[inputPort.name] = values;
195
+ const values = arrived.filter((slot) => slot !== undefined);
196
+ if (edges.length > 0 && values.length === 0 && !inputPort.optional) {
197
+ cache.set(nodeName, skipped);
198
+ return skipped;
199
+ }
200
+ nodeInputs[inputPort.name] = values.map((slot) => slot.value);
165
201
  }
166
202
  else {
167
203
  if (edges.length > 0) {
168
204
  const edge = edges[0];
169
205
  const upstreamOutputs = await evaluateNode(edge.src.node);
170
- nodeInputs[inputPort.name] = upstreamOutputs[edge.src.port];
206
+ if (notTaken(upstreamOutputs, edge.src.port)) {
207
+ if (!inputPort.optional) {
208
+ cache.set(nodeName, skipped);
209
+ return skipped;
210
+ }
211
+ }
212
+ else {
213
+ nodeInputs[inputPort.name] = upstreamOutputs[edge.src.port];
214
+ }
215
+ }
216
+ }
217
+ }
218
+ }
219
+ // Dynamic inputs: collect any edges targeting ports not declared in definition.inputs
220
+ if (portEdges) {
221
+ for (const [portName, edges] of portEdges) {
222
+ if (!declaredPortNames.has(portName) && edges.length > 0) {
223
+ const edge = edges[0];
224
+ const upstreamOutputs = await evaluateNode(edge.src.node);
225
+ if (notTaken(upstreamOutputs, edge.src.port)) {
226
+ cache.set(nodeName, skipped);
227
+ return skipped;
171
228
  }
229
+ nodeInputs[portName] = upstreamOutputs[edge.src.port];
172
230
  }
173
231
  }
174
232
  }
package/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  export { evaluate } from './evaluate';
2
- export type { NodeImplFn, NodeDefinitionWithImpl, EvaluateOptions, PropDefinitionWithOptions } from './types';
3
- export { mathDefinitions, constNumberDef, addDef, multiplyDef } from './definitions/math';
4
- export { uiDefinitions, pageDef, formDef, inputDef, buttonDef, textDef, graphInputDef, graphOutputDef, graphPropDef } from './definitions/ui';
5
- export { coreDefinitions, jsonSelectDef, jsonObjectDef, flowGuardDef, stringTemplateDef, stringConcatDef } from './definitions/core';
6
- export { netDefinitions, graphqlRequestDef } from './definitions/net';
2
+ export type { EvaluateOptions, NodeDefinitionWithImpl, NodeImplFn, PropDefinitionWithOptions } from './types';
3
+ export type { GraphValidationError, GraphValidationErrorCode, ValidateGraphOptions } from './validate';
4
+ export { validateGraph } from './validate';
5
+ export { constBooleanDef, constStringDef, coreDefinitions, flowBranchDef, flowCoerceDef, flowFilterDef, flowForEachDef, flowGuardDef, flowMergeDef, flowSwitchDef, jsonMergeDef, jsonObjectDef, jsonSelectDef, jsonSplitDef, stringConcatDef, stringTemplateDef } from './definitions/core';
6
+ export { addDef, constNumberDef, mathDefinitions, multiplyDef, subtractDef } from './definitions/math';
7
+ export { graphqlRequestDef, netDefinitions } from './definitions/net';
8
+ export { buttonDef, formDef, graphInputDef, graphOutputDef, graphPropDef, inputDef, pageDef, textDef, uiDefinitions } from './definitions/ui';
package/index.js CHANGED
@@ -1,31 +1,44 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.graphqlRequestDef = exports.netDefinitions = exports.stringConcatDef = exports.stringTemplateDef = exports.flowGuardDef = exports.jsonObjectDef = exports.jsonSelectDef = exports.coreDefinitions = exports.graphPropDef = exports.graphOutputDef = exports.graphInputDef = exports.textDef = exports.buttonDef = exports.inputDef = exports.formDef = exports.pageDef = exports.uiDefinitions = exports.multiplyDef = exports.addDef = exports.constNumberDef = exports.mathDefinitions = exports.evaluate = void 0;
3
+ exports.uiDefinitions = exports.textDef = exports.pageDef = exports.inputDef = exports.graphPropDef = exports.graphOutputDef = exports.graphInputDef = exports.formDef = exports.buttonDef = exports.netDefinitions = exports.graphqlRequestDef = exports.subtractDef = exports.multiplyDef = exports.mathDefinitions = exports.constNumberDef = exports.addDef = exports.stringTemplateDef = exports.stringConcatDef = exports.jsonSplitDef = exports.jsonSelectDef = exports.jsonObjectDef = exports.jsonMergeDef = exports.flowSwitchDef = exports.flowMergeDef = exports.flowGuardDef = exports.flowForEachDef = exports.flowFilterDef = exports.flowCoerceDef = exports.flowBranchDef = exports.coreDefinitions = exports.constStringDef = exports.constBooleanDef = exports.validateGraph = exports.evaluate = void 0;
4
4
  var evaluate_1 = require("./evaluate");
5
5
  Object.defineProperty(exports, "evaluate", { enumerable: true, get: function () { return evaluate_1.evaluate; } });
6
+ var validate_1 = require("./validate");
7
+ Object.defineProperty(exports, "validateGraph", { enumerable: true, get: function () { return validate_1.validateGraph; } });
6
8
  // Re-export node definitions for convenience
9
+ var core_1 = require("./definitions/core");
10
+ Object.defineProperty(exports, "constBooleanDef", { enumerable: true, get: function () { return core_1.constBooleanDef; } });
11
+ Object.defineProperty(exports, "constStringDef", { enumerable: true, get: function () { return core_1.constStringDef; } });
12
+ Object.defineProperty(exports, "coreDefinitions", { enumerable: true, get: function () { return core_1.coreDefinitions; } });
13
+ Object.defineProperty(exports, "flowBranchDef", { enumerable: true, get: function () { return core_1.flowBranchDef; } });
14
+ Object.defineProperty(exports, "flowCoerceDef", { enumerable: true, get: function () { return core_1.flowCoerceDef; } });
15
+ Object.defineProperty(exports, "flowFilterDef", { enumerable: true, get: function () { return core_1.flowFilterDef; } });
16
+ Object.defineProperty(exports, "flowForEachDef", { enumerable: true, get: function () { return core_1.flowForEachDef; } });
17
+ Object.defineProperty(exports, "flowGuardDef", { enumerable: true, get: function () { return core_1.flowGuardDef; } });
18
+ Object.defineProperty(exports, "flowMergeDef", { enumerable: true, get: function () { return core_1.flowMergeDef; } });
19
+ Object.defineProperty(exports, "flowSwitchDef", { enumerable: true, get: function () { return core_1.flowSwitchDef; } });
20
+ Object.defineProperty(exports, "jsonMergeDef", { enumerable: true, get: function () { return core_1.jsonMergeDef; } });
21
+ Object.defineProperty(exports, "jsonObjectDef", { enumerable: true, get: function () { return core_1.jsonObjectDef; } });
22
+ Object.defineProperty(exports, "jsonSelectDef", { enumerable: true, get: function () { return core_1.jsonSelectDef; } });
23
+ Object.defineProperty(exports, "jsonSplitDef", { enumerable: true, get: function () { return core_1.jsonSplitDef; } });
24
+ Object.defineProperty(exports, "stringConcatDef", { enumerable: true, get: function () { return core_1.stringConcatDef; } });
25
+ Object.defineProperty(exports, "stringTemplateDef", { enumerable: true, get: function () { return core_1.stringTemplateDef; } });
7
26
  var math_1 = require("./definitions/math");
8
- Object.defineProperty(exports, "mathDefinitions", { enumerable: true, get: function () { return math_1.mathDefinitions; } });
9
- Object.defineProperty(exports, "constNumberDef", { enumerable: true, get: function () { return math_1.constNumberDef; } });
10
27
  Object.defineProperty(exports, "addDef", { enumerable: true, get: function () { return math_1.addDef; } });
28
+ Object.defineProperty(exports, "constNumberDef", { enumerable: true, get: function () { return math_1.constNumberDef; } });
29
+ Object.defineProperty(exports, "mathDefinitions", { enumerable: true, get: function () { return math_1.mathDefinitions; } });
11
30
  Object.defineProperty(exports, "multiplyDef", { enumerable: true, get: function () { return math_1.multiplyDef; } });
31
+ Object.defineProperty(exports, "subtractDef", { enumerable: true, get: function () { return math_1.subtractDef; } });
32
+ var net_1 = require("./definitions/net");
33
+ Object.defineProperty(exports, "graphqlRequestDef", { enumerable: true, get: function () { return net_1.graphqlRequestDef; } });
34
+ Object.defineProperty(exports, "netDefinitions", { enumerable: true, get: function () { return net_1.netDefinitions; } });
12
35
  var ui_1 = require("./definitions/ui");
13
- Object.defineProperty(exports, "uiDefinitions", { enumerable: true, get: function () { return ui_1.uiDefinitions; } });
14
- Object.defineProperty(exports, "pageDef", { enumerable: true, get: function () { return ui_1.pageDef; } });
15
- Object.defineProperty(exports, "formDef", { enumerable: true, get: function () { return ui_1.formDef; } });
16
- Object.defineProperty(exports, "inputDef", { enumerable: true, get: function () { return ui_1.inputDef; } });
17
36
  Object.defineProperty(exports, "buttonDef", { enumerable: true, get: function () { return ui_1.buttonDef; } });
18
- Object.defineProperty(exports, "textDef", { enumerable: true, get: function () { return ui_1.textDef; } });
37
+ Object.defineProperty(exports, "formDef", { enumerable: true, get: function () { return ui_1.formDef; } });
19
38
  Object.defineProperty(exports, "graphInputDef", { enumerable: true, get: function () { return ui_1.graphInputDef; } });
20
39
  Object.defineProperty(exports, "graphOutputDef", { enumerable: true, get: function () { return ui_1.graphOutputDef; } });
21
40
  Object.defineProperty(exports, "graphPropDef", { enumerable: true, get: function () { return ui_1.graphPropDef; } });
22
- var core_1 = require("./definitions/core");
23
- Object.defineProperty(exports, "coreDefinitions", { enumerable: true, get: function () { return core_1.coreDefinitions; } });
24
- Object.defineProperty(exports, "jsonSelectDef", { enumerable: true, get: function () { return core_1.jsonSelectDef; } });
25
- Object.defineProperty(exports, "jsonObjectDef", { enumerable: true, get: function () { return core_1.jsonObjectDef; } });
26
- Object.defineProperty(exports, "flowGuardDef", { enumerable: true, get: function () { return core_1.flowGuardDef; } });
27
- Object.defineProperty(exports, "stringTemplateDef", { enumerable: true, get: function () { return core_1.stringTemplateDef; } });
28
- Object.defineProperty(exports, "stringConcatDef", { enumerable: true, get: function () { return core_1.stringConcatDef; } });
29
- var net_1 = require("./definitions/net");
30
- Object.defineProperty(exports, "netDefinitions", { enumerable: true, get: function () { return net_1.netDefinitions; } });
31
- Object.defineProperty(exports, "graphqlRequestDef", { enumerable: true, get: function () { return net_1.graphqlRequestDef; } });
41
+ Object.defineProperty(exports, "inputDef", { enumerable: true, get: function () { return ui_1.inputDef; } });
42
+ Object.defineProperty(exports, "pageDef", { enumerable: true, get: function () { return ui_1.pageDef; } });
43
+ Object.defineProperty(exports, "textDef", { enumerable: true, get: function () { return ui_1.textDef; } });
44
+ Object.defineProperty(exports, "uiDefinitions", { enumerable: true, get: function () { return ui_1.uiDefinitions; } });
package/package.json CHANGED
@@ -1,44 +1,38 @@
1
1
  {
2
2
  "name": "@fbp/evaluator",
3
- "version": "1.1.0",
4
- "author": "Dan Lynch <pyramation@gmail.com>",
5
- "description": "Lazy graph evaluator for Flow-Based Programming",
3
+ "version": "1.3.0",
4
+ "description": "FBP graph evaluator — node definitions, graph evaluation and validation",
5
+ "author": "Constructive <developers@constructive.io>",
6
+ "license": "MIT",
6
7
  "main": "index.js",
7
8
  "module": "esm/index.js",
8
9
  "types": "index.d.ts",
9
- "homepage": "https://github.com/flow-based-programming/spec",
10
- "license": "MIT",
11
10
  "publishConfig": {
12
11
  "access": "public",
13
12
  "directory": "dist"
14
13
  },
15
- "repository": {
16
- "type": "git",
17
- "url": "https://github.com/flow-based-programming/spec"
18
- },
19
- "bugs": {
20
- "url": "https://github.com/flow-based-programming/spec/issues"
21
- },
22
14
  "scripts": {
23
- "clean": "makage clean",
24
- "prepack": "npm run build",
25
15
  "build": "makage build",
26
16
  "build:dev": "makage build --dev",
27
- "lint": "eslint . --fix",
28
- "test": "jest",
29
- "test:watch": "jest --watch"
17
+ "clean": "makage clean",
18
+ "test": "jest --config jest.config.js"
30
19
  },
31
- "keywords": [
32
- "fbp",
33
- "evaluator",
34
- "flow-based-programming",
35
- "lazy-evaluation"
36
- ],
37
20
  "dependencies": {
38
- "@fbp/types": "1.1.0"
21
+ "@fbp/types": "workspace:*"
39
22
  },
40
23
  "devDependencies": {
41
- "makage": "0.1.9"
24
+ "@types/jest": "^30.0.0",
25
+ "jest": "^30.2.0",
26
+ "makage": "^0.1.12",
27
+ "ts-jest": "^29.4.0",
28
+ "typescript": "^5.7.0"
29
+ },
30
+ "homepage": "https://github.com/constructive-io/fbp",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "https://github.com/constructive-io/fbp"
42
34
  },
43
- "gitHead": "6f0ef58d9a54f35a2a5849e84234a67fa8d8a9b5"
35
+ "bugs": {
36
+ "url": "https://github.com/constructive-io/fbp/issues"
37
+ }
44
38
  }
package/validate.d.ts ADDED
@@ -0,0 +1,54 @@
1
+ import type { Graph } from '@fbp/types';
2
+ import type { NodeDefinitionWithImpl } from './types';
3
+ /**
4
+ * Codes emitted by {@link validateGraph}. Kept in lock-step with the SQL
5
+ * `validate_function_graph` definition-aware checks so the editor pre-flight and
6
+ * the database gate agree on what "invalid" means.
7
+ */
8
+ export type GraphValidationErrorCode = 'MISSING_REQUIRED_INPUT' | 'MISSING_REQUIRED_PROP';
9
+ export interface GraphValidationError {
10
+ code: GraphValidationErrorCode;
11
+ /** The offending node's name (qualified with the subnet/asset path). */
12
+ node: string;
13
+ /** For MISSING_REQUIRED_INPUT: the unconnected required input port. */
14
+ port?: string;
15
+ /** For MISSING_REQUIRED_PROP: the unsupplied required prop. */
16
+ prop?: string;
17
+ message: string;
18
+ }
19
+ export interface ValidateGraphOptions {
20
+ /**
21
+ * Node definitions available for resolution. These are merged with any
22
+ * definitions embedded on the graph (`graph.definitions`) and on nested
23
+ * digital-asset definitions.
24
+ */
25
+ definitions?: NodeDefinitionWithImpl[];
26
+ }
27
+ /**
28
+ * Statically validate a flow graph before publish/execution.
29
+ *
30
+ * Heuristic (intentionally not a proof — see the caveats below) that mirrors the
31
+ * SQL `validate_function_graph` definition-aware pass:
32
+ *
33
+ * - For every non-boundary node whose definition resolves, each **declared**
34
+ * input port that is required (`optional !== true`) and non-`multi` must have
35
+ * at least one incoming edge, else `MISSING_REQUIRED_INPUT`.
36
+ * - Each definition prop that is `required` and has no `default` must be
37
+ * supplied by a node instance prop value, else `MISSING_REQUIRED_PROP`.
38
+ * - Inline `subnet` nodes are checked against their declared interface inputs
39
+ * and recursed into.
40
+ * - Digital-asset definitions (definitions carrying an internal `graph`) are
41
+ * recursed into.
42
+ *
43
+ * Deliberately NOT flagged (kept consistent with the evaluator + SQL):
44
+ * - `graphInput` / `graphProp` boundaries — supplied at runtime.
45
+ * - `multi` inputs — zero-or-more, never required.
46
+ * - Dynamic/undeclared input ports — the evaluator accepts them, so requiredness
47
+ * is only enforced for declared ports.
48
+ * - Nodes with no resolvable definition — treated as opaque (may be a runtime
49
+ * handler), exactly as the SQL validator and evaluator do.
50
+ *
51
+ * @returns the list of validation errors; an empty array means the graph is
52
+ * statically valid. Never throws.
53
+ */
54
+ export declare function validateGraph(graph: Graph, options?: ValidateGraphOptions): GraphValidationError[];
package/validate.js ADDED
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateGraph = validateGraph;
4
+ /**
5
+ * Boundary node types. These are satisfied by the runtime (graphInput/graphProp
6
+ * receive values from the execution payload; graphOutput is a pass-through), so
7
+ * they are never checked for required inputs/props.
8
+ */
9
+ const BOUNDARY_TYPES = new Set(['graphInput', 'graphOutput', 'graphProp']);
10
+ function defKey(context, category, name) {
11
+ return `${context}:${category}:${name}`;
12
+ }
13
+ /**
14
+ * Parse a node type (e.g., 'math:add' or 'const/string') into [category, name].
15
+ * Mirrors the evaluator's resolution so pre-flight and evaluation stay aligned.
16
+ */
17
+ function parseTaskIdentifier(type) {
18
+ const colonIdx = type.indexOf(':');
19
+ if (colonIdx !== -1)
20
+ return [type.slice(0, colonIdx), type.slice(colonIdx + 1)];
21
+ const slashIdx = type.indexOf('/');
22
+ if (slashIdx !== -1)
23
+ return [type.slice(0, slashIdx), type.slice(slashIdx + 1)];
24
+ return ['core', type];
25
+ }
26
+ /** Build "dst node -> dst port -> has at least one incoming edge". */
27
+ function connectedPorts(edges) {
28
+ const map = new Map();
29
+ for (const edge of edges) {
30
+ let ports = map.get(edge.dst.node);
31
+ if (!ports) {
32
+ ports = new Set();
33
+ map.set(edge.dst.node, ports);
34
+ }
35
+ ports.add(edge.dst.port);
36
+ }
37
+ return map;
38
+ }
39
+ function nodeHasProp(node, propName) {
40
+ const p = node.props?.find(pr => pr.name === propName);
41
+ return p !== undefined && p.value !== undefined && p.value !== null;
42
+ }
43
+ /**
44
+ * Statically validate a flow graph before publish/execution.
45
+ *
46
+ * Heuristic (intentionally not a proof — see the caveats below) that mirrors the
47
+ * SQL `validate_function_graph` definition-aware pass:
48
+ *
49
+ * - For every non-boundary node whose definition resolves, each **declared**
50
+ * input port that is required (`optional !== true`) and non-`multi` must have
51
+ * at least one incoming edge, else `MISSING_REQUIRED_INPUT`.
52
+ * - Each definition prop that is `required` and has no `default` must be
53
+ * supplied by a node instance prop value, else `MISSING_REQUIRED_PROP`.
54
+ * - Inline `subnet` nodes are checked against their declared interface inputs
55
+ * and recursed into.
56
+ * - Digital-asset definitions (definitions carrying an internal `graph`) are
57
+ * recursed into.
58
+ *
59
+ * Deliberately NOT flagged (kept consistent with the evaluator + SQL):
60
+ * - `graphInput` / `graphProp` boundaries — supplied at runtime.
61
+ * - `multi` inputs — zero-or-more, never required.
62
+ * - Dynamic/undeclared input ports — the evaluator accepts them, so requiredness
63
+ * is only enforced for declared ports.
64
+ * - Nodes with no resolvable definition — treated as opaque (may be a runtime
65
+ * handler), exactly as the SQL validator and evaluator do.
66
+ *
67
+ * @returns the list of validation errors; an empty array means the graph is
68
+ * statically valid. Never throws.
69
+ */
70
+ function validateGraph(graph, options = {}) {
71
+ const errors = [];
72
+ const defMap = new Map();
73
+ const registerDefs = (defs) => {
74
+ if (!defs)
75
+ return;
76
+ for (const def of defs) {
77
+ const category = def.category ?? 'core';
78
+ defMap.set(defKey(def.context, category, def.name), def);
79
+ }
80
+ };
81
+ registerDefs(options.definitions);
82
+ const visit = (g, pathPrefix) => {
83
+ // Definitions can be embedded per-graph (digital assets carry their own).
84
+ registerDefs(g.definitions);
85
+ const graphContext = g.context || '';
86
+ const connected = connectedPorts(g.edges ?? []);
87
+ for (const node of g.nodes ?? []) {
88
+ if (BOUNDARY_TYPES.has(node.type))
89
+ continue;
90
+ const qualifiedName = pathPrefix ? `${pathPrefix}/${node.name}` : node.name;
91
+ const nodeConnected = connected.get(node.name) ?? new Set();
92
+ // Inline subnet: validate against its declared interface, then recurse.
93
+ if (node.type === 'subnet' && node.nodes) {
94
+ for (const port of node.inputs ?? []) {
95
+ if (port.optional === true || port.multi === true)
96
+ continue;
97
+ if (!nodeConnected.has(port.name)) {
98
+ errors.push({
99
+ code: 'MISSING_REQUIRED_INPUT',
100
+ node: qualifiedName,
101
+ port: port.name,
102
+ message: `Required input "${port.name}" of subnet "${qualifiedName}" is not connected`,
103
+ });
104
+ }
105
+ }
106
+ visit({ name: `${node.name}_subnet`, context: graphContext || undefined, nodes: node.nodes, edges: node.edges ?? [] }, qualifiedName);
107
+ continue;
108
+ }
109
+ const nodeContext = node.context || graphContext;
110
+ const [category, name] = parseTaskIdentifier(node.type);
111
+ const definition = defMap.get(defKey(nodeContext, category, name));
112
+ // Unknown definition: opaque node (possibly a runtime handler). Skip —
113
+ // matches the SQL validator + evaluator, which do not require a definition.
114
+ if (!definition)
115
+ continue;
116
+ for (const port of definition.inputs ?? []) {
117
+ if (port.optional === true || port.multi === true)
118
+ continue;
119
+ if (!nodeConnected.has(port.name)) {
120
+ errors.push({
121
+ code: 'MISSING_REQUIRED_INPUT',
122
+ node: qualifiedName,
123
+ port: port.name,
124
+ message: `Required input "${port.name}" of node "${qualifiedName}" (${node.type}) is not connected`,
125
+ });
126
+ }
127
+ }
128
+ for (const prop of definition.props ?? []) {
129
+ if (prop.required !== true)
130
+ continue;
131
+ if (prop.default !== undefined)
132
+ continue;
133
+ if (!nodeHasProp(node, prop.name)) {
134
+ errors.push({
135
+ code: 'MISSING_REQUIRED_PROP',
136
+ node: qualifiedName,
137
+ prop: prop.name,
138
+ message: `Required prop "${prop.name}" of node "${qualifiedName}" (${node.type}) is not set`,
139
+ });
140
+ }
141
+ }
142
+ // Digital asset: recurse into the definition's internal graph.
143
+ if (definition.graph) {
144
+ visit(definition.graph, qualifiedName);
145
+ }
146
+ }
147
+ };
148
+ visit(graph, '');
149
+ return errors;
150
+ }