@abraca/dabra 2.90.0 → 2.92.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.
- package/package.json +5 -11
- package/src/AbracadabraBaseProvider.ts +0 -963
- package/src/AbracadabraClient.ts +0 -1960
- package/src/AbracadabraProvider.ts +0 -915
- package/src/AbracadabraWS.ts +0 -695
- package/src/BackgroundSyncManager.ts +0 -856
- package/src/BackgroundSyncPersistence.ts +0 -140
- package/src/ChatClient.ts +0 -314
- package/src/CloseEvents.ts +0 -49
- package/src/ContentManager.ts +0 -246
- package/src/CoverReconcile.ts +0 -168
- package/src/CryptoIdentityKeystore.ts +0 -754
- package/src/DeviceRegistrationService.ts +0 -257
- package/src/DocConverters.ts +0 -1859
- package/src/DocKeyManager.ts +0 -163
- package/src/DocTypes.ts +0 -628
- package/src/DocUtils.ts +0 -251
- package/src/DocumentCache.ts +0 -210
- package/src/DocumentManager.ts +0 -410
- package/src/E2EAbracadabraProvider.ts +0 -426
- package/src/E2EOfflineStore.ts +0 -55
- package/src/EncryptedChatClient.ts +0 -173
- package/src/EncryptedY.ts +0 -145
- package/src/EventEmitter.ts +0 -59
- package/src/FileBlobStore.ts +0 -569
- package/src/IdentityDoc.ts +0 -711
- package/src/IncomingMessage.ts +0 -63
- package/src/MessageReceiver.ts +0 -151
- package/src/MessageSender.ts +0 -22
- package/src/MetaManager.ts +0 -194
- package/src/MnemonicKeyDerivation.ts +0 -171
- package/src/NodeConnect.ts +0 -63
- package/src/NodeIdentity.ts +0 -378
- package/src/NotificationsClient.ts +0 -207
- package/src/OfflineStore.ts +0 -294
- package/src/OutgoingMessage.ts +0 -25
- package/src/OutgoingMessages/AuthenticationMessage.ts +0 -23
- package/src/OutgoingMessages/AwarenessMessage.ts +0 -41
- package/src/OutgoingMessages/CloseMessage.ts +0 -17
- package/src/OutgoingMessages/QueryAwarenessMessage.ts +0 -17
- package/src/OutgoingMessages/StatelessMessage.ts +0 -18
- package/src/OutgoingMessages/SubdocMessage.ts +0 -35
- package/src/OutgoingMessages/SyncStepOneMessage.ts +0 -25
- package/src/OutgoingMessages/SyncStepTwoMessage.ts +0 -25
- package/src/OutgoingMessages/UpdateMessage.ts +0 -20
- package/src/QueryClient.ts +0 -209
- package/src/RpcClient.ts +0 -659
- package/src/SchemaTypes.ts +0 -179
- package/src/SearchIndex.ts +0 -250
- package/src/ServerRegistry.ts +0 -220
- package/src/ServerReset.ts +0 -222
- package/src/TokenManager.ts +0 -337
- package/src/TreeManager.ts +0 -894
- package/src/TreeTimestamps.ts +0 -101
- package/src/auth.ts +0 -62
- package/src/awarenessStatesToArray.ts +0 -10
- package/src/index.ts +0 -219
- package/src/messageRecord.ts +0 -121
- package/src/sync/BroadcastChannelSync.ts +0 -235
- package/src/types.ts +0 -790
- package/src/webrtc/AbracadabraWebRTC.ts +0 -683
- package/src/webrtc/DataChannelRouter.ts +0 -179
- package/src/webrtc/DevicePairingChannel.ts +0 -496
- package/src/webrtc/E2EEChannel.ts +0 -195
- package/src/webrtc/FileTransferChannel.ts +0 -367
- package/src/webrtc/ManualSignaling.ts +0 -204
- package/src/webrtc/PeerConnection.ts +0 -133
- package/src/webrtc/SignalingSocket.ts +0 -378
- package/src/webrtc/YjsDataChannel.ts +0 -203
- package/src/webrtc/index.ts +0 -26
- package/src/webrtc/types.ts +0 -177
|
@@ -1,856 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* BackgroundSyncManager
|
|
3
|
-
*
|
|
4
|
-
* Proactively syncs all documents in the root tree map to IndexedDB so they
|
|
5
|
-
* are available offline even if the user has never opened them directly.
|
|
6
|
-
*
|
|
7
|
-
* Key behaviours:
|
|
8
|
-
* - Priority queue: sorted by updatedAt desc → never-synced first → errored last
|
|
9
|
-
* - Concurrency: semaphore (default 2 parallel WS connections)
|
|
10
|
-
* - Provider selection: non-E2E via rootProvider.loadChild(); E2E via
|
|
11
|
-
* E2EAbracadabraProvider directly when docKeyManager + keystore are present
|
|
12
|
-
* - File pre-caching: after sync, walks the Y.Doc for file refs and warms
|
|
13
|
-
* the FileBlobStore cache (opt-in via prefetchFiles, default true)
|
|
14
|
-
* - Cover images: at start of syncAll(), pre-caches all cover upload IDs
|
|
15
|
-
* from the root tree map immediately (fire-and-forget)
|
|
16
|
-
* - Periodic sync: startPeriodicSync() returns a cleanup function
|
|
17
|
-
*
|
|
18
|
-
* Note: This is in-page only (no Service Worker). The existing
|
|
19
|
-
* flushPendingUpdates() handles offline → reconnect for open docs.
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
import * as Y from "yjs";
|
|
23
|
-
import type { AbracadabraProvider } from "./AbracadabraProvider.ts";
|
|
24
|
-
import type { AbracadabraClient } from "./AbracadabraClient.ts";
|
|
25
|
-
import type { FileBlobStore } from "./FileBlobStore.ts";
|
|
26
|
-
import {
|
|
27
|
-
BackgroundSyncPersistence,
|
|
28
|
-
type DocSyncState,
|
|
29
|
-
} from "./BackgroundSyncPersistence.ts";
|
|
30
|
-
import { OfflineStore } from "./OfflineStore.ts";
|
|
31
|
-
import EventEmitter from "./EventEmitter.ts";
|
|
32
|
-
import { E2EAbracadabraProvider } from "./E2EAbracadabraProvider.ts";
|
|
33
|
-
|
|
34
|
-
export interface BackgroundSyncManagerOptions {
|
|
35
|
-
/** Max parallel WS connections for background sync. Default: 2. */
|
|
36
|
-
concurrency?: number;
|
|
37
|
-
/** Timeout (ms) waiting for a provider to sync. Default: 30 000. */
|
|
38
|
-
syncTimeout?: number;
|
|
39
|
-
/** Pre-cache file blobs after syncing a doc. Default: true. */
|
|
40
|
-
prefetchFiles?: boolean;
|
|
41
|
-
/** Delay (ms) between starting each doc sync to avoid server pressure. Default: 200. */
|
|
42
|
-
throttleMs?: number;
|
|
43
|
-
/** Max retries for failed docs within a single syncAll() run. Default: 2. */
|
|
44
|
-
maxRetries?: number;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* Simple semaphore for capping concurrency.
|
|
49
|
-
*/
|
|
50
|
-
class Semaphore {
|
|
51
|
-
private slots: number;
|
|
52
|
-
private queue: Array<() => void> = [];
|
|
53
|
-
|
|
54
|
-
constructor(limit: number) {
|
|
55
|
-
this.slots = limit;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
acquire(): Promise<void> {
|
|
59
|
-
if (this.slots > 0) {
|
|
60
|
-
this.slots--;
|
|
61
|
-
return Promise.resolve();
|
|
62
|
-
}
|
|
63
|
-
return new Promise((resolve) => this.queue.push(resolve));
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
release(): void {
|
|
67
|
-
const next = this.queue.shift();
|
|
68
|
-
if (next) {
|
|
69
|
-
next();
|
|
70
|
-
} else {
|
|
71
|
-
this.slots++;
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
/**
|
|
77
|
-
* Server-accepted doc-id format. The Rust server's `DocId::from_string`
|
|
78
|
-
* is a strict UUID parse; any other string returns 422. Stale entries in
|
|
79
|
-
* the doc-tree map (legacy slug ids from earlier demos, manual experiments)
|
|
80
|
-
* would otherwise emit one 422 per `syncAll()` forever — see the warn
|
|
81
|
-
* below in `_buildQueue`.
|
|
82
|
-
*/
|
|
83
|
-
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
84
|
-
|
|
85
|
-
function isValidDocId(id: string): boolean {
|
|
86
|
-
return UUID_RE.test(id);
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/**
|
|
90
|
-
* Consecutive transient failures before a doc is promoted from the calm
|
|
91
|
-
* `retrying` status to a genuine `error`. Keeps a single timeout/network blip
|
|
92
|
-
* from flashing a red error badge — the doc only "counts" as broken once it
|
|
93
|
-
* has failed this many passes in a row.
|
|
94
|
-
*/
|
|
95
|
-
const FAILURE_THRESHOLD = 3;
|
|
96
|
-
|
|
97
|
-
/** Delay before a one-shot follow-up retry of stragglers after `syncAll()`. */
|
|
98
|
-
const STRAGGLER_RETRY_DELAY_MS = 60_000;
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* Decide whether a sync failure is permanent (the server will never accept
|
|
102
|
-
* this doc — deleted, forbidden, or an unparseable id) or merely transient
|
|
103
|
-
* (timeout, dropped socket, momentary 5xx). Permanent failures are parked as
|
|
104
|
-
* `unavailable` and never retried; transient ones go through `retrying`.
|
|
105
|
-
*
|
|
106
|
-
* Best-effort: inspects a numeric `status`/`code` if the thrown value carries
|
|
107
|
-
* one, otherwise falls back to message keywords. Defaults to transient so we
|
|
108
|
-
* never give up on a doc we're unsure about.
|
|
109
|
-
*/
|
|
110
|
-
function isPermanentSyncError(err: unknown): boolean {
|
|
111
|
-
const status =
|
|
112
|
-
typeof err === "object" && err !== null
|
|
113
|
-
? Number(
|
|
114
|
-
(err as { status?: unknown; statusCode?: unknown; code?: unknown })
|
|
115
|
-
.status ??
|
|
116
|
-
(err as { statusCode?: unknown }).statusCode ??
|
|
117
|
-
(err as { code?: unknown }).code,
|
|
118
|
-
)
|
|
119
|
-
: NaN;
|
|
120
|
-
if (status === 403 || status === 404 || status === 410 || status === 422) {
|
|
121
|
-
return true;
|
|
122
|
-
}
|
|
123
|
-
const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
|
|
124
|
-
return (
|
|
125
|
-
/\b(403|404|410|422)\b/.test(msg) ||
|
|
126
|
-
msg.includes("forbidden") ||
|
|
127
|
-
msg.includes("not found") ||
|
|
128
|
-
msg.includes("does not exist") ||
|
|
129
|
-
msg.includes("unprocessable")
|
|
130
|
-
);
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
export class BackgroundSyncManager extends EventEmitter {
|
|
134
|
-
private readonly rootProvider: AbracadabraProvider;
|
|
135
|
-
private readonly client: AbracadabraClient;
|
|
136
|
-
private readonly fileBlobStore: FileBlobStore | null;
|
|
137
|
-
private readonly opts: Required<BackgroundSyncManagerOptions>;
|
|
138
|
-
|
|
139
|
-
private readonly persistence: BackgroundSyncPersistence;
|
|
140
|
-
private readonly semaphore: Semaphore;
|
|
141
|
-
private readonly syncStates = new Map<string, DocSyncState>();
|
|
142
|
-
/** Doc ids we've already warned about; keeps the log to one line per id. */
|
|
143
|
-
private readonly _warnedInvalidIds = new Set<string>();
|
|
144
|
-
|
|
145
|
-
private _destroyed = false;
|
|
146
|
-
private _initPromise: Promise<void> | null = null;
|
|
147
|
-
/** One-shot timer for the post-syncAll straggler retry pass. */
|
|
148
|
-
private _stragglerTimer: ReturnType<typeof setTimeout> | null = null;
|
|
149
|
-
|
|
150
|
-
constructor(
|
|
151
|
-
rootProvider: AbracadabraProvider,
|
|
152
|
-
client: AbracadabraClient,
|
|
153
|
-
fileBlobStore?: FileBlobStore | null,
|
|
154
|
-
opts?: BackgroundSyncManagerOptions,
|
|
155
|
-
) {
|
|
156
|
-
super();
|
|
157
|
-
this.rootProvider = rootProvider;
|
|
158
|
-
this.client = client;
|
|
159
|
-
this.fileBlobStore = fileBlobStore ?? null;
|
|
160
|
-
this.opts = {
|
|
161
|
-
concurrency: opts?.concurrency ?? 2,
|
|
162
|
-
syncTimeout: opts?.syncTimeout ?? 30_000,
|
|
163
|
-
prefetchFiles: opts?.prefetchFiles ?? true,
|
|
164
|
-
throttleMs: opts?.throttleMs ?? 200,
|
|
165
|
-
maxRetries: opts?.maxRetries ?? 2,
|
|
166
|
-
};
|
|
167
|
-
|
|
168
|
-
// Derive server origin from client URL for IDB namespacing.
|
|
169
|
-
// `host` (not `hostname`): port-scoped so same-host servers on
|
|
170
|
-
// different ports don't share a namespace.
|
|
171
|
-
let serverOrigin = "default";
|
|
172
|
-
try {
|
|
173
|
-
serverOrigin = new URL((client as any).baseUrl ?? "").host;
|
|
174
|
-
} catch {}
|
|
175
|
-
|
|
176
|
-
this.persistence = new BackgroundSyncPersistence(serverOrigin);
|
|
177
|
-
this.semaphore = new Semaphore(this.opts.concurrency);
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
// ── Public API ────────────────────────────────────────────────────────────
|
|
181
|
-
|
|
182
|
-
/**
|
|
183
|
-
* Load persisted sync states from IndexedDB into the in-memory map.
|
|
184
|
-
* Called automatically by syncAll() / syncDoc(); safe to call concurrently.
|
|
185
|
-
*/
|
|
186
|
-
async init(): Promise<void> {
|
|
187
|
-
if (!this._initPromise) {
|
|
188
|
-
this._initPromise = this._loadPersistedStates();
|
|
189
|
-
}
|
|
190
|
-
return this._initPromise;
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
private async _loadPersistedStates(): Promise<void> {
|
|
194
|
-
try {
|
|
195
|
-
const states = await this.persistence.getAllStates();
|
|
196
|
-
for (const state of states) {
|
|
197
|
-
this.syncStates.set(state.docId, state);
|
|
198
|
-
}
|
|
199
|
-
} catch {
|
|
200
|
-
// IDB unavailable — proceed with empty map (full sync fallback)
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
/**
|
|
205
|
-
* Re-read persisted sync states from IndexedDB, merging in any docs not
|
|
206
|
-
* already tracked in memory. Unlike `init()` this is **not** cached behind
|
|
207
|
-
* `_initPromise` — every call hits IDB afresh.
|
|
208
|
-
*
|
|
209
|
-
* Why this exists: `init()` only ever loads IDB once. If a manager was
|
|
210
|
-
* created while IDB was empty/mid-population (or a UI singleton was left
|
|
211
|
-
* pointing at a manager whose in-memory map is stale after a connection
|
|
212
|
-
* swap), the only thing that recovered the real counts was a full page
|
|
213
|
-
* reload (which spins up a brand-new manager → fresh `_loadPersistedStates`).
|
|
214
|
-
* Calling this re-hydrates from the same source a reload reads, so the
|
|
215
|
-
* offline-sync panel can self-heal from a spurious "0/0" without a reload.
|
|
216
|
-
*
|
|
217
|
-
* Merge-only by design: an in-memory entry (possibly a fresher in-flight
|
|
218
|
-
* `syncing`/`synced`) is never clobbered by the persisted copy; we only add
|
|
219
|
-
* docs IDB knows about that memory doesn't.
|
|
220
|
-
*/
|
|
221
|
-
async reloadPersistedStates(): Promise<void> {
|
|
222
|
-
try {
|
|
223
|
-
const states = await this.persistence.getAllStates();
|
|
224
|
-
for (const state of states) {
|
|
225
|
-
if (!this.syncStates.has(state.docId)) {
|
|
226
|
-
this.syncStates.set(state.docId, state);
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
} catch {
|
|
230
|
-
// IDB unavailable — keep whatever is already in memory.
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
/** Sync all documents in the root tree. */
|
|
235
|
-
async syncAll(): Promise<void> {
|
|
236
|
-
if (this._destroyed) return;
|
|
237
|
-
|
|
238
|
-
await this.init();
|
|
239
|
-
|
|
240
|
-
const treeMap = this.rootProvider.document.getMap("doc-tree") as Y.Map<any>;
|
|
241
|
-
const entries = Array.from(treeMap.entries()) as Array<[string, any]>;
|
|
242
|
-
|
|
243
|
-
if (entries.length === 0) return;
|
|
244
|
-
|
|
245
|
-
// Build updatedAt lookup for skip-unchanged logic
|
|
246
|
-
const updatedAtMap = new Map<string, number>();
|
|
247
|
-
for (const [docId, v] of entries) {
|
|
248
|
-
updatedAtMap.set(docId, v?.updatedAt ?? v?.createdAt ?? 0);
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
// Pre-cache cover images immediately (fire-and-forget)
|
|
252
|
-
this._prefetchCovers(entries).catch(() => null);
|
|
253
|
-
|
|
254
|
-
// Build the priority queue
|
|
255
|
-
const queue = this._buildQueue(entries);
|
|
256
|
-
|
|
257
|
-
// Sync all docs with throttling: stagger starts to avoid server pressure.
|
|
258
|
-
// We use a feeding loop instead of Promise.all(queue.map(...)) so that
|
|
259
|
-
// each new doc start is spaced by throttleMs.
|
|
260
|
-
const failed: string[] = [];
|
|
261
|
-
let idx = 0;
|
|
262
|
-
const next = async (): Promise<void> => {
|
|
263
|
-
while (idx < queue.length) {
|
|
264
|
-
if (this._destroyed) return;
|
|
265
|
-
const docId = queue[idx++]!;
|
|
266
|
-
const updatedAt = updatedAtMap.get(docId) ?? 0;
|
|
267
|
-
const ok = await this._syncWithSemaphore(docId, updatedAt);
|
|
268
|
-
if (!ok) failed.push(docId);
|
|
269
|
-
// Throttle between starts
|
|
270
|
-
if (this.opts.throttleMs > 0 && idx < queue.length) {
|
|
271
|
-
await new Promise((r) => setTimeout(r, this.opts.throttleMs));
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
};
|
|
275
|
-
|
|
276
|
-
// Launch `concurrency` parallel workers feeding from the shared index.
|
|
277
|
-
const workers = Array.from({ length: this.opts.concurrency }, () => next());
|
|
278
|
-
await Promise.all(workers);
|
|
279
|
-
|
|
280
|
-
// Retry failed docs with increasing backoff.
|
|
281
|
-
for (let retry = 0; retry < this.opts.maxRetries && failed.length > 0; retry++) {
|
|
282
|
-
if (this._destroyed) return;
|
|
283
|
-
const batch = failed.splice(0, failed.length);
|
|
284
|
-
// Backoff: 2s, 4s, 8s...
|
|
285
|
-
const backoff = 2000 * 2 ** retry;
|
|
286
|
-
await new Promise((r) => setTimeout(r, backoff));
|
|
287
|
-
|
|
288
|
-
idx = 0;
|
|
289
|
-
const retryQueue = batch;
|
|
290
|
-
const retryNext = async (): Promise<void> => {
|
|
291
|
-
while (idx < retryQueue.length) {
|
|
292
|
-
if (this._destroyed) return;
|
|
293
|
-
const docId = retryQueue[idx++]!;
|
|
294
|
-
const updatedAt = updatedAtMap.get(docId) ?? 0;
|
|
295
|
-
const ok = await this._syncWithSemaphore(docId, updatedAt);
|
|
296
|
-
if (!ok) failed.push(docId);
|
|
297
|
-
if (this.opts.throttleMs > 0 && idx < retryQueue.length) {
|
|
298
|
-
await new Promise((r) => setTimeout(r, this.opts.throttleMs));
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
};
|
|
302
|
-
const retryWorkers = Array.from({ length: this.opts.concurrency }, () => retryNext());
|
|
303
|
-
await Promise.all(retryWorkers);
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
// Any docs still failing after the in-run retries are "stragglers" — the
|
|
307
|
-
// usual 1-2 slow docs that just needed a moment. Rather than make the
|
|
308
|
-
// user stare at them until the next periodic pass (which can be far off),
|
|
309
|
-
// schedule one quiet follow-up attempt while the connection is still warm.
|
|
310
|
-
if (failed.length > 0) {
|
|
311
|
-
this._scheduleStragglerRetry(failed.slice());
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
/**
|
|
316
|
-
* Schedule a single delayed retry of the given docs. Replaces any pending
|
|
317
|
-
* straggler timer so repeated `syncAll()` calls don't stack timers.
|
|
318
|
-
*/
|
|
319
|
-
private _scheduleStragglerRetry(docIds: string[]): void {
|
|
320
|
-
if (this._destroyed || docIds.length === 0) return;
|
|
321
|
-
if (this._stragglerTimer) clearTimeout(this._stragglerTimer);
|
|
322
|
-
this._stragglerTimer = setTimeout(() => {
|
|
323
|
-
this._stragglerTimer = null;
|
|
324
|
-
if (this._destroyed) return;
|
|
325
|
-
void (async () => {
|
|
326
|
-
const treeMap = this.rootProvider.document.getMap(
|
|
327
|
-
"doc-tree",
|
|
328
|
-
) as Y.Map<any>;
|
|
329
|
-
for (const docId of docIds) {
|
|
330
|
-
if (this._destroyed) return;
|
|
331
|
-
const entry = treeMap.get(docId);
|
|
332
|
-
const updatedAt = entry?.updatedAt ?? entry?.createdAt ?? 0;
|
|
333
|
-
await this._syncWithSemaphore(docId, updatedAt);
|
|
334
|
-
}
|
|
335
|
-
})();
|
|
336
|
-
}, STRAGGLER_RETRY_DELAY_MS);
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
/** Sync a single document by ID. */
|
|
340
|
-
async syncDoc(docId: string): Promise<DocSyncState> {
|
|
341
|
-
await this.init();
|
|
342
|
-
const state = await this._doSyncDoc(docId);
|
|
343
|
-
this.syncStates.set(docId, state);
|
|
344
|
-
await this.persistence.setState(state).catch(() => null);
|
|
345
|
-
this.emit("stateChanged", { docId, state });
|
|
346
|
-
return state;
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
/** Return a snapshot of all known sync states. */
|
|
350
|
-
getSyncStatus(): Map<string, DocSyncState> {
|
|
351
|
-
return new Map(this.syncStates);
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
/**
|
|
355
|
-
* Start periodic background sync.
|
|
356
|
-
* @param intervalMs Interval between sync runs. Default: 5 minutes.
|
|
357
|
-
* @returns Cleanup function to stop the periodic sync.
|
|
358
|
-
*/
|
|
359
|
-
startPeriodicSync(intervalMs = 5 * 60 * 1000): () => void {
|
|
360
|
-
const handle = setInterval(() => {
|
|
361
|
-
if (!this._destroyed) {
|
|
362
|
-
this.syncAll().catch(() => null);
|
|
363
|
-
}
|
|
364
|
-
}, intervalMs);
|
|
365
|
-
return () => clearInterval(handle);
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
/**
|
|
369
|
-
* Clear all offline document data and sync state.
|
|
370
|
-
* Opens each document's OfflineStore and clears its contents, then
|
|
371
|
-
* resets the background sync persistence. After calling this, all
|
|
372
|
-
* documents will need to be re-synced.
|
|
373
|
-
*/
|
|
374
|
-
async clearAllSyncedData(): Promise<void> {
|
|
375
|
-
// Collect doc IDs from both in-memory state and the tree
|
|
376
|
-
const docIds = new Set<string>(this.syncStates.keys());
|
|
377
|
-
const treeMap = this.rootProvider.document.getMap("doc-tree") as Y.Map<any>;
|
|
378
|
-
for (const docId of treeMap.keys()) {
|
|
379
|
-
docIds.add(docId);
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
// Derive server origin the same way the provider does (`host`, port-scoped)
|
|
383
|
-
let serverOrigin: string | undefined;
|
|
384
|
-
try {
|
|
385
|
-
serverOrigin = new URL((this.client as any).baseUrl ?? "").host;
|
|
386
|
-
} catch {}
|
|
387
|
-
|
|
388
|
-
// Clear each document's offline store contents
|
|
389
|
-
const clearPromises = Array.from(docIds).map(async (docId) => {
|
|
390
|
-
try {
|
|
391
|
-
const store = new OfflineStore(docId, serverOrigin);
|
|
392
|
-
await store.clearAll();
|
|
393
|
-
store.destroy();
|
|
394
|
-
} catch {
|
|
395
|
-
// Ignore per-doc failures
|
|
396
|
-
}
|
|
397
|
-
});
|
|
398
|
-
await Promise.all(clearPromises);
|
|
399
|
-
|
|
400
|
-
// Clear background sync persistence
|
|
401
|
-
for (const docId of docIds) {
|
|
402
|
-
await this.persistence.deleteState(docId).catch(() => null);
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
// Reset in-memory state
|
|
406
|
-
this.syncStates.clear();
|
|
407
|
-
this._initPromise = null;
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
destroy(): void {
|
|
411
|
-
this._destroyed = true;
|
|
412
|
-
if (this._stragglerTimer) {
|
|
413
|
-
clearTimeout(this._stragglerTimer);
|
|
414
|
-
this._stragglerTimer = null;
|
|
415
|
-
}
|
|
416
|
-
this.removeAllListeners();
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
// ── Internal ──────────────────────────────────────────────────────────────
|
|
420
|
-
|
|
421
|
-
/**
|
|
422
|
-
* Build a priority-sorted list of doc IDs:
|
|
423
|
-
* 1. Never-synced docs first (lastSynced === null, status !== "error")
|
|
424
|
-
* 2. Synced docs sorted by updatedAt desc (most-recently-edited first)
|
|
425
|
-
* 3. Errored docs last
|
|
426
|
-
*/
|
|
427
|
-
private _buildQueue(entries: Array<[string, any]>): string[] {
|
|
428
|
-
type Sortable = { docId: string; priority: number };
|
|
429
|
-
|
|
430
|
-
// Drop ids the server can't parse (non-UUID). One-time warn per id
|
|
431
|
-
// so the operator can chase down where the stale entry is, but no
|
|
432
|
-
// log storm on every sync run.
|
|
433
|
-
const filtered: Array<[string, any]> = [];
|
|
434
|
-
for (const entry of entries) {
|
|
435
|
-
const [docId] = entry;
|
|
436
|
-
if (isValidDocId(docId)) {
|
|
437
|
-
filtered.push(entry);
|
|
438
|
-
continue;
|
|
439
|
-
}
|
|
440
|
-
if (!this._warnedInvalidIds.has(docId)) {
|
|
441
|
-
this._warnedInvalidIds.add(docId);
|
|
442
|
-
console.warn(
|
|
443
|
-
`[BackgroundSyncManager] skipping non-UUID doc id "${docId}" in doc-tree — server would reject it (422). Likely a stale entry from an earlier seeder; remove it from the tree to silence this.`,
|
|
444
|
-
);
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
const items: Sortable[] = [];
|
|
449
|
-
for (const [docId, v] of filtered) {
|
|
450
|
-
const state = this.syncStates.get(docId);
|
|
451
|
-
|
|
452
|
-
// Permanently unavailable docs are never queued — the server would
|
|
453
|
-
// just reject them again. They stay parked until a resync clears them.
|
|
454
|
-
if (state?.status === "unavailable") continue;
|
|
455
|
-
|
|
456
|
-
const updatedAt: number = v?.updatedAt ?? v?.createdAt ?? 0;
|
|
457
|
-
|
|
458
|
-
let priority: number;
|
|
459
|
-
if (!state || state.status === "pending") {
|
|
460
|
-
// Never synced — high priority (large number so it sorts first when DESC)
|
|
461
|
-
priority = Number.MAX_SAFE_INTEGER - updatedAt;
|
|
462
|
-
} else if (state.status === "error" || state.status === "retrying") {
|
|
463
|
-
// Failing — lowest priority (large negative offset)
|
|
464
|
-
priority = -1;
|
|
465
|
-
} else {
|
|
466
|
-
// Synced — sort by updatedAt desc (most recent = highest priority)
|
|
467
|
-
priority = updatedAt;
|
|
468
|
-
}
|
|
469
|
-
items.push({ docId, priority });
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
// Sort descending by priority
|
|
473
|
-
items.sort((a, b) => b.priority - a.priority);
|
|
474
|
-
return items.map((i) => i.docId);
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
/** Returns true on success (or skip), false on error. */
|
|
478
|
-
private async _syncWithSemaphore(
|
|
479
|
-
docId: string,
|
|
480
|
-
updatedAt: number,
|
|
481
|
-
): Promise<boolean> {
|
|
482
|
-
if (this._destroyed) return true;
|
|
483
|
-
|
|
484
|
-
const existing = this.syncStates.get(docId);
|
|
485
|
-
|
|
486
|
-
// Permanently unavailable (deleted/forbidden) — don't keep hammering a
|
|
487
|
-
// doc the server will never accept. Re-emit so the UI keeps the state.
|
|
488
|
-
if (existing && existing.status === "unavailable") {
|
|
489
|
-
this.emit("stateChanged", { docId, state: existing });
|
|
490
|
-
return true;
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
// Skip if already synced and doc hasn't changed since last sync.
|
|
494
|
-
// The 200ms grace margin handles edge cases where the updatedAt
|
|
495
|
-
// observer writes a timestamp milliseconds after lastSynced was recorded.
|
|
496
|
-
if (
|
|
497
|
-
existing &&
|
|
498
|
-
existing.status === "synced" &&
|
|
499
|
-
existing.lastSynced !== null &&
|
|
500
|
-
existing.lastSynced + 200 >= updatedAt
|
|
501
|
-
) {
|
|
502
|
-
this.emit("stateChanged", { docId, state: existing });
|
|
503
|
-
return true;
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
await this.semaphore.acquire();
|
|
507
|
-
try {
|
|
508
|
-
const state = await this._doSyncDoc(docId);
|
|
509
|
-
this.syncStates.set(docId, state);
|
|
510
|
-
await this.persistence.setState(state).catch(() => null);
|
|
511
|
-
this.emit("stateChanged", { docId, state });
|
|
512
|
-
// `retrying` and `error` are both failures that warrant another pass;
|
|
513
|
-
// `unavailable` is permanent so we report it as done (no retry).
|
|
514
|
-
return state.status !== "error" && state.status !== "retrying";
|
|
515
|
-
} finally {
|
|
516
|
-
this.semaphore.release();
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
private async _doSyncDoc(docId: string): Promise<DocSyncState> {
|
|
521
|
-
// Non-UUID ids the server can't parse (422) are permanently unsyncable —
|
|
522
|
-
// park them as `unavailable` rather than churning through retries.
|
|
523
|
-
if (!isValidDocId(docId)) {
|
|
524
|
-
return {
|
|
525
|
-
docId,
|
|
526
|
-
status: "unavailable",
|
|
527
|
-
lastSynced: this.syncStates.get(docId)?.lastSynced ?? null,
|
|
528
|
-
error: "Invalid document id (not a UUID)",
|
|
529
|
-
consecutiveFailures: 0,
|
|
530
|
-
isE2E: false,
|
|
531
|
-
};
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
// Mark as syncing
|
|
535
|
-
const syncing: DocSyncState = {
|
|
536
|
-
docId,
|
|
537
|
-
status: "syncing",
|
|
538
|
-
lastSynced: this.syncStates.get(docId)?.lastSynced ?? null,
|
|
539
|
-
isE2E: false,
|
|
540
|
-
};
|
|
541
|
-
this.syncStates.set(docId, syncing);
|
|
542
|
-
this.emit("stateChanged", { docId, state: syncing });
|
|
543
|
-
|
|
544
|
-
let isE2E = false;
|
|
545
|
-
try {
|
|
546
|
-
// Check encryption type
|
|
547
|
-
try {
|
|
548
|
-
const enc = await this.client.getDocEncryption(docId);
|
|
549
|
-
isE2E = enc.mode === "e2e";
|
|
550
|
-
} catch {
|
|
551
|
-
// If we can't check, treat as non-E2E
|
|
552
|
-
}
|
|
553
|
-
|
|
554
|
-
if (isE2E) {
|
|
555
|
-
return await this._syncE2EDoc(docId);
|
|
556
|
-
} else {
|
|
557
|
-
return await this._syncNonE2EDoc(docId);
|
|
558
|
-
}
|
|
559
|
-
} catch (err) {
|
|
560
|
-
const error = err instanceof Error ? err.message : String(err);
|
|
561
|
-
const prev = this.syncStates.get(docId);
|
|
562
|
-
const lastSynced = prev?.lastSynced ?? null;
|
|
563
|
-
|
|
564
|
-
// Permanent failure (deleted / forbidden / unparseable) — park it as
|
|
565
|
-
// `unavailable` so we stop retrying and never surface it as an error.
|
|
566
|
-
if (isPermanentSyncError(err)) {
|
|
567
|
-
return {
|
|
568
|
-
docId,
|
|
569
|
-
status: "unavailable",
|
|
570
|
-
lastSynced,
|
|
571
|
-
error,
|
|
572
|
-
consecutiveFailures: 0,
|
|
573
|
-
isE2E,
|
|
574
|
-
};
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
// Transient failure — escalate to a genuine `error` only once it has
|
|
578
|
-
// recurred past the threshold; otherwise keep it calm as `retrying`.
|
|
579
|
-
const consecutiveFailures = (prev?.consecutiveFailures ?? 0) + 1;
|
|
580
|
-
return {
|
|
581
|
-
docId,
|
|
582
|
-
status:
|
|
583
|
-
consecutiveFailures >= FAILURE_THRESHOLD ? "error" : "retrying",
|
|
584
|
-
lastSynced,
|
|
585
|
-
error,
|
|
586
|
-
consecutiveFailures,
|
|
587
|
-
isE2E,
|
|
588
|
-
};
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
private async _syncNonE2EDoc(docId: string): Promise<DocSyncState> {
|
|
593
|
-
const treeMap = this.rootProvider.document.getMap("doc-tree") as Y.Map<any>;
|
|
594
|
-
|
|
595
|
-
// Check if the provider already exists (user is viewing it) before loading.
|
|
596
|
-
const alreadyCached = this.rootProvider.children.has(docId);
|
|
597
|
-
|
|
598
|
-
// Another provider (e.g. a nested renderer) may have already loaded
|
|
599
|
-
// this doc through a different parent. The shared WS providerMap
|
|
600
|
-
// tracks all attached providers; if one exists, the doc is already
|
|
601
|
-
// syncing — skip to avoid creating a duplicate.
|
|
602
|
-
if (!alreadyCached) {
|
|
603
|
-
const wsProviderMap = (this.rootProvider as any).configuration
|
|
604
|
-
?.websocketProvider?.configuration?.providerMap as
|
|
605
|
-
| Map<string, unknown>
|
|
606
|
-
| undefined;
|
|
607
|
-
if (wsProviderMap?.has(docId)) {
|
|
608
|
-
return {
|
|
609
|
-
docId,
|
|
610
|
-
status: "synced",
|
|
611
|
-
lastSynced: Date.now(),
|
|
612
|
-
consecutiveFailures: 0,
|
|
613
|
-
isE2E: false,
|
|
614
|
-
};
|
|
615
|
-
}
|
|
616
|
-
}
|
|
617
|
-
|
|
618
|
-
// Load transiently: a background-sync child must neither count toward
|
|
619
|
-
// the parent's LRU budget nor evict the user's open docs, and it must
|
|
620
|
-
// not be evicted out from under its own in-flight sync. We clean it up
|
|
621
|
-
// explicitly in `finally`.
|
|
622
|
-
const childProvider = await this.rootProvider.loadChild(docId, {
|
|
623
|
-
evictable: false,
|
|
624
|
-
});
|
|
625
|
-
|
|
626
|
-
try {
|
|
627
|
-
// Wait for ready (offline snapshot loaded) then synced (server sync done)
|
|
628
|
-
await childProvider.ready;
|
|
629
|
-
await this._waitForSynced(childProvider);
|
|
630
|
-
|
|
631
|
-
// Force the offline snapshot to disk BEFORE the `finally` below
|
|
632
|
-
// unloads (and therefore destroys) this provider. The provider's own
|
|
633
|
-
// "synced" handler also writes one, but that runs concurrently and
|
|
634
|
-
// loses the race often enough that most background-synced documents
|
|
635
|
-
// ended up with an empty offline cache — which is also why the
|
|
636
|
-
// client-side search/backlink index had almost nothing to walk.
|
|
637
|
-
// "Synced" must mean "on disk", or this manager is lying.
|
|
638
|
-
if (typeof (childProvider as any).persistSnapshot === "function") {
|
|
639
|
-
await (childProvider as any).persistSnapshot();
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
// Emit docSynced while the child is still loaded so listeners can
|
|
643
|
-
// extract data (search text, file refs) without opening a new IDB.
|
|
644
|
-
{
|
|
645
|
-
const treeEntry = treeMap.get(docId);
|
|
646
|
-
this.emit("docSynced", {
|
|
647
|
-
docId,
|
|
648
|
-
document: childProvider.document,
|
|
649
|
-
label: treeEntry?.label ?? "",
|
|
650
|
-
meta: treeEntry?.meta,
|
|
651
|
-
});
|
|
652
|
-
}
|
|
653
|
-
|
|
654
|
-
// Prefetch file blobs
|
|
655
|
-
if (this.opts.prefetchFiles && this.fileBlobStore) {
|
|
656
|
-
this._prefetchDocFiles(docId, childProvider.document).catch(() => null);
|
|
657
|
-
}
|
|
658
|
-
|
|
659
|
-
// Use the tree's updatedAt so lastSynced >= updatedAt, preventing
|
|
660
|
-
// the observer's timestamp write from triggering a spurious re-sync.
|
|
661
|
-
const treeEntry = treeMap.get(docId);
|
|
662
|
-
const treeUpdatedAt = treeEntry?.updatedAt ?? treeEntry?.createdAt ?? 0;
|
|
663
|
-
return {
|
|
664
|
-
docId,
|
|
665
|
-
status: "synced",
|
|
666
|
-
lastSynced: Math.max(Date.now(), treeUpdatedAt),
|
|
667
|
-
consecutiveFailures: 0,
|
|
668
|
-
isE2E: false,
|
|
669
|
-
};
|
|
670
|
-
} finally {
|
|
671
|
-
// Release the provider only if we created it solely for background
|
|
672
|
-
// sync. Two cases keep it alive:
|
|
673
|
-
// - `alreadyCached`: it was loaded before we started — the UI owns it.
|
|
674
|
-
// - the user OPENED it mid-sync: `loadChild` (default evictable)
|
|
675
|
-
// promoted it out of transient, so it's no longer ours. Destroying
|
|
676
|
-
// it here would detach the provider under a doc they're viewing,
|
|
677
|
-
// leaving it stuck on a blue/"retrying" indicator until reload.
|
|
678
|
-
// `isChildTransient` is a newer provider API; fall back to the old
|
|
679
|
-
// unconditional unload if the parent predates it.
|
|
680
|
-
if (!alreadyCached) {
|
|
681
|
-
const stillOurs =
|
|
682
|
-
typeof (this.rootProvider as any).isChildTransient === "function"
|
|
683
|
-
? (this.rootProvider as any).isChildTransient(docId)
|
|
684
|
-
: true;
|
|
685
|
-
if (stillOurs) this.rootProvider.unloadChild(docId);
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
|
|
690
|
-
private async _syncE2EDoc(docId: string): Promise<DocSyncState> {
|
|
691
|
-
const treeMap = this.rootProvider.document.getMap("doc-tree") as Y.Map<any>;
|
|
692
|
-
|
|
693
|
-
// Attempt E2E sync only when docKeyManager and keystore are available
|
|
694
|
-
const docKeyManager = (this.rootProvider as any).abracadabraConfig
|
|
695
|
-
?.docKeyManager;
|
|
696
|
-
const keystore = (this.rootProvider as any).abracadabraConfig?.keystore;
|
|
697
|
-
|
|
698
|
-
if (!docKeyManager || !keystore) {
|
|
699
|
-
// No key management configured — skip silently
|
|
700
|
-
return {
|
|
701
|
-
docId,
|
|
702
|
-
status: "skipped",
|
|
703
|
-
lastSynced: null,
|
|
704
|
-
consecutiveFailures: 0,
|
|
705
|
-
isE2E: true,
|
|
706
|
-
};
|
|
707
|
-
}
|
|
708
|
-
|
|
709
|
-
const childDoc = new Y.Doc({ guid: docId });
|
|
710
|
-
const childProvider = new E2EAbracadabraProvider({
|
|
711
|
-
name: docId,
|
|
712
|
-
document: childDoc,
|
|
713
|
-
client: this.client,
|
|
714
|
-
docKeyManager,
|
|
715
|
-
keystore,
|
|
716
|
-
});
|
|
717
|
-
|
|
718
|
-
try {
|
|
719
|
-
await childProvider.ready;
|
|
720
|
-
await this._waitForSynced(childProvider);
|
|
721
|
-
|
|
722
|
-
// Emit docSynced while the child is still alive so listeners can
|
|
723
|
-
// extract data without opening a new IDB connection.
|
|
724
|
-
{
|
|
725
|
-
const treeEntry = treeMap.get(docId);
|
|
726
|
-
this.emit("docSynced", {
|
|
727
|
-
docId,
|
|
728
|
-
document: childDoc,
|
|
729
|
-
label: treeEntry?.label ?? "",
|
|
730
|
-
meta: treeEntry?.meta,
|
|
731
|
-
});
|
|
732
|
-
}
|
|
733
|
-
|
|
734
|
-
if (this.opts.prefetchFiles && this.fileBlobStore) {
|
|
735
|
-
this._prefetchDocFiles(docId, childDoc).catch(() => null);
|
|
736
|
-
}
|
|
737
|
-
|
|
738
|
-
// Use the tree's updatedAt so lastSynced >= updatedAt, preventing
|
|
739
|
-
// the observer's timestamp write from triggering a spurious re-sync.
|
|
740
|
-
const treeEntry = treeMap.get(docId);
|
|
741
|
-
const treeUpdatedAt = treeEntry?.updatedAt ?? treeEntry?.createdAt ?? 0;
|
|
742
|
-
return {
|
|
743
|
-
docId,
|
|
744
|
-
status: "synced",
|
|
745
|
-
lastSynced: Math.max(Date.now(), treeUpdatedAt),
|
|
746
|
-
consecutiveFailures: 0,
|
|
747
|
-
isE2E: true,
|
|
748
|
-
};
|
|
749
|
-
} finally {
|
|
750
|
-
childProvider.destroy();
|
|
751
|
-
}
|
|
752
|
-
}
|
|
753
|
-
|
|
754
|
-
/**
|
|
755
|
-
* Wait for a provider to emit the "synced" event (with state=true),
|
|
756
|
-
* timing out after opts.syncTimeout ms.
|
|
757
|
-
*/
|
|
758
|
-
private _waitForSynced(provider: any): Promise<void> {
|
|
759
|
-
// If already synced, resolve immediately
|
|
760
|
-
if (provider.synced === true) return Promise.resolve();
|
|
761
|
-
|
|
762
|
-
return new Promise<void>((resolve, reject) => {
|
|
763
|
-
const timer = setTimeout(() => {
|
|
764
|
-
provider.off("synced", onSynced);
|
|
765
|
-
reject(new Error(`Sync timeout after ${this.opts.syncTimeout}ms`));
|
|
766
|
-
}, this.opts.syncTimeout);
|
|
767
|
-
|
|
768
|
-
function onSynced(state: boolean | { state: boolean }) {
|
|
769
|
-
// Hocuspocus passes `{ state }` or a boolean directly
|
|
770
|
-
const synced =
|
|
771
|
-
typeof state === "boolean" ? state : (state as any)?.state ?? state;
|
|
772
|
-
if (synced) {
|
|
773
|
-
clearTimeout(timer);
|
|
774
|
-
provider.off("synced", onSynced);
|
|
775
|
-
resolve();
|
|
776
|
-
}
|
|
777
|
-
}
|
|
778
|
-
|
|
779
|
-
provider.on("synced", onSynced);
|
|
780
|
-
});
|
|
781
|
-
}
|
|
782
|
-
|
|
783
|
-
/**
|
|
784
|
-
* Pre-cache all cover images referenced in the root tree map.
|
|
785
|
-
*/
|
|
786
|
-
private async _prefetchCovers(entries: Array<[string, any]>): Promise<void> {
|
|
787
|
-
if (!this.fileBlobStore) return;
|
|
788
|
-
for (const [docId, v] of entries) {
|
|
789
|
-
const coverUploadId = v?.meta?.coverUploadId;
|
|
790
|
-
if (coverUploadId) {
|
|
791
|
-
this.fileBlobStore.getBlobUrl(docId, coverUploadId).catch(() => null);
|
|
792
|
-
}
|
|
793
|
-
}
|
|
794
|
-
}
|
|
795
|
-
|
|
796
|
-
/**
|
|
797
|
-
* Pre-cache file blobs referenced in a synced Y.Doc.
|
|
798
|
-
* Walks:
|
|
799
|
-
* - ydoc.getXmlFragment('default') for `fileBlock` nodes (TipTap)
|
|
800
|
-
* - ydoc.getMap('doc-tree') for meta.coverUploadId entries
|
|
801
|
-
*/
|
|
802
|
-
private async _prefetchDocFiles(
|
|
803
|
-
docId: string,
|
|
804
|
-
ydoc: Y.Doc,
|
|
805
|
-
): Promise<void> {
|
|
806
|
-
if (!this.fileBlobStore) return;
|
|
807
|
-
|
|
808
|
-
const refs = this._extractFileRefs(ydoc);
|
|
809
|
-
for (const { refDocId, uploadId } of refs) {
|
|
810
|
-
this.fileBlobStore
|
|
811
|
-
.getBlobUrl(refDocId ?? docId, uploadId)
|
|
812
|
-
.catch(() => null);
|
|
813
|
-
}
|
|
814
|
-
}
|
|
815
|
-
|
|
816
|
-
private _extractFileRefs(
|
|
817
|
-
ydoc: Y.Doc,
|
|
818
|
-
): Array<{ refDocId: string | null; uploadId: string }> {
|
|
819
|
-
const refs: Array<{ refDocId: string | null; uploadId: string }> = [];
|
|
820
|
-
|
|
821
|
-
// Walk XML fragment for fileBlock nodes
|
|
822
|
-
try {
|
|
823
|
-
const fragment = ydoc.getXmlFragment("default");
|
|
824
|
-
this._walkXml(fragment, refs);
|
|
825
|
-
} catch {}
|
|
826
|
-
|
|
827
|
-
// Walk doc-tree meta for cover upload IDs
|
|
828
|
-
try {
|
|
829
|
-
const treeMap = ydoc.getMap("doc-tree") as Y.Map<any>;
|
|
830
|
-
for (const [id, v] of treeMap.entries()) {
|
|
831
|
-
const coverUploadId = v?.meta?.coverUploadId;
|
|
832
|
-
if (coverUploadId) {
|
|
833
|
-
refs.push({ refDocId: id, uploadId: coverUploadId });
|
|
834
|
-
}
|
|
835
|
-
}
|
|
836
|
-
} catch {}
|
|
837
|
-
|
|
838
|
-
return refs;
|
|
839
|
-
}
|
|
840
|
-
|
|
841
|
-
private _walkXml(
|
|
842
|
-
node: Y.XmlFragment | Y.XmlElement,
|
|
843
|
-
refs: Array<{ refDocId: string | null; uploadId: string }>,
|
|
844
|
-
): void {
|
|
845
|
-
for (const child of node.toArray()) {
|
|
846
|
-
if (child instanceof Y.XmlElement) {
|
|
847
|
-
if (child.nodeName === "fileBlock") {
|
|
848
|
-
const uploadId = child.getAttribute("uploadId");
|
|
849
|
-
const refDocId = child.getAttribute("docId") ?? null;
|
|
850
|
-
if (uploadId) refs.push({ refDocId, uploadId });
|
|
851
|
-
}
|
|
852
|
-
this._walkXml(child, refs);
|
|
853
|
-
}
|
|
854
|
-
}
|
|
855
|
-
}
|
|
856
|
-
}
|