@valerypopoff/rivet2-core 2.3.0 → 2.4.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 (55) hide show
  1. package/dist/cjs/bundle.cjs +517 -96
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +1537 -121
  4. package/dist/cjs/webAppRuntime.cjs.map +4 -4
  5. package/dist/esm/api/createProcessor.js +2 -0
  6. package/dist/esm/exports.js +2 -0
  7. package/dist/esm/model/AgentResponseTrace.js +16 -0
  8. package/dist/esm/model/GraphProcessor.js +14 -0
  9. package/dist/esm/model/NodeExclusionPolicy.js +9 -1
  10. package/dist/esm/model/ProcessContextBuilder.js +2 -1
  11. package/dist/esm/model/RecordingPlayer.js +8 -0
  12. package/dist/esm/model/SubprocessorBridge.js +1 -0
  13. package/dist/esm/model/UiGraphActionProtocol.js +46 -4
  14. package/dist/esm/model/UiGraphBrowserRuntime.js +15 -1
  15. package/dist/esm/model/UiGraphIndexedDbPersistence.js +523 -0
  16. package/dist/esm/model/UiGraphRendererStyles.js +14 -0
  17. package/dist/esm/model/WebAppBrowserStorage.js +653 -0
  18. package/dist/esm/model/WebAppBrowserStorageRpc.js +200 -0
  19. package/dist/esm/model/chat-v2/chatV2CallObserver.js +1 -0
  20. package/dist/esm/model/chat-v2/chatV2EditorCache.js +2 -33
  21. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +1 -0
  22. package/dist/esm/model/chat-v2/llmChatV2OutputClone.js +42 -0
  23. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +31 -2
  24. package/dist/esm/model/chat-v2/llmProfile.js +17 -1
  25. package/dist/esm/model/chat-v2/llmProfileFallback.js +17 -5
  26. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +2 -0
  27. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +4 -0
  28. package/dist/esm/model/chat-v2/toolContinuation.js +27 -1
  29. package/dist/esm/model/nodes/LLMChatV2Node.js +21 -2
  30. package/dist/esm/recording/ExecutionRecorder.js +1 -0
  31. package/dist/esm/webAppRuntime.js +5 -2
  32. package/dist/types/api/createProcessor.d.ts +2 -0
  33. package/dist/types/exports.d.ts +2 -0
  34. package/dist/types/model/AgentResponseTrace.d.ts +1 -0
  35. package/dist/types/model/ExecutorProtocol.d.ts +9 -1
  36. package/dist/types/model/GraphProcessor.d.ts +3 -1
  37. package/dist/types/model/NodeExclusionPolicy.d.ts +6 -0
  38. package/dist/types/model/ProcessContext.d.ts +33 -0
  39. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  40. package/dist/types/model/UiGraphActionProtocol.d.ts +8 -3
  41. package/dist/types/model/UiGraphBrowserRuntime.d.ts +6 -0
  42. package/dist/types/model/UiGraphIndexedDbPersistence.d.ts +50 -0
  43. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  44. package/dist/types/model/WebAppBrowserStorage.d.ts +90 -0
  45. package/dist/types/model/WebAppBrowserStorageRpc.d.ts +85 -0
  46. package/dist/types/model/chat-v2/chatV2Types.d.ts +3 -1
  47. package/dist/types/model/chat-v2/llmChatV2OutputClone.d.ts +3 -0
  48. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +5 -1
  49. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +4 -0
  50. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +10 -0
  51. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +6 -0
  52. package/dist/types/model/chat-v2/toolContinuation.d.ts +14 -0
  53. package/dist/types/recording/RecordedEvents.d.ts +11 -0
  54. package/dist/types/webAppRuntime.d.ts +8 -2
  55. package/package.json +1 -1
@@ -0,0 +1,653 @@
1
+ import { cloneRivetStoredValue } from './StoredValueStore.js';
2
+ export const RIVET_WEB_APP_BROWSER_STORAGE_DATABASE = 'rivet-web-app-browser-storage';
3
+ export const RIVET_WEB_APP_BROWSER_STORAGE_SCHEMA_VERSION = 1;
4
+ export const RIVET_WEB_APP_BROWSER_STORAGE_CHUNK_BYTES = 256 * 1024;
5
+ export const RIVET_WEB_APP_LEGACY_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
6
+ const METADATA_STORE = 'metadata';
7
+ const CHUNKS_STORE = 'chunks';
8
+ const MIGRATIONS_STORE = 'migrations';
9
+ const STAGING_STORE = 'staging';
10
+ const RECORD_GENERATION_INDEX = 'record-generation';
11
+ const SCHEMA_METADATA_ID = '__rivet_schema__';
12
+ const BROADCAST_CHANNEL_NAME = 'rivet-web-app-browser-storage:v1';
13
+ /**
14
+ * Browser-local Rivet web-app persistence. Values are chunked to avoid relying
15
+ * on browser-specific maximum IndexedDB record sizes. The memory mirror is
16
+ * updated even when persistence fails so the current page remains usable.
17
+ */
18
+ export class IndexedDbWebAppBrowserStorage {
19
+ #databaseName;
20
+ #factory;
21
+ #now;
22
+ #storageManager;
23
+ #broadcastChannelFactory;
24
+ #listeners = new Set();
25
+ #memory = new Map();
26
+ #memoryDeleted = new Set();
27
+ #memoryOnly = new Set();
28
+ #instanceId = createGeneration();
29
+ #knownRevisions = new Map();
30
+ #focusListener = () => void this.#recheckRevisions();
31
+ #channel;
32
+ #database;
33
+ #openPromise;
34
+ #scope;
35
+ #scopeId;
36
+ #status = { durable: false, reason: 'indexeddb-unavailable' };
37
+ #writeQueue = Promise.resolve();
38
+ #lastRevision = 0;
39
+ constructor(options = {}) {
40
+ this.#databaseName = options.databaseName ?? RIVET_WEB_APP_BROWSER_STORAGE_DATABASE;
41
+ this.#factory = options.indexedDB === undefined ? getDefaultIndexedDbFactory() : options.indexedDB ?? undefined;
42
+ this.#now = options.now ?? Date.now;
43
+ this.#storageManager = options.storageManager ?? getDefaultStorageManager();
44
+ this.#broadcastChannelFactory = options.broadcastChannelFactory ?? getDefaultBroadcastChannelFactory();
45
+ }
46
+ async initialize(scope) {
47
+ const normalized = normalizeScope(scope);
48
+ const nextScopeId = serializeScope(normalized);
49
+ if (this.#scopeId && this.#scopeId !== nextScopeId) {
50
+ throw new Error('A browser storage instance cannot be reused for another web app scope.');
51
+ }
52
+ this.#scope = normalized;
53
+ this.#scopeId = nextScopeId;
54
+ this.#ensureBroadcastChannel();
55
+ if (!this.#factory)
56
+ return this.#status;
57
+ try {
58
+ this.#database = await this.#openDatabase();
59
+ await this.#ensureSchemaMetadata();
60
+ this.#status = { durable: true };
61
+ await this.#removeAbandonedStaging();
62
+ globalThis.addEventListener?.('focus', this.#focusListener);
63
+ }
64
+ catch {
65
+ this.#status = { durable: false, reason: 'open-failed' };
66
+ }
67
+ return this.#status;
68
+ }
69
+ async get(namespace, key) {
70
+ const id = this.#recordId(namespace, key);
71
+ if (this.#memoryDeleted.has(id))
72
+ return undefined;
73
+ const memoryValue = this.#memory.get(id);
74
+ if (memoryValue !== undefined)
75
+ return cloneRivetStoredValue(memoryValue, 'Browser stored value');
76
+ if (!this.#database)
77
+ return undefined;
78
+ const transaction = this.#database.transaction([METADATA_STORE, CHUNKS_STORE], 'readonly');
79
+ const metadata = await requestResult(transaction.objectStore(METADATA_STORE).get(id));
80
+ if (!metadata) {
81
+ await transactionDone(transaction);
82
+ this.#knownRevisions.set(id, 0);
83
+ return undefined;
84
+ }
85
+ if (metadata.deleted) {
86
+ await transactionDone(transaction);
87
+ this.#memory.delete(id);
88
+ this.#memoryDeleted.add(id);
89
+ this.#knownRevisions.set(id, metadata.revision);
90
+ return undefined;
91
+ }
92
+ const chunks = await requestResult(transaction
93
+ .objectStore(CHUNKS_STORE)
94
+ .index(RECORD_GENERATION_INDEX)
95
+ .getAll(IDBKeyRange.only([id, metadata.generation])));
96
+ await transactionDone(transaction);
97
+ const value = decodeChunks(metadata, chunks);
98
+ this.#memory.set(id, value);
99
+ this.#knownRevisions.set(id, metadata.revision);
100
+ return cloneRivetStoredValue(value, 'Browser stored value');
101
+ }
102
+ async list(namespace) {
103
+ const scopeId = this.#requireScope();
104
+ const entries = new Map();
105
+ const database = this.#database;
106
+ if (database) {
107
+ const transaction = database.transaction([METADATA_STORE, CHUNKS_STORE], 'readonly');
108
+ const records = (await requestResult(transaction.objectStore(METADATA_STORE).getAll()))
109
+ .filter(isStoredRecordMetadata)
110
+ .filter((metadata) => metadata.scopeId === scopeId && metadata.namespace === namespace && !metadata.deleted)
111
+ .sort((left, right) => left.key.localeCompare(right.key));
112
+ for (const metadata of records) {
113
+ if (this.#memoryDeleted.has(metadata.id))
114
+ continue;
115
+ const memoryValue = this.#memory.get(metadata.id);
116
+ if (memoryValue !== undefined) {
117
+ entries.set(metadata.key, cloneRivetStoredValue(memoryValue, 'Browser stored value'));
118
+ continue;
119
+ }
120
+ const chunks = await requestResult(transaction
121
+ .objectStore(CHUNKS_STORE)
122
+ .index(RECORD_GENERATION_INDEX)
123
+ .getAll(IDBKeyRange.only([metadata.id, metadata.generation])));
124
+ const value = decodeChunks(metadata, chunks);
125
+ this.#memory.set(metadata.id, value);
126
+ this.#knownRevisions.set(metadata.id, metadata.revision);
127
+ entries.set(metadata.key, cloneRivetStoredValue(value, 'Browser stored value'));
128
+ }
129
+ await transactionDone(transaction);
130
+ }
131
+ const prefix = `${scopeId}\u0000${namespace}\u0000`;
132
+ for (const [id, value] of this.#memory) {
133
+ if (!id.startsWith(prefix) || this.#memoryDeleted.has(id))
134
+ continue;
135
+ entries.set(id.slice(prefix.length), cloneRivetStoredValue(value, 'Browser stored value'));
136
+ }
137
+ return [...entries].sort(([left], [right]) => left.localeCompare(right)).map(([key, value]) => ({ key, value }));
138
+ }
139
+ async set(namespace, key, value) {
140
+ return await this.commitBatch([{ key, namespace, value }]);
141
+ }
142
+ async delete(namespace, key) {
143
+ return await this.commitBatch([{ key, namespace }]);
144
+ }
145
+ async commitBatch(changes) {
146
+ this.#requireScope();
147
+ if (changes.length === 0)
148
+ return { ...this.#status, revision: this.#now() };
149
+ const prepared = changes.map((change) => prepareChange(this.#recordId(change.namespace, change.key), change));
150
+ if (new Set(prepared.map((change) => change.id)).size !== prepared.length) {
151
+ throw new Error('A browser storage batch cannot change the same scoped key more than once.');
152
+ }
153
+ for (const change of prepared) {
154
+ if (change.serialized) {
155
+ const parsed = cloneRivetStoredValue(JSON.parse(new TextDecoder().decode(change.serialized)), 'Browser stored value');
156
+ this.#memory.set(change.id, parsed);
157
+ this.#memoryDeleted.delete(change.id);
158
+ }
159
+ else {
160
+ this.#memory.delete(change.id);
161
+ this.#memoryDeleted.add(change.id);
162
+ }
163
+ }
164
+ const revision = this.#nextRevision();
165
+ try {
166
+ let committedRevision = revision;
167
+ await this.#enqueueWrite(async () => {
168
+ if (!this.#database)
169
+ throw new Error('IndexedDB is unavailable.');
170
+ committedRevision = await this.#commitPreparedChanges(prepared, revision);
171
+ });
172
+ this.#lastRevision = Math.max(this.#lastRevision, committedRevision);
173
+ for (const change of prepared) {
174
+ this.#memoryOnly.delete(change.id);
175
+ this.#knownRevisions.set(change.id, committedRevision);
176
+ this.#publishChange(change.namespace, change.key, committedRevision);
177
+ }
178
+ this.#status = this.#memoryOnly.size === 0 ? { durable: true } : { durable: false, reason: 'write-failed' };
179
+ return {
180
+ durable: true,
181
+ ...(this.#memoryOnly.size > 0 ? { hasMemoryOnlyRecords: true } : {}),
182
+ revision: committedRevision,
183
+ };
184
+ }
185
+ catch (error) {
186
+ for (const change of prepared)
187
+ this.#memoryOnly.add(change.id);
188
+ this.#status = { durable: false, reason: 'write-failed' };
189
+ throw new WebAppBrowserStoragePersistenceError('Browser data could not be saved. Changes will last only until this page is closed.', { cause: error, revision });
190
+ }
191
+ }
192
+ subscribe(listener) {
193
+ this.#listeners.add(listener);
194
+ return () => this.#listeners.delete(listener);
195
+ }
196
+ hasMemoryOnlyRecord(namespace, key) {
197
+ return this.#memoryOnly.has(this.#recordId(namespace, key));
198
+ }
199
+ async estimateUsage() {
200
+ if (!this.#storageManager)
201
+ return {};
202
+ try {
203
+ const estimate = await this.#storageManager.estimate();
204
+ return {
205
+ ...(typeof estimate.quota === 'number' ? { quota: estimate.quota } : {}),
206
+ ...(typeof estimate.usage === 'number' ? { usage: estimate.usage } : {}),
207
+ };
208
+ }
209
+ catch {
210
+ return {};
211
+ }
212
+ }
213
+ dispose() {
214
+ this.#channel?.close();
215
+ globalThis.removeEventListener?.('focus', this.#focusListener);
216
+ this.#channel = undefined;
217
+ this.#database?.close();
218
+ this.#database = undefined;
219
+ this.#openPromise = undefined;
220
+ this.#listeners.clear();
221
+ this.#knownRevisions.clear();
222
+ this.#memoryDeleted.clear();
223
+ this.#memoryOnly.clear();
224
+ }
225
+ async getMigration(legacyKey) {
226
+ const scopeId = this.#requireScope();
227
+ if (!this.#database)
228
+ return undefined;
229
+ const id = migrationId(scopeId, legacyKey);
230
+ const transaction = this.#database.transaction(MIGRATIONS_STORE, 'readonly');
231
+ const migration = await requestResult(transaction.objectStore(MIGRATIONS_STORE).get(id));
232
+ await transactionDone(transaction);
233
+ if (!migration)
234
+ return undefined;
235
+ return {
236
+ cleanupAfter: migration.cleanupAfter,
237
+ completedAt: migration.completedAt,
238
+ key: migration.key,
239
+ legacyKey: migration.legacyKey,
240
+ namespace: migration.namespace,
241
+ };
242
+ }
243
+ async recordMigration(migration) {
244
+ const scopeId = this.#requireScope();
245
+ if (!this.#database)
246
+ throw new Error('IndexedDB is unavailable.');
247
+ const transaction = this.#database.transaction(MIGRATIONS_STORE, 'readwrite');
248
+ transaction.objectStore(MIGRATIONS_STORE).put({
249
+ ...migration,
250
+ id: migrationId(scopeId, migration.legacyKey),
251
+ scopeId,
252
+ });
253
+ await transactionDone(transaction);
254
+ }
255
+ async listMigrations() {
256
+ const scopeId = this.#requireScope();
257
+ if (!this.#database)
258
+ return [];
259
+ const transaction = this.#database.transaction(MIGRATIONS_STORE, 'readonly');
260
+ const migrations = await requestResult(transaction.objectStore(MIGRATIONS_STORE).getAll());
261
+ await transactionDone(transaction);
262
+ return migrations
263
+ .filter((migration) => migration.scopeId === scopeId)
264
+ .map(({ cleanupAfter, completedAt, key, legacyKey, namespace }) => ({
265
+ cleanupAfter,
266
+ completedAt,
267
+ key,
268
+ legacyKey,
269
+ namespace,
270
+ }));
271
+ }
272
+ #recordId(namespace, key) {
273
+ const scopeId = this.#requireScope();
274
+ if (!key)
275
+ throw new Error('Browser storage key cannot be empty.');
276
+ return `${scopeId}\u0000${namespace}\u0000${key}`;
277
+ }
278
+ #requireScope() {
279
+ if (!this.#scopeId || !this.#scope)
280
+ throw new Error('Browser storage must be initialized before use.');
281
+ return this.#scopeId;
282
+ }
283
+ async #openDatabase() {
284
+ if (this.#database)
285
+ return this.#database;
286
+ if (this.#openPromise)
287
+ return await this.#openPromise;
288
+ if (!this.#factory)
289
+ throw new Error('IndexedDB is unavailable.');
290
+ this.#openPromise = new Promise((resolve, reject) => {
291
+ const request = this.#factory.open(this.#databaseName, RIVET_WEB_APP_BROWSER_STORAGE_SCHEMA_VERSION);
292
+ request.onupgradeneeded = () => {
293
+ const database = request.result;
294
+ if (!database.objectStoreNames.contains(METADATA_STORE)) {
295
+ database.createObjectStore(METADATA_STORE, { keyPath: 'id' });
296
+ }
297
+ if (!database.objectStoreNames.contains(CHUNKS_STORE)) {
298
+ const chunks = database.createObjectStore(CHUNKS_STORE, {
299
+ keyPath: ['recordId', 'generation', 'index'],
300
+ });
301
+ chunks.createIndex(RECORD_GENERATION_INDEX, ['recordId', 'generation']);
302
+ }
303
+ if (!database.objectStoreNames.contains(MIGRATIONS_STORE)) {
304
+ database.createObjectStore(MIGRATIONS_STORE, { keyPath: 'id' });
305
+ }
306
+ if (!database.objectStoreNames.contains(STAGING_STORE)) {
307
+ database.createObjectStore(STAGING_STORE, { keyPath: 'id' });
308
+ }
309
+ };
310
+ request.onerror = () => reject(request.error ?? new Error('Failed to open IndexedDB.'));
311
+ request.onblocked = () => reject(new Error('IndexedDB upgrade was blocked by another page.'));
312
+ request.onsuccess = () => {
313
+ const database = request.result;
314
+ database.onversionchange = () => database.close();
315
+ resolve(database);
316
+ };
317
+ });
318
+ try {
319
+ return await this.#openPromise;
320
+ }
321
+ finally {
322
+ this.#openPromise = undefined;
323
+ }
324
+ }
325
+ async #ensureSchemaMetadata() {
326
+ if (!this.#database)
327
+ return;
328
+ const transaction = this.#database.transaction(METADATA_STORE, 'readwrite');
329
+ transaction.objectStore(METADATA_STORE).put({
330
+ id: SCHEMA_METADATA_ID,
331
+ schemaVersion: RIVET_WEB_APP_BROWSER_STORAGE_SCHEMA_VERSION,
332
+ updatedAt: this.#now(),
333
+ });
334
+ await transactionDone(transaction);
335
+ }
336
+ async #commitPreparedChanges(prepared, revision) {
337
+ const database = this.#database;
338
+ const generation = createGeneration();
339
+ const staged = prepared.filter((change) => change.serialized != null);
340
+ if (staged.length > 0) {
341
+ const stageTransaction = database.transaction([CHUNKS_STORE, STAGING_STORE], 'readwrite');
342
+ const chunksStore = stageTransaction.objectStore(CHUNKS_STORE);
343
+ const stagingStore = stageTransaction.objectStore(STAGING_STORE);
344
+ for (const change of staged) {
345
+ const stagingId = `${change.id}\u0000${generation}`;
346
+ stagingStore.put({
347
+ createdAt: this.#now(),
348
+ generation,
349
+ id: stagingId,
350
+ recordId: change.id,
351
+ });
352
+ change.chunks.forEach((bytes, index) => {
353
+ chunksStore.put({ bytes, generation, index, recordId: change.id });
354
+ });
355
+ }
356
+ await transactionDone(stageTransaction);
357
+ const validationTransaction = database.transaction(CHUNKS_STORE, 'readonly');
358
+ const index = validationTransaction.objectStore(CHUNKS_STORE).index(RECORD_GENERATION_INDEX);
359
+ for (const change of staged) {
360
+ const chunks = await requestResult(index.getAll(IDBKeyRange.only([change.id, generation])));
361
+ decodeChunks({
362
+ byteLength: change.serialized.byteLength,
363
+ chunkCount: change.chunks.length,
364
+ generation,
365
+ id: change.id,
366
+ key: change.key,
367
+ namespace: change.namespace,
368
+ revision,
369
+ scopeId: this.#scopeId,
370
+ updatedAt: this.#now(),
371
+ }, chunks);
372
+ }
373
+ await transactionDone(validationTransaction);
374
+ }
375
+ const switchTransaction = database.transaction([METADATA_STORE, STAGING_STORE], 'readwrite');
376
+ const metadataStore = switchTransaction.objectStore(METADATA_STORE);
377
+ const stagingStore = switchTransaction.objectStore(STAGING_STORE);
378
+ const previous = [];
379
+ const priorRecords = [];
380
+ for (const change of prepared) {
381
+ const prior = await requestResult(metadataStore.get(change.id));
382
+ if (prior) {
383
+ priorRecords.push(prior);
384
+ if (!prior.deleted)
385
+ previous.push(prior);
386
+ }
387
+ }
388
+ const committedRevision = Math.max(revision, ...priorRecords.map((prior) => prior.revision + 1));
389
+ for (const change of prepared) {
390
+ const base = {
391
+ byteLength: change.serialized?.byteLength ?? 0,
392
+ chunkCount: change.serialized?.byteLength == null ? 0 : change.chunks.length,
393
+ deleted: change.serialized == null,
394
+ generation,
395
+ id: change.id,
396
+ key: change.key,
397
+ namespace: change.namespace,
398
+ revision: committedRevision,
399
+ scopeId: this.#scopeId,
400
+ updatedAt: this.#now(),
401
+ };
402
+ metadataStore.put(base);
403
+ if (change.serialized)
404
+ stagingStore.delete(`${change.id}\u0000${generation}`);
405
+ }
406
+ await transactionDone(switchTransaction);
407
+ void Promise.all(previous.map((metadata) => this.#deleteGeneration(metadata.id, metadata.generation))).catch(() => undefined);
408
+ return committedRevision;
409
+ }
410
+ async #deleteGeneration(recordId, generation) {
411
+ if (!this.#database)
412
+ return;
413
+ const transaction = this.#database.transaction(CHUNKS_STORE, 'readwrite');
414
+ const index = transaction.objectStore(CHUNKS_STORE).index(RECORD_GENERATION_INDEX);
415
+ const keys = await requestResult(index.getAllKeys(IDBKeyRange.only([recordId, generation])));
416
+ const store = transaction.objectStore(CHUNKS_STORE);
417
+ for (const key of keys)
418
+ store.delete(key);
419
+ await transactionDone(transaction);
420
+ }
421
+ async #removeAbandonedStaging() {
422
+ if (!this.#database)
423
+ return;
424
+ const transaction = this.#database.transaction(STAGING_STORE, 'readwrite');
425
+ const staging = await requestResult(transaction.objectStore(STAGING_STORE).getAll());
426
+ const store = transaction.objectStore(STAGING_STORE);
427
+ const abandoned = staging.filter((record) => this.#now() - record.createdAt >= 5 * 60 * 1000);
428
+ for (const record of abandoned)
429
+ store.delete(record.id);
430
+ await transactionDone(transaction);
431
+ await Promise.all(abandoned.map((record) => this.#deleteGeneration(record.recordId, record.generation)));
432
+ }
433
+ #ensureBroadcastChannel() {
434
+ if (this.#channel || !this.#broadcastChannelFactory)
435
+ return;
436
+ try {
437
+ this.#channel = this.#broadcastChannelFactory(BROADCAST_CHANNEL_NAME);
438
+ this.#channel.onmessage = (event) => {
439
+ const message = parseBroadcastMessage(event.data);
440
+ if (!message || message.sourceId === this.#instanceId || message.scopeId !== this.#scopeId)
441
+ return;
442
+ void this.#enqueueWrite(async () => {
443
+ const id = this.#recordId(message.namespace, message.key);
444
+ // Keep a failed local write visible in this tab until it can be saved.
445
+ // A remote durable revision must not erase the current live state.
446
+ if (this.#memoryOnly.has(id))
447
+ return;
448
+ const knownRevision = this.#knownRevisions.get(id);
449
+ if (knownRevision !== undefined && message.revision <= knownRevision)
450
+ return;
451
+ this.#memory.delete(id);
452
+ this.#memoryDeleted.delete(id);
453
+ this.#knownRevisions.set(id, message.revision);
454
+ const change = { key: message.key, namespace: message.namespace, revision: message.revision };
455
+ for (const listener of this.#listeners)
456
+ listener(change);
457
+ });
458
+ };
459
+ }
460
+ catch {
461
+ this.#channel = undefined;
462
+ }
463
+ }
464
+ #publishChange(namespace, key, revision) {
465
+ const change = { key, namespace, revision };
466
+ try {
467
+ this.#channel?.postMessage({
468
+ ...change,
469
+ scopeId: this.#scopeId,
470
+ sourceId: this.#instanceId,
471
+ type: 'record-changed',
472
+ });
473
+ }
474
+ catch {
475
+ // Cross-tab invalidation is best effort; durable state is already committed.
476
+ }
477
+ }
478
+ async #enqueueWrite(operation) {
479
+ const result = this.#writeQueue.catch(() => undefined).then(operation);
480
+ this.#writeQueue = result.catch(() => undefined);
481
+ await result;
482
+ }
483
+ #nextRevision() {
484
+ this.#lastRevision = Math.max(this.#lastRevision + 1, this.#now());
485
+ return this.#lastRevision;
486
+ }
487
+ async #recheckRevisions() {
488
+ if (!this.#database || !this.#scopeId)
489
+ return;
490
+ await this.#enqueueWrite(async () => {
491
+ if (!this.#database || !this.#scopeId)
492
+ return;
493
+ const transaction = this.#database.transaction(METADATA_STORE, 'readonly');
494
+ const records = (await requestResult(transaction.objectStore(METADATA_STORE).getAll())).filter(isStoredRecordMetadata);
495
+ await transactionDone(transaction);
496
+ for (const metadata of records) {
497
+ if (metadata.scopeId !== this.#scopeId)
498
+ continue;
499
+ // Focus-time rechecks follow the same rule as BroadcastChannel updates.
500
+ if (this.#memoryOnly.has(metadata.id))
501
+ continue;
502
+ const knownRevision = this.#knownRevisions.get(metadata.id);
503
+ if (knownRevision !== undefined && metadata.revision <= knownRevision)
504
+ continue;
505
+ this.#memory.delete(metadata.id);
506
+ this.#memoryDeleted.delete(metadata.id);
507
+ this.#knownRevisions.set(metadata.id, metadata.revision);
508
+ const change = {
509
+ key: metadata.key,
510
+ namespace: metadata.namespace,
511
+ revision: metadata.revision,
512
+ };
513
+ for (const listener of this.#listeners)
514
+ listener(change);
515
+ }
516
+ }).catch(() => undefined);
517
+ }
518
+ }
519
+ export class WebAppBrowserStoragePersistenceError extends Error {
520
+ revision;
521
+ constructor(message, options) {
522
+ super(message, options);
523
+ this.name = 'WebAppBrowserStoragePersistenceError';
524
+ this.revision = options.revision;
525
+ }
526
+ }
527
+ function prepareChange(id, change) {
528
+ if (!change.key)
529
+ throw new Error('Browser storage key cannot be empty.');
530
+ if (change.value === undefined) {
531
+ return { chunks: [], id, key: change.key, namespace: change.namespace };
532
+ }
533
+ const portable = cloneRivetStoredValue(change.value, 'Browser stored value');
534
+ const serialized = new TextEncoder().encode(JSON.stringify(portable));
535
+ const chunks = [];
536
+ for (let offset = 0; offset < serialized.byteLength; offset += RIVET_WEB_APP_BROWSER_STORAGE_CHUNK_BYTES) {
537
+ const chunk = serialized.slice(offset, Math.min(serialized.byteLength, offset + RIVET_WEB_APP_BROWSER_STORAGE_CHUNK_BYTES));
538
+ chunks.push(chunk.buffer);
539
+ }
540
+ if (chunks.length === 0)
541
+ chunks.push(new ArrayBuffer(0));
542
+ return { chunks, id, key: change.key, namespace: change.namespace, serialized };
543
+ }
544
+ function decodeChunks(metadata, chunks) {
545
+ if (chunks.length !== metadata.chunkCount)
546
+ throw new Error('Browser storage record is incomplete.');
547
+ chunks.sort((left, right) => left.index - right.index);
548
+ const bytes = new Uint8Array(metadata.byteLength);
549
+ let offset = 0;
550
+ for (let index = 0; index < chunks.length; index += 1) {
551
+ const chunk = chunks[index];
552
+ if (chunk.index !== index)
553
+ throw new Error('Browser storage record has invalid chunk ordering.');
554
+ const source = new Uint8Array(chunk.bytes);
555
+ if (offset + source.byteLength > bytes.byteLength)
556
+ throw new Error('Browser storage record exceeds its metadata.');
557
+ bytes.set(source, offset);
558
+ offset += source.byteLength;
559
+ }
560
+ if (offset !== metadata.byteLength)
561
+ throw new Error('Browser storage record byte length does not match its metadata.');
562
+ return cloneRivetStoredValue(JSON.parse(new TextDecoder().decode(bytes)), 'Browser stored value');
563
+ }
564
+ function isStoredRecordMetadata(value) {
565
+ if (!value || typeof value !== 'object' || Array.isArray(value))
566
+ return false;
567
+ const metadata = value;
568
+ return (typeof metadata.id === 'string' &&
569
+ metadata.id !== SCHEMA_METADATA_ID &&
570
+ typeof metadata.scopeId === 'string' &&
571
+ typeof metadata.key === 'string' &&
572
+ (metadata.namespace === 'chat-state' ||
573
+ metadata.namespace === 'response-traces' ||
574
+ metadata.namespace === 'stored-values') &&
575
+ typeof metadata.revision === 'number' &&
576
+ typeof metadata.generation === 'string' &&
577
+ typeof metadata.byteLength === 'number' &&
578
+ typeof metadata.chunkCount === 'number');
579
+ }
580
+ function normalizeScope(scope) {
581
+ if (!scope.origin)
582
+ throw new Error('Browser storage origin cannot be empty.');
583
+ if (!scope.uiGraphId)
584
+ throw new Error('Browser storage UI graph id cannot be empty.');
585
+ const pathname = scope.pathname.replace(/\/+$/, '') || '/';
586
+ return { origin: scope.origin, pathname, uiGraphId: scope.uiGraphId };
587
+ }
588
+ function serializeScope(scope) {
589
+ return [
590
+ encodeURIComponent(scope.origin),
591
+ encodeURIComponent(scope.pathname),
592
+ encodeURIComponent(scope.uiGraphId),
593
+ ].join(':');
594
+ }
595
+ function migrationId(scopeId, legacyKey) {
596
+ return `${scopeId}\u0000${legacyKey}`;
597
+ }
598
+ function createGeneration() {
599
+ return globalThis.crypto?.randomUUID?.() ?? `rivet-${Date.now()}-${Math.random().toString(36).slice(2)}`;
600
+ }
601
+ function getDefaultIndexedDbFactory() {
602
+ try {
603
+ return globalThis.indexedDB ?? globalThis.window?.indexedDB;
604
+ }
605
+ catch {
606
+ return undefined;
607
+ }
608
+ }
609
+ function getDefaultStorageManager() {
610
+ try {
611
+ return globalThis.navigator?.storage;
612
+ }
613
+ catch {
614
+ return undefined;
615
+ }
616
+ }
617
+ function getDefaultBroadcastChannelFactory() {
618
+ try {
619
+ return typeof globalThis.BroadcastChannel === 'function' ? (name) => new BroadcastChannel(name) : undefined;
620
+ }
621
+ catch {
622
+ return undefined;
623
+ }
624
+ }
625
+ function parseBroadcastMessage(value) {
626
+ if (!value || typeof value !== 'object' || Array.isArray(value))
627
+ return undefined;
628
+ const message = value;
629
+ return message.type === 'record-changed' &&
630
+ typeof message.scopeId === 'string' &&
631
+ typeof message.sourceId === 'string' &&
632
+ typeof message.key === 'string' &&
633
+ (message.namespace === 'chat-state' ||
634
+ message.namespace === 'response-traces' ||
635
+ message.namespace === 'stored-values') &&
636
+ Number.isSafeInteger(message.revision) &&
637
+ Number(message.revision) > 0
638
+ ? message
639
+ : undefined;
640
+ }
641
+ function requestResult(request) {
642
+ return new Promise((resolve, reject) => {
643
+ request.onsuccess = () => resolve(request.result);
644
+ request.onerror = () => reject(request.error ?? new Error('IndexedDB request failed.'));
645
+ });
646
+ }
647
+ function transactionDone(transaction) {
648
+ return new Promise((resolve, reject) => {
649
+ transaction.oncomplete = () => resolve();
650
+ transaction.onerror = () => reject(transaction.error ?? new Error('IndexedDB transaction failed.'));
651
+ transaction.onabort = () => reject(transaction.error ?? new Error('IndexedDB transaction was aborted.'));
652
+ });
653
+ }