@valerypopoff/rivet2-core 2.0.3 → 2.0.5

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.
@@ -5,13 +5,20 @@ import { nanoid } from 'nanoid/non-secure';
5
5
  import {} from '../GraphProcessor.js';
6
6
  import { dedent } from 'ts-dedent';
7
7
  import { nodeDefinition } from '../NodeDefinition.js';
8
+ import {} from '../EditorDefinition.js';
9
+ const INPUT_PORT_ID_PATTERN = /^input(\d+)$/;
10
+ const IGNORE_NULL_LABEL = "Ignore 'null'";
11
+ const IGNORE_UNDEFINED_LABEL = "Ignore 'undefined'";
8
12
  export class CoalesceNodeImpl extends NodeImpl {
9
13
  static create = () => {
10
14
  const chartNode = {
11
15
  type: 'coalesce',
12
16
  title: 'Coalesce',
13
17
  id: nanoid(),
14
- data: {},
18
+ data: {
19
+ ignoreNull: false,
20
+ ignoreUndefined: false,
21
+ },
15
22
  visualData: {
16
23
  x: 0,
17
24
  y: 0,
@@ -46,10 +53,36 @@ export class CoalesceNodeImpl extends NodeImpl {
46
53
  },
47
54
  ];
48
55
  }
56
+ getEditors() {
57
+ return [
58
+ {
59
+ type: 'toggle',
60
+ label: IGNORE_NULL_LABEL,
61
+ dataKey: 'ignoreNull',
62
+ },
63
+ {
64
+ type: 'toggle',
65
+ label: IGNORE_UNDEFINED_LABEL,
66
+ dataKey: 'ignoreUndefined',
67
+ },
68
+ ];
69
+ }
70
+ getBody() {
71
+ const ignoredValues = [];
72
+ if (this.data.ignoreNull) {
73
+ ignoredValues.push(IGNORE_NULL_LABEL);
74
+ }
75
+ if (this.data.ignoreUndefined) {
76
+ ignoredValues.push(IGNORE_UNDEFINED_LABEL);
77
+ }
78
+ return ignoredValues.length > 0 ? ignoredValues.join('\n') : undefined;
79
+ }
49
80
  static getUIData() {
50
81
  return {
51
82
  infoBoxBody: dedent `
52
- Takes in any number of inputs and outputs the first value that exists. Useful for consolidating branches after a Match node. This node can also "consume" the "Not Ran" value.
83
+ Takes in any number of inputs and outputs the first value that is not "Not Ran". Useful for consolidating branches after a Match node.
84
+
85
+ Null and undefined input values are emitted by default, but the node can be configured to skip either value and continue checking later inputs.
53
86
  `,
54
87
  infoBoxTitle: 'Coalesce Node',
55
88
  contextMenuTitle: 'Coalesce',
@@ -58,12 +91,14 @@ export class CoalesceNodeImpl extends NodeImpl {
58
91
  }
59
92
  #getInputPortCount(connections) {
60
93
  const inputNodeId = this.chartNode.id;
61
- const inputConnections = connections.filter((connection) => connection.inputNodeId === inputNodeId && connection.inputId.startsWith('input'));
62
94
  let maxInputNumber = 0;
63
- for (const connection of inputConnections) {
64
- const messageNumber = parseInt(connection.inputId.replace('input', ''), 10);
65
- if (messageNumber > maxInputNumber) {
66
- maxInputNumber = messageNumber;
95
+ for (const connection of connections) {
96
+ if (connection.inputNodeId !== inputNodeId) {
97
+ continue;
98
+ }
99
+ const inputNumber = this.#getInputPortNumber(connection.inputId);
100
+ if (inputNumber && inputNumber > maxInputNumber) {
101
+ maxInputNumber = inputNumber;
67
102
  }
68
103
  }
69
104
  return maxInputNumber + 1;
@@ -80,25 +115,43 @@ export class CoalesceNodeImpl extends NodeImpl {
80
115
  },
81
116
  };
82
117
  }
83
- const inputCount = Object.keys(inputData).filter((key) => key.startsWith('input')).length;
84
- const okInputValues = [];
118
+ const inputCount = this.#getInputCountFromValues(inputData);
85
119
  for (let i = 1; i <= inputCount; i++) {
86
120
  const inputValue = inputData[`input${i}`];
87
- if (inputValue && inputValue.type !== 'control-flow-excluded' && unwrapDataValue(inputValue) != null) {
88
- okInputValues.push(inputValue);
121
+ if (inputValue && inputValue.type !== 'control-flow-excluded' && !this.#shouldSkipInputValue(inputValue)) {
122
+ return {
123
+ ['output']: inputValue,
124
+ };
89
125
  }
90
126
  }
91
- if (okInputValues.length === 0) {
92
- return {
93
- ['output']: {
94
- type: 'control-flow-excluded',
95
- value: undefined,
96
- },
97
- };
98
- }
99
127
  return {
100
- ['output']: okInputValues[0],
128
+ ['output']: {
129
+ type: 'control-flow-excluded',
130
+ value: undefined,
131
+ },
101
132
  };
102
133
  }
134
+ #getInputCountFromValues(inputData) {
135
+ let maxInputNumber = 0;
136
+ for (const inputId of Object.keys(inputData)) {
137
+ const inputNumber = this.#getInputPortNumber(inputId);
138
+ if (inputNumber && inputNumber > maxInputNumber) {
139
+ maxInputNumber = inputNumber;
140
+ }
141
+ }
142
+ return maxInputNumber;
143
+ }
144
+ #getInputPortNumber(inputId) {
145
+ const match = INPUT_PORT_ID_PATTERN.exec(inputId);
146
+ if (!match) {
147
+ return undefined;
148
+ }
149
+ const inputNumber = Number(match[1]);
150
+ return Number.isSafeInteger(inputNumber) && inputNumber > 0 ? inputNumber : undefined;
151
+ }
152
+ #shouldSkipInputValue(inputValue) {
153
+ const value = unwrapDataValue(inputValue).value;
154
+ return ((this.data.ignoreNull === true && value === null) || (this.data.ignoreUndefined === true && value === undefined));
155
+ }
103
156
  }
104
157
  export const coalesceNode = nodeDefinition(CoalesceNodeImpl, 'Coalesce');
@@ -187,7 +187,7 @@ export class CodeNodeImpl extends NodeImpl {
187
187
  }
188
188
  const missingOutputs = this.getOutputDefinitions().filter((output) => !(output.id in outputs));
189
189
  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": undefiend }. To return undefined, return { "type": "any", "value": undefined }. Missing: ${missingOutputs
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
191
  .map((output) => output.id)
192
192
  .join(', ')}`);
193
193
  }
@@ -10,6 +10,44 @@ import { createInterpolationInputDefinition } from '../interpolationInputDefinit
10
10
  const DEFAULT_JSON_TEMPLATE = `{
11
11
  "key": "{{input}}"
12
12
  }`;
13
+ function isEscapedCharacter(value, index) {
14
+ let backslashCount = 0;
15
+ for (let i = index - 1; i >= 0 && value[i] === '\\'; i--) {
16
+ backslashCount++;
17
+ }
18
+ return backslashCount % 2 === 1;
19
+ }
20
+ function isUnescapedQuoteAt(value, index) {
21
+ return index >= 0 && index < value.length && value[index] === '"' && !isEscapedCharacter(value, index);
22
+ }
23
+ function isInsideJsonString(value, index) {
24
+ let insideString = false;
25
+ for (let i = 0; i < index; i++) {
26
+ if (isUnescapedQuoteAt(value, i)) {
27
+ insideString = !insideString;
28
+ }
29
+ }
30
+ return insideString;
31
+ }
32
+ function stringifyJsonValue(value) {
33
+ if (value == null) {
34
+ return 'null';
35
+ }
36
+ return JSON.stringify(value);
37
+ }
38
+ function stringifyWholeQuotedJsonValue(value) {
39
+ if (value == null) {
40
+ return 'null';
41
+ }
42
+ if (typeof value === 'string') {
43
+ return JSON.stringify(value);
44
+ }
45
+ return JSON.stringify(JSON.stringify(value));
46
+ }
47
+ function stringifyEmbeddedJsonStringFragment(value) {
48
+ const fragment = value == null ? 'null' : typeof value === 'string' ? value : JSON.stringify(value) ?? 'null';
49
+ return JSON.stringify(fragment).slice(1, -1);
50
+ }
13
51
  export class ObjectNodeImpl extends NodeImpl {
14
52
  static create() {
15
53
  const chartNode = {
@@ -86,12 +124,13 @@ export class ObjectNodeImpl extends NodeImpl {
86
124
  let result = '';
87
125
  let cursor = 0;
88
126
  for (const tokenSpan of tokenSpans) {
89
- const hasLeadingQuote = tokenSpan.start > 0 && protectedBaseString[tokenSpan.start - 1] === '"';
90
- const hasTrailingQuote = tokenSpan.end < protectedBaseString.length && protectedBaseString[tokenSpan.end] === '"';
91
- const replacementStart = hasLeadingQuote ? tokenSpan.start - 1 : tokenSpan.start;
92
- const replacementEnd = hasTrailingQuote ? tokenSpan.end + 1 : tokenSpan.end;
127
+ const isInsideString = isInsideJsonString(protectedBaseString, tokenSpan.start);
128
+ const isWholeQuotedToken = isInsideString &&
129
+ isUnescapedQuoteAt(protectedBaseString, tokenSpan.start - 1) &&
130
+ isUnescapedQuoteAt(protectedBaseString, tokenSpan.end);
131
+ const replacementStart = isWholeQuotedToken ? tokenSpan.start - 1 : tokenSpan.start;
132
+ const replacementEnd = isWholeQuotedToken ? tokenSpan.end + 1 : tokenSpan.end;
93
133
  const trimmedKey = getInterpolationTokenName(tokenSpan.rawInner) ?? tokenSpan.rawInner.trim();
94
- const isQuoted = hasLeadingQuote;
95
134
  let value;
96
135
  const graphInputPrefix = '@graphInputs.';
97
136
  const contextPrefix = '@context.';
@@ -105,20 +144,14 @@ export class ObjectNodeImpl extends NodeImpl {
105
144
  value = values[trimmedKey]; // Original logic for non-@ variables
106
145
  }
107
146
  result += protectedBaseString.slice(cursor, replacementStart);
108
- if (value == null) {
109
- result += 'null';
110
- }
111
- else if (isQuoted && typeof value === 'string') {
112
- // Adds double-quotes back.
113
- result += JSON.stringify(value);
147
+ if (isInsideString && !isWholeQuotedToken) {
148
+ result += stringifyEmbeddedJsonStringFragment(value);
114
149
  }
115
- else if (isQuoted) {
116
- // Non-strings require a double-stringify, first to turn them into a string, then to escape that string and add quotes.
117
- result += JSON.stringify(JSON.stringify(value));
150
+ else if (isWholeQuotedToken) {
151
+ result += stringifyWholeQuotedJsonValue(value);
118
152
  }
119
153
  else {
120
- // Otherwise, it was not quoted, so no need to double-stringify
121
- result += JSON.stringify(value);
154
+ result += stringifyJsonValue(value);
122
155
  }
123
156
  cursor = replacementEnd;
124
157
  }
@@ -131,8 +164,7 @@ export class ObjectNodeImpl extends NodeImpl {
131
164
  return acc;
132
165
  }, {});
133
166
  const interpolatedString = this.interpolate(this.chartNode.data.jsonTemplate, inputMap, context.graphInputNodeValues, // Pass graph inputs
134
- context.contextValues // Pass context values
135
- );
167
+ context.contextValues);
136
168
  let outputValue;
137
169
  try {
138
170
  outputValue = JSON.parse(interpolatedString);
@@ -3,9 +3,8 @@ import { nanoid } from 'nanoid/non-secure';
3
3
  import { NodeImpl } from '../NodeImpl.js';
4
4
  import { nodeDefinition } from '../NodeDefinition.js';
5
5
  import {} from '../../index.js';
6
- import { mapValues } from 'lodash-es';
7
6
  import { dedent } from 'ts-dedent';
8
- import { coerceType, coerceTypeOptional } from '../../utils/coerceType.js';
7
+ import { coerceTypeOptional } from '../../utils/coerceType.js';
9
8
  import { getInputOrData } from '../../utils/index.js';
10
9
  import { interpolate, extractInterpolationVariables } from '../../utils/interpolation.js';
11
10
  import { match } from 'ts-pattern';
@@ -110,6 +109,14 @@ export class PromptNodeImpl extends NodeImpl {
110
109
  dataKey: 'type',
111
110
  useInputToggleDataKey: 'useTypeInput',
112
111
  },
112
+ {
113
+ type: 'code',
114
+ label: 'Prompt Text',
115
+ dataKey: 'promptText',
116
+ language: 'prompt-interpolation-markdown',
117
+ theme: 'prompt-interpolation',
118
+ showTextStats: true,
119
+ },
113
120
  {
114
121
  type: 'string',
115
122
  label: 'Name',
@@ -136,13 +143,6 @@ export class PromptNodeImpl extends NodeImpl {
136
143
  helperMessage: 'For Anthropic, marks this message as a cache breakpoint - this message and every message before it will be cached using Prompt Caching.',
137
144
  useInputToggleDataKey: 'useIsCacheBreakpointInput',
138
145
  },
139
- {
140
- type: 'code',
141
- label: 'Prompt Text',
142
- dataKey: 'promptText',
143
- language: 'prompt-interpolation-markdown',
144
- theme: 'prompt-interpolation',
145
- },
146
146
  ];
147
147
  }
148
148
  getBody() {
@@ -174,7 +174,10 @@ export class PromptNodeImpl extends NodeImpl {
174
174
  };
175
175
  }
176
176
  async process(inputs, context) {
177
- const inputMap = mapValues(inputs, (input) => coerceType(input, 'string'));
177
+ const inputMap = Object.keys(inputs).reduce((acc, key) => {
178
+ acc[key] = coerceTypeOptional(inputs[key], 'string') ?? '';
179
+ return acc;
180
+ }, {});
178
181
  const outputValue = interpolate(this.chartNode.data.promptText, inputMap, context.graphInputNodeValues, context.contextValues);
179
182
  const type = getInputOrData(this.data, inputs, 'type', 'string');
180
183
  const isCacheBreakpoint = getInputOrData(this.data, inputs, 'isCacheBreakpoint', 'boolean');
@@ -74,6 +74,7 @@ export class TextNodeImpl extends NodeImpl {
74
74
  dataKey: 'text',
75
75
  language: 'prompt-interpolation-markdown',
76
76
  theme: 'prompt-interpolation',
77
+ showTextStats: true,
77
78
  },
78
79
  {
79
80
  type: 'toggle',
@@ -90,6 +90,7 @@ export type CodeEditorDefinition<T extends ChartNode> = SharedEditorDefinitionPr
90
90
  theme?: string;
91
91
  height?: number;
92
92
  enableFolding?: boolean;
93
+ showTextStats?: boolean;
93
94
  };
94
95
  export type ColorEditorDefinition<T extends ChartNode> = SharedEditorDefinitionProps<T> & {
95
96
  type: 'color';
@@ -190,8 +190,8 @@ export type OutgoingMessageMap = {
190
190
  requestId: RemoteRunRequestId;
191
191
  graphId: GraphId;
192
192
  runToNodeIds?: NodeId[];
193
+ preloadData?: Record<NodeId, Outputs>;
193
194
  contextValues: Record<string, DataValue>;
194
- runFromNodeId?: NodeId;
195
195
  inputs?: GraphInputs;
196
196
  projectPath?: string | null;
197
197
  useEditorCache?: boolean;
@@ -1,13 +1,19 @@
1
1
  import { NodeImpl, type NodeUIData } from '../NodeImpl.js';
2
2
  import { type ChartNode, type NodeConnection, type NodeInputDefinition, type NodeOutputDefinition } from '../NodeBase.js';
3
3
  import { type Inputs, type Outputs } from '../GraphProcessor.js';
4
+ import { type EditorDefinition } from '../EditorDefinition.js';
4
5
  export type CoalesceNode = ChartNode<'coalesce', CoalesceNodeData>;
5
- export type CoalesceNodeData = {};
6
+ export type CoalesceNodeData = {
7
+ ignoreNull?: boolean;
8
+ ignoreUndefined?: boolean;
9
+ };
6
10
  export declare class CoalesceNodeImpl extends NodeImpl<CoalesceNode> {
7
11
  #private;
8
12
  static create: () => CoalesceNode;
9
13
  getInputDefinitions(connections: NodeConnection[]): NodeInputDefinition[];
10
14
  getOutputDefinitions(): NodeOutputDefinition[];
15
+ getEditors(): EditorDefinition<CoalesceNode>[];
16
+ getBody(): string | undefined;
11
17
  static getUIData(): NodeUIData;
12
18
  process(inputData: Inputs): Promise<Outputs>;
13
19
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@valerypopoff/rivet2-core",
3
- "version": "2.0.3",
3
+ "version": "2.0.5",
4
4
  "license": "MIT",
5
5
  "main": "dist/cjs/bundle.cjs",
6
6
  "module": "dist/esm/index.js",