@fbp/evaluator 1.6.0 → 1.8.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/esm/evaluate.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { derivePorts, derivePropDefinitions, isRef, joinPath, parsePath, resolveRef } from '@fbp/spec';
1
2
  import { findCycle, formatCycle } from './cycles';
2
3
  /**
3
4
  * Build a definition map key from context, category, and name.
@@ -29,18 +30,53 @@ function parseTaskIdentifier(type) {
29
30
  * @returns Promise resolving to the value at the specified output port
30
31
  */
31
32
  export async function evaluate(graph, options) {
32
- return evaluateGraph(graph, options, []);
33
+ const outputs = await openGraph(graph, options, [])(options.outputNode);
34
+ return outputs[options.outputPort];
35
+ }
36
+ /**
37
+ * A `{ ref }` to a sibling node's value is a dependency, like an edge.
38
+ * `scopePath` is where `nodes` live, so absolute references are recognised too.
39
+ */
40
+ export function refEdges(nodes, scopePath = []) {
41
+ const names = new Set(nodes.map(n => n.name));
42
+ const scope = joinPath(scopePath);
43
+ const edges = [];
44
+ for (const node of nodes) {
45
+ for (const prop of node.props ?? []) {
46
+ if (!isRef(prop.value))
47
+ continue;
48
+ let target;
49
+ try {
50
+ target = resolveRef(scope, prop.value.ref);
51
+ }
52
+ catch {
53
+ continue;
54
+ }
55
+ const segments = parsePath(target.path);
56
+ const sibling = segments[segments.length - 1];
57
+ if (target.prop === undefined && sibling !== undefined && names.has(sibling) &&
58
+ joinPath(segments.slice(0, -1)) === scope) {
59
+ edges.push({ src: { node: sibling, port: 'value' }, dst: { node: node.name, port: prop.name } });
60
+ }
61
+ }
62
+ }
63
+ return edges;
33
64
  }
34
65
  /**
35
66
  * @param assetPath - definition keys of the digital assets being evaluated,
36
67
  * outermost first, so an asset that contains itself throws instead of
37
68
  * recursing forever.
38
69
  */
39
- async function evaluateGraph(graph, options, assetPath) {
40
- const { definitions, outputNode, outputPort, inputs = {}, props = {} } = options;
70
+ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
71
+ 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;
41
77
  // Reject cycles up front, as the validator and the SQL gate do: pulling
42
78
  // through a loop would otherwise recurse until the stack overflows.
43
- const cycle = findCycle(graph.nodes.map(n => n.name), graph.edges);
79
+ const cycle = findCycle(graph.nodes.map(n => n.name), [...graph.edges, ...refEdges(graph.nodes, scopePath)]);
44
80
  if (cycle) {
45
81
  throw new Error(`Graph "${graph.name}" contains a cycle: ${formatCycle(cycle)}`);
46
82
  }
@@ -51,7 +87,7 @@ async function evaluateGraph(graph, options, assetPath) {
51
87
  }
52
88
  const defMap = new Map();
53
89
  for (const def of definitions) {
54
- defMap.set(defKey(def.context, def.category, def.name), def);
90
+ defMap.set(defKey(def.context, def.category ?? 'core', def.name), def);
55
91
  }
56
92
  // Graph-level context used as default for node lookups
57
93
  const graphContext = graph.context || '';
@@ -71,6 +107,42 @@ async function evaluateGraph(graph, options, assetPath) {
71
107
  }
72
108
  // Cache for evaluated node outputs to avoid re-evaluation
73
109
  const cache = new Map();
110
+ /**
111
+ * Resolve a prop value: a `{ ref }` takes the value of the node it points at
112
+ * (its `value` output, or the named prop for a '.prop' reference). The target
113
+ * is in this scope or one that encloses it.
114
+ */
115
+ async function resolve(value, holder, chain = []) {
116
+ if (!isRef(value))
117
+ return value;
118
+ const target = resolveRef(joinPath(scopePath), value.ref);
119
+ const segments = parsePath(target.path);
120
+ const name = segments[segments.length - 1];
121
+ const owner = segments.slice(0, -1).join('/');
122
+ let found = scope;
123
+ while (found && found.path.join('/') !== owner)
124
+ found = found.parent;
125
+ if (!found || name === undefined || !found.getNode(name)) {
126
+ throw new Error(`Reference "${value.ref}" on node "${holder}" does not point at a node in its scope or an enclosing one`);
127
+ }
128
+ if (target.prop !== undefined) {
129
+ const key = `${target.path}.${target.prop}`;
130
+ if (chain.includes(key)) {
131
+ throw new Error(`Reference "${value.ref}" on node "${holder}" refers back to itself`);
132
+ }
133
+ const prop = found.getNode(name).props?.find(p => p.name === target.prop);
134
+ return found.resolve(prop?.value, name, [...chain, key]);
135
+ }
136
+ const outputs = await found.evaluateNode(name);
137
+ return 'value' in outputs ? outputs.value : Object.values(outputs)[0];
138
+ }
139
+ const scope = {
140
+ path: scopePath,
141
+ parent: parentScope,
142
+ getNode: name => nodeMap.get(name),
143
+ evaluateNode: name => evaluateNode(name),
144
+ resolve
145
+ };
74
146
  /**
75
147
  * Recursively evaluate a node and return all its outputs.
76
148
  * Fully async to support async node implementations.
@@ -90,6 +162,11 @@ async function evaluateGraph(graph, options, assetPath) {
90
162
  // Get the port name from the portName property
91
163
  const portNameProp = node.props?.find(p => p.name === 'portName');
92
164
  const inputName = portNameProp?.value || nodeName;
165
+ // A wired input whose arm was not taken stays dark, default or not, as it would in the flat graph.
166
+ if (absent?.has(inputName)) {
167
+ cache.set(nodeName, {});
168
+ return {};
169
+ }
93
170
  // Check external inputs first, then fall back to node's default prop
94
171
  let value = inputs[inputName];
95
172
  if (value === undefined) {
@@ -104,7 +181,10 @@ async function evaluateGraph(graph, options, assetPath) {
104
181
  // Get the prop name from the propName property
105
182
  const propNameProp = node.props?.find(p => p.name === 'propName');
106
183
  const propName = propNameProp?.value || nodeName;
107
- const value = props[propName];
184
+ let value = props[propName];
185
+ if (value === undefined) {
186
+ value = node.props?.find(p => p.name === 'default')?.value;
187
+ }
108
188
  const result = { value };
109
189
  cache.set(nodeName, result);
110
190
  return result;
@@ -117,6 +197,10 @@ async function evaluateGraph(graph, options, assetPath) {
117
197
  if (edges.length > 0) {
118
198
  const edge = edges[0];
119
199
  const upstreamOutputs = await evaluateNode(edge.src.node);
200
+ if (!(edge.src.port in upstreamOutputs)) {
201
+ cache.set(nodeName, {});
202
+ return {};
203
+ }
120
204
  value = upstreamOutputs[edge.src.port];
121
205
  }
122
206
  const result = { value };
@@ -124,48 +208,49 @@ async function evaluateGraph(graph, options, assetPath) {
124
208
  return result;
125
209
  }
126
210
  // Handle subnet nodes (type: 'subnet' with inline nodes/edges)
127
- if (node.type === 'subnet' && node.nodes && node.edges) {
211
+ if (node.type === 'subnet' && node.nodes) {
212
+ // 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;
128
216
  // Collect inputs for the subnet by evaluating upstream nodes
129
217
  const subnetInputs = {};
218
+ const absentInputs = new Set();
130
219
  const subnetPortEdges = edgesByDst.get(nodeName);
131
- if (node.inputs && subnetPortEdges) {
132
- for (const inputPort of node.inputs) {
220
+ if (subnetPortEdges) {
221
+ for (const inputPort of inputPorts) {
133
222
  const edges = subnetPortEdges.get(inputPort.name) ?? [];
134
223
  if (edges.length > 0) {
135
224
  const edge = edges[0];
136
225
  const upstreamOutputs = await evaluateNode(edge.src.node);
137
- subnetInputs[inputPort.name] = upstreamOutputs[edge.src.port];
226
+ if (edge.src.port in upstreamOutputs) {
227
+ subnetInputs[inputPort.name] = upstreamOutputs[edge.src.port];
228
+ }
229
+ else {
230
+ absentInputs.add(inputPort.name);
231
+ }
138
232
  }
139
233
  }
140
234
  }
141
- // Find the output boundary nodes in the subnet
235
+ // Promoted parameters: the value set on the subnet node, else the graphProp's default.
236
+ const subnetProps = {};
237
+ for (const propDef of derivePropDefinitions(node)) {
238
+ const instanceProp = node.props?.find(p => p.name === propDef.name);
239
+ if (instanceProp !== undefined && instanceProp.value !== undefined) {
240
+ subnetProps[propDef.name] = await resolve(instanceProp.value, nodeName);
241
+ }
242
+ }
243
+ // 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);
142
245
  const subnetOutputs = {};
143
- if (node.outputs) {
144
- for (const outputPort of node.outputs) {
145
- // Find the graphOutput boundary node by matching portName property
146
- const outputBoundaryNode = node.nodes.find(n => {
147
- if (n.type !== 'graphOutput')
148
- return false;
149
- const portNameProp = n.props?.find(p => p.name === 'portName');
150
- return portNameProp?.value === outputPort.name;
151
- });
152
- if (!outputBoundaryNode) {
153
- throw new Error(`Output boundary node not found for port: ${outputPort.name}`);
154
- }
155
- // Recursively evaluate the subnet's internal graph
156
- const subnetResult = await evaluateGraph({
157
- name: `${nodeName}_subnet`,
158
- context: graphContext || undefined,
159
- nodes: node.nodes,
160
- edges: node.edges
161
- }, {
162
- definitions,
163
- outputNode: outputBoundaryNode.name,
164
- outputPort: 'value',
165
- inputs: subnetInputs
166
- }, assetPath);
167
- subnetOutputs[outputPort.name] = subnetResult;
246
+ 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);
248
+ if (!outputBoundaryNode) {
249
+ throw new Error(`Output boundary node not found for port: ${outputPort.name}`);
168
250
  }
251
+ const result = await pull(outputBoundaryNode.name);
252
+ if ('value' in result)
253
+ subnetOutputs[outputPort.name] = result.value;
169
254
  }
170
255
  cache.set(nodeName, subnetOutputs);
171
256
  return subnetOutputs;
@@ -193,6 +278,8 @@ async function evaluateGraph(graph, options, assetPath) {
193
278
  */
194
279
  const notTaken = (outputs, port) => !(port in outputs);
195
280
  const skipped = {};
281
+ // A digital asset is a subnet stored once: its unwired arms stay dark inside it, as in an inline subnet.
282
+ const absentInputs = new Set();
196
283
  const declaredPortNames = new Set();
197
284
  if (definition.inputs) {
198
285
  for (const inputPort of definition.inputs) {
@@ -206,6 +293,10 @@ async function evaluateGraph(graph, options, assetPath) {
206
293
  : { value: upstreamOutputs[edge.src.port] };
207
294
  }));
208
295
  const values = arrived.filter((slot) => slot !== undefined);
296
+ if (edges.length > 0 && values.length === 0 && definition.graph && !inputPort.optional) {
297
+ absentInputs.add(inputPort.name);
298
+ continue;
299
+ }
209
300
  if (edges.length > 0 && values.length === 0 && !inputPort.optional) {
210
301
  cache.set(nodeName, skipped);
211
302
  return skipped;
@@ -217,7 +308,10 @@ async function evaluateGraph(graph, options, assetPath) {
217
308
  const edge = edges[0];
218
309
  const upstreamOutputs = await evaluateNode(edge.src.node);
219
310
  if (notTaken(upstreamOutputs, edge.src.port)) {
220
- if (!inputPort.optional) {
311
+ if (definition.graph) {
312
+ absentInputs.add(inputPort.name);
313
+ }
314
+ else if (!inputPort.optional) {
221
315
  cache.set(nodeName, skipped);
222
316
  return skipped;
223
317
  }
@@ -236,6 +330,10 @@ async function evaluateGraph(graph, options, assetPath) {
236
330
  const edge = edges[0];
237
331
  const upstreamOutputs = await evaluateNode(edge.src.node);
238
332
  if (notTaken(upstreamOutputs, edge.src.port)) {
333
+ if (definition.graph) {
334
+ absentInputs.add(portName);
335
+ continue;
336
+ }
239
337
  cache.set(nodeName, skipped);
240
338
  return skipped;
241
339
  }
@@ -249,7 +347,7 @@ async function evaluateGraph(graph, options, assetPath) {
249
347
  for (const propDef of definition.props) {
250
348
  const instanceProp = node.props?.find(p => p.name === propDef.name);
251
349
  if (instanceProp !== undefined && instanceProp.value !== undefined) {
252
- nodeProps[propDef.name] = instanceProp.value;
350
+ nodeProps[propDef.name] = await resolve(instanceProp.value, nodeName);
253
351
  }
254
352
  else if (propDef.default !== undefined) {
255
353
  nodeProps[propDef.name] = propDef.default;
@@ -262,14 +360,14 @@ async function evaluateGraph(graph, options, assetPath) {
262
360
  throw new Error(`Digital asset "${nodeContext}:${node.type}" contains itself: ${formatCycle([...assetPath, key])}`);
263
361
  }
264
362
  const assetGraph = definition.graph;
265
- // Find all output boundary nodes in the asset's graph
363
+ // 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]);
266
365
  const assetOutputs = {};
267
- const outputBoundaryNodes = assetGraph.nodes.filter(n => n.type === 'graphOutput');
268
- for (const outputBoundaryNode of outputBoundaryNodes) {
366
+ for (const outputBoundaryNode of assetGraph.nodes.filter(n => n.type === 'graphOutput')) {
269
367
  const portNameProp = outputBoundaryNode.props?.find(p => p.name === 'portName');
270
- const portName = portNameProp?.value || outputBoundaryNode.name;
271
- const result = await evaluateGraph({ name: `${nodeName}_asset`, context: assetGraph.context, nodes: assetGraph.nodes, edges: assetGraph.edges }, { definitions, outputNode: outputBoundaryNode.name, outputPort: 'value', inputs: nodeInputs, props: nodeProps }, [...assetPath, key]);
272
- assetOutputs[portName] = result;
368
+ const result = await pull(outputBoundaryNode.name);
369
+ if ('value' in result)
370
+ assetOutputs[portNameProp?.value || outputBoundaryNode.name] = result.value;
273
371
  }
274
372
  cache.set(nodeName, assetOutputs);
275
373
  return assetOutputs;
@@ -282,7 +380,5 @@ async function evaluateGraph(graph, options, assetPath) {
282
380
  cache.set(nodeName, outputs);
283
381
  return outputs;
284
382
  }
285
- // Evaluate starting from the output node
286
- const outputs = await evaluateNode(outputNode);
287
- return outputs[outputPort];
383
+ return evaluateNode;
288
384
  }
package/esm/validate.js CHANGED
@@ -1,4 +1,6 @@
1
+ import { derivePorts, derivePropDefinitions } from '@fbp/spec';
1
2
  import { findCycle, formatCycle } from './cycles';
3
+ import { refEdges } from './evaluate';
2
4
  /**
3
5
  * Boundary node types. These are satisfied by the runtime (graphInput/graphProp
4
6
  * receive values from the execution payload; graphOutput is a pass-through), so
@@ -85,12 +87,12 @@ export function validateGraph(graph, options = {}) {
85
87
  // Digital assets currently being visited, outermost first, so an asset that
86
88
  // contains itself is reported instead of recursed into forever.
87
89
  const assetStack = [];
88
- const visit = (g, pathPrefix) => {
90
+ const visit = (g, pathPrefix, scope = []) => {
89
91
  // Definitions can be embedded per-graph (digital assets carry their own).
90
92
  registerDefs(g.definitions);
91
93
  const graphContext = g.context || '';
92
94
  const connected = connectedPorts(g.edges ?? []);
93
- const cycle = findCycle((g.nodes ?? []).map(n => n.name), g.edges ?? []);
95
+ const cycle = findCycle((g.nodes ?? []).map(n => n.name), [...(g.edges ?? []), ...refEdges(g.nodes ?? [], scope)]);
94
96
  if (cycle) {
95
97
  const path = cycle.map(name => qualify(pathPrefix, name));
96
98
  errors.push({
@@ -107,8 +109,11 @@ export function validateGraph(graph, options = {}) {
107
109
  const nodeConnected = connected.get(node.name) ?? new Set();
108
110
  // Inline subnet: validate against its declared interface, then recurse.
109
111
  if (node.type === 'subnet' && node.nodes) {
110
- for (const port of node.inputs ?? []) {
111
- if (port.optional === true || port.multi === true)
112
+ const defaulted = new Set(node.nodes
113
+ .filter(n => n.type === 'graphInput' && nodeHasProp(n, 'default'))
114
+ .map(n => n.props.find(p => p.name === 'portName')?.value ?? n.name));
115
+ for (const port of node.inputs ?? derivePorts(node).inputs) {
116
+ if (port.optional === true || port.multi === true || defaulted.has(port.name))
112
117
  continue;
113
118
  if (!nodeConnected.has(port.name)) {
114
119
  errors.push({
@@ -119,7 +124,19 @@ export function validateGraph(graph, options = {}) {
119
124
  });
120
125
  }
121
126
  }
122
- visit({ name: `${node.name}_subnet`, context: graphContext || undefined, nodes: node.nodes, edges: node.edges ?? [] }, qualifiedName);
127
+ for (const prop of derivePropDefinitions(node)) {
128
+ if (prop.required !== true || 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 subnet "${qualifiedName}" is not set`,
136
+ });
137
+ }
138
+ }
139
+ visit({ name: `${node.name}_subnet`, context: node.context || graphContext || undefined, nodes: node.nodes, edges: node.edges ?? [] }, qualifiedName, [...scope, node.name]);
123
140
  continue;
124
141
  }
125
142
  const nodeContext = node.context || graphContext;
package/evaluate.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Graph } from '@fbp/types';
1
+ import type { Edge, Graph, Node } from '@fbp/types';
2
2
  import type { EvaluateOptions } from './types';
3
3
  /**
4
4
  * Evaluate a graph starting from the specified output node/port.
@@ -10,3 +10,8 @@ import type { EvaluateOptions } from './types';
10
10
  * @returns Promise resolving to the value at the specified output port
11
11
  */
12
12
  export declare function evaluate(graph: Graph, options: EvaluateOptions): Promise<any>;
13
+ /**
14
+ * A `{ ref }` to a sibling node's value is a dependency, like an edge.
15
+ * `scopePath` is where `nodes` live, so absolute references are recognised too.
16
+ */
17
+ export declare function refEdges(nodes: Node[], scopePath?: string[]): Edge[];
package/evaluate.js CHANGED
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.evaluate = evaluate;
4
+ exports.refEdges = refEdges;
5
+ const spec_1 = require("@fbp/spec");
4
6
  const cycles_1 = require("./cycles");
5
7
  /**
6
8
  * Build a definition map key from context, category, and name.
@@ -32,18 +34,53 @@ function parseTaskIdentifier(type) {
32
34
  * @returns Promise resolving to the value at the specified output port
33
35
  */
34
36
  async function evaluate(graph, options) {
35
- return evaluateGraph(graph, options, []);
37
+ const outputs = await openGraph(graph, options, [])(options.outputNode);
38
+ return outputs[options.outputPort];
39
+ }
40
+ /**
41
+ * A `{ ref }` to a sibling node's value is a dependency, like an edge.
42
+ * `scopePath` is where `nodes` live, so absolute references are recognised too.
43
+ */
44
+ function refEdges(nodes, scopePath = []) {
45
+ const names = new Set(nodes.map(n => n.name));
46
+ const scope = (0, spec_1.joinPath)(scopePath);
47
+ const edges = [];
48
+ for (const node of nodes) {
49
+ for (const prop of node.props ?? []) {
50
+ if (!(0, spec_1.isRef)(prop.value))
51
+ continue;
52
+ let target;
53
+ try {
54
+ target = (0, spec_1.resolveRef)(scope, prop.value.ref);
55
+ }
56
+ catch {
57
+ continue;
58
+ }
59
+ const segments = (0, spec_1.parsePath)(target.path);
60
+ const sibling = segments[segments.length - 1];
61
+ if (target.prop === undefined && sibling !== undefined && names.has(sibling) &&
62
+ (0, spec_1.joinPath)(segments.slice(0, -1)) === scope) {
63
+ edges.push({ src: { node: sibling, port: 'value' }, dst: { node: node.name, port: prop.name } });
64
+ }
65
+ }
66
+ }
67
+ return edges;
36
68
  }
37
69
  /**
38
70
  * @param assetPath - definition keys of the digital assets being evaluated,
39
71
  * outermost first, so an asset that contains itself throws instead of
40
72
  * recursing forever.
41
73
  */
42
- async function evaluateGraph(graph, options, assetPath) {
43
- const { definitions, outputNode, outputPort, inputs = {}, props = {} } = options;
74
+ function openGraph(graph, options, assetPath, scopePath = [], parentScope) {
75
+ 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;
44
81
  // Reject cycles up front, as the validator and the SQL gate do: pulling
45
82
  // through a loop would otherwise recurse until the stack overflows.
46
- const cycle = (0, cycles_1.findCycle)(graph.nodes.map(n => n.name), graph.edges);
83
+ const cycle = (0, cycles_1.findCycle)(graph.nodes.map(n => n.name), [...graph.edges, ...refEdges(graph.nodes, scopePath)]);
47
84
  if (cycle) {
48
85
  throw new Error(`Graph "${graph.name}" contains a cycle: ${(0, cycles_1.formatCycle)(cycle)}`);
49
86
  }
@@ -54,7 +91,7 @@ async function evaluateGraph(graph, options, assetPath) {
54
91
  }
55
92
  const defMap = new Map();
56
93
  for (const def of definitions) {
57
- defMap.set(defKey(def.context, def.category, def.name), def);
94
+ defMap.set(defKey(def.context, def.category ?? 'core', def.name), def);
58
95
  }
59
96
  // Graph-level context used as default for node lookups
60
97
  const graphContext = graph.context || '';
@@ -74,6 +111,42 @@ async function evaluateGraph(graph, options, assetPath) {
74
111
  }
75
112
  // Cache for evaluated node outputs to avoid re-evaluation
76
113
  const cache = new Map();
114
+ /**
115
+ * Resolve a prop value: a `{ ref }` takes the value of the node it points at
116
+ * (its `value` output, or the named prop for a '.prop' reference). The target
117
+ * is in this scope or one that encloses it.
118
+ */
119
+ async function resolve(value, holder, chain = []) {
120
+ if (!(0, spec_1.isRef)(value))
121
+ return value;
122
+ const target = (0, spec_1.resolveRef)((0, spec_1.joinPath)(scopePath), value.ref);
123
+ const segments = (0, spec_1.parsePath)(target.path);
124
+ const name = segments[segments.length - 1];
125
+ const owner = segments.slice(0, -1).join('/');
126
+ let found = scope;
127
+ while (found && found.path.join('/') !== owner)
128
+ found = found.parent;
129
+ if (!found || name === undefined || !found.getNode(name)) {
130
+ throw new Error(`Reference "${value.ref}" on node "${holder}" does not point at a node in its scope or an enclosing one`);
131
+ }
132
+ if (target.prop !== undefined) {
133
+ const key = `${target.path}.${target.prop}`;
134
+ if (chain.includes(key)) {
135
+ throw new Error(`Reference "${value.ref}" on node "${holder}" refers back to itself`);
136
+ }
137
+ const prop = found.getNode(name).props?.find(p => p.name === target.prop);
138
+ return found.resolve(prop?.value, name, [...chain, key]);
139
+ }
140
+ const outputs = await found.evaluateNode(name);
141
+ return 'value' in outputs ? outputs.value : Object.values(outputs)[0];
142
+ }
143
+ const scope = {
144
+ path: scopePath,
145
+ parent: parentScope,
146
+ getNode: name => nodeMap.get(name),
147
+ evaluateNode: name => evaluateNode(name),
148
+ resolve
149
+ };
77
150
  /**
78
151
  * Recursively evaluate a node and return all its outputs.
79
152
  * Fully async to support async node implementations.
@@ -93,6 +166,11 @@ async function evaluateGraph(graph, options, assetPath) {
93
166
  // Get the port name from the portName property
94
167
  const portNameProp = node.props?.find(p => p.name === 'portName');
95
168
  const inputName = portNameProp?.value || nodeName;
169
+ // A wired input whose arm was not taken stays dark, default or not, as it would in the flat graph.
170
+ if (absent?.has(inputName)) {
171
+ cache.set(nodeName, {});
172
+ return {};
173
+ }
96
174
  // Check external inputs first, then fall back to node's default prop
97
175
  let value = inputs[inputName];
98
176
  if (value === undefined) {
@@ -107,7 +185,10 @@ async function evaluateGraph(graph, options, assetPath) {
107
185
  // Get the prop name from the propName property
108
186
  const propNameProp = node.props?.find(p => p.name === 'propName');
109
187
  const propName = propNameProp?.value || nodeName;
110
- const value = props[propName];
188
+ let value = props[propName];
189
+ if (value === undefined) {
190
+ value = node.props?.find(p => p.name === 'default')?.value;
191
+ }
111
192
  const result = { value };
112
193
  cache.set(nodeName, result);
113
194
  return result;
@@ -120,6 +201,10 @@ async function evaluateGraph(graph, options, assetPath) {
120
201
  if (edges.length > 0) {
121
202
  const edge = edges[0];
122
203
  const upstreamOutputs = await evaluateNode(edge.src.node);
204
+ if (!(edge.src.port in upstreamOutputs)) {
205
+ cache.set(nodeName, {});
206
+ return {};
207
+ }
123
208
  value = upstreamOutputs[edge.src.port];
124
209
  }
125
210
  const result = { value };
@@ -127,48 +212,49 @@ async function evaluateGraph(graph, options, assetPath) {
127
212
  return result;
128
213
  }
129
214
  // Handle subnet nodes (type: 'subnet' with inline nodes/edges)
130
- if (node.type === 'subnet' && node.nodes && node.edges) {
215
+ if (node.type === 'subnet' && node.nodes) {
216
+ // 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;
131
220
  // Collect inputs for the subnet by evaluating upstream nodes
132
221
  const subnetInputs = {};
222
+ const absentInputs = new Set();
133
223
  const subnetPortEdges = edgesByDst.get(nodeName);
134
- if (node.inputs && subnetPortEdges) {
135
- for (const inputPort of node.inputs) {
224
+ if (subnetPortEdges) {
225
+ for (const inputPort of inputPorts) {
136
226
  const edges = subnetPortEdges.get(inputPort.name) ?? [];
137
227
  if (edges.length > 0) {
138
228
  const edge = edges[0];
139
229
  const upstreamOutputs = await evaluateNode(edge.src.node);
140
- subnetInputs[inputPort.name] = upstreamOutputs[edge.src.port];
230
+ if (edge.src.port in upstreamOutputs) {
231
+ subnetInputs[inputPort.name] = upstreamOutputs[edge.src.port];
232
+ }
233
+ else {
234
+ absentInputs.add(inputPort.name);
235
+ }
141
236
  }
142
237
  }
143
238
  }
144
- // Find the output boundary nodes in the subnet
239
+ // Promoted parameters: the value set on the subnet node, else the graphProp's default.
240
+ const subnetProps = {};
241
+ for (const propDef of (0, spec_1.derivePropDefinitions)(node)) {
242
+ const instanceProp = node.props?.find(p => p.name === propDef.name);
243
+ if (instanceProp !== undefined && instanceProp.value !== undefined) {
244
+ subnetProps[propDef.name] = await resolve(instanceProp.value, nodeName);
245
+ }
246
+ }
247
+ // 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);
145
249
  const subnetOutputs = {};
146
- if (node.outputs) {
147
- for (const outputPort of node.outputs) {
148
- // Find the graphOutput boundary node by matching portName property
149
- const outputBoundaryNode = node.nodes.find(n => {
150
- if (n.type !== 'graphOutput')
151
- return false;
152
- const portNameProp = n.props?.find(p => p.name === 'portName');
153
- return portNameProp?.value === outputPort.name;
154
- });
155
- if (!outputBoundaryNode) {
156
- throw new Error(`Output boundary node not found for port: ${outputPort.name}`);
157
- }
158
- // Recursively evaluate the subnet's internal graph
159
- const subnetResult = await evaluateGraph({
160
- name: `${nodeName}_subnet`,
161
- context: graphContext || undefined,
162
- nodes: node.nodes,
163
- edges: node.edges
164
- }, {
165
- definitions,
166
- outputNode: outputBoundaryNode.name,
167
- outputPort: 'value',
168
- inputs: subnetInputs
169
- }, assetPath);
170
- subnetOutputs[outputPort.name] = subnetResult;
250
+ 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);
252
+ if (!outputBoundaryNode) {
253
+ throw new Error(`Output boundary node not found for port: ${outputPort.name}`);
171
254
  }
255
+ const result = await pull(outputBoundaryNode.name);
256
+ if ('value' in result)
257
+ subnetOutputs[outputPort.name] = result.value;
172
258
  }
173
259
  cache.set(nodeName, subnetOutputs);
174
260
  return subnetOutputs;
@@ -196,6 +282,8 @@ async function evaluateGraph(graph, options, assetPath) {
196
282
  */
197
283
  const notTaken = (outputs, port) => !(port in outputs);
198
284
  const skipped = {};
285
+ // A digital asset is a subnet stored once: its unwired arms stay dark inside it, as in an inline subnet.
286
+ const absentInputs = new Set();
199
287
  const declaredPortNames = new Set();
200
288
  if (definition.inputs) {
201
289
  for (const inputPort of definition.inputs) {
@@ -209,6 +297,10 @@ async function evaluateGraph(graph, options, assetPath) {
209
297
  : { value: upstreamOutputs[edge.src.port] };
210
298
  }));
211
299
  const values = arrived.filter((slot) => slot !== undefined);
300
+ if (edges.length > 0 && values.length === 0 && definition.graph && !inputPort.optional) {
301
+ absentInputs.add(inputPort.name);
302
+ continue;
303
+ }
212
304
  if (edges.length > 0 && values.length === 0 && !inputPort.optional) {
213
305
  cache.set(nodeName, skipped);
214
306
  return skipped;
@@ -220,7 +312,10 @@ async function evaluateGraph(graph, options, assetPath) {
220
312
  const edge = edges[0];
221
313
  const upstreamOutputs = await evaluateNode(edge.src.node);
222
314
  if (notTaken(upstreamOutputs, edge.src.port)) {
223
- if (!inputPort.optional) {
315
+ if (definition.graph) {
316
+ absentInputs.add(inputPort.name);
317
+ }
318
+ else if (!inputPort.optional) {
224
319
  cache.set(nodeName, skipped);
225
320
  return skipped;
226
321
  }
@@ -239,6 +334,10 @@ async function evaluateGraph(graph, options, assetPath) {
239
334
  const edge = edges[0];
240
335
  const upstreamOutputs = await evaluateNode(edge.src.node);
241
336
  if (notTaken(upstreamOutputs, edge.src.port)) {
337
+ if (definition.graph) {
338
+ absentInputs.add(portName);
339
+ continue;
340
+ }
242
341
  cache.set(nodeName, skipped);
243
342
  return skipped;
244
343
  }
@@ -252,7 +351,7 @@ async function evaluateGraph(graph, options, assetPath) {
252
351
  for (const propDef of definition.props) {
253
352
  const instanceProp = node.props?.find(p => p.name === propDef.name);
254
353
  if (instanceProp !== undefined && instanceProp.value !== undefined) {
255
- nodeProps[propDef.name] = instanceProp.value;
354
+ nodeProps[propDef.name] = await resolve(instanceProp.value, nodeName);
256
355
  }
257
356
  else if (propDef.default !== undefined) {
258
357
  nodeProps[propDef.name] = propDef.default;
@@ -265,14 +364,14 @@ async function evaluateGraph(graph, options, assetPath) {
265
364
  throw new Error(`Digital asset "${nodeContext}:${node.type}" contains itself: ${(0, cycles_1.formatCycle)([...assetPath, key])}`);
266
365
  }
267
366
  const assetGraph = definition.graph;
268
- // Find all output boundary nodes in the asset's graph
367
+ // 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]);
269
369
  const assetOutputs = {};
270
- const outputBoundaryNodes = assetGraph.nodes.filter(n => n.type === 'graphOutput');
271
- for (const outputBoundaryNode of outputBoundaryNodes) {
370
+ for (const outputBoundaryNode of assetGraph.nodes.filter(n => n.type === 'graphOutput')) {
272
371
  const portNameProp = outputBoundaryNode.props?.find(p => p.name === 'portName');
273
- const portName = portNameProp?.value || outputBoundaryNode.name;
274
- const result = await evaluateGraph({ name: `${nodeName}_asset`, context: assetGraph.context, nodes: assetGraph.nodes, edges: assetGraph.edges }, { definitions, outputNode: outputBoundaryNode.name, outputPort: 'value', inputs: nodeInputs, props: nodeProps }, [...assetPath, key]);
275
- assetOutputs[portName] = result;
372
+ const result = await pull(outputBoundaryNode.name);
373
+ if ('value' in result)
374
+ assetOutputs[portNameProp?.value || outputBoundaryNode.name] = result.value;
276
375
  }
277
376
  cache.set(nodeName, assetOutputs);
278
377
  return assetOutputs;
@@ -285,7 +384,5 @@ async function evaluateGraph(graph, options, assetPath) {
285
384
  cache.set(nodeName, outputs);
286
385
  return outputs;
287
386
  }
288
- // Evaluate starting from the output node
289
- const outputs = await evaluateNode(outputNode);
290
- return outputs[outputPort];
387
+ return evaluateNode;
291
388
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fbp/evaluator",
3
- "version": "1.6.0",
3
+ "version": "1.8.0",
4
4
  "description": "FBP graph evaluator — node definitions, graph evaluation and validation",
5
5
  "author": "Constructive <developers@constructive.io>",
6
6
  "license": "MIT",
@@ -12,7 +12,8 @@
12
12
  "directory": "dist"
13
13
  },
14
14
  "dependencies": {
15
- "@fbp/types": "1.4.1"
15
+ "@fbp/types": "1.5.0",
16
+ "@fbp/spec": "1.5.0"
16
17
  },
17
18
  "devDependencies": {
18
19
  "@types/jest": "^30.0.0",
package/validate.js CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.validateGraph = validateGraph;
4
+ const spec_1 = require("@fbp/spec");
4
5
  const cycles_1 = require("./cycles");
6
+ const evaluate_1 = require("./evaluate");
5
7
  /**
6
8
  * Boundary node types. These are satisfied by the runtime (graphInput/graphProp
7
9
  * receive values from the execution payload; graphOutput is a pass-through), so
@@ -88,12 +90,12 @@ function validateGraph(graph, options = {}) {
88
90
  // Digital assets currently being visited, outermost first, so an asset that
89
91
  // contains itself is reported instead of recursed into forever.
90
92
  const assetStack = [];
91
- const visit = (g, pathPrefix) => {
93
+ const visit = (g, pathPrefix, scope = []) => {
92
94
  // Definitions can be embedded per-graph (digital assets carry their own).
93
95
  registerDefs(g.definitions);
94
96
  const graphContext = g.context || '';
95
97
  const connected = connectedPorts(g.edges ?? []);
96
- const cycle = (0, cycles_1.findCycle)((g.nodes ?? []).map(n => n.name), g.edges ?? []);
98
+ const cycle = (0, cycles_1.findCycle)((g.nodes ?? []).map(n => n.name), [...(g.edges ?? []), ...(0, evaluate_1.refEdges)(g.nodes ?? [], scope)]);
97
99
  if (cycle) {
98
100
  const path = cycle.map(name => qualify(pathPrefix, name));
99
101
  errors.push({
@@ -110,8 +112,11 @@ function validateGraph(graph, options = {}) {
110
112
  const nodeConnected = connected.get(node.name) ?? new Set();
111
113
  // Inline subnet: validate against its declared interface, then recurse.
112
114
  if (node.type === 'subnet' && node.nodes) {
113
- for (const port of node.inputs ?? []) {
114
- if (port.optional === true || port.multi === true)
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) {
119
+ if (port.optional === true || port.multi === true || defaulted.has(port.name))
115
120
  continue;
116
121
  if (!nodeConnected.has(port.name)) {
117
122
  errors.push({
@@ -122,7 +127,19 @@ function validateGraph(graph, options = {}) {
122
127
  });
123
128
  }
124
129
  }
125
- visit({ name: `${node.name}_subnet`, context: graphContext || undefined, nodes: node.nodes, edges: node.edges ?? [] }, qualifiedName);
130
+ for (const prop of (0, spec_1.derivePropDefinitions)(node)) {
131
+ if (prop.required !== true || 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 subnet "${qualifiedName}" is not set`,
139
+ });
140
+ }
141
+ }
142
+ visit({ name: `${node.name}_subnet`, context: node.context || graphContext || undefined, nodes: node.nodes, edges: node.edges ?? [] }, qualifiedName, [...scope, node.name]);
126
143
  continue;
127
144
  }
128
145
  const nodeContext = node.context || graphContext;