@powersync/web 0.0.0-dev-20260917080037 → 0.0.0-dev-20261015114518
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 +64 -6
- package/dist/index.react_native_web.js.map +1 -1
- package/dist/worker/{AccessHandlePoolVFS-BPUHfZME.js → AccessHandlePoolVFS-B9CKqcQ3.js} +2 -2
- package/dist/worker/AccessHandlePoolVFS-B9CKqcQ3.js.map +1 -0
- package/dist/worker/FacadeVFS-d1ZDvud7.js.map +1 -1
- package/dist/worker/IDBBatchAtomicVFS-BfRzbRoV.js +2 -0
- package/dist/worker/IDBBatchAtomicVFS-BfRzbRoV.js.map +1 -0
- package/dist/worker/MemoryVFS-DVJL5F8j.js.map +1 -1
- package/dist/worker/OPFSCoopSyncVFS-BxXAVpVQ.js +2 -0
- package/dist/worker/OPFSCoopSyncVFS-BxXAVpVQ.js.map +1 -0
- package/dist/worker/OPFSWriteAheadVFS-DuqXaOct.js +2 -0
- package/dist/worker/OPFSWriteAheadVFS-DuqXaOct.js.map +1 -0
- package/dist/worker/mc-wa-sqlite-PubB6u8c.js.map +1 -1
- package/dist/worker/mc-wa-sqlite-async-DJG_ANKO.js.map +1 -1
- package/dist/worker/wa-sqlite-D1_4mGs8.js.map +1 -1
- package/dist/worker/wa-sqlite-async-BxkwNY-2.js.map +1 -1
- package/dist/worker/worker.js +1 -1
- package/dist/worker/worker.js.map +1 -1
- package/lib/db/PowerSyncDatabase.js +6 -2
- package/lib/db/PowerSyncDatabase.js.map +1 -1
- package/lib/db/sync/SharedWebStreamingSyncImplementation.d.ts +1 -0
- package/lib/db/sync/SharedWebStreamingSyncImplementation.js +17 -3
- package/lib/db/sync/SharedWebStreamingSyncImplementation.js.map +1 -1
- package/lib/db/sync/WebStreamingSyncImplementation.d.ts +8 -1
- package/lib/db/sync/WebStreamingSyncImplementation.js +14 -0
- package/lib/db/sync/WebStreamingSyncImplementation.js.map +1 -1
- package/lib/devtools/index.d.ts +7 -0
- package/lib/devtools/index.js +8 -0
- package/lib/devtools/index.js.map +1 -0
- package/lib/devtools/registry.d.ts +12 -0
- package/lib/devtools/registry.js +42 -0
- package/lib/devtools/registry.js.map +1 -0
- package/lib/worker/sync/BroadcastLogger.d.ts +1 -4
- package/lib/worker/sync/BroadcastLogger.js +14 -15
- package/lib/worker/sync/BroadcastLogger.js.map +1 -1
- package/lib/worker/sync/SharedSyncImplementation.js +27 -76
- package/lib/worker/sync/SharedSyncImplementation.js.map +1 -1
- package/package.json +12 -8
- package/src/db/PowerSyncDatabase.ts +6 -2
- package/src/db/sync/SharedWebStreamingSyncImplementation.ts +22 -4
- package/src/db/sync/WebStreamingSyncImplementation.ts +18 -0
- package/src/devtools/index.ts +7 -0
- package/src/devtools/registry.ts +53 -0
- package/src/worker/sync/BroadcastLogger.ts +15 -15
- package/src/worker/sync/SharedSyncImplementation.ts +30 -92
- package/dist/worker/AccessHandlePoolVFS-BPUHfZME.js.map +0 -1
- package/dist/worker/IDBBatchAtomicVFS-DbkDb777.js +0 -2
- package/dist/worker/IDBBatchAtomicVFS-DbkDb777.js.map +0 -1
- package/dist/worker/OPFSCoopSyncVFS-BgTiWPfa.js +0 -2
- package/dist/worker/OPFSCoopSyncVFS-BgTiWPfa.js.map +0 -1
- package/dist/worker/OPFSWriteAheadVFS-Rt5CGCZP.js +0 -2
- package/dist/worker/OPFSWriteAheadVFS-Rt5CGCZP.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@powersync/web",
|
|
3
|
-
"version": "0.0.0-dev-
|
|
3
|
+
"version": "0.0.0-dev-20261015114518",
|
|
4
4
|
"description": "PowerSync Web SDK",
|
|
5
5
|
"main": "lib/index.js",
|
|
6
6
|
"module": "lib/index.js",
|
|
@@ -23,6 +23,10 @@
|
|
|
23
23
|
"react-native": "./dist/index.react_native_web.js",
|
|
24
24
|
"default": "./lib/index.js"
|
|
25
25
|
},
|
|
26
|
+
"./devtools": {
|
|
27
|
+
"types": "./lib/devtools/index.d.ts",
|
|
28
|
+
"default": "./lib/devtools/index.js"
|
|
29
|
+
},
|
|
26
30
|
"./extra/shared-memory-pool": {
|
|
27
31
|
"types": "./lib/db/adapters/memory-pool/client.d.ts",
|
|
28
32
|
"default": "./lib/db/adapters/memory-pool/client.js"
|
|
@@ -54,15 +58,15 @@
|
|
|
54
58
|
"author": "PowerSync",
|
|
55
59
|
"license": "Apache-2.0",
|
|
56
60
|
"peerDependencies": {
|
|
57
|
-
"@powersync/common": "
|
|
58
|
-
"@powersync/shared-internals": "0.0.0-dev-
|
|
61
|
+
"@powersync/common": "0.0.0-dev-20261015114518",
|
|
62
|
+
"@powersync/shared-internals": "0.0.0-dev-20261015114518"
|
|
59
63
|
},
|
|
60
64
|
"dependencies": {
|
|
61
|
-
"@journeyapps/wa-sqlite": "2.0.
|
|
65
|
+
"@journeyapps/wa-sqlite": "2.0.7",
|
|
62
66
|
"comlink": "^4.4.2",
|
|
63
67
|
"commander": "^12.1.0",
|
|
64
|
-
"@powersync/common": "
|
|
65
|
-
"@powersync/shared-internals": "0.0.0-dev-
|
|
68
|
+
"@powersync/common": "0.0.0-dev-20261015114518",
|
|
69
|
+
"@powersync/shared-internals": "0.0.0-dev-20261015114518"
|
|
66
70
|
},
|
|
67
71
|
"devDependencies": {
|
|
68
72
|
"@types/uuid": "^9.0.6",
|
|
@@ -71,7 +75,7 @@
|
|
|
71
75
|
"p-defer": "^4.0.1",
|
|
72
76
|
"source-map-loader": "^5.0.0",
|
|
73
77
|
"uuid": "^11.1.0",
|
|
74
|
-
"vite": "^7.3.
|
|
78
|
+
"vite": "^7.3.6",
|
|
75
79
|
"rollup": "^4.52.5",
|
|
76
80
|
"@rollup/plugin-node-resolve": "^16.0.3",
|
|
77
81
|
"@rollup/plugin-terser": "^1.0.0",
|
|
@@ -85,6 +89,6 @@
|
|
|
85
89
|
"clean": "rm -rf lib dist tsconfig.tsbuildinfo",
|
|
86
90
|
"watch": "tsc --build -w",
|
|
87
91
|
"test": "pnpm build && vitest",
|
|
88
|
-
"test:exports": "attw --pack . --entrypoints . extra/shared-memory-pool --profile=esm-only "
|
|
92
|
+
"test:exports": "attw --pack . --entrypoints . devtools extra/shared-memory-pool --profile=esm-only "
|
|
89
93
|
}
|
|
90
94
|
}
|
|
@@ -30,6 +30,7 @@ import { WebStreamingSyncImplementationOptions } from './sync/WebStreamingSyncIm
|
|
|
30
30
|
import { AsyncDbAdapter } from './adapters/AsyncWebAdapter.js';
|
|
31
31
|
import { resolveAndValidateOptions } from './adapters/resolveAndValidateOptions.js';
|
|
32
32
|
import { TabLocalStreamingSyncImplementation } from './sync/TabLocalStreamingSyncImplementation.js';
|
|
33
|
+
import { registerDatabase, unregisterDatabase } from '../devtools/registry.js';
|
|
33
34
|
|
|
34
35
|
export type WebPowerSyncDatabaseOptions = BasePowerSyncDatabaseOptions &
|
|
35
36
|
DatabaseSource<WebSQLOpenOptions> &
|
|
@@ -77,6 +78,8 @@ export class WebPowerSyncDatabase extends BasePowerSyncDatabase<WebPowerSyncData
|
|
|
77
78
|
super(options);
|
|
78
79
|
this.resolvedOpenOptions = resolvedOpenOptions;
|
|
79
80
|
this.enableBroadcastLogs = options.broadcastLogs ?? true;
|
|
81
|
+
// Lets development tooling in this page find the live databases.
|
|
82
|
+
registerDatabase(this);
|
|
80
83
|
}
|
|
81
84
|
|
|
82
85
|
async _initialize(): Promise<void> {
|
|
@@ -122,11 +125,12 @@ export class WebPowerSyncDatabase extends BasePowerSyncDatabase<WebPowerSyncData
|
|
|
122
125
|
* By default the sync stream client is only disconnected if
|
|
123
126
|
* multiple tabs are not enabled.
|
|
124
127
|
*/
|
|
125
|
-
close(options?: PowerSyncCloseOptions): Promise<void> {
|
|
126
|
-
|
|
128
|
+
async close(options?: PowerSyncCloseOptions): Promise<void> {
|
|
129
|
+
await super.close({
|
|
127
130
|
// Don't disconnect by default if multiple tabs are enabled
|
|
128
131
|
disconnect: options?.disconnect ?? !this.resolvedOpenOptions.enableMultiTabs
|
|
129
132
|
});
|
|
133
|
+
unregisterDatabase(this);
|
|
130
134
|
}
|
|
131
135
|
|
|
132
136
|
protected async loadVersion(): Promise<void> {
|
|
@@ -9,7 +9,12 @@ import {
|
|
|
9
9
|
WebStreamingSyncImplementationOptions
|
|
10
10
|
} from './WebStreamingSyncImplementation.js';
|
|
11
11
|
import { generateTabCloseSignal } from '../../shared/tab_close_signal.js';
|
|
12
|
-
import {
|
|
12
|
+
import {
|
|
13
|
+
SubscribedStream,
|
|
14
|
+
SyncStatusJson,
|
|
15
|
+
ResolvedSyncOptions,
|
|
16
|
+
serializeErrorForRelay
|
|
17
|
+
} from '@powersync/shared-internals';
|
|
13
18
|
import { connectToExistingWorker, connectToWorker, WorkerConnection } from '../../worker/client.js';
|
|
14
19
|
|
|
15
20
|
/**
|
|
@@ -30,12 +35,25 @@ class SharedSyncClientProvider extends AbstractSharedSyncClientProvider {
|
|
|
30
35
|
return Comlink.transfer(port, [port]);
|
|
31
36
|
}
|
|
32
37
|
|
|
38
|
+
async #relay<T>(action: () => Promise<T>): Promise<T> {
|
|
39
|
+
try {
|
|
40
|
+
return await action();
|
|
41
|
+
} catch (ex) {
|
|
42
|
+
/**
|
|
43
|
+
* Connector callbacks run in this tab and their rejection crosses the
|
|
44
|
+
* MessagePort to the sync worker, so serialize it here, where the error
|
|
45
|
+
* originates, before Comlink's error transfer can drop custom fields.
|
|
46
|
+
*/
|
|
47
|
+
throw serializeErrorForRelay(ex);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
33
51
|
invalidateCredentials() {
|
|
34
52
|
this.options.remote.invalidateCredentials();
|
|
35
53
|
}
|
|
36
54
|
|
|
37
55
|
async fetchCredentials(): Promise<PowerSyncCredentials | null> {
|
|
38
|
-
const credentials = await this.options.remote.getCredentials();
|
|
56
|
+
const credentials = await this.#relay(() => this.options.remote.getCredentials());
|
|
39
57
|
if (credentials == null) {
|
|
40
58
|
return null;
|
|
41
59
|
}
|
|
@@ -56,11 +74,11 @@ class SharedSyncClientProvider extends AbstractSharedSyncClientProvider {
|
|
|
56
74
|
* Don't return anything here, just incase something which is not
|
|
57
75
|
* serializable is returned from the `uploadCrud` function.
|
|
58
76
|
*/
|
|
59
|
-
await this.options.uploadCrud();
|
|
77
|
+
await this.#relay(() => this.options.uploadCrud());
|
|
60
78
|
}
|
|
61
79
|
|
|
62
80
|
override async postCheckpointRequest(clientId: string, requestId: string): Promise<string | null> {
|
|
63
|
-
return await this.options.postCheckpointRequest(clientId, requestId);
|
|
81
|
+
return await this.#relay(async () => (await this.options.postCheckpointRequest!(clientId, requestId)) ?? null);
|
|
64
82
|
}
|
|
65
83
|
|
|
66
84
|
get logger() {
|
|
@@ -2,6 +2,7 @@ import { LogLevels } from '@powersync/common';
|
|
|
2
2
|
import {
|
|
3
3
|
AbstractStreamingSyncImplementation,
|
|
4
4
|
AbstractStreamingSyncImplementationOptions,
|
|
5
|
+
DiagnosticsEvent,
|
|
5
6
|
LockOptions,
|
|
6
7
|
LockType
|
|
7
8
|
} from '@powersync/shared-internals';
|
|
@@ -14,11 +15,28 @@ export interface WebStreamingSyncImplementationOptions extends AbstractStreaming
|
|
|
14
15
|
}
|
|
15
16
|
|
|
16
17
|
export class WebStreamingSyncImplementation extends AbstractStreamingSyncImplementation {
|
|
18
|
+
private diagnosticsChannel?: BroadcastChannel;
|
|
19
|
+
|
|
17
20
|
constructor(options: WebStreamingSyncImplementationOptions) {
|
|
18
21
|
// Super will store and provide default values for options
|
|
19
22
|
super(options);
|
|
20
23
|
}
|
|
21
24
|
|
|
25
|
+
/**
|
|
26
|
+
* Broadcasts a core diagnostics event on a same-origin channel for diagnostics tooling to consume.
|
|
27
|
+
* The channel reaches the page even when sync runs in a shared worker.
|
|
28
|
+
*/
|
|
29
|
+
protected override emitDiagnostics(event: DiagnosticsEvent): void {
|
|
30
|
+
this.diagnosticsChannel ??= new BroadcastChannel('powersync-diagnostics-events');
|
|
31
|
+
this.diagnosticsChannel.postMessage(event);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
override async dispose(): Promise<void> {
|
|
35
|
+
await super.dispose();
|
|
36
|
+
this.diagnosticsChannel?.close();
|
|
37
|
+
this.diagnosticsChannel = undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
22
40
|
get webOptions(): WebStreamingSyncImplementationOptions {
|
|
23
41
|
return this.options as WebStreamingSyncImplementationOptions;
|
|
24
42
|
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Development-tooling entry point (`@powersync/web/devtools`).
|
|
3
|
+
*
|
|
4
|
+
* Kept off the main index so the public API of `@powersync/web` is unchanged; tooling imports this
|
|
5
|
+
* subpath explicitly.
|
|
6
|
+
*/
|
|
7
|
+
export { getRegisteredDatabases, observeRegisteredDatabases } from './registry.js';
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { BaseObserver, type BaseListener } from '@powersync/common';
|
|
2
|
+
import type { WebPowerSyncDatabase } from '../db/PowerSyncDatabase.js';
|
|
3
|
+
|
|
4
|
+
interface RegistryListener extends BaseListener {
|
|
5
|
+
databasesChanged: (databases: readonly WebPowerSyncDatabase[]) => void;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Live database instances in this page, for development tooling.
|
|
10
|
+
*
|
|
11
|
+
* Every {@link WebPowerSyncDatabase} registers itself when constructed and leaves when closed, so a
|
|
12
|
+
* tool that runs in the same page (for example the diagnostics Vite plugin's injected agent) can find
|
|
13
|
+
* the app's databases without the app wiring anything up. The set holds only instances that already
|
|
14
|
+
* exist, so it adds nothing to a production bundle beyond the references themselves.
|
|
15
|
+
*/
|
|
16
|
+
class DatabaseRegistry extends BaseObserver<RegistryListener> {
|
|
17
|
+
readonly databases = new Set<WebPowerSyncDatabase>();
|
|
18
|
+
|
|
19
|
+
notify(): void {
|
|
20
|
+
const snapshot = [...this.databases];
|
|
21
|
+
this.iterateListeners((listener) => listener.databasesChanged?.(snapshot));
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const registry = new DatabaseRegistry();
|
|
26
|
+
|
|
27
|
+
/** @internal Called by the database constructor. */
|
|
28
|
+
export function registerDatabase(db: WebPowerSyncDatabase): void {
|
|
29
|
+
registry.databases.add(db);
|
|
30
|
+
registry.notify();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** @internal Called when the database closes. */
|
|
34
|
+
export function unregisterDatabase(db: WebPowerSyncDatabase): void {
|
|
35
|
+
if (registry.databases.delete(db)) {
|
|
36
|
+
registry.notify();
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The databases currently open in this page. */
|
|
41
|
+
export function getRegisteredDatabases(): readonly WebPowerSyncDatabase[] {
|
|
42
|
+
return [...registry.databases];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Calls `listener` with the current databases now, and again whenever one is opened or closed.
|
|
47
|
+
* Returns a function that stops listening.
|
|
48
|
+
*/
|
|
49
|
+
export function observeRegisteredDatabases(listener: (databases: readonly WebPowerSyncDatabase[]) => void): () => void {
|
|
50
|
+
const stop = registry.registerListener({ databasesChanged: listener });
|
|
51
|
+
listener([...registry.databases]);
|
|
52
|
+
return stop;
|
|
53
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { PowerSyncLogger, LogLevels, CreateLoggerOptions, createConsoleLogger, LogRecord } from '@powersync/common';
|
|
2
|
+
import { serializeErrorForRelay } from '@powersync/shared-internals';
|
|
2
3
|
import { type WrappedSyncPort } from './SharedSyncImplementation.js';
|
|
3
4
|
|
|
4
5
|
/**
|
|
@@ -8,6 +9,8 @@ export class BroadcastLogger implements PowerSyncLogger {
|
|
|
8
9
|
private readonly inner: PowerSyncLogger & CreateLoggerOptions;
|
|
9
10
|
private currentLevel: number = LogLevels.info;
|
|
10
11
|
|
|
12
|
+
private sequence = 0;
|
|
13
|
+
|
|
11
14
|
sendBroadcasts = true;
|
|
12
15
|
|
|
13
16
|
constructor(
|
|
@@ -48,27 +51,24 @@ export class BroadcastLogger implements PowerSyncLogger {
|
|
|
48
51
|
}
|
|
49
52
|
}
|
|
50
53
|
|
|
51
|
-
/**
|
|
52
|
-
* Guards against any logging errors.
|
|
53
|
-
* We don't want a logging exception to cause further issues upstream
|
|
54
|
-
*/
|
|
55
54
|
protected sanitizeRecord(record: LogRecord): LogRecord {
|
|
56
|
-
|
|
55
|
+
// Preserve explicit undefined rejection reasons.
|
|
56
|
+
if (!('error' in record)) {
|
|
57
57
|
return record;
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
-
|
|
61
|
-
try {
|
|
62
|
-
// Try and clone here first. If it fails it won't be passable over a MessagePort
|
|
63
|
-
error = structuredClone(record.error);
|
|
64
|
-
} catch (ex) {
|
|
65
|
-
console.error(ex);
|
|
66
|
-
error = 'Could not serialize log params. Check shared worker logs for more details.';
|
|
67
|
-
}
|
|
68
|
-
|
|
60
|
+
const serialized = serializeErrorForRelay(record.error);
|
|
69
61
|
return {
|
|
70
62
|
...record,
|
|
71
|
-
error
|
|
63
|
+
error: {
|
|
64
|
+
...serialized,
|
|
65
|
+
relay: {
|
|
66
|
+
origin: 'shared-sync-worker',
|
|
67
|
+
sequence: this.sequence++,
|
|
68
|
+
errorState: serialized.state,
|
|
69
|
+
relayedAt: new Date().toISOString()
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
72
|
};
|
|
73
73
|
}
|
|
74
74
|
}
|
|
@@ -92,23 +92,6 @@ export type WrappedSyncPort = {
|
|
|
92
92
|
*/
|
|
93
93
|
const CONNECTOR_PLACEHOLDER = {} as PowerSyncBackendConnector;
|
|
94
94
|
|
|
95
|
-
/**
|
|
96
|
-
* How long to wait for a client tab to answer a call before giving up on it.
|
|
97
|
-
*/
|
|
98
|
-
const CONNECTOR_CALL_TIMEOUT_MS = 30_000;
|
|
99
|
-
|
|
100
|
-
type UseConnectorOptions = {
|
|
101
|
-
/**
|
|
102
|
-
* Aborted when the sync client disconnects.
|
|
103
|
-
*/
|
|
104
|
-
signal?: AbortSignal;
|
|
105
|
-
/**
|
|
106
|
-
* Fail the call if the tab has not responded within this many milliseconds. `null` waits indefinitely, which is only
|
|
107
|
-
* appropriate for calls that are unbounded by nature and already covered by {@link UseConnectorOptions.signal}.
|
|
108
|
-
*/
|
|
109
|
-
timeoutMs?: number | null;
|
|
110
|
-
};
|
|
111
|
-
|
|
112
95
|
/**
|
|
113
96
|
* @internal
|
|
114
97
|
* Shared sync implementation which runs inside a shared webworker
|
|
@@ -167,11 +150,8 @@ export class SharedSyncImplementation extends BaseObserver<SharedSyncImplementat
|
|
|
167
150
|
onDispose: () => {
|
|
168
151
|
removeStatusListener();
|
|
169
152
|
|
|
170
|
-
//
|
|
171
|
-
//
|
|
172
|
-
// so a `downloadError` left here is shown by tabs that never saw the failure, and nothing can clear it
|
|
173
|
-
// because only a completed sync does. The core status is kept - `hasSynced` and `lastSyncedAt` are
|
|
174
|
-
// persisted facts that remain true while disconnected.
|
|
153
|
+
// Clear transient state so new tabs don't inherit stale errors.
|
|
154
|
+
// Preserve core status, including hasSynced and lastSyncedAt.
|
|
175
155
|
this.syncStatus &&= new SyncStatusSnapshot(this.syncStatus.core, {});
|
|
176
156
|
}
|
|
177
157
|
};
|
|
@@ -412,7 +392,9 @@ export class SharedSyncImplementation extends BaseObserver<SharedSyncImplementat
|
|
|
412
392
|
this.logger.log({ level: LogLevels.error, message: 'error invalidating credentials', error });
|
|
413
393
|
}
|
|
414
394
|
},
|
|
415
|
-
fetchCredentials: (
|
|
395
|
+
fetchCredentials: (
|
|
396
|
+
signal?: AbortSignal
|
|
397
|
+
) => {
|
|
416
398
|
return this.#useConnector(
|
|
417
399
|
(port) => {
|
|
418
400
|
this.logger.log({
|
|
@@ -423,26 +405,20 @@ export class SharedSyncImplementation extends BaseObserver<SharedSyncImplementat
|
|
|
423
405
|
return port.clientProvider.fetchCredentials();
|
|
424
406
|
},
|
|
425
407
|
'fetchCredentials',
|
|
426
|
-
|
|
427
|
-
{ timeoutMs: CONNECTOR_CALL_TIMEOUT_MS }
|
|
408
|
+
signal
|
|
428
409
|
);
|
|
429
410
|
}
|
|
430
411
|
},
|
|
431
412
|
this.logger
|
|
432
413
|
),
|
|
433
414
|
uploadCrud: (signal) => {
|
|
434
|
-
return this.#useConnector((port) => port.clientProvider.uploadCrud(), 'uploadCrud',
|
|
435
|
-
signal,
|
|
436
|
-
// Uploads are user-defined and legitimately unbounded (large batches over slow connections), so a timeout
|
|
437
|
-
// would cut valid work short. Disconnecting aborts the signal, which is what releases this.
|
|
438
|
-
timeoutMs: null
|
|
439
|
-
});
|
|
415
|
+
return this.#useConnector((port) => port.clientProvider.uploadCrud(), 'uploadCrud', signal);
|
|
440
416
|
},
|
|
441
417
|
postCheckpointRequest: (clientId, requestId, signal) => {
|
|
442
418
|
return this.#useConnector(
|
|
443
419
|
(port) => port.clientProvider.postCheckpointRequest(clientId, requestId),
|
|
444
420
|
'postCheckpointRequest',
|
|
445
|
-
|
|
421
|
+
signal
|
|
446
422
|
);
|
|
447
423
|
},
|
|
448
424
|
...syncParams.streamOptions,
|
|
@@ -453,76 +429,39 @@ export class SharedSyncImplementation extends BaseObserver<SharedSyncImplementat
|
|
|
453
429
|
}
|
|
454
430
|
|
|
455
431
|
/**
|
|
456
|
-
* Calls into a client tab.
|
|
457
|
-
*
|
|
458
|
-
* A tab can stop servicing its message port without ever closing it: it may be frozen or in the back/forward cache,
|
|
459
|
-
* or its sync implementation may have been abandoned without being disposed. Comlink has no timeout of its own, so a
|
|
460
|
-
* call to such a port settles neither way, and the `closeListeners` below only fire for ports we know have closed.
|
|
461
|
-
*
|
|
462
|
-
* That is not a local problem. `disconnect()` awaits the sync loops, so a single call that can never settle wedges
|
|
463
|
-
* the disconnect, and with it every `connect()` queued behind it. Every call is therefore bounded by the caller's
|
|
464
|
-
* abort signal, a timeout, or both.
|
|
432
|
+
* Calls into a client tab, stopping the wait on disconnect when a signal is supplied.
|
|
465
433
|
*/
|
|
466
434
|
async #useConnector<T>(
|
|
467
435
|
inner: (port: WrappedSyncPort) => Promise<T>,
|
|
468
436
|
debugContext: string,
|
|
469
|
-
|
|
437
|
+
signal?: AbortSignal
|
|
470
438
|
): Promise<T> {
|
|
471
|
-
const
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
if (controller.signal.aborted) {
|
|
476
|
-
return;
|
|
439
|
+
const action = async () => {
|
|
440
|
+
const lastPort = await this.getLastWrappedPort();
|
|
441
|
+
if (!lastPort) {
|
|
442
|
+
throw new Error(`No client port found for ${debugContext}`);
|
|
477
443
|
}
|
|
478
|
-
this.logger.log({ level: LogLevels.warn, message: `Aborting ${debugContext}: ${reason}` });
|
|
479
|
-
controller.abort(new AbortOperation(`Aborted ${debugContext}: ${reason}`));
|
|
480
|
-
};
|
|
481
|
-
|
|
482
|
-
const timeout =
|
|
483
|
-
timeoutMs == null
|
|
484
|
-
? undefined
|
|
485
|
-
: setTimeout(() => abortWith(`the client tab did not respond within ${timeoutMs}ms`), timeoutMs);
|
|
486
444
|
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
try {
|
|
494
|
-
return await withAbort({
|
|
495
|
-
signal: controller.signal,
|
|
496
|
-
// Resolving the port takes the portMutex, which is held while other ports are being removed, so it has to be
|
|
497
|
-
// inside the guard as well.
|
|
498
|
-
action: async () => {
|
|
499
|
-
const lastPort = await this.getLastWrappedPort();
|
|
500
|
-
if (!lastPort) {
|
|
501
|
-
throw new Error(`No client port found for ${debugContext}`);
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
return await new Promise<T>((resolve, reject) => {
|
|
505
|
-
const portClosed = () => {
|
|
506
|
-
reject(new Error(`Tab closed while handling ${debugContext}`));
|
|
507
|
-
};
|
|
445
|
+
return await new Promise<T>((resolve, reject) => {
|
|
446
|
+
const portClosed = () => {
|
|
447
|
+
reject(new Error(`Tab closed while handling ${debugContext}`));
|
|
448
|
+
};
|
|
508
449
|
|
|
509
|
-
|
|
450
|
+
lastPort.closeListeners.push(portClosed);
|
|
510
451
|
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
});
|
|
452
|
+
inner(lastPort)
|
|
453
|
+
.then(resolve, reject)
|
|
454
|
+
.finally(() => {
|
|
455
|
+
const index = lastPort.closeListeners.indexOf(portClosed);
|
|
456
|
+
if (index >= 0) {
|
|
457
|
+
lastPort.closeListeners.splice(index, 1);
|
|
458
|
+
}
|
|
519
459
|
});
|
|
520
|
-
}
|
|
521
460
|
});
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
}
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
// Include port lookup in the guard: port removal can hold portMutex.
|
|
464
|
+
return signal ? withAbort({ signal, action }) : action();
|
|
526
465
|
}
|
|
527
466
|
|
|
528
467
|
/**
|
|
@@ -708,7 +647,6 @@ function withAbort<T>(options: {
|
|
|
708
647
|
cleanupOnAbort?: (result: T) => void;
|
|
709
648
|
}): Promise<T> {
|
|
710
649
|
const { action, signal, cleanupOnAbort } = options;
|
|
711
|
-
// Callers that abort with an `Error` reason get it propagated, so the failure says what actually went wrong.
|
|
712
650
|
const abortError = () =>
|
|
713
651
|
signal.reason instanceof Error ? signal.reason : new AbortOperation('Operation aborted by abort controller');
|
|
714
652
|
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"AccessHandlePoolVFS-BPUHfZME.js","sources":["../../../../node_modules/.pnpm/@journeyapps+wa-sqlite@2.0.4/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 await Promise.all(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 }\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","Promise","all","map","async","getAssociatedPath","add","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,GACAC,GAKAC,GAAyB,IAAIC,IAK7BC,GAAyB,IAAID,IAC7BE,GAA0B,IAAIC,IAE9BC,GAAe,IAAIJ,IAEnB,mBAAaK,CAAOC,EAAMC,GACxB,MAAMC,EAAM,IAAId,EAAoBY,EAAMC,GAE1C,aADMC,EAAIC,UACHD,CACT,CAEA,WAAAE,CAAYJ,EAAMC,GAChBI,MAAML,EAAMC,GACZK,MAAKf,EAAiBS,CACxB,CASA,KAAAO,CAAMC,EAAOC,EAAQC,EAAOC,GAC1B,IAEE,MAAMC,EAAOJ,EAAQF,MAAKO,EAASL,GAASM,KAAKC,SAASC,SAAS,IACnE,IAAIC,EAAeX,MAAKX,EAAuBuB,IAAIN,GACnD,IAAKK,GAAiBP,EAAQS,EAAyB,CAErD,KAAIb,KAAKc,UAAYd,KAAKe,eAOxB,MAAM,IAAIC,MAAM,uBALdL,GAAgBX,MAAKV,EAAwB2B,OAC/CjB,MAAKkB,EAAmBP,EAAcL,EAAMF,EAMhD,CACA,IAAKO,EACH,MAAM,IAAIK,MAAM,kBAIlB,MAAMG,EAAO,CAAEb,OAAMF,QAAOO,gBAI5B,OAHAX,MAAKR,EAAa4B,IAAIjB,EAAQgB,GAE9Bd,EAAUgB,SAAS,EAAGjB,GAAO,GACtBkB,CACT,CAAE,MAAOC,GAEP,OADAC,QAAQC,MAAMF,EAAEG,SACTC,CACT,CACF,CAMA,MAAAC,CAAOzB,GACL,MAAMgB,EAAOnB,MAAKR,EAAaoB,IAAIT,GAQnC,OAPIgB,IACFA,EAAKR,aAAakB,QAClB7B,MAAKR,EAAasC,OAAO3B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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 C,E as R,F as L}from"./worker.js";const F={mode:"shared"},M={ifAvailable:!0,mode:"shared"},D={ifAvailable:!0,mode:"exclusive"},z=["exclusive","shared","shared+hint"],B=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===z.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===B.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})})}};B.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(B(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 U.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&&await this.#d.sync(!1),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=IDBKeyRange.bound([r.path,-a],[r.path,1/0]),s=await e.get(t);s.data.subarray(a+s.offset).set(n),e.put(s)},"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=N(a,4),n=N(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,B.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,C}return super.jFileControl(e,s,a)}jDeviceCharacteristics(e){return 0|R|L}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 N(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 U{#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 U(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,U as IDBContext};
|
|
2
|
-
//# sourceMappingURL=IDBBatchAtomicVFS-DbkDb777.js.map
|