@valerypopoff/rivet2-core 2.13.0 → 2.15.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.
Files changed (48) hide show
  1. package/dist/cjs/bundle.cjs +2485 -425
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/api/createProcessor.js +5 -0
  4. package/dist/esm/api/processSettings.js +1 -0
  5. package/dist/esm/exports.js +4 -0
  6. package/dist/esm/model/GraphProcessor.js +10 -16
  7. package/dist/esm/model/MarkdownSanitizationPolicy.js +2 -0
  8. package/dist/esm/model/NodeImpl.js +1 -1
  9. package/dist/esm/model/Nodes.js +6 -0
  10. package/dist/esm/model/StreamingWatchTopology.js +98 -61
  11. package/dist/esm/model/classifier/credentials.js +81 -0
  12. package/dist/esm/model/classifier/migration.js +97 -0
  13. package/dist/esm/model/classifier/providers.js +347 -0
  14. package/dist/esm/model/classifier/questionHelpers.js +125 -0
  15. package/dist/esm/model/classifier/types.js +1 -0
  16. package/dist/esm/model/nodeBodyMarkdown.js +37 -0
  17. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +392 -0
  18. package/dist/esm/model/nodes/ClassifierQuestionNode.js +569 -0
  19. package/dist/esm/model/nodes/CodeNewNode.js +33 -9
  20. package/dist/esm/model/nodes/LLMChatV2Node.js +3 -12
  21. package/dist/esm/model/nodes/LLMProfileNode.js +6 -12
  22. package/dist/esm/model/nodes/MatchCaseNode.js +76 -1
  23. package/dist/esm/model/nodes/MatchCaseNodeBase.js +24 -2
  24. package/dist/esm/model/nodes/ObjectNode.js +48 -41
  25. package/dist/esm/model/nodes/PassthroughNode.js +1 -1
  26. package/dist/esm/model/nodes/codeOutputInference.js +292 -0
  27. package/dist/esm/utils/serialization/serialization.js +4 -0
  28. package/dist/types/exports.d.ts +4 -0
  29. package/dist/types/model/EditorDefinition.d.ts +24 -0
  30. package/dist/types/model/MarkdownSanitizationPolicy.d.ts +1 -1
  31. package/dist/types/model/NodeImpl.d.ts +3 -1
  32. package/dist/types/model/Nodes.d.ts +6 -4
  33. package/dist/types/model/Settings.d.ts +4 -0
  34. package/dist/types/model/StreamingWatchTopology.d.ts +6 -0
  35. package/dist/types/model/classifier/credentials.d.ts +24 -0
  36. package/dist/types/model/classifier/migration.d.ts +18 -0
  37. package/dist/types/model/classifier/providers.d.ts +78 -0
  38. package/dist/types/model/classifier/questionHelpers.d.ts +31 -0
  39. package/dist/types/model/classifier/types.d.ts +58 -0
  40. package/dist/types/model/nodeBodyMarkdown.d.ts +19 -0
  41. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +47 -0
  42. package/dist/types/model/nodes/ClassifierQuestionNode.d.ts +60 -0
  43. package/dist/types/model/nodes/CodeNewNode.d.ts +6 -0
  44. package/dist/types/model/nodes/MatchCaseNode.d.ts +8 -1
  45. package/dist/types/model/nodes/MatchCaseNodeBase.d.ts +13 -1
  46. package/dist/types/model/nodes/ObjectNode.d.ts +5 -0
  47. package/dist/types/model/nodes/codeOutputInference.d.ts +31 -0
  48. package/package.json +1 -1
@@ -2,6 +2,7 @@ import { nanoid } from 'nanoid/non-secure';
2
2
  import { dedent } from 'ts-dedent';
3
3
  import { nodeDefinition } from '../NodeDefinition.js';
4
4
  import { NodeImpl } from '../NodeImpl.js';
5
+ import { formatNodeBodyMarkdownField, formatNodeBodyMarkdownLabel } from '../nodeBodyMarkdown.js';
5
6
  import { getCommonChatV2Inputs, getCommonChatV2Outputs } from '../chat-v2/chatV2Shared.js';
6
7
  import { getLLMChatV2Editors } from '../chat-v2/llmChatV2NodeEditors.js';
7
8
  import { createLLMChatV2NodeData, shouldIncludeLLMChatV2ToolCalls, } from '../chat-v2/llmChatV2NodeData.js';
@@ -19,18 +20,8 @@ export { buildLLMChatV2EditorCacheKey, resolveLLMChatV2RuntimeProviderOptions };
19
20
  function usesBaseURLInput(data) {
20
21
  return data.provider === 'custom' && data.useCustomProviderBaseURLInput;
21
22
  }
22
- function escapeMarkdownInline(value) {
23
- return value
24
- .replace(/\r/g, '\\r')
25
- .replace(/\n/g, '\\n')
26
- .replace(/&/g, '&')
27
- .replace(/</g, '&lt;')
28
- .replace(/>/g, '&gt;')
29
- .replace(/"/g, '&quot;')
30
- .replace(/([\\`*_[\]{}()#+\-.!|])/g, '\\$1');
31
- }
32
23
  function getBodyLine(label, value) {
33
- return `<span style="opacity: 0.55">${label}:</span> ${escapeMarkdownInline(value)}`;
24
+ return formatNodeBodyMarkdownField(label, value);
34
25
  }
35
26
  function escapeMarkdownPreformatted(value) {
36
27
  return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@@ -40,7 +31,7 @@ function getBodySectionText(section) {
40
31
  ...section.fields.map((field) => getBodyLine(field.label, field.value)),
41
32
  ...(section.snippet
42
33
  ? [
43
- `<span style="opacity: 0.55">${section.snippet.label}:</span>`,
34
+ formatNodeBodyMarkdownLabel(section.snippet.label),
44
35
  `<pre>${escapeMarkdownPreformatted(section.snippet.text)}</pre>`,
45
36
  ]
46
37
  : []),
@@ -1,22 +1,13 @@
1
1
  import { nanoid } from 'nanoid/non-secure';
2
2
  import { nodeDefinition } from '../NodeDefinition.js';
3
3
  import { NodeImpl } from '../NodeImpl.js';
4
+ import { formatNodeBodyMarkdownField, formatNodeBodyMarkdownLabel } from '../nodeBodyMarkdown.js';
4
5
  import { getLLMProfileEditors } from '../chat-v2/llmChatV2NodeEditors.js';
5
6
  import { getLLMProfileBodySections } from '../chat-v2/llmProfileBody.js';
6
7
  import { resolveLLMProfileNodeValue } from '../chat-v2/llmProfileNodeRuntime.js';
7
8
  import { createLLMProfileNodeData } from '../chat-v2/llmProfileTypes.js';
8
- function escapeMarkdownInline(value) {
9
- return String(value)
10
- .replace(/\r/g, '\\r')
11
- .replace(/\n/g, '\\n')
12
- .replace(/&/g, '&amp;')
13
- .replace(/</g, '&lt;')
14
- .replace(/>/g, '&gt;')
15
- .replace(/"/g, '&quot;')
16
- .replace(/([\\`*_[\]{}()#+\-.!|])/g, '\\$1');
17
- }
18
9
  function getBodyLine(label, value) {
19
- return `<span style="opacity: 0.55">${label}:</span> ${escapeMarkdownInline(value)}`;
10
+ return formatNodeBodyMarkdownField(label, value);
20
11
  }
21
12
  export class LLMProfileNodeImpl extends NodeImpl {
22
13
  static create() {
@@ -120,7 +111,7 @@ export class LLMProfileNodeImpl extends NodeImpl {
120
111
  .map((section) => {
121
112
  const fields = section.fields.map((field) => getBodyLine(field.label, field.value));
122
113
  const snippet = section.snippet
123
- ? `${getBodyLine(section.snippet.label, '')}\n${escapeMarkdownInline(section.snippet.text)}`
114
+ ? `${formatNodeBodyMarkdownLabel(section.snippet.label)}\n<pre>${escapeHtml(section.snippet.text)}</pre>`
124
115
  : undefined;
125
116
  return [...fields, ...(snippet ? [snippet] : [])].join('\n');
126
117
  })
@@ -148,4 +139,7 @@ export class LLMProfileNodeImpl extends NodeImpl {
148
139
  };
149
140
  }
150
141
  }
142
+ function escapeHtml(value) {
143
+ return String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
144
+ }
151
145
  export const llmProfileNode = nodeDefinition(LLMProfileNodeImpl, 'LLM Profile');
@@ -4,11 +4,45 @@ import { nodeDefinition } from '../NodeDefinition.js';
4
4
  import {} from '../NodeImpl.js';
5
5
  import {} from '../NodeBase.js';
6
6
  import {} from '../EditorDefinition.js';
7
+ import {} from '../GraphProcessor.js';
8
+ import {} from '../ProcessContext.js';
9
+ import {} from '../DataValue.js';
10
+ import { extractInterpolationVariableReferences, getInterpolationGlobalValues, interpolate, } from '../../utils/interpolation.js';
11
+ import { createInterpolationInputDefinition } from '../interpolationInputDefinition.js';
7
12
  import { MatchCaseNodeBase, } from './MatchCaseNodeBase.js';
13
+ const MATCH_CASE_INTERPOLATION_INPUT_PREFIX = 'input-';
14
+ /**
15
+ * Discovers case-template inputs without joining case strings, so an incomplete
16
+ * token at one row boundary can never become a token in a neighboring row.
17
+ */
18
+ function getMatchCaseInterpolationVariableReferences(cases) {
19
+ const references = new Map();
20
+ for (const caseValue of cases) {
21
+ for (const reference of extractInterpolationVariableReferences(caseValue)) {
22
+ const existing = references.get(reference.baseName);
23
+ if (existing) {
24
+ existing.hasPath ||= reference.hasPath;
25
+ }
26
+ else {
27
+ references.set(reference.baseName, { ...reference });
28
+ }
29
+ }
30
+ }
31
+ return Array.from(references.values(), (reference) => ({ ...reference }));
32
+ }
33
+ function getMatchCaseInterpolationInputId(name) {
34
+ return `${MATCH_CASE_INTERPOLATION_INPUT_PREFIX}${name}`;
35
+ }
36
+ function getMatchCaseInterpolationInputs(references, inputs) {
37
+ return Object.fromEntries(references.map(({ baseName }) => [baseName, inputs[getMatchCaseInterpolationInputId(baseName)]]));
38
+ }
8
39
  /** Match case is the current routing node; legacy `match` remains regex-only. */
9
40
  export class MatchCaseNodeImpl extends MatchCaseNodeBase {
10
41
  caseEditorLabel = 'Cases';
11
42
  caseEditorPlaceholder = 'Case';
43
+ caseEditorHighlightsInterpolation = true;
44
+ caseEditorInputFontFamily = 'monospace';
45
+ caseEditorBoxed = true;
12
46
  casesEditorPlacement = 'before-trigger';
13
47
  customCaseValuesEditorLabel = '';
14
48
  defaultExclusive = true;
@@ -88,12 +122,52 @@ export class MatchCaseNodeImpl extends MatchCaseNodeBase {
88
122
  shouldHideCustomCaseValues(data) {
89
123
  return (data.returnValue ?? 'true') !== 'custom';
90
124
  }
125
+ getInterpolationInputDefinitions() {
126
+ return getMatchCaseInterpolationVariableReferences(this.data.cases).map(({ baseName, hasPath }) => createInterpolationInputDefinition({
127
+ id: getMatchCaseInterpolationInputId(baseName),
128
+ interpolationName: baseName,
129
+ dataType: hasPath ? 'any' : 'string',
130
+ required: false,
131
+ description: `The value substituted for {{${baseName}}} in Cases.`,
132
+ }));
133
+ }
134
+ resolveCaseValues(inputs, context) {
135
+ const references = getMatchCaseInterpolationVariableReferences(this.data.cases);
136
+ if (references.length === 0 && !this.data.cases.some((caseValue) => caseValue.includes('{{'))) {
137
+ return this.data.cases;
138
+ }
139
+ const globalValueCache = new Map();
140
+ const missingGlobalIds = new Set();
141
+ const getCachedGlobal = (id) => {
142
+ if (globalValueCache.has(id)) {
143
+ return globalValueCache.get(id);
144
+ }
145
+ if (missingGlobalIds.has(id)) {
146
+ return undefined;
147
+ }
148
+ const value = context?.getGlobal?.(id);
149
+ if (value === undefined) {
150
+ missingGlobalIds.add(id);
151
+ }
152
+ else {
153
+ globalValueCache.set(id, value);
154
+ }
155
+ return value;
156
+ };
157
+ const interpolationInputs = getMatchCaseInterpolationInputs(references, inputs);
158
+ return this.data.cases.map((caseValue) => interpolate(caseValue, interpolationInputs, context?.graphInputNodeValues, context?.contextValues, {
159
+ coerceBareVariableDataValues: true,
160
+ globalValues: getInterpolationGlobalValues(caseValue, getCachedGlobal),
161
+ }));
162
+ }
91
163
  getEditors() {
92
164
  return [
93
165
  {
94
166
  type: 'segmented',
95
167
  label: 'Match mode',
96
168
  dataKey: 'matchMode',
169
+ layout: 'inline',
170
+ allowOptionWrap: false,
97
171
  defaultValue: 'plainText',
98
172
  options: [
99
173
  { value: 'plainText', label: 'Plain text' },
@@ -104,6 +178,7 @@ export class MatchCaseNodeImpl extends MatchCaseNodeBase {
104
178
  type: 'toggle',
105
179
  label: 'Case sensitive',
106
180
  dataKey: 'caseSensitive',
181
+ layout: 'inline',
107
182
  defaultValue: true,
108
183
  hideIf: (data) => data.matchMode === 'regex',
109
184
  },
@@ -113,7 +188,7 @@ export class MatchCaseNodeImpl extends MatchCaseNodeBase {
113
188
  static getUIData() {
114
189
  return {
115
190
  infoBoxBody: dedent `
116
- Routes an Input value to matching case outputs. Plain text cases use exact, case-sensitive equality by default; turn off Case sensitive to ignore letter case. Choose Regular expression to use the existing JavaScript RegExp pattern behavior; the Case sensitive switch does not apply in that mode.
191
+ Routes an Input value to matching case outputs. Plain text cases use exact, case-sensitive equality by default; turn off Case sensitive to ignore letter case. Choose Regular expression to use the existing JavaScript RegExp pattern behavior; the Case sensitive switch does not apply in that mode. Cases support {{variable}} interpolation, JSONPath, and the @graphInputs, @context, and @globals runtime roots; ordinary variables create optional inputs.
117
192
 
118
193
  Choose First matching case to trigger only the first matching output, or All matching cases to trigger every matching output. Active outputs return True by default. They can instead return the Input value, or a custom value supplied through one shared Output value input or separate Output values inputs for every case and Unmatched.
119
194
  `,
@@ -1,6 +1,7 @@
1
1
  import {} from '../DataValue.js';
2
2
  import {} from '../EditorDefinition.js';
3
3
  import {} from '../GraphProcessor.js';
4
+ import {} from '../ProcessContext.js';
4
5
  import { NodeImpl } from '../NodeImpl.js';
5
6
  import {} from '../NodeBase.js';
6
7
  import { coerceType } from '../../utils/coerceType.js';
@@ -11,6 +12,10 @@ import { resolveStoredOrderedPortIds } from '../../utils/orderedStringPortIds.js
11
12
  * only its matching semantics and editor wording.
12
13
  */
13
14
  export class MatchCaseNodeBase extends NodeImpl {
15
+ caseEditorHelperMessage = undefined;
16
+ caseEditorHighlightsInterpolation = false;
17
+ caseEditorInputFontFamily = undefined;
18
+ caseEditorBoxed = false;
14
19
  casesEditorPlacement = 'after-custom-values';
15
20
  customCaseValuesEditorLabel = 'Custom case values';
16
21
  defaultExclusive = false;
@@ -31,6 +36,17 @@ export class MatchCaseNodeBase extends NodeImpl {
31
36
  shouldHideCustomCaseValues(_data) {
32
37
  return false;
33
38
  }
39
+ /**
40
+ * Current Match case resolves its saved case templates at execution time.
41
+ * The legacy Regex Match node deliberately leaves its saved expressions raw.
42
+ */
43
+ resolveCaseValues(_inputs, _context) {
44
+ return this.data.cases;
45
+ }
46
+ /** Additional inputs that sit between the tested value and custom return values. */
47
+ getInterpolationInputDefinitions() {
48
+ return [];
49
+ }
34
50
  getInputDefinitions() {
35
51
  const inputs = [
36
52
  {
@@ -41,6 +57,7 @@ export class MatchCaseNodeBase extends NodeImpl {
41
57
  description: `The ${this.inputTitle} value tested against each case.`,
42
58
  },
43
59
  ];
60
+ inputs.push(...this.getInterpolationInputDefinitions());
44
61
  if (this.getReturnValueMode() !== 'custom') {
45
62
  return inputs;
46
63
  }
@@ -103,6 +120,10 @@ export class MatchCaseNodeBase extends NodeImpl {
103
120
  dataKey: 'cases',
104
121
  label: this.caseEditorLabel,
105
122
  placeholder: this.caseEditorPlaceholder,
123
+ helperMessage: this.caseEditorHelperMessage,
124
+ highlightInterpolationTokens: this.caseEditorHighlightsInterpolation,
125
+ inputFontFamily: this.caseEditorInputFontFamily,
126
+ boxed: this.caseEditorBoxed,
106
127
  reorderable: true,
107
128
  portBinding: {
108
129
  side: 'output',
@@ -141,12 +162,13 @@ export class MatchCaseNodeBase extends NodeImpl {
141
162
  ...(this.casesEditorPlacement === 'after-custom-values' ? [casesEditor] : []),
142
163
  ];
143
164
  }
144
- async process(inputs) {
165
+ async process(inputs, context) {
145
166
  const inputValue = inputs['input'];
146
167
  const inputString = inputValue?.value == null ? undefined : coerceType(inputValue, 'string');
147
168
  const portIds = this.getCasePortIds();
148
169
  const sharedValue = inputs['value'];
149
170
  const returnValueMode = this.getReturnValueMode();
171
+ const resolvedCaseValues = this.resolveCaseValues(inputs, context);
150
172
  const getInputOutputValue = () => ({
151
173
  type: 'string',
152
174
  value: inputString,
@@ -168,7 +190,7 @@ export class MatchCaseNodeBase extends NodeImpl {
168
190
  let matched = false;
169
191
  const output = {};
170
192
  for (let index = 0; index < this.data.cases.length; index++) {
171
- const caseValue = this.data.cases[index];
193
+ const caseValue = resolvedCaseValues[index] ?? this.data.cases[index];
172
194
  const matches = inputString !== undefined && this.matchesCase(inputString, caseValue);
173
195
  const canMatch = !this.getExclusive() || !matched;
174
196
  const portId = portIds[index];
@@ -48,6 +48,53 @@ function stringifyEmbeddedJsonStringFragment(value) {
48
48
  const fragment = value == null ? 'null' : typeof value === 'string' ? value : JSON.stringify(value) ?? 'null';
49
49
  return JSON.stringify(fragment).slice(1, -1);
50
50
  }
51
+ /**
52
+ * Interpolates a JSON template without parsing it. Shared by Object and other
53
+ * first-party nodes which author structured EntryType values.
54
+ */
55
+ export function interpolateJsonTemplate(baseString, values, graphInputNodeValues, contextValues, globalValues) {
56
+ const protectedBaseString = protectEscapedInterpolationTokens(baseString);
57
+ const parsedTemplate = parseInterpolationTemplate(protectedBaseString);
58
+ if (parsedTemplate.tokens.length === 0) {
59
+ return restoreEscapedInterpolationTokens(protectedBaseString);
60
+ }
61
+ let result = '';
62
+ let cursor = 0;
63
+ for (const token of parsedTemplate.tokens) {
64
+ const tokenSpan = token.span;
65
+ const isInsideString = isInsideJsonString(protectedBaseString, tokenSpan.start);
66
+ const isWholeQuotedToken = isInsideString &&
67
+ isUnescapedQuoteAt(protectedBaseString, tokenSpan.start - 1) &&
68
+ isUnescapedQuoteAt(protectedBaseString, tokenSpan.end);
69
+ const replacementStart = isWholeQuotedToken ? tokenSpan.start - 1 : tokenSpan.start;
70
+ const replacementEnd = isWholeQuotedToken ? tokenSpan.end + 1 : tokenSpan.end;
71
+ const value = token.reference
72
+ ? resolveInterpolationExpressionRawValue(token.reference, {
73
+ variables: values,
74
+ graphInputValues: graphInputNodeValues,
75
+ contextValues,
76
+ globalValues,
77
+ unwrapVariableDataValues: false,
78
+ })
79
+ : undefined;
80
+ // Restore escaped delimiters only from the authored JSON template. An
81
+ // interpolated string may itself contain literal interpolation syntax and
82
+ // must not be processed again while the final JSON is assembled.
83
+ result += restoreEscapedInterpolationTokens(protectedBaseString.slice(cursor, replacementStart));
84
+ if (isInsideString && !isWholeQuotedToken) {
85
+ result += stringifyEmbeddedJsonStringFragment(value);
86
+ }
87
+ else if (isWholeQuotedToken) {
88
+ result += stringifyWholeQuotedJsonValue(value);
89
+ }
90
+ else {
91
+ result += stringifyJsonValue(value);
92
+ }
93
+ cursor = replacementEnd;
94
+ }
95
+ result += restoreEscapedInterpolationTokens(protectedBaseString.slice(cursor));
96
+ return result;
97
+ }
51
98
  export class ObjectNodeImpl extends NodeImpl {
52
99
  static create() {
53
100
  const chartNode = {
@@ -117,47 +164,7 @@ export class ObjectNodeImpl extends NodeImpl {
117
164
  };
118
165
  }
119
166
  interpolate(baseString, values, graphInputNodeValues, contextValues, globalValues) {
120
- const protectedBaseString = protectEscapedInterpolationTokens(baseString);
121
- const parsedTemplate = parseInterpolationTemplate(protectedBaseString);
122
- if (parsedTemplate.tokens.length === 0) {
123
- return restoreEscapedInterpolationTokens(protectedBaseString);
124
- }
125
- let result = '';
126
- let cursor = 0;
127
- for (const token of parsedTemplate.tokens) {
128
- const tokenSpan = token.span;
129
- const isInsideString = isInsideJsonString(protectedBaseString, tokenSpan.start);
130
- const isWholeQuotedToken = isInsideString &&
131
- isUnescapedQuoteAt(protectedBaseString, tokenSpan.start - 1) &&
132
- isUnescapedQuoteAt(protectedBaseString, tokenSpan.end);
133
- const replacementStart = isWholeQuotedToken ? tokenSpan.start - 1 : tokenSpan.start;
134
- const replacementEnd = isWholeQuotedToken ? tokenSpan.end + 1 : tokenSpan.end;
135
- const value = token.reference
136
- ? resolveInterpolationExpressionRawValue(token.reference, {
137
- variables: values,
138
- graphInputValues: graphInputNodeValues,
139
- contextValues,
140
- globalValues,
141
- unwrapVariableDataValues: false,
142
- })
143
- : undefined;
144
- // Restore escaped delimiters only from the authored JSON template. An
145
- // interpolated string may itself contain literal interpolation syntax and
146
- // must not be processed again while the final JSON is assembled.
147
- result += restoreEscapedInterpolationTokens(protectedBaseString.slice(cursor, replacementStart));
148
- if (isInsideString && !isWholeQuotedToken) {
149
- result += stringifyEmbeddedJsonStringFragment(value);
150
- }
151
- else if (isWholeQuotedToken) {
152
- result += stringifyWholeQuotedJsonValue(value);
153
- }
154
- else {
155
- result += stringifyJsonValue(value);
156
- }
157
- cursor = replacementEnd;
158
- }
159
- result += restoreEscapedInterpolationTokens(protectedBaseString.slice(cursor));
160
- return result;
167
+ return interpolateJsonTemplate(baseString, values, graphInputNodeValues, contextValues, globalValues);
161
168
  }
162
169
  async process(inputs, context) {
163
170
  const inputMap = Object.keys(inputs).reduce((acc, key) => {
@@ -32,7 +32,7 @@ export class PassthroughNodeImpl extends NodeImpl {
32
32
  visualData: {
33
33
  x: 0,
34
34
  y: 0,
35
- width: 175,
35
+ width: 190,
36
36
  },
37
37
  };
38
38
  return chartNode;
@@ -0,0 +1,292 @@
1
+ import { nanoid } from 'nanoid/non-secure';
2
+ import { parse } from 'acorn';
3
+ import { buildJsValueInterpolatedSource, getJsValueInterpolationRuntimeContext } from './jsValueInterpolation.js';
4
+ const cache = new Map();
5
+ const MAX_CACHED_SOURCES = 128;
6
+ const WRAPPER_PREFIX = 'async function __codeOutputs() {\n';
7
+ const TRAVERSAL_BOUNDARIES = new Set([
8
+ 'FunctionDeclaration',
9
+ 'FunctionExpression',
10
+ 'ArrowFunctionExpression',
11
+ 'ClassDeclaration',
12
+ 'ClassExpression',
13
+ ]);
14
+ function isAstNode(value) {
15
+ return value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string';
16
+ }
17
+ function getPropertyKey(property) {
18
+ if (property.type !== 'Property') {
19
+ return undefined;
20
+ }
21
+ const objectProperty = property;
22
+ if (objectProperty.computed || objectProperty.method || objectProperty.kind !== 'init')
23
+ return undefined;
24
+ const key = objectProperty.key;
25
+ if (key.type === 'Identifier') {
26
+ return { key: key.name, start: key.start, end: key.end };
27
+ }
28
+ return key.type === 'Literal' && ['string', 'number'].includes(typeof key.value)
29
+ ? { key: String(key.value), start: key.start, end: key.end }
30
+ : undefined;
31
+ }
32
+ function analyzeCodeOutputSyntax(code) {
33
+ const cached = cache.get(code);
34
+ if (cached) {
35
+ return cached;
36
+ }
37
+ let result;
38
+ try {
39
+ const source = buildJsValueInterpolatedSource(code, getJsValueInterpolationRuntimeContext(code, '__codeOutputInputs'), { trim: false });
40
+ const tree = parse(`${WRAPPER_PREFIX}${source}\n}`, { ecmaVersion: 'latest' });
41
+ const keys = new Set();
42
+ const occurrences = [];
43
+ const visit = (node) => {
44
+ if (TRAVERSAL_BOUNDARIES.has(node.type))
45
+ return;
46
+ if (node.type === 'ReturnStatement') {
47
+ const argument = node.argument;
48
+ if (argument?.type === 'ObjectExpression') {
49
+ for (const property of argument.properties) {
50
+ const key = getPropertyKey(property);
51
+ if (key === undefined)
52
+ continue;
53
+ keys.add(key.key);
54
+ occurrences.push({
55
+ key: key.key,
56
+ start: key.start - WRAPPER_PREFIX.length,
57
+ end: key.end - WRAPPER_PREFIX.length,
58
+ });
59
+ }
60
+ }
61
+ return;
62
+ }
63
+ for (const value of Object.values(node)) {
64
+ if (Array.isArray(value)) {
65
+ for (const child of value)
66
+ if (isAstNode(child))
67
+ visit(child);
68
+ }
69
+ else if (isAstNode(value)) {
70
+ visit(value);
71
+ }
72
+ }
73
+ };
74
+ // Enter only the wrapper body; nested functions remain traversal boundaries.
75
+ visit(tree.body[0].body);
76
+ result = Object.freeze({
77
+ valid: true,
78
+ keys: Object.freeze([...keys]),
79
+ occurrences: Object.freeze(occurrences.map((occurrence) => Object.freeze(occurrence))),
80
+ source,
81
+ });
82
+ }
83
+ catch {
84
+ result = Object.freeze({ valid: false });
85
+ }
86
+ if (cache.size >= MAX_CACHED_SOURCES) {
87
+ cache.delete(cache.keys().next().value);
88
+ }
89
+ cache.set(code, result);
90
+ return result;
91
+ }
92
+ /** Syntax-only analysis of explicit object returns in the authored function. */
93
+ export function analyzeCodeOutputs(code) {
94
+ const analysis = analyzeCodeOutputSyntax(code);
95
+ return analysis.valid ? Object.freeze({ valid: true, keys: analysis.keys }) : Object.freeze({ valid: false });
96
+ }
97
+ function sanitizeOutputFields(fieldsToSanitize) {
98
+ const seenIds = new Set();
99
+ const seenKeys = new Set();
100
+ const fields = [];
101
+ for (const field of fieldsToSanitize ?? []) {
102
+ if (typeof field?.id !== 'string' ||
103
+ !field.id.startsWith('field:') ||
104
+ typeof field.key !== 'string' ||
105
+ seenIds.has(field.id) ||
106
+ seenKeys.has(field.key)) {
107
+ continue;
108
+ }
109
+ seenIds.add(field.id);
110
+ seenKeys.add(field.key);
111
+ fields.push({ id: field.id, key: field.key });
112
+ }
113
+ return fields;
114
+ }
115
+ function getStoredOutputFields(data) {
116
+ return sanitizeOutputFields(data.inferredOutputFields);
117
+ }
118
+ function getLegacyOutputFields(keys) {
119
+ return [...new Set(keys.filter((key) => typeof key === 'string'))].map((key) => ({
120
+ id: `field:${key}`,
121
+ key,
122
+ }));
123
+ }
124
+ /** Resolves the displayed fields and their stable port identities without mutating node data. */
125
+ export function getCodeOutputFields(data) {
126
+ const analysis = analyzeCodeOutputSyntax(data.code);
127
+ const storedFields = getStoredOutputFields(data);
128
+ if (!analysis.valid) {
129
+ return storedFields.length > 0 ? storedFields : getLegacyOutputFields(data.inferredOutputKeys ?? []);
130
+ }
131
+ const storedFieldByKey = new Map(storedFields.map((field) => [field.key, field]));
132
+ return analysis.keys.map((key) => storedFieldByKey.get(key) ?? { id: `field:${key}`, key });
133
+ }
134
+ export function getCodeOutputKeys(data) {
135
+ return getCodeOutputFields(data).map((field) => field.key);
136
+ }
137
+ function getSingleTextChange(previous, next) {
138
+ let prefixLength = 0;
139
+ const sharedLength = Math.min(previous.length, next.length);
140
+ while (prefixLength < sharedLength && previous[prefixLength] === next[prefixLength]) {
141
+ prefixLength += 1;
142
+ }
143
+ let previousEnd = previous.length;
144
+ let nextEnd = next.length;
145
+ while (previousEnd > prefixLength && nextEnd > prefixLength && previous[previousEnd - 1] === next[nextEnd - 1]) {
146
+ previousEnd -= 1;
147
+ nextEnd -= 1;
148
+ }
149
+ if (prefixLength === previousEnd && prefixLength === nextEnd) {
150
+ return undefined;
151
+ }
152
+ return {
153
+ previousStart: prefixLength,
154
+ previousEnd,
155
+ nextStart: prefixLength,
156
+ nextEnd,
157
+ };
158
+ }
159
+ function isChangeWithinOccurrence(start, end, occurrence) {
160
+ return start >= occurrence.start && end <= occurrence.end;
161
+ }
162
+ /**
163
+ * A rename is safe only when the complete source change is confined to one
164
+ * explicit property key on each side. This deliberately rejects broad edits.
165
+ */
166
+ function getProvenOutputRename(previous, next) {
167
+ if (!previous.valid || !next.valid) {
168
+ return undefined;
169
+ }
170
+ const previousKeys = new Set(previous.keys);
171
+ const nextKeys = new Set(next.keys);
172
+ const removedKeys = previous.keys.filter((key) => !nextKeys.has(key));
173
+ const addedKeys = next.keys.filter((key) => !previousKeys.has(key));
174
+ if (removedKeys.length !== 1 || addedKeys.length !== 1) {
175
+ return undefined;
176
+ }
177
+ const oldKey = removedKeys[0];
178
+ const newKey = addedKeys[0];
179
+ const previousOccurrences = previous.occurrences.filter((occurrence) => occurrence.key === oldKey);
180
+ const nextOccurrences = next.occurrences.filter((occurrence) => occurrence.key === newKey);
181
+ if (previousOccurrences.length !== 1 || nextOccurrences.length !== 1) {
182
+ return undefined;
183
+ }
184
+ const change = getSingleTextChange(previous.source, next.source);
185
+ if (!change) {
186
+ return undefined;
187
+ }
188
+ return isChangeWithinOccurrence(change.previousStart, change.previousEnd, previousOccurrences[0]) &&
189
+ isChangeWithinOccurrence(change.nextStart, change.nextEnd, nextOccurrences[0])
190
+ ? { oldKey, newKey }
191
+ : undefined;
192
+ }
193
+ function createOutputFieldId(usedIds) {
194
+ let id;
195
+ do {
196
+ id = `field:${nanoid()}`;
197
+ } while (usedIds.has(id));
198
+ return id;
199
+ }
200
+ function getPreviousOutputFields(data) {
201
+ const storedFields = getStoredOutputFields(data);
202
+ return storedFields.length > 0 ? storedFields : [...getCodeOutputFields(data)];
203
+ }
204
+ function getRetiredOutputFields(data, activeFields) {
205
+ const activeIds = new Set(activeFields.map((field) => field.id));
206
+ const activeKeys = new Set(activeFields.map((field) => field.key));
207
+ return sanitizeOutputFields(data.inferredOutputRetiredFields).filter((field) => !activeIds.has(field.id) && !activeKeys.has(field.key));
208
+ }
209
+ const MAX_RETIRED_OUTPUT_FIELDS = 32;
210
+ function reconcileOutputFields(previous, nextAnalysis) {
211
+ const previousFields = getPreviousOutputFields(previous);
212
+ const previousFieldByKey = new Map(previousFields.map((field) => [field.key, field]));
213
+ const retiredFields = getRetiredOutputFields(previous, previousFields);
214
+ const retiredFieldByKey = new Map(retiredFields.map((field) => [field.key, field]));
215
+ const sourceForRename = previous.inferredOutputLastValidCode ?? previous.code;
216
+ const rename = getProvenOutputRename(analyzeCodeOutputSyntax(sourceForRename), nextAnalysis);
217
+ const usedIds = new Set([...previousFields, ...retiredFields].map((field) => field.id));
218
+ const fields = [];
219
+ const reusedRetiredKeys = new Set();
220
+ const renamedKeys = new Set();
221
+ for (const key of nextAnalysis.keys) {
222
+ const exactField = previousFieldByKey.get(key);
223
+ if (exactField) {
224
+ fields.push({ ...exactField });
225
+ continue;
226
+ }
227
+ const retiredField = retiredFieldByKey.get(key);
228
+ if (retiredField) {
229
+ fields.push({ ...retiredField });
230
+ reusedRetiredKeys.add(key);
231
+ continue;
232
+ }
233
+ const renamedField = rename?.newKey === key ? previousFieldByKey.get(rename.oldKey) : undefined;
234
+ if (renamedField && rename && !previousFieldByKey.has(key)) {
235
+ fields.push({ id: renamedField.id, key });
236
+ renamedKeys.add(rename.oldKey);
237
+ continue;
238
+ }
239
+ const id = createOutputFieldId(usedIds);
240
+ usedIds.add(id);
241
+ fields.push({ id, key });
242
+ }
243
+ const fieldKeys = new Set(fields.map((field) => field.key));
244
+ const fieldIds = new Set(fields.map((field) => field.id));
245
+ const newlyRetiredFields = previousFields.filter((field) => !fieldKeys.has(field.key) && !renamedKeys.has(field.key));
246
+ const nextRetiredFields = [
247
+ ...retiredFields.filter((field) => !reusedRetiredKeys.has(field.key)),
248
+ ...newlyRetiredFields,
249
+ ]
250
+ .filter((field, index, all) => !fieldIds.has(field.id) && all.findIndex((candidate) => candidate.id === field.id) === index)
251
+ .slice(-MAX_RETIRED_OUTPUT_FIELDS);
252
+ return {
253
+ inferredOutputFields: fields,
254
+ inferredOutputRetiredFields: nextRetiredFields,
255
+ };
256
+ }
257
+ function getLastValidCode(data) {
258
+ return analyzeCodeOutputSyntax(data.code).valid ? data.code : data.inferredOutputLastValidCode;
259
+ }
260
+ function withoutOutputMetadata(data) {
261
+ const { inferredOutputFields: _discardedFields, inferredOutputKeys: _discardedKeys, inferredOutputRetiredFields: _discardedRetiredFields, inferredOutputLastValidCode: _discardedLastValidCode, ...dataWithoutOutputMetadata } = data;
262
+ return dataWithoutOutputMetadata;
263
+ }
264
+ /**
265
+ * Prepares persisted output identities as part of an editor transaction.
266
+ * Valid source owns the visible fields. Invalid source retains the last valid
267
+ * identities and source so a completed key-only rename can still be proved.
268
+ */
269
+ export function prepareCodeOutputEdit(previous, patch) {
270
+ const next = { ...previous, ...patch };
271
+ const analysis = analyzeCodeOutputSyntax(next.code);
272
+ const nextWithoutOutputMetadata = withoutOutputMetadata(next);
273
+ if (analysis.valid) {
274
+ const { inferredOutputFields, inferredOutputRetiredFields } = reconcileOutputFields(previous, analysis);
275
+ return {
276
+ ...nextWithoutOutputMetadata,
277
+ inferredOutputFields,
278
+ inferredOutputKeys: inferredOutputFields.map((field) => field.key),
279
+ ...(inferredOutputRetiredFields.length > 0 ? { inferredOutputRetiredFields } : {}),
280
+ };
281
+ }
282
+ const inferredOutputFields = getPreviousOutputFields(previous);
283
+ const inferredOutputRetiredFields = getRetiredOutputFields(previous, inferredOutputFields);
284
+ const lastValidCode = getLastValidCode(previous);
285
+ return {
286
+ ...nextWithoutOutputMetadata,
287
+ inferredOutputFields,
288
+ inferredOutputKeys: inferredOutputFields.map((field) => field.key),
289
+ ...(inferredOutputRetiredFields.length > 0 ? { inferredOutputRetiredFields } : {}),
290
+ ...(lastValidCode ? { inferredOutputLastValidCode: lastValidCode } : {}),
291
+ };
292
+ }