@fbp/evaluator 1.9.0 → 2.1.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/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();
@@ -40,8 +18,8 @@ function connectedPorts(edges) {
40
18
  return map;
41
19
  }
42
20
  function nodeHasProp(node, propName) {
43
- const p = node.props?.find(pr => pr.name === propName);
44
- return p !== undefined && p.value !== undefined && p.value !== null;
21
+ const value = (0, spec_1.plainValue)(node.props?.find(pr => pr.name === propName)?.value);
22
+ return value !== undefined && value !== null;
45
23
  }
46
24
  /**
47
25
  * Statically validate a flow graph before publish/execution.
@@ -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,38 +47,49 @@ 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
- const cycle = (0, cycles_1.findCycle)((g.nodes ?? []).map(n => n.name), [...(g.edges ?? []), ...(0, evaluate_1.refEdges)(g.nodes ?? [], scope)]);
89
+ const cycle = (0, cycles_1.findCycle)((g.nodes ?? []).map(n => n.name), [
90
+ ...(g.edges ?? []),
91
+ ...(0, evaluate_1.refEdges)(g.nodes ?? [], scope, (0, evaluate_1.wiringOf)(g.edges ?? [], graphContext, defMap))
92
+ ]);
99
93
  if (cycle) {
100
94
  const path = cycle.map(name => qualify(pathPrefix, name));
101
95
  errors.push({
@@ -106,24 +100,25 @@ function validateGraph(graph, options = {}) {
106
100
  });
107
101
  }
108
102
  for (const node of g.nodes ?? []) {
109
- if (BOUNDARY_TYPES.has(node.type))
103
+ if ((0, spec_1.isBoundaryType)(node.type))
110
104
  continue;
111
105
  const qualifiedName = qualify(pathPrefix, node.name);
112
106
  const nodeConnected = connected.get(node.name) ?? new Set();
113
107
  // 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'))
117
- .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) {
108
+ if (node.type === spec_1.SUBNET) {
109
+ const children = node.nodes ?? [];
110
+ const defaulted = new Set(children
111
+ .filter(n => n.type === spec_1.GRAPH_INPUT && nodeHasProp(n, 'default'))
112
+ .map(spec_1.boundaryName));
113
+ for (const port of (0, spec_1.derivePorts)(node).inputs) {
119
114
  if (port.optional === true || port.multi === true || defaulted.has(port.name))
120
115
  continue;
121
- if (!nodeConnected.has(port.name)) {
116
+ if (!nodeConnected.has(port.name) && (0, spec_1.plainValue)((0, spec_1.unwiredInput)(node, port.name)) == null) {
122
117
  errors.push({
123
118
  code: 'MISSING_REQUIRED_INPUT',
124
119
  node: qualifiedName,
125
120
  port: port.name,
126
- message: `Required input "${port.name}" of subnet "${qualifiedName}" is not connected`,
121
+ message: `Required input "${port.name}" of subnet "${qualifiedName}" is not connected or set`,
127
122
  });
128
123
  }
129
124
  }
@@ -139,26 +134,26 @@ function validateGraph(graph, options = {}) {
139
134
  });
140
135
  }
141
136
  }
142
- visit({ name: `${node.name}_subnet`, context: node.context || graphContext || undefined, nodes: node.nodes, edges: node.edges ?? [] }, qualifiedName, [...scope, node.name]);
137
+ visit({ name: `${node.name}_subnet`, context: node.context || graphContext || undefined, nodes: children, edges: node.edges ?? [] }, qualifiedName, [...scope, node.name]);
143
138
  continue;
144
139
  }
145
140
  const nodeContext = node.context || graphContext;
146
- const [category, name] = parseTaskIdentifier(node.type);
147
- const key = defKey(nodeContext, category, name);
141
+ if (!(0, spec_1.isNodeType)(node.type))
142
+ continue;
143
+ const key = (0, spec_1.typeKey)(nodeContext, node.type);
148
144
  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.
145
+ // Already reported as UNKNOWN_TYPE.
151
146
  if (!definition)
152
147
  continue;
153
148
  for (const port of definition.inputs ?? []) {
154
149
  if (port.optional === true || port.multi === true)
155
150
  continue;
156
- if (!nodeConnected.has(port.name)) {
151
+ if (!nodeConnected.has(port.name) && (0, spec_1.plainValue)((0, spec_1.unwiredInput)(node, port.name, definition.props)) == null) {
157
152
  errors.push({
158
153
  code: 'MISSING_REQUIRED_INPUT',
159
154
  node: qualifiedName,
160
155
  port: port.name,
161
- message: `Required input "${port.name}" of node "${qualifiedName}" (${node.type}) is not connected`,
156
+ message: `Required input "${port.name}" of node "${qualifiedName}" (${node.type}) is not connected or set`,
162
157
  });
163
158
  }
164
159
  }
@@ -190,7 +185,7 @@ function validateGraph(graph, options = {}) {
190
185
  continue;
191
186
  }
192
187
  assetStack.push({ key, node: qualifiedName });
193
- visit(definition.graph, qualifiedName);
188
+ visit({ ...definition.graph, context: definition.graph.context || definition.context }, qualifiedName);
194
189
  assetStack.pop();
195
190
  }
196
191
  }