@valerypopoff/rivet2-core 2.17.0 → 2.21.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 (120) hide show
  1. package/dist/cjs/bundle.cjs +3197 -1461
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +40 -4
  4. package/dist/cjs/interpolationRuntime.cjs.map +2 -2
  5. package/dist/cjs/serialization.cjs +1880 -0
  6. package/dist/cjs/serialization.cjs.map +7 -0
  7. package/dist/cjs/webAppRuntime.cjs +168 -6
  8. package/dist/cjs/webAppRuntime.cjs.map +3 -3
  9. package/dist/esm/api/processSettings.js +1 -0
  10. package/dist/esm/exports.js +3 -0
  11. package/dist/esm/model/AgentResponseTrace.js +99 -34
  12. package/dist/esm/model/AgentResponseTracePresentation.js +130 -0
  13. package/dist/esm/model/DataValue.js +11 -2
  14. package/dist/esm/model/GlobalVariables.js +2 -1
  15. package/dist/esm/model/GraphBoundaryEffects.js +38 -1
  16. package/dist/esm/model/GraphExecutionState.js +81 -0
  17. package/dist/esm/model/GraphProcessor.js +625 -943
  18. package/dist/esm/model/GraphSchedulerBoundaryState.js +64 -0
  19. package/dist/esm/model/Nodes.js +5 -0
  20. package/dist/esm/model/ProjectBundle.js +69 -11
  21. package/dist/esm/model/ProjectBundleRuntime.js +54 -0
  22. package/dist/esm/model/ProjectGraphCallSites.js +46 -0
  23. package/dist/esm/model/SchedulerBoundaryPlanner.js +233 -0
  24. package/dist/esm/model/SubprocessorBridge.js +125 -87
  25. package/dist/esm/model/ToolCallContinuationCoordinator.js +1 -1
  26. package/dist/esm/model/chat-v2/aiSdkBridge.js +15 -12
  27. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -4
  28. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +5 -1
  29. package/dist/esm/model/chat-v2/chatV2Outputs.js +2 -2
  30. package/dist/esm/model/chat-v2/chatV2Pipeline.js +11 -1
  31. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +3 -2
  32. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +46 -6
  33. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +7 -0
  34. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +10 -0
  35. package/dist/esm/model/chat-v2/llmChatV2Body.js +3 -3
  36. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +5 -2
  37. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +1 -0
  38. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +25 -15
  39. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +10 -2
  40. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +17 -0
  41. package/dist/esm/model/chat-v2/llmModelCandidate.js +2 -1
  42. package/dist/esm/model/chat-v2/llmProfile.js +2 -1
  43. package/dist/esm/model/chat-v2/llmProfileBody.js +9 -0
  44. package/dist/esm/model/chat-v2/llmProfileFallback.js +7 -4
  45. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -0
  46. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +16 -3
  47. package/dist/esm/model/chat-v2/messageConverter.js +18 -16
  48. package/dist/esm/model/chat-v2/modelRegistry.js +14 -4
  49. package/dist/esm/model/chat-v2/openRouterModel.js +73 -0
  50. package/dist/esm/model/chat-v2/parallelToolCalls.js +2 -0
  51. package/dist/esm/model/chat-v2/providerOptions.js +30 -25
  52. package/dist/esm/model/classifier/credentials.js +13 -3
  53. package/dist/esm/model/classifier/limits.js +33 -3
  54. package/dist/esm/model/classifier/perplexity.js +63 -0
  55. package/dist/esm/model/classifier/profile.js +151 -0
  56. package/dist/esm/model/classifier/profileExecution.js +294 -0
  57. package/dist/esm/model/classifier/providers.js +217 -30
  58. package/dist/esm/model/classifier/state.js +4 -1
  59. package/dist/esm/model/classifier/types.js +11 -1
  60. package/dist/esm/model/nodeRunFailure.js +8 -1
  61. package/dist/esm/model/nodes/CallGraphNode.js +6 -0
  62. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +257 -66
  63. package/dist/esm/model/nodes/ClassifierProfileNode.js +133 -0
  64. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +1 -1
  65. package/dist/esm/model/nodes/LLMChatV2Node.js +2 -1
  66. package/dist/esm/model/nodes/SubGraphNode.js +4 -0
  67. package/dist/esm/model/nodes/toolCallDelegation.js +5 -1
  68. package/dist/esm/model/profileSuspensionHints.js +8 -0
  69. package/dist/esm/serialization.js +2 -0
  70. package/dist/esm/utils/coerceType.js +11 -1
  71. package/dist/esm/webAppRuntime.js +1 -0
  72. package/dist/types/exports.d.ts +3 -0
  73. package/dist/types/model/AgentResponseTrace.d.ts +15 -4
  74. package/dist/types/model/AgentResponseTracePresentation.d.ts +15 -0
  75. package/dist/types/model/DataValue.d.ts +12 -8
  76. package/dist/types/model/ExecutorProtocol.d.ts +14 -2
  77. package/dist/types/model/GraphBoundaryEffects.d.ts +10 -1
  78. package/dist/types/model/GraphExecutionState.d.ts +68 -0
  79. package/dist/types/model/GraphProcessor.d.ts +1 -0
  80. package/dist/types/model/GraphSchedulerBoundaryState.d.ts +96 -0
  81. package/dist/types/model/Nodes.d.ts +7 -4
  82. package/dist/types/model/ProcessContext.d.ts +12 -3
  83. package/dist/types/model/ProjectBundle.d.ts +18 -4
  84. package/dist/types/model/ProjectBundleRuntime.d.ts +24 -0
  85. package/dist/types/model/ProjectGraphCallSites.d.ts +12 -0
  86. package/dist/types/model/RivetUIContext.d.ts +1 -1
  87. package/dist/types/model/SchedulerBoundaryPlanner.d.ts +42 -0
  88. package/dist/types/model/Settings.d.ts +1 -0
  89. package/dist/types/model/SubgraphProjectTarget.d.ts +6 -0
  90. package/dist/types/model/SubprocessorBridge.d.ts +2 -0
  91. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +4 -0
  92. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  93. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +79 -1
  94. package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -1
  95. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +2 -0
  96. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +2 -1
  97. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +2 -0
  98. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +2 -0
  99. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +51 -3
  100. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +9 -6
  101. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +6 -2
  102. package/dist/types/model/chat-v2/modelRegistry.d.ts +5 -4
  103. package/dist/types/model/chat-v2/openRouterModel.d.ts +2 -0
  104. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -13
  105. package/dist/types/model/classifier/credentials.d.ts +4 -0
  106. package/dist/types/model/classifier/limits.d.ts +4 -1
  107. package/dist/types/model/classifier/perplexity.d.ts +7 -0
  108. package/dist/types/model/classifier/profile.d.ts +46 -0
  109. package/dist/types/model/classifier/profileExecution.d.ts +32 -0
  110. package/dist/types/model/classifier/providers.d.ts +32 -1
  111. package/dist/types/model/classifier/types.d.ts +9 -0
  112. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +14 -12
  113. package/dist/types/model/nodes/ClassifierProfileNode.d.ts +20 -0
  114. package/dist/types/model/nodes/SubGraphNode.d.ts +1 -1
  115. package/dist/types/model/nodes/toolCallDelegation.d.ts +3 -1
  116. package/dist/types/model/profileSuspensionHints.d.ts +8 -0
  117. package/dist/types/recording/ExecutionRecorder.d.ts +5 -1
  118. package/dist/types/serialization.d.ts +2 -0
  119. package/dist/types/webAppRuntime.d.ts +1 -0
  120. package/package.json +7 -1
@@ -0,0 +1,1880 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/serialization.ts
31
+ var serialization_exports = {};
32
+ __export(serialization_exports, {
33
+ deserializeDatasets: () => deserializeDatasets,
34
+ deserializeGraph: () => deserializeGraph,
35
+ deserializeProject: () => deserializeProject,
36
+ serializeDatasets: () => serializeDatasets,
37
+ serializeGraph: () => serializeGraph,
38
+ serializeProject: () => serializeProject
39
+ });
40
+ module.exports = __toCommonJS(serialization_exports);
41
+
42
+ // src/utils/serialization/serialization.ts
43
+ var yaml3 = __toESM(require("yaml"), 1);
44
+
45
+ // src/utils/serialization/serialization_v3.ts
46
+ var import_lodash_es = require("lodash");
47
+
48
+ // src/utils/newId.ts
49
+ var import_non_secure = require("nanoid/non-secure");
50
+
51
+ // src/model/UiGraph.ts
52
+ var UI_GRAPH_GAP_SIZES = ["small", "medium", "large"];
53
+ var UI_GRAPH_OUTPUT_RENDER_MODES = ["text", "json", "markdown", "image"];
54
+ function hasValidUiGraphComponentIds(uiGraph) {
55
+ const componentIds = /* @__PURE__ */ new Set();
56
+ for (const component of uiGraph.components) {
57
+ const componentId2 = typeof component.id === "string" ? component.id : "";
58
+ if (!componentId2.trim() || componentIds.has(componentId2)) {
59
+ return false;
60
+ }
61
+ componentIds.add(componentId2);
62
+ }
63
+ return true;
64
+ }
65
+ function normalizeUiGraphComponentIds(uiGraph) {
66
+ if (hasValidUiGraphComponentIds(uiGraph)) {
67
+ return uiGraph;
68
+ }
69
+ const reservedIds = new Set(
70
+ uiGraph.components.map((component) => typeof component.id === "string" ? component.id : "").filter((componentId2) => Boolean(componentId2.trim()))
71
+ );
72
+ const usedIds = /* @__PURE__ */ new Set();
73
+ const graphId2 = typeof uiGraph.id === "string" && uiGraph.id.trim() ? uiGraph.id : "ui-graph";
74
+ const components = uiGraph.components.map((component, index) => {
75
+ const componentId2 = typeof component.id === "string" ? component.id : "";
76
+ if (componentId2.trim() && !usedIds.has(componentId2)) {
77
+ usedIds.add(componentId2);
78
+ return component;
79
+ }
80
+ const repairedId = getRepairedUiGraphComponentId(graphId2, index, reservedIds, usedIds);
81
+ usedIds.add(repairedId);
82
+ return { ...component, id: repairedId };
83
+ });
84
+ return { ...uiGraph, components };
85
+ }
86
+ function getRepairedUiGraphComponentId(graphId2, componentIndex, reservedIds, usedIds) {
87
+ const baseId = `${graphId2}-component-${componentIndex + 1}`;
88
+ let repairedId = baseId;
89
+ let suffix = 2;
90
+ while (reservedIds.has(repairedId) || usedIds.has(repairedId)) {
91
+ repairedId = `${baseId}-${suffix}`;
92
+ suffix += 1;
93
+ }
94
+ return repairedId;
95
+ }
96
+
97
+ // src/model/UiGraphSchema.ts
98
+ var import_zod = require("zod");
99
+ var requiredString = import_zod.z.string({ error: "must be a string" });
100
+ var optionalString = import_zod.z.string({ error: "must be a string when provided" }).optional();
101
+ var componentId = import_zod.z.custom((value) => typeof value === "string", { error: "must be a string" }).optional();
102
+ var uiGraphId = import_zod.z.custom((value) => typeof value === "string", { error: "must be a string" }).refine((value) => value.trim().length > 0, { error: "must be a non-empty string" });
103
+ var graphId = import_zod.z.custom((value) => typeof value === "string", { error: "must be a string when provided" }).optional();
104
+ var objectOptions = { error: "must be an object" };
105
+ var inputBindingSchema = import_zod.z.object({ inputKey: requiredString, stateKey: requiredString }, objectOptions);
106
+ var outputBindingSchema = import_zod.z.object({ outputKey: optionalString, stateKey: requiredString }, objectOptions);
107
+ var stateValueBindingSchema = import_zod.z.object({ key: requiredString, type: import_zod.z.literal("state") }, objectOptions);
108
+ var literalValueBindingSchema = import_zod.z.object({ type: import_zod.z.literal("literal"), value: import_zod.z.unknown() }, objectOptions).superRefine((binding, context) => {
109
+ if (!Object.hasOwn(binding, "value")) {
110
+ context.addIssue({ code: "custom", message: "is required", path: ["value"] });
111
+ }
112
+ });
113
+ var valueBindingSchema = import_zod.z.discriminatedUnion("type", [stateValueBindingSchema, literalValueBindingSchema], {
114
+ error: 'must be "state" or "literal"'
115
+ });
116
+ var inputMappingsSchema = import_zod.z.array(inputBindingSchema, { error: "must be an array" }).optional();
117
+ var runGraphActionSchema = import_zod.z.object(
118
+ {
119
+ type: import_zod.z.literal("runGraph"),
120
+ graphId,
121
+ outputKey: optionalString,
122
+ outputStateKey: optionalString,
123
+ inputMappings: inputMappingsSchema,
124
+ inputs: import_zod.z.record(import_zod.z.string(), valueBindingSchema, { error: "must be an object" }).optional(),
125
+ outputs: import_zod.z.array(outputBindingSchema, { error: "must be an array" }).optional()
126
+ },
127
+ objectOptions
128
+ );
129
+ var chatRunGraphActionSchema = import_zod.z.object(
130
+ {
131
+ type: import_zod.z.literal("runGraph"),
132
+ graphId,
133
+ userInputId: optionalString,
134
+ historyInputId: optionalString,
135
+ responseOutputId: optionalString,
136
+ inputMappings: inputMappingsSchema
137
+ },
138
+ objectOptions
139
+ );
140
+ var inputComponentFields = {
141
+ id: componentId,
142
+ label: requiredString,
143
+ stateKey: requiredString,
144
+ placeholder: optionalString,
145
+ defaultValue: optionalString
146
+ };
147
+ var UI_GRAPH_COMPONENT_SCHEMA = import_zod.z.discriminatedUnion(
148
+ "type",
149
+ [
150
+ import_zod.z.object({ id: componentId, type: import_zod.z.literal("text"), text: requiredString }, objectOptions),
151
+ import_zod.z.object({ id: componentId, type: import_zod.z.literal("markdown"), markdown: requiredString }, objectOptions),
152
+ import_zod.z.object(
153
+ {
154
+ id: componentId,
155
+ type: import_zod.z.literal("gap"),
156
+ size: import_zod.z.enum(UI_GRAPH_GAP_SIZES, { error: `must be one of: ${UI_GRAPH_GAP_SIZES.join(", ")}` })
157
+ },
158
+ objectOptions
159
+ ),
160
+ import_zod.z.object({ type: import_zod.z.literal("input"), ...inputComponentFields }, objectOptions),
161
+ import_zod.z.object({ type: import_zod.z.literal("textarea"), ...inputComponentFields }, objectOptions),
162
+ import_zod.z.object(
163
+ {
164
+ id: componentId,
165
+ type: import_zod.z.literal("dropdown"),
166
+ label: requiredString,
167
+ stateKey: requiredString,
168
+ items: import_zod.z.array(import_zod.z.object({ label: requiredString, value: requiredString }, objectOptions), {
169
+ error: "must be an array"
170
+ })
171
+ },
172
+ objectOptions
173
+ ),
174
+ import_zod.z.object(
175
+ { id: componentId, type: import_zod.z.literal("button"), label: requiredString, action: runGraphActionSchema },
176
+ objectOptions
177
+ ),
178
+ import_zod.z.object(
179
+ {
180
+ id: componentId,
181
+ type: import_zod.z.literal("chat"),
182
+ placeholder: optionalString,
183
+ allowResponseInspection: import_zod.z.boolean().optional(),
184
+ action: chatRunGraphActionSchema
185
+ },
186
+ objectOptions
187
+ ),
188
+ import_zod.z.object(
189
+ {
190
+ id: componentId,
191
+ type: import_zod.z.literal("output"),
192
+ label: optionalString,
193
+ stateKey: requiredString,
194
+ renderAs: import_zod.z.enum(UI_GRAPH_OUTPUT_RENDER_MODES, {
195
+ error: `must be one of: ${UI_GRAPH_OUTPUT_RENDER_MODES.join(", ")}`
196
+ }).optional()
197
+ },
198
+ objectOptions
199
+ )
200
+ ],
201
+ { error: "must have a supported string type" }
202
+ );
203
+ var UI_GRAPH_ENVELOPE_SCHEMA = import_zod.z.object(
204
+ {
205
+ id: uiGraphId,
206
+ name: requiredString,
207
+ description: optionalString,
208
+ components: import_zod.z.array(import_zod.z.unknown(), { error: "must be an array" })
209
+ },
210
+ objectOptions
211
+ );
212
+
213
+ // src/model/UiGraphNormalization.ts
214
+ var UiGraphNormalizationError = class extends Error {
215
+ constructor(issues) {
216
+ super(`Invalid UI graph configuration: ${issues.map(formatUiGraphNormalizationIssue).join("; ")}`);
217
+ this.issues = issues;
218
+ this.name = "UiGraphNormalizationError";
219
+ }
220
+ };
221
+ function formatUiGraphNormalizationIssue(issue) {
222
+ return `${issue.path}: ${issue.message}`;
223
+ }
224
+ function normalizeUiGraphRecord(value, options = {}) {
225
+ if (!isRecord(value)) {
226
+ throw new UiGraphNormalizationError([{ message: "must be an object", path: "Project uiGraphs" }]);
227
+ }
228
+ const issues = [];
229
+ const replacements = /* @__PURE__ */ new Map();
230
+ const uiGraphEntries = Object.entries(value);
231
+ for (const [uiGraphId2, uiGraph] of uiGraphEntries) {
232
+ const result = parseUiGraph(uiGraph, { ...options, expectedId: uiGraphId2 });
233
+ issues.push(...result.issues);
234
+ if (result.uiGraph && result.uiGraph !== uiGraph) {
235
+ replacements.set(uiGraphId2, result.uiGraph);
236
+ }
237
+ }
238
+ if (issues.length > 0) {
239
+ throw new UiGraphNormalizationError(issues);
240
+ }
241
+ if (replacements.size === 0) {
242
+ return value;
243
+ }
244
+ return Object.fromEntries(
245
+ uiGraphEntries.map(([uiGraphId2, uiGraph]) => [uiGraphId2, replacements.get(uiGraphId2) ?? uiGraph])
246
+ );
247
+ }
248
+ function parseUiGraph(value, options) {
249
+ const graphPath = `UI graph "${getUiGraphLabel(value, options.expectedId)}"`;
250
+ if (!isRecord(value)) {
251
+ return { issues: [{ message: "must be an object", path: graphPath }] };
252
+ }
253
+ const envelopeResult = UI_GRAPH_ENVELOPE_SCHEMA.safeParse(value);
254
+ const issues = envelopeResult.success ? [] : mapSchemaIssues(envelopeResult.error.issues, graphPath);
255
+ if (options.expectedId !== void 0 && typeof value.id === "string" && value.id !== options.expectedId) {
256
+ issues.push({ message: `must match its project key "${options.expectedId}"`, path: `${graphPath}.id` });
257
+ }
258
+ if (!Array.isArray(value.components)) {
259
+ return { issues };
260
+ }
261
+ validateComponents(value.components, graphPath, options, issues);
262
+ if (issues.length > 0) {
263
+ return { issues };
264
+ }
265
+ const uiGraph = value;
266
+ return {
267
+ issues,
268
+ uiGraph: options.repairComponentIds === false ? uiGraph : normalizeUiGraphComponentIds(uiGraph)
269
+ };
270
+ }
271
+ function validateComponents(components, graphPath, options, issues) {
272
+ const repairComponentIds = options.repairComponentIds !== false;
273
+ const usedIds = /* @__PURE__ */ new Set();
274
+ for (const [index, component] of components.entries()) {
275
+ const componentPath = `${graphPath} component at index ${index}`;
276
+ if (!isRecord(component)) {
277
+ issues.push({ message: "must be an object", path: componentPath });
278
+ continue;
279
+ }
280
+ const result = UI_GRAPH_COMPONENT_SCHEMA.safeParse(component);
281
+ if (!result.success) {
282
+ issues.push(...mapComponentSchemaIssues(result.error.issues, componentPath, component.type));
283
+ }
284
+ const rawComponentId = component.id;
285
+ if (rawComponentId !== void 0 && typeof rawComponentId !== "string") {
286
+ continue;
287
+ }
288
+ const componentId2 = rawComponentId ?? "";
289
+ if (!componentId2.trim()) {
290
+ if (!repairComponentIds) {
291
+ issues.push({ message: "must be a non-empty string", path: `${componentPath}.id` });
292
+ }
293
+ continue;
294
+ }
295
+ if (usedIds.has(componentId2)) {
296
+ if (!repairComponentIds) {
297
+ issues.push({ message: `duplicates component id "${componentId2}"`, path: `${componentPath}.id` });
298
+ }
299
+ continue;
300
+ }
301
+ usedIds.add(componentId2);
302
+ }
303
+ }
304
+ function mapComponentSchemaIssues(schemaIssues, path, componentType) {
305
+ return schemaIssues.map((issue) => ({
306
+ message: issue.path.length === 1 && issue.path[0] === "type" ? typeof componentType === "string" ? `has unsupported type "${componentType}"` : "must have a supported string type" : issue.message,
307
+ path: formatSchemaPath(path, issue.path)
308
+ }));
309
+ }
310
+ function mapSchemaIssues(schemaIssues, path) {
311
+ return schemaIssues.map((issue) => ({ message: issue.message, path: formatSchemaPath(path, issue.path) }));
312
+ }
313
+ function formatSchemaPath(basePath, schemaPath) {
314
+ let path = basePath;
315
+ for (let index = 0; index < schemaPath.length; index += 1) {
316
+ const segment = schemaPath[index];
317
+ const previous = schemaPath[index - 1];
318
+ if (typeof segment === "number") {
319
+ path += previous === "items" ? `[${segment}]` : ` at index ${segment}`;
320
+ } else if (typeof previous === "string" && previous === "inputs") {
321
+ path += `[${JSON.stringify(segment)}]`;
322
+ } else {
323
+ path += `.${String(segment)}`;
324
+ }
325
+ }
326
+ return path;
327
+ }
328
+ function getUiGraphLabel(value, expectedId) {
329
+ if (expectedId !== void 0) {
330
+ return expectedId;
331
+ }
332
+ return isRecord(value) && typeof value.id === "string" && value.id.trim() ? value.id : "<unknown>";
333
+ }
334
+ function isRecord(value) {
335
+ return value != null && typeof value === "object" && !Array.isArray(value);
336
+ }
337
+
338
+ // src/utils/serialization/serializationInput.ts
339
+ var YAML = __toESM(require("yaml"), 1);
340
+ function prepareSerializedInput(data) {
341
+ if (typeof data !== "string") {
342
+ return {
343
+ deserializerInput: data,
344
+ version: 1
345
+ };
346
+ }
347
+ const trimmed = data.trim();
348
+ if (!trimmed) {
349
+ return {
350
+ deserializerInput: data,
351
+ version: 1
352
+ };
353
+ }
354
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
355
+ try {
356
+ const parsed2 = JSON.parse(trimmed);
357
+ const version2 = getParsedSerializationVersion(parsed2);
358
+ return {
359
+ deserializerInput: version2 === 1 ? data : parsed2,
360
+ version: version2
361
+ };
362
+ } catch {
363
+ return {
364
+ deserializerInput: data,
365
+ version: 1
366
+ };
367
+ }
368
+ }
369
+ const parsed = YAML.parse(trimmed);
370
+ const version = getParsedSerializationVersion(parsed);
371
+ return {
372
+ deserializerInput: version === 1 ? data : parsed,
373
+ version
374
+ };
375
+ }
376
+ function getParsedSerializationVersion(parsed) {
377
+ if (!parsed || typeof parsed !== "object") {
378
+ return 1;
379
+ }
380
+ const version = parsed.version;
381
+ if (version === 2 || version === 3 || version === 4) {
382
+ return version;
383
+ }
384
+ return 1;
385
+ }
386
+
387
+ // src/integrations/KnowledgeStoreValidation.ts
388
+ function normalizeKnowledgeConnectionId(value) {
389
+ const id = typeof value === "string" ? value.trim() : "";
390
+ if (!id) throw new Error("Knowledge store connection ID cannot be empty.");
391
+ if (id.length > 256) throw new Error("Knowledge store connection ID cannot exceed 256 characters.");
392
+ if (isReservedKnowledgeObjectKey(id)) {
393
+ throw new Error(`Knowledge store connection ID "${id}" is reserved.`);
394
+ }
395
+ return id;
396
+ }
397
+ function isReservedKnowledgeObjectKey(key) {
398
+ return key === "__proto__" || key === "prototype" || key === "constructor";
399
+ }
400
+ function normalizeKnowledgeMetadata(value, label = "Knowledge metadata") {
401
+ if (value == null) return {};
402
+ if (!isRecord2(value)) throw new Error(`${label} must be a plain object.`);
403
+ const normalized = {};
404
+ for (const [rawKey, rawValue] of Object.entries(value)) {
405
+ const key = rawKey.trim();
406
+ if (!key) throw new Error(`${label} contains an empty field name.`);
407
+ rejectUnsafeObjectKey(key, label);
408
+ if (Object.prototype.hasOwnProperty.call(normalized, key)) {
409
+ throw new Error(`${label} contains duplicate field "${key}" after trimming.`);
410
+ }
411
+ normalized[key] = normalizeKnowledgeMetadataValue(rawValue, `${label}.${key}`);
412
+ }
413
+ return normalized;
414
+ }
415
+ function normalizeKnowledgeMetadataValue(value, label) {
416
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
417
+ if (typeof value === "number") {
418
+ if (!Number.isFinite(value)) throw new Error(`${label} must be a finite number.`);
419
+ return value;
420
+ }
421
+ if (Array.isArray(value)) {
422
+ if (value.every((item) => typeof item === "string")) return value;
423
+ if (value.every((item) => typeof item === "boolean")) return value;
424
+ if (value.every((item) => typeof item === "number" && Number.isFinite(item))) return value;
425
+ throw new Error(`${label} arrays must contain only strings, booleans, or finite numbers of one type.`);
426
+ }
427
+ throw new Error(`${label} must be a portable scalar or a homogeneous scalar array.`);
428
+ }
429
+ function rejectUnsafeObjectKey(key, label) {
430
+ if (isReservedKnowledgeObjectKey(key)) {
431
+ throw new Error(`${label} field "${key}" is reserved.`);
432
+ }
433
+ }
434
+ function isRecord2(value) {
435
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
436
+ const prototype = Object.getPrototypeOf(value);
437
+ return prototype === Object.prototype || prototype === null;
438
+ }
439
+
440
+ // src/utils/genericUtilFunctions.ts
441
+ var exhaustiveTuple = () => (
442
+ // impressive inference from TS: it knows when the condition and the true branch can't both be satisfied
443
+ (...x) => x
444
+ );
445
+
446
+ // src/model/chat-v2/chatV2Shared.ts
447
+ function createChatV2CommonNodeData(overrides = {}) {
448
+ return {
449
+ model: "gpt-4o",
450
+ useModelInput: false,
451
+ temperature: 0.5,
452
+ useTemperatureInput: false,
453
+ topP: void 0,
454
+ useTopPInput: false,
455
+ topK: void 0,
456
+ useTopKInput: false,
457
+ presencePenalty: void 0,
458
+ usePresencePenaltyInput: false,
459
+ frequencyPenalty: void 0,
460
+ useFrequencyPenaltyInput: false,
461
+ stopSequences: [],
462
+ useStopSequencesInput: false,
463
+ seed: void 0,
464
+ useSeedInput: false,
465
+ maxTokens: 1024,
466
+ useMaxTokensInput: false,
467
+ useToolCalling: false,
468
+ outputUsage: false,
469
+ outputReasoning: false,
470
+ cache: false,
471
+ useAsGraphPartialOutput: false,
472
+ ...overrides
473
+ };
474
+ }
475
+
476
+ // src/model/chat-v2/chatV2Retry.ts
477
+ var DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES = 1;
478
+ var DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS = 0;
479
+
480
+ // src/model/chat-v2/llmProfileFieldRegistry.ts
481
+ var llmProfileFieldSpecs = [
482
+ { key: "model", inputId: "model", valueKind: "string" },
483
+ { key: "useModelInput", valueKind: "boolean", resolvedInputToggle: true },
484
+ { key: "temperature", inputId: "temperature", valueKind: "optional-number" },
485
+ { key: "useTemperatureInput", valueKind: "boolean", resolvedInputToggle: true },
486
+ { key: "topP", inputId: "topP", valueKind: "optional-number" },
487
+ { key: "useTopPInput", valueKind: "boolean", resolvedInputToggle: true },
488
+ { key: "topK", inputId: "topK", valueKind: "optional-number" },
489
+ { key: "useTopKInput", valueKind: "boolean", resolvedInputToggle: true },
490
+ { key: "presencePenalty", inputId: "presencePenalty", valueKind: "optional-number" },
491
+ { key: "usePresencePenaltyInput", valueKind: "boolean", resolvedInputToggle: true },
492
+ { key: "frequencyPenalty", inputId: "frequencyPenalty", valueKind: "optional-number" },
493
+ { key: "useFrequencyPenaltyInput", valueKind: "boolean", resolvedInputToggle: true },
494
+ { key: "stopSequences", inputId: "stopSequences" },
495
+ { key: "useStopSequencesInput", valueKind: "boolean", resolvedInputToggle: true },
496
+ { key: "seed", inputId: "seed", valueKind: "optional-number" },
497
+ { key: "useSeedInput", valueKind: "boolean", resolvedInputToggle: true },
498
+ { key: "maxTokens", inputId: "maxTokens", valueKind: "required-number" },
499
+ { key: "useMaxTokensInput", valueKind: "boolean", resolvedInputToggle: true },
500
+ { key: "provider" },
501
+ { key: "apiKeySource", inputId: "apiKey" },
502
+ { key: "providerApiKeyNames" },
503
+ { key: "customProviderApiKeyProgrammaticName", valueKind: "string" },
504
+ { key: "customProviderApiKeyEnvVarName", valueKind: "string" },
505
+ { key: "customProviderBaseURL", inputId: "customProviderBaseURL", valueKind: "string" },
506
+ { key: "useCustomProviderBaseURLInput", valueKind: "boolean", resolvedInputToggle: true },
507
+ { key: "customProviderApi" },
508
+ { key: "headers", inputId: "headers" },
509
+ { key: "useHeadersInput", valueKind: "boolean", resolvedInputToggle: true },
510
+ { key: "extraProviderOptions", inputId: "extraProviderOptions", valueKind: "string" },
511
+ { key: "useExtraProviderOptionsInput", valueKind: "boolean", resolvedInputToggle: true },
512
+ { key: "openAIReasoningEffort", valueKind: "string" },
513
+ { key: "openRouterReasoningEffort", valueKind: "string" },
514
+ { key: "openAIReasoningSummary", valueKind: "string" },
515
+ { key: "openAIPreviousResponseId", inputId: "previousResponseId", valueKind: "string" },
516
+ { key: "useOpenAIPreviousResponseIdInput", valueKind: "boolean", resolvedInputToggle: true },
517
+ { key: "enableOpenAIWebSearch", valueKind: "boolean" },
518
+ { key: "openAIWebSearchContextSize" },
519
+ { key: "enableOpenAICodeInterpreter", valueKind: "boolean" },
520
+ { key: "anthropicThinkingMode" },
521
+ { key: "anthropicThinkingBudget", inputId: "anthropicThinkingBudget", valueKind: "optional-number" },
522
+ { key: "useAnthropicThinkingBudgetInput", valueKind: "boolean", resolvedInputToggle: true },
523
+ { key: "anthropicEffort" },
524
+ { key: "anthropicCacheControlTtl" },
525
+ { key: "googleThinkingBudget", inputId: "googleThinkingBudget", valueKind: "optional-number" },
526
+ { key: "useGoogleThinkingBudgetInput", valueKind: "boolean", resolvedInputToggle: true },
527
+ { key: "googleThinkingLevel" },
528
+ { key: "googleIncludeThoughts", valueKind: "boolean" },
529
+ { key: "enableGoogleSearchGrounding", valueKind: "boolean" },
530
+ { key: "enableGoogleUrlContext", valueKind: "boolean" },
531
+ { key: "enableCircuitBreaker", valueKind: "boolean" },
532
+ { key: "firstOutputTimeoutMs", valueKind: "required-number" },
533
+ { key: "streamInactivityTimeoutMs", valueKind: "required-number" },
534
+ { key: "circuitBreakerFailureThreshold", valueKind: "required-number" },
535
+ { key: "circuitBreakerFailureWindowMs", valueKind: "required-number" },
536
+ { key: "circuitBreakerOpenDurationMs", valueKind: "required-number" }
537
+ ];
538
+ var llmProfileDataKeys = llmProfileFieldSpecs.map((field) => field.key);
539
+ var llmProfileInputIds = llmProfileFieldSpecs.flatMap((field) => "inputId" in field ? [field.inputId] : []).filter((inputId, index, inputIds) => inputIds.indexOf(inputId) === index);
540
+ function keysForValueKind(valueKind) {
541
+ return llmProfileFieldSpecs.filter((field) => "valueKind" in field && field.valueKind === valueKind).map((field) => field.key);
542
+ }
543
+ var llmProfileStringDataKeys = keysForValueKind("string");
544
+ var llmProfileBooleanDataKeys = keysForValueKind("boolean");
545
+ var llmProfileRequiredNumberDataKeys = keysForValueKind("required-number");
546
+ var llmProfileOptionalNumberDataKeys = keysForValueKind("optional-number");
547
+ var llmProfileResolvedInputToggleDataKeys = llmProfileFieldSpecs.filter((field) => "resolvedInputToggle" in field && field.resolvedInputToggle).map((field) => field.key);
548
+
549
+ // src/model/chat-v2/llmProfileHealthStore.ts
550
+ var import_non_secure2 = require("nanoid/non-secure");
551
+ var import_crypto_js = __toESM(require("crypto-js"), 1);
552
+ var import_safe_stable_stringify = __toESM(require("safe-stable-stringify"), 1);
553
+ var DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS = 3e4;
554
+ var DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS = 3e4;
555
+ var DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD = 3;
556
+ var DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_WINDOW_MS = 3e5;
557
+ var DEFAULT_LLM_PROFILE_CIRCUIT_OPEN_DURATION_MS = 3e5;
558
+ var LLM_PROFILE_CLOSED_PERMIT_MIN_RETENTION_MS = 24 * 60 * 60 * 1e3;
559
+
560
+ // src/model/chat-v2/llmChatV2NodeData.ts
561
+ var llmChatV2ProfileDataKeys = llmProfileDataKeys;
562
+ function createLLMChatV2NodeData() {
563
+ return {
564
+ ...createChatV2CommonNodeData({
565
+ model: "gpt-5"
566
+ }),
567
+ configurationMode: "inline",
568
+ provider: "openai",
569
+ apiKeySource: "environment",
570
+ customProviderApiKeyProgrammaticName: "",
571
+ customProviderApiKeyEnvVarName: "CUSTOM_PROVIDER_API_KEY",
572
+ customProviderBaseURL: "",
573
+ useCustomProviderBaseURLInput: false,
574
+ customProviderApi: "completions",
575
+ baseURL: "",
576
+ useBaseURLInput: false,
577
+ headers: [],
578
+ useHeadersInput: false,
579
+ extraProviderOptions: "",
580
+ useExtraProviderOptionsInput: false,
581
+ openAIReasoningEffort: "",
582
+ openRouterReasoningEffort: "",
583
+ openAIReasoningSummary: "",
584
+ openAIPreviousResponseId: "",
585
+ useOpenAIPreviousResponseIdInput: false,
586
+ enableOpenAIWebSearch: false,
587
+ openAIWebSearchContextSize: "medium",
588
+ enableOpenAICodeInterpreter: false,
589
+ anthropicThinkingMode: "",
590
+ anthropicThinkingBudget: void 0,
591
+ useAnthropicThinkingBudgetInput: false,
592
+ anthropicEffort: "",
593
+ anthropicCacheControlTtl: "",
594
+ googleThinkingBudget: void 0,
595
+ useGoogleThinkingBudgetInput: false,
596
+ googleThinkingLevel: "",
597
+ googleIncludeThoughts: false,
598
+ enableGoogleSearchGrounding: false,
599
+ enableGoogleUrlContext: false,
600
+ enableCircuitBreaker: false,
601
+ firstOutputTimeoutMs: DEFAULT_LLM_PROFILE_FIRST_OUTPUT_TIMEOUT_MS,
602
+ streamInactivityTimeoutMs: DEFAULT_LLM_PROFILE_STREAM_INACTIVITY_TIMEOUT_MS,
603
+ circuitBreakerFailureThreshold: DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_THRESHOLD,
604
+ circuitBreakerFailureWindowMs: DEFAULT_LLM_PROFILE_CIRCUIT_FAILURE_WINDOW_MS,
605
+ circuitBreakerOpenDurationMs: DEFAULT_LLM_PROFILE_CIRCUIT_OPEN_DURATION_MS,
606
+ responseFormat: "",
607
+ responseSchemaName: "",
608
+ useResponseSchemaNameInput: false,
609
+ responseSchemaDescription: "",
610
+ useResponseSchemaDescriptionInput: false,
611
+ toolChoice: "",
612
+ toolChoiceFunction: "",
613
+ parallelToolCalls: false,
614
+ autoContinueToolCalls: false,
615
+ maxToolRounds: 3,
616
+ retryOnNon200: false,
617
+ errorOnNon200: true,
618
+ catchRequestFailed: false,
619
+ retryOnNon200RepeatTimes: DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES,
620
+ retryOnNon200CooldownMs: DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS,
621
+ outputLLMAttempts: false,
622
+ outputRequestBody: false,
623
+ outputResponseBody: false
624
+ };
625
+ }
626
+
627
+ // src/model/chat-v2/llmProfileTypes.ts
628
+ var LLM_PROFILE_VALUE_VERSION = 1;
629
+ function createLLMProfileNodeData() {
630
+ return pickLLMChatV2ProfileData(createLLMChatV2NodeData());
631
+ }
632
+ function createDefaultLLMProfileValue() {
633
+ return {
634
+ version: LLM_PROFILE_VALUE_VERSION,
635
+ configuration: createLLMProfileNodeData(),
636
+ credential: { reference: { source: "none" } }
637
+ };
638
+ }
639
+ function pickLLMChatV2ProfileData(data) {
640
+ return Object.fromEntries(llmChatV2ProfileDataKeys.map((key) => [key, data[key]]));
641
+ }
642
+
643
+ // src/model/DataValue.ts
644
+ var dataTypes = exhaustiveTuple()(
645
+ "any",
646
+ "any[]",
647
+ "boolean",
648
+ "boolean[]",
649
+ "string",
650
+ "string[]",
651
+ "number",
652
+ "number[]",
653
+ "date",
654
+ "date[]",
655
+ "time",
656
+ "time[]",
657
+ "datetime",
658
+ "datetime[]",
659
+ "chat-message",
660
+ "chat-message[]",
661
+ "control-flow-excluded",
662
+ "control-flow-excluded[]",
663
+ "object",
664
+ "object[]",
665
+ "fn<string>",
666
+ "fn<number>",
667
+ "fn<boolean>",
668
+ "fn<date>",
669
+ "fn<time>",
670
+ "fn<datetime>",
671
+ "fn<any>",
672
+ "fn<object>",
673
+ "fn<chat-message>",
674
+ "fn<control-flow-excluded>",
675
+ "fn<string[]>",
676
+ "fn<number[]>",
677
+ "fn<boolean[]>",
678
+ "fn<date[]>",
679
+ "fn<time[]>",
680
+ "fn<datetime[]>",
681
+ "fn<any[]>",
682
+ "fn<object[]>",
683
+ "fn<chat-message[]>",
684
+ "fn<control-flow-excluded[]>",
685
+ "gpt-function",
686
+ "gpt-function[]",
687
+ "fn<gpt-function[]>",
688
+ "fn<gpt-function>",
689
+ "vector",
690
+ "vector[]",
691
+ "fn<vector>",
692
+ "fn<vector[]>",
693
+ "image",
694
+ "image[]",
695
+ "fn<image>",
696
+ "fn<image[]>",
697
+ "binary",
698
+ "binary[]",
699
+ "fn<binary>",
700
+ "fn<binary[]>",
701
+ "audio",
702
+ "audio[]",
703
+ "fn<audio>",
704
+ "fn<audio[]>",
705
+ "graph-reference",
706
+ "graph-reference[]",
707
+ "fn<graph-reference>",
708
+ "fn<graph-reference[]>",
709
+ "knowledge-source",
710
+ "knowledge-source[]",
711
+ "fn<knowledge-source>",
712
+ "fn<knowledge-source[]>",
713
+ "knowledge-document",
714
+ "knowledge-document[]",
715
+ "fn<knowledge-document>",
716
+ "fn<knowledge-document[]>",
717
+ "knowledge-evidence",
718
+ "knowledge-evidence[]",
719
+ "fn<knowledge-evidence>",
720
+ "fn<knowledge-evidence[]>",
721
+ "llm-config",
722
+ "llm-config[]",
723
+ "fn<llm-config>",
724
+ "fn<llm-config[]>",
725
+ "classifier-config",
726
+ "classifier-config[]",
727
+ "fn<classifier-config>",
728
+ "fn<classifier-config[]>",
729
+ "document",
730
+ "document[]",
731
+ "fn<document>",
732
+ "fn<document[]>"
733
+ );
734
+ var scalarTypes = exhaustiveTuple()(
735
+ "any",
736
+ "boolean",
737
+ "string",
738
+ "number",
739
+ "date",
740
+ "time",
741
+ "datetime",
742
+ "chat-message",
743
+ "control-flow-excluded",
744
+ "object",
745
+ "gpt-function",
746
+ "vector",
747
+ "image",
748
+ "binary",
749
+ "audio",
750
+ "graph-reference",
751
+ "knowledge-source",
752
+ "knowledge-document",
753
+ "knowledge-evidence",
754
+ "llm-config",
755
+ "classifier-config",
756
+ "document"
757
+ );
758
+ var scalarDefaults = {
759
+ string: "",
760
+ number: 0,
761
+ boolean: false,
762
+ any: void 0,
763
+ "chat-message": {
764
+ type: "user",
765
+ message: "",
766
+ isCacheBreakpoint: void 0
767
+ },
768
+ "control-flow-excluded": void 0,
769
+ date: (/* @__PURE__ */ new Date()).toISOString(),
770
+ time: (/* @__PURE__ */ new Date()).toISOString(),
771
+ datetime: (/* @__PURE__ */ new Date()).toISOString(),
772
+ object: {},
773
+ "gpt-function": {
774
+ name: "unknown",
775
+ description: "",
776
+ parameters: {},
777
+ namespace: void 0,
778
+ strict: false
779
+ },
780
+ vector: [],
781
+ image: {
782
+ mediaType: "image/jpeg",
783
+ data: new Uint8Array()
784
+ },
785
+ binary: new Uint8Array(),
786
+ audio: { data: new Uint8Array() },
787
+ "graph-reference": { graphId: "", graphName: "" },
788
+ "knowledge-source": { connectionId: "", sourceId: "" },
789
+ "knowledge-document": { text: "" },
790
+ "knowledge-evidence": {
791
+ id: "",
792
+ text: "",
793
+ source: { connectionId: "", sourceId: "" },
794
+ documentId: ""
795
+ },
796
+ "llm-config": createDefaultLLMProfileValue(),
797
+ "classifier-config": {
798
+ version: 1,
799
+ configuration: { provider: "jev", model: "jev-latest" },
800
+ credential: {}
801
+ },
802
+ document: {
803
+ mediaType: "text/plain",
804
+ data: new Uint8Array(),
805
+ title: void 0,
806
+ context: void 0,
807
+ enableCitations: false
808
+ }
809
+ };
810
+
811
+ // src/utils/base64.ts
812
+ function base64ToUint8Array(base64) {
813
+ const binaryString = atob(base64);
814
+ const len = binaryString.length;
815
+ const bytes = new Uint8Array(len);
816
+ for (let i = 0; i < len; i++) {
817
+ bytes[i] = binaryString.charCodeAt(i);
818
+ }
819
+ return bytes;
820
+ }
821
+
822
+ // src/model/GlobalVariables.ts
823
+ var literalMarkerKey = "$rivetProjectGlobalLiteral";
824
+ var literalMarkerObject = "object";
825
+ var projectGlobalVariableScalarTypes = new Set(
826
+ scalarTypes.filter((type) => type !== "control-flow-excluded")
827
+ );
828
+ function isPlainRecord(value) {
829
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
830
+ const prototype = Object.getPrototypeOf(value);
831
+ return prototype === Object.prototype || prototype === null;
832
+ }
833
+ function isProjectGlobalVariableDataType(value) {
834
+ if (typeof value !== "string") return false;
835
+ const scalarType = value.endsWith("[]") ? value.slice(0, -2) : value;
836
+ return projectGlobalVariableScalarTypes.has(scalarType);
837
+ }
838
+ function isSparseArray(value) {
839
+ for (let index = 0; index < value.length; index++) {
840
+ if (!Object.hasOwn(value, index)) return true;
841
+ }
842
+ return false;
843
+ }
844
+ function literalError(label, message) {
845
+ return new Error(`${label}: ${message}`);
846
+ }
847
+ function decodeLiteral(value, label, seen = /* @__PURE__ */ new Set()) {
848
+ if (value === null || typeof value === "boolean" || typeof value === "string") return value;
849
+ if (typeof value === "number") {
850
+ if (!Number.isFinite(value)) throw literalError(label, "must use a Rivet marker for a non-finite number");
851
+ return value;
852
+ }
853
+ if (typeof value !== "object") throw literalError(label, "value must be JSON-compatible");
854
+ if (seen.has(value)) throw literalError(label, "cannot be circular");
855
+ seen.add(value);
856
+ try {
857
+ if (Array.isArray(value)) {
858
+ if (isSparseArray(value)) throw literalError(label, "cannot be a sparse array");
859
+ return value.map((item, index) => decodeLiteral(item, `${label}[${index}]`, seen));
860
+ }
861
+ if (!isPlainRecord(value)) throw literalError(label, "value must be JSON-compatible");
862
+ if (Object.hasOwn(value, literalMarkerKey)) {
863
+ const kind = value[literalMarkerKey];
864
+ if (kind === "undefined" && Object.keys(value).length === 1) return void 0;
865
+ if (kind === "number" && Object.keys(value).length === 2 && Object.hasOwn(value, "value")) {
866
+ if (value.value === "nan") return Number.NaN;
867
+ if (value.value === "infinity") return Infinity;
868
+ if (value.value === "-infinity") return -Infinity;
869
+ }
870
+ if (kind === "uint8array" && Object.keys(value).length === 2 && Object.hasOwn(value, "value") && typeof value.value === "string") {
871
+ try {
872
+ return base64ToUint8Array(value.value);
873
+ } catch {
874
+ throw literalError(label, "has an invalid Uint8Array base64 value");
875
+ }
876
+ }
877
+ if (kind === literalMarkerObject && Object.keys(value).length === 2 && Object.hasOwn(value, "value") && Array.isArray(value.value)) {
878
+ if (isSparseArray(value.value)) throw literalError(label, "has a sparse escaped object value");
879
+ const result2 = {};
880
+ for (const [index, entry] of value.value.entries()) {
881
+ if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== "string") {
882
+ throw literalError(label, `has an invalid escaped object entry at index ${index}`);
883
+ }
884
+ Object.defineProperty(result2, entry[0], {
885
+ configurable: true,
886
+ enumerable: true,
887
+ value: decodeLiteral(entry[1], `${label}.${entry[0]}`, seen),
888
+ writable: true
889
+ });
890
+ }
891
+ return result2;
892
+ }
893
+ throw literalError(label, "has an invalid reserved literal marker");
894
+ }
895
+ const result = {};
896
+ for (const [key, item] of Object.entries(value)) {
897
+ Object.defineProperty(result, key, {
898
+ configurable: true,
899
+ enumerable: true,
900
+ value: decodeLiteral(item, `${label}.${key}`, seen),
901
+ writable: true
902
+ });
903
+ }
904
+ return result;
905
+ } finally {
906
+ seen.delete(value);
907
+ }
908
+ }
909
+ function validateMetadata(value, label) {
910
+ if (value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string") return;
911
+ if (!Array.isArray(value) || isSparseArray(value))
912
+ throw literalError(label, "must contain only JSON-compatible metadata values");
913
+ for (const [index, item] of value.entries()) {
914
+ if (item === null || typeof item === "boolean" || typeof item === "number" || typeof item === "string") continue;
915
+ throw literalError(`${label}[${index}]`, "must be a scalar value");
916
+ }
917
+ }
918
+ function requirePlainRecord(value, label) {
919
+ if (!isPlainRecord(value)) throw literalError(label, "must be an object");
920
+ return value;
921
+ }
922
+ function requireString(value, label) {
923
+ if (typeof value !== "string") throw literalError(label, "must be a string");
924
+ }
925
+ function requireBoolean(value, label) {
926
+ if (typeof value !== "boolean") throw literalError(label, "must be a boolean");
927
+ }
928
+ function requireUint8Array(value, label) {
929
+ if (!(value instanceof Uint8Array)) throw literalError(label, "must be a Uint8Array");
930
+ }
931
+ function validateChatMessagePart(value, label) {
932
+ if (typeof value === "string") return;
933
+ const part = requirePlainRecord(value, label);
934
+ if (part.type === "url") {
935
+ requireString(part.url, `${label}.url`);
936
+ return;
937
+ }
938
+ if (part.type === "image") {
939
+ requireString(part.mediaType, `${label}.mediaType`);
940
+ requireUint8Array(part.data, `${label}.data`);
941
+ return;
942
+ }
943
+ if (part.type === "document") {
944
+ requireString(part.mediaType, `${label}.mediaType`);
945
+ requireUint8Array(part.data, `${label}.data`);
946
+ if (part.title !== void 0) requireString(part.title, `${label}.title`);
947
+ if (part.context !== void 0) requireString(part.context, `${label}.context`);
948
+ requireBoolean(part.enableCitations, `${label}.enableCitations`);
949
+ return;
950
+ }
951
+ throw literalError(label, "has an unsupported message part");
952
+ }
953
+ function validateStructuredScalar(type, value, label) {
954
+ switch (type) {
955
+ case "any":
956
+ return;
957
+ case "boolean":
958
+ return requireBoolean(value, label);
959
+ case "number":
960
+ if (typeof value !== "number") throw literalError(label, "must be a number");
961
+ return;
962
+ case "string":
963
+ case "date":
964
+ case "time":
965
+ case "datetime":
966
+ return requireString(value, label);
967
+ case "object":
968
+ requirePlainRecord(value, label);
969
+ return;
970
+ case "vector": {
971
+ if (!Array.isArray(value) || isSparseArray(value) || !value.every((item) => typeof item === "number")) {
972
+ throw literalError(label, "must be an array of numbers");
973
+ }
974
+ return;
975
+ }
976
+ case "binary":
977
+ return requireUint8Array(value, label);
978
+ case "image": {
979
+ const image = requirePlainRecord(value, label);
980
+ requireString(image.mediaType, `${label}.mediaType`);
981
+ requireUint8Array(image.data, `${label}.data`);
982
+ return;
983
+ }
984
+ case "audio": {
985
+ const audio = requirePlainRecord(value, label);
986
+ if (audio.mediaType !== void 0) requireString(audio.mediaType, `${label}.mediaType`);
987
+ requireUint8Array(audio.data, `${label}.data`);
988
+ return;
989
+ }
990
+ case "document": {
991
+ const document = requirePlainRecord(value, label);
992
+ requireString(document.mediaType, `${label}.mediaType`);
993
+ requireUint8Array(document.data, `${label}.data`);
994
+ if (document.title !== void 0) requireString(document.title, `${label}.title`);
995
+ if (document.context !== void 0) requireString(document.context, `${label}.context`);
996
+ requireBoolean(document.enableCitations, `${label}.enableCitations`);
997
+ return;
998
+ }
999
+ case "graph-reference": {
1000
+ const graph = requirePlainRecord(value, label);
1001
+ requireString(graph.graphId, `${label}.graphId`);
1002
+ requireString(graph.graphName, `${label}.graphName`);
1003
+ return;
1004
+ }
1005
+ case "knowledge-source": {
1006
+ const source = requirePlainRecord(value, label);
1007
+ requireString(source.connectionId, `${label}.connectionId`);
1008
+ requireString(source.sourceId, `${label}.sourceId`);
1009
+ if (source.version !== void 0) requireString(source.version, `${label}.version`);
1010
+ return;
1011
+ }
1012
+ case "knowledge-document": {
1013
+ const document = requirePlainRecord(value, label);
1014
+ requireString(document.text, `${label}.text`);
1015
+ if (document.id !== void 0) requireString(document.id, `${label}.id`);
1016
+ if (document.title !== void 0) requireString(document.title, `${label}.title`);
1017
+ if (document.metadata !== void 0) requirePlainRecord(document.metadata, `${label}.metadata`);
1018
+ for (const [key, item] of Object.entries(document.metadata ?? {})) {
1019
+ validateMetadata(item, `${label}.metadata.${key}`);
1020
+ }
1021
+ return;
1022
+ }
1023
+ case "knowledge-evidence": {
1024
+ const evidence = requirePlainRecord(value, label);
1025
+ requireString(evidence.id, `${label}.id`);
1026
+ requireString(evidence.text, `${label}.text`);
1027
+ requireString(evidence.documentId, `${label}.documentId`);
1028
+ validateStructuredScalar("knowledge-source", evidence.source, `${label}.source`);
1029
+ if (evidence.relevanceScore !== void 0 && typeof evidence.relevanceScore !== "number") {
1030
+ throw literalError(`${label}.relevanceScore`, "must be a number");
1031
+ }
1032
+ if (evidence.title !== void 0) requireString(evidence.title, `${label}.title`);
1033
+ if (evidence.chunkIndex !== void 0 && typeof evidence.chunkIndex !== "number") {
1034
+ throw literalError(`${label}.chunkIndex`, "must be a number");
1035
+ }
1036
+ if (evidence.metadata !== void 0) requirePlainRecord(evidence.metadata, `${label}.metadata`);
1037
+ for (const [key, item] of Object.entries(evidence.metadata ?? {})) {
1038
+ validateMetadata(item, `${label}.metadata.${key}`);
1039
+ }
1040
+ return;
1041
+ }
1042
+ case "gpt-function": {
1043
+ const fn = requirePlainRecord(value, label);
1044
+ requireString(fn.name, `${label}.name`);
1045
+ requireString(fn.description, `${label}.description`);
1046
+ requirePlainRecord(fn.parameters, `${label}.parameters`);
1047
+ requireBoolean(fn.strict, `${label}.strict`);
1048
+ if (fn.namespace !== void 0) requireString(fn.namespace, `${label}.namespace`);
1049
+ if (fn.resultHandling !== void 0 && fn.resultHandling !== "continue" && fn.resultHandling !== "return-direct") {
1050
+ throw literalError(`${label}.resultHandling`, 'must be "continue" or "return-direct"');
1051
+ }
1052
+ return;
1053
+ }
1054
+ case "chat-message": {
1055
+ const message = requirePlainRecord(value, label);
1056
+ if (message.type !== "system" && message.type !== "developer" && message.type !== "user" && message.type !== "assistant" && message.type !== "function") {
1057
+ throw literalError(`${label}.type`, "must be a supported chat message type");
1058
+ }
1059
+ const parts = Array.isArray(message.message) ? message.message : [message.message];
1060
+ if (Array.isArray(message.message) && isSparseArray(message.message)) {
1061
+ throw literalError(`${label}.message`, "cannot be a sparse array");
1062
+ }
1063
+ for (const [index, part] of parts.entries()) validateChatMessagePart(part, `${label}.message[${index}]`);
1064
+ if (message.isCacheBreakpoint !== void 0)
1065
+ requireBoolean(message.isCacheBreakpoint, `${label}.isCacheBreakpoint`);
1066
+ if (message.type === "assistant") {
1067
+ if (message.function_call !== void 0 && !isPlainRecord(message.function_call)) {
1068
+ throw literalError(`${label}.function_call`, "must be an object");
1069
+ }
1070
+ if (message.function_calls !== void 0 && !Array.isArray(message.function_calls)) {
1071
+ throw literalError(`${label}.function_calls`, "must be an array");
1072
+ }
1073
+ }
1074
+ if (message.type === "function") requireString(message.name, `${label}.name`);
1075
+ return;
1076
+ }
1077
+ case "llm-config":
1078
+ case "classifier-config": {
1079
+ const profile = requirePlainRecord(value, label);
1080
+ if (profile.version !== 1) throw literalError(`${label}.version`, "must be version 1");
1081
+ requirePlainRecord(profile.configuration, `${label}.configuration`);
1082
+ requirePlainRecord(profile.credential, `${label}.credential`);
1083
+ return;
1084
+ }
1085
+ default:
1086
+ throw literalError(label, `has unsupported data type "${type}"`);
1087
+ }
1088
+ }
1089
+ function validateProjectGlobalVariableDataValue(type, value, label) {
1090
+ const isArrayType = type.endsWith("[]");
1091
+ const scalarType = isArrayType ? type.slice(0, -2) : type;
1092
+ const values = isArrayType ? value : [value];
1093
+ if (!Array.isArray(values) || isArrayType && isSparseArray(values)) {
1094
+ throw literalError(label, isArrayType ? "must be an array" : "has an invalid value");
1095
+ }
1096
+ for (const [index, item] of values.entries()) {
1097
+ validateStructuredScalar(scalarType, item, isArrayType ? `${label}[${index}]` : label);
1098
+ }
1099
+ }
1100
+ function decodeProjectGlobalVariable(value, label = "Project global variable") {
1101
+ if (!isPlainRecord(value)) throw literalError(label, "definition must be an object");
1102
+ if (!isProjectGlobalVariableDataType(value.type)) {
1103
+ throw literalError(label, "type must be a supported non-function data type");
1104
+ }
1105
+ if (!Object.hasOwn(value, "value")) throw literalError(label, "definition is missing value");
1106
+ const decoded = {
1107
+ type: value.type,
1108
+ value: decodeLiteral(value.value, label)
1109
+ };
1110
+ validateProjectGlobalVariableDataValue(decoded.type, decoded.value, label);
1111
+ return decoded;
1112
+ }
1113
+ function decodeProjectGlobalVariables(value, label) {
1114
+ if (!isPlainRecord(value)) throw literalError(label, "must be a plain object");
1115
+ return Object.entries(value).map(([id, definition]) => {
1116
+ if (!id.trim()) throw literalError(label, "contains an empty variable ID");
1117
+ return [id, decodeProjectGlobalVariable(definition, `${label}.${id}`)];
1118
+ });
1119
+ }
1120
+ function validateProjectGlobalVariables(value, label = "Project metadata.globalVariables") {
1121
+ decodeProjectGlobalVariables(value, label);
1122
+ }
1123
+
1124
+ // src/utils/serialization/serializationUtils.ts
1125
+ var ProjectValidationError = class extends Error {
1126
+ constructor(validation) {
1127
+ super(`Invalid project file: ${validation.errors.join("; ")}`);
1128
+ this.validation = validation;
1129
+ this.name = "ProjectValidationError";
1130
+ }
1131
+ };
1132
+ function validateProject(project) {
1133
+ const errors = [];
1134
+ const warnings = [];
1135
+ if (!project || typeof project !== "object") {
1136
+ return { valid: false, errors: ["Project is not an object"], warnings };
1137
+ }
1138
+ const p = project;
1139
+ if (!isValidProjectStaticData(p.data)) {
1140
+ errors.push("Project data must be a record of static-data strings");
1141
+ }
1142
+ if (!p.metadata || typeof p.metadata !== "object") {
1143
+ errors.push("Missing project metadata");
1144
+ } else {
1145
+ const meta = p.metadata;
1146
+ if (!meta.id) errors.push("Missing project metadata.id");
1147
+ if (!meta.title) errors.push("Missing project metadata.title");
1148
+ if (meta.knowledgeStores != null) validateKnowledgeStores(meta.knowledgeStores, errors);
1149
+ if (meta.globalVariables != null) {
1150
+ try {
1151
+ validateProjectGlobalVariables(meta.globalVariables);
1152
+ } catch (error) {
1153
+ errors.push(error instanceof Error ? error.message : String(error));
1154
+ }
1155
+ }
1156
+ }
1157
+ if (!p.graphs || typeof p.graphs !== "object") {
1158
+ errors.push("Missing or invalid project graphs");
1159
+ } else {
1160
+ const graphs = p.graphs;
1161
+ for (const [graphId2, graph] of Object.entries(graphs)) {
1162
+ if (!graph || typeof graph !== "object") {
1163
+ errors.push(`Graph "${graphId2}": not an object`);
1164
+ continue;
1165
+ }
1166
+ const g = graph;
1167
+ if (!Array.isArray(g.nodes)) {
1168
+ errors.push(`Graph "${graphId2}": nodes is not an array`);
1169
+ } else {
1170
+ for (let i = 0; i < g.nodes.length; i++) {
1171
+ const node = g.nodes[i];
1172
+ if (!node || typeof node !== "object") {
1173
+ errors.push(`Graph "${graphId2}": node at index ${i} is not an object`);
1174
+ continue;
1175
+ }
1176
+ if (!node.id) errors.push(`Graph "${graphId2}": node at index ${i} missing id`);
1177
+ if (!node.type) errors.push(`Graph "${graphId2}": node "${node.id ?? i}" missing type`);
1178
+ }
1179
+ }
1180
+ if (!Array.isArray(g.connections)) {
1181
+ errors.push(`Graph "${graphId2}": connections is not an array`);
1182
+ } else {
1183
+ for (let i = 0; i < g.connections.length; i++) {
1184
+ const conn = g.connections[i];
1185
+ if (!conn || typeof conn !== "object") {
1186
+ errors.push(`Graph "${graphId2}": connection at index ${i} is not an object`);
1187
+ continue;
1188
+ }
1189
+ if (!conn.inputNodeId || !conn.outputNodeId) {
1190
+ warnings.push(`Graph "${graphId2}": connection at index ${i} missing node reference`);
1191
+ }
1192
+ }
1193
+ }
1194
+ }
1195
+ }
1196
+ if (p.uiGraphs != null) {
1197
+ validateUiGraphs(p.uiGraphs, errors);
1198
+ }
1199
+ return { valid: errors.length === 0, errors, warnings };
1200
+ }
1201
+ function validateKnowledgeStores(value, errors) {
1202
+ if (!isPlainRecord2(value)) {
1203
+ errors.push("Project metadata.knowledgeStores is not a plain object");
1204
+ return;
1205
+ }
1206
+ for (const [connectionId, definition] of Object.entries(value)) {
1207
+ try {
1208
+ const normalizedId = normalizeKnowledgeConnectionId(connectionId);
1209
+ if (normalizedId !== connectionId) throw new Error("connection ID cannot be padded");
1210
+ if (!isPlainRecord2(definition)) throw new Error("definition is not a plain object");
1211
+ if (typeof definition.displayName !== "string" || !definition.displayName.trim()) {
1212
+ throw new Error("displayName must be a non-empty string");
1213
+ }
1214
+ if (definition.displayName !== definition.displayName.trim()) {
1215
+ throw new Error("displayName cannot be padded");
1216
+ }
1217
+ validateKnowledgeProviderId(definition.provider, "provider");
1218
+ if (definition.pluginId != null) validateKnowledgeProviderId(definition.pluginId, "pluginId");
1219
+ if (!isPlainRecord2(definition.config)) throw new Error("config must be a plain object");
1220
+ for (const key of Object.keys(definition.config)) {
1221
+ if (key !== key.trim()) throw new Error(`config field "${key}" cannot be padded`);
1222
+ }
1223
+ normalizeKnowledgeMetadata(definition.config, "Knowledge store connection configuration");
1224
+ } catch (error) {
1225
+ errors.push(
1226
+ `Knowledge store connection "${connectionId}": ${error instanceof Error ? error.message : String(error)}`
1227
+ );
1228
+ }
1229
+ }
1230
+ }
1231
+ function validateKnowledgeProviderId(value, field) {
1232
+ if (typeof value !== "string" || !value.trim() || value !== value.trim()) {
1233
+ throw new Error(`${field} must be a non-empty, unpadded string`);
1234
+ }
1235
+ if (isReservedKnowledgeObjectKey(value)) throw new Error(`${field} "${value}" is reserved`);
1236
+ }
1237
+ function isPlainRecord2(value) {
1238
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
1239
+ const prototype = Object.getPrototypeOf(value);
1240
+ return prototype === Object.prototype || prototype === null;
1241
+ }
1242
+ function isValidProjectStaticData(value) {
1243
+ return value === void 0 || isPlainRecord2(value) && Object.values(value).every((entry) => typeof entry === "string");
1244
+ }
1245
+ function validateUiGraphs(uiGraphs, errors) {
1246
+ try {
1247
+ normalizeUiGraphRecord(uiGraphs, { repairComponentIds: false });
1248
+ } catch (error) {
1249
+ if (error instanceof UiGraphNormalizationError) {
1250
+ errors.push(...error.issues.map(formatUiGraphNormalizationIssue));
1251
+ return;
1252
+ }
1253
+ throw error;
1254
+ }
1255
+ }
1256
+ function doubleCheckProject(project) {
1257
+ const result = validateProject(project);
1258
+ if (!result.valid) {
1259
+ throw new ProjectValidationError(result);
1260
+ }
1261
+ }
1262
+ function yamlProblem(err) {
1263
+ const { code, message, pos, linePos } = err;
1264
+ throw new Error(`YAML error: ${code} ${message} at ${pos} ${linePos}`);
1265
+ }
1266
+
1267
+ // src/utils/serialization/serializationHelpers.ts
1268
+ var import_safe_stable_stringify2 = __toESM(require("safe-stable-stringify"), 1);
1269
+ var yaml = __toESM(require("yaml"), 1);
1270
+ var CONNECTION_BEND_MARKER = " __rivet_bend:";
1271
+ var CONNECTION_BEND_MARKER_TITLE_FALLBACK = " __rivet bend:";
1272
+ var FINITE_NUMBER_PATTERN = String.raw`[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?`;
1273
+ var CONNECTION_BEND_PATTERN = new RegExp(
1274
+ `${CONNECTION_BEND_MARKER.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(${FINITE_NUMBER_PATTERN}),(${FINITE_NUMBER_PATTERN})$`
1275
+ );
1276
+ function serializeConnection(connection, allNodes) {
1277
+ var _a;
1278
+ const targetTitle = serializeConnectionTargetTitle(
1279
+ ((_a = allNodes.find((node) => node.id === connection.inputNodeId)) == null ? void 0 : _a.title) ?? ""
1280
+ );
1281
+ const bendPoint = connection.bendPoint && Number.isFinite(connection.bendPoint.x) && Number.isFinite(connection.bendPoint.y) ? `${CONNECTION_BEND_MARKER}${connection.bendPoint.x},${connection.bendPoint.y}` : "";
1282
+ return `${connection.outputId}->"${targetTitle}${bendPoint}" ${connection.inputNodeId}/${connection.inputId}`;
1283
+ }
1284
+ function deserializeConnection(connection, sourceNodeId) {
1285
+ const match = connection.match(/(.+)->"(.*)"\s+(.+)\/(.+)/);
1286
+ if (!match) {
1287
+ throw new Error(`Invalid connection: ${connection}`);
1288
+ }
1289
+ const [, outputId, targetTitle, inputNodeId, inputId] = match;
1290
+ const bendPoint = deserializeConnectionBendPoint(targetTitle);
1291
+ return {
1292
+ outputId,
1293
+ outputNodeId: sourceNodeId,
1294
+ inputId,
1295
+ inputNodeId,
1296
+ ...bendPoint ? { bendPoint } : {}
1297
+ };
1298
+ }
1299
+ function serializeConnectionTargetTitle(targetTitle) {
1300
+ return targetTitle.replaceAll(CONNECTION_BEND_MARKER, CONNECTION_BEND_MARKER_TITLE_FALLBACK);
1301
+ }
1302
+ function deserializeConnectionBendPoint(targetTitle) {
1303
+ const match = targetTitle == null ? void 0 : targetTitle.match(CONNECTION_BEND_PATTERN);
1304
+ if (!match) {
1305
+ return void 0;
1306
+ }
1307
+ const x = Number.parseFloat(match[1]);
1308
+ const y = Number.parseFloat(match[2]);
1309
+ return Number.isFinite(x) && Number.isFinite(y) ? { x, y } : void 0;
1310
+ }
1311
+ function parseOptionalFloat(val) {
1312
+ return val === "null" || val === void 0 || val === "" ? void 0 : parseFloat(val);
1313
+ }
1314
+ function parseVisualData(packed) {
1315
+ const parts = packed.split("/");
1316
+ const [x, y, width, zIndex, borderColor, bgColor] = parts;
1317
+ return {
1318
+ x: parseFloat(x),
1319
+ y: parseFloat(y),
1320
+ width: parseOptionalFloat(width),
1321
+ zIndex: parseOptionalFloat(zIndex),
1322
+ borderColor: borderColor || void 0,
1323
+ bgColor: bgColor || void 0
1324
+ };
1325
+ }
1326
+ function packVisualDataV4(node) {
1327
+ var _a, _b;
1328
+ return `${node.visualData.x}/${node.visualData.y}/${node.visualData.width ?? "null"}/${node.visualData.zIndex ?? "null"}/${((_a = node.visualData.color) == null ? void 0 : _a.border) ?? ""}/${((_b = node.visualData.color) == null ? void 0 : _b.bg) ?? ""}`;
1329
+ }
1330
+ function wrapInYamlEnvelope(version, data) {
1331
+ const stabilized = JSON.parse((0, import_safe_stable_stringify2.default)(data) ?? "{}");
1332
+ return yaml.stringify({ version, data: stabilized }, null, { indent: 2 });
1333
+ }
1334
+ function unwrapYamlEnvelope(raw, expectedVersion, label) {
1335
+ if (typeof raw !== "string" && (!raw || typeof raw !== "object" || Array.isArray(raw))) {
1336
+ throw new Error(`${label} deserializer requires a string`);
1337
+ }
1338
+ const parsed = typeof raw === "string" ? yaml.parse(raw) : raw;
1339
+ if (parsed.version !== expectedVersion) {
1340
+ throw new Error(`${label} deserializer requires a version ${expectedVersion} ${label.toLowerCase()}`);
1341
+ }
1342
+ return parsed.data;
1343
+ }
1344
+
1345
+ // src/utils/serialization/serialization_v3.ts
1346
+ function projectV3Deserializer(data) {
1347
+ const serializedProject = unwrapYamlEnvelope(data, 3, "Project v3");
1348
+ const project = fromSerializedProject(serializedProject);
1349
+ doubleCheckProject(project);
1350
+ return project;
1351
+ }
1352
+ function graphV3Deserializer(data) {
1353
+ const serializedGraph = unwrapYamlEnvelope(data, 3, "Graph v3");
1354
+ return fromSerializedGraph(serializedGraph);
1355
+ }
1356
+ function fromSerializedProject(serializedProject) {
1357
+ return {
1358
+ metadata: serializedProject.metadata,
1359
+ graphs: (0, import_lodash_es.mapValues)(serializedProject.graphs, (graph) => fromSerializedGraph(graph)),
1360
+ plugins: []
1361
+ };
1362
+ }
1363
+ function fromSerializedGraph(serializedGraph) {
1364
+ const allConnections = [];
1365
+ const allNodes = [];
1366
+ for (const node of Object.values(serializedGraph.nodes)) {
1367
+ const [chartNode, connections] = fromSerializedNode(node);
1368
+ allNodes.push(chartNode);
1369
+ allConnections.push(...connections);
1370
+ }
1371
+ return {
1372
+ metadata: {
1373
+ id: serializedGraph.metadata.id,
1374
+ name: serializedGraph.metadata.name,
1375
+ description: serializedGraph.metadata.description
1376
+ },
1377
+ nodes: allNodes,
1378
+ connections: allConnections
1379
+ };
1380
+ }
1381
+ function fromSerializedNode(serializedNode) {
1382
+ const { x, y, width, zIndex } = parseVisualData(serializedNode.visualData);
1383
+ const connections = serializedNode.outgoingConnections.map(
1384
+ (conn) => deserializeConnection(conn, serializedNode.id)
1385
+ );
1386
+ return [
1387
+ {
1388
+ id: serializedNode.id,
1389
+ title: serializedNode.title,
1390
+ description: serializedNode.description,
1391
+ type: serializedNode.type,
1392
+ isSplitRun: serializedNode.isSplitRun,
1393
+ splitRunMax: serializedNode.splitRunMax,
1394
+ splitRunConcurrency: serializedNode.splitRunConcurrency,
1395
+ visualData: { x, y, width, zIndex },
1396
+ data: serializedNode.data,
1397
+ variants: serializedNode.variants
1398
+ },
1399
+ connections
1400
+ ];
1401
+ }
1402
+
1403
+ // src/utils/errors.ts
1404
+ function getError(error) {
1405
+ const errorInstance = typeof error === "object" && error instanceof Error ? error : new Error(error != null ? error.toString() : "Unknown error");
1406
+ return errorInstance;
1407
+ }
1408
+
1409
+ // src/utils/serialization/serialization_v4.ts
1410
+ var import_lodash_es2 = require("lodash");
1411
+
1412
+ // src/model/chat-v2/llmChatV2NodeMigration.ts
1413
+ function normalizeSerializedLLMTemperatureData(nodeType, data) {
1414
+ if (!["llmChatV2", "llmProfile"].includes(nodeType) || data == null || typeof data !== "object") return data;
1415
+ const record = data;
1416
+ if (!Object.hasOwn(record, "temperature")) return data;
1417
+ if (record.temperature != null && !(typeof record.temperature === "number" && Number.isNaN(record.temperature)))
1418
+ return data;
1419
+ const copy = { ...record };
1420
+ delete copy.temperature;
1421
+ return copy;
1422
+ }
1423
+ function normalizeSerializedLLMChatV2Node(node) {
1424
+ if (!["llmChatV2", "llmProfile"].includes(node.type)) return;
1425
+ for (const variant of node.variants ?? []) {
1426
+ variant.data = normalizeSerializedLLMTemperatureData(node.type, variant.data);
1427
+ }
1428
+ node.data = normalizeSerializedLLMTemperatureData(node.type, node.data);
1429
+ if (node.data == null || typeof node.data !== "object") return;
1430
+ const data = node.data;
1431
+ if (node.type !== "llmChatV2") return;
1432
+ const hadLegacyRequestDiagnostics = data.outputRequestStatus === true || data.outputRequestError === true;
1433
+ if (hadLegacyRequestDiagnostics && !Object.hasOwn(data, "outputLLMAttempts")) {
1434
+ data.outputLLMAttempts = true;
1435
+ }
1436
+ if (data.outputRequestStatus === true && !Object.hasOwn(data, "outputRequestBody")) {
1437
+ data.outputRequestBody = true;
1438
+ }
1439
+ delete data.outputRequestStatus;
1440
+ delete data.outputRequestError;
1441
+ }
1442
+
1443
+ // src/utils/typeSafety.ts
1444
+ var entries = (object) => object == null ? [] : Object.entries(object);
1445
+
1446
+ // src/model/NodeGraph.ts
1447
+ var import_non_secure3 = require("nanoid/non-secure");
1448
+
1449
+ // src/utils/serialization/serialization_v4.ts
1450
+ function projectV4Deserializer(data) {
1451
+ const serializedProject = unwrapYamlEnvelope(data, 4, "Project v4");
1452
+ const [project, attachedData] = fromSerializedProject2(serializedProject);
1453
+ doubleCheckProject(project);
1454
+ return [project, attachedData];
1455
+ }
1456
+ function graphV4Deserializer(data) {
1457
+ const serializedGraph = unwrapYamlEnvelope(data, 4, "Graph v4");
1458
+ return fromSerializedGraph2(serializedGraph);
1459
+ }
1460
+ function projectV4Serializer(project, attachedData) {
1461
+ if (!isValidProjectStaticData(project.data)) {
1462
+ throw new Error("Project data must be a record of static-data strings");
1463
+ }
1464
+ if (project.metadata.globalVariables != null) {
1465
+ validateProjectGlobalVariables(project.metadata.globalVariables);
1466
+ }
1467
+ const filteredProject = {
1468
+ ...project,
1469
+ metadata: {
1470
+ ...project.metadata,
1471
+ path: void 0
1472
+ }
1473
+ };
1474
+ return wrapInYamlEnvelope(4, toSerializedProject(filteredProject, attachedData));
1475
+ }
1476
+ function graphV4Serializer(graph) {
1477
+ return wrapInYamlEnvelope(4, toSerializedGraph(graph));
1478
+ }
1479
+ function toSerializedProject(project, attachedData) {
1480
+ const nodePrefabs = (0, import_lodash_es2.mapValues)(project.nodePrefabs ?? {}, (prefab) => ({
1481
+ id: prefab.id,
1482
+ sourceNode: toSerializedIsolatedNode(prefab.sourceNode)
1483
+ }));
1484
+ const uiGraphs = normalizeUiGraphRecord(project.uiGraphs === void 0 ? {} : project.uiGraphs);
1485
+ return {
1486
+ metadata: project.metadata,
1487
+ graphs: (0, import_lodash_es2.mapValues)(project.graphs, (graph) => toSerializedGraph(graph)),
1488
+ nodePrefabs: Object.keys(nodePrefabs).length > 0 ? nodePrefabs : void 0,
1489
+ uiGraphs: Object.keys(uiGraphs).length > 0 ? uiGraphs : void 0,
1490
+ attachedData,
1491
+ plugins: project.plugins ?? [],
1492
+ references: project.references ?? [],
1493
+ data: project.data
1494
+ };
1495
+ }
1496
+ function fromSerializedProject2(serializedProject) {
1497
+ const nodePrefabs = (0, import_lodash_es2.mapValues)(serializedProject.nodePrefabs ?? {}, (prefab) => ({
1498
+ id: prefab.id,
1499
+ sourceNode: fromSerializedIsolatedNode(prefab.sourceNode)
1500
+ }));
1501
+ const uiGraphs = normalizeUiGraphRecord(serializedProject.uiGraphs === void 0 ? {} : serializedProject.uiGraphs);
1502
+ return [
1503
+ {
1504
+ metadata: serializedProject.metadata,
1505
+ graphs: (0, import_lodash_es2.mapValues)(serializedProject.graphs, (graph) => fromSerializedGraph2(graph)),
1506
+ nodePrefabs: Object.keys(nodePrefabs).length > 0 ? nodePrefabs : void 0,
1507
+ uiGraphs: Object.keys(uiGraphs).length > 0 ? uiGraphs : void 0,
1508
+ plugins: serializedProject.plugins ?? [],
1509
+ references: serializedProject.references ?? [],
1510
+ ...serializedProject.data !== void 0 ? { data: serializedProject.data } : {}
1511
+ },
1512
+ serializedProject.attachedData ?? {}
1513
+ ];
1514
+ }
1515
+ function toSerializedIsolatedNode(node) {
1516
+ const { outgoingConnections: _outgoingConnections, ...serializedNode } = toSerializedNode(node, [node], []);
1517
+ return {
1518
+ ...serializedNode,
1519
+ id: node.id,
1520
+ type: node.type,
1521
+ title: node.title
1522
+ };
1523
+ }
1524
+ function fromSerializedIsolatedNode(serializedNode) {
1525
+ const [node] = fromSerializedNode2(
1526
+ {
1527
+ ...serializedNode,
1528
+ outgoingConnections: void 0
1529
+ },
1530
+ `[${serializedNode.id}]:${serializedNode.type} "${serializedNode.title}"`
1531
+ );
1532
+ return node;
1533
+ }
1534
+ function toSerializedGraph(graph) {
1535
+ const graphMetadata = {
1536
+ id: graph.metadata.id,
1537
+ name: graph.metadata.name,
1538
+ description: graph.metadata.description
1539
+ };
1540
+ if (graph.metadata.attachedData) {
1541
+ graphMetadata.attachedData = graph.metadata.attachedData;
1542
+ }
1543
+ return {
1544
+ metadata: graphMetadata,
1545
+ nodes: graph.nodes.reduce(
1546
+ (acc, node) => ({
1547
+ ...acc,
1548
+ [getGraphNodeKey(node)]: toSerializedNode(node, graph.nodes, graph.connections)
1549
+ }),
1550
+ {}
1551
+ )
1552
+ };
1553
+ }
1554
+ function getGraphNodeKey(node) {
1555
+ return `[${node.id}]:${node.type} "${node.title}"`;
1556
+ }
1557
+ function deserializeGraphNodeKey(key) {
1558
+ var _a;
1559
+ const { nodeId, type, title } = ((_a = key.match(/^\[(?<nodeId>[^\]]+)\]:(?<type>[^\s]+) "(?<title>.*)"$/)) == null ? void 0 : _a.groups) ?? {};
1560
+ if (!nodeId || !type || title == null) {
1561
+ throw new Error(`Invalid graph node key: ${key}`);
1562
+ }
1563
+ return [nodeId, type, title];
1564
+ }
1565
+ function fromSerializedGraph2(serializedGraph) {
1566
+ const allConnections = [];
1567
+ const allNodes = [];
1568
+ for (const [serializedNodeInfo, node] of entries(serializedGraph.nodes)) {
1569
+ const [chartNode, connections] = fromSerializedNode2(node, serializedNodeInfo);
1570
+ allNodes.push(chartNode);
1571
+ allConnections.push(...connections);
1572
+ }
1573
+ const metadata = {
1574
+ id: serializedGraph.metadata.id,
1575
+ name: serializedGraph.metadata.name,
1576
+ description: serializedGraph.metadata.description
1577
+ };
1578
+ if (serializedGraph.metadata.attachedData) {
1579
+ metadata.attachedData = serializedGraph.metadata.attachedData;
1580
+ }
1581
+ return {
1582
+ metadata,
1583
+ nodes: allNodes,
1584
+ connections: allConnections
1585
+ };
1586
+ }
1587
+ function toSerializedNode(node, allNodes, allConnections) {
1588
+ var _a, _b;
1589
+ const data = normalizeSerializedLLMTemperatureData(node.type, node.data);
1590
+ const outgoingConnections = allConnections.filter((connection) => connection.outputNodeId === node.id).map((connection) => serializeConnection(connection, allNodes)).sort();
1591
+ return {
1592
+ description: ((_a = node.description) == null ? void 0 : _a.trim()) ? node.description : void 0,
1593
+ visualData: packVisualDataV4(node),
1594
+ isSplitRun: node.isSplitRun ? true : void 0,
1595
+ splitRunMax: node.isSplitRun ? node.splitRunMax : void 0,
1596
+ splitRunConcurrency: node.isSplitRun ? node.splitRunConcurrency : void 0,
1597
+ isSplitSequential: node.isSplitSequential ? true : void 0,
1598
+ data: Object.keys(data ?? {}).length > 0 ? data : void 0,
1599
+ outgoingConnections: outgoingConnections.length > 0 ? outgoingConnections : void 0,
1600
+ variants: (((_b = node.variants) == null ? void 0 : _b.length) ?? 0) > 0 ? node.variants.map((variant) => ({
1601
+ ...variant,
1602
+ data: normalizeSerializedLLMTemperatureData(node.type, variant.data)
1603
+ })) : void 0,
1604
+ disabled: node.disabled ? true : void 0,
1605
+ isConditional: node.isConditional
1606
+ };
1607
+ }
1608
+ function fromSerializedNode2(serializedNode, serializedNodeInfo) {
1609
+ var _a;
1610
+ const [nodeId, type, title] = deserializeGraphNodeKey(serializedNodeInfo);
1611
+ const { x, y, width, zIndex, borderColor, bgColor } = parseVisualData(serializedNode.visualData);
1612
+ const connections = ((_a = serializedNode.outgoingConnections) == null ? void 0 : _a.map((conn) => deserializeConnection(conn, nodeId))) ?? [];
1613
+ const color = borderColor || bgColor ? { border: borderColor, bg: bgColor } : void 0;
1614
+ return [
1615
+ {
1616
+ id: nodeId,
1617
+ type,
1618
+ title,
1619
+ description: serializedNode.description,
1620
+ isSplitRun: serializedNode.isSplitRun ?? false,
1621
+ splitRunMax: serializedNode.splitRunMax ?? 10,
1622
+ splitRunConcurrency: serializedNode.splitRunConcurrency,
1623
+ isSplitSequential: serializedNode.isSplitSequential ?? false,
1624
+ visualData: {
1625
+ x,
1626
+ y,
1627
+ width,
1628
+ zIndex,
1629
+ color
1630
+ },
1631
+ data: serializedNode.data ?? {},
1632
+ variants: serializedNode.variants ?? [],
1633
+ disabled: serializedNode.disabled,
1634
+ isConditional: serializedNode.isConditional
1635
+ },
1636
+ connections
1637
+ ];
1638
+ }
1639
+ function datasetV4Serializer(datasets) {
1640
+ return JSON.stringify({ datasets });
1641
+ }
1642
+ function datasetV4Deserializer(serializedDatasets) {
1643
+ const dataContainer = JSON.parse(serializedDatasets);
1644
+ if (!dataContainer.datasets) {
1645
+ throw new Error("Invalid dataset data");
1646
+ }
1647
+ return dataContainer.datasets;
1648
+ }
1649
+
1650
+ // src/utils/serialization/serialization_v2.ts
1651
+ var yaml2 = __toESM(require("yaml"), 1);
1652
+ function projectV2Deserializer(data) {
1653
+ const project = unwrapV2Envelope(data, "Project v2");
1654
+ if (project.version !== 2) {
1655
+ throw new Error("Project v2 deserializer requires a version 2 project");
1656
+ }
1657
+ doubleCheckProject(project.data);
1658
+ return project.data;
1659
+ }
1660
+ function graphV2Deserializer(data) {
1661
+ const graph = unwrapV2Envelope(data, "Graph v2");
1662
+ if (graph.version !== 2) {
1663
+ throw new Error("Graph v2 deserializer requires a version 2 graph");
1664
+ }
1665
+ return graph.data;
1666
+ }
1667
+ function unwrapV2Envelope(data, label) {
1668
+ if (typeof data !== "string" && (!data || typeof data !== "object" || Array.isArray(data))) {
1669
+ throw new Error(`${label} deserializer requires a string`);
1670
+ }
1671
+ return typeof data === "string" ? yaml2.parse(data) : data;
1672
+ }
1673
+
1674
+ // src/utils/serialization/serialization_v1.ts
1675
+ function projectV1Deserializer(data) {
1676
+ if (typeof data !== "string") {
1677
+ throw new Error("Project v1 deserializer requires a string");
1678
+ }
1679
+ const project = JSON.parse(data);
1680
+ doubleCheckProject(project);
1681
+ return project;
1682
+ }
1683
+ function graphV1Deserializer(data) {
1684
+ if (typeof data !== "string") {
1685
+ throw new Error("Graph v1 deserializer requires a string");
1686
+ }
1687
+ const graph = JSON.parse(data);
1688
+ if (!graph.nodes || !graph.connections) {
1689
+ throw new Error("Invalid graph file");
1690
+ }
1691
+ return graph;
1692
+ }
1693
+
1694
+ // src/model/classifier/migration.ts
1695
+ var legacyTypesafePluginId = "typesafe";
1696
+ function isLegacyTypesafePlugin(spec) {
1697
+ return spec.type === "built-in" && spec.id === legacyTypesafePluginId;
1698
+ }
1699
+ function normalizeClassifierProject(project) {
1700
+ var _a;
1701
+ for (const graph of Object.values(project.graphs)) normalizeClassifierGraph(graph);
1702
+ for (const prefab of Object.values(project.nodePrefabs ?? {})) normalizeClassifierNode(prefab.sourceNode);
1703
+ if ((_a = project.plugins) == null ? void 0 : _a.some(isLegacyTypesafePlugin)) {
1704
+ project.plugins = project.plugins.filter((plugin) => !isLegacyTypesafePlugin(plugin));
1705
+ }
1706
+ }
1707
+ function normalizeClassifierGraph(graph) {
1708
+ for (const node of graph.nodes) normalizeClassifierNode(node);
1709
+ }
1710
+ function normalizeClassifierNode(node) {
1711
+ const legacyNode = node;
1712
+ switch (legacyNode.type) {
1713
+ case "jevChoiceQuestion":
1714
+ normalizeQuestionNode(legacyNode, "choice", "Jev Choice Question");
1715
+ return;
1716
+ case "jevScoreQuestion":
1717
+ normalizeQuestionNode(legacyNode, "score", "Jev Score Question");
1718
+ return;
1719
+ case "jevNoulQuestion":
1720
+ normalizeQuestionNode(legacyNode, "noul", "Jev Noul Question");
1721
+ return;
1722
+ case "jevEvaluate":
1723
+ normalizeEvaluateNode(legacyNode);
1724
+ return;
1725
+ case "classifierEvaluate":
1726
+ if (hasDeprecatedGlobalCredentialNames(legacyNode)) normalizeEvaluateNode(legacyNode);
1727
+ return;
1728
+ default:
1729
+ return;
1730
+ }
1731
+ }
1732
+ function hasDeprecatedGlobalCredentialNames(node) {
1733
+ return Object.prototype.hasOwnProperty.call(asRecord(node.data), "apiKeyNames");
1734
+ }
1735
+ function normalizeQuestionNode(node, questionType, legacyTitle) {
1736
+ node.type = "classifierQuestion";
1737
+ node.data = {
1738
+ ...asRecord(node.data),
1739
+ questionType
1740
+ };
1741
+ if (node.title === legacyTitle) node.title = "Classifier Question";
1742
+ }
1743
+ function normalizeEvaluateNode(node) {
1744
+ const legacyData = asRecord(node.data);
1745
+ const legacyApiKeyNames = legacyData.apiKeyNames;
1746
+ const existingNames = asRecord(legacyData.apiKeyNamesByProvider);
1747
+ const apiKeyNamesByProvider = legacyApiKeyNames === void 0 || Object.prototype.hasOwnProperty.call(existingNames, "jev") ? existingNames : { ...existingNames, jev: legacyApiKeyNames };
1748
+ const { apiKeyNames: _legacyApiKeyNames, ...dataWithoutLegacyNames } = legacyData;
1749
+ node.type = "classifierEvaluate";
1750
+ node.data = {
1751
+ ...dataWithoutLegacyNames,
1752
+ provider: typeof legacyData.provider === "string" && legacyData.provider ? legacyData.provider : "jev",
1753
+ ...Object.keys(apiKeyNamesByProvider).length > 0 ? { apiKeyNamesByProvider } : {}
1754
+ };
1755
+ if (node.title === "Jev Evaluate") node.title = "Classifier Evaluate";
1756
+ }
1757
+ function asRecord(value) {
1758
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1759
+ }
1760
+
1761
+ // src/utils/serialization/serialization.ts
1762
+ function serializeProject(project, attachedData) {
1763
+ return projectV4Serializer(project, attachedData);
1764
+ }
1765
+ var errMessage = (err) => `${getError(err).message}
1766
+ ${getError(err).stack}`;
1767
+ function deserializeProject(serializedProject, path = null, options = {}) {
1768
+ const { deserializerInput, version } = prepareSerializedInput(serializedProject);
1769
+ try {
1770
+ const result = deserializeProjectByVersion(deserializerInput, version);
1771
+ normalizeDeserializedProject(result[0]);
1772
+ if (path !== null) {
1773
+ result[0].metadata.path = path;
1774
+ }
1775
+ return result;
1776
+ } catch (err) {
1777
+ if (err instanceof yaml3.YAMLError) {
1778
+ yamlProblem(err);
1779
+ }
1780
+ if (options.logErrors !== false) console.warn(`Failed to deserialize project v${version}: ${errMessage(err)}`);
1781
+ if (err instanceof UiGraphNormalizationError) {
1782
+ throw new Error(`Could not deserialize project: ${err.message}`, { cause: err });
1783
+ }
1784
+ if (err instanceof ProjectValidationError) {
1785
+ throw new Error(`Could not deserialize project: ${err.message}`, { cause: err });
1786
+ }
1787
+ throw new Error("Could not deserialize project");
1788
+ }
1789
+ }
1790
+ function serializeGraph(graph) {
1791
+ return graphV4Serializer(graph);
1792
+ }
1793
+ function deserializeGraph(serializedGraph) {
1794
+ const { deserializerInput, version } = prepareSerializedInput(serializedGraph);
1795
+ try {
1796
+ const graph = deserializeGraphByVersion(deserializerInput, version);
1797
+ normalizeDeserializedGraph(graph);
1798
+ return graph;
1799
+ } catch (err) {
1800
+ if (err instanceof yaml3.YAMLError) {
1801
+ yamlProblem(err);
1802
+ }
1803
+ console.warn(`Failed to deserialize graph v${version}: ${errMessage(err)}`);
1804
+ throw new Error("Could not deserialize graph");
1805
+ }
1806
+ }
1807
+ function normalizeDeserializedProject(project) {
1808
+ normalizeClassifierProject(project);
1809
+ for (const graph of Object.values(project.graphs)) {
1810
+ normalizeDeserializedGraph(graph);
1811
+ }
1812
+ for (const prefab of Object.values(project.nodePrefabs ?? {})) {
1813
+ normalizeDeserializedNode(prefab.sourceNode);
1814
+ }
1815
+ }
1816
+ function normalizeDeserializedGraph(graph) {
1817
+ normalizeClassifierGraph(graph);
1818
+ for (const node of graph.nodes) {
1819
+ normalizeDeserializedNode(node);
1820
+ }
1821
+ }
1822
+ function hasLegacyDataBusFlag(node) {
1823
+ const data = node.data;
1824
+ return node.type === "passthrough" && data != null && Object.hasOwn(data, "renderAsDataBus");
1825
+ }
1826
+ function normalizeDeserializedNode(node) {
1827
+ normalizeClassifierNode(node);
1828
+ if (node.type === "code" && node.title === "Code") {
1829
+ node.title = "Code (legacy)";
1830
+ } else if (node.type === "codeNew" && node.title === "Code new") {
1831
+ node.title = "Code";
1832
+ }
1833
+ if (hasLegacyDataBusFlag(node)) {
1834
+ const { renderAsDataBus: _legacyFlag, ...data } = node.data;
1835
+ node.data = data;
1836
+ }
1837
+ normalizeSerializedLLMChatV2Node(node);
1838
+ }
1839
+ function deserializeProjectByVersion(serializedProject, version) {
1840
+ switch (version) {
1841
+ case 4:
1842
+ return projectV4Deserializer(serializedProject);
1843
+ case 3:
1844
+ return [projectV3Deserializer(serializedProject), {}];
1845
+ case 2:
1846
+ return [projectV2Deserializer(serializedProject), {}];
1847
+ case 1:
1848
+ default:
1849
+ return [projectV1Deserializer(serializedProject), {}];
1850
+ }
1851
+ }
1852
+ function deserializeGraphByVersion(serializedGraph, version) {
1853
+ switch (version) {
1854
+ case 4:
1855
+ return graphV4Deserializer(serializedGraph);
1856
+ case 3:
1857
+ return graphV3Deserializer(serializedGraph);
1858
+ case 2:
1859
+ return graphV2Deserializer(serializedGraph);
1860
+ case 1:
1861
+ default:
1862
+ return graphV1Deserializer(serializedGraph);
1863
+ }
1864
+ }
1865
+ function serializeDatasets(datasets) {
1866
+ return datasetV4Serializer(datasets);
1867
+ }
1868
+ function deserializeDatasets(serializedDatasets) {
1869
+ return datasetV4Deserializer(serializedDatasets);
1870
+ }
1871
+ // Annotate the CommonJS export names for ESM import in node:
1872
+ 0 && (module.exports = {
1873
+ deserializeDatasets,
1874
+ deserializeGraph,
1875
+ deserializeProject,
1876
+ serializeDatasets,
1877
+ serializeGraph,
1878
+ serializeProject
1879
+ });
1880
+ //# sourceMappingURL=serialization.cjs.map