@valerypopoff/rivet2-core 2.0.5 → 2.0.7

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.
@@ -14,6 +14,8 @@ import { extractRegexNode } from './nodes/ExtractRegexNode.js';
14
14
  export * from './nodes/ExtractRegexNode.js';
15
15
  import { codeNode } from './nodes/CodeNode.js';
16
16
  export * from './nodes/CodeNode.js';
17
+ import { codeNewNode } from './nodes/CodeNewNode.js';
18
+ export * from './nodes/CodeNewNode.js';
17
19
  import { expressionNode } from './nodes/ExpressionNode.js';
18
20
  export * from './nodes/ExpressionNode.js';
19
21
  import { matchNode } from './nodes/MatchNode.js';
@@ -186,6 +188,7 @@ export const registerBuiltInNodes = (registry) => {
186
188
  .register(promptNode)
187
189
  .register(extractRegexNode)
188
190
  .register(codeNode)
191
+ .register(codeNewNode)
189
192
  .register(expressionNode)
190
193
  .register(matchNode)
191
194
  .register(ifNode)
@@ -0,0 +1,207 @@
1
+ import { nanoid } from 'nanoid/non-secure';
2
+ import { dedent } from 'ts-dedent';
3
+ import {} from '../EditorDefinition.js';
4
+ import { nodeDefinition } from '../NodeDefinition.js';
5
+ import { NodeImpl } from '../NodeImpl.js';
6
+ import {} from '../NodeBodySpec.js';
7
+ import { appendCodeNodeSourceUrl, buildCodeNodeSourceUrl, enrichCodeNodeErrorWithLocation, } from './codeNodeErrorDiagnostics.js';
8
+ import { buildJsValueInterpolatedSource, buildJsValueInputsInitializer, buildJsValuePreview, getJsValueInterpolationInputDefinitions, getJsValueInterpolationRuntimeContext, interpolateJsValuePreviewSource, sanitizeGeneratedJsValueError, } from './jsValueInterpolation.js';
9
+ const DEFAULT_CODE_NEW = dedent `
10
+ // This is a Code node. Write JavaScript here and return one value.
11
+ // Interpolation tokens create input ports and evaluate as connected values.
12
+ // The returned value becomes the node's single output.
13
+ const value = {{input}};
14
+ return value;
15
+ `;
16
+ const MAX_BODY_PREVIEW_LINES = 15;
17
+ const CODE_NEW_INPUTS_IDENTIFIER = '__codeNewInputs';
18
+ const CODE_NEW_INPUT_CLONE_CACHE_IDENTIFIER = 'codeNewInputCloneCache';
19
+ export const CODE_NEW_OUTPUT_PORT_ID = 'output';
20
+ function buildCodeNewPreview(code) {
21
+ return buildJsValuePreview(code, MAX_BODY_PREVIEW_LINES);
22
+ }
23
+ function buildCodeNewRuntimeSource(code, inputsIdentifier) {
24
+ return buildJsValueInterpolatedSource(code, inputsIdentifier, { trim: false });
25
+ }
26
+ function buildCodeNewInputsInitializer(inputNames, inputsIdentifier) {
27
+ return buildJsValueInputsInitializer({
28
+ cacheIdentifier: CODE_NEW_INPUT_CLONE_CACHE_IDENTIFIER,
29
+ inputNames,
30
+ inputsIdentifier,
31
+ });
32
+ }
33
+ export function interpolateCodeNewSource(code, inputs) {
34
+ return interpolateJsValuePreviewSource(code, inputs, { trim: false });
35
+ }
36
+ function sanitizeCodeNewError(error, inputNames, inputsIdentifier) {
37
+ return sanitizeGeneratedJsValueError(error, inputNames, inputsIdentifier, 'code input');
38
+ }
39
+ function buildCodeNewWrapper(code, interpolationContext) {
40
+ const { inputNames, inputsIdentifier } = interpolationContext;
41
+ const beforeUserCodeLines = [
42
+ ...buildCodeNewInputsInitializer(inputNames, inputsIdentifier).split(/\r?\n/),
43
+ '',
44
+ 'const __codeNewResult = await (async () => {',
45
+ ];
46
+ const afterUserCodeLines = [
47
+ '})();',
48
+ '',
49
+ 'return {',
50
+ ' output: {',
51
+ " type: 'any',",
52
+ ' value: __codeNewResult,',
53
+ ' },',
54
+ '};',
55
+ ];
56
+ return {
57
+ source: [...beforeUserCodeLines, buildCodeNewRuntimeSource(code, inputsIdentifier), ...afterUserCodeLines].join('\n'),
58
+ userCodeLineOffset: beforeUserCodeLines.length,
59
+ };
60
+ }
61
+ function isDataValueLike(value) {
62
+ return (typeof value === 'object' &&
63
+ value !== null &&
64
+ typeof value.type === 'string' &&
65
+ Object.prototype.hasOwnProperty.call(value, 'value'));
66
+ }
67
+ function validateCodeNewRunnerOutputs(outputs) {
68
+ if (outputs == null || typeof outputs !== 'object' || ('then' in outputs && typeof outputs.then === 'function')) {
69
+ throw new Error('Code node runner must return an object containing the Output value.');
70
+ }
71
+ const output = outputs[CODE_NEW_OUTPUT_PORT_ID];
72
+ if (!isDataValueLike(output)) {
73
+ throw new Error('Code node runner must return a DataValue for the Output port.');
74
+ }
75
+ if (output.type !== 'any') {
76
+ throw new Error('Code node runner must return an any DataValue for the Output port.');
77
+ }
78
+ return outputs;
79
+ }
80
+ export class CodeNewNodeImpl extends NodeImpl {
81
+ static create() {
82
+ return {
83
+ type: 'codeNew',
84
+ title: 'Code',
85
+ id: nanoid(),
86
+ visualData: {
87
+ x: 0,
88
+ y: 0,
89
+ width: 260,
90
+ },
91
+ data: {
92
+ code: DEFAULT_CODE_NEW,
93
+ allowFetch: false,
94
+ allowRequire: false,
95
+ allowRivet: false,
96
+ allowProcess: false,
97
+ allowConsole: false,
98
+ },
99
+ };
100
+ }
101
+ getInputDefinitions() {
102
+ return getJsValueInterpolationInputDefinitions(this.data.code);
103
+ }
104
+ getOutputDefinitions() {
105
+ return [
106
+ {
107
+ id: CODE_NEW_OUTPUT_PORT_ID,
108
+ title: 'Output',
109
+ dataType: 'any',
110
+ },
111
+ ];
112
+ }
113
+ getEditors() {
114
+ return [
115
+ {
116
+ type: 'code',
117
+ label: 'Code',
118
+ helperMessage: 'Use {{var}} to create input ports. Interpolated variables evaluate as the connected values.',
119
+ dataKey: 'code',
120
+ language: 'javascript',
121
+ interpolationSyntax: 'js-value',
122
+ enableFolding: true,
123
+ },
124
+ {
125
+ type: 'group',
126
+ label: 'Runtime permissions',
127
+ defaultOpen: true,
128
+ editors: [
129
+ {
130
+ type: 'toggle',
131
+ label: 'Allow "fetch"',
132
+ dataKey: 'allowFetch',
133
+ },
134
+ {
135
+ type: 'toggle',
136
+ label: 'Allow "Rivet"',
137
+ dataKey: 'allowRivet',
138
+ },
139
+ {
140
+ type: 'toggle',
141
+ label: 'Allow "console"',
142
+ dataKey: 'allowConsole',
143
+ },
144
+ {
145
+ type: 'toggle',
146
+ label: 'Allow "require"',
147
+ dataKey: 'allowRequire',
148
+ helperMessage: 'Only available with the Node executor',
149
+ },
150
+ {
151
+ type: 'toggle',
152
+ label: 'Allow "process"',
153
+ dataKey: 'allowProcess',
154
+ helperMessage: 'Only available with the Node executor',
155
+ },
156
+ ],
157
+ },
158
+ ];
159
+ }
160
+ getBody() {
161
+ return {
162
+ type: 'colorized',
163
+ text: buildCodeNewPreview(this.data.code),
164
+ language: 'javascript',
165
+ fontSize: 12,
166
+ fontFamily: 'monospace',
167
+ };
168
+ }
169
+ static getUIData() {
170
+ return {
171
+ infoBoxBody: dedent `
172
+ Runs JavaScript code that can use interpolation-created input ports and emits the returned value as the node output.
173
+ `,
174
+ infoBoxTitle: 'Code Node',
175
+ contextMenuTitle: 'Code',
176
+ group: ['Advanced'],
177
+ };
178
+ }
179
+ async process(inputs, context) {
180
+ const sourceUrl = buildCodeNodeSourceUrl(this.chartNode.id, context.processId);
181
+ const interpolationContext = getJsValueInterpolationRuntimeContext(this.data.code, CODE_NEW_INPUTS_IDENTIFIER);
182
+ const { inputNames, inputsIdentifier } = interpolationContext;
183
+ const { source, userCodeLineOffset } = buildCodeNewWrapper(this.data.code, interpolationContext);
184
+ try {
185
+ const outputs = await context.codeRunner.runCode(appendCodeNodeSourceUrl(source, sourceUrl), inputs, {
186
+ includeFetch: this.data.allowFetch ?? false,
187
+ includeRequire: this.data.allowRequire ?? false,
188
+ includeRivet: this.data.allowRivet ?? false,
189
+ includeProcess: this.data.allowProcess ?? false,
190
+ includeConsole: this.data.allowConsole ?? false,
191
+ }, context.graphInputNodeValues, context.contextValues);
192
+ return validateCodeNewRunnerOutputs(outputs);
193
+ }
194
+ catch (error) {
195
+ const enrichedError = await enrichCodeNodeErrorWithLocation({
196
+ code: this.data.code,
197
+ diagnosticCode: source,
198
+ error,
199
+ locationLabel: 'Code node',
200
+ sourceUrl,
201
+ userCodeLineOffset,
202
+ });
203
+ throw sanitizeCodeNewError(enrichedError, inputNames, inputsIdentifier);
204
+ }
205
+ }
206
+ }
207
+ export const codeNewNode = nodeDefinition(CodeNewNodeImpl, 'Code');
@@ -11,7 +11,7 @@ export class CodeNodeImpl extends NodeImpl {
11
11
  static create() {
12
12
  const chartNode = {
13
13
  type: 'code',
14
- title: 'Code',
14
+ title: 'Code (legacy)',
15
15
  id: nanoid(),
16
16
  visualData: {
17
17
  x: 0,
@@ -19,10 +19,10 @@ export class CodeNodeImpl extends NodeImpl {
19
19
  },
20
20
  data: {
21
21
  code: dedent `
22
- // This is a code node, you can write and JS in here and it will be executed.
22
+ // This is a Code (legacy) node. Write JavaScript here and it will be executed.
23
23
  // Inputs are accessible via an object \`inputs\` and data is typed (i.e. inputs.foo.type, inputs.foo.value)
24
24
  // Return an object with named outputs that match the output names specified in the node's config.
25
- // Output values must by typed as well (e.g. { bar: { type: 'string', value: 'bar' } }
25
+ // Output values must be typed as well (e.g. { bar: { type: 'string', value: 'bar' } }
26
26
  return {
27
27
  output1: {
28
28
  type: inputs.input1.type,
@@ -156,10 +156,10 @@ export class CodeNodeImpl extends NodeImpl {
156
156
  static getUIData() {
157
157
  return {
158
158
  infoBoxBody: dedent `
159
- Executes a piece of JavaScript code. See the Rivet Documentation for more information on how to write code for the Code Node.
159
+ Executes legacy JavaScript code with manually configured inputs and outputs.
160
160
  `,
161
- infoBoxTitle: 'Code Node',
162
- contextMenuTitle: 'Code',
161
+ infoBoxTitle: 'Code (legacy) Node',
162
+ contextMenuTitle: 'Code (legacy)',
163
163
  group: ['Advanced'],
164
164
  };
165
165
  }
@@ -179,19 +179,20 @@ export class CodeNodeImpl extends NodeImpl {
179
179
  throw await enrichCodeNodeErrorWithLocation({
180
180
  code: this.data.code,
181
181
  error,
182
+ locationLabel: 'Code (legacy) node',
182
183
  sourceUrl,
183
184
  });
184
185
  }
185
186
  if (outputs == null || typeof outputs !== 'object' || ('then' in outputs && typeof outputs.then === 'function')) {
186
- throw new Error('Code node must return an object with output values.');
187
+ throw new Error('Code (legacy) node must return an object with output values.');
187
188
  }
188
189
  const missingOutputs = this.getOutputDefinitions().filter((output) => !(output.id in outputs));
189
190
  if (missingOutputs.length > 0) {
190
- throw new Error(`Code node must return an object with output values for all outputs. To not run an output, return { "type": "control-flow-excluded", "value": undefined }. To return undefined, return { "type": "any", "value": undefined }. Missing: ${missingOutputs
191
+ throw new Error(`Code (legacy) node must return an object with output values for all outputs. To not run an output, return { "type": "control-flow-excluded", "value": undefined }. To return undefined, return { "type": "any", "value": undefined }. Missing: ${missingOutputs
191
192
  .map((output) => output.id)
192
193
  .join(', ')}`);
193
194
  }
194
195
  return outputs;
195
196
  }
196
197
  }
197
- export const codeNode = nodeDefinition(CodeNodeImpl, 'Code');
198
+ export const codeNode = nodeDefinition(CodeNodeImpl, 'Code (legacy)');
@@ -20,7 +20,7 @@ export class CommentNodeImpl extends NodeImpl {
20
20
  text: '',
21
21
  height: 600,
22
22
  color: 'rgba(255,255,255,1)',
23
- backgroundColor: 'rgba(0,0,0,0.05)',
23
+ backgroundColor: 'rgba(128,128,128,0.05)',
24
24
  },
25
25
  };
26
26
  return chartNode;
@@ -4,49 +4,36 @@ import { NodeImpl } from '../NodeImpl.js';
4
4
  import {} from '../../index.js';
5
5
  import { dedent } from 'ts-dedent';
6
6
  import { nodeDefinition } from '../NodeDefinition.js';
7
- import { getError } from '../../utils/errors.js';
8
- import { buildClonedInputValueAssignments, buildCloneJsInputValueFunction, buildJsValueInterpolatedSource, getJsValueInterpolationInputNames, interpolateJsValuePreviewSource, sanitizeGeneratedJsValueText, } from './jsValueInterpolation.js';
9
- import { createInterpolationInputDefinition } from '../interpolationInputDefinition.js';
7
+ import { buildJsValueInterpolatedSource, buildJsValueInputsInitializer, buildJsValuePreview, getJsValueInterpolationInputDefinitions, getJsValueInterpolationRuntimeContext, interpolateJsValuePreviewSource, sanitizeGeneratedJsValueError, } from './jsValueInterpolation.js';
10
8
  const DEFAULT_EXPRESSION = '{{a}} == "123" ? {{b}} : {{c}}';
11
9
  const MAX_BODY_PREVIEW_LINES = 15;
12
10
  const EXPRESSION_INPUTS_IDENTIFIER = '__expressionInputs';
13
11
  const EXPRESSION_INPUT_CLONE_CACHE_IDENTIFIER = 'expressionInputCloneCache';
14
12
  export const EXPRESSION_OUTPUT_PORT_ID = 'output';
15
13
  function buildExpressionPreview(expression) {
16
- return expression.split('\n').slice(0, MAX_BODY_PREVIEW_LINES).join('\n').trim();
14
+ return buildJsValuePreview(expression, MAX_BODY_PREVIEW_LINES);
17
15
  }
18
- function getExpressionInputNames(expression) {
19
- return getJsValueInterpolationInputNames(expression);
16
+ function buildExpressionRuntimeSource(expression, inputsIdentifier) {
17
+ return buildJsValueInterpolatedSource(expression, inputsIdentifier);
20
18
  }
21
- function buildExpressionRuntimeSource(expression) {
22
- return buildJsValueInterpolatedSource(expression, EXPRESSION_INPUTS_IDENTIFIER);
23
- }
24
- function buildExpressionInputsInitializer(inputNames) {
25
- return dedent `
26
- ${buildCloneJsInputValueFunction()}
27
- const ${EXPRESSION_INPUTS_IDENTIFIER} = Object.create(null);
28
- const ${EXPRESSION_INPUT_CLONE_CACHE_IDENTIFIER} = new WeakMap();
29
- ${buildClonedInputValueAssignments(inputNames, EXPRESSION_INPUTS_IDENTIFIER, EXPRESSION_INPUT_CLONE_CACHE_IDENTIFIER)}
30
- `;
19
+ function buildExpressionInputsInitializer(inputNames, inputsIdentifier) {
20
+ return buildJsValueInputsInitializer({
21
+ cacheIdentifier: EXPRESSION_INPUT_CLONE_CACHE_IDENTIFIER,
22
+ inputNames,
23
+ inputsIdentifier,
24
+ });
31
25
  }
32
26
  export function interpolateExpressionSource(expression, inputs) {
33
27
  return interpolateJsValuePreviewSource(expression, inputs);
34
28
  }
35
- function sanitizeGeneratedExpressionText(text, inputNames) {
36
- return sanitizeGeneratedJsValueText(text, inputNames, EXPRESSION_INPUTS_IDENTIFIER, 'expression input');
29
+ function sanitizeExpressionError(error, inputNames, inputsIdentifier) {
30
+ return sanitizeGeneratedJsValueError(error, inputNames, inputsIdentifier, 'expression input');
37
31
  }
38
- function sanitizeExpressionError(error, inputNames) {
39
- const expressionError = getError(error);
40
- expressionError.message =
41
- sanitizeGeneratedExpressionText(expressionError.message, inputNames) ?? expressionError.message;
42
- expressionError.stack = sanitizeGeneratedExpressionText(expressionError.stack, inputNames);
43
- return expressionError;
44
- }
45
- function buildExpressionWrapper(expression) {
46
- const inputNames = getExpressionInputNames(expression);
47
- const expressionSource = buildExpressionRuntimeSource(expression);
32
+ function buildExpressionWrapper(expression, interpolationContext) {
33
+ const { inputNames, inputsIdentifier } = interpolationContext;
34
+ const expressionSource = buildExpressionRuntimeSource(expression, inputsIdentifier);
48
35
  return dedent `
49
- ${buildExpressionInputsInitializer(inputNames)}
36
+ ${buildExpressionInputsInitializer(inputNames, inputsIdentifier)}
50
37
 
51
38
  return {
52
39
  output: {
@@ -74,13 +61,7 @@ export class ExpressionNodeImpl extends NodeImpl {
74
61
  return chartNode;
75
62
  }
76
63
  getInputDefinitions() {
77
- return getExpressionInputNames(this.data.expression).map((inputName) => {
78
- return createInterpolationInputDefinition({
79
- interpolationName: inputName,
80
- dataType: 'any',
81
- required: false,
82
- });
83
- });
64
+ return getJsValueInterpolationInputDefinitions(this.data.expression);
84
65
  }
85
66
  getOutputDefinitions() {
86
67
  return [
@@ -99,6 +80,7 @@ export class ExpressionNodeImpl extends NodeImpl {
99
80
  helperMessage: 'Use {{var}} to create input ports. Interpolated variables evaluate as the connected values.',
100
81
  dataKey: 'expression',
101
82
  language: 'javascript',
83
+ interpolationSyntax: 'js-value',
102
84
  enableFolding: true,
103
85
  },
104
86
  ];
@@ -125,9 +107,11 @@ export class ExpressionNodeImpl extends NodeImpl {
125
107
  };
126
108
  }
127
109
  async process(inputs, context) {
128
- const inputNames = getExpressionInputNames(this.data.expression);
110
+ const interpolationContext = getJsValueInterpolationRuntimeContext(this.data.expression, EXPRESSION_INPUTS_IDENTIFIER);
111
+ const { inputNames, inputsIdentifier } = interpolationContext;
112
+ const source = buildExpressionWrapper(this.data.expression, interpolationContext);
129
113
  try {
130
- return await context.codeRunner.runCode(buildExpressionWrapper(this.data.expression), inputs, {
114
+ return await context.codeRunner.runCode(source, inputs, {
131
115
  includeFetch: false,
132
116
  includeRequire: false,
133
117
  includeRivet: false,
@@ -136,7 +120,7 @@ export class ExpressionNodeImpl extends NodeImpl {
136
120
  }, context.graphInputNodeValues, context.contextValues);
137
121
  }
138
122
  catch (error) {
139
- throw sanitizeExpressionError(error, inputNames);
123
+ throw sanitizeExpressionError(error, inputNames, inputsIdentifier);
140
124
  }
141
125
  }
142
126
  }
@@ -96,6 +96,7 @@ export class ObjectNodeImpl extends NodeImpl {
96
96
  label: 'JSON Template',
97
97
  dataKey: 'jsonTemplate',
98
98
  language: 'json',
99
+ interpolationSyntax: 'json-template',
99
100
  theme: 'prompt-interpolation',
100
101
  enableFolding: true,
101
102
  },
@@ -110,6 +110,7 @@ export class GptFunctionNodeImpl extends NodeImpl {
110
110
  label: 'Schema',
111
111
  dataKey: 'schema',
112
112
  language: 'json',
113
+ interpolationSyntax: 'json-template',
113
114
  useInputToggleDataKey: 'useSchemaInput',
114
115
  enableFolding: true,
115
116
  },
@@ -26,7 +26,7 @@ function getRuntimeErrorLocationFromStack(params) {
26
26
  }
27
27
  const generatedLine = Number(match[1]);
28
28
  const column = Number(match[2]);
29
- const line = generatedLine - ASYNC_FUNCTION_LINE_OFFSET;
29
+ const line = generatedLine - ASYNC_FUNCTION_LINE_OFFSET - (params.userCodeLineOffset ?? 0);
30
30
  const lineCount = Math.max(params.code.split(/\r?\n/).length, 1);
31
31
  if (!Number.isFinite(line) || line < 1 || line > lineCount) {
32
32
  return undefined;
@@ -49,11 +49,11 @@ function getParserErrorLocation(error) {
49
49
  line: loc.line,
50
50
  };
51
51
  }
52
- async function getSyntaxErrorLocation(code, error) {
52
+ async function getSyntaxErrorLocation(code, error, options = {}) {
53
53
  if (error.name !== 'SyntaxError') {
54
54
  return undefined;
55
55
  }
56
- const wrappedCode = `async function __rivetCodeNode__() {\n${code}\n}`;
56
+ const wrappedCode = `async function __rivetCodeNode__() {\n${options.diagnosticCode ?? code}\n}`;
57
57
  try {
58
58
  const { parse } = await import('acorn');
59
59
  parse(wrappedCode, {
@@ -68,7 +68,7 @@ async function getSyntaxErrorLocation(code, error) {
68
68
  return undefined;
69
69
  }
70
70
  const lineCount = Math.max(code.split(/\r?\n/).length, 1);
71
- const line = Math.min(Math.max(parserLocation.line - SYNTAX_PARSE_WRAPPER_LINE_OFFSET, 1), lineCount);
71
+ const line = Math.min(Math.max(parserLocation.line - SYNTAX_PARSE_WRAPPER_LINE_OFFSET - (options.userCodeLineOffset ?? 0), 1), lineCount);
72
72
  return {
73
73
  column: parserLocation.column,
74
74
  line,
@@ -76,9 +76,9 @@ async function getSyntaxErrorLocation(code, error) {
76
76
  }
77
77
  return undefined;
78
78
  }
79
- function formatLocationSuffix(location) {
79
+ function formatLocationSuffix(location, locationLabel) {
80
80
  const columnText = location.column != null ? `, column ${location.column}` : '';
81
- return `Code node line ${location.line}${columnText}`;
81
+ return `${locationLabel} line ${location.line}${columnText}`;
82
82
  }
83
83
  function replaceStackHeader(stack, error) {
84
84
  if (!stack) {
@@ -90,15 +90,21 @@ function replaceStackHeader(stack, error) {
90
90
  }
91
91
  export async function enrichCodeNodeErrorWithLocation(params) {
92
92
  const originalError = getError(params.error);
93
+ const userCodeLineOffset = params.userCodeLineOffset ?? 0;
93
94
  const location = getRuntimeErrorLocationFromStack({
94
95
  code: params.code,
95
96
  error: originalError,
96
97
  sourceUrl: params.sourceUrl,
97
- }) ?? (await getSyntaxErrorLocation(params.code, originalError));
98
+ userCodeLineOffset,
99
+ }) ??
100
+ (await getSyntaxErrorLocation(params.code, originalError, {
101
+ diagnosticCode: params.diagnosticCode,
102
+ userCodeLineOffset,
103
+ }));
98
104
  if (!location) {
99
105
  return originalError;
100
106
  }
101
- originalError.message = `${originalError.message} (${formatLocationSuffix(location)})`;
107
+ originalError.message = `${originalError.message} (${formatLocationSuffix(location, params.locationLabel ?? 'Code node')})`;
102
108
  originalError.stack = replaceStackHeader(originalError.stack, originalError);
103
109
  return originalError;
104
110
  }
@@ -1,7 +1,5 @@
1
1
  import { dedent } from 'ts-dedent';
2
- import { getError } from '../../utils/errors.js';
3
- import { createInterpolationInputDefinition } from '../interpolationInputDefinition.js';
4
- import { buildClonedInputValueAssignments, buildCloneJsInputValueFunction, buildJsValueInterpolatedSource, getJsValueInterpolationInputNames, interpolateJsValuePreviewSource, sanitizeGeneratedJsValueText, } from './jsValueInterpolation.js';
2
+ import { buildClonedInputValueAssignments, buildJsValueInterpolatedSource, buildJsValueInputClonePreamble, buildJsValuePreview, getJsValueInterpolationInputDefinitions, getJsValueInterpolationRuntimeContext, interpolateJsValuePreviewSource, sanitizeGeneratedJsValueError, } from './jsValueInterpolation.js';
5
3
  const MAX_CALLBACK_PREVIEW_BODY_LINES = 13;
6
4
  const JS_LIST_CALLBACK_SIGNATURE = '(item, index, array)';
7
5
  export const JS_LIST_CALLBACK_LOCAL_NAMES = new Set(['item', 'index', 'array']);
@@ -28,41 +26,38 @@ export function assertSynchronousCallbackResult(result, nodeName) {
28
26
  throw new Error(`${nodeName} callbacks must be synchronous.`);
29
27
  }
30
28
  }
31
- function getJSListCallbackInterpolationInputNames(callbackBody) {
32
- return getJsValueInterpolationInputNames(callbackBody, {
29
+ function getJSListInterpolationContext(callbackBody) {
30
+ return getJsValueInterpolationRuntimeContext(callbackBody, JS_LIST_INPUTS_IDENTIFIER, {
33
31
  localIdentifiers: JS_LIST_CALLBACK_LOCAL_NAMES,
34
32
  });
35
33
  }
36
- function buildJSListRuntimePreamble(callbackBody) {
37
- const inputNames = getJSListCallbackInterpolationInputNames(callbackBody);
34
+ function buildJSListRuntimePreamble(interpolationContext) {
38
35
  return dedent `
39
36
  const assertSynchronousCallbackResult = ${assertSynchronousCallbackResult.toString()};
40
- ${buildCloneJsInputValueFunction()}
41
- const ${JS_LIST_INPUTS_IDENTIFIER} = Object.create(null);
42
- const ${JS_LIST_INPUT_CLONE_CACHE_IDENTIFIER} = new WeakMap();
37
+ ${buildJsValueInputClonePreamble({
38
+ cacheIdentifier: JS_LIST_INPUT_CLONE_CACHE_IDENTIFIER,
39
+ inputsIdentifier: interpolationContext.inputsIdentifier,
40
+ })}
43
41
  const array = cloneJsInputValue(inputs.array?.value, ${JS_LIST_INPUT_CLONE_CACHE_IDENTIFIER});
44
- ${buildClonedInputValueAssignments(inputNames, JS_LIST_INPUTS_IDENTIFIER, JS_LIST_INPUT_CLONE_CACHE_IDENTIFIER)}
42
+ ${buildClonedInputValueAssignments(interpolationContext.inputNames, interpolationContext.inputsIdentifier, JS_LIST_INPUT_CLONE_CACHE_IDENTIFIER)}
45
43
  `;
46
44
  }
47
- function buildJSListCallbackRuntimeSource(callbackBody) {
48
- return buildJsValueInterpolatedSource(callbackBody, JS_LIST_INPUTS_IDENTIFIER, {
45
+ function buildJSListCallbackRuntimeSource(callbackBody, inputsIdentifier) {
46
+ return buildJsValueInterpolatedSource(callbackBody, inputsIdentifier, {
49
47
  localIdentifiers: JS_LIST_CALLBACK_LOCAL_NAMES,
50
48
  });
51
49
  }
52
50
  function sanitizeJSListError(error, callbackBody, nodeName) {
53
- const jsListError = getError(error);
54
- const inputNames = getJSListCallbackInterpolationInputNames(callbackBody);
51
+ const { inputNames, inputsIdentifier } = getJSListInterpolationContext(callbackBody);
55
52
  const fallbackLabel = `${nodeName} input`;
56
- jsListError.message =
57
- sanitizeGeneratedJsValueText(jsListError.message, inputNames, JS_LIST_INPUTS_IDENTIFIER, fallbackLabel) ??
58
- jsListError.message;
59
- jsListError.stack = sanitizeGeneratedJsValueText(jsListError.stack, inputNames, JS_LIST_INPUTS_IDENTIFIER, fallbackLabel);
60
- return jsListError;
53
+ return sanitizeGeneratedJsValueError(error, inputNames, inputsIdentifier, fallbackLabel);
61
54
  }
62
55
  export function buildJSFilterWrapper(callbackBody) {
63
- const callbackBodySource = buildJSListCallbackRuntimeSource(callbackBody);
56
+ const interpolationContext = getJSListInterpolationContext(callbackBody);
57
+ const { inputsIdentifier } = interpolationContext;
58
+ const callbackBodySource = buildJSListCallbackRuntimeSource(callbackBody, inputsIdentifier);
64
59
  return dedent `
65
- ${buildJSListRuntimePreamble(callbackBody)}
60
+ ${buildJSListRuntimePreamble(interpolationContext)}
66
61
 
67
62
  if (!Array.isArray(array)) {
68
63
  throw new Error('JS Filter input "array" must be an array.');
@@ -95,9 +90,11 @@ export function buildJSFilterWrapper(callbackBody) {
95
90
  `;
96
91
  }
97
92
  export function buildJSMapWrapper(callbackBody) {
98
- const callbackBodySource = buildJSListCallbackRuntimeSource(callbackBody);
93
+ const interpolationContext = getJSListInterpolationContext(callbackBody);
94
+ const { inputsIdentifier } = interpolationContext;
95
+ const callbackBodySource = buildJSListCallbackRuntimeSource(callbackBody, inputsIdentifier);
99
96
  return dedent `
100
- ${buildJSListRuntimePreamble(callbackBody)}
97
+ ${buildJSListRuntimePreamble(interpolationContext)}
101
98
 
102
99
  if (!Array.isArray(array)) {
103
100
  throw new Error('JS Map input "array" must be an array.');
@@ -127,11 +124,9 @@ export function buildJSMapWrapper(callbackBody) {
127
124
  `;
128
125
  }
129
126
  export function getJSListCallbackInterpolationInputDefinitions(callbackBody) {
130
- return getJSListCallbackInterpolationInputNames(callbackBody).map((inputName) => createInterpolationInputDefinition({
131
- interpolationName: inputName,
132
- dataType: 'any',
133
- required: false,
134
- }));
127
+ return getJsValueInterpolationInputDefinitions(callbackBody, {
128
+ localIdentifiers: JS_LIST_CALLBACK_LOCAL_NAMES,
129
+ });
135
130
  }
136
131
  export function getJSListInputDefinitions(callbackBody) {
137
132
  return [
@@ -153,6 +148,7 @@ export function getJSListEditors() {
153
148
  postEditorHelperMessage: '};\n\n//Use {{var}} to create input ports that evaluate as connected values.',
154
149
  dataKey: 'callbackBody',
155
150
  language: 'javascript',
151
+ interpolationSyntax: 'js-value',
156
152
  enableFolding: true,
157
153
  },
158
154
  ];
@@ -163,7 +159,7 @@ export function interpolateJSListCallbackBody(callbackBody, inputs) {
163
159
  });
164
160
  }
165
161
  export function getJSListNodeBody(callbackBody) {
166
- const previewBody = callbackBody.split('\n').slice(0, MAX_CALLBACK_PREVIEW_BODY_LINES).join('\n').trim();
162
+ const previewBody = buildJsValuePreview(callbackBody, MAX_CALLBACK_PREVIEW_BODY_LINES);
167
163
  return {
168
164
  type: 'colorized',
169
165
  text: dedent `