@fbp/evaluator 1.9.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cycles.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Edge } from '@fbp/types';
1
+ import type { Edge } from '@fbp/spec';
2
2
  /**
3
3
  * Find a dependency cycle among the named nodes, the way pgpm's dependency
4
4
  * resolver does: walk upstream depth-first, keeping the nodes still being
@@ -6,4 +6,5 @@ export declare const constNumberDef: NodeDefinitionWithImpl;
6
6
  export declare const addDef: NodeDefinitionWithImpl;
7
7
  export declare const multiplyDef: NodeDefinitionWithImpl;
8
8
  export declare const subtractDef: NodeDefinitionWithImpl;
9
+ export declare const divideDef: NodeDefinitionWithImpl;
9
10
  export declare const mathDefinitions: NodeDefinitionWithImpl[];
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.mathDefinitions = exports.subtractDef = exports.multiplyDef = exports.addDef = exports.constNumberDef = void 0;
3
+ exports.mathDefinitions = exports.divideDef = exports.subtractDef = exports.multiplyDef = exports.addDef = exports.constNumberDef = void 0;
4
4
  /**
5
5
  * Math node definitions with implementations for testing.
6
6
  */
@@ -61,9 +61,28 @@ exports.subtractDef = {
61
61
  difference: (inputs.a ?? 0) - (inputs.b ?? 0)
62
62
  })
63
63
  };
64
+ exports.divideDef = {
65
+ context: 'js',
66
+ name: 'divide',
67
+ category: 'math',
68
+ icon: 'divide',
69
+ inputs: [
70
+ { name: 'a', type: 'number' },
71
+ { name: 'b', type: 'number' }
72
+ ],
73
+ outputs: [{ name: 'quotient', type: 'number' }],
74
+ description: 'Divides a by b',
75
+ impl: (inputs) => {
76
+ const divisor = inputs.b ?? 1;
77
+ if (divisor === 0)
78
+ throw new Error('math:divide cannot divide by zero');
79
+ return { quotient: (inputs.a ?? 0) / divisor };
80
+ }
81
+ };
64
82
  exports.mathDefinitions = [
65
83
  exports.constNumberDef,
66
84
  exports.addDef,
67
85
  exports.multiplyDef,
68
- exports.subtractDef
86
+ exports.subtractDef,
87
+ exports.divideDef
69
88
  ];
package/definitions/ui.js CHANGED
@@ -24,9 +24,9 @@ function coerceValue(value, valueType) {
24
24
  }
25
25
  // Boundary node definitions for graph inputs/outputs
26
26
  exports.graphInputDef = {
27
- context: 'core',
27
+ context: 'js',
28
28
  name: 'graphInput',
29
- category: 'graph',
29
+ category: 'core',
30
30
  icon: 'arrow-right',
31
31
  inputs: [],
32
32
  outputs: [{ name: 'value', type: 'any' }],
@@ -38,9 +38,9 @@ exports.graphInputDef = {
38
38
  impl: (_inputs, props) => ({ value: coerceValue(props?.value ?? props?.default, props?.valueType ?? 'any') })
39
39
  };
40
40
  exports.graphOutputDef = {
41
- context: 'core',
41
+ context: 'js',
42
42
  name: 'graphOutput',
43
- category: 'graph',
43
+ category: 'core',
44
44
  icon: 'arrow-left',
45
45
  inputs: [{ name: 'value', type: 'any' }],
46
46
  outputs: [],
@@ -51,9 +51,9 @@ exports.graphOutputDef = {
51
51
  impl: (inputs, props) => ({ value: coerceValue(inputs.value, props?.valueType ?? 'any') })
52
52
  };
53
53
  exports.graphPropDef = {
54
- context: 'core',
54
+ context: 'js',
55
55
  name: 'graphProp',
56
- category: 'graph',
56
+ category: 'core',
57
57
  icon: 'settings',
58
58
  inputs: [],
59
59
  outputs: [{ name: 'value', type: 'any' }],
@@ -58,9 +58,28 @@ export const subtractDef = {
58
58
  difference: (inputs.a ?? 0) - (inputs.b ?? 0)
59
59
  })
60
60
  };
61
+ export const divideDef = {
62
+ context: 'js',
63
+ name: 'divide',
64
+ category: 'math',
65
+ icon: 'divide',
66
+ inputs: [
67
+ { name: 'a', type: 'number' },
68
+ { name: 'b', type: 'number' }
69
+ ],
70
+ outputs: [{ name: 'quotient', type: 'number' }],
71
+ description: 'Divides a by b',
72
+ impl: (inputs) => {
73
+ const divisor = inputs.b ?? 1;
74
+ if (divisor === 0)
75
+ throw new Error('math:divide cannot divide by zero');
76
+ return { quotient: (inputs.a ?? 0) / divisor };
77
+ }
78
+ };
61
79
  export const mathDefinitions = [
62
80
  constNumberDef,
63
81
  addDef,
64
82
  multiplyDef,
65
- subtractDef
83
+ subtractDef,
84
+ divideDef
66
85
  ];
@@ -21,9 +21,9 @@ function coerceValue(value, valueType) {
21
21
  }
22
22
  // Boundary node definitions for graph inputs/outputs
23
23
  export const graphInputDef = {
24
- context: 'core',
24
+ context: 'js',
25
25
  name: 'graphInput',
26
- category: 'graph',
26
+ category: 'core',
27
27
  icon: 'arrow-right',
28
28
  inputs: [],
29
29
  outputs: [{ name: 'value', type: 'any' }],
@@ -35,9 +35,9 @@ export const graphInputDef = {
35
35
  impl: (_inputs, props) => ({ value: coerceValue(props?.value ?? props?.default, props?.valueType ?? 'any') })
36
36
  };
37
37
  export const graphOutputDef = {
38
- context: 'core',
38
+ context: 'js',
39
39
  name: 'graphOutput',
40
- category: 'graph',
40
+ category: 'core',
41
41
  icon: 'arrow-left',
42
42
  inputs: [{ name: 'value', type: 'any' }],
43
43
  outputs: [],
@@ -48,9 +48,9 @@ export const graphOutputDef = {
48
48
  impl: (inputs, props) => ({ value: coerceValue(inputs.value, props?.valueType ?? 'any') })
49
49
  };
50
50
  export const graphPropDef = {
51
- context: 'core',
51
+ context: 'js',
52
52
  name: 'graphProp',
53
- category: 'graph',
53
+ category: 'core',
54
54
  icon: 'settings',
55
55
  inputs: [],
56
56
  outputs: [{ name: 'value', type: 'any' }],
package/esm/evaluate.js CHANGED
@@ -1,25 +1,5 @@
1
- import { derivePorts, derivePropDefinitions, isRef, joinPath, parsePath, resolveRef } from '@fbp/spec';
1
+ import { assertTypes, definitionKey, derivePorts, derivePropDefinitions, GRAPH_INPUT, GRAPH_OUTPUT, GRAPH_PROP, hoistDefinitions, isRef, joinPath, parsePath, resolveRef, SUBNET, typeKey } from '@fbp/spec';
2
2
  import { findCycle, formatCycle } from './cycles';
3
- /**
4
- * Build a definition map key from context, category, and name.
5
- */
6
- function defKey(context, category, name) {
7
- return `${context}:${category}:${name}`;
8
- }
9
- /**
10
- * Parse a node type (e.g., 'math:add' or 'const/string') into [category, name].
11
- * Colon is the canonical separator (category:name); slash is checked as fallback
12
- * for legacy graph files. Boundary nodes (no separator) default to ['core', type].
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
3
  /**
24
4
  * Evaluate a graph starting from the specified output node/port.
25
5
  * Uses lazy evaluation - only evaluates nodes that are needed for the output.
@@ -28,9 +8,19 @@ function parseTaskIdentifier(type) {
28
8
  * @param graph - The graph to evaluate
29
9
  * @param options - Evaluation options including definitions, output node/port, and external inputs
30
10
  * @returns Promise resolving to the value at the specified output port
11
+ * @throws before anything runs if a node type is not `category:name`, names no
12
+ * known definition, or two definitions share an identity
31
13
  */
32
14
  export async function evaluate(graph, options) {
33
- const outputs = await openGraph(graph, options, [])(options.outputNode);
15
+ // One definition table: the graph's own (nested ones hoisted into it) beside the host's.
16
+ const root = hoistDefinitions(graph);
17
+ const host = hoistDefinitions({ nodes: [], edges: [], definitions: options.definitions }).definitions;
18
+ assertTypes(root, { definitions: host });
19
+ // A stored definition with no graph only describes a node, so it never replaces one that can run.
20
+ const supplied = new Set(host.map(definitionKey));
21
+ const stored = (root.definitions ?? []).filter(d => !supplied.has(definitionKey(d)));
22
+ const definitions = stored.length ? [...host, ...stored] : host;
23
+ const outputs = await openGraph(root, { ...options, definitions }, [])(options.outputNode);
34
24
  return outputs[options.outputPort];
35
25
  }
36
26
  /**
@@ -69,11 +59,7 @@ export function refEdges(nodes, scopePath = []) {
69
59
  */
70
60
  function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
71
61
  const { inputs = {}, props = {}, absent } = options;
72
- // Definitions stored in the graph (converted subnets) join the ones passed in, for this graph and everything inside it.
73
- // A stored definition with no graph only describes a node, so it never replaces one that can run.
74
- const supplied = new Set(options.definitions.map(d => defKey(d.context, d.category ?? 'core', d.name)));
75
- const stored = (graph.definitions ?? []).filter(d => d.graph || !supplied.has(defKey(d.context, d.category ?? 'core', d.name)));
76
- const definitions = stored.length ? [...options.definitions, ...stored] : options.definitions;
62
+ const { definitions } = options;
77
63
  // Reject cycles up front, as the validator and the SQL gate do: pulling
78
64
  // through a loop would otherwise recurse until the stack overflows.
79
65
  const cycle = findCycle(graph.nodes.map(n => n.name), [...graph.edges, ...refEdges(graph.nodes, scopePath)]);
@@ -87,7 +73,7 @@ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
87
73
  }
88
74
  const defMap = new Map();
89
75
  for (const def of definitions) {
90
- defMap.set(defKey(def.context, def.category ?? 'core', def.name), def);
76
+ defMap.set(definitionKey(def), def);
91
77
  }
92
78
  // Graph-level context used as default for node lookups
93
79
  const graphContext = graph.context || '';
@@ -158,7 +144,7 @@ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
158
144
  }
159
145
  // Handle system nodes (graphInput, graphOutput, graphProp)
160
146
  // System nodes are identified by their type name — reserved, no definition lookup needed
161
- if (node.type === 'graphInput') {
147
+ if (node.type === GRAPH_INPUT) {
162
148
  // Get the port name from the portName property
163
149
  const portNameProp = node.props?.find(p => p.name === 'portName');
164
150
  const inputName = portNameProp?.value || nodeName;
@@ -177,7 +163,7 @@ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
177
163
  cache.set(nodeName, result);
178
164
  return result;
179
165
  }
180
- if (node.type === 'graphProp') {
166
+ if (node.type === GRAPH_PROP) {
181
167
  // Get the prop name from the propName property
182
168
  const propNameProp = node.props?.find(p => p.name === 'propName');
183
169
  const propName = propNameProp?.value || nodeName;
@@ -189,7 +175,7 @@ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
189
175
  cache.set(nodeName, result);
190
176
  return result;
191
177
  }
192
- if (node.type === 'graphOutput') {
178
+ if (node.type === GRAPH_OUTPUT) {
193
179
  // graphOutput is a pass-through: evaluate its upstream 'value' input
194
180
  const portEdges = edgesByDst.get(nodeName);
195
181
  const edges = portEdges?.get('value') ?? [];
@@ -207,12 +193,11 @@ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
207
193
  cache.set(nodeName, result);
208
194
  return result;
209
195
  }
210
- // Handle subnet nodes (type: 'subnet' with inline nodes/edges)
211
- if (node.type === 'subnet' && node.nodes) {
196
+ // Handle subnet nodes (inline nodes/edges)
197
+ if (node.type === SUBNET) {
212
198
  // The interface is derived from the boundary nodes inside the subnet.
213
- const derived = derivePorts(node);
214
- const inputPorts = node.inputs ?? derived.inputs;
215
- const outputPorts = node.outputs ?? derived.outputs;
199
+ const children = node.nodes ?? [];
200
+ const { inputs: inputPorts, outputs: outputPorts } = derivePorts(node);
216
201
  // Collect inputs for the subnet by evaluating upstream nodes
217
202
  const subnetInputs = {};
218
203
  const absentInputs = new Set();
@@ -241,10 +226,10 @@ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
241
226
  }
242
227
  }
243
228
  // One evaluation of the inner graph serves every output port.
244
- const pull = openGraph({ name: `${nodeName}_subnet`, context: node.context || graphContext || undefined, nodes: node.nodes, edges: node.edges ?? [] }, { definitions, inputs: subnetInputs, props: subnetProps, absent: absentInputs }, assetPath, [...scopePath, nodeName], scope);
229
+ const pull = openGraph({ name: `${nodeName}_subnet`, context: node.context || graphContext || undefined, nodes: children, edges: node.edges ?? [] }, { definitions, inputs: subnetInputs, props: subnetProps, absent: absentInputs }, assetPath, [...scopePath, nodeName], scope);
245
230
  const subnetOutputs = {};
246
231
  for (const outputPort of outputPorts) {
247
- const outputBoundaryNode = node.nodes.find(n => n.type === 'graphOutput' && n.props?.find(p => p.name === 'portName')?.value === outputPort.name);
232
+ const outputBoundaryNode = children.find(n => n.type === GRAPH_OUTPUT && n.props?.find(p => p.name === 'portName')?.value === outputPort.name);
248
233
  if (!outputBoundaryNode) {
249
234
  throw new Error(`Output boundary node not found for port: ${outputPort.name}`);
250
235
  }
@@ -257,8 +242,7 @@ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
257
242
  }
258
243
  // Get the definition for this node — resolve context from node override or graph default
259
244
  const nodeContext = node.context || graphContext;
260
- const [nodeCategory, nodeDefName] = parseTaskIdentifier(node.type);
261
- const key = defKey(nodeContext, nodeCategory, nodeDefName);
245
+ const key = typeKey(nodeContext, node.type);
262
246
  const definition = defMap.get(key);
263
247
  if (!definition) {
264
248
  throw new Error(`No definition found for node: ${nodeContext}:${node.type}`);
@@ -361,9 +345,9 @@ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
361
345
  }
362
346
  const assetGraph = definition.graph;
363
347
  // One evaluation of the asset's graph serves every output port.
364
- const pull = openGraph({ name: `${nodeName}_asset`, context: assetGraph.context, nodes: assetGraph.nodes, edges: assetGraph.edges, definitions: assetGraph.definitions }, { definitions, inputs: nodeInputs, props: nodeProps, absent: absentInputs }, [...assetPath, key]);
348
+ const pull = openGraph({ name: `${nodeName}_asset`, context: assetGraph.context || definition.context, nodes: assetGraph.nodes, edges: assetGraph.edges }, { definitions, inputs: nodeInputs, props: nodeProps, absent: absentInputs }, [...assetPath, key]);
365
349
  const assetOutputs = {};
366
- for (const outputBoundaryNode of assetGraph.nodes.filter(n => n.type === 'graphOutput')) {
350
+ for (const outputBoundaryNode of assetGraph.nodes.filter(n => n.type === GRAPH_OUTPUT)) {
367
351
  const portNameProp = outputBoundaryNode.props?.find(p => p.name === 'portName');
368
352
  const result = await pull(outputBoundaryNode.name);
369
353
  if ('value' in result)
package/esm/index.js CHANGED
@@ -3,6 +3,6 @@ export { evaluate } from './evaluate';
3
3
  export { validateGraph } from './validate';
4
4
  // Re-export node definitions for convenience
5
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';
6
+ export { addDef, constNumberDef, divideDef, mathDefinitions, multiplyDef, subtractDef } from './definitions/math';
7
7
  export { graphqlRequestDef, netDefinitions } from './definitions/net';
8
8
  export { buttonDef, formDef, graphInputDef, graphOutputDef, graphPropDef, inputDef, pageDef, textDef, uiDefinitions } from './definitions/ui';
package/esm/validate.js CHANGED
@@ -1,28 +1,6 @@
1
- import { derivePorts, derivePropDefinitions } from '@fbp/spec';
1
+ import { checkTypes, definitionKey, derivePorts, derivePropDefinitions, GRAPH_INPUT, hoistDefinitions, isBoundaryType, isNodeType, SUBNET, typeKey } from '@fbp/spec';
2
2
  import { findCycle, formatCycle } from './cycles';
3
3
  import { refEdges } from './evaluate';
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
4
  /** Build "dst node -> dst port -> has at least one incoming edge". */
27
5
  function connectedPorts(edges) {
28
6
  const map = new Map();
@@ -46,12 +24,17 @@ function nodeHasProp(node, propName) {
46
24
  * Heuristic (intentionally not a proof — see the caveats below) that mirrors the
47
25
  * SQL `validate_function_graph` definition-aware pass:
48
26
  *
49
- * - For every non-boundary node whose definition resolves, each **declared**
27
+ * - Every node type must be `category:name` (`INVALID_TYPE`) and name a
28
+ * structural type or a definition known in the node's effective context
29
+ * (`UNKNOWN_TYPE`); a definition identity may be used once
30
+ * (`DUPLICATE_DEFINITION`, `INVALID_DEFINITION`). The evaluator refuses to
31
+ * run a graph that fails these.
32
+ * - For every non-boundary node, each **declared**
50
33
  * input port that is required (`optional !== true`) and non-`multi` must have
51
34
  * at least one incoming edge, else `MISSING_REQUIRED_INPUT`.
52
35
  * - Each definition prop that is `required` and has no `default` must be
53
36
  * supplied by a node instance prop value, else `MISSING_REQUIRED_PROP`.
54
- * - Inline `subnet` nodes are checked against their declared interface inputs
37
+ * - Inline `core:subnet` nodes are checked against their declared interface inputs
55
38
  * and recursed into.
56
39
  * - Digital-asset definitions (definitions carrying an internal `graph`) are
57
40
  * recursed into.
@@ -61,35 +44,43 @@ function nodeHasProp(node, propName) {
61
44
  * is also a `CYCLE_DETECTED`.
62
45
  *
63
46
  * Deliberately NOT flagged (kept consistent with the evaluator + SQL):
64
- * - `graphInput` / `graphProp` boundaries — supplied at runtime.
47
+ * - `core:graphInput` / `core:graphProp` boundaries — supplied at runtime.
65
48
  * - `multi` inputs — zero-or-more, never required.
66
49
  * - Dynamic/undeclared input ports — the evaluator accepts them, so requiredness
67
50
  * is only enforced for declared ports.
68
- * - Nodes with no resolvable definition — treated as opaque (may be a runtime
69
- * handler), exactly as the SQL validator and evaluator do.
70
51
  *
71
52
  * @returns the list of validation errors; an empty array means the graph is
72
53
  * statically valid. Never throws.
73
54
  */
74
55
  export function validateGraph(graph, options = {}) {
75
56
  const errors = [];
57
+ // Types first: every node type is `category:name` and names a known definition, with one definition per identity.
58
+ for (const issue of checkTypes(graph, { definitions: options.definitions })) {
59
+ errors.push({ ...issue, node: issue.node?.replace(/^\//, '') });
60
+ }
76
61
  const defMap = new Map();
77
62
  const registerDefs = (defs) => {
78
- if (!defs)
79
- return;
80
- for (const def of defs) {
81
- const category = def.category ?? 'core';
82
- defMap.set(defKey(def.context, category, def.name), def);
63
+ for (const def of defs ?? []) {
64
+ // A stored definition with no graph only describes a node; one that can run keeps its place.
65
+ if (def.graph || !defMap.has(definitionKey(def)))
66
+ defMap.set(definitionKey(def), def);
83
67
  }
84
68
  };
85
- registerDefs(options.definitions);
69
+ const tableOf = (definitions) => {
70
+ try {
71
+ return hoistDefinitions({ nodes: [], edges: [], definitions: definitions ?? [] }).definitions ?? [];
72
+ }
73
+ catch {
74
+ return definitions ?? [];
75
+ }
76
+ };
77
+ registerDefs(tableOf(options.definitions));
78
+ registerDefs(tableOf(graph.definitions));
86
79
  const qualify = (pathPrefix, name) => (pathPrefix ? `${pathPrefix}/${name}` : name);
87
80
  // Digital assets currently being visited, outermost first, so an asset that
88
81
  // contains itself is reported instead of recursed into forever.
89
82
  const assetStack = [];
90
83
  const visit = (g, pathPrefix, scope = []) => {
91
- // Definitions can be embedded per-graph (digital assets carry their own).
92
- registerDefs(g.definitions);
93
84
  const graphContext = g.context || '';
94
85
  const connected = connectedPorts(g.edges ?? []);
95
86
  const cycle = findCycle((g.nodes ?? []).map(n => n.name), [...(g.edges ?? []), ...refEdges(g.nodes ?? [], scope)]);
@@ -103,16 +94,17 @@ export function validateGraph(graph, options = {}) {
103
94
  });
104
95
  }
105
96
  for (const node of g.nodes ?? []) {
106
- if (BOUNDARY_TYPES.has(node.type))
97
+ if (isBoundaryType(node.type))
107
98
  continue;
108
99
  const qualifiedName = qualify(pathPrefix, node.name);
109
100
  const nodeConnected = connected.get(node.name) ?? new Set();
110
101
  // Inline subnet: validate against its declared interface, then recurse.
111
- if (node.type === 'subnet' && node.nodes) {
112
- const defaulted = new Set(node.nodes
113
- .filter(n => n.type === 'graphInput' && nodeHasProp(n, 'default'))
102
+ if (node.type === SUBNET) {
103
+ const children = node.nodes ?? [];
104
+ const defaulted = new Set(children
105
+ .filter(n => n.type === GRAPH_INPUT && nodeHasProp(n, 'default'))
114
106
  .map(n => n.props.find(p => p.name === 'portName')?.value ?? n.name));
115
- for (const port of node.inputs ?? derivePorts(node).inputs) {
107
+ for (const port of derivePorts(node).inputs) {
116
108
  if (port.optional === true || port.multi === true || defaulted.has(port.name))
117
109
  continue;
118
110
  if (!nodeConnected.has(port.name)) {
@@ -136,15 +128,15 @@ export function validateGraph(graph, options = {}) {
136
128
  });
137
129
  }
138
130
  }
139
- visit({ name: `${node.name}_subnet`, context: node.context || graphContext || undefined, nodes: node.nodes, edges: node.edges ?? [] }, qualifiedName, [...scope, node.name]);
131
+ visit({ name: `${node.name}_subnet`, context: node.context || graphContext || undefined, nodes: children, edges: node.edges ?? [] }, qualifiedName, [...scope, node.name]);
140
132
  continue;
141
133
  }
142
134
  const nodeContext = node.context || graphContext;
143
- const [category, name] = parseTaskIdentifier(node.type);
144
- const key = defKey(nodeContext, category, name);
135
+ if (!isNodeType(node.type))
136
+ continue;
137
+ const key = typeKey(nodeContext, node.type);
145
138
  const definition = defMap.get(key);
146
- // Unknown definition: opaque node (possibly a runtime handler). Skip —
147
- // matches the SQL validator + evaluator, which do not require a definition.
139
+ // Already reported as UNKNOWN_TYPE.
148
140
  if (!definition)
149
141
  continue;
150
142
  for (const port of definition.inputs ?? []) {
@@ -187,7 +179,7 @@ export function validateGraph(graph, options = {}) {
187
179
  continue;
188
180
  }
189
181
  assetStack.push({ key, node: qualifiedName });
190
- visit(definition.graph, qualifiedName);
182
+ visit({ ...definition.graph, context: definition.graph.context || definition.context }, qualifiedName);
191
183
  assetStack.pop();
192
184
  }
193
185
  }
package/evaluate.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Edge, Graph, Node } from '@fbp/types';
1
+ import type { Edge, Graph, Node } from '@fbp/spec';
2
2
  import type { EvaluateOptions } from './types';
3
3
  /**
4
4
  * Evaluate a graph starting from the specified output node/port.
@@ -8,6 +8,8 @@ import type { EvaluateOptions } from './types';
8
8
  * @param graph - The graph to evaluate
9
9
  * @param options - Evaluation options including definitions, output node/port, and external inputs
10
10
  * @returns Promise resolving to the value at the specified output port
11
+ * @throws before anything runs if a node type is not `category:name`, names no
12
+ * known definition, or two definitions share an identity
11
13
  */
12
14
  export declare function evaluate(graph: Graph, options: EvaluateOptions): Promise<any>;
13
15
  /**
package/evaluate.js CHANGED
@@ -4,26 +4,6 @@ exports.evaluate = evaluate;
4
4
  exports.refEdges = refEdges;
5
5
  const spec_1 = require("@fbp/spec");
6
6
  const cycles_1 = require("./cycles");
7
- /**
8
- * Build a definition map key from context, category, and name.
9
- */
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
- * Colon is the canonical separator (category:name); slash is checked as fallback
16
- * for legacy graph files. Boundary nodes (no separator) default to ['core', type].
17
- */
18
- function parseTaskIdentifier(type) {
19
- const colonIdx = type.indexOf(':');
20
- if (colonIdx !== -1)
21
- return [type.slice(0, colonIdx), type.slice(colonIdx + 1)];
22
- const slashIdx = type.indexOf('/');
23
- if (slashIdx !== -1)
24
- return [type.slice(0, slashIdx), type.slice(slashIdx + 1)];
25
- return ['core', type];
26
- }
27
7
  /**
28
8
  * Evaluate a graph starting from the specified output node/port.
29
9
  * Uses lazy evaluation - only evaluates nodes that are needed for the output.
@@ -32,9 +12,19 @@ function parseTaskIdentifier(type) {
32
12
  * @param graph - The graph to evaluate
33
13
  * @param options - Evaluation options including definitions, output node/port, and external inputs
34
14
  * @returns Promise resolving to the value at the specified output port
15
+ * @throws before anything runs if a node type is not `category:name`, names no
16
+ * known definition, or two definitions share an identity
35
17
  */
36
18
  async function evaluate(graph, options) {
37
- const outputs = await openGraph(graph, options, [])(options.outputNode);
19
+ // One definition table: the graph's own (nested ones hoisted into it) beside the host's.
20
+ const root = (0, spec_1.hoistDefinitions)(graph);
21
+ const host = (0, spec_1.hoistDefinitions)({ nodes: [], edges: [], definitions: options.definitions }).definitions;
22
+ (0, spec_1.assertTypes)(root, { definitions: host });
23
+ // A stored definition with no graph only describes a node, so it never replaces one that can run.
24
+ const supplied = new Set(host.map(spec_1.definitionKey));
25
+ const stored = (root.definitions ?? []).filter(d => !supplied.has((0, spec_1.definitionKey)(d)));
26
+ const definitions = stored.length ? [...host, ...stored] : host;
27
+ const outputs = await openGraph(root, { ...options, definitions }, [])(options.outputNode);
38
28
  return outputs[options.outputPort];
39
29
  }
40
30
  /**
@@ -73,11 +63,7 @@ function refEdges(nodes, scopePath = []) {
73
63
  */
74
64
  function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
75
65
  const { inputs = {}, props = {}, absent } = options;
76
- // Definitions stored in the graph (converted subnets) join the ones passed in, for this graph and everything inside it.
77
- // A stored definition with no graph only describes a node, so it never replaces one that can run.
78
- const supplied = new Set(options.definitions.map(d => defKey(d.context, d.category ?? 'core', d.name)));
79
- const stored = (graph.definitions ?? []).filter(d => d.graph || !supplied.has(defKey(d.context, d.category ?? 'core', d.name)));
80
- const definitions = stored.length ? [...options.definitions, ...stored] : options.definitions;
66
+ const { definitions } = options;
81
67
  // Reject cycles up front, as the validator and the SQL gate do: pulling
82
68
  // through a loop would otherwise recurse until the stack overflows.
83
69
  const cycle = (0, cycles_1.findCycle)(graph.nodes.map(n => n.name), [...graph.edges, ...refEdges(graph.nodes, scopePath)]);
@@ -91,7 +77,7 @@ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
91
77
  }
92
78
  const defMap = new Map();
93
79
  for (const def of definitions) {
94
- defMap.set(defKey(def.context, def.category ?? 'core', def.name), def);
80
+ defMap.set((0, spec_1.definitionKey)(def), def);
95
81
  }
96
82
  // Graph-level context used as default for node lookups
97
83
  const graphContext = graph.context || '';
@@ -162,7 +148,7 @@ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
162
148
  }
163
149
  // Handle system nodes (graphInput, graphOutput, graphProp)
164
150
  // System nodes are identified by their type name — reserved, no definition lookup needed
165
- if (node.type === 'graphInput') {
151
+ if (node.type === spec_1.GRAPH_INPUT) {
166
152
  // Get the port name from the portName property
167
153
  const portNameProp = node.props?.find(p => p.name === 'portName');
168
154
  const inputName = portNameProp?.value || nodeName;
@@ -181,7 +167,7 @@ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
181
167
  cache.set(nodeName, result);
182
168
  return result;
183
169
  }
184
- if (node.type === 'graphProp') {
170
+ if (node.type === spec_1.GRAPH_PROP) {
185
171
  // Get the prop name from the propName property
186
172
  const propNameProp = node.props?.find(p => p.name === 'propName');
187
173
  const propName = propNameProp?.value || nodeName;
@@ -193,7 +179,7 @@ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
193
179
  cache.set(nodeName, result);
194
180
  return result;
195
181
  }
196
- if (node.type === 'graphOutput') {
182
+ if (node.type === spec_1.GRAPH_OUTPUT) {
197
183
  // graphOutput is a pass-through: evaluate its upstream 'value' input
198
184
  const portEdges = edgesByDst.get(nodeName);
199
185
  const edges = portEdges?.get('value') ?? [];
@@ -211,12 +197,11 @@ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
211
197
  cache.set(nodeName, result);
212
198
  return result;
213
199
  }
214
- // Handle subnet nodes (type: 'subnet' with inline nodes/edges)
215
- if (node.type === 'subnet' && node.nodes) {
200
+ // Handle subnet nodes (inline nodes/edges)
201
+ if (node.type === spec_1.SUBNET) {
216
202
  // The interface is derived from the boundary nodes inside the subnet.
217
- const derived = (0, spec_1.derivePorts)(node);
218
- const inputPorts = node.inputs ?? derived.inputs;
219
- const outputPorts = node.outputs ?? derived.outputs;
203
+ const children = node.nodes ?? [];
204
+ const { inputs: inputPorts, outputs: outputPorts } = (0, spec_1.derivePorts)(node);
220
205
  // Collect inputs for the subnet by evaluating upstream nodes
221
206
  const subnetInputs = {};
222
207
  const absentInputs = new Set();
@@ -245,10 +230,10 @@ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
245
230
  }
246
231
  }
247
232
  // One evaluation of the inner graph serves every output port.
248
- const pull = openGraph({ name: `${nodeName}_subnet`, context: node.context || graphContext || undefined, nodes: node.nodes, edges: node.edges ?? [] }, { definitions, inputs: subnetInputs, props: subnetProps, absent: absentInputs }, assetPath, [...scopePath, nodeName], scope);
233
+ const pull = openGraph({ name: `${nodeName}_subnet`, context: node.context || graphContext || undefined, nodes: children, edges: node.edges ?? [] }, { definitions, inputs: subnetInputs, props: subnetProps, absent: absentInputs }, assetPath, [...scopePath, nodeName], scope);
249
234
  const subnetOutputs = {};
250
235
  for (const outputPort of outputPorts) {
251
- const outputBoundaryNode = node.nodes.find(n => n.type === 'graphOutput' && n.props?.find(p => p.name === 'portName')?.value === outputPort.name);
236
+ const outputBoundaryNode = children.find(n => n.type === spec_1.GRAPH_OUTPUT && n.props?.find(p => p.name === 'portName')?.value === outputPort.name);
252
237
  if (!outputBoundaryNode) {
253
238
  throw new Error(`Output boundary node not found for port: ${outputPort.name}`);
254
239
  }
@@ -261,8 +246,7 @@ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
261
246
  }
262
247
  // Get the definition for this node — resolve context from node override or graph default
263
248
  const nodeContext = node.context || graphContext;
264
- const [nodeCategory, nodeDefName] = parseTaskIdentifier(node.type);
265
- const key = defKey(nodeContext, nodeCategory, nodeDefName);
249
+ const key = (0, spec_1.typeKey)(nodeContext, node.type);
266
250
  const definition = defMap.get(key);
267
251
  if (!definition) {
268
252
  throw new Error(`No definition found for node: ${nodeContext}:${node.type}`);
@@ -365,9 +349,9 @@ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
365
349
  }
366
350
  const assetGraph = definition.graph;
367
351
  // One evaluation of the asset's graph serves every output port.
368
- const pull = openGraph({ name: `${nodeName}_asset`, context: assetGraph.context, nodes: assetGraph.nodes, edges: assetGraph.edges, definitions: assetGraph.definitions }, { definitions, inputs: nodeInputs, props: nodeProps, absent: absentInputs }, [...assetPath, key]);
352
+ const pull = openGraph({ name: `${nodeName}_asset`, context: assetGraph.context || definition.context, nodes: assetGraph.nodes, edges: assetGraph.edges }, { definitions, inputs: nodeInputs, props: nodeProps, absent: absentInputs }, [...assetPath, key]);
369
353
  const assetOutputs = {};
370
- for (const outputBoundaryNode of assetGraph.nodes.filter(n => n.type === 'graphOutput')) {
354
+ for (const outputBoundaryNode of assetGraph.nodes.filter(n => n.type === spec_1.GRAPH_OUTPUT)) {
371
355
  const portNameProp = outputBoundaryNode.props?.find(p => p.name === 'portName');
372
356
  const result = await pull(outputBoundaryNode.name);
373
357
  if ('value' in result)
package/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  export { findCycle, formatCycle } from './cycles';
2
2
  export { evaluate } from './evaluate';
3
- export type { EvaluateOptions, NodeDefinitionWithImpl, NodeImplFn, PropDefinitionWithOptions } from './types';
3
+ export type { EvaluateOptions, NodeDefinitionWithImpl, NodeImplFn } from './types';
4
4
  export type { GraphValidationError, GraphValidationErrorCode, ValidateGraphOptions } from './validate';
5
5
  export { validateGraph } from './validate';
6
6
  export { constBooleanDef, constStringDef, coreDefinitions, flowBranchDef, flowCoerceDef, flowFilterDef, flowForEachDef, flowGuardDef, flowMergeDef, flowSwitchDef, jsonMergeDef, jsonObjectDef, jsonSelectDef, jsonSplitDef, stringConcatDef, stringTemplateDef } from './definitions/core';
7
- export { addDef, constNumberDef, mathDefinitions, multiplyDef, subtractDef } from './definitions/math';
7
+ export { addDef, constNumberDef, divideDef, mathDefinitions, multiplyDef, subtractDef } from './definitions/math';
8
8
  export { graphqlRequestDef, netDefinitions } from './definitions/net';
9
9
  export { buttonDef, formDef, graphInputDef, graphOutputDef, graphPropDef, inputDef, pageDef, textDef, uiDefinitions } from './definitions/ui';
package/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
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 = exports.formatCycle = exports.findCycle = 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.divideDef = 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 = exports.formatCycle = exports.findCycle = void 0;
4
4
  var cycles_1 = require("./cycles");
5
5
  Object.defineProperty(exports, "findCycle", { enumerable: true, get: function () { return cycles_1.findCycle; } });
6
6
  Object.defineProperty(exports, "formatCycle", { enumerable: true, get: function () { return cycles_1.formatCycle; } });
@@ -29,6 +29,7 @@ Object.defineProperty(exports, "stringTemplateDef", { enumerable: true, get: fun
29
29
  var math_1 = require("./definitions/math");
30
30
  Object.defineProperty(exports, "addDef", { enumerable: true, get: function () { return math_1.addDef; } });
31
31
  Object.defineProperty(exports, "constNumberDef", { enumerable: true, get: function () { return math_1.constNumberDef; } });
32
+ Object.defineProperty(exports, "divideDef", { enumerable: true, get: function () { return math_1.divideDef; } });
32
33
  Object.defineProperty(exports, "mathDefinitions", { enumerable: true, get: function () { return math_1.mathDefinitions; } });
33
34
  Object.defineProperty(exports, "multiplyDef", { enumerable: true, get: function () { return math_1.multiplyDef; } });
34
35
  Object.defineProperty(exports, "subtractDef", { enumerable: true, get: function () { return math_1.subtractDef; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fbp/evaluator",
3
- "version": "1.9.0",
3
+ "version": "2.0.0",
4
4
  "description": "FBP graph evaluator — node definitions, graph evaluation and validation",
5
5
  "author": "Constructive <developers@constructive.io>",
6
6
  "license": "MIT",
@@ -11,16 +11,8 @@
11
11
  "access": "public",
12
12
  "directory": "dist"
13
13
  },
14
- "scripts": {
15
- "prepack": "npm run build",
16
- "build": "makage build",
17
- "build:dev": "makage build --dev",
18
- "clean": "makage clean",
19
- "test": "jest --config jest.config.js"
20
- },
21
14
  "dependencies": {
22
- "@fbp/spec": "1.7.0",
23
- "@fbp/types": "1.6.0"
15
+ "@fbp/spec": "2.0.0"
24
16
  },
25
17
  "devDependencies": {
26
18
  "@types/jest": "^30.0.0",
@@ -37,5 +29,10 @@
37
29
  "bugs": {
38
30
  "url": "https://github.com/constructive-io/fbp/issues"
39
31
  },
40
- "gitHead": "a201bb20191c3f918a62d7a491ea4500a72e4454"
41
- }
32
+ "scripts": {
33
+ "build": "makage build",
34
+ "build:dev": "makage build --dev",
35
+ "clean": "makage clean",
36
+ "test": "jest --config jest.config.js"
37
+ }
38
+ }
package/types.d.ts CHANGED
@@ -1,24 +1,16 @@
1
- import type { NodeDefinition, PropDefinition } from '@fbp/types';
1
+ import type { NodeDefinition } from '@fbp/spec';
2
2
  /**
3
3
  * A function that implements a node's computation.
4
4
  * Takes inputs (keyed by port name) and props, returns outputs (keyed by port name).
5
5
  * Can be sync or async - the evaluator will await the result.
6
6
  */
7
7
  export type NodeImplFn = (inputs: Record<string, any>, props: Record<string, any>) => Record<string, any> | Promise<Record<string, any>>;
8
- /**
9
- * Extended PropDefinition with runtime-only options for enum/select types.
10
- * The options field is not part of the JSON schema but is used by the UI.
11
- */
12
- export interface PropDefinitionWithOptions extends PropDefinition {
13
- options?: string[];
14
- }
15
8
  /**
16
9
  * A NodeDefinition extended with an optional implementation function.
17
10
  * The impl function is not part of the JSON schema (not serializable),
18
11
  * but is used at runtime for evaluation.
19
12
  */
20
- export interface NodeDefinitionWithImpl extends Omit<NodeDefinition, 'props'> {
21
- props?: PropDefinitionWithOptions[];
13
+ export interface NodeDefinitionWithImpl extends NodeDefinition {
22
14
  impl?: NodeImplFn;
23
15
  }
24
16
  /**
package/validate.d.ts CHANGED
@@ -1,15 +1,17 @@
1
- import type { Graph } from '@fbp/types';
1
+ import type { Graph } from '@fbp/spec';
2
2
  import type { NodeDefinitionWithImpl } from './types';
3
3
  /**
4
4
  * Codes emitted by {@link validateGraph}. Kept in lock-step with the SQL
5
5
  * `validate_function_graph` definition-aware checks so the editor pre-flight and
6
6
  * the database gate agree on what "invalid" means.
7
7
  */
8
- export type GraphValidationErrorCode = 'MISSING_REQUIRED_INPUT' | 'MISSING_REQUIRED_PROP' | 'CYCLE_DETECTED';
8
+ export type GraphValidationErrorCode = 'MISSING_REQUIRED_INPUT' | 'MISSING_REQUIRED_PROP' | 'CYCLE_DETECTED' | 'INVALID_TYPE' | 'UNKNOWN_TYPE' | 'DUPLICATE_DEFINITION' | 'INVALID_DEFINITION';
9
9
  export interface GraphValidationError {
10
10
  code: GraphValidationErrorCode;
11
- /** The offending node's name (qualified with the subnet/asset path). */
12
- node: string;
11
+ /** The offending node's name (qualified with the subnet/asset path). Absent for a problem with a definition itself. */
12
+ node?: string;
13
+ /** For a type or definition problem: the definition concerned, as `context:category:name`. */
14
+ definition?: string;
13
15
  /** For MISSING_REQUIRED_INPUT: the unconnected required input port. */
14
16
  port?: string;
15
17
  /** For MISSING_REQUIRED_PROP: the unsupplied required prop. */
@@ -24,9 +26,8 @@ export interface GraphValidationError {
24
26
  }
25
27
  export interface ValidateGraphOptions {
26
28
  /**
27
- * Node definitions available for resolution. These are merged with any
28
- * definitions embedded on the graph (`graph.definitions`) and on nested
29
- * digital-asset definitions.
29
+ * The host's node definitions. They join the graph's own root `definitions`
30
+ * table; a node type found in neither is an error.
30
31
  */
31
32
  definitions?: NodeDefinitionWithImpl[];
32
33
  }
@@ -36,12 +37,17 @@ export interface ValidateGraphOptions {
36
37
  * Heuristic (intentionally not a proof — see the caveats below) that mirrors the
37
38
  * SQL `validate_function_graph` definition-aware pass:
38
39
  *
39
- * - For every non-boundary node whose definition resolves, each **declared**
40
+ * - Every node type must be `category:name` (`INVALID_TYPE`) and name a
41
+ * structural type or a definition known in the node's effective context
42
+ * (`UNKNOWN_TYPE`); a definition identity may be used once
43
+ * (`DUPLICATE_DEFINITION`, `INVALID_DEFINITION`). The evaluator refuses to
44
+ * run a graph that fails these.
45
+ * - For every non-boundary node, each **declared**
40
46
  * input port that is required (`optional !== true`) and non-`multi` must have
41
47
  * at least one incoming edge, else `MISSING_REQUIRED_INPUT`.
42
48
  * - Each definition prop that is `required` and has no `default` must be
43
49
  * supplied by a node instance prop value, else `MISSING_REQUIRED_PROP`.
44
- * - Inline `subnet` nodes are checked against their declared interface inputs
50
+ * - Inline `core:subnet` nodes are checked against their declared interface inputs
45
51
  * and recursed into.
46
52
  * - Digital-asset definitions (definitions carrying an internal `graph`) are
47
53
  * recursed into.
@@ -51,12 +57,10 @@ export interface ValidateGraphOptions {
51
57
  * is also a `CYCLE_DETECTED`.
52
58
  *
53
59
  * Deliberately NOT flagged (kept consistent with the evaluator + SQL):
54
- * - `graphInput` / `graphProp` boundaries — supplied at runtime.
60
+ * - `core:graphInput` / `core:graphProp` boundaries — supplied at runtime.
55
61
  * - `multi` inputs — zero-or-more, never required.
56
62
  * - Dynamic/undeclared input ports — the evaluator accepts them, so requiredness
57
63
  * is only enforced for declared ports.
58
- * - Nodes with no resolvable definition — treated as opaque (may be a runtime
59
- * handler), exactly as the SQL validator and evaluator do.
60
64
  *
61
65
  * @returns the list of validation errors; an empty array means the graph is
62
66
  * statically valid. Never throws.
package/validate.js CHANGED
@@ -4,28 +4,6 @@ exports.validateGraph = validateGraph;
4
4
  const spec_1 = require("@fbp/spec");
5
5
  const cycles_1 = require("./cycles");
6
6
  const evaluate_1 = require("./evaluate");
7
- /**
8
- * Boundary node types. These are satisfied by the runtime (graphInput/graphProp
9
- * receive values from the execution payload; graphOutput is a pass-through), so
10
- * they are never checked for required inputs/props.
11
- */
12
- const BOUNDARY_TYPES = new Set(['graphInput', 'graphOutput', 'graphProp']);
13
- function defKey(context, category, name) {
14
- return `${context}:${category}:${name}`;
15
- }
16
- /**
17
- * Parse a node type (e.g., 'math:add' or 'const/string') into [category, name].
18
- * Mirrors the evaluator's resolution so pre-flight and evaluation stay aligned.
19
- */
20
- function parseTaskIdentifier(type) {
21
- const colonIdx = type.indexOf(':');
22
- if (colonIdx !== -1)
23
- return [type.slice(0, colonIdx), type.slice(colonIdx + 1)];
24
- const slashIdx = type.indexOf('/');
25
- if (slashIdx !== -1)
26
- return [type.slice(0, slashIdx), type.slice(slashIdx + 1)];
27
- return ['core', type];
28
- }
29
7
  /** Build "dst node -> dst port -> has at least one incoming edge". */
30
8
  function connectedPorts(edges) {
31
9
  const map = new Map();
@@ -49,12 +27,17 @@ function nodeHasProp(node, propName) {
49
27
  * Heuristic (intentionally not a proof — see the caveats below) that mirrors the
50
28
  * SQL `validate_function_graph` definition-aware pass:
51
29
  *
52
- * - For every non-boundary node whose definition resolves, each **declared**
30
+ * - Every node type must be `category:name` (`INVALID_TYPE`) and name a
31
+ * structural type or a definition known in the node's effective context
32
+ * (`UNKNOWN_TYPE`); a definition identity may be used once
33
+ * (`DUPLICATE_DEFINITION`, `INVALID_DEFINITION`). The evaluator refuses to
34
+ * run a graph that fails these.
35
+ * - For every non-boundary node, each **declared**
53
36
  * input port that is required (`optional !== true`) and non-`multi` must have
54
37
  * at least one incoming edge, else `MISSING_REQUIRED_INPUT`.
55
38
  * - Each definition prop that is `required` and has no `default` must be
56
39
  * supplied by a node instance prop value, else `MISSING_REQUIRED_PROP`.
57
- * - Inline `subnet` nodes are checked against their declared interface inputs
40
+ * - Inline `core:subnet` nodes are checked against their declared interface inputs
58
41
  * and recursed into.
59
42
  * - Digital-asset definitions (definitions carrying an internal `graph`) are
60
43
  * recursed into.
@@ -64,35 +47,43 @@ function nodeHasProp(node, propName) {
64
47
  * is also a `CYCLE_DETECTED`.
65
48
  *
66
49
  * Deliberately NOT flagged (kept consistent with the evaluator + SQL):
67
- * - `graphInput` / `graphProp` boundaries — supplied at runtime.
50
+ * - `core:graphInput` / `core:graphProp` boundaries — supplied at runtime.
68
51
  * - `multi` inputs — zero-or-more, never required.
69
52
  * - Dynamic/undeclared input ports — the evaluator accepts them, so requiredness
70
53
  * is only enforced for declared ports.
71
- * - Nodes with no resolvable definition — treated as opaque (may be a runtime
72
- * handler), exactly as the SQL validator and evaluator do.
73
54
  *
74
55
  * @returns the list of validation errors; an empty array means the graph is
75
56
  * statically valid. Never throws.
76
57
  */
77
58
  function validateGraph(graph, options = {}) {
78
59
  const errors = [];
60
+ // Types first: every node type is `category:name` and names a known definition, with one definition per identity.
61
+ for (const issue of (0, spec_1.checkTypes)(graph, { definitions: options.definitions })) {
62
+ errors.push({ ...issue, node: issue.node?.replace(/^\//, '') });
63
+ }
79
64
  const defMap = new Map();
80
65
  const registerDefs = (defs) => {
81
- if (!defs)
82
- return;
83
- for (const def of defs) {
84
- const category = def.category ?? 'core';
85
- defMap.set(defKey(def.context, category, def.name), def);
66
+ for (const def of defs ?? []) {
67
+ // A stored definition with no graph only describes a node; one that can run keeps its place.
68
+ if (def.graph || !defMap.has((0, spec_1.definitionKey)(def)))
69
+ defMap.set((0, spec_1.definitionKey)(def), def);
86
70
  }
87
71
  };
88
- registerDefs(options.definitions);
72
+ const tableOf = (definitions) => {
73
+ try {
74
+ return (0, spec_1.hoistDefinitions)({ nodes: [], edges: [], definitions: definitions ?? [] }).definitions ?? [];
75
+ }
76
+ catch {
77
+ return definitions ?? [];
78
+ }
79
+ };
80
+ registerDefs(tableOf(options.definitions));
81
+ registerDefs(tableOf(graph.definitions));
89
82
  const qualify = (pathPrefix, name) => (pathPrefix ? `${pathPrefix}/${name}` : name);
90
83
  // Digital assets currently being visited, outermost first, so an asset that
91
84
  // contains itself is reported instead of recursed into forever.
92
85
  const assetStack = [];
93
86
  const visit = (g, pathPrefix, scope = []) => {
94
- // Definitions can be embedded per-graph (digital assets carry their own).
95
- registerDefs(g.definitions);
96
87
  const graphContext = g.context || '';
97
88
  const connected = connectedPorts(g.edges ?? []);
98
89
  const cycle = (0, cycles_1.findCycle)((g.nodes ?? []).map(n => n.name), [...(g.edges ?? []), ...(0, evaluate_1.refEdges)(g.nodes ?? [], scope)]);
@@ -106,16 +97,17 @@ function validateGraph(graph, options = {}) {
106
97
  });
107
98
  }
108
99
  for (const node of g.nodes ?? []) {
109
- if (BOUNDARY_TYPES.has(node.type))
100
+ if ((0, spec_1.isBoundaryType)(node.type))
110
101
  continue;
111
102
  const qualifiedName = qualify(pathPrefix, node.name);
112
103
  const nodeConnected = connected.get(node.name) ?? new Set();
113
104
  // Inline subnet: validate against its declared interface, then recurse.
114
- if (node.type === 'subnet' && node.nodes) {
115
- const defaulted = new Set(node.nodes
116
- .filter(n => n.type === 'graphInput' && nodeHasProp(n, 'default'))
105
+ if (node.type === spec_1.SUBNET) {
106
+ const children = node.nodes ?? [];
107
+ const defaulted = new Set(children
108
+ .filter(n => n.type === spec_1.GRAPH_INPUT && nodeHasProp(n, 'default'))
117
109
  .map(n => n.props.find(p => p.name === 'portName')?.value ?? n.name));
118
- for (const port of node.inputs ?? (0, spec_1.derivePorts)(node).inputs) {
110
+ for (const port of (0, spec_1.derivePorts)(node).inputs) {
119
111
  if (port.optional === true || port.multi === true || defaulted.has(port.name))
120
112
  continue;
121
113
  if (!nodeConnected.has(port.name)) {
@@ -139,15 +131,15 @@ function validateGraph(graph, options = {}) {
139
131
  });
140
132
  }
141
133
  }
142
- visit({ name: `${node.name}_subnet`, context: node.context || graphContext || undefined, nodes: node.nodes, edges: node.edges ?? [] }, qualifiedName, [...scope, node.name]);
134
+ visit({ name: `${node.name}_subnet`, context: node.context || graphContext || undefined, nodes: children, edges: node.edges ?? [] }, qualifiedName, [...scope, node.name]);
143
135
  continue;
144
136
  }
145
137
  const nodeContext = node.context || graphContext;
146
- const [category, name] = parseTaskIdentifier(node.type);
147
- const key = defKey(nodeContext, category, name);
138
+ if (!(0, spec_1.isNodeType)(node.type))
139
+ continue;
140
+ const key = (0, spec_1.typeKey)(nodeContext, node.type);
148
141
  const definition = defMap.get(key);
149
- // Unknown definition: opaque node (possibly a runtime handler). Skip —
150
- // matches the SQL validator + evaluator, which do not require a definition.
142
+ // Already reported as UNKNOWN_TYPE.
151
143
  if (!definition)
152
144
  continue;
153
145
  for (const port of definition.inputs ?? []) {
@@ -190,7 +182,7 @@ function validateGraph(graph, options = {}) {
190
182
  continue;
191
183
  }
192
184
  assetStack.push({ key, node: qualifiedName });
193
- visit(definition.graph, qualifiedName);
185
+ visit({ ...definition.graph, context: definition.graph.context || definition.context }, qualifiedName);
194
186
  assetStack.pop();
195
187
  }
196
188
  }