@open-artifact/live-store 0.0.0-stage → 0.2.1

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.
package/src/engine.js ADDED
@@ -0,0 +1,1270 @@
1
+ /**
2
+ * The live sync engine: keeps a value in step with a document store (a
3
+ * board: one document per element plus a few board records; a dashboard:
4
+ * its datasets, page files and settings).
5
+ *
6
+ * Model, per document path:
7
+ * - `server`: the last value the store reported (by listing, a change event,
8
+ * or our own acknowledged write);
9
+ * - `acked`: our writes acknowledged in the last few seconds, re-applied over
10
+ * `server` so a late event about an older write does not flash old data;
11
+ * - `inflight`: the change being written;
12
+ * - `pending`: the change waiting to be written (debounced, merged).
13
+ *
14
+ * What the viewer sees is `server ⊕ acked ⊕ inflight ⊕ pending`. Changes are
15
+ * JSON merge patches computed against the document as it was before them, so
16
+ * two people editing different fields of one element both win; the same
17
+ * field: the last write wins.
18
+ *
19
+ * Local edits are applied at once ({@link LiveStore.commit}), split into
20
+ * documents on the next tick, and written after {@link LIVE_EDIT_DEBOUNCE_MS}
21
+ * of quiet (at most {@link LIVE_EDIT_MAX_WAIT_MS} after the first edit). Failed
22
+ * writes are retried with backoff; a document the store refuses (too large,
23
+ * invalid) is parked and the rest keep syncing. Losing write access stops
24
+ * syncing and keeps the edits on screen.
25
+ *
26
+ * Saved copy: with a {@link LiveCache}, the engine keeps the documents the
27
+ * store confirmed on the device. When the store does not answer within
28
+ * {@link LIVE_SNAPSHOT_TIMEOUT_MS}, or loading fails for a reason other than
29
+ * access, the saved copy is shown (`cached`): people can keep editing, and
30
+ * their edits wait until the store answers, then sync over what it holds.
31
+ *
32
+ * The engine is framework-agnostic: {@link LiveStore.getSnapshot} and
33
+ * {@link LiveStore.subscribe} fit React's `useSyncExternalStore` or a Zustand
34
+ * store.
35
+ */
36
+ import { applyJsonMergePatch, canonicalValuesEqual, countMergePatchTombstones, createJsonMergePatch, escapedJsonByteLength, isPlainRecord, removeNullMergePatchFields, } from "./json.js";
37
+ import { SYSTEM_TIMERS, collectionOfPath, isAccessError, syncErrorCode, syncErrorMessage, } from "./transport.js";
38
+ /* -------------------------------------------------------------------------- */
39
+ /* Tuning */
40
+ /* -------------------------------------------------------------------------- */
41
+ /** Quiet time after the last edit of a document before it is written. */
42
+ export const LIVE_EDIT_DEBOUNCE_MS = 350;
43
+ /** Longest a document waits after its first unsent edit. */
44
+ export const LIVE_EDIT_MAX_WAIT_MS = 1500;
45
+ /** After this long loading, the saved copy shows (when there is one), else the status says it is still loading. */
46
+ export const LIVE_SNAPSHOT_TIMEOUT_MS = 10_000;
47
+ /** After this long loading, the load counts as failed and is retried. */
48
+ export const LIVE_EXTENDED_LOAD_TIMEOUT_MS = 35_000;
49
+ /** Delays between load retries; the last one repeats. */
50
+ export const LIVE_RECONNECT_BACKOFF_MS = [2000, 4000, 8000, 15_000, 30_000, 60_000];
51
+ /** How long an acknowledged write is re-applied over store events. */
52
+ export const ACKNOWLEDGED_WRITE_GRACE_MS = 5000;
53
+ /** A write that has not settled after this long is retried. */
54
+ export const STUCK_WRITE_TIMEOUT_MS = 60_000;
55
+ /** A patch deleting more fields than this is sent as a whole document instead. */
56
+ export const MAX_MERGE_PATCH_TOMBSTONES = 64;
57
+ /** The first retry after a failed write waits a random time in this range. */
58
+ export const INITIAL_WRITE_RETRY_JITTER_MS = [300, 800];
59
+ /** Later retries: `min(MAX, BASE · 2^(failures − 2))`. */
60
+ export const WRITE_RETRY_BASE_MS = 2000;
61
+ export const WRITE_RETRY_MAX_MS = 30_000;
62
+ /** Retries when the store says it is overloaded: `min(MAX, BASE · 2^(failures − 1))`. */
63
+ export const BACKPRESSURE_RETRY_BASE_MS = 1000;
64
+ export const BACKPRESSURE_RETRY_MAX_MS = 8000;
65
+ /** Overload lasting this long shows as an error. */
66
+ export const BACKPRESSURE_ERROR_AFTER_MS = 30_000;
67
+ /** Shortest timer the engine sets. */
68
+ export const MIN_SYNC_TIMER_DELAY_MS = 16;
69
+ /** Acknowledged writes kept per document, at most. */
70
+ export const MAX_UNCOALESCED_ACKNOWLEDGED_WRITES = 8;
71
+ /** Write calls in flight at once, at most. */
72
+ export const MAX_CONCURRENT_LIVE_WRITES = 25;
73
+ /** Documents per write call, at most (the store allows 500). */
74
+ export const MAX_WRITES_PER_BATCH = 100;
75
+ /** Approximate bytes per write call, at most (one larger document still goes alone). */
76
+ export const MAX_BATCH_BYTES = 1_048_576;
77
+ /** Quiet time before the saved copy is updated after the store's documents change. */
78
+ export const LIVE_CACHE_WRITE_DELAY_MS = 2000;
79
+ /** Why {@link LiveStore.whenWritten} rejected. */
80
+ export class LiveWriteError extends Error {
81
+ code;
82
+ path;
83
+ constructor(code, message, path) {
84
+ super(message);
85
+ this.name = 'LiveWriteError';
86
+ this.code = code;
87
+ this.path = path;
88
+ }
89
+ }
90
+ /* -------------------------------------------------------------------------- */
91
+ /* Messages */
92
+ /* -------------------------------------------------------------------------- */
93
+ /** Status and notice texts (English defaults). */
94
+ export const LIVE_MESSAGES = {
95
+ loading: 'Loading the latest content…',
96
+ loadingSlow: 'Still loading the latest content…',
97
+ loadFailed: 'The latest content failed to load. Click to retry.',
98
+ cached: 'Showing your saved copy. Reconnecting…',
99
+ cachedEdits: 'Showing your saved copy. Your changes will sync when you’re back online.',
100
+ cachedReadOnly: 'Showing a saved copy. Reconnecting…',
101
+ readOnly: 'Read-only. You’re seeing live changes.',
102
+ accessEnded: 'Live sync ended for this view. Reload to continue.',
103
+ parkedSuffix: 'Other changes keep syncing.',
104
+ refusedHint: 'Shorten it to resume syncing this item.',
105
+ retryHint: 'Click to retry.',
106
+ unreachableNow: 'The store is unreachable. Retrying now. Your edits are kept on this screen.',
107
+ unreachableLater: 'The store is unreachable. Retrying shortly; click to retry now. Your edits are kept on this screen.',
108
+ busy: 'The store is busy. Your edits are kept on this screen and will sync when it recovers.',
109
+ saving: 'Syncing…',
110
+ syncedHint: 'Edits sync as you go; if two people change the same thing, the last change wins.',
111
+ itemGone: 'An item you were editing was deleted by someone else.',
112
+ cannotStore: (why) => `This change can’t be stored (${why}).`,
113
+ waiting: (count) => (count === 1 ? '1 change waiting to sync.' : `${count} changes waiting to sync.`),
114
+ syncedAt: (time) => `All changes synced · ${time}.`,
115
+ synced: 'Synced.',
116
+ };
117
+ const DELETE = { kind: 'delete' };
118
+ /**
119
+ * Applies a change to a document; a patch on a document someone deleted
120
+ * stays deleted. With `keepsNulls` a whole document keeps its `null` values.
121
+ */
122
+ function applyDocumentChange(doc, change, removed, keepsNulls = false) {
123
+ if (change.kind === 'delete')
124
+ return undefined;
125
+ if (change.replace)
126
+ return keepsNulls ? change.patch : removeNullMergePatchFields(change.patch);
127
+ if (doc === undefined)
128
+ return removed ? undefined : removeNullMergePatchFields(change.patch);
129
+ return applyJsonMergePatch(doc, change.patch);
130
+ }
131
+ /** True when a merge patch would remove a field that `target` holds as `null`. */
132
+ function patchDropsNull(patch, target) {
133
+ for (const key of Object.keys(patch)) {
134
+ const value = patch[key];
135
+ if (value === null && Object.hasOwn(target, key))
136
+ return true;
137
+ const held = target[key];
138
+ if (isPlainRecord(value) && isPlainRecord(held) && patchDropsNull(value, held))
139
+ return true;
140
+ }
141
+ return false;
142
+ }
143
+ /** The change that turns `base` into `target`. */
144
+ function documentChangeBetween(base, target, replace, keepsNulls = false) {
145
+ if (target === undefined)
146
+ return base === undefined ? undefined : DELETE;
147
+ if (base === undefined || replace)
148
+ return { kind: 'patch', patch: target, replace: true };
149
+ const patch = createJsonMergePatch(base, target);
150
+ if (patch === null)
151
+ return undefined;
152
+ if (keepsNulls && patchDropsNull(patch, target))
153
+ return { kind: 'patch', patch: target, replace: true };
154
+ return { kind: 'patch', patch: patch, replace: false };
155
+ }
156
+ /**
157
+ * Drops the parts of a patch that recurse into an object field the store now
158
+ * holds as a non-object: merging them would build a half object.
159
+ */
160
+ export function dropShapeConflicts(patch, server) {
161
+ if (server === undefined)
162
+ return patch;
163
+ let result;
164
+ for (const key of Object.keys(patch)) {
165
+ const value = patch[key];
166
+ if (!isPlainRecord(value))
167
+ continue;
168
+ const current = server[key];
169
+ let next;
170
+ if (current !== undefined && !isPlainRecord(current))
171
+ next = undefined;
172
+ else if (isPlainRecord(current))
173
+ next = dropShapeConflicts(value, current);
174
+ else
175
+ continue;
176
+ if (next === value)
177
+ continue;
178
+ result ??= { ...patch };
179
+ if (next === undefined)
180
+ delete result[key];
181
+ else
182
+ result[key] = next;
183
+ }
184
+ return result ?? patch;
185
+ }
186
+ function defaultFormatTime(epochMs) {
187
+ return new Date(epochMs).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
188
+ }
189
+ /* -------------------------------------------------------------------------- */
190
+ /* Engine */
191
+ /* -------------------------------------------------------------------------- */
192
+ /** Creates a live store; loading starts at once. */
193
+ export function createLiveStore(options) {
194
+ const { transport, codec } = options;
195
+ const keepsNulls = codec.keepsNulls === true;
196
+ const applyChange = (doc, change, removed) => applyDocumentChange(doc, change, removed, keepsNulls);
197
+ const changeBetween = (base, target, replace) => documentChangeBetween(base, target, replace, keepsNulls);
198
+ const timers = options.timers ?? SYSTEM_TIMERS;
199
+ const formatTime = options.formatTime ?? defaultFormatTime;
200
+ const collections = new Set(codec.collections);
201
+ const collectionRank = new Map(codec.collections.map((name, index) => [name, index]));
202
+ const entries = new Map();
203
+ const listeners = new Set();
204
+ let local = new Map();
205
+ const bytes = new Map();
206
+ let totalBytes = 0;
207
+ let carry;
208
+ let value = options.initial;
209
+ let unmaterialized = false;
210
+ let materializeTimer;
211
+ let loadState = 'loading';
212
+ let loadAttempt = 0;
213
+ let loadFailures = 0;
214
+ let loadSlow = false;
215
+ let loadTimer;
216
+ let slowTimer;
217
+ let retryLoadTimer;
218
+ let buffered = [];
219
+ let cacheTimer;
220
+ let readOnly = options.readOnly === true;
221
+ let stopped = false;
222
+ let disposed = false;
223
+ let seqCounter = 0;
224
+ let flights = new Set();
225
+ let syncTimer;
226
+ let syncTimerAt = Infinity;
227
+ let urgent = false;
228
+ let backpressureSince;
229
+ let lastSyncedAt;
230
+ let lastError;
231
+ let notice;
232
+ let noticeCounter = 0;
233
+ let flushWaiters = [];
234
+ let writeWaiters = [];
235
+ /** Documents a {@link LiveStore.writeNow} batch is writing: the engine holds their changes meanwhile. */
236
+ const guarded = new Map();
237
+ let directWrites = 0;
238
+ let snapshot = buildSnapshot();
239
+ /* ---------------------------------------------------------------- entries */
240
+ function entryFor(path) {
241
+ let entry = entries.get(path);
242
+ if (entry === undefined) {
243
+ entry = {
244
+ path,
245
+ server: undefined,
246
+ removedSeen: false,
247
+ inflight: undefined,
248
+ pending: undefined,
249
+ acked: [],
250
+ firstAt: 0,
251
+ lastAt: 0,
252
+ failures: 0,
253
+ notBefore: 0,
254
+ seq: 0,
255
+ parked: undefined,
256
+ solo: false,
257
+ goneNoticed: false,
258
+ };
259
+ entries.set(path, entry);
260
+ }
261
+ return entry;
262
+ }
263
+ /** Forgets entries that hold nothing. */
264
+ function sweep(entry) {
265
+ if (entry.server === undefined && !entry.removedSeen && entry.inflight === undefined && entry.pending === undefined && entry.acked.length === 0) {
266
+ entries.delete(entry.path);
267
+ }
268
+ }
269
+ /** The document before `pending` (or with it). */
270
+ function viewOf(entry, withPending) {
271
+ let doc = entry.server;
272
+ for (const acked of entry.acked)
273
+ doc = applyChange(doc, acked.change, entry.removedSeen);
274
+ if (entry.inflight !== undefined)
275
+ doc = applyChange(doc, entry.inflight, entry.removedSeen);
276
+ if (withPending && entry.pending !== undefined)
277
+ doc = applyChange(doc, entry.pending, entry.removedSeen);
278
+ return doc;
279
+ }
280
+ function setBytes(path, doc) {
281
+ totalBytes -= bytes.get(path) ?? 0;
282
+ if (doc === undefined)
283
+ bytes.delete(path);
284
+ else {
285
+ const size = escapedJsonByteLength(doc);
286
+ bytes.set(path, size);
287
+ totalBytes += size;
288
+ }
289
+ }
290
+ function setPending(entry, change, now) {
291
+ if (change === undefined) {
292
+ entry.pending = undefined;
293
+ entry.firstAt = 0;
294
+ if (entry.parked?.refused === true)
295
+ entry.parked = undefined;
296
+ return;
297
+ }
298
+ if (entry.pending === undefined) {
299
+ entry.firstAt = now;
300
+ entry.seq = ++seqCounter;
301
+ }
302
+ entry.pending = change;
303
+ entry.lastAt = now;
304
+ }
305
+ function showNotice(message) {
306
+ notice = { id: ++noticeCounter, message };
307
+ }
308
+ /** The doc was deleted by someone else while we had edits for it. */
309
+ function itemGone(entry) {
310
+ entry.pending = undefined;
311
+ entry.firstAt = 0;
312
+ entry.parked = undefined;
313
+ if (!entry.goneNoticed) {
314
+ entry.goneNoticed = true;
315
+ showNotice(LIVE_MESSAGES.itemGone);
316
+ }
317
+ }
318
+ /* ------------------------------------------------------------ local edits */
319
+ function canEdit() {
320
+ return (loadState === 'live' || loadState === 'cached') && !readOnly && !stopped && !disposed;
321
+ }
322
+ function commit(next) {
323
+ if (!canEdit())
324
+ return false;
325
+ if (next === value)
326
+ return true;
327
+ const previous = value;
328
+ value = next;
329
+ unmaterialized = true;
330
+ if (materializeTimer === undefined)
331
+ materializeTimer = timers.setTimeout(materialize, MIN_SYNC_TIMER_DELAY_MS);
332
+ emit({ remote: false, valueChanged: true, previous });
333
+ return true;
334
+ }
335
+ /** Splits the current value into documents and stages what changed. */
336
+ function materialize() {
337
+ if (materializeTimer !== undefined) {
338
+ timers.clearTimeout(materializeTimer);
339
+ materializeTimer = undefined;
340
+ }
341
+ if (!unmaterialized)
342
+ return;
343
+ unmaterialized = false;
344
+ const now = timers.now();
345
+ const next = codec.decompose(value, local, carry);
346
+ const touched = [];
347
+ for (const [path, doc] of next) {
348
+ const previous = local.get(path);
349
+ if (previous === doc)
350
+ continue;
351
+ if (previous !== undefined && canonicalValuesEqual(previous, doc)) {
352
+ next.set(path, previous);
353
+ continue;
354
+ }
355
+ stage(path, doc, now);
356
+ touched.push(path);
357
+ }
358
+ for (const path of local.keys()) {
359
+ if (next.has(path))
360
+ continue;
361
+ stage(path, undefined, now);
362
+ touched.push(path);
363
+ }
364
+ local = next;
365
+ if (touched.length > 0)
366
+ schedule();
367
+ emitStatus();
368
+ }
369
+ /** Stages the local value of one document. */
370
+ function stage(path, doc, now) {
371
+ const entry = entryFor(path);
372
+ const base = viewOf(entry, false);
373
+ let change;
374
+ if (doc === undefined)
375
+ change = base === undefined ? undefined : DELETE;
376
+ else if (base === undefined || codec.replaceOnly(path))
377
+ change = canonicalValuesEqual(base, doc) ? undefined : { kind: 'patch', patch: doc, replace: true };
378
+ else
379
+ change = changeBetween(base, doc, false);
380
+ setPending(entry, change, now);
381
+ const previousBytes = bytes.get(path) ?? 0;
382
+ setBytes(path, doc);
383
+ if (doc === undefined || change === undefined) {
384
+ if (entry.parked?.refused === true)
385
+ entry.parked = undefined;
386
+ }
387
+ else {
388
+ const size = bytes.get(path) ?? 0;
389
+ const reason = codec.refuse(path, doc, size > previousBytes ? totalBytes : 0);
390
+ if (reason !== undefined) {
391
+ entry.parked = { message: reason, refused: true };
392
+ lastError = { code: 'refused', message: reason, path };
393
+ }
394
+ else if (entry.parked !== undefined) {
395
+ entry.parked = undefined;
396
+ entry.failures = 0;
397
+ }
398
+ }
399
+ sweep(entry);
400
+ }
401
+ /* ----------------------------------------------------------- remote edits */
402
+ function onRemote(event) {
403
+ if (disposed)
404
+ return;
405
+ if (buffered !== undefined) {
406
+ buffered.push(event);
407
+ return;
408
+ }
409
+ applyRemote(event);
410
+ }
411
+ function applyRemote(event) {
412
+ materialize();
413
+ const touched = [];
414
+ for (const [path, data] of Object.entries(event.changes)) {
415
+ if (!collections.has(collectionOfPath(path)))
416
+ continue;
417
+ const entry = entryFor(path);
418
+ if (data === null) {
419
+ entry.server = undefined;
420
+ entry.removedSeen = true;
421
+ const pending = entry.pending;
422
+ if (pending !== undefined && pending.kind === 'patch' && !pending.replace && entry.inflight === undefined)
423
+ itemGone(entry);
424
+ }
425
+ else {
426
+ entry.server = data;
427
+ entry.removedSeen = false;
428
+ entry.goneNoticed = false;
429
+ const pending = entry.pending;
430
+ if (pending !== undefined && pending.kind === 'patch' && !pending.replace) {
431
+ const patch = dropShapeConflicts(pending.patch, viewOf(entry, false));
432
+ if (patch !== pending.patch)
433
+ setPending(entry, Object.keys(patch).length === 0 ? undefined : { kind: 'patch', patch, replace: false }, entry.lastAt);
434
+ }
435
+ }
436
+ touched.push(path);
437
+ }
438
+ if (touched.length > 0)
439
+ refresh(touched, true);
440
+ }
441
+ /** Recomputes the local documents of some paths and recomposes the value. */
442
+ function refresh(paths, remote) {
443
+ let changed = false;
444
+ for (const path of paths) {
445
+ const entry = entries.get(path);
446
+ const doc = entry === undefined ? undefined : viewOf(entry, true);
447
+ const previous = local.get(path);
448
+ if (doc === undefined) {
449
+ if (previous === undefined)
450
+ continue;
451
+ local.delete(path);
452
+ }
453
+ else {
454
+ if (previous !== undefined && (previous === doc || canonicalValuesEqual(previous, doc)))
455
+ continue;
456
+ local.set(path, doc);
457
+ }
458
+ setBytes(path, doc);
459
+ changed = true;
460
+ if (entry !== undefined)
461
+ sweep(entry);
462
+ }
463
+ if (!changed) {
464
+ emitStatus();
465
+ return;
466
+ }
467
+ recompose(remote);
468
+ }
469
+ function recompose(remote) {
470
+ const previous = value;
471
+ const composed = codec.compose(local);
472
+ carry = composed.carry;
473
+ value = codec.share !== undefined ? codec.share(previous, composed.value) : composed.value;
474
+ emit({ remote, valueChanged: value !== previous, previous });
475
+ }
476
+ /* ------------------------------------------------------------------ load */
477
+ const unsubscribe = transport.onChange(onRemote);
478
+ /** Whether a load is still waiting for the store (with or without the saved copy shown). */
479
+ function awaitingStore() {
480
+ return loadState === 'loading' || loadState === 'cached';
481
+ }
482
+ function load() {
483
+ if (disposed)
484
+ return;
485
+ const attempt = ++loadAttempt;
486
+ // The saved copy stays up (and editable) while loading again.
487
+ if (loadState !== 'cached')
488
+ loadState = 'loading';
489
+ loadSlow = false;
490
+ buffered = [];
491
+ clearLoadTimers();
492
+ slowTimer = timers.setTimeout(() => {
493
+ if (attempt !== loadAttempt || !awaitingStore())
494
+ return;
495
+ loadSlow = true;
496
+ if (!showSavedCopy())
497
+ emitStatus();
498
+ }, LIVE_SNAPSHOT_TIMEOUT_MS);
499
+ loadTimer = timers.setTimeout(() => {
500
+ if (attempt !== loadAttempt || !awaitingStore())
501
+ return;
502
+ loadFailed(attempt, { code: 'unavailable', message: 'timed out' });
503
+ }, LIVE_EXTENDED_LOAD_TIMEOUT_MS);
504
+ emitStatus();
505
+ Promise.all(codec.collections.map((collection) => transport.list(collection))).then((lists) => {
506
+ if (attempt !== loadAttempt || disposed)
507
+ return;
508
+ clearLoadTimers();
509
+ const seen = new Set();
510
+ for (const list of lists) {
511
+ for (const document of list) {
512
+ if (!collections.has(collectionOfPath(document.path)))
513
+ continue;
514
+ const entry = entryFor(document.path);
515
+ entry.server = document.data;
516
+ entry.removedSeen = false;
517
+ seen.add(document.path);
518
+ }
519
+ }
520
+ for (const entry of entries.values()) {
521
+ if (!seen.has(entry.path) && entry.server !== undefined) {
522
+ entry.server = undefined;
523
+ entry.removedSeen = true;
524
+ // Edited on the saved copy, deleted in the store meanwhile: the edit goes.
525
+ const pending = entry.pending;
526
+ if (pending !== undefined && pending.kind === 'patch' && !pending.replace && entry.inflight === undefined)
527
+ itemGone(entry);
528
+ }
529
+ }
530
+ const events = buffered ?? [];
531
+ buffered = undefined;
532
+ loadState = 'live';
533
+ loadFailures = 0;
534
+ lastError = undefined;
535
+ for (const event of events) {
536
+ for (const [path, data] of Object.entries(event.changes)) {
537
+ if (!collections.has(collectionOfPath(path)))
538
+ continue;
539
+ const entry = entryFor(path);
540
+ entry.server = data ?? undefined;
541
+ entry.removedSeen = data === null;
542
+ }
543
+ }
544
+ local = new Map();
545
+ bytes.clear();
546
+ totalBytes = 0;
547
+ for (const entry of entries.values()) {
548
+ const doc = viewOf(entry, true);
549
+ if (doc === undefined)
550
+ continue;
551
+ local.set(entry.path, doc);
552
+ setBytes(entry.path, doc);
553
+ }
554
+ recompose(true);
555
+ schedule();
556
+ saveCopySoon();
557
+ }, (error) => {
558
+ if (attempt !== loadAttempt || disposed)
559
+ return;
560
+ loadFailed(attempt, { code: syncErrorCode(error), message: syncErrorMessage(error) });
561
+ });
562
+ }
563
+ function loadFailed(attempt, error) {
564
+ if (attempt !== loadAttempt)
565
+ return;
566
+ loadAttempt += 1;
567
+ clearLoadTimers();
568
+ buffered = [];
569
+ lastError = error;
570
+ const code = error.code;
571
+ const retrying = code !== 'refused' && !isAccessError(code);
572
+ // Out of reach (not refused): show the saved copy, if there is one, while retrying.
573
+ if (!retrying || !showSavedCopy())
574
+ loadState = 'failed';
575
+ if (retrying) {
576
+ const delay = LIVE_RECONNECT_BACKOFF_MS[Math.min(loadFailures, LIVE_RECONNECT_BACKOFF_MS.length - 1)] ?? 60_000;
577
+ loadFailures += 1;
578
+ retryLoadTimer = timers.setTimeout(() => {
579
+ retryLoadTimer = undefined;
580
+ if (loadState === 'failed' || loadState === 'cached')
581
+ load();
582
+ }, delay);
583
+ }
584
+ emitStatus();
585
+ }
586
+ /**
587
+ * Shows the saved copy while the store is out of reach. `true` when it is
588
+ * shown (now or already); `false` without one.
589
+ */
590
+ function showSavedCopy() {
591
+ if (loadState === 'cached')
592
+ return true;
593
+ if (loadState === 'live' || disposed)
594
+ return false;
595
+ const saved = readSavedCopy();
596
+ if (saved === undefined)
597
+ return false;
598
+ loadState = 'cached';
599
+ for (const document of saved) {
600
+ if (!collections.has(collectionOfPath(document.path)))
601
+ continue;
602
+ const entry = entryFor(document.path);
603
+ entry.server = document.data;
604
+ entry.removedSeen = false;
605
+ }
606
+ local = new Map();
607
+ bytes.clear();
608
+ totalBytes = 0;
609
+ for (const entry of entries.values()) {
610
+ const doc = viewOf(entry, true);
611
+ if (doc === undefined)
612
+ continue;
613
+ local.set(entry.path, doc);
614
+ setBytes(entry.path, doc);
615
+ }
616
+ recompose(true);
617
+ return true;
618
+ }
619
+ function readSavedCopy() {
620
+ try {
621
+ return options.cache?.read();
622
+ }
623
+ catch {
624
+ return undefined;
625
+ }
626
+ }
627
+ /** The store's documents with our acknowledged writes: what the saved copy holds. */
628
+ function confirmedDocuments() {
629
+ const documents = [];
630
+ for (const entry of entries.values()) {
631
+ let doc = entry.server;
632
+ for (const acked of entry.acked)
633
+ doc = applyChange(doc, acked.change, entry.removedSeen);
634
+ if (doc !== undefined)
635
+ documents.push({ path: entry.path, data: doc });
636
+ }
637
+ return documents;
638
+ }
639
+ /** Updates the saved copy after {@link LIVE_CACHE_WRITE_DELAY_MS} (live only). */
640
+ function saveCopySoon() {
641
+ if (options.cache === undefined || loadState !== 'live' || disposed || cacheTimer !== undefined)
642
+ return;
643
+ cacheTimer = timers.setTimeout(() => {
644
+ cacheTimer = undefined;
645
+ saveCopyNow();
646
+ }, LIVE_CACHE_WRITE_DELAY_MS);
647
+ }
648
+ function saveCopyNow() {
649
+ if (options.cache === undefined || loadState !== 'live')
650
+ return;
651
+ try {
652
+ options.cache.write(confirmedDocuments());
653
+ }
654
+ catch {
655
+ // A full or disabled storage only loses the saved copy.
656
+ }
657
+ }
658
+ function clearLoadTimers() {
659
+ for (const handle of [loadTimer, slowTimer, retryLoadTimer])
660
+ if (handle !== undefined)
661
+ timers.clearTimeout(handle);
662
+ loadTimer = slowTimer = retryLoadTimer = undefined;
663
+ }
664
+ /* ---------------------------------------------------------------- writes */
665
+ function sendable(entry) {
666
+ return entry.pending !== undefined && entry.inflight === undefined && entry.parked === undefined && !guarded.has(entry.path);
667
+ }
668
+ function dueAt(entry) {
669
+ const debounced = urgent ? 0 : Math.min(entry.lastAt + LIVE_EDIT_DEBOUNCE_MS, entry.firstAt + LIVE_EDIT_MAX_WAIT_MS);
670
+ return Math.max(debounced, entry.notBefore);
671
+ }
672
+ function writing() {
673
+ return loadState === 'live' && !readOnly && !stopped && !disposed;
674
+ }
675
+ /** Sets the one sync timer for the soonest due work. */
676
+ function schedule() {
677
+ if (disposed)
678
+ return;
679
+ let soonest = Infinity;
680
+ if (writing())
681
+ for (const entry of entries.values())
682
+ if (sendable(entry))
683
+ soonest = Math.min(soonest, dueAt(entry));
684
+ for (const entry of entries.values()) {
685
+ const oldest = entry.acked[0];
686
+ if (oldest !== undefined)
687
+ soonest = Math.min(soonest, oldest.at + ACKNOWLEDGED_WRITE_GRACE_MS);
688
+ }
689
+ if (soonest === Infinity) {
690
+ if (syncTimer !== undefined)
691
+ timers.clearTimeout(syncTimer);
692
+ syncTimer = undefined;
693
+ syncTimerAt = Infinity;
694
+ return;
695
+ }
696
+ const now = timers.now();
697
+ const at = Math.max(soonest, now + (urgent ? 0 : MIN_SYNC_TIMER_DELAY_MS));
698
+ if (syncTimer !== undefined && syncTimerAt <= at)
699
+ return;
700
+ if (syncTimer !== undefined)
701
+ timers.clearTimeout(syncTimer);
702
+ syncTimerAt = at;
703
+ syncTimer = timers.setTimeout(() => {
704
+ syncTimer = undefined;
705
+ syncTimerAt = Infinity;
706
+ pump();
707
+ }, at - now);
708
+ }
709
+ /** Drops acknowledged writes past their grace period. */
710
+ function pruneAcked(now) {
711
+ const touched = [];
712
+ for (const entry of entries.values()) {
713
+ const before = entry.acked.length;
714
+ if (before === 0)
715
+ continue;
716
+ entry.acked = entry.acked.filter((acked) => now - acked.at < ACKNOWLEDGED_WRITE_GRACE_MS).slice(-MAX_UNCOALESCED_ACKNOWLEDGED_WRITES);
717
+ if (entry.acked.length !== before)
718
+ touched.push(entry.path);
719
+ }
720
+ if (touched.length > 0)
721
+ refresh(touched, true);
722
+ }
723
+ /** Sends what is due. */
724
+ function pump() {
725
+ if (disposed)
726
+ return;
727
+ materialize();
728
+ const now = timers.now();
729
+ pruneAcked(now);
730
+ if (writing()) {
731
+ const ready = [...entries.values()].filter((entry) => sendable(entry) && dueAt(entry) <= now);
732
+ ready.sort(compareEntries);
733
+ while (ready.length > 0 && flights.size < MAX_CONCURRENT_LIVE_WRITES) {
734
+ const batch = [];
735
+ let batchBytes = 0;
736
+ while (ready.length > 0 && batch.length < MAX_WRITES_PER_BATCH) {
737
+ const entry = ready[0];
738
+ const size = bytes.get(entry.path) ?? 256;
739
+ if (entry.solo && batch.length > 0)
740
+ break;
741
+ if (batch.length > 0 && batchBytes + size > MAX_BATCH_BYTES)
742
+ break;
743
+ ready.shift();
744
+ batch.push(entry);
745
+ batchBytes += size;
746
+ if (entry.solo)
747
+ break;
748
+ }
749
+ send(batch);
750
+ }
751
+ }
752
+ schedule();
753
+ emitStatus();
754
+ }
755
+ /** Write order: changes before deletes, collections in order (deletes reversed), meta last, then age. */
756
+ function compareEntries(a, b) {
757
+ const rank = (entry) => {
758
+ const deleting = entry.pending?.kind === 'delete';
759
+ const collection = collectionRank.get(collectionOfPath(entry.path)) ?? codec.collections.length;
760
+ const ordered = deleting ? codec.collections.length - collection : collection;
761
+ return (deleting ? 1000 : 0) + ordered + (entry.path === codec.metaPath ? 0.5 : 0);
762
+ };
763
+ return rank(a) - rank(b) || a.seq - b.seq;
764
+ }
765
+ function send(batch) {
766
+ const writes = [];
767
+ const sent = [];
768
+ for (const entry of batch) {
769
+ const change = entry.pending;
770
+ if (change === undefined)
771
+ continue;
772
+ let write;
773
+ let inflight = change;
774
+ if (change.kind === 'delete')
775
+ write = { op: 'delete', path: entry.path };
776
+ else if (change.replace)
777
+ write = { op: 'set', path: entry.path, data: keepsNulls ? change.patch : removeNullMergePatchFields(change.patch) };
778
+ else {
779
+ const base = viewOf(entry, false);
780
+ if (base === undefined || (entry.server === undefined && entry.removedSeen)) {
781
+ itemGone(entry);
782
+ refresh([entry.path], true);
783
+ continue;
784
+ }
785
+ if (countMergePatchTombstones(change.patch) > MAX_MERGE_PATCH_TOMBSTONES) {
786
+ const data = applyJsonMergePatch(base, change.patch);
787
+ write = { op: 'set', path: entry.path, data };
788
+ inflight = { kind: 'patch', patch: data, replace: true };
789
+ }
790
+ else
791
+ write = { op: 'update', path: entry.path, patch: change.patch };
792
+ }
793
+ entry.inflight = inflight;
794
+ entry.pending = undefined;
795
+ entry.firstAt = 0;
796
+ writes.push(write);
797
+ sent.push(entry);
798
+ }
799
+ if (writes.length === 0)
800
+ return;
801
+ const flight = { entries: sent, writes, settled: false, timer: undefined };
802
+ flights.add(flight);
803
+ flight.timer = timers.setTimeout(() => settle(flight, { code: 'unavailable', error: new Error('the write timed out') }), STUCK_WRITE_TIMEOUT_MS);
804
+ let request;
805
+ try {
806
+ request = transport.write(writes);
807
+ }
808
+ catch (error) {
809
+ request = Promise.reject(error);
810
+ }
811
+ request.then(() => settle(flight, undefined), (error) => settle(flight, { code: syncErrorCode(error), error }));
812
+ }
813
+ /** Puts an in-flight change back in front of the pending one. */
814
+ function restorePending(entry, now) {
815
+ const inflight = entry.inflight;
816
+ entry.inflight = undefined;
817
+ if (inflight === undefined)
818
+ return;
819
+ if (entry.pending === undefined) {
820
+ entry.pending = inflight;
821
+ entry.firstAt = now;
822
+ entry.lastAt = now;
823
+ entry.seq = ++seqCounter;
824
+ return;
825
+ }
826
+ const base = viewOf(entry, false);
827
+ const target = applyChange(applyChange(base, inflight, entry.removedSeen), entry.pending, entry.removedSeen);
828
+ const replace = (inflight.kind === 'patch' && inflight.replace) || (entry.pending.kind === 'patch' && entry.pending.replace) || inflight.kind === 'delete';
829
+ entry.pending = changeBetween(base, target, replace);
830
+ if (entry.pending === undefined)
831
+ entry.firstAt = 0;
832
+ }
833
+ function settle(flight, failure) {
834
+ if (flight.settled)
835
+ return;
836
+ flight.settled = true;
837
+ if (flight.timer !== undefined)
838
+ timers.clearTimeout(flight.timer);
839
+ flights.delete(flight);
840
+ if (disposed)
841
+ return;
842
+ const now = timers.now();
843
+ if (failure === undefined) {
844
+ backpressureSince = undefined;
845
+ lastSyncedAt = now;
846
+ if (lastError !== undefined && lastError.code !== 'refused')
847
+ lastError = undefined;
848
+ flight.writes.forEach((write, index) => {
849
+ const entry = flight.entries[index];
850
+ const change = entry.inflight;
851
+ entry.inflight = undefined;
852
+ entry.failures = 0;
853
+ entry.solo = false;
854
+ if (change === undefined)
855
+ return;
856
+ if (write.op === 'delete') {
857
+ entry.server = undefined;
858
+ entry.removedSeen = false;
859
+ }
860
+ else if (write.op === 'set') {
861
+ entry.server = write.data;
862
+ entry.removedSeen = false;
863
+ }
864
+ else if (entry.server === undefined && entry.removedSeen) {
865
+ // Deleted while the update flew: the store may now hold a stub; remove it.
866
+ itemGone(entry);
867
+ setPending(entry, DELETE, now);
868
+ entry.notBefore = 0;
869
+ }
870
+ else
871
+ entry.server = applyJsonMergePatch(entry.server, write.patch);
872
+ entry.acked.push({ change, at: now });
873
+ if (entry.acked.length > MAX_UNCOALESCED_ACKNOWLEDGED_WRITES)
874
+ entry.acked.shift();
875
+ });
876
+ refresh(flight.entries.map((entry) => entry.path), false);
877
+ }
878
+ else
879
+ handleFailure(flight, failure.code, failure.error, now);
880
+ if (urgent && flushIdle())
881
+ urgent = false;
882
+ pump();
883
+ resolveFlushWaiters();
884
+ }
885
+ function handleFailure(flight, code, error, now) {
886
+ const why = syncErrorMessage(error);
887
+ lastError = { code, message: why, path: flight.entries.length === 1 ? flight.entries[0].path : undefined };
888
+ if (isAccessError(code)) {
889
+ for (const entry of flight.entries)
890
+ restorePending(entry, now);
891
+ stopped = true;
892
+ return;
893
+ }
894
+ if (code === 'invalid' || code === 'not_found') {
895
+ if (flight.entries.length > 1) {
896
+ for (const entry of flight.entries) {
897
+ restorePending(entry, now);
898
+ entry.solo = true;
899
+ entry.notBefore = 0;
900
+ entry.firstAt = entry.lastAt = 0;
901
+ }
902
+ return;
903
+ }
904
+ const entry = flight.entries[0];
905
+ const write = flight.writes[0];
906
+ if (write.op === 'update' && (code === 'not_found' || (entry.server === undefined && entry.removedSeen))) {
907
+ entry.inflight = undefined;
908
+ itemGone(entry);
909
+ refresh([entry.path], true);
910
+ return;
911
+ }
912
+ restorePending(entry, now);
913
+ entry.parked = { message: LIVE_MESSAGES.cannotStore(why), refused: false };
914
+ return;
915
+ }
916
+ const busy = code === 'resource_exhausted';
917
+ if (busy)
918
+ backpressureSince ??= now;
919
+ for (const entry of flight.entries) {
920
+ restorePending(entry, now);
921
+ entry.failures += 1;
922
+ const failures = entry.failures;
923
+ const delay = busy
924
+ ? Math.min(BACKPRESSURE_RETRY_MAX_MS, BACKPRESSURE_RETRY_BASE_MS * 2 ** (failures - 1))
925
+ : failures === 1
926
+ ? INITIAL_WRITE_RETRY_JITTER_MS[0] + timers.random() * (INITIAL_WRITE_RETRY_JITTER_MS[1] - INITIAL_WRITE_RETRY_JITTER_MS[0])
927
+ : Math.min(WRITE_RETRY_MAX_MS, WRITE_RETRY_BASE_MS * 2 ** Math.max(0, failures - 2));
928
+ entry.notBefore = now + delay;
929
+ }
930
+ }
931
+ /* ----------------------------------------------------------------- flush */
932
+ function flushIdle() {
933
+ if (flights.size > 0 || directWrites > 0)
934
+ return false;
935
+ if (!writing())
936
+ return true;
937
+ const now = timers.now();
938
+ for (const entry of entries.values())
939
+ if (sendable(entry) && entry.failures === 0 && entry.notBefore <= now)
940
+ return false;
941
+ return !unmaterialized;
942
+ }
943
+ function resolveFlushWaiters() {
944
+ if (flushWaiters.length === 0 || !flushIdle())
945
+ return;
946
+ const waiters = flushWaiters;
947
+ flushWaiters = [];
948
+ for (const resolve of waiters)
949
+ resolve();
950
+ }
951
+ function flush() {
952
+ materialize();
953
+ if (flushIdle())
954
+ return Promise.resolve();
955
+ urgent = true;
956
+ for (const entry of entries.values())
957
+ if (sendable(entry))
958
+ entry.notBefore = 0;
959
+ const done = new Promise((resolve) => flushWaiters.push(resolve));
960
+ pump();
961
+ resolveFlushWaiters();
962
+ return done;
963
+ }
964
+ function retry() {
965
+ if (disposed)
966
+ return;
967
+ if (loadState === 'failed' || loadState === 'cached') {
968
+ loadFailures = 0;
969
+ load();
970
+ return;
971
+ }
972
+ for (const entry of entries.values()) {
973
+ if (entry.parked !== undefined && !entry.parked.refused)
974
+ entry.parked = undefined;
975
+ entry.notBefore = 0;
976
+ }
977
+ pump();
978
+ }
979
+ /* ------------------------------------------------------ write promises */
980
+ /** `true` when stored, a {@link LiveWriteError} when it never will be, `undefined` while waiting. */
981
+ function writeOutcome(paths) {
982
+ if (disposed)
983
+ return new LiveWriteError('disposed', 'The live document was closed.');
984
+ if (stopped)
985
+ return new LiveWriteError(lastError?.code ?? 'not_writer', LIVE_MESSAGES.accessEnded);
986
+ if (readOnly)
987
+ return new LiveWriteError('readonly', LIVE_MESSAGES.readOnly);
988
+ let waiting = false;
989
+ for (const path of paths) {
990
+ const entry = entries.get(path);
991
+ if (entry === undefined || (entry.pending === undefined && entry.inflight === undefined))
992
+ continue;
993
+ if (entry.parked !== undefined && entry.inflight === undefined) {
994
+ return new LiveWriteError(entry.parked.refused ? 'refused' : (lastError?.code ?? 'invalid'), entry.parked.message, path);
995
+ }
996
+ waiting = true;
997
+ }
998
+ return waiting || unmaterialized ? undefined : true;
999
+ }
1000
+ function settleWriteWaiters() {
1001
+ if (writeWaiters.length === 0)
1002
+ return;
1003
+ const waiting = [];
1004
+ for (const waiter of writeWaiters) {
1005
+ const outcome = writeOutcome(waiter.paths);
1006
+ if (outcome === undefined)
1007
+ waiting.push(waiter);
1008
+ else if (outcome === true)
1009
+ waiter.resolve();
1010
+ else
1011
+ waiter.reject(outcome);
1012
+ }
1013
+ writeWaiters = waiting;
1014
+ }
1015
+ function whenWritten(paths) {
1016
+ materialize();
1017
+ const outcome = writeOutcome(paths);
1018
+ if (outcome === true)
1019
+ return Promise.resolve();
1020
+ if (outcome !== undefined)
1021
+ return Promise.reject(outcome);
1022
+ return new Promise((resolve, reject) => writeWaiters.push({ paths: [...paths], resolve, reject }));
1023
+ }
1024
+ async function writeNow(writes) {
1025
+ if (writes.length === 0)
1026
+ return;
1027
+ const paths = writes.map((write) => write.path);
1028
+ if (!canEdit()) {
1029
+ const outcome = writeOutcome(paths);
1030
+ throw outcome instanceof LiveWriteError ? outcome : new LiveWriteError('unavailable', LIVE_MESSAGES.loading);
1031
+ }
1032
+ for (const path of paths) {
1033
+ const entry = entries.get(path);
1034
+ if (entry !== undefined && sendable(entry))
1035
+ entry.notBefore = 0;
1036
+ }
1037
+ urgent = true;
1038
+ pump();
1039
+ await whenWritten(paths);
1040
+ if (loadState !== 'live')
1041
+ throw new LiveWriteError('unavailable', LIVE_MESSAGES.unreachableLater);
1042
+ for (const path of paths)
1043
+ guarded.set(path, (guarded.get(path) ?? 0) + 1);
1044
+ directWrites += 1;
1045
+ emitStatus();
1046
+ let timer;
1047
+ try {
1048
+ await new Promise((resolve, reject) => {
1049
+ timer = timers.setTimeout(() => reject(Object.assign(new Error('the write timed out'), { code: 'unavailable' })), STUCK_WRITE_TIMEOUT_MS);
1050
+ let request;
1051
+ try {
1052
+ request = transport.write([...writes]);
1053
+ }
1054
+ catch (error) {
1055
+ request = Promise.reject(error);
1056
+ }
1057
+ request.then(resolve, reject);
1058
+ });
1059
+ }
1060
+ catch (error) {
1061
+ const code = syncErrorCode(error);
1062
+ if (!disposed) {
1063
+ lastError = { code, message: syncErrorMessage(error), ...(paths.length === 1 ? { path: paths[0] } : {}) };
1064
+ if (isAccessError(code))
1065
+ stopped = true;
1066
+ }
1067
+ throw new LiveWriteError(code, syncErrorMessage(error), paths.length === 1 ? paths[0] : undefined);
1068
+ }
1069
+ finally {
1070
+ if (timer !== undefined)
1071
+ timers.clearTimeout(timer);
1072
+ directWrites -= 1;
1073
+ for (const path of paths) {
1074
+ const count = (guarded.get(path) ?? 1) - 1;
1075
+ if (count <= 0)
1076
+ guarded.delete(path);
1077
+ else
1078
+ guarded.set(path, count);
1079
+ }
1080
+ if (!disposed) {
1081
+ if (urgent && flushIdle())
1082
+ urgent = false;
1083
+ pump();
1084
+ resolveFlushWaiters();
1085
+ }
1086
+ }
1087
+ if (disposed)
1088
+ return;
1089
+ const now = timers.now();
1090
+ materialize();
1091
+ lastSyncedAt = now;
1092
+ if (lastError !== undefined && lastError.code !== 'refused')
1093
+ lastError = undefined;
1094
+ for (const write of writes) {
1095
+ const entry = entryFor(write.path);
1096
+ let change;
1097
+ if (write.op === 'delete') {
1098
+ entry.server = undefined;
1099
+ change = DELETE;
1100
+ }
1101
+ else if (write.op === 'set') {
1102
+ entry.server = write.data;
1103
+ change = { kind: 'patch', patch: write.data, replace: true };
1104
+ }
1105
+ else {
1106
+ entry.server = applyJsonMergePatch(entry.server, write.patch);
1107
+ change = { kind: 'patch', patch: write.patch, replace: false };
1108
+ }
1109
+ entry.removedSeen = false;
1110
+ entry.acked.push({ change, at: now });
1111
+ if (entry.acked.length > MAX_UNCOALESCED_ACKNOWLEDGED_WRITES)
1112
+ entry.acked.shift();
1113
+ }
1114
+ refresh(paths, false);
1115
+ schedule();
1116
+ }
1117
+ /* --------------------------------------------------------------- status */
1118
+ function pendingCount() {
1119
+ let count = 0;
1120
+ for (const entry of entries.values())
1121
+ if (entry.pending !== undefined || entry.inflight !== undefined)
1122
+ count += 1;
1123
+ return count + (unmaterialized ? 1 : 0);
1124
+ }
1125
+ function buildSnapshot() {
1126
+ const pending = pendingCount();
1127
+ let refusal;
1128
+ for (const entry of entries.values())
1129
+ if (entry.parked?.refused === true && entry.pending !== undefined)
1130
+ refusal ??= entry.parked.message;
1131
+ const base = {
1132
+ value,
1133
+ loadState,
1134
+ readOnly: readOnly || stopped,
1135
+ pending,
1136
+ flights: flights.size + directWrites,
1137
+ ...(refusal !== undefined ? { refusal } : {}),
1138
+ ...(notice !== undefined ? { notice } : {}),
1139
+ ...(lastSyncedAt !== undefined ? { lastSyncedAt } : {}),
1140
+ ...(lastError !== undefined ? { lastError } : {}),
1141
+ };
1142
+ if (loadState === 'loading')
1143
+ return { ...base, status: 'loading', message: loadSlow ? LIVE_MESSAGES.loadingSlow : LIVE_MESSAGES.loading, retryable: false };
1144
+ if (loadState === 'failed')
1145
+ return { ...base, status: 'error', message: LIVE_MESSAGES.loadFailed, retryable: lastError === undefined || !isAccessError(lastError.code) };
1146
+ if (loadState === 'cached') {
1147
+ const message = readOnly || stopped ? LIVE_MESSAGES.cachedReadOnly : pending > 0 ? LIVE_MESSAGES.cachedEdits : LIVE_MESSAGES.cached;
1148
+ return { ...base, status: readOnly || stopped ? 'readonly' : 'cached', message, retryable: true };
1149
+ }
1150
+ if (stopped)
1151
+ return { ...base, status: 'error', message: LIVE_MESSAGES.accessEnded, retryable: false };
1152
+ if (readOnly)
1153
+ return { ...base, status: 'readonly', message: LIVE_MESSAGES.readOnly, retryable: false };
1154
+ let parked;
1155
+ let failing = false;
1156
+ for (const entry of entries.values()) {
1157
+ if (entry.parked !== undefined && entry.pending !== undefined)
1158
+ parked ??= entry.parked;
1159
+ if (entry.failures > 0 && (entry.pending !== undefined || entry.inflight !== undefined))
1160
+ failing = true;
1161
+ }
1162
+ if (parked !== undefined) {
1163
+ return {
1164
+ ...base,
1165
+ status: 'error',
1166
+ message: `${parked.message} ${LIVE_MESSAGES.parkedSuffix}`,
1167
+ hint: parked.refused ? LIVE_MESSAGES.refusedHint : LIVE_MESSAGES.retryHint,
1168
+ retryable: !parked.refused,
1169
+ };
1170
+ }
1171
+ if (backpressureSince !== undefined && failing) {
1172
+ const long = timers.now() - backpressureSince >= BACKPRESSURE_ERROR_AFTER_MS;
1173
+ return { ...base, status: long ? 'error' : 'offline', message: LIVE_MESSAGES.busy, retryable: true };
1174
+ }
1175
+ if (failing)
1176
+ return { ...base, status: 'offline', message: base.flights > 0 ? LIVE_MESSAGES.unreachableNow : LIVE_MESSAGES.unreachableLater, retryable: true };
1177
+ if (base.flights > 0)
1178
+ return { ...base, status: 'saving', message: LIVE_MESSAGES.saving, retryable: false };
1179
+ if (pending > 0)
1180
+ return { ...base, status: 'dirty', message: LIVE_MESSAGES.waiting(pending), retryable: false };
1181
+ return {
1182
+ ...base,
1183
+ status: 'ready',
1184
+ message: lastSyncedAt !== undefined ? LIVE_MESSAGES.syncedAt(formatTime(lastSyncedAt)) : LIVE_MESSAGES.synced,
1185
+ hint: LIVE_MESSAGES.syncedHint,
1186
+ retryable: false,
1187
+ };
1188
+ }
1189
+ function sameSnapshot(a, b) {
1190
+ return (a.value === b.value &&
1191
+ a.loadState === b.loadState &&
1192
+ a.status === b.status &&
1193
+ a.message === b.message &&
1194
+ a.hint === b.hint &&
1195
+ a.retryable === b.retryable &&
1196
+ a.readOnly === b.readOnly &&
1197
+ a.pending === b.pending &&
1198
+ a.flights === b.flights &&
1199
+ a.refusal === b.refusal &&
1200
+ a.notice === b.notice &&
1201
+ a.lastSyncedAt === b.lastSyncedAt &&
1202
+ a.lastError === b.lastError);
1203
+ }
1204
+ function emit(change) {
1205
+ saveCopySoon();
1206
+ settleWriteWaiters();
1207
+ const next = buildSnapshot();
1208
+ if (!change.valueChanged && sameSnapshot(snapshot, next))
1209
+ return;
1210
+ snapshot = next;
1211
+ for (const listener of [...listeners])
1212
+ listener(change);
1213
+ }
1214
+ function emitStatus() {
1215
+ emit({ remote: false, valueChanged: false, previous: value });
1216
+ }
1217
+ /* ------------------------------------------------------------------ API */
1218
+ load();
1219
+ return {
1220
+ getSnapshot: () => snapshot,
1221
+ value: () => value,
1222
+ subscribe(listener) {
1223
+ listeners.add(listener);
1224
+ return () => void listeners.delete(listener);
1225
+ },
1226
+ commit,
1227
+ canEdit,
1228
+ flush,
1229
+ whenWritten,
1230
+ writeNow,
1231
+ retry,
1232
+ setReadOnly(next) {
1233
+ if (readOnly === next)
1234
+ return;
1235
+ readOnly = next;
1236
+ if (!readOnly)
1237
+ schedule();
1238
+ emitStatus();
1239
+ },
1240
+ documentBytes: () => {
1241
+ materialize();
1242
+ return totalBytes;
1243
+ },
1244
+ dispose() {
1245
+ if (disposed)
1246
+ return;
1247
+ disposed = true;
1248
+ unsubscribe();
1249
+ clearLoadTimers();
1250
+ if (cacheTimer !== undefined) {
1251
+ timers.clearTimeout(cacheTimer);
1252
+ cacheTimer = undefined;
1253
+ saveCopyNow();
1254
+ }
1255
+ for (const handle of [syncTimer, materializeTimer])
1256
+ if (handle !== undefined)
1257
+ timers.clearTimeout(handle);
1258
+ for (const flight of flights)
1259
+ if (flight.timer !== undefined)
1260
+ timers.clearTimeout(flight.timer);
1261
+ flights = new Set();
1262
+ listeners.clear();
1263
+ const waiters = flushWaiters;
1264
+ flushWaiters = [];
1265
+ for (const resolve of waiters)
1266
+ resolve();
1267
+ settleWriteWaiters();
1268
+ },
1269
+ };
1270
+ }