@powersync/web 2.5.0 → 2.7.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/dist/index.react_native_web.js +741 -155
- package/dist/index.react_native_web.js.map +1 -1
- package/dist/worker/AccessHandlePoolVFS-Do8lc5Ck.js +2 -0
- package/dist/worker/AccessHandlePoolVFS-Do8lc5Ck.js.map +1 -0
- package/dist/worker/FacadeVFS-d1ZDvud7.js.map +1 -1
- package/dist/worker/IDBBatchAtomicVFS-CDb4d4wN.js +2 -0
- package/dist/worker/IDBBatchAtomicVFS-CDb4d4wN.js.map +1 -0
- package/dist/worker/MemoryVFS-DVJL5F8j.js.map +1 -1
- package/dist/worker/OPFSCoopSyncVFS-Dujy2ZwX.js +2 -0
- package/dist/worker/OPFSCoopSyncVFS-Dujy2ZwX.js.map +1 -0
- package/dist/worker/OPFSWriteAheadVFS-V9yBrLWl.js +2 -0
- package/dist/worker/OPFSWriteAheadVFS-V9yBrLWl.js.map +1 -0
- package/dist/worker/SimpleOpfsFileSystem-6GYD1Xui.js +2 -0
- package/dist/worker/SimpleOpfsFileSystem-6GYD1Xui.js.map +1 -0
- package/dist/worker/assets/mc-wa-sqlite-Cq3AePIW.wasm +0 -0
- package/dist/worker/assets/{mc-wa-sqlite-async-DdlQmAUV.wasm → mc-wa-sqlite-async-aRcIGeKj.wasm} +0 -0
- package/dist/worker/assets/wa-sqlite-CePoIZt_.wasm +0 -0
- package/dist/worker/assets/wa-sqlite-async-B3FiUnt1.wasm +0 -0
- package/dist/worker/{mc-wa-sqlite-PubB6u8c.js → mc-wa-sqlite-DRR2R_uj.js} +2 -2
- package/dist/worker/mc-wa-sqlite-DRR2R_uj.js.map +1 -0
- package/dist/worker/{mc-wa-sqlite-async-DJG_ANKO.js → mc-wa-sqlite-async-C40l6kIz.js} +2 -2
- package/dist/worker/mc-wa-sqlite-async-C40l6kIz.js.map +1 -0
- package/dist/worker/{wa-sqlite-D1_4mGs8.js → wa-sqlite-_a9CU4MM.js} +2 -2
- package/dist/worker/wa-sqlite-_a9CU4MM.js.map +1 -0
- package/dist/worker/wa-sqlite-async-Da0d0GJg.js +2 -0
- package/dist/worker/wa-sqlite-async-Da0d0GJg.js.map +1 -0
- package/dist/worker/{websockets-Q8W_lerF.js → websockets-Dx9ExO-W.js} +2 -2
- package/dist/worker/{websockets-Q8W_lerF.js.map → websockets-Dx9ExO-W.js.map} +1 -1
- package/dist/worker/worker.js +1 -1
- package/dist/worker/worker.js.map +1 -1
- package/lib/db/NavigatorTriggerClaimManager.js +1 -1
- package/lib/db/NavigatorTriggerClaimManager.js.map +1 -1
- package/lib/db/PowerSyncDatabase.d.ts +4 -3
- package/lib/db/PowerSyncDatabase.js +4 -1
- package/lib/db/PowerSyncDatabase.js.map +1 -1
- package/lib/db/adapters/options.d.ts +55 -2
- package/lib/db/adapters/options.js.map +1 -1
- package/lib/db/adapters/resolveAndValidateOptions.js +6 -1
- package/lib/db/adapters/resolveAndValidateOptions.js.map +1 -1
- package/lib/db/adapters/wa-sqlite/ConcurrentConnection.d.ts +56 -7
- package/lib/db/adapters/wa-sqlite/ConcurrentConnection.js +130 -25
- package/lib/db/adapters/wa-sqlite/ConcurrentConnection.js.map +1 -1
- package/lib/db/adapters/wa-sqlite/DatabaseClient.d.ts +13 -0
- package/lib/db/adapters/wa-sqlite/DatabaseClient.js.map +1 -1
- package/lib/db/adapters/wa-sqlite/RawSqliteConnection.d.ts +7 -1
- package/lib/db/adapters/wa-sqlite/RawSqliteConnection.js +19 -8
- package/lib/db/adapters/wa-sqlite/RawSqliteConnection.js.map +1 -1
- package/lib/db/adapters/wa-sqlite/SimpleOpfsFileSystem.d.ts +30 -0
- package/lib/db/adapters/wa-sqlite/SimpleOpfsFileSystem.js +210 -0
- package/lib/db/adapters/wa-sqlite/SimpleOpfsFileSystem.js.map +1 -0
- package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +1 -0
- package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +178 -73
- package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.js.map +1 -1
- package/lib/db/adapters/wa-sqlite/vfs.d.ts +52 -3
- package/lib/db/adapters/wa-sqlite/vfs.js +84 -4
- package/lib/db/adapters/wa-sqlite/vfs.js.map +1 -1
- package/lib/db/sync/SharedWebStreamingSyncImplementation.d.ts +1 -0
- package/lib/db/sync/SharedWebStreamingSyncImplementation.js +29 -12
- package/lib/db/sync/SharedWebStreamingSyncImplementation.js.map +1 -1
- package/lib/db/sync/WebRemote.d.ts +2 -3
- package/lib/db/sync/WebRemote.js +0 -2
- package/lib/db/sync/WebRemote.js.map +1 -1
- package/lib/db/sync/WebStreamingSyncImplementation.js +1 -1
- package/lib/db/sync/WebStreamingSyncImplementation.js.map +1 -1
- package/lib/shared/{tab_close_signal.d.ts → locks.d.ts} +13 -0
- package/lib/shared/locks.js +56 -0
- package/lib/shared/locks.js.map +1 -0
- package/lib/worker/db/MultiDatabaseServer.js +37 -12
- package/lib/worker/db/MultiDatabaseServer.js.map +1 -1
- package/lib/worker/sync/SharedSyncImplementation.d.ts +9 -2
- package/lib/worker/sync/SharedSyncImplementation.js +67 -38
- package/lib/worker/sync/SharedSyncImplementation.js.map +1 -1
- package/lib/worker/sync/WorkerClient.d.ts +3 -3
- package/lib/worker/sync/WorkerClient.js +4 -4
- package/lib/worker/sync/WorkerClient.js.map +1 -1
- package/lib/worker/worker.js +67 -1
- package/lib/worker/worker.js.map +1 -1
- package/package.json +6 -6
- package/src/db/NavigatorTriggerClaimManager.ts +1 -1
- package/src/db/PowerSyncDatabase.ts +7 -4
- package/src/db/adapters/options.ts +59 -2
- package/src/db/adapters/resolveAndValidateOptions.ts +9 -1
- package/src/db/adapters/wa-sqlite/ConcurrentConnection.ts +148 -34
- package/src/db/adapters/wa-sqlite/DatabaseClient.ts +16 -0
- package/src/db/adapters/wa-sqlite/RawSqliteConnection.ts +28 -9
- package/src/db/adapters/wa-sqlite/SimpleOpfsFileSystem.ts +249 -0
- package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +236 -93
- package/src/db/adapters/wa-sqlite/vfs.ts +107 -6
- package/src/db/sync/SharedWebStreamingSyncImplementation.ts +35 -16
- package/src/db/sync/WebRemote.ts +2 -5
- package/src/db/sync/WebStreamingSyncImplementation.ts +1 -1
- package/src/shared/locks.ts +66 -0
- package/src/worker/db/MultiDatabaseServer.ts +46 -12
- package/src/worker/sync/SharedSyncImplementation.ts +90 -49
- package/src/worker/sync/WorkerClient.ts +5 -4
- package/src/worker/worker.ts +82 -3
- package/dist/worker/AccessHandlePoolVFS-B9CKqcQ3.js +0 -2
- package/dist/worker/AccessHandlePoolVFS-B9CKqcQ3.js.map +0 -1
- package/dist/worker/IDBBatchAtomicVFS-BfRzbRoV.js +0 -2
- package/dist/worker/IDBBatchAtomicVFS-BfRzbRoV.js.map +0 -1
- package/dist/worker/OPFSCoopSyncVFS-BxXAVpVQ.js +0 -2
- package/dist/worker/OPFSCoopSyncVFS-BxXAVpVQ.js.map +0 -1
- package/dist/worker/OPFSWriteAheadVFS-DuqXaOct.js +0 -2
- package/dist/worker/OPFSWriteAheadVFS-DuqXaOct.js.map +0 -1
- package/dist/worker/assets/mc-wa-sqlite-BHScYYZw.wasm +0 -0
- package/dist/worker/assets/wa-sqlite-CIxTmRHQ.wasm +0 -0
- package/dist/worker/assets/wa-sqlite-async-zc68fxQq.wasm +0 -0
- package/dist/worker/mc-wa-sqlite-PubB6u8c.js.map +0 -1
- package/dist/worker/mc-wa-sqlite-async-DJG_ANKO.js.map +0 -1
- package/dist/worker/wa-sqlite-D1_4mGs8.js.map +0 -1
- package/dist/worker/wa-sqlite-async-BxkwNY-2.js +0 -2
- package/dist/worker/wa-sqlite-async-BxkwNY-2.js.map +0 -1
- package/lib/shared/navigator.d.ts +0 -1
- package/lib/shared/navigator.js +0 -7
- package/lib/shared/navigator.js.map +0 -1
- package/lib/shared/tab_close_signal.js +0 -27
- package/lib/shared/tab_close_signal.js.map +0 -1
- package/src/shared/navigator.ts +0 -9
- package/src/shared/tab_close_signal.ts +0 -28
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { UnlockFn } from '@powersync/shared-internals';
|
|
2
|
+
|
|
3
|
+
export const getNavigatorLocks = (): LockManager => {
|
|
4
|
+
if ('locks' in navigator && navigator.locks) {
|
|
5
|
+
return navigator.locks;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
throw new Error(
|
|
9
|
+
'Navigator locks are not available in an insecure context. Use a secure context such as HTTPS or http://localhost.'
|
|
10
|
+
);
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Requests a random lock that will be released once the optional signal is aborted (or, if no signal is given, when the
|
|
15
|
+
* tab is closed).
|
|
16
|
+
*
|
|
17
|
+
* This allows sending the name of the lock to another context (e.g. a shared worker), which will also attempt to
|
|
18
|
+
* acquire it. Since the lock is returned when the tab is closed, this allows the shared worker to free resources
|
|
19
|
+
* assocatiated with this tab.
|
|
20
|
+
*
|
|
21
|
+
* We take hold of this lock as soon-as-possible in order to cater for potentially closed tabs.
|
|
22
|
+
*/
|
|
23
|
+
export async function generateTabCloseSignal(abort?: AbortSignal): Promise<string> {
|
|
24
|
+
const name = `tab-close-signal-${crypto.randomUUID()}`;
|
|
25
|
+
const releaseLock = await requestNavigatorLock(name, { signal: abort });
|
|
26
|
+
|
|
27
|
+
abort?.addEventListener('abort', releaseLock);
|
|
28
|
+
return name;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Requests a navigator lock, resolving once it has been granted.
|
|
33
|
+
*
|
|
34
|
+
* The lock is held until the returned function is called, or until another context steals it (in which case `onStolen`
|
|
35
|
+
* is invoked).
|
|
36
|
+
*/
|
|
37
|
+
export function requestNavigatorLock(
|
|
38
|
+
name: string,
|
|
39
|
+
{ signal, steal, onStolen }: { signal?: AbortSignal; steal?: boolean; onStolen?: () => void } = {}
|
|
40
|
+
): Promise<UnlockFn> {
|
|
41
|
+
return new Promise((resolve, reject) => {
|
|
42
|
+
let granted: { released: boolean } | null = null;
|
|
43
|
+
|
|
44
|
+
getNavigatorLocks()
|
|
45
|
+
.request(name, { signal, steal }, (_) => {
|
|
46
|
+
return new Promise<void>((returnLock) => {
|
|
47
|
+
const state = { released: false };
|
|
48
|
+
granted = state;
|
|
49
|
+
resolve(() => {
|
|
50
|
+
state.released = true;
|
|
51
|
+
returnLock();
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
})
|
|
55
|
+
.catch((e) => {
|
|
56
|
+
if (granted == null) {
|
|
57
|
+
// Failed to obtain the lock (e.g. because the request was aborted).
|
|
58
|
+
reject(e);
|
|
59
|
+
} else if (!granted.released) {
|
|
60
|
+
// The callback was invoked, but the lock hasn't been released yet. That can only mean that the lock has been
|
|
61
|
+
// stolen from another context.
|
|
62
|
+
onStolen?.();
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
}
|
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
import { LogLevels, PowerSyncLogger } from '@powersync/common';
|
|
2
2
|
import * as Comlink from 'comlink';
|
|
3
3
|
import { ClientConnectionView, DatabaseServer } from '../../db/adapters/wa-sqlite/DatabaseServer.js';
|
|
4
|
-
import { getNavigatorLocks } from '../../shared/
|
|
4
|
+
import { getNavigatorLocks } from '../../shared/locks.js';
|
|
5
5
|
import { RawSqliteConnection, RawWaSqliteDatabaseOptions } from '../../db/adapters/wa-sqlite/RawSqliteConnection.js';
|
|
6
|
-
import {
|
|
7
|
-
|
|
6
|
+
import {
|
|
7
|
+
ConcurrentSqliteConnection,
|
|
8
|
+
ConnectionMutex,
|
|
9
|
+
LazyNavigatorMutex,
|
|
10
|
+
NavigatorMutex
|
|
11
|
+
} from '../../db/adapters/wa-sqlite/ConcurrentConnection.js';
|
|
12
|
+
import { loadModuleAndVfs, WASQLiteVFS } from '../../db/adapters/wa-sqlite/vfs.js';
|
|
8
13
|
import { Mutex } from '@powersync/shared-internals';
|
|
14
|
+
import type { SimpleOpfsFileSystem } from '../../db/adapters/wa-sqlite/SimpleOpfsFileSystem.js';
|
|
9
15
|
|
|
10
16
|
const OPEN_DB_LOCK = 'open-wasqlite-db';
|
|
11
17
|
|
|
@@ -75,28 +81,56 @@ export class MultiDatabaseServer {
|
|
|
75
81
|
|
|
76
82
|
async #databaseOpenAttempt(logger: PowerSyncLogger, options: RawWaSqliteDatabaseOptions): Promise<DatabaseServer> {
|
|
77
83
|
const { filename, readonly, vfs } = options;
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
84
|
+
|
|
85
|
+
let locks: ConnectionMutex;
|
|
86
|
+
let needsNavigatorLocks;
|
|
87
|
+
if (
|
|
88
|
+
isSharedWorker ||
|
|
89
|
+
readonly ||
|
|
90
|
+
vfs == WASQLiteVFS.InMemoryVfs ||
|
|
91
|
+
(vfs == WASQLiteVFS.SimpleOpfsVFS && options.simpleMode == 'shared')
|
|
92
|
+
) {
|
|
93
|
+
// We don't need navigator locks for shared workers because all queries run in this shared worker exclusively.
|
|
94
|
+
// For read-only connections, we use a VFS that supports concurrent reads (so a single lock on the connection is
|
|
95
|
+
// fine). In-memory databases either run in a shared worker or aren't shared across tabs at all, so the internal
|
|
96
|
+
// lock is enough.
|
|
97
|
+
locks = new Mutex();
|
|
98
|
+
needsNavigatorLocks = false;
|
|
99
|
+
} else if (vfs == WASQLiteVFS.SimpleOpfsVFS && options.simpleMode != 'rw-unsafe') {
|
|
100
|
+
// Use navigator locks that also release sync access handles when there's contention.
|
|
101
|
+
locks = new LazyNavigatorMutex(`db-lock-${options.filename}`);
|
|
102
|
+
needsNavigatorLocks = true;
|
|
103
|
+
} else {
|
|
104
|
+
// We need navigator locks, but these don't need to coordinate with the file system.
|
|
105
|
+
locks = new NavigatorMutex(`db-lock-${options.filename}`);
|
|
106
|
+
needsNavigatorLocks = true;
|
|
107
|
+
}
|
|
108
|
+
|
|
83
109
|
const activeDatabases = this.#activeDatabases;
|
|
84
110
|
|
|
85
111
|
async function openDatabase() {
|
|
86
112
|
let server: DatabaseServer | undefined = activeDatabases.get(filename);
|
|
87
113
|
if (server == null) {
|
|
88
114
|
const connection = new RawSqliteConnection(options);
|
|
89
|
-
const withSafeConcurrency = new ConcurrentSqliteConnection(connection,
|
|
115
|
+
const withSafeConcurrency = new ConcurrentSqliteConnection(connection, locks);
|
|
90
116
|
|
|
91
117
|
// Initializing the RawSqliteConnection will run some pragmas that might write to the database file, so we want
|
|
92
118
|
// to do that in an exclusive lock. Note that OPEN_DB_LOCK is not enough for that, as another tab might have
|
|
93
119
|
// already created a connection (and is thus outside of OPEN_DB_LOCK) while currently writing to it.
|
|
94
120
|
const returnLease = await withSafeConcurrency.acquireMutex();
|
|
95
121
|
try {
|
|
96
|
-
await
|
|
122
|
+
const { module, vfs } = await loadModuleAndVfs(options);
|
|
123
|
+
if (options.vfs == WASQLiteVFS.SimpleOpfsVFS) {
|
|
124
|
+
withSafeConcurrency.simpleOpfsVfs = vfs as unknown as SimpleOpfsFileSystem;
|
|
125
|
+
if (locks instanceof LazyNavigatorMutex) {
|
|
126
|
+
locks.linkedVfs = withSafeConcurrency.simpleOpfsVfs;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
await connection.initWithModule(module, vfs);
|
|
97
131
|
} catch (e) {
|
|
98
|
-
|
|
99
|
-
await
|
|
132
|
+
// Close the connection and its file handles while we still have exclusive access.
|
|
133
|
+
await withSafeConcurrency.close(returnLease);
|
|
100
134
|
throw e;
|
|
101
135
|
}
|
|
102
136
|
returnLease();
|
|
@@ -17,7 +17,8 @@ import {
|
|
|
17
17
|
type StreamingSyncImplementationListener,
|
|
18
18
|
Mutex,
|
|
19
19
|
ResolvedSyncOptions,
|
|
20
|
-
SyncStatusSnapshot
|
|
20
|
+
SyncStatusSnapshot,
|
|
21
|
+
InternalConnector
|
|
21
22
|
} from '@powersync/shared-internals';
|
|
22
23
|
import * as Comlink from 'comlink';
|
|
23
24
|
import { WebRemote } from '../../db/sync/WebRemote.js';
|
|
@@ -29,7 +30,7 @@ import {
|
|
|
29
30
|
import { AbstractSharedSyncClientProvider } from './AbstractSharedSyncClientProvider.js';
|
|
30
31
|
import { BroadcastLogger } from './BroadcastLogger.js';
|
|
31
32
|
import { DatabaseClient, OpenWorkerConnection } from '../../db/adapters/wa-sqlite/DatabaseClient.js';
|
|
32
|
-
import { generateTabCloseSignal } from '../../shared/
|
|
33
|
+
import { generateTabCloseSignal } from '../../shared/locks.js';
|
|
33
34
|
import { ResolvedWebSQLOpenOptions } from '../../db/adapters/options.js';
|
|
34
35
|
|
|
35
36
|
/**
|
|
@@ -60,12 +61,18 @@ export type ManualSharedSyncPayload = {
|
|
|
60
61
|
export type SharedSyncInitOptions = {
|
|
61
62
|
streamOptions: Omit<
|
|
62
63
|
WebStreamingSyncImplementationOptions,
|
|
63
|
-
'
|
|
64
|
+
'connector' | 'adapter' | 'remote' | 'subscriptions' | 'logger'
|
|
64
65
|
>;
|
|
65
66
|
dbParams: ResolvedWebSQLOpenOptions;
|
|
66
67
|
enableBroadcastLogs: boolean;
|
|
67
68
|
};
|
|
68
69
|
|
|
70
|
+
export interface ClientConnectorCapabilities {
|
|
71
|
+
hasFetchCredentials: boolean;
|
|
72
|
+
hasPostCheckpointRequest: boolean;
|
|
73
|
+
hasUploadCrud: boolean;
|
|
74
|
+
}
|
|
75
|
+
|
|
69
76
|
/**
|
|
70
77
|
* @internal
|
|
71
78
|
*/
|
|
@@ -82,6 +89,7 @@ export type WrappedSyncPort = {
|
|
|
82
89
|
db?: DBAdapter;
|
|
83
90
|
currentSubscriptions: SubscribedStream[];
|
|
84
91
|
closeListeners: (() => void | Promise<void>)[];
|
|
92
|
+
clientCapabilities: ClientConnectorCapabilities;
|
|
85
93
|
isClosing: boolean;
|
|
86
94
|
};
|
|
87
95
|
|
|
@@ -136,7 +144,7 @@ export class SharedSyncImplementation extends BaseObserver<SharedSyncImplementat
|
|
|
136
144
|
createSyncImplementation: async () => {
|
|
137
145
|
await this.waitForReady();
|
|
138
146
|
|
|
139
|
-
const sync = this.generateStreamingImplementation();
|
|
147
|
+
const sync = await this.generateStreamingImplementation();
|
|
140
148
|
const removeStatusListener = sync.registerListener({
|
|
141
149
|
statusChanged: (snapshot) => {
|
|
142
150
|
this.syncStatus = snapshot;
|
|
@@ -283,14 +291,22 @@ export class SharedSyncImplementation extends BaseObserver<SharedSyncImplementat
|
|
|
283
291
|
/**
|
|
284
292
|
* Adds a new client tab's message port to the list of connected ports
|
|
285
293
|
*/
|
|
286
|
-
|
|
287
|
-
return
|
|
294
|
+
addPort(port: MessagePort, capabilities: ClientConnectorCapabilities) {
|
|
295
|
+
return this.portMutex.runExclusive(() => {
|
|
296
|
+
if (this.ports.length) {
|
|
297
|
+
// If we're already tracking a port, the added port must connect in the same mode (download or upload only, or
|
|
298
|
+
// both).
|
|
299
|
+
const anyPort = this.ports[0];
|
|
300
|
+
checkCapabilitiesCompatible(anyPort.clientCapabilities, capabilities);
|
|
301
|
+
}
|
|
302
|
+
|
|
288
303
|
const portProvider = {
|
|
289
304
|
port,
|
|
290
305
|
clientProvider: Comlink.wrap<AbstractSharedSyncClientProvider>(port),
|
|
291
306
|
currentSubscriptions: [],
|
|
292
307
|
closeListeners: [],
|
|
293
|
-
isClosing: false
|
|
308
|
+
isClosing: false,
|
|
309
|
+
clientCapabilities: capabilities
|
|
294
310
|
} satisfies WrappedSyncPort;
|
|
295
311
|
this.ports.push(portProvider);
|
|
296
312
|
|
|
@@ -372,55 +388,68 @@ export class SharedSyncImplementation extends BaseObserver<SharedSyncImplementat
|
|
|
372
388
|
protected generateStreamingImplementation() {
|
|
373
389
|
// This should only be called after initialization has completed
|
|
374
390
|
const syncParams = this.syncParams!;
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
391
|
+
const capabilities = this.ports[0]?.clientCapabilities;
|
|
392
|
+
if (!capabilities) {
|
|
393
|
+
throw new Error('Cannot create a sync implementation without connected clients');
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const connector: InternalConnector = {};
|
|
397
|
+
|
|
398
|
+
if (capabilities.hasFetchCredentials) {
|
|
399
|
+
// Always forward invalidations to the tab, since it has its own credentials cache (and potentially a
|
|
400
|
+
// connector-level invalidateCredentials callback).
|
|
401
|
+
connector.invalidateCredentials = async () => {
|
|
402
|
+
const lastPort = await this.getLastWrappedPort();
|
|
403
|
+
if (!lastPort) {
|
|
404
|
+
throw new Error('No client port found to invalidate credentials');
|
|
405
|
+
}
|
|
406
|
+
try {
|
|
407
|
+
this.logger.log({
|
|
408
|
+
level: LogLevels.info,
|
|
409
|
+
message: 'calling the last port client provider to invalidate credentials'
|
|
410
|
+
});
|
|
411
|
+
lastPort.clientProvider.invalidateCredentials();
|
|
412
|
+
} catch (error) {
|
|
413
|
+
this.logger.log({ level: LogLevels.error, message: 'error invalidating credentials', error });
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
if (capabilities.hasFetchCredentials) {
|
|
418
|
+
connector.fetchCredentials = (signal?: AbortSignal) => {
|
|
419
|
+
return this.#useConnector(
|
|
420
|
+
(port) => {
|
|
421
|
+
this.logger.log({
|
|
422
|
+
level: LogLevels.info,
|
|
423
|
+
message: 'calling the last port client provider for credentials'
|
|
424
|
+
});
|
|
425
|
+
|
|
426
|
+
return port.clientProvider.fetchCredentials();
|
|
394
427
|
},
|
|
395
|
-
fetchCredentials
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
message: 'calling the last port client provider for credentials'
|
|
403
|
-
});
|
|
404
|
-
|
|
405
|
-
return port.clientProvider.fetchCredentials();
|
|
406
|
-
},
|
|
407
|
-
'fetchCredentials',
|
|
408
|
-
signal
|
|
409
|
-
);
|
|
410
|
-
}
|
|
411
|
-
},
|
|
412
|
-
this.logger
|
|
413
|
-
),
|
|
414
|
-
uploadCrud: (signal) => {
|
|
428
|
+
'fetchCredentials',
|
|
429
|
+
signal
|
|
430
|
+
);
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
if (capabilities.hasUploadCrud) {
|
|
434
|
+
connector.uploadCrud = (signal) => {
|
|
415
435
|
return this.#useConnector((port) => port.clientProvider.uploadCrud(), 'uploadCrud', signal);
|
|
416
|
-
}
|
|
417
|
-
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
if (capabilities.hasPostCheckpointRequest) {
|
|
439
|
+
connector.postCheckpointRequest = (clientId, requestId, signal) => {
|
|
418
440
|
return this.#useConnector(
|
|
419
441
|
(port) => port.clientProvider.postCheckpointRequest(clientId, requestId),
|
|
420
442
|
'postCheckpointRequest',
|
|
421
443
|
signal
|
|
422
444
|
);
|
|
423
|
-
}
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// Create a new StreamingSyncImplementation for each connect call. This is usually done is all SDKs.
|
|
449
|
+
return new WebStreamingSyncImplementation({
|
|
450
|
+
adapter: new SqliteBucketStorage(this.database, this.logger),
|
|
451
|
+
connector,
|
|
452
|
+
remote: new WebRemote(connector, this.logger),
|
|
424
453
|
...syncParams.streamOptions,
|
|
425
454
|
subscriptions: this.subscriptions,
|
|
426
455
|
// Logger cannot be transferred just yet
|
|
@@ -679,3 +708,15 @@ function withAbort<T>(options: {
|
|
|
679
708
|
.catch((e) => completePromise(() => reject(e)));
|
|
680
709
|
});
|
|
681
710
|
}
|
|
711
|
+
|
|
712
|
+
function checkCapabilitiesCompatible(a: ClientConnectorCapabilities, b: ClientConnectorCapabilities) {
|
|
713
|
+
if (
|
|
714
|
+
a.hasFetchCredentials != b.hasFetchCredentials ||
|
|
715
|
+
a.hasUploadCrud != b.hasUploadCrud ||
|
|
716
|
+
a.hasPostCheckpointRequest != b.hasPostCheckpointRequest
|
|
717
|
+
) {
|
|
718
|
+
throw new Error(
|
|
719
|
+
'Different tabs connecting in different modes (download-only / upload-only / full, or with and without custom checkpoint requests) is not supported'
|
|
720
|
+
);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as Comlink from 'comlink';
|
|
2
|
-
import { getNavigatorLocks } from '../../shared/
|
|
2
|
+
import { getNavigatorLocks } from '../../shared/locks.js';
|
|
3
3
|
import {
|
|
4
|
+
ClientConnectorCapabilities,
|
|
4
5
|
ManualSharedSyncPayload,
|
|
5
6
|
SharedSyncClientEvent,
|
|
6
7
|
SharedSyncImplementation,
|
|
@@ -10,7 +11,7 @@ import {
|
|
|
10
11
|
import { SubscribedStream, ResolvedSyncOptions } from '@powersync/shared-internals';
|
|
11
12
|
|
|
12
13
|
/**
|
|
13
|
-
* A client
|
|
14
|
+
* A connected client from the perspective of the shared sync worker.
|
|
14
15
|
*
|
|
15
16
|
* The shared sync implementation needs a per-client view of subscriptions so that subscriptions of closed tabs can
|
|
16
17
|
* automatically be evicted later.
|
|
@@ -56,9 +57,9 @@ export class WorkerClient {
|
|
|
56
57
|
* When the client tab is closed, its lock will be returned. So when the shared worker attempts to acquire the lock,
|
|
57
58
|
* it can consider the connection to be closed.
|
|
58
59
|
*/
|
|
59
|
-
async
|
|
60
|
+
async initialize(name: string, capabilities: ClientConnectorCapabilities) {
|
|
60
61
|
// Only add the port once the lock has been obtained on the client.
|
|
61
|
-
this.resolvedPort = await this.sync.addPort(this.port);
|
|
62
|
+
this.resolvedPort = await this.sync.addPort(this.port, capabilities);
|
|
62
63
|
// Don't await this lock request
|
|
63
64
|
getNavigatorLocks().request(name, async () => {
|
|
64
65
|
await this.removePort();
|
package/src/worker/worker.ts
CHANGED
|
@@ -3,17 +3,96 @@ import * as Comlink from 'comlink';
|
|
|
3
3
|
import { createConsoleLogger, LogLevels } from '@powersync/common';
|
|
4
4
|
import { isSharedWorker, MultiDatabaseServer } from './db/MultiDatabaseServer.js';
|
|
5
5
|
import { SharedSyncImplementation } from './sync/SharedSyncImplementation.js';
|
|
6
|
-
import { OpenWorkerConnection } from '../db/adapters/wa-sqlite/DatabaseClient.js';
|
|
7
|
-
import { SharedWorkerConnectionRequest } from './SharedWorkerConnectionRequest.js';
|
|
6
|
+
import type { DedicatedFeatureDetectionResult, OpenWorkerConnection } from '../db/adapters/wa-sqlite/DatabaseClient.js';
|
|
7
|
+
import type { SharedWorkerConnectionRequest } from './SharedWorkerConnectionRequest.js';
|
|
8
8
|
import { WorkerClient } from './sync/WorkerClient.js';
|
|
9
9
|
|
|
10
|
+
interface NestedWorker {
|
|
11
|
+
remote: Comlink.Remote<OpenWorkerConnection>;
|
|
12
|
+
features: DedicatedFeatureDetectionResult;
|
|
13
|
+
}
|
|
14
|
+
|
|
10
15
|
const server = new MultiDatabaseServer(createConsoleLogger({ prefix: 'db-worker', minLevel: LogLevels.trace }));
|
|
16
|
+
let nestedWorker: Promise<NestedWorker> | null = null;
|
|
11
17
|
|
|
12
18
|
const exposedDatabaseFunctions: OpenWorkerConnection = {
|
|
13
19
|
connect: (config) => server.handleConnection(config),
|
|
14
|
-
connectToExisting: ({ identifier, lockName }) => server.connectToExisting(identifier, lockName)
|
|
20
|
+
connectToExisting: ({ identifier, lockName }) => server.connectToExisting(identifier, lockName),
|
|
21
|
+
sharedFeatureDetection: async () => {
|
|
22
|
+
let nestedWorkerSupport: DedicatedFeatureDetectionResult | null = null;
|
|
23
|
+
if ('Worker' in globalThis) {
|
|
24
|
+
try {
|
|
25
|
+
const worker = await (nestedWorker ??= trySpawningNestedWorker());
|
|
26
|
+
nestedWorkerSupport = worker.features;
|
|
27
|
+
} catch (e) {
|
|
28
|
+
// We don't support nested workers.
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return {
|
|
33
|
+
worker: nestedWorkerSupport
|
|
34
|
+
};
|
|
35
|
+
},
|
|
36
|
+
dedicatedFeatureDetection: async () => {
|
|
37
|
+
return {
|
|
38
|
+
openWithMode: fileSystemSupportsOpenMode(),
|
|
39
|
+
opfs: await checkOpfsSupport()
|
|
40
|
+
};
|
|
41
|
+
},
|
|
42
|
+
spawnNested: async () => {
|
|
43
|
+
const { remote } = await (nestedWorker ??= trySpawningNestedWorker());
|
|
44
|
+
|
|
45
|
+
const port = await remote[Comlink.createEndpoint]();
|
|
46
|
+
return Comlink.transfer(port, [port]);
|
|
47
|
+
}
|
|
15
48
|
};
|
|
16
49
|
|
|
50
|
+
async function checkOpfsSupport(): Promise<boolean> {
|
|
51
|
+
const storage = navigator.storage;
|
|
52
|
+
if (storage == null || !('FileSystemSyncAccessHandle' in globalThis)) return false;
|
|
53
|
+
|
|
54
|
+
try {
|
|
55
|
+
await storage.getDirectory();
|
|
56
|
+
return true;
|
|
57
|
+
} catch (e) {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function trySpawningNestedWorker(): Promise<NestedWorker> {
|
|
63
|
+
const fork = new Worker(location.href, { type: 'module' });
|
|
64
|
+
|
|
65
|
+
return new Promise((resolve, reject) => {
|
|
66
|
+
let done = false;
|
|
67
|
+
const wrapped = Comlink.wrap<OpenWorkerConnection>(fork);
|
|
68
|
+
|
|
69
|
+
wrapped.dedicatedFeatureDetection().then(
|
|
70
|
+
(features) => {
|
|
71
|
+
done = true;
|
|
72
|
+
resolve({ remote: wrapped, features });
|
|
73
|
+
},
|
|
74
|
+
(e) => {
|
|
75
|
+
done = true;
|
|
76
|
+
reject(e);
|
|
77
|
+
}
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
fork.addEventListener('error', (e) => {
|
|
81
|
+
if (!done) {
|
|
82
|
+
done = true;
|
|
83
|
+
reject(e);
|
|
84
|
+
} else {
|
|
85
|
+
console.error('Nested worker error', e);
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function fileSystemSupportsOpenMode(): boolean {
|
|
92
|
+
// Credits: https://github.com/whatwg/fs/issues/34#issuecomment-1780168010
|
|
93
|
+
return 'FileSystemSyncAccessHandle' in globalThis && FileSystemSyncAccessHandle.prototype.hasOwnProperty('mode');
|
|
94
|
+
}
|
|
95
|
+
|
|
17
96
|
if (isSharedWorker) {
|
|
18
97
|
const sharedSyncImplementation = new SharedSyncImplementation();
|
|
19
98
|
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{F as e}from"./FacadeVFS-d1ZDvud7.js";import{j as t,S as a,k as s,n as i,p as c,D as n,F as r,r as o,G as l,H as h,I as d}from"./worker.js";const m=4096,p=o|l|h|d;class u extends e{log=null;#e;#t;#a=new Map;#s=new Map;#i=new Set;#c=new Map;static async create(e,t){const a=new u(e,t);return await a.isReady(),a}constructor(e,t){super(e,t),this.#e=e}jOpen(e,i,c,n){try{const s=e?this.#n(e):Math.random().toString(36);let r=this.#s.get(s);if(!r&&c&t){if(!(this.getSize()<this.getCapacity()))throw new Error("cannot create file");[r]=this.#i.keys(),this.#r(r,s,c)}if(!r)throw new Error("file not found");const o={path:s,flags:c,accessHandle:r};return this.#c.set(i,o),n.setInt32(0,c,!0),a}catch(e){return console.error(e.message),s}}jClose(e){const t=this.#c.get(e);return t&&(t.accessHandle.flush(),this.#c.delete(e),t.flags&i&&this.#o(t.path)),a}jRead(e,t,s){const i=this.#c.get(e).accessHandle.read(t.subarray(),{at:m+s});return i<t.byteLength?(t.fill(0,i,t.byteLength),c):a}jWrite(e,t,s){return this.#c.get(e).accessHandle.write(t.subarray(),{at:m+s})===t.byteLength?a:n}jTruncate(e,t){return this.#c.get(e).accessHandle.truncate(m+t),a}jSync(e,t){return this.#c.get(e).accessHandle.flush(),a}jFileSize(e,t){const s=this.#c.get(e).accessHandle.getSize()-m;return t.setBigInt64(0,BigInt(s),!0),a}jSectorSize(e){return 4096}jDeviceCharacteristics(e){return r}jAccess(e,t,s){const i=this.#n(e);return s.setInt32(0,this.#s.has(i)?1:0,!0),a}jDelete(e,t){const s=this.#n(e);return this.#o(s),a}async close(){await this.#l()}async isReady(){if(!this.#t){let e=await navigator.storage.getDirectory();for(const t of this.#e.split("/"))t&&(e=await e.getDirectoryHandle(t,{create:!0}));this.#t=e,await this.#h(),0===this.getCapacity()&&await this.addCapacity(6)}return!0}getSize(){return this.#s.size}getCapacity(){return this.#a.size}async addCapacity(e){for(let t=0;t<e;++t){const e=Math.random().toString(36).replace("0.",""),t=await this.#t.getFileHandle(e,{create:!0}),a=await t.createSyncAccessHandle();this.#a.set(a,e),this.#r(a,"",0)}return e}async removeCapacity(e){let t=0;for(const a of Array.from(this.#i)){if(t==e||this.getSize()===this.getCapacity())return t;const s=this.#a.get(a);await a.close(),await this.#t.removeEntry(s),this.#a.delete(a),this.#i.delete(a),++t}return t}async#h(){const e=[];for await(const[t,a]of this.#t)"file"===a.kind&&e.push([t,a]);const t=(await Promise.allSettled(e.map(async([e,t])=>{const a=await t.createSyncAccessHandle();this.#a.set(a,e);const s=this.#d(a);s?this.#s.set(s,a):this.#i.add(a)}))).find(e=>"rejected"===e.status);if(t)throw this.#l(),t.reason}#l(){for(const e of this.#a.keys())e.close();this.#a.clear(),this.#s.clear(),this.#i.clear()}#d(e){const t=new Uint8Array(516);e.read(t,{at:0});const a=new DataView(t.buffer,t.byteOffset).getUint32(512);if(t[0]&&(a&i||0===(a&p)))return console.warn(`Remove file with unexpected flags ${a.toString(16)}`),this.#r(e,"",0),"";const s=new Uint32Array(2);e.read(s,{at:516});const c=this.#m(t);if(s.every((e,t)=>e===c[t])){const a=t.findIndex(e=>0===e);return 0===a&&e.truncate(m),(new TextDecoder).decode(t.subarray(0,a))}return console.warn("Disassociating file with bad digest."),this.#r(e,"",0),""}#r(e,t,a){const s=new Uint8Array(516);if((new TextEncoder).encodeInto(t,s).written>=512)throw new Error("path too long");new DataView(s.buffer,s.byteOffset).setUint32(512,a);const i=this.#m(s);e.write(s,{at:0}),e.write(i,{at:516}),e.flush(),t?(this.#s.set(t,e),this.#i.delete(e)):(e.truncate(m),this.#i.add(e))}#m(e){if(!e[0])return new Uint32Array([4274806656,2899230775]);let t=3735928559,a=1103547991;for(const s of e)t=Math.imul(t^s,2654435761),a=Math.imul(a^s,1597334677);return t=Math.imul(t^t>>>16,2246822507)^Math.imul(a^a>>>13,3266489909),a=Math.imul(a^a>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),new Uint32Array([t>>>0,a>>>0])}#n(e){return("string"==typeof e?new URL(e,"file://localhost/"):e).pathname}#o(e){const t=this.#s.get(e);t&&(this.#s.delete(e),this.#r(t,"",0))}}export{u as AccessHandlePoolVFS};
|
|
2
|
-
//# sourceMappingURL=AccessHandlePoolVFS-B9CKqcQ3.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"AccessHandlePoolVFS-B9CKqcQ3.js","sources":["../../../../node_modules/.pnpm/@journeyapps+wa-sqlite@2.0.7/node_modules/@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js"],"sourcesContent":["// Copyright 2023 Roy T. Hashimoto. All Rights Reserved.\nimport { FacadeVFS } from '../FacadeVFS.js';\nimport * as VFS from '../VFS.js';\n\nconst SECTOR_SIZE = 4096;\n\n// Each OPFS file begins with a fixed-size header with metadata. The\n// contents of the file follow immediately after the header.\nconst HEADER_MAX_PATH_SIZE = 512;\nconst HEADER_FLAGS_SIZE = 4;\nconst HEADER_DIGEST_SIZE = 8;\nconst HEADER_CORPUS_SIZE = HEADER_MAX_PATH_SIZE + HEADER_FLAGS_SIZE;\nconst HEADER_OFFSET_FLAGS = HEADER_MAX_PATH_SIZE;\nconst HEADER_OFFSET_DIGEST = HEADER_CORPUS_SIZE;\nconst HEADER_OFFSET_DATA = SECTOR_SIZE;\n\n// These file types are expected to persist in the file system outside\n// a session. Other files will be removed on VFS start.\nconst PERSISTENT_FILE_TYPES =\n VFS.SQLITE_OPEN_MAIN_DB |\n VFS.SQLITE_OPEN_MAIN_JOURNAL |\n VFS.SQLITE_OPEN_SUPER_JOURNAL |\n VFS.SQLITE_OPEN_WAL;\n\nconst DEFAULT_CAPACITY = 6;\n\n/**\n * This VFS uses the updated Access Handle API with all synchronous methods\n * on FileSystemSyncAccessHandle (instead of just read and write). It will\n * work with the regular SQLite WebAssembly build, i.e. the one without\n * Asyncify.\n */\nexport class AccessHandlePoolVFS extends FacadeVFS {\n log = null; //function(...args) { console.log(`[${contextName}]`, ...args) };\n\n // All the OPFS files the VFS uses are contained in one flat directory\n // specified in the constructor. No other files should be written here.\n #directoryPath;\n #directoryHandle;\n\n // The OPFS files all have randomly-generated names that do not match\n // the SQLite files whose data they contain. This map links those names\n // with their respective OPFS access handles.\n #mapAccessHandleToName = new Map();\n\n // When a SQLite file is associated with an OPFS file, that association\n // is kept in #mapPathToAccessHandle. Each access handle is in exactly\n // one of #mapPathToAccessHandle or #availableAccessHandles.\n #mapPathToAccessHandle = new Map();\n #availableAccessHandles = new Set();\n\n #mapIdToFile = new Map();\n\n static async create(name, module) {\n const vfs = new AccessHandlePoolVFS(name, module);\n await vfs.isReady();\n return vfs;\n }\n \n constructor(name, module) {\n super(name, module);\n this.#directoryPath = name;\n }\n\n /**\n * @param {string?} zName \n * @param {number} fileId \n * @param {number} flags \n * @param {DataView} pOutFlags \n * @returns {number}\n */\n jOpen(zName, fileId, flags, pOutFlags) {\n try {\n // First try to open a path that already exists in the file system.\n const path = zName ? this.#getPath(zName) : Math.random().toString(36);\n let accessHandle = this.#mapPathToAccessHandle.get(path);\n if (!accessHandle && (flags & VFS.SQLITE_OPEN_CREATE)) {\n // File not found so try to create it.\n if (this.getSize() < this.getCapacity()) {\n // Choose an unassociated OPFS file from the pool.\n ([accessHandle] = this.#availableAccessHandles.keys());\n this.#setAssociatedPath(accessHandle, path, flags);\n } else {\n // Out of unassociated files. This can be fixed by calling\n // addCapacity() from the application.\n throw new Error('cannot create file');\n }\n }\n if (!accessHandle) {\n throw new Error('file not found');\n }\n // Subsequent methods are only passed the fileId, so make sure we have\n // a way to get the file resources.\n const file = { path, flags, accessHandle };\n this.#mapIdToFile.set(fileId, file);\n\n pOutFlags.setInt32(0, flags, true);\n return VFS.SQLITE_OK;\n } catch (e) {\n console.error(e.message);\n return VFS.SQLITE_CANTOPEN;\n }\n }\n\n /**\n * @param {number} fileId \n * @returns {number}\n */\n jClose(fileId) {\n const file = this.#mapIdToFile.get(fileId);\n if (file) {\n file.accessHandle.flush();\n this.#mapIdToFile.delete(fileId);\n if (file.flags & VFS.SQLITE_OPEN_DELETEONCLOSE) {\n this.#deletePath(file.path);\n }\n }\n return VFS.SQLITE_OK;\n }\n\n /**\n * @param {number} fileId \n * @param {Uint8Array} pData \n * @param {number} iOffset\n * @returns {number}\n */\n jRead(fileId, pData, iOffset) {\n const file = this.#mapIdToFile.get(fileId);\n const nBytes = file.accessHandle.read(\n pData.subarray(),\n { at: HEADER_OFFSET_DATA + iOffset });\n if (nBytes < pData.byteLength) {\n pData.fill(0, nBytes, pData.byteLength);\n return VFS.SQLITE_IOERR_SHORT_READ;\n }\n return VFS.SQLITE_OK;\n }\n\n /**\n * @param {number} fileId \n * @param {Uint8Array} pData \n * @param {number} iOffset\n * @returns {number}\n */\n jWrite(fileId, pData, iOffset) {\n const file = this.#mapIdToFile.get(fileId);\n const nBytes = file.accessHandle.write(\n pData.subarray(),\n { at: HEADER_OFFSET_DATA + iOffset });\n return nBytes === pData.byteLength ? VFS.SQLITE_OK : VFS.SQLITE_IOERR;\n }\n\n /**\n * @param {number} fileId \n * @param {number} iSize \n * @returns {number}\n */\n jTruncate(fileId, iSize) {\n const file = this.#mapIdToFile.get(fileId);\n file.accessHandle.truncate(HEADER_OFFSET_DATA + iSize);\n return VFS.SQLITE_OK;\n }\n\n /**\n * @param {number} fileId \n * @param {number} flags \n * @returns {number}\n */\n jSync(fileId, flags) {\n const file = this.#mapIdToFile.get(fileId);\n file.accessHandle.flush();\n return VFS.SQLITE_OK;\n }\n\n /**\n * @param {number} fileId \n * @param {DataView} pSize64 \n * @returns {number}\n */\n jFileSize(fileId, pSize64) {\n const file = this.#mapIdToFile.get(fileId);\n const size = file.accessHandle.getSize() - HEADER_OFFSET_DATA;\n pSize64.setBigInt64(0, BigInt(size), true);\n return VFS.SQLITE_OK;\n }\n\n jSectorSize(fileId) {\n return SECTOR_SIZE;\n }\n\n jDeviceCharacteristics(fileId) {\n return VFS.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;\n }\n\n /**\n * @param {string} zName \n * @param {number} flags \n * @param {DataView} pResOut \n * @returns {number}\n */\n jAccess(zName, flags, pResOut) {\n const path = this.#getPath(zName);\n pResOut.setInt32(0, this.#mapPathToAccessHandle.has(path) ? 1 : 0, true);\n return VFS.SQLITE_OK;\n }\n\n /**\n * @param {string} zName \n * @param {number} syncDir \n * @returns {number}\n */\n jDelete(zName, syncDir) {\n const path = this.#getPath(zName);\n this.#deletePath(path);\n return VFS.SQLITE_OK;\n }\n\n async close() {\n await this.#releaseAccessHandles();\n }\n\n async isReady() {\n if (!this.#directoryHandle) {\n // All files are stored in a single directory.\n let handle = await navigator.storage.getDirectory();\n for (const d of this.#directoryPath.split('/')) {\n if (d) {\n handle = await handle.getDirectoryHandle(d, { create: true });\n }\n }\n this.#directoryHandle = handle;\n\n await this.#acquireAccessHandles();\n if (this.getCapacity() === 0) {\n await this.addCapacity(DEFAULT_CAPACITY);\n }\n }\n return true;\n }\n\n /**\n * Returns the number of SQLite files in the file system.\n * @returns {number}\n */\n getSize() {\n return this.#mapPathToAccessHandle.size;\n }\n\n /**\n * Returns the maximum number of SQLite files the file system can hold.\n * @returns {number}\n */\n getCapacity() {\n return this.#mapAccessHandleToName.size;\n }\n\n /**\n * Increase the capacity of the file system by n.\n * @param {number} n \n * @returns {Promise<number>} \n */\n async addCapacity(n) {\n for (let i = 0; i < n; ++i) {\n const name = Math.random().toString(36).replace('0.', '');\n const handle = await this.#directoryHandle.getFileHandle(name, { create: true });\n const accessHandle = await handle.createSyncAccessHandle();\n this.#mapAccessHandleToName.set(accessHandle, name);\n\n this.#setAssociatedPath(accessHandle, '', 0);\n }\n return n;\n }\n\n /**\n * Decrease the capacity of the file system by n. The capacity cannot be\n * decreased to fewer than the current number of SQLite files in the\n * file system.\n * @param {number} n \n * @returns {Promise<number>}\n */\n async removeCapacity(n) {\n let nRemoved = 0;\n for (const accessHandle of Array.from(this.#availableAccessHandles)) {\n if (nRemoved == n || this.getSize() === this.getCapacity()) return nRemoved;\n\n const name = this.#mapAccessHandleToName.get(accessHandle);\n await accessHandle.close();\n await this.#directoryHandle.removeEntry(name);\n this.#mapAccessHandleToName.delete(accessHandle);\n this.#availableAccessHandles.delete(accessHandle);\n ++nRemoved;\n }\n return nRemoved;\n }\n\n async #acquireAccessHandles() {\n // Enumerate all the files in the directory.\n const files = [];\n for await (const [name, handle] of this.#directoryHandle) {\n if (handle.kind === 'file') {\n files.push([name, handle]);\n }\n }\n\n // Open access handles in parallel, separating associated and unassociated.\n // Settle them all before reporting a failure, so that the handles\n // acquired beside the one that failed are closed rather than kept.\n const results = await Promise.allSettled(files.map(async ([name, handle]) => {\n const accessHandle = await handle.createSyncAccessHandle();\n this.#mapAccessHandleToName.set(accessHandle, name);\n const path = this.#getAssociatedPath(accessHandle);\n if (path) {\n this.#mapPathToAccessHandle.set(path, accessHandle);\n } else {\n this.#availableAccessHandles.add(accessHandle);\n }\n }));\n const failure = results.find(result => result.status === 'rejected');\n if (failure) {\n this.#releaseAccessHandles();\n throw failure.reason;\n }\n }\n\n #releaseAccessHandles() {\n for (const accessHandle of this.#mapAccessHandleToName.keys()) {\n accessHandle.close();\n }\n this.#mapAccessHandleToName.clear();\n this.#mapPathToAccessHandle.clear();\n this.#availableAccessHandles.clear();\n }\n\n /**\n * Read and return the associated path from an OPFS file header.\n * Empty string is returned for an unassociated OPFS file.\n * @param accessHandle FileSystemSyncAccessHandle\n * @returns {string} path or empty string\n */\n #getAssociatedPath(accessHandle) {\n // Read the path and digest of the path from the file.\n const corpus = new Uint8Array(HEADER_CORPUS_SIZE);\n accessHandle.read(corpus, { at: 0 })\n\n // Delete files not expected to be present.\n const dataView = new DataView(corpus.buffer, corpus.byteOffset);\n const flags = dataView.getUint32(HEADER_OFFSET_FLAGS);\n if (corpus[0] &&\n ((flags & VFS.SQLITE_OPEN_DELETEONCLOSE) ||\n (flags & PERSISTENT_FILE_TYPES) === 0)) {\n console.warn(`Remove file with unexpected flags ${flags.toString(16)}`);\n this.#setAssociatedPath(accessHandle, '', 0);\n return '';\n }\n\n const fileDigest = new Uint32Array(HEADER_DIGEST_SIZE / 4);\n accessHandle.read(fileDigest, { at: HEADER_OFFSET_DIGEST });\n\n // Verify the digest.\n const computedDigest = this.#computeDigest(corpus);\n if (fileDigest.every((value, i) => value === computedDigest[i])) {\n // Good digest. Decode the null-terminated path string.\n const pathBytes = corpus.findIndex(value => value === 0);\n if (pathBytes === 0) {\n // Ensure that unassociated files are empty. Unassociated files are\n // truncated in #setAssociatedPath after the header is written. If\n // an interruption occurs right before the truncation then garbage\n // may remain in the file.\n accessHandle.truncate(HEADER_OFFSET_DATA);\n }\n return new TextDecoder().decode(corpus.subarray(0, pathBytes));\n } else {\n // Bad digest. Repair this header.\n console.warn('Disassociating file with bad digest.');\n this.#setAssociatedPath(accessHandle, '', 0);\n return '';\n }\n }\n\n /**\n * Set the path on an OPFS file header.\n * @param accessHandle FileSystemSyncAccessHandle\n * @param {string} path\n * @param {number} flags\n */\n #setAssociatedPath(accessHandle, path, flags) {\n // Convert the path string to UTF-8.\n const corpus = new Uint8Array(HEADER_CORPUS_SIZE);\n const encodedResult = new TextEncoder().encodeInto(path, corpus);\n if (encodedResult.written >= HEADER_MAX_PATH_SIZE) {\n throw new Error('path too long');\n }\n\n // Add the creation flags.\n const dataView = new DataView(corpus.buffer, corpus.byteOffset);\n dataView.setUint32(HEADER_OFFSET_FLAGS, flags);\n\n // Write the OPFS file header, including the digest.\n const digest = this.#computeDigest(corpus);\n accessHandle.write(corpus, { at: 0 });\n accessHandle.write(digest, { at: HEADER_OFFSET_DIGEST });\n accessHandle.flush();\n\n if (path) {\n this.#mapPathToAccessHandle.set(path, accessHandle);\n this.#availableAccessHandles.delete(accessHandle);\n } else {\n // This OPFS file doesn't represent any SQLite file so it doesn't\n // need to keep any data.\n accessHandle.truncate(HEADER_OFFSET_DATA);\n this.#availableAccessHandles.add(accessHandle);\n }\n }\n\n /**\n * We need a synchronous digest function so can't use WebCrypto.\n * Adapted from https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js\n * @param {Uint8Array} corpus \n * @returns {ArrayBuffer} 64-bit digest\n */\n #computeDigest(corpus) {\n if (!corpus[0]) {\n // Optimization for deleted file.\n return new Uint32Array([0xfecc5f80, 0xaccec037]);\n }\n\n let h1 = 0xdeadbeef;\n let h2 = 0x41c6ce57;\n \n for (const value of corpus) {\n h1 = Math.imul(h1 ^ value, 2654435761);\n h2 = Math.imul(h2 ^ value, 1597334677);\n }\n \n h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);\n \n return new Uint32Array([h1 >>> 0, h2 >>> 0]);\n };\n \n /**\n * Convert a bare filename, path, or URL to a UNIX-style path.\n * @param {string|URL} nameOrURL\n * @returns {string} path\n */\n #getPath(nameOrURL) {\n const url = typeof nameOrURL === 'string' ?\n new URL(nameOrURL, 'file://localhost/') :\n nameOrURL;\n return url.pathname;\n }\n\n /**\n * Remove the association between a path and an OPFS file.\n * @param {string} path \n */\n #deletePath(path) {\n const accessHandle = this.#mapPathToAccessHandle.get(path);\n if (accessHandle) {\n // Un-associate the SQLite path from the OPFS file.\n this.#mapPathToAccessHandle.delete(path);\n this.#setAssociatedPath(accessHandle, '', 0);\n }\n }\n}"],"names":["HEADER_OFFSET_DATA","PERSISTENT_FILE_TYPES","VFS.SQLITE_OPEN_MAIN_DB","VFS.SQLITE_OPEN_MAIN_JOURNAL","VFS.SQLITE_OPEN_SUPER_JOURNAL","VFS.SQLITE_OPEN_WAL","AccessHandlePoolVFS","FacadeVFS","log","directoryPath","directoryHandle","mapAccessHandleToName","Map","mapPathToAccessHandle","availableAccessHandles","Set","mapIdToFile","create","name","module","vfs","isReady","constructor","super","this","jOpen","zName","fileId","flags","pOutFlags","path","getPath","Math","random","toString","accessHandle","get","VFS.SQLITE_OPEN_CREATE","getSize","getCapacity","Error","keys","setAssociatedPath","file","set","setInt32","VFS.SQLITE_OK","e","console","error","message","VFS.SQLITE_CANTOPEN","jClose","flush","delete","VFS.SQLITE_OPEN_DELETEONCLOSE","deletePath","jRead","pData","iOffset","nBytes","read","subarray","at","byteLength","fill","VFS.SQLITE_IOERR_SHORT_READ","jWrite","write","VFS.SQLITE_IOERR","jTruncate","iSize","truncate","jSync","jFileSize","pSize64","size","setBigInt64","BigInt","jSectorSize","jDeviceCharacteristics","VFS.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN","jAccess","pResOut","has","jDelete","syncDir","close","releaseAccessHandles","handle","navigator","storage","getDirectory","d","split","getDirectoryHandle","acquireAccessHandles","addCapacity","n","i","replace","getFileHandle","createSyncAccessHandle","removeCapacity","nRemoved","Array","from","removeEntry","files","kind","push","failure","Promise","allSettled","map","async","getAssociatedPath","add","find","result","status","reason","clear","corpus","Uint8Array","HEADER_MAX_PATH_SIZE","DataView","buffer","byteOffset","getUint32","warn","fileDigest","Uint32Array","HEADER_DIGEST_SIZE","computedDigest","computeDigest","every","value","pathBytes","findIndex","TextDecoder","decode","TextEncoder","encodeInto","written","setUint32","digest","h1","h2","imul","nameOrURL","URL","pathname"],"mappings":"kJAIA,MAUMA,EAVc,KAcdC,EACJC,EACAC,EACAC,EACAC,EAUK,MAAMC,UAA4BC,EACvCC,IAAM,KAINC,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,EAAOI,OAAQJ,EAAOK,YAC3CiB,UAnYgB,IAmYerH,GAGxC,MAAMsH,EAAS1H,MAAK+G,EAAeZ,GACnCxF,EAAaiC,MAAMuD,EAAQ,CAAE5D,GAAI,IACjC5B,EAAaiC,MAAM8E,EAAQ,CAAEnF,GArYN8D,MAsYvB1F,EAAakB,QAETvB,GACFN,MAAKX,EAAuB+B,IAAId,EAAMK,GACtCX,MAAKV,EAAwBwC,OAAOnB,KAIpCA,EAAaqC,SAASxE,GACtBwB,MAAKV,EAAwBuG,IAAIlF,GAErC,CAQA,EAAAoG,CAAeZ,GACb,IAAKA,EAAO,GAEV,OAAO,IAAIS,YAAY,CAAC,WAAY,aAGtC,IAAIe,EAAK,WACLC,EAAK,WAET,IAAK,MAAMX,KAASd,EAClBwB,EAAKnH,KAAKqH,KAAKF,EAAKV,EAAO,YAC3BW,EAAKpH,KAAKqH,KAAKD,EAAKX,EAAO,YAM7B,OAHAU,EAAKnH,KAAKqH,KAAKF,EAAMA,IAAO,GAAK,YAAcnH,KAAKqH,KAAKD,EAAMA,IAAO,GAAK,YAC3EA,EAAKpH,KAAKqH,KAAKD,EAAMA,IAAO,GAAK,YAAcpH,KAAKqH,KAAKF,EAAMA,IAAO,GAAK,YAEpE,IAAIf,YAAY,CAACe,IAAO,EAAGC,IAAO,GAC3C,CAOA,EAAArH,CAASuH,GAIP,OAHiC,iBAAdA,EACjB,IAAIC,IAAID,EAAW,qBACnBA,GACSE,QACb,CAMA,EAAAhG,CAAY1B,GACV,MAAMK,EAAeX,MAAKX,EAAuBuB,IAAIN,GACjDK,IAEFX,MAAKX,EAAuByC,OAAOxB,GACnCN,MAAKkB,EAAmBP,EAAc,GAAI,GAE9C","x_google_ignoreList":[0]}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{F as e}from"./FacadeVFS-d1ZDvud7.js";import{S as t,a as s,b as a,c as r,d as n,e as i,f as o,g as c,h as l,i as h,j as d,k as u,l as p,m as y,n as g,o as f,p as b,q as w,r as m,s as k,t as v,u as x,v as I,w as S,x as E,y as q,z as j,A as T,B as O,C as P,D as L,E as R,F as C}from"./worker.js";const F={mode:"shared"},M={ifAvailable:!0,mode:"shared"},D={ifAvailable:!0,mode:"exclusive"},B=["exclusive","shared","shared+hint"],z=e=>class extends e{#e={lockPolicy:"exclusive",lockTimeout:1/0};#t=new Map;constructor(e,t,s){if(super(e,t,s),Object.assign(this.#e,s),-1===B.indexOf(this.#e.lockPolicy))throw new Error(`WebLocksMixin: invalid lock mode: ${s.lockPolicy}`)}async jLock(e,a){try{const s=this.#s(e);if(a<=s.type)return t;switch(this.#e.lockPolicy){case"exclusive":return await this.#a(s,a);case"shared":case"shared+hint":return await this.#r(s,a)}}catch(e){return console.error("WebLocksMixin: lock error",e),s}}async jUnlock(e,s){try{const a=this.#s(e);if(!(s<a.type))return t;switch(this.#e.lockPolicy){case"exclusive":return await this.#n(a,s);case"shared":case"shared+hint":return await this.#i(a,s)}}catch(e){return console.error("WebLocksMixin: unlock error",e),a}}async jCheckReservedLock(e,s){try{const t=this.#s(e);switch(this.#e.lockPolicy){case"exclusive":return this.#o(t,s);case"shared":case"shared+hint":return await this.#c(t,s)}}catch(e){return console.error("WebLocksMixin: check reserved lock error",e),r}return s.setInt32(0,0,!0),t}jFileControl(e,t,s){if(t===z.WRITE_HINT_OP_CODE&&"shared+hint"===this.#e.lockPolicy){this.#s(e).writeHint=!0}return n}#s(e){let t=this.#t.get(e);if(!t){t={baseName:this.getFilename(e),type:i,writeHint:!1},this.#t.set(e,t)}return t}async#a(e,s){if(!e.access){if(!await this.#l(e,"access"))return o;console.assert(!!e.access)}return e.type=s,t}#n(e,s){return s===i&&(e.access?.(),console.assert(!e.access)),e.type=s,t}#o(e,s){return s.setInt32(0,0,!0),t}async#r(e,s){switch(e.type){case i:if(s!==h)throw new Error("unsupported lock transition");if(e.writeHint&&!await this.#l(e,"hint"))return o;if(!await this.#l(e,"gate",F))return e.hint?.(),o;await this.#l(e,"access",F),e.gate(),console.assert(!e.gate),console.assert(!!e.access),console.assert(!e.reserved);break;case h:switch(s){case c:if("shared+hint"===this.#e.lockPolicy&&!e.hint&&!await this.#l(e,"hint",D))return o;if(!await this.#l(e,"reserved",D))return e.hint?.(),o;e.access(),console.assert(!e.gate),console.assert(!e.access),console.assert(!!e.reserved);break;case l:if(!await this.#l(e,"gate"))return o;if(e.access(),!await this.#l(e,"access"))return e.gate(),o;console.assert(!!e.gate),console.assert(!!e.access),console.assert(!e.reserved);break;default:throw new Error("unsupported lock transition")}break;case c:if(s!==l)throw new Error("unsupported lock transition");if(!await this.#l(e,"gate"))return o;if(!await this.#l(e,"access"))return e.gate(),o;console.assert(!!e.gate),console.assert(!!e.access),console.assert(!!e.reserved)}return e.type=s,t}async#i(e,s){if(s===i)e.access?.(),e.gate?.(),e.reserved?.(),e.hint?.(),e.writeHint=!1,console.assert(!e.access),console.assert(!e.gate),console.assert(!e.reserved),console.assert(!e.hint);else switch(e.type){case l:e.access(),await this.#l(e,"access",F),e.gate(),e.reserved?.(),e.hint?.(),console.assert(!!e.access),console.assert(!e.gate),console.assert(!e.reserved);break;case c:await this.#l(e,"access",F),e.reserved(),e.hint?.(),console.assert(!!e.access),console.assert(!e.gate),console.assert(!e.reserved)}return e.type=s,t}async#c(e,s){return await this.#l(e,"reserved",M)?(e.reserved(),s.setInt32(0,0,!0)):s.setInt32(0,1,!0),t}#l(e,t,s={}){return console.assert(!e[t]),new Promise(a=>{if(!s.ifAvailable&&this.#e.lockTimeout<1/0){const e=new AbortController;s=Object.assign({},s,{signal:e.signal}),setTimeout(()=>{e.abort(),a?.(!1)},this.#e.lockTimeout)}const r=`lock##${e.baseName}##${t}`;navigator.locks.request(r,s,s=>{if(s)return new Promise(s=>{e[t]=()=>{s(),e[t]=null},a(!0),a=null});e[t]=null,a(!1),a=null}).catch(e=>{if("AbortError"!==e.name)throw e})})}};z.WRITE_HINT_OP_CODE=-9999;const _=new Set(["TransactionInactiveError","InvalidStateError"]);class A{path;flags;metadata;fileSize=0;needsMetadataSync=!1;rollback=null;changedPages=new Set;synchronous="full";txOptions={durability:"strict"};constructor(e,t,s){this.path=e,this.flags=t,this.metadata=s}}class W extends(z(e)){mapIdToFile=new Map;lastError=null;log=null;#h;#d;static async create(e,t,s){const a=new W(e,t,s);return await a.isReady(),a}constructor(e,t,s={}){super(e,t,s),this.#h=this.#u(s.idbName??e)}async#u(e){this.#d=await N.create(e)}close(){this.#d.close()}async isReady(){await super.isReady(),await this.#h}getFilename(e){const t=this.mapIdToFile.get(e).path;return`IDB(${this.name}):${t}`}async jOpen(e,s,a,r){try{const n=new URL(e||Math.random().toString(36).slice(2),"file://").pathname;let i=await this.#d.q(({metadata:e})=>e.get(n));if(!i&&a&d&&(i={name:n,fileSize:0,version:0},await this.#d.q(({metadata:e})=>e.put(i),"rw")),!i)throw new Error(`File ${n} not found`);const o=new A(n,a,i);return this.mapIdToFile.set(s,o),r.setInt32(0,a,!0),t}catch(e){return this.lastError=e,u}}async jDelete(e,s){try{const a=new URL(e,"file://").pathname;return this.#d.q(({metadata:e,blocks:t})=>{const s=IDBKeyRange.bound([a,-1/0],[a,1/0]);t.delete(s),e.delete(a)},"rw",s?{durability:"strict"}:{}),s&&await this.#d.sync(!0),t}catch(e){return this.lastError=e,p}}async jAccess(e,s,a){try{const s=new URL(e,"file://").pathname,r=await this.#d.q(({metadata:e})=>e.get(s));return a.setInt32(0,r?1:0,!0),t}catch(e){return this.lastError=e,y}}async jClose(e){try{const s=this.mapIdToFile.get(e);return this.mapIdToFile.delete(e),s.flags&g&&await this.#d.q(({metadata:e,blocks:t})=>{e.delete(s.path),t.delete(IDBKeyRange.bound([s.path,0],[s.path,1/0]))},"rw"),s.needsMetadataSync&&this.#d.q(({metadata:e})=>e.put(s.metadata),"rw"),await this.#d.sync("full"===s.synchronous),t}catch(e){return this.lastError=e,f}}async jRead(e,s,a){try{const r=this.mapIdToFile.get(e);let n=0;for(;n<s.byteLength;){const e=a+n,t=await this.#d.q(({blocks:t})=>{const s=IDBKeyRange.bound([r.path,-e],[r.path,1/0]);return t.get(s)});if(!t||t.data.byteLength-t.offset<=e)return s.fill(0,n),b;const i=s.subarray(n),o=e+t.offset,c=Math.min(Math.max(t.data.byteLength-o,0),i.byteLength);i.set(t.data.subarray(o,o+c)),n+=c}return t}catch(e){return this.lastError=e,w}}jWrite(e,s,a){try{const r=this.mapIdToFile.get(e);if(r.flags&m&&!r.rollback){const e=Object.assign({pendingVersion:r.metadata.version-1},r.metadata);this.#d.q(({metadata:t})=>t.put(e),"rw",r.txOptions),r.rollback=Object.assign({},r.metadata),r.metadata.version--}r.flags&m&&r.changedPages.add(a);const n=s.slice(),i=r.metadata.version;if(!(a<r.metadata.fileSize)||r.flags&m||r.flags&k){const e={path:r.path,offset:-a,version:i,data:s.slice()};this.#d.q(({blocks:t})=>{t.put(e),r.changedPages.add(a)},"rw",r.txOptions)}else this.#d.q(async({blocks:e})=>{const t=(await e.getAllKeys(IDBKeyRange.bound([r.path,-(a+n.byteLength)],[r.path,-a],!0,!0))).map(e=>-e[1]).reverse();let s=0;for(;s<n.byteLength;){const o=a+s;for(;t.length&&t[0]<=o;)t.shift();const c=Math.min(n.byteLength,(t[0]??1/0)-a),l=IDBKeyRange.bound([r.path,-o],[r.path,1/0]),h=await e.get(l);if(!h||h.data.byteLength-h.offset<=o){e.put({path:r.path,offset:-o,version:i,data:n.slice(s,c)}),s=c;continue}const d=o+h.offset,u=Math.min(h.data.byteLength-d,c-s);h.data.subarray(d,d+u).set(n.subarray(s,s+u)),e.put(h),s+=u}},"rw",r.txOptions);return r.metadata.fileSize<a+s.length&&(r.metadata.fileSize=a+s.length,r.needsMetadataSync=!0),t}catch(e){return this.lastError=e,v}}jTruncate(e,s){try{const a=this.mapIdToFile.get(e);return s<a.metadata.fileSize&&(this.#d.q(({blocks:e})=>{const t=IDBKeyRange.bound([a.path,-1/0],[a.path,-s,1/0]);e.delete(t)},"rw",a.txOptions),a.metadata.fileSize=s,a.needsMetadataSync=!0),t}catch(e){return this.lastError=e,x}}async jSync(e,s){try{const s=this.mapIdToFile.get(e);return s.needsMetadataSync&&(this.#d.q(({metadata:e})=>e.put(s.metadata),"rw",s.txOptions),s.needsMetadataSync=!1),s.flags&m?"full"===s.synchronous&&await this.#d.sync(!0):await this.#d.sync("full"===s.synchronous),t}catch(e){return this.lastError=e,I}}jFileSize(e,s){try{const a=this.mapIdToFile.get(e);return s.setBigInt64(0,BigInt(a.metadata.fileSize),!0),t}catch(e){return this.lastError=e,S}}async jLock(e,t){const s=this.mapIdToFile.get(e),a=await super.jLock(e,t);return t===h&&(s.metadata=await this.#d.q(async({metadata:e,blocks:t})=>{const a=await e.get(s.path);return a.pendingVersion&&(console.warn(`removing failed transaction ${a.pendingVersion}`),await new Promise((e,s)=>{const r=IDBKeyRange.bound([a.name,-1/0],[a.name,1/0]),n=t.openCursor(r);n.onsuccess=()=>{const t=n.result;if(t){t.value.version<a.version&&t.delete(),t.continue()}else e()},n.onerror=()=>s(n.error)}),delete a.pendingVersion,e.put(a)),a},"rw",s.txOptions)),a}async jUnlock(e,t){if(t===i){const t=this.mapIdToFile.get(e);await this.#d.sync("full"===t.synchronous)}return super.jUnlock(e,t)}jFileControl(e,s,a){try{const r=this.mapIdToFile.get(e);switch(s){case O:const s=K(a,4),n=K(a,8);this.log?.("xFileControl",r.path,"PRAGMA",s,n);switch(s.toLowerCase()){case"page_size":if(r.flags&m&&n&&r.metadata.fileSize)return P;break;case"synchronous":if(n)switch(n.toLowerCase()){case"0":case"off":r.synchronous="off",r.txOptions={durability:"relaxed"};break;case"1":case"normal":r.synchronous="normal",r.txOptions={durability:"relaxed"};break;case"2":case"3":case"full":case"extra":r.synchronous="full",r.txOptions={durability:"strict"}}break;case"write_hint":return super.jFileControl(e,z.WRITE_HINT_OP_CODE,null)}break;case T:if(this.log?.("xFileControl",r.path,"SYNC"),r.rollback){const e=Object.assign({},r.metadata),t=r.rollback.fileSize;this.#d.q(({metadata:s,blocks:a})=>{s.put(e);for(const s of r.changedPages)if(s<t){const t=IDBKeyRange.bound([r.path,-s,e.version],[r.path,-s,1/0],!0);a.delete(t)}r.changedPages.clear()},"rw",r.txOptions),r.needsMetadataSync=!1,r.rollback=null}break;case j:return this.log?.("xFileControl",r.path,"BEGIN_ATOMIC_WRITE"),t;case q:return this.log?.("xFileControl",r.path,"COMMIT_ATOMIC_WRITE"),t;case E:this.log?.("xFileControl",r.path,"ROLLBACK_ATOMIC_WRITE"),r.metadata=r.rollback;const i=Object.assign({},r.metadata);return this.#d.q(({metadata:e,blocks:t})=>{e.put(i);for(const e of r.changedPages)t.delete([r.path,-e,i.version-1]);r.changedPages.clear()},"rw",r.txOptions),r.needsMetadataSync=!1,r.rollback=null,t}}catch(e){return this.lastError=e,L}return super.jFileControl(e,s,a)}jDeviceCharacteristics(e){return 0|R|C}jGetLastError(e){if(this.lastError){console.error(this.lastError);const t=e.subarray(0,e.byteLength-1),{written:s}=(new TextEncoder).encodeInto(this.lastError.message,t);e[s]=0}return t}}function K(e,t){const s=e.getUint32(t,!0);if(s){const t=new Uint8Array(e.buffer,s);return(new TextDecoder).decode(t.subarray(0,t.indexOf(0)))}return null}class N{#p;#y=null;#g=Promise.resolve();#f=null;#b=new WeakSet;log=null;static async create(e){const t=await new Promise((t,s)=>{const a=indexedDB.open(e,6);a.onupgradeneeded=async e=>{const t=a.result;switch(e.oldVersion&&console.log(`Upgrading IndexedDB from version ${e.oldVersion}`),e.oldVersion){case 0:t.createObjectStore("blocks",{keyPath:["path","offset","version"]}).createIndex("version",["path","version"]);case 5:const e=a.transaction;e.objectStore("blocks").deleteIndex("version");const s=t.createObjectStore("metadata",{keyPath:"name"});await new Promise((t,a)=>{let r={};const n=e.objectStore("blocks").openCursor();n.onsuccess=()=>{const e=n.result;if(e){const t=e.value;"number"!=typeof t.offset||t.path===r.path&&t.offset===r.offset?e.delete():0===t.offset&&(s.put({name:t.path,fileSize:t.fileSize,version:t.version}),delete t.fileSize,e.update(t)),r=t,e.continue()}else t()},n.onerror=()=>a(n.error)})}},a.onsuccess=()=>t(a.result),a.onerror=()=>s(a.error)});return new N(t)}constructor(e){this.#p=e}close(){this.#p.close()}q(e,t="ro",s={}){const a="ro"===t?"readonly":"readwrite",r=Object.assign({durability:"default"},s);return this.#y=(this.#y||Promise.resolve()).then(()=>this.#w(e,a,r)),this.#y}async#w(e,t,s){let a;this.#f&&this.#b.has(this.#f.transaction)&&this.#f.transaction.mode>=t&&this.#f.transaction.durability===s.durability&&(a=this.#f.transaction,"pending"===this.#f.readyState&&await new Promise(e=>{this.#f.addEventListener("success",e,{once:!0}),this.#f.addEventListener("error",e,{once:!0})}));for(let r=0;r<2;++r){a||(await this.#g,a=this.#p.transaction(this.#p.objectStoreNames,t,s),this.log?.("IDBTransaction open",t),this.#b.add(a),this.#g=new Promise((e,t)=>{a.addEventListener("complete",()=>{this.log?.("IDBTransaction complete"),this.#b.delete(a),e()}),a.addEventListener("abort",()=>{this.#b.delete(a),t(new Error("transaction aborted"))})}));try{const t=[...a.objectStoreNames].map(e=>[e,this.proxyStoreOrIndex(a.objectStore(e))]);return await e(Object.fromEntries(t))}catch(e){if(!r&&_.has(e.name)){this.log?.(`${e.name}, retrying`),a=null;continue}throw e}}}proxyStoreOrIndex(e){return new Proxy(e,{get:(e,t,s)=>{const a=Reflect.get(e,t,s);return"function"==typeof a?(...s)=>{const r=Reflect.apply(a,e,s);return r instanceof IDBRequest&&!t.endsWith("Cursor")?(this.#f=r,r.addEventListener("error",()=>{console.error(r.error),r.transaction.abort()},{once:!0}),n=r,new Promise((e,t)=>{n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})):r;var n}:a}})}async sync(e){this.#y&&(await this.#y,e&&await this.#g,this.reset())}reset(){this.#y=null,this.#g=Promise.resolve(),this.#f=null}}export{W as IDBBatchAtomicVFS,N as IDBContext};
|
|
2
|
-
//# sourceMappingURL=IDBBatchAtomicVFS-BfRzbRoV.js.map
|