@valerypopoff/rivet2-core 2.1.4 → 2.1.6

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 (107) hide show
  1. package/dist/cjs/bundle.cjs +6651 -1022
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +733 -19
  4. package/dist/cjs/webAppRuntime.cjs.map +3 -3
  5. package/dist/esm/api/createProcessor.js +6 -1
  6. package/dist/esm/exports.js +7 -0
  7. package/dist/esm/integrations/KnowledgeStore.js +1 -0
  8. package/dist/esm/integrations/KnowledgeStoreProvider.js +292 -0
  9. package/dist/esm/integrations/KnowledgeStoreValidation.js +428 -0
  10. package/dist/esm/integrations/ManagedKnowledgeStore.js +539 -0
  11. package/dist/esm/model/DataValue.js +22 -2
  12. package/dist/esm/model/GraphBoundaryEffects.js +13 -0
  13. package/dist/esm/model/GraphProcessor.js +1141 -82
  14. package/dist/esm/model/ManagedAsyncBranches.js +28 -0
  15. package/dist/esm/model/Nodes.js +27 -0
  16. package/dist/esm/model/ProcessContextBuilder.js +2 -1
  17. package/dist/esm/model/RecordingPlayer.js +9 -0
  18. package/dist/esm/model/StoredValueStore.js +226 -0
  19. package/dist/esm/model/SubprocessorBridge.js +50 -19
  20. package/dist/esm/model/ToolCallContinuation.js +1 -0
  21. package/dist/esm/model/UiGraph.js +52 -2
  22. package/dist/esm/model/UiGraphActionProtocol.js +10 -1
  23. package/dist/esm/model/UiGraphBrowserRuntime.js +444 -0
  24. package/dist/esm/model/UiGraphNormalization.js +35 -185
  25. package/dist/esm/model/UiGraphRendererStyles.js +878 -78
  26. package/dist/esm/model/UiGraphRuntimeModel.js +255 -15
  27. package/dist/esm/model/UiGraphSchema.js +91 -0
  28. package/dist/esm/model/UiGraphWebAppStorage.js +1 -0
  29. package/dist/esm/model/chat/chatMessages.js +5 -9
  30. package/dist/esm/model/chat/openAIChatRequest.js +8 -2
  31. package/dist/esm/model/chat-v2/chatV2Errors.js +36 -3
  32. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +8 -8
  33. package/dist/esm/model/chat-v2/index.js +1 -0
  34. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +3 -1
  35. package/dist/esm/model/chat-v2/parallelToolCalls.js +38 -0
  36. package/dist/esm/model/chat-v2/toolContinuation.js +45 -8
  37. package/dist/esm/model/chat-v2/toolContinuationConnection.js +68 -0
  38. package/dist/esm/model/nodes/BuildKnowledgeContextNode.js +157 -0
  39. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +12 -40
  40. package/dist/esm/model/nodes/GetKnowledgeSourceStatusNode.js +79 -0
  41. package/dist/esm/model/nodes/GetStoredValueNode.js +109 -0
  42. package/dist/esm/model/nodes/KnowledgeDocumentNode.js +88 -0
  43. package/dist/esm/model/nodes/KnowledgeSourceNode.js +94 -0
  44. package/dist/esm/model/nodes/LLMChatV2Node.js +17 -1
  45. package/dist/esm/model/nodes/MatchNode.js +7 -7
  46. package/dist/esm/model/nodes/SearchKnowledgeNode.js +127 -0
  47. package/dist/esm/model/nodes/SetStoredValueNode.js +84 -0
  48. package/dist/esm/model/nodes/StartBackgroundBranchNode.js +59 -0
  49. package/dist/esm/model/nodes/StoredValueNodeUtils.js +57 -0
  50. package/dist/esm/model/nodes/SyncKnowledgeSourceNode.js +149 -0
  51. package/dist/esm/model/nodes/ToolNode.js +14 -0
  52. package/dist/esm/model/nodes/toolCallDelegation.js +44 -1
  53. package/dist/esm/plugins/pinecone/PineconeKnowledgeStore.js +553 -0
  54. package/dist/esm/plugins/pinecone/plugin.js +32 -0
  55. package/dist/esm/recording/ExecutionRecorder.js +1 -0
  56. package/dist/esm/utils/coerceType.js +27 -2
  57. package/dist/esm/utils/getPluginConfig.js +12 -6
  58. package/dist/esm/utils/serialization/serialization.js +4 -1
  59. package/dist/esm/utils/serialization/serializationUtils.js +59 -1
  60. package/dist/esm/webAppRuntime.js +3 -3
  61. package/dist/types/api/createProcessor.d.ts +6 -0
  62. package/dist/types/exports.d.ts +7 -0
  63. package/dist/types/integrations/KnowledgeStore.d.ts +131 -0
  64. package/dist/types/integrations/KnowledgeStoreProvider.d.ts +46 -0
  65. package/dist/types/integrations/KnowledgeStoreValidation.d.ts +16 -0
  66. package/dist/types/integrations/ManagedKnowledgeStore.d.ts +57 -0
  67. package/dist/types/model/DataValue.d.ts +10 -3
  68. package/dist/types/model/EditorDefinition.d.ts +9 -2
  69. package/dist/types/model/ExecutorProtocol.d.ts +12 -0
  70. package/dist/types/model/GraphBoundaryEffects.d.ts +9 -1
  71. package/dist/types/model/GraphProcessor.d.ts +21 -2
  72. package/dist/types/model/ManagedAsyncBranches.d.ts +6 -0
  73. package/dist/types/model/Nodes.d.ts +11 -2
  74. package/dist/types/model/ProcessContext.d.ts +18 -0
  75. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  76. package/dist/types/model/Project.d.ts +11 -0
  77. package/dist/types/model/StoredValueStore.d.ts +55 -0
  78. package/dist/types/model/SubprocessorBridge.d.ts +4 -2
  79. package/dist/types/model/ToolCallContinuation.d.ts +13 -0
  80. package/dist/types/model/UiGraph.d.ts +24 -1
  81. package/dist/types/model/UiGraphActionProtocol.d.ts +2 -0
  82. package/dist/types/model/UiGraphBrowserRuntime.d.ts +75 -0
  83. package/dist/types/model/UiGraphRendererStyles.d.ts +2 -2
  84. package/dist/types/model/UiGraphRuntimeModel.d.ts +22 -3
  85. package/dist/types/model/UiGraphSchema.d.ts +113 -0
  86. package/dist/types/model/UiGraphWebAppStorage.d.ts +3 -0
  87. package/dist/types/model/chat-v2/index.d.ts +1 -0
  88. package/dist/types/model/chat-v2/parallelToolCalls.d.ts +9 -0
  89. package/dist/types/model/chat-v2/toolContinuation.d.ts +1 -0
  90. package/dist/types/model/chat-v2/toolContinuationConnection.d.ts +28 -0
  91. package/dist/types/model/nodes/BuildKnowledgeContextNode.d.ts +23 -0
  92. package/dist/types/model/nodes/GetKnowledgeSourceStatusNode.d.ts +19 -0
  93. package/dist/types/model/nodes/GetStoredValueNode.d.ts +25 -0
  94. package/dist/types/model/nodes/KnowledgeDocumentNode.d.ts +26 -0
  95. package/dist/types/model/nodes/KnowledgeSourceNode.d.ts +25 -0
  96. package/dist/types/model/nodes/SearchKnowledgeNode.d.ts +25 -0
  97. package/dist/types/model/nodes/SetStoredValueNode.d.ts +23 -0
  98. package/dist/types/model/nodes/StartBackgroundBranchNode.d.ts +14 -0
  99. package/dist/types/model/nodes/StoredValueNodeUtils.d.ts +5 -0
  100. package/dist/types/model/nodes/SyncKnowledgeSourceNode.d.ts +27 -0
  101. package/dist/types/model/nodes/ToolNode.d.ts +2 -0
  102. package/dist/types/model/nodes/toolCallDelegation.d.ts +4 -0
  103. package/dist/types/plugins/pinecone/PineconeKnowledgeStore.d.ts +11 -0
  104. package/dist/types/recording/RecordedEvents.d.ts +5 -0
  105. package/dist/types/utils/serialization/serializationUtils.d.ts +4 -0
  106. package/dist/types/webAppRuntime.d.ts +5 -4
  107. package/package.json +1 -1
@@ -1,4 +1,315 @@
1
+ import { getUiGraphChatDraftStateKey, getUiGraphChatMessages, getUiGraphChatMessagesStateKey, getUiGraphChatPins, getUiGraphChatPinsStateKey, } from './UiGraph.js';
1
2
  import { getUiGraphJsonOutputFilename } from './UiGraphRuntimeModel.js';
3
+ const OUTPUT_MAX_HEIGHT_PX = 800;
4
+ const OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO = 0.8;
5
+ const OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY = '--rivet-web-app-output-resize-min-height';
6
+ const OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY = '--rivet-web-app-output-resize-max-height';
7
+ const CHAT_SEARCH_MATCH_CLASS = 'rivet-web-app-chat-search-match';
8
+ const CHAT_SEARCH_ACTIVE_MATCH_CLASS = 'rivet-web-app-chat-search-match-active';
9
+ const UI_GRAPH_CHAT_STORAGE_PREFIX = 'rivet-web-app-chat-state:v1';
10
+ const UI_GRAPH_APP_STORAGE_PREFIX = 'rivet-web-app-storage:v1';
11
+ const escapeRegularExpression = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
12
+ const getPixelValue = (value, fallback) => {
13
+ const parsed = Number.parseFloat(value);
14
+ return Number.isFinite(parsed) ? parsed : fallback;
15
+ };
16
+ const setStyleProperty = (element, property, value) => {
17
+ if (element.style.getPropertyValue(property) !== value) {
18
+ element.style.setProperty(property, value);
19
+ }
20
+ };
21
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
22
+ const getDefaultUiGraphBrowserStorage = () => {
23
+ try {
24
+ return globalThis.localStorage ?? globalThis.window?.localStorage;
25
+ }
26
+ catch {
27
+ // Embedded, private, and restricted browser contexts can reject storage.
28
+ return undefined;
29
+ }
30
+ };
31
+ const getDefaultUiGraphStorageLocation = () => {
32
+ try {
33
+ return globalThis.location ?? globalThis.window?.location;
34
+ }
35
+ catch {
36
+ return undefined;
37
+ }
38
+ };
39
+ /**
40
+ * Formats persisted Chat timestamps in the current browser locale and timezone.
41
+ * Undated or malformed legacy messages deliberately remain present without time
42
+ * metadata rather than being assigned a fabricated date.
43
+ */
44
+ export function getUiGraphChatMessagePresentations(messages, options = {}) {
45
+ const { locales, timeZone } = options;
46
+ const timeFormatter = new Intl.DateTimeFormat(locales, {
47
+ hour: '2-digit',
48
+ hourCycle: 'h23',
49
+ minute: '2-digit',
50
+ ...(timeZone ? { timeZone } : {}),
51
+ });
52
+ const dateFormatter = new Intl.DateTimeFormat(locales, {
53
+ day: 'numeric',
54
+ month: 'long',
55
+ year: 'numeric',
56
+ ...(timeZone ? { timeZone } : {}),
57
+ });
58
+ const dateKeyFormatter = new Intl.DateTimeFormat('en-CA', {
59
+ day: '2-digit',
60
+ month: '2-digit',
61
+ year: 'numeric',
62
+ ...(timeZone ? { timeZone } : {}),
63
+ });
64
+ const entries = messages.map((message) => {
65
+ const timestamp = parseUiGraphChatTimestamp(message.timestamp);
66
+ if (!timestamp)
67
+ return undefined;
68
+ return {
69
+ dateKey: dateKeyFormatter.format(timestamp),
70
+ dateTime: timestamp.toISOString(),
71
+ dateLabel: dateFormatter.format(timestamp),
72
+ timeLabel: timeFormatter.format(timestamp),
73
+ };
74
+ });
75
+ const hasMultipleDates = new Set(entries.flatMap((entry) => (entry ? [entry.dateKey] : []))).size > 1;
76
+ let previousDateKey;
77
+ return entries.map((entry) => {
78
+ if (!entry)
79
+ return {};
80
+ const dateSeparator = hasMultipleDates && previousDateKey != null && previousDateKey !== entry.dateKey
81
+ ? { dateTime: entry.dateTime, label: entry.dateLabel }
82
+ : undefined;
83
+ previousDateKey = entry.dateKey;
84
+ return {
85
+ ...(dateSeparator ? { dateSeparator } : {}),
86
+ timestamp: { dateTime: entry.dateTime, label: entry.timeLabel },
87
+ };
88
+ });
89
+ }
90
+ const parseUiGraphChatTimestamp = (value) => {
91
+ if (typeof value !== 'string')
92
+ return undefined;
93
+ const timestamp = new Date(value);
94
+ return Number.isNaN(timestamp.getTime()) ? undefined : timestamp;
95
+ };
96
+ /** Returns the browser-local key for one app URL and one persisted UI graph. */
97
+ export function getUiGraphChatStorageKey(uiGraph, location = getDefaultUiGraphStorageLocation()) {
98
+ if (!location?.origin) {
99
+ return undefined;
100
+ }
101
+ const pathname = location.pathname.replace(/\/+$/, '') || '/';
102
+ return [
103
+ UI_GRAPH_CHAT_STORAGE_PREFIX,
104
+ encodeURIComponent(location.origin),
105
+ encodeURIComponent(pathname),
106
+ encodeURIComponent(uiGraph.id),
107
+ ].join(':');
108
+ }
109
+ /** Returns the browser-local key for graph-managed storage owned by one web app. */
110
+ export function getUiGraphWebAppStorageKey(uiGraph, location = getDefaultUiGraphStorageLocation()) {
111
+ if (!location?.origin) {
112
+ return undefined;
113
+ }
114
+ const pathname = location.pathname.replace(/\/+$/, '') || '/';
115
+ return [
116
+ UI_GRAPH_APP_STORAGE_PREFIX,
117
+ encodeURIComponent(location.origin),
118
+ encodeURIComponent(pathname),
119
+ encodeURIComponent(uiGraph.id),
120
+ ].join(':');
121
+ }
122
+ /** Loads the browser snapshot used by Stored Value nodes for this one web app. */
123
+ export function loadUiGraphWebAppStorage(uiGraph, storage = getDefaultUiGraphBrowserStorage(), location) {
124
+ const key = getUiGraphWebAppStorageKey(uiGraph, location);
125
+ if (!key || !storage)
126
+ return {};
127
+ try {
128
+ const serialized = storage.getItem(key);
129
+ if (!serialized)
130
+ return {};
131
+ const value = JSON.parse(serialized);
132
+ return isRecord(value) ? value : {};
133
+ }
134
+ catch {
135
+ return {};
136
+ }
137
+ }
138
+ /** Merges a successful action's changed keys and persists the complete app-local record. */
139
+ export function applyUiGraphWebAppStoragePatch(uiGraph, currentStorage, patch, storage = getDefaultUiGraphBrowserStorage(), location) {
140
+ const key = getUiGraphWebAppStorageKey(uiGraph, location);
141
+ if (!key || !storage) {
142
+ throw new Error('Browser storage is unavailable for this web app.');
143
+ }
144
+ const nextStorage = { ...currentStorage, ...patch };
145
+ let serialized;
146
+ try {
147
+ serialized = JSON.stringify(nextStorage);
148
+ storage.setItem(key, serialized);
149
+ }
150
+ catch (error) {
151
+ throw new Error('Web app storage could not be saved. Browser storage may be unavailable or full.', {
152
+ cause: error,
153
+ });
154
+ }
155
+ return nextStorage;
156
+ }
157
+ /**
158
+ * Applies the keys from one completed action that have not already been superseded.
159
+ * Ordering metadata is committed only after persistence succeeds, so a failed newer
160
+ * write cannot suppress an older successful action that completes later.
161
+ */
162
+ export function applyUiGraphWebAppStorageActionPatch(patch, actionNumber, appliedActionByKey, persist) {
163
+ const applicablePatch = Object.fromEntries(Object.entries(patch).filter(([key]) => actionNumber >= (appliedActionByKey.get(key) ?? 0)));
164
+ const applicableKeys = Object.keys(applicablePatch);
165
+ if (applicableKeys.length === 0)
166
+ return applicablePatch;
167
+ persist(applicablePatch);
168
+ for (const key of applicableKeys)
169
+ appliedActionByKey.set(key, actionNumber);
170
+ return applicablePatch;
171
+ }
172
+ /** Selects and validates the private browser-persisted state of Chat components only. */
173
+ export function getUiGraphChatPersistentState(uiGraph, state) {
174
+ const persistentState = {};
175
+ for (const component of uiGraph.components) {
176
+ if (component.type !== 'chat')
177
+ continue;
178
+ const draftStateKey = getUiGraphChatDraftStateKey(component.id);
179
+ const messagesStateKey = getUiGraphChatMessagesStateKey(component.id);
180
+ const pinsStateKey = getUiGraphChatPinsStateKey(component.id);
181
+ const draft = state[draftStateKey];
182
+ const messages = getUiGraphChatMessages(component.id, state);
183
+ const pins = getUiGraphChatPins(component.id, state).map((pin) => pin.messageIndex);
184
+ if (typeof draft === 'string' && draft) {
185
+ persistentState[draftStateKey] = draft;
186
+ }
187
+ if (messages.length > 0) {
188
+ persistentState[messagesStateKey] = messages;
189
+ }
190
+ if (pins.length > 0) {
191
+ persistentState[pinsStateKey] = pins;
192
+ }
193
+ }
194
+ return persistentState;
195
+ }
196
+ /**
197
+ * Reports whether a state transition changed the browser-persisted portion of
198
+ * any Chat. Runtime state updates are immutable, so reference comparison keeps
199
+ * action progress and unrelated form edits from serializing a large history.
200
+ */
201
+ export function hasUiGraphChatPersistentStateChanged(uiGraph, previousState, nextState) {
202
+ return uiGraph.components.some((component) => {
203
+ if (component.type !== 'chat')
204
+ return false;
205
+ return (previousState[getUiGraphChatDraftStateKey(component.id)] !==
206
+ nextState[getUiGraphChatDraftStateKey(component.id)] ||
207
+ previousState[getUiGraphChatMessagesStateKey(component.id)] !==
208
+ nextState[getUiGraphChatMessagesStateKey(component.id)] ||
209
+ previousState[getUiGraphChatPinsStateKey(component.id)] !== nextState[getUiGraphChatPinsStateKey(component.id)]);
210
+ });
211
+ }
212
+ /** Loads valid Chat-only state without allowing malformed local storage to affect rendering. */
213
+ export function loadUiGraphChatPersistentState(uiGraph, storage = getDefaultUiGraphBrowserStorage(), location) {
214
+ const key = getUiGraphChatStorageKey(uiGraph, location);
215
+ if (!key || !storage) {
216
+ return {};
217
+ }
218
+ try {
219
+ const serializedState = storage.getItem(key);
220
+ if (!serializedState) {
221
+ return {};
222
+ }
223
+ const storedState = JSON.parse(serializedState);
224
+ return isRecord(storedState) ? getUiGraphChatPersistentState(uiGraph, storedState) : {};
225
+ }
226
+ catch {
227
+ return {};
228
+ }
229
+ }
230
+ /** Persists only Chat draft, conversation, and pins for the current browser app URL. */
231
+ export function saveUiGraphChatPersistentState(uiGraph, state, storage = getDefaultUiGraphBrowserStorage(), location) {
232
+ const key = getUiGraphChatStorageKey(uiGraph, location);
233
+ if (!key || !storage) {
234
+ return;
235
+ }
236
+ try {
237
+ const persistentState = getUiGraphChatPersistentState(uiGraph, state);
238
+ if (Object.keys(persistentState).length === 0) {
239
+ storage.removeItem(key);
240
+ return;
241
+ }
242
+ const serializedState = JSON.stringify(persistentState);
243
+ if (storage.getItem(key) !== serializedState) {
244
+ storage.setItem(key, serializedState);
245
+ }
246
+ }
247
+ catch {
248
+ // Storage can be unavailable, full, or blocked; Chat itself still works.
249
+ }
250
+ }
251
+ /**
252
+ * Limits an expanded Output card's native resize range to one visible content
253
+ * line through its rendered value. Short, naturally-sized outputs have no resize
254
+ * handle because resizing them would only add blank space.
255
+ */
256
+ export function observeUiGraphOutputResizeBounds(output) {
257
+ const ownerWindow = output.ownerDocument.defaultView;
258
+ let scheduledFrame;
259
+ const sync = () => {
260
+ scheduledFrame = undefined;
261
+ if (!ownerWindow)
262
+ return;
263
+ const header = output.querySelector('.rivet-web-app-output-header');
264
+ const content = output.querySelector('.rivet-web-app-output-content');
265
+ const body = output.querySelector('.rivet-web-app-output-content-body');
266
+ if (!header || !content || !body) {
267
+ output.classList.remove('rivet-web-app-output-resizable');
268
+ output.classList.remove('rivet-web-app-output-scrollable');
269
+ output.style.removeProperty(OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY);
270
+ output.style.removeProperty(OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY);
271
+ return;
272
+ }
273
+ const bodyStyle = ownerWindow.getComputedStyle(body);
274
+ const lineHeight = getPixelValue(bodyStyle.lineHeight, getPixelValue(bodyStyle.fontSize, 16) * 1.5);
275
+ const contentStyle = ownerWindow.getComputedStyle(content);
276
+ const contentPadding = getPixelValue(contentStyle.paddingTop, 0) + getPixelValue(contentStyle.paddingBottom, 0);
277
+ const verticalBorder = Math.max(0, output.offsetHeight - output.clientHeight);
278
+ const minimumHeight = Math.ceil(header.getBoundingClientRect().height + contentPadding + lineHeight + verticalBorder);
279
+ const naturalHeight = Math.ceil(header.getBoundingClientRect().height + contentPadding + Math.max(body.scrollHeight, lineHeight) + verticalBorder);
280
+ const viewportHeight = ownerWindow?.innerHeight ?? OUTPUT_MAX_HEIGHT_PX / OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO;
281
+ const maximumViewportHeight = Math.min(viewportHeight * OUTPUT_MAX_VIEWPORT_HEIGHT_RATIO, OUTPUT_MAX_HEIGHT_PX);
282
+ output.classList.toggle('rivet-web-app-output-resizable', naturalHeight > maximumViewportHeight);
283
+ output.classList.toggle('rivet-web-app-output-scrollable', body.scrollHeight > body.clientHeight);
284
+ setStyleProperty(output, OUTPUT_RESIZE_MIN_HEIGHT_PROPERTY, `${minimumHeight}px`);
285
+ setStyleProperty(output, OUTPUT_RESIZE_MAX_HEIGHT_PROPERTY, `${naturalHeight}px`);
286
+ };
287
+ const scheduleSync = () => {
288
+ if (scheduledFrame != null)
289
+ return;
290
+ if (ownerWindow?.requestAnimationFrame) {
291
+ scheduledFrame = ownerWindow.requestAnimationFrame(sync);
292
+ }
293
+ else {
294
+ sync();
295
+ }
296
+ };
297
+ const resizeObserver = ownerWindow?.ResizeObserver ? new ownerWindow.ResizeObserver(scheduleSync) : undefined;
298
+ resizeObserver?.observe(output);
299
+ const mutationObserver = ownerWindow?.MutationObserver ? new ownerWindow.MutationObserver(scheduleSync) : undefined;
300
+ mutationObserver?.observe(output, { childList: true, characterData: true, subtree: true });
301
+ output.addEventListener('load', scheduleSync, true);
302
+ ownerWindow?.addEventListener('resize', scheduleSync);
303
+ sync();
304
+ return () => {
305
+ if (scheduledFrame != null)
306
+ ownerWindow?.cancelAnimationFrame(scheduledFrame);
307
+ resizeObserver?.disconnect();
308
+ mutationObserver?.disconnect();
309
+ output.removeEventListener('load', scheduleSync, true);
310
+ ownerWindow?.removeEventListener('resize', scheduleSync);
311
+ };
312
+ }
2
313
  /** Copies rendered web-app output without requiring the modern Clipboard API. */
3
314
  export async function copyUiGraphText(value) {
4
315
  try {
@@ -38,3 +349,136 @@ export function downloadUiGraphJsonOutput(value, appName) {
38
349
  globalThis.setTimeout(() => URL.revokeObjectURL(url), 0);
39
350
  }
40
351
  }
352
+ /**
353
+ * Adds Rivet-owned Copy and Download controls to sanitized fenced JSON blocks.
354
+ * The Markdown renderer must run first: this helper never accepts or inserts
355
+ * author-provided interactive markup.
356
+ */
357
+ export function enhanceUiGraphChatJsonCodeBlocks(root, appName) {
358
+ const codeBlocks = root.querySelectorAll('pre > code.language-json');
359
+ root.classList.toggle('rivet-web-app-chat-markdown-has-json', codeBlocks.length > 0);
360
+ for (const code of codeBlocks) {
361
+ const pre = code.parentElement;
362
+ const existingWrapper = pre?.parentElement;
363
+ if (!pre) {
364
+ continue;
365
+ }
366
+ if (existingWrapper?.classList.contains('rivet-web-app-chat-json-block')) {
367
+ existingWrapper.dataset.rivetChatJsonAppName = appName;
368
+ continue;
369
+ }
370
+ const value = code.textContent ?? '';
371
+ const document = root.ownerDocument;
372
+ const wrapper = document.createElement('div');
373
+ wrapper.className = 'rivet-web-app-chat-json-block';
374
+ wrapper.dataset.rivetChatJsonAppName = appName;
375
+ const actions = document.createElement('div');
376
+ actions.className = 'rivet-web-app-chat-json-actions';
377
+ actions.dataset.rivetChatSearchIgnore = 'true';
378
+ const copyButton = document.createElement('button');
379
+ copyButton.type = 'button';
380
+ copyButton.className = 'rivet-web-app-output-action-button rivet-web-app-output-copy-button';
381
+ copyButton.title = 'Copy JSON';
382
+ copyButton.setAttribute('aria-label', 'Copy JSON');
383
+ copyButton.addEventListener('click', (event) => {
384
+ event.stopPropagation();
385
+ void copyUiGraphText(value);
386
+ });
387
+ const downloadButton = document.createElement('button');
388
+ downloadButton.type = 'button';
389
+ downloadButton.className = 'rivet-web-app-output-action-button rivet-web-app-output-download-button';
390
+ downloadButton.title = 'Download JSON';
391
+ downloadButton.setAttribute('aria-label', 'Download JSON');
392
+ downloadButton.addEventListener('click', (event) => {
393
+ event.stopPropagation();
394
+ downloadUiGraphJsonOutput(value, wrapper.dataset.rivetChatJsonAppName ?? appName);
395
+ });
396
+ actions.append(copyButton, downloadButton);
397
+ pre.replaceWith(wrapper);
398
+ wrapper.append(pre, actions);
399
+ const syncScrollableState = () => {
400
+ wrapper.classList.toggle('rivet-web-app-chat-json-block-scrollable', pre.scrollHeight > pre.clientHeight);
401
+ };
402
+ syncScrollableState();
403
+ root.ownerDocument.defaultView?.requestAnimationFrame(syncScrollableState);
404
+ }
405
+ }
406
+ /**
407
+ * Replaces visible chat-message text matches with safe `<mark>` elements. This
408
+ * operates on rendered Markdown DOM rather than source Markdown, so search
409
+ * follows what the user can actually read.
410
+ */
411
+ export function highlightUiGraphChatSearchMatches(messagesElement, query, requestedActiveIndex = 0) {
412
+ clearUiGraphChatSearchMatches(messagesElement);
413
+ const searchText = query.trim();
414
+ if (!searchText) {
415
+ return { activeIndex: -1, matches: [] };
416
+ }
417
+ const document = messagesElement.ownerDocument;
418
+ const textNodes = [];
419
+ const walker = document.createTreeWalker(messagesElement, 4);
420
+ let node = walker.nextNode();
421
+ while (node) {
422
+ if (node.parentElement?.closest('script, style, textarea, [data-rivet-chat-search-ignore]')) {
423
+ node = walker.nextNode();
424
+ continue;
425
+ }
426
+ textNodes.push(node);
427
+ node = walker.nextNode();
428
+ }
429
+ const matches = [];
430
+ for (const textNode of textNodes) {
431
+ const value = textNode.data;
432
+ const ranges = [];
433
+ const expression = new RegExp(escapeRegularExpression(searchText), 'gi');
434
+ for (const match of value.matchAll(expression)) {
435
+ if (match.index != null && match[0]) {
436
+ ranges.push({ start: match.index, end: match.index + match[0].length });
437
+ }
438
+ }
439
+ if (ranges.length === 0 || !textNode.parentNode) {
440
+ continue;
441
+ }
442
+ const fragment = document.createDocumentFragment();
443
+ let cursor = 0;
444
+ for (const range of ranges) {
445
+ fragment.append(value.slice(cursor, range.start));
446
+ const match = document.createElement('mark');
447
+ match.className = CHAT_SEARCH_MATCH_CLASS;
448
+ match.textContent = value.slice(range.start, range.end);
449
+ fragment.append(match);
450
+ matches.push(match);
451
+ cursor = range.end;
452
+ }
453
+ fragment.append(value.slice(cursor));
454
+ textNode.parentNode.replaceChild(fragment, textNode);
455
+ }
456
+ if (matches.length === 0) {
457
+ return { activeIndex: -1, matches };
458
+ }
459
+ const activeIndex = ((requestedActiveIndex % matches.length) + matches.length) % matches.length;
460
+ matches[activeIndex]?.classList.add(CHAT_SEARCH_ACTIVE_MATCH_CLASS);
461
+ return { activeIndex, matches };
462
+ }
463
+ /** Removes transient chat-search markup without changing the rendered message text. */
464
+ export function clearUiGraphChatSearchMatches(messagesElement) {
465
+ for (const match of messagesElement.querySelectorAll(`.${CHAT_SEARCH_MATCH_CLASS}`)) {
466
+ match.replaceWith(messagesElement.ownerDocument.createTextNode(match.textContent ?? ''));
467
+ }
468
+ messagesElement.normalize();
469
+ }
470
+ /** Reveals a rendered message or search match inside the chat's own scroll region. */
471
+ export function revealUiGraphChatElement(messagesElement, element, alignment = 'center') {
472
+ if (!element || !messagesElement.contains(element)) {
473
+ return;
474
+ }
475
+ const containerRect = messagesElement.getBoundingClientRect();
476
+ const elementRect = element.getBoundingClientRect();
477
+ const maxScrollTop = Math.max(0, messagesElement.scrollHeight - messagesElement.clientHeight);
478
+ const offset = elementRect.top -
479
+ containerRect.top -
480
+ (alignment === 'center' ? (messagesElement.clientHeight - elementRect.height) / 2 : 0);
481
+ messagesElement.scrollTop = Math.max(0, Math.min(maxScrollTop, messagesElement.scrollTop + offset));
482
+ }
483
+ /** Centers the active chat-search match inside the chat's own scroll region. */
484
+ export const revealUiGraphChatSearchMatch = revealUiGraphChatElement;