@abraca/dabra 2.90.0 → 2.91.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
package/src/FileBlobStore.ts
DELETED
|
@@ -1,569 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* IndexedDB-backed file blob cache with an offline-tolerant upload queue.
|
|
3
|
-
*
|
|
4
|
-
* Responsibilities:
|
|
5
|
-
* - Cache downloaded file blobs locally so they can be served offline via
|
|
6
|
-
* object URLs (URL.createObjectURL).
|
|
7
|
-
* - Queue file uploads when the network is unavailable. The queue persists
|
|
8
|
-
* across page reloads (IndexedDB-backed).
|
|
9
|
-
* - Auto-flush the upload queue when the browser reports it is back online,
|
|
10
|
-
* and expose flushQueue() for manual flushing.
|
|
11
|
-
*
|
|
12
|
-
* Events:
|
|
13
|
-
* - "upload:queued" — entry added to queue
|
|
14
|
-
* - "upload:started" — upload attempt started
|
|
15
|
-
* - "upload:done" — upload succeeded
|
|
16
|
-
* - "upload:error" — upload attempt failed
|
|
17
|
-
*
|
|
18
|
-
* Falls back to a silent no-op when IndexedDB is unavailable (SSR / Node.js).
|
|
19
|
-
*/
|
|
20
|
-
|
|
21
|
-
import type { UploadQueueEntry, ThumbnailOptions } from "./types.ts";
|
|
22
|
-
import type { AbracadabraClient } from "./AbracadabraClient.ts";
|
|
23
|
-
import EventEmitter from "./EventEmitter.ts";
|
|
24
|
-
|
|
25
|
-
const DB_VERSION = 1;
|
|
26
|
-
|
|
27
|
-
function idbAvailable(): boolean {
|
|
28
|
-
return typeof globalThis !== "undefined" && "indexedDB" in globalThis;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function openDb(origin: string): Promise<IDBDatabase> {
|
|
32
|
-
return new Promise((resolve, reject) => {
|
|
33
|
-
const req = globalThis.indexedDB.open(`abracadabra:files:${origin}`, DB_VERSION);
|
|
34
|
-
|
|
35
|
-
req.onupgradeneeded = (event) => {
|
|
36
|
-
const db = (event.target as IDBOpenDBRequest).result;
|
|
37
|
-
if (!db.objectStoreNames.contains("blobs")) {
|
|
38
|
-
db.createObjectStore("blobs");
|
|
39
|
-
}
|
|
40
|
-
if (!db.objectStoreNames.contains("upload_queue")) {
|
|
41
|
-
db.createObjectStore("upload_queue", { keyPath: "id" });
|
|
42
|
-
}
|
|
43
|
-
};
|
|
44
|
-
|
|
45
|
-
req.onsuccess = () => resolve(req.result);
|
|
46
|
-
req.onerror = () => reject(req.error);
|
|
47
|
-
});
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
function txPromise<T>(store: IDBObjectStore, request: IDBRequest<T>): Promise<T> {
|
|
51
|
-
return new Promise((resolve, reject) => {
|
|
52
|
-
request.onsuccess = () => resolve(request.result);
|
|
53
|
-
request.onerror = () => reject(request.error);
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
interface BlobCacheEntry {
|
|
58
|
-
blob: Blob;
|
|
59
|
-
mime_type: string;
|
|
60
|
-
filename: string;
|
|
61
|
-
cachedAt: number;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
export class FileBlobStore extends EventEmitter {
|
|
65
|
-
private readonly origin: string;
|
|
66
|
-
private readonly client: AbracadabraClient | null;
|
|
67
|
-
private dbPromise: Promise<IDBDatabase | null> | null = null;
|
|
68
|
-
private db: IDBDatabase | null = null;
|
|
69
|
-
|
|
70
|
-
/** Tracks active object URLs so we can revoke them on destroy. */
|
|
71
|
-
private readonly objectUrls = new Map<string, string>();
|
|
72
|
-
|
|
73
|
-
/** Keys that returned 404 from the server — avoids repeated requests. TTL: 5 min. */
|
|
74
|
-
private readonly _notFound = new Map<string, number>();
|
|
75
|
-
private static readonly NOT_FOUND_TTL = 5 * 60 * 1000;
|
|
76
|
-
|
|
77
|
-
/** Prevents concurrent flush runs. */
|
|
78
|
-
private _flushPromise: Promise<void> | null = null;
|
|
79
|
-
|
|
80
|
-
private readonly _onlineHandler: () => void;
|
|
81
|
-
|
|
82
|
-
constructor(serverOrigin: string, client?: AbracadabraClient | null) {
|
|
83
|
-
super();
|
|
84
|
-
this.origin = serverOrigin;
|
|
85
|
-
this.client = client ?? null;
|
|
86
|
-
|
|
87
|
-
this._onlineHandler = () => { this.flushQueue().catch(() => null); };
|
|
88
|
-
if (typeof window !== "undefined") {
|
|
89
|
-
window.addEventListener("online", this._onlineHandler);
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
private getDb(): Promise<IDBDatabase | null> {
|
|
94
|
-
if (!idbAvailable()) return Promise.resolve(null);
|
|
95
|
-
if (!this.dbPromise) {
|
|
96
|
-
this.dbPromise = openDb(this.origin)
|
|
97
|
-
.catch(() => null)
|
|
98
|
-
.then((db) => {
|
|
99
|
-
this.db = db;
|
|
100
|
-
if (db) {
|
|
101
|
-
// A browser-initiated close (storage pressure, tab
|
|
102
|
-
// eviction) leaves the cached handle unusable. Reset so
|
|
103
|
-
// the next getDb() reopens instead of handing back a
|
|
104
|
-
// connection that throws "database connection is
|
|
105
|
-
// closing" on transaction().
|
|
106
|
-
db.onclose = () => {
|
|
107
|
-
if (this.db === db) this.db = null;
|
|
108
|
-
this.dbPromise = null;
|
|
109
|
-
};
|
|
110
|
-
}
|
|
111
|
-
return db;
|
|
112
|
-
});
|
|
113
|
-
}
|
|
114
|
-
return this.dbPromise;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
private blobKey(docId: string, uploadId: string): string {
|
|
118
|
-
return `${docId}/${uploadId}`;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
/**
|
|
122
|
-
* Cache key for a thumbnail. Lives in the SAME IDB `blobs` store as
|
|
123
|
-
* originals (no schema bump — the frozen cross-SDK IDB contract stays
|
|
124
|
-
* intact) under a distinct `thumb:` namespace. The spec suffix is
|
|
125
|
-
* deterministic so identical options collapse to one entry.
|
|
126
|
-
*/
|
|
127
|
-
private thumbKey(docId: string, uploadId: string, opts: ThumbnailOptions): string {
|
|
128
|
-
const spec = [
|
|
129
|
-
opts.w != null ? `w${opts.w}` : "",
|
|
130
|
-
opts.h != null ? `h${opts.h}` : "",
|
|
131
|
-
opts.fit ? `f${opts.fit}` : "",
|
|
132
|
-
opts.format ? `m${opts.format}` : "",
|
|
133
|
-
opts.q != null ? `q${opts.q}` : "",
|
|
134
|
-
]
|
|
135
|
-
.filter(Boolean)
|
|
136
|
-
.join("-");
|
|
137
|
-
return `thumb:${docId}/${uploadId}/${spec}`;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
// ── Blob cache ────────────────────────────────────────────────────────────
|
|
141
|
-
|
|
142
|
-
/**
|
|
143
|
-
* Return a local object URL for a file.
|
|
144
|
-
* On first call the blob is downloaded from the server and cached in IDB.
|
|
145
|
-
* Returns null when offline and the blob is not yet cached, or when
|
|
146
|
-
* URL.createObjectURL is unavailable (e.g. Node.js / SSR).
|
|
147
|
-
*/
|
|
148
|
-
async getBlobUrl(docId: string, uploadId: string): Promise<string | null> {
|
|
149
|
-
return this._objectUrlForKey(
|
|
150
|
-
this.blobKey(docId, uploadId),
|
|
151
|
-
uploadId,
|
|
152
|
-
this.client ? () => this.client!.getUpload(docId, uploadId) : null,
|
|
153
|
-
);
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* Return a **server** URL that streams an upload with HTTP Range support —
|
|
158
|
-
* for `<video src>` / `<audio src>`, where `getBlobUrl` would first pull
|
|
159
|
-
* the entire file into IndexedDB and seeking would stall until it landed.
|
|
160
|
-
*
|
|
161
|
-
* Requires a client and the network (the URL points at the server, and
|
|
162
|
-
* minting its token is a request). Returns `null` when either is missing,
|
|
163
|
-
* when the server predates the `stream-token` endpoint, or when we're
|
|
164
|
-
* already known to be offline — callers fall back to `getBlobUrl` for the
|
|
165
|
-
* cached copy.
|
|
166
|
-
*/
|
|
167
|
-
async getStreamUrl(docId: string, uploadId: string): Promise<string | null> {
|
|
168
|
-
if (!this.client) return null;
|
|
169
|
-
if (typeof navigator !== "undefined" && navigator.onLine === false) {
|
|
170
|
-
return null;
|
|
171
|
-
}
|
|
172
|
-
try {
|
|
173
|
-
return await this.client.getStreamUrl(docId, uploadId);
|
|
174
|
-
} catch {
|
|
175
|
-
return null;
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
/**
|
|
180
|
-
* Return a local object URL for a **thumbnail** of an image upload.
|
|
181
|
-
* On first call the server renders + caches it and this stores the bytes
|
|
182
|
-
* in IDB (same offline-serving model as `getBlobUrl`). Returns null when
|
|
183
|
-
* offline + uncached, on non-image sources (server 415 → treated like a
|
|
184
|
-
* miss), or outside the browser. Options must match the server's
|
|
185
|
-
* `allowed_sizes` / `allowed_formats` or the fetch 422s (→ null).
|
|
186
|
-
*/
|
|
187
|
-
async getThumbUrl(
|
|
188
|
-
docId: string,
|
|
189
|
-
uploadId: string,
|
|
190
|
-
opts: ThumbnailOptions = {},
|
|
191
|
-
): Promise<string | null> {
|
|
192
|
-
return this._objectUrlForKey(
|
|
193
|
-
this.thumbKey(docId, uploadId, opts),
|
|
194
|
-
uploadId,
|
|
195
|
-
this.client ? () => this.client!.getThumbnail(docId, uploadId, opts) : null,
|
|
196
|
-
);
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
/**
|
|
200
|
-
* Shared read-through: in-memory object URL → IDB `blobs` cache (with a
|
|
201
|
-
* one-shot reopen on `InvalidStateError`) → `download()` (when a client is
|
|
202
|
-
* available), caching the result. `download === null` means "no network
|
|
203
|
-
* source" (offline / no client) → cache-only. 404 is negative-cached.
|
|
204
|
-
*/
|
|
205
|
-
private async _objectUrlForKey(
|
|
206
|
-
key: string,
|
|
207
|
-
filename: string,
|
|
208
|
-
download: (() => Promise<Blob>) | null,
|
|
209
|
-
): Promise<string | null> {
|
|
210
|
-
// Object URLs are only meaningful in browser environments.
|
|
211
|
-
if (typeof window === "undefined") return null;
|
|
212
|
-
|
|
213
|
-
// Reuse existing in-memory object URL if available
|
|
214
|
-
const existing = this.objectUrls.get(key);
|
|
215
|
-
if (existing) return existing;
|
|
216
|
-
|
|
217
|
-
let db = await this.getDb();
|
|
218
|
-
if (db) {
|
|
219
|
-
let entry: BlobCacheEntry | undefined;
|
|
220
|
-
try {
|
|
221
|
-
const tx = db.transaction("blobs", "readonly");
|
|
222
|
-
entry = await txPromise<BlobCacheEntry | undefined>(
|
|
223
|
-
tx.objectStore("blobs"),
|
|
224
|
-
tx.objectStore("blobs").get(key),
|
|
225
|
-
);
|
|
226
|
-
} catch (err: unknown) {
|
|
227
|
-
// The cached connection was closed underneath us (space
|
|
228
|
-
// teardown / destroy() racing this async read). Reopen once
|
|
229
|
-
// and retry — the blob is still persisted in IDB.
|
|
230
|
-
if ((err as { name?: string })?.name === "InvalidStateError") {
|
|
231
|
-
if (this.db === db) this.db = null;
|
|
232
|
-
this.dbPromise = null;
|
|
233
|
-
db = await this.getDb();
|
|
234
|
-
if (db) {
|
|
235
|
-
const tx = db.transaction("blobs", "readonly");
|
|
236
|
-
entry = await txPromise<BlobCacheEntry | undefined>(
|
|
237
|
-
tx.objectStore("blobs"),
|
|
238
|
-
tx.objectStore("blobs").get(key),
|
|
239
|
-
);
|
|
240
|
-
}
|
|
241
|
-
} else {
|
|
242
|
-
throw err;
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
if (entry) {
|
|
246
|
-
const url = URL.createObjectURL(entry.blob);
|
|
247
|
-
this.objectUrls.set(key, url);
|
|
248
|
-
return url;
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
// Not cached — try downloading from server (requires a client)
|
|
253
|
-
if (!download) return null;
|
|
254
|
-
|
|
255
|
-
// Skip if we recently got a 404 for this key
|
|
256
|
-
const nfTime = this._notFound.get(key);
|
|
257
|
-
if (nfTime && Date.now() - nfTime < FileBlobStore.NOT_FOUND_TTL) {
|
|
258
|
-
return null;
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
let blob: Blob;
|
|
262
|
-
try {
|
|
263
|
-
blob = await download();
|
|
264
|
-
} catch (err: unknown) {
|
|
265
|
-
const status = (err as any)?.status;
|
|
266
|
-
if (status === 404) {
|
|
267
|
-
this._notFound.set(key, Date.now());
|
|
268
|
-
}
|
|
269
|
-
return null;
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
// Cache the blob
|
|
273
|
-
if (db) {
|
|
274
|
-
const entry: BlobCacheEntry = {
|
|
275
|
-
blob,
|
|
276
|
-
mime_type: blob.type,
|
|
277
|
-
filename,
|
|
278
|
-
cachedAt: Date.now(),
|
|
279
|
-
};
|
|
280
|
-
const tx = db.transaction("blobs", "readwrite");
|
|
281
|
-
tx.objectStore("blobs").put(entry, key);
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
const url = URL.createObjectURL(blob);
|
|
285
|
-
this.objectUrls.set(key, url);
|
|
286
|
-
return url;
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
/**
|
|
290
|
-
* Store a blob directly into the cache under the given (docId, uploadId) key
|
|
291
|
-
* and return its object URL. Use this to pre-populate the cache for files
|
|
292
|
-
* that haven't been uploaded to the server yet (e.g. offline upload queue).
|
|
293
|
-
*/
|
|
294
|
-
async putBlob(
|
|
295
|
-
docId: string,
|
|
296
|
-
uploadId: string,
|
|
297
|
-
blob: Blob,
|
|
298
|
-
filename: string,
|
|
299
|
-
): Promise<string> {
|
|
300
|
-
if (typeof window === "undefined") return URL.createObjectURL(blob);
|
|
301
|
-
|
|
302
|
-
const key = this.blobKey(docId, uploadId);
|
|
303
|
-
this._notFound.delete(key);
|
|
304
|
-
|
|
305
|
-
// Return existing URL if already cached in-memory
|
|
306
|
-
const existing = this.objectUrls.get(key);
|
|
307
|
-
if (existing) return existing;
|
|
308
|
-
|
|
309
|
-
const db = await this.getDb();
|
|
310
|
-
if (db) {
|
|
311
|
-
const entry: BlobCacheEntry = {
|
|
312
|
-
blob,
|
|
313
|
-
mime_type: blob.type || "application/octet-stream",
|
|
314
|
-
filename,
|
|
315
|
-
cachedAt: Date.now(),
|
|
316
|
-
};
|
|
317
|
-
const tx = db.transaction("blobs", "readwrite");
|
|
318
|
-
tx.objectStore("blobs").put(entry, key);
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
const url = URL.createObjectURL(blob);
|
|
322
|
-
this.objectUrls.set(key, url);
|
|
323
|
-
return url;
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
/**
|
|
327
|
-
* Retrieve the raw Blob from IDB for a previously cached upload.
|
|
328
|
-
* Returns null if the blob has been evicted or was never stored.
|
|
329
|
-
* Use this to re-upload a file after a page reload.
|
|
330
|
-
*/
|
|
331
|
-
async getBlob(docId: string, uploadId: string): Promise<Blob | null> {
|
|
332
|
-
const db = await this.getDb();
|
|
333
|
-
if (!db) return null;
|
|
334
|
-
|
|
335
|
-
const key = this.blobKey(docId, uploadId);
|
|
336
|
-
const tx = db.transaction("blobs", "readonly");
|
|
337
|
-
const entry = await txPromise<BlobCacheEntry | undefined>(
|
|
338
|
-
tx.objectStore("blobs"),
|
|
339
|
-
tx.objectStore("blobs").get(key),
|
|
340
|
-
);
|
|
341
|
-
return entry?.blob ?? null;
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
/** Return metadata for all cached blobs (for storage stats). */
|
|
345
|
-
async getAllCachedEntries(): Promise<Array<{
|
|
346
|
-
docId: string; uploadId: string; filename: string;
|
|
347
|
-
mimeType: string; size: number; cachedAt: number;
|
|
348
|
-
}>> {
|
|
349
|
-
const db = await this.getDb();
|
|
350
|
-
if (!db) return [];
|
|
351
|
-
return new Promise((resolve, reject) => {
|
|
352
|
-
const tx = db.transaction("blobs", "readonly");
|
|
353
|
-
const store = tx.objectStore("blobs");
|
|
354
|
-
const keysReq = store.getAllKeys();
|
|
355
|
-
const valuesReq = store.getAll();
|
|
356
|
-
tx.oncomplete = () => {
|
|
357
|
-
const keys = keysReq.result as string[];
|
|
358
|
-
const values = valuesReq.result as BlobCacheEntry[];
|
|
359
|
-
resolve(keys.map((key, i) => {
|
|
360
|
-
const slashIdx = key.indexOf("/");
|
|
361
|
-
const docId = key.slice(0, slashIdx);
|
|
362
|
-
const uploadId = key.slice(slashIdx + 1);
|
|
363
|
-
const e = values[i]!;
|
|
364
|
-
return { docId, uploadId, filename: e.filename, mimeType: e.mime_type, size: e.blob.size, cachedAt: e.cachedAt };
|
|
365
|
-
}));
|
|
366
|
-
};
|
|
367
|
-
tx.onerror = () => reject(tx.error);
|
|
368
|
-
});
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
/** Revoke all object URLs and clear the entire blob cache from IDB. */
|
|
372
|
-
async clearAllBlobs(): Promise<void> {
|
|
373
|
-
for (const url of this.objectUrls.values()) URL.revokeObjectURL(url);
|
|
374
|
-
this.objectUrls.clear();
|
|
375
|
-
const db = await this.getDb();
|
|
376
|
-
if (!db) return;
|
|
377
|
-
return new Promise((resolve, reject) => {
|
|
378
|
-
const tx = db.transaction("blobs", "readwrite");
|
|
379
|
-
const req = tx.objectStore("blobs").clear();
|
|
380
|
-
req.onsuccess = () => resolve();
|
|
381
|
-
req.onerror = () => reject(req.error);
|
|
382
|
-
});
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
/**
|
|
386
|
-
* Revoke the in-memory object URL without touching the IDB cache.
|
|
387
|
-
* The next call to getBlobUrl() will re-create a fresh URL from IDB.
|
|
388
|
-
* Use this when an <img> @error fires — the blob data is fine, only
|
|
389
|
-
* the object URL reference is stale.
|
|
390
|
-
*/
|
|
391
|
-
invalidateUrl(docId: string, uploadId: string): void {
|
|
392
|
-
const key = this.blobKey(docId, uploadId);
|
|
393
|
-
const url = this.objectUrls.get(key);
|
|
394
|
-
if (url) {
|
|
395
|
-
URL.revokeObjectURL(url);
|
|
396
|
-
this.objectUrls.delete(key);
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
/**
|
|
401
|
-
* Thumbnail counterpart of {@link invalidateUrl}: revoke the in-memory
|
|
402
|
-
* object URL for a specific thumbnail spec without touching its IDB cache.
|
|
403
|
-
*/
|
|
404
|
-
invalidateThumbUrl(docId: string, uploadId: string, opts: ThumbnailOptions = {}): void {
|
|
405
|
-
const key = this.thumbKey(docId, uploadId, opts);
|
|
406
|
-
const url = this.objectUrls.get(key);
|
|
407
|
-
if (url) {
|
|
408
|
-
URL.revokeObjectURL(url);
|
|
409
|
-
this.objectUrls.delete(key);
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
/**
|
|
414
|
-
* Clear the 404 negative-cache entry for (docId, uploadId) so the next
|
|
415
|
-
* getBlobUrl() re-fetches from the server instead of short-circuiting.
|
|
416
|
-
* Use on explicit user retry or after reconnect, when the file may have
|
|
417
|
-
* become available since the last 404.
|
|
418
|
-
*/
|
|
419
|
-
clearNotFound(docId: string, uploadId: string): void {
|
|
420
|
-
this._notFound.delete(this.blobKey(docId, uploadId));
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
/** Revoke the object URL and remove the blob from cache. */
|
|
424
|
-
async evictBlob(docId: string, uploadId: string): Promise<void> {
|
|
425
|
-
const key = this.blobKey(docId, uploadId);
|
|
426
|
-
|
|
427
|
-
const url = this.objectUrls.get(key);
|
|
428
|
-
if (url) {
|
|
429
|
-
URL.revokeObjectURL(url);
|
|
430
|
-
this.objectUrls.delete(key);
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
const db = await this.getDb();
|
|
434
|
-
if (!db) return;
|
|
435
|
-
const tx = db.transaction("blobs", "readwrite");
|
|
436
|
-
await txPromise(tx.objectStore("blobs"), tx.objectStore("blobs").delete(key));
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
// ── Upload queue ──────────────────────────────────────────────────────────
|
|
440
|
-
|
|
441
|
-
/**
|
|
442
|
-
* Queue a file for upload. Works offline — the entry is persisted to IDB
|
|
443
|
-
* and flushed the next time the queue is flushed.
|
|
444
|
-
* Returns the generated queue entry id.
|
|
445
|
-
*/
|
|
446
|
-
async queueUpload(
|
|
447
|
-
docId: string,
|
|
448
|
-
file: File | Blob,
|
|
449
|
-
filename?: string,
|
|
450
|
-
): Promise<string> {
|
|
451
|
-
const id = crypto.randomUUID();
|
|
452
|
-
const resolvedFilename =
|
|
453
|
-
file instanceof File ? file.name : (filename ?? "file");
|
|
454
|
-
|
|
455
|
-
const entry: UploadQueueEntry = {
|
|
456
|
-
id,
|
|
457
|
-
docId,
|
|
458
|
-
file,
|
|
459
|
-
filename: resolvedFilename,
|
|
460
|
-
status: "pending",
|
|
461
|
-
createdAt: Date.now(),
|
|
462
|
-
};
|
|
463
|
-
|
|
464
|
-
const db = await this.getDb();
|
|
465
|
-
if (db) {
|
|
466
|
-
const tx = db.transaction("upload_queue", "readwrite");
|
|
467
|
-
await txPromise(
|
|
468
|
-
tx.objectStore("upload_queue"),
|
|
469
|
-
tx.objectStore("upload_queue").put(entry),
|
|
470
|
-
);
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
this.emit("upload:queued", entry);
|
|
474
|
-
return id;
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
/** Return all upload queue entries. */
|
|
478
|
-
async getQueue(): Promise<UploadQueueEntry[]> {
|
|
479
|
-
const db = await this.getDb();
|
|
480
|
-
if (!db) return [];
|
|
481
|
-
return new Promise((resolve, reject) => {
|
|
482
|
-
const tx = db.transaction("upload_queue", "readonly");
|
|
483
|
-
const req = tx.objectStore("upload_queue").getAll();
|
|
484
|
-
req.onsuccess = () => resolve(req.result as UploadQueueEntry[]);
|
|
485
|
-
req.onerror = () => reject(req.error);
|
|
486
|
-
});
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
/**
|
|
490
|
-
* Upload all pending queue entries via AbracadabraClient.
|
|
491
|
-
* Safe to call repeatedly — a concurrent call is a no-op.
|
|
492
|
-
* Entries that fail are marked with status "error" and left in the queue.
|
|
493
|
-
*/
|
|
494
|
-
async flushQueue(): Promise<void> {
|
|
495
|
-
if (this._flushPromise || !this.client) return;
|
|
496
|
-
this._flushPromise = this._doFlush();
|
|
497
|
-
try {
|
|
498
|
-
await this._flushPromise;
|
|
499
|
-
} finally {
|
|
500
|
-
this._flushPromise = null;
|
|
501
|
-
}
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
private async _doFlush(): Promise<void> {
|
|
505
|
-
if (!this.client) return;
|
|
506
|
-
const all = await this.getQueue();
|
|
507
|
-
const pending = all.filter((e) => e.status === "pending");
|
|
508
|
-
|
|
509
|
-
for (const entry of pending) {
|
|
510
|
-
await this._updateQueueEntry(entry.id, { status: "uploading" });
|
|
511
|
-
this.emit("upload:started", { ...entry, status: "uploading" });
|
|
512
|
-
|
|
513
|
-
try {
|
|
514
|
-
await this.client.upload(entry.docId, entry.file, entry.filename);
|
|
515
|
-
await this._updateQueueEntry(entry.id, { status: "done" });
|
|
516
|
-
this.emit("upload:done", { ...entry, status: "done" });
|
|
517
|
-
} catch (err) {
|
|
518
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
519
|
-
await this._updateQueueEntry(entry.id, { status: "error", error: message });
|
|
520
|
-
this.emit("upload:error", { ...entry, status: "error", error: message });
|
|
521
|
-
}
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
private async _updateQueueEntry(
|
|
526
|
-
id: string,
|
|
527
|
-
patch: Partial<UploadQueueEntry>,
|
|
528
|
-
): Promise<void> {
|
|
529
|
-
const db = await this.getDb();
|
|
530
|
-
if (!db) return;
|
|
531
|
-
|
|
532
|
-
return new Promise<void>((resolve, reject) => {
|
|
533
|
-
const tx = db.transaction("upload_queue", "readwrite");
|
|
534
|
-
const store = tx.objectStore("upload_queue");
|
|
535
|
-
const req = store.get(id);
|
|
536
|
-
req.onsuccess = () => {
|
|
537
|
-
if (!req.result) { resolve(); return; }
|
|
538
|
-
const updated = { ...req.result, ...patch };
|
|
539
|
-
store.put(updated);
|
|
540
|
-
tx.oncomplete = () => resolve();
|
|
541
|
-
tx.onerror = () => reject(tx.error);
|
|
542
|
-
};
|
|
543
|
-
req.onerror = () => reject(req.error);
|
|
544
|
-
});
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
// ── Lifecycle ─────────────────────────────────────────────────────────────
|
|
548
|
-
|
|
549
|
-
destroy(): void {
|
|
550
|
-
if (typeof window !== "undefined") {
|
|
551
|
-
window.removeEventListener("online", this._onlineHandler);
|
|
552
|
-
}
|
|
553
|
-
|
|
554
|
-
// Revoke all tracked object URLs
|
|
555
|
-
for (const url of this.objectUrls.values()) {
|
|
556
|
-
URL.revokeObjectURL(url);
|
|
557
|
-
}
|
|
558
|
-
this.objectUrls.clear();
|
|
559
|
-
|
|
560
|
-
this.db?.close();
|
|
561
|
-
this.db = null;
|
|
562
|
-
// Drop the cached promise too — otherwise a still-mounted FileNodeView
|
|
563
|
-
// that calls getBlobUrl() after teardown gets the just-closed handle
|
|
564
|
-
// and throws InvalidStateError. Nulling it lets getDb() reopen a fresh
|
|
565
|
-
// connection to read the (still-persisted) cached blob.
|
|
566
|
-
this.dbPromise = null;
|
|
567
|
-
this.removeAllListeners();
|
|
568
|
-
}
|
|
569
|
-
}
|