@evolu/web 2.4.0 → 3.0.0-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/src/Platform.d.ts +3 -0
- package/dist/src/Platform.d.ts.map +1 -0
- package/dist/src/{local-first/Platform.js → Platform.js} +1 -1
- package/dist/src/Sqlite.d.ts +3 -0
- package/dist/src/Sqlite.d.ts.map +1 -0
- package/dist/src/Sqlite.js +162 -0
- package/dist/src/Task.d.ts +29 -0
- package/dist/src/Task.d.ts.map +1 -0
- package/dist/src/Task.js +38 -0
- package/dist/src/Worker.d.ts +60 -0
- package/dist/src/Worker.d.ts.map +1 -0
- package/dist/src/Worker.js +328 -0
- package/dist/src/index.d.ts +3 -3
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +3 -3
- package/dist/src/local-first/Db.worker.js +13 -10
- package/dist/src/local-first/Evolu.d.ts +11 -0
- package/dist/src/local-first/Evolu.d.ts.map +1 -0
- package/dist/src/local-first/Evolu.js +57 -0
- package/dist/src/local-first/LocalAuth.d.ts +2 -3
- package/dist/src/local-first/LocalAuth.d.ts.map +1 -1
- package/dist/src/local-first/LocalAuth.js +60 -71
- package/dist/src/local-first/Shared.worker.d.ts +2 -0
- package/dist/src/local-first/Shared.worker.d.ts.map +1 -0
- package/dist/src/local-first/Shared.worker.js +94 -0
- package/dist/src/local-first/index.d.ts +1 -3
- package/dist/src/local-first/index.d.ts.map +1 -1
- package/dist/src/local-first/index.js +1 -20
- package/package.json +16 -16
- package/src/Platform.ts +9 -0
- package/src/Sqlite.ts +138 -0
- package/src/Task.ts +59 -0
- package/src/Worker.ts +319 -0
- package/src/index.ts +3 -3
- package/src/local-first/Db.worker.ts +16 -16
- package/src/local-first/Evolu.ts +104 -0
- package/src/local-first/LocalAuth.ts +93 -105
- package/src/local-first/Shared.worker.ts +58 -0
- package/src/local-first/index.ts +1 -41
- package/dist/src/SharedWebWorker.d.ts +0 -30
- package/dist/src/SharedWebWorker.d.ts.map +0 -1
- package/dist/src/SharedWebWorker.js +0 -104
- package/dist/src/WasmSqliteDriver.d.ts +0 -3
- package/dist/src/WasmSqliteDriver.d.ts.map +0 -1
- package/dist/src/WasmSqliteDriver.js +0 -85
- package/dist/src/WebWorker.d.ts +0 -17
- package/dist/src/WebWorker.d.ts.map +0 -1
- package/dist/src/WebWorker.js +0 -42
- package/dist/src/local-first/Platform.d.ts +0 -3
- package/dist/src/local-first/Platform.d.ts.map +0 -1
- package/dist/test/SharedWebWorker.test.d.ts +0 -2
- package/dist/test/SharedWebWorker.test.d.ts.map +0 -1
- package/dist/test/SharedWebWorker.test.js +0 -248
- package/src/SharedWebWorker.ts +0 -149
- package/src/WasmSqliteDriver.ts +0 -118
- package/src/WebWorker.ts +0 -54
- package/src/local-first/Platform.ts +0 -9
|
@@ -1,29 +1,27 @@
|
|
|
1
|
-
import { set, get, del, keys, clear, createStore } from "idb-keyval";
|
|
2
|
-
|
|
3
|
-
import {
|
|
4
|
-
createSlip21,
|
|
5
|
-
utf8ToBytes,
|
|
6
|
-
bytesToUtf8,
|
|
7
|
-
base64UrlToUint8Array,
|
|
8
|
-
uint8ArrayToBase64Url,
|
|
9
|
-
EncryptionKey,
|
|
10
|
-
Base64Url,
|
|
11
|
-
} from "@evolu/common";
|
|
12
|
-
|
|
13
1
|
import type {
|
|
14
2
|
AuthResult,
|
|
15
3
|
Entropy32,
|
|
16
|
-
SensitiveInfoItem,
|
|
17
|
-
SecureStorage,
|
|
18
4
|
RandomBytesDep,
|
|
19
|
-
|
|
5
|
+
SecureStorage,
|
|
6
|
+
SensitiveInfoItem,
|
|
7
|
+
} from "@evolu/common";
|
|
8
|
+
import {
|
|
9
|
+
Base64Url,
|
|
10
|
+
base64UrlToUint8Array,
|
|
11
|
+
bytesToUtf8,
|
|
12
|
+
createSlip21,
|
|
13
|
+
decryptWithXChaCha20Poly1305,
|
|
14
|
+
EncryptionKey,
|
|
15
|
+
encryptWithXChaCha20Poly1305,
|
|
16
|
+
Entropy24,
|
|
17
|
+
uint8ArrayToBase64Url,
|
|
18
|
+
utf8ToBytes,
|
|
19
|
+
XChaCha20Poly1305Ciphertext,
|
|
20
20
|
} from "@evolu/common";
|
|
21
21
|
import type { UseStore } from "idb-keyval";
|
|
22
|
+
import { clear, createStore, del, get, keys, set } from "idb-keyval";
|
|
22
23
|
|
|
23
|
-
|
|
24
|
-
export const createWebAuthnStore = (
|
|
25
|
-
deps: RandomBytesDep & SymmetricCryptoDep,
|
|
26
|
-
): SecureStorage => ({
|
|
24
|
+
export const createWebAuthnStore = (deps: RandomBytesDep): SecureStorage => ({
|
|
27
25
|
setItem: async (key, value, options) => {
|
|
28
26
|
if (options?.accessControl === "none") {
|
|
29
27
|
const metadata = createMetadata(false);
|
|
@@ -86,7 +84,7 @@ export const createWebAuthnStore = (
|
|
|
86
84
|
);
|
|
87
85
|
const credentialSeed = extractSeedFromCredential(credential);
|
|
88
86
|
const encryptionKey = deriveEncryptionKey(credentialSeed);
|
|
89
|
-
const authResultVal = decryptAuthResult(
|
|
87
|
+
const authResultVal = decryptAuthResult(data, encryptionKey);
|
|
90
88
|
if (!authResultVal) {
|
|
91
89
|
return null;
|
|
92
90
|
}
|
|
@@ -137,19 +135,16 @@ export const createWebAuthnStore = (
|
|
|
137
135
|
* Create default metadata for backwards compatibility with items that don't
|
|
138
136
|
* have stored metadata.
|
|
139
137
|
*/
|
|
140
|
-
const createMetadata = (isSecure = true): SensitiveInfoItem["metadata"] => {
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
};
|
|
147
|
-
};
|
|
138
|
+
const createMetadata = (isSecure = true): SensitiveInfoItem["metadata"] => ({
|
|
139
|
+
backend: "keychain",
|
|
140
|
+
accessControl: isSecure ? "biometryCurrentSet" : "none",
|
|
141
|
+
securityLevel: isSecure ? "biometry" : "software",
|
|
142
|
+
timestamp: Date.now(),
|
|
143
|
+
});
|
|
148
144
|
|
|
149
145
|
/** Get storage key for owner ID. (supports namespaces via prefix) */
|
|
150
|
-
const getStore = (prefix = "default"): UseStore =>
|
|
151
|
-
|
|
152
|
-
};
|
|
146
|
+
const getStore = (prefix = "default"): UseStore =>
|
|
147
|
+
createStore(prefix, "evolu-auth");
|
|
153
148
|
|
|
154
149
|
const createCredential =
|
|
155
150
|
(deps: RandomBytesDep) =>
|
|
@@ -218,43 +213,41 @@ const createCredentialCreationOptions =
|
|
|
218
213
|
relyingPartyName?: string,
|
|
219
214
|
userVerification?: UserVerificationRequirement,
|
|
220
215
|
authenticatorAttachment?: AuthenticatorAttachment,
|
|
221
|
-
): CredentialCreationOptions => {
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
name: relyingPartyName ?? "Evolu",
|
|
228
|
-
},
|
|
229
|
-
user: {
|
|
230
|
-
id: seed as BufferSource,
|
|
231
|
-
name: username,
|
|
232
|
-
displayName: username,
|
|
233
|
-
},
|
|
234
|
-
pubKeyCredParams: [
|
|
235
|
-
{ type: "public-key", alg: -8 }, // Ed25519
|
|
236
|
-
{ type: "public-key", alg: -7 }, // ES256
|
|
237
|
-
{ type: "public-key", alg: -257 }, // RS256
|
|
238
|
-
],
|
|
239
|
-
attestation: "none",
|
|
240
|
-
authenticatorSelection: {
|
|
241
|
-
// - "platform": Uses the platform's built-in authenticator.
|
|
242
|
-
// - "cross-platform": Uses a device specific authenticator (yubikey, fido2, etc.)
|
|
243
|
-
authenticatorAttachment: authenticatorAttachment ?? "platform",
|
|
244
|
-
// - "discouraged": Only User Presence is needed.
|
|
245
|
-
// - "preferred": User Verification is preferred but not required. Falls back to User Presence.
|
|
246
|
-
// - "required": User Verification MUST occur (biometrics/PIN). Clients may silently downgrade to User Presence only.
|
|
247
|
-
userVerification: userVerification ?? "required",
|
|
248
|
-
// - "discouraged": Server-side credential is preferable, but will accept client-side discoverable credential.
|
|
249
|
-
// - "preferred": Relying Party strongly prefers client-side discoverable credential but will accept server-side credential.
|
|
250
|
-
// - "required": Client-side discoverable credential MUST be created, error if it can't be created.
|
|
251
|
-
residentKey: "required",
|
|
252
|
-
// Included for backwards compatibility. Deprecated in favor of residentKey (true = "required")
|
|
253
|
-
requireResidentKey: true,
|
|
254
|
-
},
|
|
216
|
+
): CredentialCreationOptions => ({
|
|
217
|
+
publicKey: {
|
|
218
|
+
challenge: generateSeed(deps)() as BufferSource,
|
|
219
|
+
rp: {
|
|
220
|
+
id: relyingPartyID ?? document.location.hostname,
|
|
221
|
+
name: relyingPartyName ?? "Evolu",
|
|
255
222
|
},
|
|
256
|
-
|
|
257
|
-
|
|
223
|
+
user: {
|
|
224
|
+
id: seed as BufferSource,
|
|
225
|
+
name: username,
|
|
226
|
+
displayName: username,
|
|
227
|
+
},
|
|
228
|
+
pubKeyCredParams: [
|
|
229
|
+
{ type: "public-key", alg: -8 }, // Ed25519
|
|
230
|
+
{ type: "public-key", alg: -7 }, // ES256
|
|
231
|
+
{ type: "public-key", alg: -257 }, // RS256
|
|
232
|
+
],
|
|
233
|
+
attestation: "none",
|
|
234
|
+
authenticatorSelection: {
|
|
235
|
+
// - "platform": Uses the platform's built-in authenticator.
|
|
236
|
+
// - "cross-platform": Uses a device specific authenticator (yubikey, fido2, etc.)
|
|
237
|
+
authenticatorAttachment: authenticatorAttachment ?? "platform",
|
|
238
|
+
// - "discouraged": Only User Presence is needed.
|
|
239
|
+
// - "preferred": User Verification is preferred but not required. Falls back to User Presence.
|
|
240
|
+
// - "required": User Verification MUST occur (biometrics/PIN). Clients may silently downgrade to User Presence only.
|
|
241
|
+
userVerification: userVerification ?? "required",
|
|
242
|
+
// - "discouraged": Server-side credential is preferable, but will accept client-side discoverable credential.
|
|
243
|
+
// - "preferred": Relying Party strongly prefers client-side discoverable credential but will accept server-side credential.
|
|
244
|
+
// - "required": Client-side discoverable credential MUST be created, error if it can't be created.
|
|
245
|
+
residentKey: "required",
|
|
246
|
+
// Included for backwards compatibility. Deprecated in favor of residentKey (true = "required")
|
|
247
|
+
requireResidentKey: true,
|
|
248
|
+
},
|
|
249
|
+
},
|
|
250
|
+
});
|
|
258
251
|
|
|
259
252
|
const createCredentialRequestOptions =
|
|
260
253
|
(deps: RandomBytesDep) =>
|
|
@@ -262,23 +255,21 @@ const createCredentialRequestOptions =
|
|
|
262
255
|
credentialId: string,
|
|
263
256
|
relyingPartyID?: string,
|
|
264
257
|
userVerification?: UserVerificationRequirement,
|
|
265
|
-
): CredentialRequestOptions => {
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
};
|
|
281
|
-
};
|
|
258
|
+
): CredentialRequestOptions => ({
|
|
259
|
+
publicKey: {
|
|
260
|
+
challenge: generateSeed(deps)() as BufferSource,
|
|
261
|
+
rpId: relyingPartyID ?? document.location.hostname,
|
|
262
|
+
userVerification: userVerification ?? "preferred",
|
|
263
|
+
allowCredentials: [
|
|
264
|
+
{
|
|
265
|
+
type: "public-key",
|
|
266
|
+
id: base64UrlToUint8Array(
|
|
267
|
+
Base64Url.orThrow(credentialId),
|
|
268
|
+
) as BufferSource,
|
|
269
|
+
},
|
|
270
|
+
],
|
|
271
|
+
},
|
|
272
|
+
});
|
|
282
273
|
|
|
283
274
|
const deriveEncryptionKey = (seed: Uint8Array): EncryptionKey => {
|
|
284
275
|
const seed32 = seed.length === 32 ? seed : seed.slice(0, 32);
|
|
@@ -288,7 +279,7 @@ const deriveEncryptionKey = (seed: Uint8Array): EncryptionKey => {
|
|
|
288
279
|
};
|
|
289
280
|
|
|
290
281
|
const encryptAuthResult =
|
|
291
|
-
(deps:
|
|
282
|
+
(deps: RandomBytesDep) =>
|
|
292
283
|
(
|
|
293
284
|
authResult: AuthResult,
|
|
294
285
|
encryptionKey: EncryptionKey,
|
|
@@ -297,7 +288,7 @@ const encryptAuthResult =
|
|
|
297
288
|
ciphertext: Base64Url;
|
|
298
289
|
} => {
|
|
299
290
|
const plaintext = utf8ToBytes(JSON.stringify(authResult));
|
|
300
|
-
const
|
|
291
|
+
const [ciphertext, nonce] = encryptWithXChaCha20Poly1305(deps)(
|
|
301
292
|
plaintext,
|
|
302
293
|
encryptionKey,
|
|
303
294
|
);
|
|
@@ -307,23 +298,20 @@ const encryptAuthResult =
|
|
|
307
298
|
};
|
|
308
299
|
};
|
|
309
300
|
|
|
310
|
-
const decryptAuthResult =
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
if (!result.ok) return null;
|
|
324
|
-
return bytesToUtf8(result.value);
|
|
325
|
-
};
|
|
326
|
-
|
|
327
|
-
const generateSeed = (deps: RandomBytesDep) => () => {
|
|
328
|
-
return deps.randomBytes.create(32);
|
|
301
|
+
const decryptAuthResult = (
|
|
302
|
+
encryptedData: { nonce: Base64Url; ciphertext: Base64Url },
|
|
303
|
+
encryptionKey: EncryptionKey,
|
|
304
|
+
): string | null => {
|
|
305
|
+
const nonce = base64UrlToUint8Array(encryptedData.nonce);
|
|
306
|
+
const ciphertext = base64UrlToUint8Array(encryptedData.ciphertext);
|
|
307
|
+
const result = decryptWithXChaCha20Poly1305(
|
|
308
|
+
XChaCha20Poly1305Ciphertext.orThrow(ciphertext),
|
|
309
|
+
Entropy24.orThrow(nonce),
|
|
310
|
+
encryptionKey,
|
|
311
|
+
);
|
|
312
|
+
if (!result.ok) return null;
|
|
313
|
+
return bytesToUtf8(result.value);
|
|
329
314
|
};
|
|
315
|
+
|
|
316
|
+
const generateSeed = (deps: RandomBytesDep) => () =>
|
|
317
|
+
deps.randomBytes.create(32);
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/// <reference lib="webworker" />
|
|
2
|
+
declare const self: DedicatedWorkerGlobalScope | SharedWorkerGlobalScope;
|
|
3
|
+
|
|
4
|
+
import { installPolyfills } from "@evolu/common/polyfills";
|
|
5
|
+
installPolyfills();
|
|
6
|
+
|
|
7
|
+
import { createWebSocket, ok } from "@evolu/common";
|
|
8
|
+
import type {
|
|
9
|
+
SharedWorkerInput,
|
|
10
|
+
SharedWorkerOutput,
|
|
11
|
+
} from "@evolu/common/local-first";
|
|
12
|
+
import { initSharedWorker } from "@evolu/common/local-first";
|
|
13
|
+
import type { SharedWorkerUnsupported } from "./Evolu.js";
|
|
14
|
+
import { createRun } from "../Task.js";
|
|
15
|
+
import {
|
|
16
|
+
createOneTabSharedWorkerSelfPolyfill,
|
|
17
|
+
createSharedWorkerSelf,
|
|
18
|
+
createWorkerDeps,
|
|
19
|
+
} from "../Worker.js";
|
|
20
|
+
|
|
21
|
+
// No disposal (`await using`) is needed — a SharedWorker lives forever.
|
|
22
|
+
const run = createRun({
|
|
23
|
+
...createWorkerDeps(),
|
|
24
|
+
createWebSocket,
|
|
25
|
+
lockManager: globalThis.navigator.locks,
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
void run(async (run) => {
|
|
29
|
+
if ("onconnect" in self) {
|
|
30
|
+
void run(initSharedWorker(createSharedWorkerSelf(self)));
|
|
31
|
+
return ok();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
using workerSelf = createOneTabSharedWorkerSelfPolyfill<
|
|
35
|
+
SharedWorkerInput,
|
|
36
|
+
SharedWorkerOutput
|
|
37
|
+
>(self);
|
|
38
|
+
|
|
39
|
+
await globalThis.navigator.locks.request(
|
|
40
|
+
"evolu-one-tab-sharedworker-polyfill",
|
|
41
|
+
{ ifAvailable: true, mode: "exclusive" },
|
|
42
|
+
async (lock) => {
|
|
43
|
+
if (!lock) {
|
|
44
|
+
const message: SharedWorkerUnsupported = {
|
|
45
|
+
type: "SharedWorkerUnsupported",
|
|
46
|
+
};
|
|
47
|
+
self.postMessage(message);
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
void run(initSharedWorker(workerSelf));
|
|
52
|
+
|
|
53
|
+
await Promise.withResolvers<never>().promise;
|
|
54
|
+
},
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
return ok();
|
|
58
|
+
});
|
package/src/local-first/index.ts
CHANGED
|
@@ -1,41 +1 @@
|
|
|
1
|
-
|
|
2
|
-
createConsole,
|
|
3
|
-
createLocalAuth,
|
|
4
|
-
createRandomBytes,
|
|
5
|
-
createSymmetricCrypto,
|
|
6
|
-
createTime,
|
|
7
|
-
} from "@evolu/common";
|
|
8
|
-
import {
|
|
9
|
-
CreateDbWorker,
|
|
10
|
-
DbWorkerInput,
|
|
11
|
-
DbWorkerOutput,
|
|
12
|
-
EvoluDeps,
|
|
13
|
-
} from "@evolu/common/local-first";
|
|
14
|
-
import { createSharedWebWorker } from "../SharedWebWorker.js";
|
|
15
|
-
import { createWebAuthnStore } from "./LocalAuth.js";
|
|
16
|
-
import { reloadApp } from "./Platform.js";
|
|
17
|
-
|
|
18
|
-
const randomBytes = createRandomBytes();
|
|
19
|
-
const symmetricCrypto = createSymmetricCrypto({ randomBytes });
|
|
20
|
-
|
|
21
|
-
const createDbWorker: CreateDbWorker = (name) =>
|
|
22
|
-
createSharedWebWorker<DbWorkerInput, DbWorkerOutput>(
|
|
23
|
-
name,
|
|
24
|
-
() =>
|
|
25
|
-
new Worker(new URL("Db.worker.js", import.meta.url), {
|
|
26
|
-
type: "module",
|
|
27
|
-
}),
|
|
28
|
-
);
|
|
29
|
-
|
|
30
|
-
export const localAuth = createLocalAuth({
|
|
31
|
-
randomBytes,
|
|
32
|
-
secureStorage: createWebAuthnStore({ randomBytes, symmetricCrypto }),
|
|
33
|
-
});
|
|
34
|
-
|
|
35
|
-
export const evoluWebDeps: EvoluDeps = {
|
|
36
|
-
console: createConsole(),
|
|
37
|
-
createDbWorker,
|
|
38
|
-
randomBytes: createRandomBytes(),
|
|
39
|
-
reloadApp,
|
|
40
|
-
time: createTime(),
|
|
41
|
-
};
|
|
1
|
+
export * from "./Evolu.js";
|
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* SharedWebWorker (WebWorker + BroadcastChannel + Web Locks)
|
|
3
|
-
*
|
|
4
|
-
* A SharedWebWorker is a Web Worker that is shared across multiple browser
|
|
5
|
-
* tabs. This implementation provides a shared worker-like experience even in
|
|
6
|
-
* browsers that do not support the native SharedWorker API.
|
|
7
|
-
*
|
|
8
|
-
* Unlike a true SharedWorker (which uses MessagePorts for direct, tab-specific
|
|
9
|
-
* communication), this approach uses BroadcastChannel for cross-tab messaging
|
|
10
|
-
* and Web Locks to ensure only one tab owns and runs the actual Worker
|
|
11
|
-
* instance.
|
|
12
|
-
*
|
|
13
|
-
* All tabs communicate via BroadcastChannel, so every message is broadcast to
|
|
14
|
-
* all tabs, and each tab must filter/process only relevant messages. This is
|
|
15
|
-
* less efficient than MessagePorts, but it works everywhere and is "good
|
|
16
|
-
* enough" for most use cases.
|
|
17
|
-
*
|
|
18
|
-
* See the protocol and coordination logic below for details.
|
|
19
|
-
*
|
|
20
|
-
* @module SharedWebWorker
|
|
21
|
-
*/
|
|
22
|
-
import { SimpleName, Worker } from "@evolu/common";
|
|
23
|
-
/**
|
|
24
|
-
* Creates a shared Web Worker using BroadcastChannel and Web Locks. This allows
|
|
25
|
-
* multiple tabs to share a single Web Worker instance. The first tab to acquire
|
|
26
|
-
* the lock becomes the owner and runs the worker. Other tabs act as proxies,
|
|
27
|
-
* forwarding messages to the owner.
|
|
28
|
-
*/
|
|
29
|
-
export declare const createSharedWebWorker: <Input, Output>(name: SimpleName, createWebWorker: () => globalThis.Worker) => Worker<Input, Output>;
|
|
30
|
-
//# sourceMappingURL=SharedWebWorker.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"SharedWebWorker.d.ts","sourceRoot":"","sources":["../../src/SharedWebWorker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAa,UAAU,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AA8B9D;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB,GAAI,KAAK,EAAE,MAAM,EACjD,MAAM,UAAU,EAChB,iBAAiB,MAAM,UAAU,CAAC,MAAM,KACvC,MAAM,CAAC,KAAK,EAAE,MAAM,CAuFtB,CAAC"}
|
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* SharedWebWorker (WebWorker + BroadcastChannel + Web Locks)
|
|
3
|
-
*
|
|
4
|
-
* A SharedWebWorker is a Web Worker that is shared across multiple browser
|
|
5
|
-
* tabs. This implementation provides a shared worker-like experience even in
|
|
6
|
-
* browsers that do not support the native SharedWorker API.
|
|
7
|
-
*
|
|
8
|
-
* Unlike a true SharedWorker (which uses MessagePorts for direct, tab-specific
|
|
9
|
-
* communication), this approach uses BroadcastChannel for cross-tab messaging
|
|
10
|
-
* and Web Locks to ensure only one tab owns and runs the actual Worker
|
|
11
|
-
* instance.
|
|
12
|
-
*
|
|
13
|
-
* All tabs communicate via BroadcastChannel, so every message is broadcast to
|
|
14
|
-
* all tabs, and each tab must filter/process only relevant messages. This is
|
|
15
|
-
* less efficient than MessagePorts, but it works everywhere and is "good
|
|
16
|
-
* enough" for most use cases.
|
|
17
|
-
*
|
|
18
|
-
* See the protocol and coordination logic below for details.
|
|
19
|
-
*
|
|
20
|
-
* @module SharedWebWorker
|
|
21
|
-
*/
|
|
22
|
-
import { constVoid } from "@evolu/common";
|
|
23
|
-
/**
|
|
24
|
-
* Creates a shared Web Worker using BroadcastChannel and Web Locks. This allows
|
|
25
|
-
* multiple tabs to share a single Web Worker instance. The first tab to acquire
|
|
26
|
-
* the lock becomes the owner and runs the worker. Other tabs act as proxies,
|
|
27
|
-
* forwarding messages to the owner.
|
|
28
|
-
*/
|
|
29
|
-
export const createSharedWebWorker = (name, createWebWorker) => {
|
|
30
|
-
// Server.
|
|
31
|
-
if (typeof document === "undefined")
|
|
32
|
-
return {
|
|
33
|
-
postMessage: constVoid,
|
|
34
|
-
onMessage: constVoid,
|
|
35
|
-
};
|
|
36
|
-
const namespacedName = `evolu-sharedwebworker-${name}`;
|
|
37
|
-
const channel = new BroadcastChannel(namespacedName);
|
|
38
|
-
let worker;
|
|
39
|
-
let onMessageCallback;
|
|
40
|
-
let ownerReady = false;
|
|
41
|
-
const pendingMessages = [];
|
|
42
|
-
// Listen for owner-ready and worker responses
|
|
43
|
-
channel.onmessage = (event) => {
|
|
44
|
-
const data = event.data;
|
|
45
|
-
if (data.type === "owner-ready") {
|
|
46
|
-
ownerReady = true;
|
|
47
|
-
// Flush pending messages to the new owner
|
|
48
|
-
for (const message of pendingMessages) {
|
|
49
|
-
channel.postMessage({ type: "to-worker", message });
|
|
50
|
-
}
|
|
51
|
-
pendingMessages.length = 0;
|
|
52
|
-
}
|
|
53
|
-
else if (!worker && data.type === "from-worker") {
|
|
54
|
-
onMessageCallback?.(data.message);
|
|
55
|
-
}
|
|
56
|
-
};
|
|
57
|
-
// Request owner-ready when not the owner
|
|
58
|
-
channel.postMessage({ type: "request-owner-ready" });
|
|
59
|
-
// Try to acquire the lock and become the owner
|
|
60
|
-
void navigator.locks.request(namespacedName, async () => {
|
|
61
|
-
worker = createWebWorker();
|
|
62
|
-
// Flush pending messages to the worker
|
|
63
|
-
for (const message of pendingMessages) {
|
|
64
|
-
worker.postMessage(message);
|
|
65
|
-
}
|
|
66
|
-
pendingMessages.length = 0;
|
|
67
|
-
// Forward messages from channel to worker
|
|
68
|
-
channel.onmessage = (event) => {
|
|
69
|
-
const data = event.data;
|
|
70
|
-
if (data.type === "to-worker") {
|
|
71
|
-
worker.postMessage(data.message);
|
|
72
|
-
}
|
|
73
|
-
else if (data.type === "request-owner-ready") {
|
|
74
|
-
// Respond to request
|
|
75
|
-
channel.postMessage({ type: "owner-ready" });
|
|
76
|
-
}
|
|
77
|
-
};
|
|
78
|
-
// Forward messages from worker to channel
|
|
79
|
-
worker.onmessage = (event) => {
|
|
80
|
-
channel.postMessage({ type: "from-worker", message: event.data });
|
|
81
|
-
onMessageCallback?.(event.data);
|
|
82
|
-
};
|
|
83
|
-
// Announce ownership
|
|
84
|
-
channel.postMessage({ type: "owner-ready" });
|
|
85
|
-
// Hold the lock forever
|
|
86
|
-
await new Promise(constVoid);
|
|
87
|
-
});
|
|
88
|
-
return {
|
|
89
|
-
postMessage: (message) => {
|
|
90
|
-
if (worker) {
|
|
91
|
-
worker.postMessage(message);
|
|
92
|
-
}
|
|
93
|
-
else if (ownerReady) {
|
|
94
|
-
channel.postMessage({ type: "to-worker", message });
|
|
95
|
-
}
|
|
96
|
-
else {
|
|
97
|
-
pendingMessages.push(message);
|
|
98
|
-
}
|
|
99
|
-
},
|
|
100
|
-
onMessage: (callback) => {
|
|
101
|
-
onMessageCallback = callback;
|
|
102
|
-
},
|
|
103
|
-
};
|
|
104
|
-
};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"WasmSqliteDriver.d.ts","sourceRoot":"","sources":["../../src/WasmSqliteDriver.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,kBAAkB,EAGnB,MAAM,eAAe,CAAC;AAwBvB,eAAO,MAAM,sBAAsB,EAAE,kBAuFpC,CAAC"}
|
|
@@ -1,85 +0,0 @@
|
|
|
1
|
-
import { bytesToHex, createPreparedStatementsCache, } from "@evolu/common";
|
|
2
|
-
import sqlite3InitModule from "@evolu/sqlite-wasm";
|
|
3
|
-
// @ts-expect-error Missing types.
|
|
4
|
-
globalThis.sqlite3ApiConfig = {
|
|
5
|
-
warn: (arg) => {
|
|
6
|
-
// Ignore irrelevant warning.
|
|
7
|
-
// https://github.com/sqlite/sqlite-wasm/issues/62
|
|
8
|
-
if (typeof arg === "string" &&
|
|
9
|
-
arg.startsWith("Ignoring inability to install OPFS sqlite3_vfs"))
|
|
10
|
-
return;
|
|
11
|
-
// eslint-disable-next-line no-console
|
|
12
|
-
console.warn(arg);
|
|
13
|
-
},
|
|
14
|
-
};
|
|
15
|
-
// Init ASAP.
|
|
16
|
-
const sqlite3Promise = sqlite3InitModule();
|
|
17
|
-
export const createWasmSqliteDriver = async (name, options) => {
|
|
18
|
-
const sqlite3 = await sqlite3Promise;
|
|
19
|
-
// This is used to make OPFS default vfs for multipleciphers
|
|
20
|
-
// @ts-expect-error Missing types (update @evolu/sqlite-wasm types)
|
|
21
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
|
22
|
-
sqlite3.capi.sqlite3mc_vfs_create("opfs", 1);
|
|
23
|
-
let db;
|
|
24
|
-
if (options?.memory) {
|
|
25
|
-
db = new sqlite3.oo1.DB(":memory:");
|
|
26
|
-
}
|
|
27
|
-
else if (options?.encryptionKey) {
|
|
28
|
-
const pool = await sqlite3.installOpfsSAHPoolVfs({ directory: `.${name}` });
|
|
29
|
-
db = new pool.OpfsSAHPoolDb("file:evolu1.db?vfs=multipleciphers-opfs-sahpool");
|
|
30
|
-
db.exec(`
|
|
31
|
-
PRAGMA cipher = 'sqlcipher';
|
|
32
|
-
PRAGMA legacy = 4;
|
|
33
|
-
PRAGMA key = "x'${bytesToHex(options.encryptionKey)}'";
|
|
34
|
-
`);
|
|
35
|
-
}
|
|
36
|
-
else {
|
|
37
|
-
const pool = await sqlite3.installOpfsSAHPoolVfs({ name });
|
|
38
|
-
db = new pool.OpfsSAHPoolDb("file:evolu1.db");
|
|
39
|
-
}
|
|
40
|
-
let isDisposed = false;
|
|
41
|
-
const cache = createPreparedStatementsCache((sql) => db.prepare(sql), (statement) => {
|
|
42
|
-
statement.finalize();
|
|
43
|
-
});
|
|
44
|
-
const driver = {
|
|
45
|
-
exec: (query, isMutation) => {
|
|
46
|
-
const prepared = cache.get(query);
|
|
47
|
-
if (prepared) {
|
|
48
|
-
prepared.bind(query.parameters);
|
|
49
|
-
if (isMutation) {
|
|
50
|
-
prepared.stepReset();
|
|
51
|
-
return {
|
|
52
|
-
rows: [],
|
|
53
|
-
changes: db.changes(),
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
const rows = [];
|
|
57
|
-
while (prepared.step()) {
|
|
58
|
-
rows.push(prepared.get({}));
|
|
59
|
-
}
|
|
60
|
-
prepared.reset();
|
|
61
|
-
return {
|
|
62
|
-
rows: rows,
|
|
63
|
-
changes: 0,
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
const rows = db.exec(query.sql, {
|
|
67
|
-
returnValue: "resultRows",
|
|
68
|
-
rowMode: "object",
|
|
69
|
-
bind: query.parameters,
|
|
70
|
-
});
|
|
71
|
-
const changes = db.changes();
|
|
72
|
-
return { rows, changes };
|
|
73
|
-
},
|
|
74
|
-
export: () => sqlite3.capi.sqlite3_js_db_export(db),
|
|
75
|
-
[Symbol.dispose]: () => {
|
|
76
|
-
if (isDisposed)
|
|
77
|
-
return;
|
|
78
|
-
isDisposed = true;
|
|
79
|
-
// poolUtil.unlink?
|
|
80
|
-
cache[Symbol.dispose]();
|
|
81
|
-
db.close();
|
|
82
|
-
},
|
|
83
|
-
};
|
|
84
|
-
return driver;
|
|
85
|
-
};
|
package/dist/src/WebWorker.d.ts
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Typed wrapper for Web Worker
|
|
3
|
-
*
|
|
4
|
-
* While Comlink DX is nice, there are still memory leaks and unresolved bugs.
|
|
5
|
-
* Use plain Web Worker with a typed wrapper if maximum performance and
|
|
6
|
-
* reliability are required.
|
|
7
|
-
*
|
|
8
|
-
* @module
|
|
9
|
-
*/
|
|
10
|
-
import { Worker } from "@evolu/common";
|
|
11
|
-
/**
|
|
12
|
-
* Wraps a Web Worker to provide a typed interface for sending and receiving
|
|
13
|
-
* messages.
|
|
14
|
-
*/
|
|
15
|
-
export declare const wrapWebWorker: <Input, Output>(createWebWorker: () => globalThis.Worker) => Worker<Input, Output>;
|
|
16
|
-
export declare const wrapWebWorkerSelf: <Input, Output>(worker: Worker<Input, Output>) => void;
|
|
17
|
-
//# sourceMappingURL=WebWorker.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"WebWorker.d.ts","sourceRoot":"","sources":["../../src/WebWorker.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAa,MAAM,EAAE,MAAM,eAAe,CAAC;AAElD;;;GAGG;AACH,eAAO,MAAM,aAAa,GAAI,KAAK,EAAE,MAAM,EACzC,iBAAiB,MAAM,UAAU,CAAC,MAAM,KACvC,MAAM,CAAC,KAAK,EAAE,MAAM,CAuBtB,CAAC;AAEF,eAAO,MAAM,iBAAiB,GAAI,KAAK,EAAE,MAAM,EAC7C,QAAQ,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,KAC5B,IAQF,CAAC"}
|
package/dist/src/WebWorker.js
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Typed wrapper for Web Worker
|
|
3
|
-
*
|
|
4
|
-
* While Comlink DX is nice, there are still memory leaks and unresolved bugs.
|
|
5
|
-
* Use plain Web Worker with a typed wrapper if maximum performance and
|
|
6
|
-
* reliability are required.
|
|
7
|
-
*
|
|
8
|
-
* @module
|
|
9
|
-
*/
|
|
10
|
-
import { constVoid } from "@evolu/common";
|
|
11
|
-
/**
|
|
12
|
-
* Wraps a Web Worker to provide a typed interface for sending and receiving
|
|
13
|
-
* messages.
|
|
14
|
-
*/
|
|
15
|
-
export const wrapWebWorker = (createWebWorker) => {
|
|
16
|
-
// Server.
|
|
17
|
-
if (typeof document === "undefined")
|
|
18
|
-
return {
|
|
19
|
-
postMessage: constVoid,
|
|
20
|
-
onMessage: constVoid,
|
|
21
|
-
};
|
|
22
|
-
const webWorker = createWebWorker();
|
|
23
|
-
const worker = {
|
|
24
|
-
postMessage: (message) => {
|
|
25
|
-
webWorker.postMessage(message);
|
|
26
|
-
},
|
|
27
|
-
onMessage: (callback) => {
|
|
28
|
-
webWorker.onmessage = (event) => {
|
|
29
|
-
callback(event.data);
|
|
30
|
-
};
|
|
31
|
-
},
|
|
32
|
-
};
|
|
33
|
-
return worker;
|
|
34
|
-
};
|
|
35
|
-
export const wrapWebWorkerSelf = (worker) => {
|
|
36
|
-
worker.onMessage((message) => {
|
|
37
|
-
postMessage(message);
|
|
38
|
-
});
|
|
39
|
-
self.onmessage = (event) => {
|
|
40
|
-
worker.postMessage(event.data);
|
|
41
|
-
};
|
|
42
|
-
};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Platform.d.ts","sourceRoot":"","sources":["../../../src/local-first/Platform.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAEtD,eAAO,MAAM,SAAS,EAAE,SAMvB,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"SharedWebWorker.test.d.ts","sourceRoot":"","sources":["../../test/SharedWebWorker.test.ts"],"names":[],"mappings":""}
|