@syncular/client 0.57.0 → 0.59.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/README.md +7 -7
- package/dist/apply.d.ts +20 -11
- package/dist/apply.js +67 -45
- package/dist/blob.d.ts +17 -9
- package/dist/blob.js +5 -6
- package/dist/bun-database.d.ts +1 -0
- package/dist/bun-database.js +28 -0
- package/dist/client.d.ts +27 -10
- package/dist/client.js +357 -190
- package/dist/database.d.ts +5 -0
- package/dist/encryption.d.ts +2 -2
- package/dist/encryption.js +8 -2
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +4 -0
- package/dist/failed-overlay.d.ts +0 -1
- package/dist/failed-overlay.js +3 -6
- package/dist/http.d.ts +4 -1
- package/dist/http.js +61 -39
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/invalidation.d.ts +11 -10
- package/dist/invalidation.js +15 -26
- package/dist/local-purge.js +9 -12
- package/dist/local-rebootstrap.js +2 -2
- package/dist/multi-tab.d.ts +89 -1
- package/dist/multi-tab.js +70 -31
- package/dist/native-bridge.d.ts +235 -0
- package/dist/native-bridge.js +789 -0
- package/dist/node-database.d.ts +1 -0
- package/dist/node-database.js +29 -0
- package/dist/outbox.d.ts +9 -12
- package/dist/outbox.js +19 -36
- package/dist/outcomes.js +3 -3
- package/dist/previous-version.js +96 -114
- package/dist/query-guard.d.ts +25 -24
- package/dist/query-guard.js +34 -191
- package/dist/reactive-store.js +53 -11
- package/dist/realtime-supervisor.d.ts +9 -2
- package/dist/realtime-supervisor.js +31 -7
- package/dist/remote.js +11 -15
- package/dist/schema.js +15 -10
- package/dist/sync-scheduler.js +28 -2
- package/dist/transport.d.ts +19 -4
- package/dist/wasm-database.js +58 -21
- package/dist/worker-core.d.ts +5 -0
- package/dist/worker-core.js +80 -72
- package/dist/worker-host.d.ts +10 -5
- package/dist/worker-host.js +64 -7
- package/dist/worker-local-authority.js +2 -2
- package/dist/worker-protocol.d.ts +6 -2
- package/package.json +11 -3
- package/src/apply.ts +91 -55
- package/src/blob.ts +27 -15
- package/src/bun-database.ts +29 -0
- package/src/client.ts +477 -261
- package/src/database.ts +5 -0
- package/src/encryption.ts +10 -5
- package/src/errors.ts +8 -0
- package/src/failed-overlay.ts +3 -7
- package/src/http.ts +90 -79
- package/src/index.ts +1 -1
- package/src/invalidation.ts +17 -32
- package/src/local-purge.ts +11 -13
- package/src/local-rebootstrap.ts +2 -3
- package/src/multi-tab.ts +88 -30
- package/src/native-bridge.ts +1189 -0
- package/src/node-database.ts +32 -0
- package/src/outbox.ts +19 -41
- package/src/outcomes.ts +3 -5
- package/src/previous-version.ts +103 -114
- package/src/query-guard.ts +43 -180
- package/src/reactive-store.ts +50 -10
- package/src/realtime-supervisor.ts +37 -12
- package/src/remote.ts +12 -16
- package/src/schema.ts +19 -12
- package/src/sync-scheduler.ts +31 -1
- package/src/transport.ts +21 -2
- package/src/wasm-database.ts +76 -27
- package/src/worker-core.ts +94 -74
- package/src/worker-host.ts +63 -16
- package/src/worker-local-authority.ts +2 -5
- package/src/worker-protocol.ts +6 -2
package/dist/database.d.ts
CHANGED
|
@@ -29,6 +29,11 @@ export interface ClientDatabase {
|
|
|
29
29
|
exec(sql: string, params?: readonly SqlValue[]): void;
|
|
30
30
|
/** Execute a single statement and return its rows as objects. */
|
|
31
31
|
query(sql: string, params?: readonly SqlValue[]): SqlRow[];
|
|
32
|
+
/**
|
|
33
|
+
* The raw-SQL tier behind `client.query()`: prepare `sql` through
|
|
34
|
+
* `prepareReadOnly`, then return the statement's rows.
|
|
35
|
+
*/
|
|
36
|
+
queryReadOnly(sql: string, params?: readonly SqlValue[]): SqlRow[];
|
|
32
37
|
/**
|
|
33
38
|
* Run `fn` atomically. Nested calls are savepoints: an inner failure
|
|
34
39
|
* rolls back only the inner scope.
|
package/dist/encryption.d.ts
CHANGED
|
@@ -57,7 +57,7 @@ export declare function encryptionConfigFromKeyring(keyring: EncryptionKeyringCo
|
|
|
57
57
|
* value becomes the §5.11 ciphertext-envelope `bytes`. NULLs pass through
|
|
58
58
|
* unencrypted (§5.11).
|
|
59
59
|
*/
|
|
60
|
-
export declare function encryptRowValues<T extends RowValue | undefined>(config: EncryptionConfig, table: CompiledClientTable, rowId: string, values: readonly T[], storedKeyId?: string): Promise<T[]>;
|
|
60
|
+
export declare function encryptRowValues<T extends RowValue | undefined>(config: EncryptionConfig | undefined, table: CompiledClientTable, rowId: string, values: readonly T[], storedKeyId?: string): Promise<T[]>;
|
|
61
61
|
/**
|
|
62
62
|
* Decrypt the encrypted columns of a decoded positional row value array
|
|
63
63
|
* (returns a new array). Called at the apply seam (§4.5 COMMIT, §5.6 rows
|
|
@@ -66,4 +66,4 @@ export declare function encryptRowValues<T extends RowValue | undefined>(config:
|
|
|
66
66
|
* mirror. A wrong/missing key or malformed envelope throws
|
|
67
67
|
* {@link DecryptError} (`client.decrypt_failed`, §5.11).
|
|
68
68
|
*/
|
|
69
|
-
export declare function decryptRowValues(config: EncryptionConfig, table: CompiledClientTable, values: readonly RowValue[]): Promise<RowValue[]>;
|
|
69
|
+
export declare function decryptRowValues(config: EncryptionConfig | undefined, table: CompiledClientTable, values: readonly RowValue[]): Promise<RowValue[]>;
|
package/dist/encryption.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* envelope primitives.
|
|
10
10
|
*/
|
|
11
11
|
import { DecryptError, decryptValue, EncryptError, encryptValue, KEY_LENGTH, } from '@syncular/core';
|
|
12
|
-
import {
|
|
12
|
+
import { invalidRequest } from './errors.js';
|
|
13
13
|
/**
|
|
14
14
|
* Convert a portable keyring into the direct-client encryption contract.
|
|
15
15
|
* Key lengths are validated here, at install time: every side of the wire
|
|
@@ -19,7 +19,7 @@ import { ClientSyncError } from './errors.js';
|
|
|
19
19
|
export function encryptionConfigFromKeyring(keyring) {
|
|
20
20
|
for (const [keyId, key] of Object.entries(keyring.keys)) {
|
|
21
21
|
if (key.length !== KEY_LENGTH) {
|
|
22
|
-
throw
|
|
22
|
+
throw invalidRequest(`encryption key ${JSON.stringify(keyId)} must be ${KEY_LENGTH} bytes (AES-256), got ${key.length}`);
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
25
|
return {
|
|
@@ -86,6 +86,9 @@ export async function encryptRowValues(config, table, rowId, values, storedKeyId
|
|
|
86
86
|
}
|
|
87
87
|
if (!hasPresentEncrypted)
|
|
88
88
|
return out;
|
|
89
|
+
if (config === undefined) {
|
|
90
|
+
throw new EncryptError('encrypted columns need an encryption config');
|
|
91
|
+
}
|
|
89
92
|
// Key selection reads the presence set first, then the stored local row.
|
|
90
93
|
// Absent slots densify to null for selection only; the loop below still
|
|
91
94
|
// leaves them untouched. Absent ≠ NULL (§6.1): only an ABSENT selector
|
|
@@ -137,6 +140,9 @@ export async function decryptRowValues(config, table, values) {
|
|
|
137
140
|
if (!(value instanceof Uint8Array)) {
|
|
138
141
|
throw new DecryptError(`encrypted column ${column.name} decoded to a non-bytes value`);
|
|
139
142
|
}
|
|
143
|
+
if (config === undefined) {
|
|
144
|
+
throw new DecryptError('encrypted columns need an encryption config');
|
|
145
|
+
}
|
|
140
146
|
out[i] = deserializeGuard(await decryptValue(declaredTypeOf(column), value, config.keyProvider));
|
|
141
147
|
}
|
|
142
148
|
return out;
|
package/dist/errors.d.ts
CHANGED
|
@@ -34,6 +34,8 @@ export declare class ClientSyncError extends Error {
|
|
|
34
34
|
}
|
|
35
35
|
/** Shared invalid-request construction for client validators and transport guards. */
|
|
36
36
|
export declare function invalidRequest(message: string, retryable?: boolean): ClientSyncError;
|
|
37
|
+
/** Shared retryable `sync.transport_failed` construction for client transports. */
|
|
38
|
+
export declare function transportFailed(message: string, details?: Readonly<Record<string, unknown>>): ClientSyncError;
|
|
37
39
|
/**
|
|
38
40
|
* SPEC §7.5: the latest sync attempt failed while a live query still waited
|
|
39
41
|
* for its required coverage. `code` is the attempt's static progress error
|
package/dist/errors.js
CHANGED
|
@@ -41,6 +41,10 @@ export class ClientSyncError extends Error {
|
|
|
41
41
|
export function invalidRequest(message, retryable = false) {
|
|
42
42
|
return new ClientSyncError('sync.invalid_request', message, retryable);
|
|
43
43
|
}
|
|
44
|
+
/** Shared retryable `sync.transport_failed` construction for client transports. */
|
|
45
|
+
export function transportFailed(message, details) {
|
|
46
|
+
return new ClientSyncError('sync.transport_failed', message, true, details);
|
|
47
|
+
}
|
|
44
48
|
/**
|
|
45
49
|
* SPEC §7.5: the latest sync attempt failed while a live query still waited
|
|
46
50
|
* for its required coverage. `code` is the attempt's static progress error
|
package/dist/failed-overlay.d.ts
CHANGED
|
@@ -12,7 +12,6 @@ export declare function retainFailedRows(db: ClientDatabase, commit: OutboxCommi
|
|
|
12
12
|
export declare function uniqueConflicts(db: ClientDatabase, table: CompiledClientTable, values: Readonly<Record<string, RowValue>>): NonNullable<RetainedCommitRow['uniqueConflicts']>;
|
|
13
13
|
/** Exact row keys are JSON [table,id]; table scopes include unique-key peers. */
|
|
14
14
|
export type OverlayScope = readonly string[];
|
|
15
|
-
export declare function overlayScopePredicate(table: string, id: string): string;
|
|
16
15
|
export declare function restoreFailedBases(db: ClientDatabase, schema: CompiledClientSchema, scope?: OverlayScope): boolean;
|
|
17
16
|
export declare function failedOverlayCommits(db: ClientDatabase, acknowledged?: boolean, scope?: OverlayScope, schema?: CompiledClientSchema): OutboxCommit[];
|
|
18
17
|
export declare function dropFailedRows(db: ClientDatabase, schema: CompiledClientSchema, matches: (table: string, values: Readonly<Record<string, JsonRowValue>>) => boolean): OutboxCommit[];
|
package/dist/failed-overlay.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { hasUniqueIndex } from './schema.js';
|
|
2
2
|
import { OUTCOMES_TABLE } from './outcomes.js';
|
|
3
|
-
import {
|
|
3
|
+
import { OUTBOX_IMAGES } from './outbox.js';
|
|
4
4
|
export const RETAINED_ROWS = '_syncular_failed_rows';
|
|
5
5
|
import { ClientSyncError } from './errors.js';
|
|
6
6
|
import { mapRowValues, fromSqlValue, jsonToRowValue, pkSqlValue, quoteIdent, rowValueToJson, SYNC_VERSION_COLUMN, toSqlValue, } from './schema.js';
|
|
@@ -90,11 +90,8 @@ export function uniqueConflicts(db, table, values) {
|
|
|
90
90
|
serverVersion: Number(row[SYNC_VERSION_COLUMN]),
|
|
91
91
|
})));
|
|
92
92
|
}
|
|
93
|
-
export function overlayScopePredicate(table, id) {
|
|
94
|
-
return `?1 IS NULL OR json_array(${table},${id}) IN(SELECT value FROM json_each(?1)) OR json_array(${table}) IN(SELECT value FROM json_each(?1))`;
|
|
95
|
-
}
|
|
96
93
|
function retainedRows(db, scope, acknowledged) {
|
|
97
|
-
return db.query(`SELECT * FROM ${RETAINED_ROWS} WHERE (
|
|
94
|
+
return db.query(`SELECT * FROM ${RETAINED_ROWS} WHERE (?1 IS NULL OR json_array(tbl,id) IN(SELECT value FROM json_each(?1)) OR json_array(tbl) IN(SELECT value FROM json_each(?1)))${acknowledged === undefined ? '' : ` AND commit_seq IS${acknowledged ? ' NOT' : ''} NULL`} ORDER BY commit_seq,at,commit_id,idx`, [scope ? JSON.stringify(scope) : null]);
|
|
98
95
|
}
|
|
99
96
|
export function restoreFailedBases(db, schema, scope) {
|
|
100
97
|
const seen = new Set();
|
|
@@ -141,7 +138,7 @@ export function failedOverlayCommits(db, acknowledged = false, scope, schema) {
|
|
|
141
138
|
// Hydrate legacy failure evidence from authoritative unique-key peers.
|
|
142
139
|
const values = JSON.parse(row.intent);
|
|
143
140
|
const authorized = uniqueConflicts(db, table, mapRowValues(values, jsonToRowValue)).filter((conflict) => conflict.serverVersion >= 0 &&
|
|
144
|
-
!db.query(`SELECT 1 FROM ${RETAINED_ROWS} WHERE tbl=? AND id=? UNION ALL SELECT 1 FROM ${
|
|
141
|
+
!db.query(`SELECT 1 FROM ${RETAINED_ROWS} WHERE tbl=? AND id=? UNION ALL SELECT 1 FROM ${OUTBOX_IMAGES} WHERE tbl=? AND row_id=? LIMIT 1`, [table.name, conflict.rowId, table.name, conflict.rowId]).length);
|
|
145
142
|
if (authorized.length)
|
|
146
143
|
db.exec(`UPDATE ${RETAINED_ROWS} SET unique_conflicts=? WHERE commit_id=? AND idx=?`, [
|
|
147
144
|
JSON.stringify(authorized.map((conflict) => ({
|
package/dist/http.d.ts
CHANGED
|
@@ -29,5 +29,8 @@ export declare function httpSegmentDownloader(segmentsBaseUrl: string, options?:
|
|
|
29
29
|
* rows). Content-address verification is the client core's job (§5.9.7).
|
|
30
30
|
*/
|
|
31
31
|
export declare function httpBlobTransport(blobsBaseUrl: string, options?: HttpTransportOptions): BlobTransport;
|
|
32
|
-
/**
|
|
32
|
+
/**
|
|
33
|
+
* WebSocket realtime connector (§8.1): text = control, binary = deltas. The
|
|
34
|
+
* client's id replaces a `{clientId}` placeholder in the URL.
|
|
35
|
+
*/
|
|
33
36
|
export declare function webSocketRealtimeConnector(realtimeUrl: string): RealtimeConnector;
|
package/dist/http.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { SSP2_CONTENT_TYPE } from './content-type.js';
|
|
2
|
-
import { ClientSyncError } from './errors.js';
|
|
2
|
+
import { ClientSyncError, transportFailed } from './errors.js';
|
|
3
3
|
async function transfer(message, operation, httpStatus) {
|
|
4
4
|
try {
|
|
5
5
|
return await operation();
|
|
@@ -16,7 +16,7 @@ async function transfer(message, operation, httpStatus) {
|
|
|
16
16
|
: error instanceof TypeError
|
|
17
17
|
? 'network'
|
|
18
18
|
: 'unknown';
|
|
19
|
-
throw
|
|
19
|
+
throw transportFailed(message, {
|
|
20
20
|
causeKind,
|
|
21
21
|
...(httpStatus !== undefined ? { httpStatus } : {}),
|
|
22
22
|
});
|
|
@@ -64,7 +64,7 @@ function hostHeaders(options) {
|
|
|
64
64
|
/** POST `<mount>/sync` with SSP2 bodies (§1.1). */
|
|
65
65
|
export function httpSyncTransport(syncUrl, options) {
|
|
66
66
|
const doFetch = options?.fetch ?? fetch;
|
|
67
|
-
return async (request) => {
|
|
67
|
+
return async (request, signal) => {
|
|
68
68
|
const response = await transfer('sync request failed', () => doFetch(syncUrl, {
|
|
69
69
|
method: 'POST',
|
|
70
70
|
headers: {
|
|
@@ -72,6 +72,7 @@ export function httpSyncTransport(syncUrl, options) {
|
|
|
72
72
|
...hostHeaders(options),
|
|
73
73
|
},
|
|
74
74
|
body: request.slice().buffer,
|
|
75
|
+
...(signal !== undefined ? { signal } : {}),
|
|
75
76
|
}));
|
|
76
77
|
if (!response.ok)
|
|
77
78
|
await throwHttpError(response);
|
|
@@ -100,7 +101,7 @@ function socketOperation(message, operation) {
|
|
|
100
101
|
return operation();
|
|
101
102
|
}
|
|
102
103
|
catch {
|
|
103
|
-
throw
|
|
104
|
+
throw transportFailed(message, {
|
|
104
105
|
causeKind: 'unknown',
|
|
105
106
|
});
|
|
106
107
|
}
|
|
@@ -125,7 +126,7 @@ export function webSocketRemoteOperationConnector(realtimeUrl) {
|
|
|
125
126
|
};
|
|
126
127
|
socket.onerror = () => {
|
|
127
128
|
if (!opened) {
|
|
128
|
-
reject(
|
|
129
|
+
reject(transportFailed('remote operation realtime socket failed to connect'));
|
|
129
130
|
}
|
|
130
131
|
try {
|
|
131
132
|
socket.close();
|
|
@@ -136,7 +137,7 @@ export function webSocketRemoteOperationConnector(realtimeUrl) {
|
|
|
136
137
|
};
|
|
137
138
|
socket.onclose = () => {
|
|
138
139
|
if (!opened) {
|
|
139
|
-
reject(
|
|
140
|
+
reject(transportFailed('remote operation realtime socket closed while connecting'));
|
|
140
141
|
}
|
|
141
142
|
handlers.onClose?.();
|
|
142
143
|
};
|
|
@@ -150,7 +151,7 @@ export function webSocketRemoteOperationConnector(realtimeUrl) {
|
|
|
150
151
|
* Resolution (which path a descriptor takes, expiry, no fall-through)
|
|
151
152
|
* lives in the client core, not here.
|
|
152
153
|
*/
|
|
153
|
-
async function
|
|
154
|
+
async function readBody(response, onProgress, maxBytes) {
|
|
154
155
|
const chunks = [];
|
|
155
156
|
let received = 0;
|
|
156
157
|
let reported = 0;
|
|
@@ -163,6 +164,11 @@ async function readSegmentBody(response, onProgress) {
|
|
|
163
164
|
break;
|
|
164
165
|
chunks.push(value);
|
|
165
166
|
received += value.byteLength;
|
|
167
|
+
// The caller rejects a body longer than its declared byteLength.
|
|
168
|
+
if (received > (maxBytes ?? received)) {
|
|
169
|
+
await reader.cancel();
|
|
170
|
+
break;
|
|
171
|
+
}
|
|
166
172
|
if (received - reported >= 64 * 1024) {
|
|
167
173
|
onProgress?.(received);
|
|
168
174
|
reported = received;
|
|
@@ -175,33 +181,31 @@ async function readSegmentBody(response, onProgress) {
|
|
|
175
181
|
}
|
|
176
182
|
if (received !== reported)
|
|
177
183
|
onProgress?.(received);
|
|
178
|
-
|
|
179
|
-
let offset = 0;
|
|
180
|
-
for (const chunk of chunks) {
|
|
181
|
-
bytes.set(chunk, offset);
|
|
182
|
-
offset += chunk.byteLength;
|
|
183
|
-
}
|
|
184
|
-
return bytes;
|
|
184
|
+
return new Uint8Array(await new Blob(chunks).arrayBuffer());
|
|
185
185
|
}
|
|
186
186
|
export function httpSegmentDownloader(segmentsBaseUrl, options) {
|
|
187
187
|
const doFetch = options?.fetch ?? fetch;
|
|
188
|
-
const download = async (url, init, onProgress, signed = false) => {
|
|
188
|
+
const download = async (url, init, onProgress, signed = false, maxBytes) => {
|
|
189
189
|
const response = await transfer('segment transfer failed', () => doFetch(url, init));
|
|
190
190
|
if (!response.ok) {
|
|
191
191
|
if (!signed)
|
|
192
192
|
await throwHttpError(response);
|
|
193
|
-
throw
|
|
193
|
+
throw transportFailed('signed segment request failed', {
|
|
194
|
+
causeKind: 'status',
|
|
195
|
+
httpStatus: response.status,
|
|
196
|
+
});
|
|
194
197
|
}
|
|
195
|
-
return transfer('segment transfer failed', () =>
|
|
198
|
+
return transfer('segment transfer failed', () => readBody(response, onProgress, maxBytes), response.status);
|
|
196
199
|
};
|
|
197
200
|
const direct = (request) => download(`${segmentsBaseUrl}/${encodeURIComponent(request.segmentId)}`, {
|
|
198
201
|
headers: {
|
|
199
202
|
'X-Syncular-Scopes': request.requestedScopesJson,
|
|
200
203
|
...hostHeaders(options),
|
|
201
204
|
},
|
|
202
|
-
|
|
205
|
+
...(request.signal !== undefined ? { signal: request.signal } : {}),
|
|
206
|
+
}, request.onProgress, false, request.byteLength);
|
|
203
207
|
// Deliberately headerless: the URL is the bearer grant (§5.4).
|
|
204
|
-
const fetchUrl = (url, onProgress) => download(url, undefined, onProgress, true);
|
|
208
|
+
const fetchUrl = (url, onProgress, signal, byteLength) => download(url, signal !== undefined ? { signal } : undefined, onProgress, true, byteLength);
|
|
205
209
|
return Object.assign(direct, { fetchUrl });
|
|
206
210
|
}
|
|
207
211
|
/**
|
|
@@ -214,7 +218,7 @@ export function httpBlobTransport(blobsBaseUrl, options) {
|
|
|
214
218
|
const doFetch = options?.fetch ?? fetch;
|
|
215
219
|
const blobUrl = (blobId) => `${blobsBaseUrl}/${encodeURIComponent(blobId)}`;
|
|
216
220
|
return {
|
|
217
|
-
upload: async (blobId, bytes, mediaType) => {
|
|
221
|
+
upload: async (blobId, bytes, mediaType, signal) => {
|
|
218
222
|
const response = await transfer('blob upload failed', () => doFetch(blobUrl(blobId), {
|
|
219
223
|
method: 'PUT',
|
|
220
224
|
headers: {
|
|
@@ -222,11 +226,12 @@ export function httpBlobTransport(blobsBaseUrl, options) {
|
|
|
222
226
|
...hostHeaders(options),
|
|
223
227
|
},
|
|
224
228
|
body: bytes.slice().buffer,
|
|
229
|
+
...(signal !== undefined ? { signal } : {}),
|
|
225
230
|
}));
|
|
226
231
|
if (!response.ok)
|
|
227
232
|
await throwHttpError(response);
|
|
228
233
|
},
|
|
229
|
-
download: async (blobId) => {
|
|
234
|
+
download: async (blobId, byteLength) => {
|
|
230
235
|
const response = await transfer('blob download failed', () => doFetch(blobUrl(blobId), {
|
|
231
236
|
headers: { ...hostHeaders(options) },
|
|
232
237
|
}));
|
|
@@ -239,11 +244,10 @@ export function httpBlobTransport(blobsBaseUrl, options) {
|
|
|
239
244
|
? 'sync.auth_required'
|
|
240
245
|
: 'sync.transport_failed');
|
|
241
246
|
// §5.9.5 always-issue: a JSON body with a `url` means presigned delivery;
|
|
242
|
-
// any other body is inline bytes
|
|
243
|
-
|
|
244
|
-
const
|
|
245
|
-
|
|
246
|
-
if (contentType.includes('application/json')) {
|
|
247
|
+
// any other body is inline bytes, capped by the declared byteLength.
|
|
248
|
+
const json = (response.headers.get('content-type') ?? '').includes('application/json');
|
|
249
|
+
const bytes = await transfer('blob body read failed', () => readBody(response, undefined, json ? undefined : byteLength), response.status);
|
|
250
|
+
if (json) {
|
|
247
251
|
let envelope = null;
|
|
248
252
|
try {
|
|
249
253
|
envelope = JSON.parse(new TextDecoder().decode(bytes));
|
|
@@ -264,15 +268,18 @@ export function httpBlobTransport(blobsBaseUrl, options) {
|
|
|
264
268
|
return { kind: 'bytes', bytes };
|
|
265
269
|
},
|
|
266
270
|
// §5.9.5: bare GET of the signed URL — no host auth (the URL is the grant).
|
|
267
|
-
fetchUrl: async (url) => {
|
|
271
|
+
fetchUrl: async (url, byteLength) => {
|
|
268
272
|
const response = await transfer('signed blob download failed', () => doFetch(url));
|
|
269
273
|
if (!response.ok) {
|
|
270
|
-
throw
|
|
274
|
+
throw transportFailed('signed blob download failed', {
|
|
275
|
+
causeKind: 'status',
|
|
276
|
+
httpStatus: response.status,
|
|
277
|
+
});
|
|
271
278
|
}
|
|
272
|
-
return
|
|
279
|
+
return transfer('response body read failed', () => readBody(response, undefined, byteLength), response.status);
|
|
273
280
|
},
|
|
274
281
|
// §5.9.3: presigned-upload grant.
|
|
275
|
-
uploadGrant: async (blobId, byteLength, mediaType) => {
|
|
282
|
+
uploadGrant: async (blobId, byteLength, mediaType, signal) => {
|
|
276
283
|
const response = await transfer('blob upload grant request failed', () => doFetch(`${blobUrl(blobId)}/upload-grant`, {
|
|
277
284
|
method: 'POST',
|
|
278
285
|
headers: {
|
|
@@ -283,10 +290,11 @@ export function httpBlobTransport(blobsBaseUrl, options) {
|
|
|
283
290
|
byteLength,
|
|
284
291
|
...(mediaType !== undefined ? { mediaType } : {}),
|
|
285
292
|
}),
|
|
293
|
+
...(signal !== undefined ? { signal } : {}),
|
|
286
294
|
}));
|
|
287
295
|
if (!response.ok)
|
|
288
296
|
await throwHttpError(response);
|
|
289
|
-
const body = (await transfer('blob
|
|
297
|
+
const body = (await transfer('blob grant read failed', () => response.json(), response.status));
|
|
290
298
|
if (typeof body.url === 'string') {
|
|
291
299
|
return {
|
|
292
300
|
kind: 'url',
|
|
@@ -301,24 +309,38 @@ export function httpBlobTransport(blobsBaseUrl, options) {
|
|
|
301
309
|
return { kind: 'none' };
|
|
302
310
|
},
|
|
303
311
|
// §5.9.3: direct-to-storage PUT — no host auth (the URL is the grant).
|
|
304
|
-
uploadToUrl: async (url, bytes, mediaType) => {
|
|
312
|
+
uploadToUrl: async (url, bytes, mediaType, signal) => {
|
|
313
|
+
const body = bytes.slice().buffer;
|
|
314
|
+
// The grant signs content-length (set by fetch from the body) and this
|
|
315
|
+
// checksum, so the object store rejects any other bytes (§5.9.3).
|
|
316
|
+
const checksum = btoa(String.fromCharCode(...new Uint8Array(await crypto.subtle.digest('SHA-256', body))));
|
|
305
317
|
const response = await transfer('signed blob upload failed', () => doFetch(url, {
|
|
306
318
|
method: 'PUT',
|
|
307
319
|
headers: {
|
|
308
320
|
'Content-Type': mediaType ?? 'application/octet-stream',
|
|
321
|
+
'x-amz-checksum-sha256': checksum,
|
|
309
322
|
},
|
|
310
|
-
body
|
|
323
|
+
body,
|
|
324
|
+
...(signal !== undefined ? { signal } : {}),
|
|
311
325
|
}));
|
|
312
326
|
if (!response.ok) {
|
|
313
|
-
throw
|
|
327
|
+
throw transportFailed('signed blob upload failed', {
|
|
328
|
+
causeKind: 'status',
|
|
329
|
+
httpStatus: response.status,
|
|
330
|
+
});
|
|
314
331
|
}
|
|
315
332
|
},
|
|
316
333
|
};
|
|
317
334
|
}
|
|
318
|
-
/**
|
|
335
|
+
/**
|
|
336
|
+
* WebSocket realtime connector (§8.1): text = control, binary = deltas. The
|
|
337
|
+
* client's id replaces a `{clientId}` placeholder in the URL.
|
|
338
|
+
*/
|
|
319
339
|
export function webSocketRealtimeConnector(realtimeUrl) {
|
|
320
|
-
return (handlers) => new Promise((resolve, reject) => {
|
|
321
|
-
const socket = socketOperation('realtime socket failed to connect', () => new WebSocket(
|
|
340
|
+
return (handlers, clientId) => new Promise((resolve, reject) => {
|
|
341
|
+
const socket = socketOperation('realtime socket failed to connect', () => new WebSocket(clientId === undefined
|
|
342
|
+
? realtimeUrl
|
|
343
|
+
: realtimeUrl.replace('{clientId}', encodeURIComponent(clientId))));
|
|
322
344
|
let opened = false;
|
|
323
345
|
socket.binaryType = 'arraybuffer';
|
|
324
346
|
socket.onopen = () => {
|
|
@@ -339,7 +361,7 @@ export function webSocketRealtimeConnector(realtimeUrl) {
|
|
|
339
361
|
};
|
|
340
362
|
socket.onerror = () => {
|
|
341
363
|
if (!opened) {
|
|
342
|
-
reject(
|
|
364
|
+
reject(transportFailed('realtime socket failed to connect'));
|
|
343
365
|
}
|
|
344
366
|
try {
|
|
345
367
|
socket.close();
|
|
@@ -350,7 +372,7 @@ export function webSocketRealtimeConnector(realtimeUrl) {
|
|
|
350
372
|
};
|
|
351
373
|
socket.onclose = () => {
|
|
352
374
|
if (!opened) {
|
|
353
|
-
reject(
|
|
375
|
+
reject(transportFailed('realtime socket closed while connecting'));
|
|
354
376
|
}
|
|
355
377
|
handlers.onClose?.();
|
|
356
378
|
};
|
package/dist/index.d.ts
CHANGED
|
@@ -30,7 +30,7 @@ export * from './naming.js';
|
|
|
30
30
|
export * from './outbox.js';
|
|
31
31
|
export * from './outcomes.js';
|
|
32
32
|
export { decodePreviousVersionAuditResult, decodePreviousVersionDiscardResult, decodePreviousVersionSnapshot, type PreviousVersionAudit, type PreviousVersionReadSpec, type PreviousVersionReason, type PreviousVersionSnapshot, } from './previous-version.js';
|
|
33
|
-
export
|
|
33
|
+
export { prepareReadOnly, RawSqlError } from './query-guard.js';
|
|
34
34
|
export * from './reactive-store.js';
|
|
35
35
|
export * from './remote.js';
|
|
36
36
|
export * from './realtime-supervisor.js';
|
package/dist/index.js
CHANGED
|
@@ -23,7 +23,7 @@ export * from './outcomes.js';
|
|
|
23
23
|
// refusal/audit codecs), not package API. The feature is opt-in and its
|
|
24
24
|
// consumer-facing contract is exactly the read spec and the two result types.
|
|
25
25
|
export { decodePreviousVersionAuditResult, decodePreviousVersionDiscardResult, decodePreviousVersionSnapshot, } from './previous-version.js';
|
|
26
|
-
export
|
|
26
|
+
export { prepareReadOnly, RawSqlError } from './query-guard.js';
|
|
27
27
|
export * from './reactive-store.js';
|
|
28
28
|
export * from './remote.js';
|
|
29
29
|
export * from './realtime-supervisor.js';
|
package/dist/invalidation.d.ts
CHANGED
|
@@ -87,7 +87,11 @@ export declare class ChangeAccumulator {
|
|
|
87
87
|
conflicts(): void;
|
|
88
88
|
rejections(): void;
|
|
89
89
|
outcomes(): void;
|
|
90
|
-
/**
|
|
90
|
+
/**
|
|
91
|
+
* Add precise keys for a bulk scoped delete. A map that leaves a declared
|
|
92
|
+
* scope variable unnamed cannot list the deleted rows' keys for that
|
|
93
|
+
* variable, so the change is table-wide.
|
|
94
|
+
*/
|
|
91
95
|
scopeMap(table: CompiledClientTable, scopes: ScopeMap): void;
|
|
92
96
|
/** Add precise keys for a COMMIT change's stored scope values. */
|
|
93
97
|
changeScopes(table: CompiledClientTable, scopes: Readonly<Record<string, string>>): void;
|
|
@@ -96,11 +100,12 @@ export declare class ChangeAccumulator {
|
|
|
96
100
|
get statusChanged(): boolean;
|
|
97
101
|
finish(revision: LocalRevision, status: SyncStatusSnapshot | undefined): ClientChangeBatch;
|
|
98
102
|
}
|
|
99
|
-
/** Exception-isolated synchronous
|
|
100
|
-
|
|
103
|
+
/** Exception-isolated synchronous listener set; observer code must never
|
|
104
|
+
* corrupt the committed core path. */
|
|
105
|
+
export declare class ChangeEmitter<T = ClientChangeBatch> {
|
|
101
106
|
#private;
|
|
102
|
-
on(listener:
|
|
103
|
-
emit(
|
|
107
|
+
on(listener: (value: T) => void): () => void;
|
|
108
|
+
emit(value: T): void;
|
|
104
109
|
get size(): number;
|
|
105
110
|
}
|
|
106
111
|
/**
|
|
@@ -113,11 +118,7 @@ export interface InvalidationEvent {
|
|
|
113
118
|
}
|
|
114
119
|
export type InvalidationListener = (event: InvalidationEvent) => void;
|
|
115
120
|
export declare function invalidationFromChange(batch: ClientChangeBatch): InvalidationEvent | undefined;
|
|
116
|
-
export declare class InvalidationEmitter {
|
|
117
|
-
#private;
|
|
118
|
-
on(listener: InvalidationListener): () => void;
|
|
119
|
-
emit(event: InvalidationEvent): void;
|
|
120
|
-
get size(): number;
|
|
121
|
+
export declare class InvalidationEmitter extends ChangeEmitter<InvalidationEvent> {
|
|
121
122
|
}
|
|
122
123
|
/** @deprecated Use {@link ChangeAccumulator}. */
|
|
123
124
|
export { ChangeAccumulator as Invalidation };
|
package/dist/invalidation.js
CHANGED
|
@@ -58,8 +58,16 @@ export class ChangeAccumulator {
|
|
|
58
58
|
outcomes() {
|
|
59
59
|
this.#outcomes = true;
|
|
60
60
|
}
|
|
61
|
-
/**
|
|
61
|
+
/**
|
|
62
|
+
* Add precise keys for a bulk scoped delete. A map that leaves a declared
|
|
63
|
+
* scope variable unnamed cannot list the deleted rows' keys for that
|
|
64
|
+
* variable, so the change is table-wide.
|
|
65
|
+
*/
|
|
62
66
|
scopeMap(table, scopes) {
|
|
67
|
+
for (const variable of table.scopePrefixByVariable.keys()) {
|
|
68
|
+
if (!Object.hasOwn(scopes, variable))
|
|
69
|
+
return this.table(table.name);
|
|
70
|
+
}
|
|
63
71
|
for (const [variable, values] of Object.entries(scopes)) {
|
|
64
72
|
const prefix = table.scopePrefixByVariable.get(variable);
|
|
65
73
|
if (prefix === undefined)
|
|
@@ -123,7 +131,8 @@ export class ChangeAccumulator {
|
|
|
123
131
|
};
|
|
124
132
|
}
|
|
125
133
|
}
|
|
126
|
-
/** Exception-isolated synchronous
|
|
134
|
+
/** Exception-isolated synchronous listener set; observer code must never
|
|
135
|
+
* corrupt the committed core path. */
|
|
127
136
|
export class ChangeEmitter {
|
|
128
137
|
#listeners = new Set();
|
|
129
138
|
on(listener) {
|
|
@@ -132,13 +141,13 @@ export class ChangeEmitter {
|
|
|
132
141
|
this.#listeners.delete(listener);
|
|
133
142
|
};
|
|
134
143
|
}
|
|
135
|
-
emit(
|
|
144
|
+
emit(value) {
|
|
136
145
|
for (const listener of this.#listeners) {
|
|
137
146
|
try {
|
|
138
|
-
listener(
|
|
147
|
+
listener(value);
|
|
139
148
|
}
|
|
140
149
|
catch {
|
|
141
|
-
//
|
|
150
|
+
// Isolated: a throwing observer does not stop the others.
|
|
142
151
|
}
|
|
143
152
|
}
|
|
144
153
|
}
|
|
@@ -162,27 +171,7 @@ export function invalidationFromChange(batch) {
|
|
|
162
171
|
tables.add(change.table);
|
|
163
172
|
return { tables, scopeKeys };
|
|
164
173
|
}
|
|
165
|
-
export class InvalidationEmitter {
|
|
166
|
-
#listeners = new Set();
|
|
167
|
-
on(listener) {
|
|
168
|
-
this.#listeners.add(listener);
|
|
169
|
-
return () => {
|
|
170
|
-
this.#listeners.delete(listener);
|
|
171
|
-
};
|
|
172
|
-
}
|
|
173
|
-
emit(event) {
|
|
174
|
-
for (const listener of this.#listeners) {
|
|
175
|
-
try {
|
|
176
|
-
listener(event);
|
|
177
|
-
}
|
|
178
|
-
catch {
|
|
179
|
-
// Compatibility observers are isolated like exact observers.
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
get size() {
|
|
184
|
-
return this.#listeners.size;
|
|
185
|
-
}
|
|
174
|
+
export class InvalidationEmitter extends ChangeEmitter {
|
|
186
175
|
}
|
|
187
176
|
/** @deprecated Use {@link ChangeAccumulator}. */
|
|
188
177
|
export { ChangeAccumulator as Invalidation };
|
package/dist/local-purge.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* local engine. The engine owns the atomic SQLite consequences: synced rows,
|
|
8
8
|
* generated FTS projections, doomed optimistic commits, and blob references.
|
|
9
9
|
*/
|
|
10
|
-
import {
|
|
10
|
+
import { invalidRequest } from './errors.js';
|
|
11
11
|
const MAX_TARGETS = 64;
|
|
12
12
|
const MAX_SELECTORS_PER_TARGET = 8;
|
|
13
13
|
const MAX_VALUES_PER_SELECTOR = 128;
|
|
@@ -16,41 +16,38 @@ const CODE_LIKE_VALUE = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
|
|
|
16
16
|
function compareCodeLike(left, right) {
|
|
17
17
|
return left < right ? -1 : left > right ? 1 : 0;
|
|
18
18
|
}
|
|
19
|
-
function invalid(message) {
|
|
20
|
-
throw new ClientSyncError('sync.invalid_request', message);
|
|
21
|
-
}
|
|
22
19
|
/** Validate and canonicalize before any transaction is entered. */
|
|
23
20
|
export function compileLocalDataPurge(schema, input) {
|
|
24
21
|
if (input.purgeId.length === 0 ||
|
|
25
22
|
input.purgeId.length > 128 ||
|
|
26
23
|
!CODE_LIKE_VALUE.test(input.purgeId)) {
|
|
27
|
-
|
|
24
|
+
throw invalidRequest('local purge purgeId must be a 1–128 character code-like identifier');
|
|
28
25
|
}
|
|
29
26
|
if (input.targets.length === 0 || input.targets.length > MAX_TARGETS) {
|
|
30
|
-
|
|
27
|
+
throw invalidRequest(`local purge needs between 1 and ${MAX_TARGETS} targets`);
|
|
31
28
|
}
|
|
32
29
|
const deduplicated = new Map();
|
|
33
30
|
for (const target of input.targets) {
|
|
34
31
|
const table = schema.tables.get(target.table);
|
|
35
32
|
if (table === undefined) {
|
|
36
|
-
|
|
33
|
+
throw invalidRequest(`local purge names unknown table ${JSON.stringify(target.table)}`);
|
|
37
34
|
}
|
|
38
35
|
const entries = Object.entries(target.selectors);
|
|
39
36
|
if (entries.length === 0 || entries.length > MAX_SELECTORS_PER_TARGET) {
|
|
40
|
-
|
|
37
|
+
throw invalidRequest(`local purge target ${JSON.stringify(target.table)} needs between 1 and ${MAX_SELECTORS_PER_TARGET} selectors`);
|
|
41
38
|
}
|
|
42
39
|
const selectors = entries
|
|
43
40
|
.map(([columnName, rawValues]) => {
|
|
44
41
|
const column = table.columns.find((candidate) => candidate.name === columnName);
|
|
45
42
|
if (column === undefined) {
|
|
46
|
-
|
|
43
|
+
throw invalidRequest(`local purge target ${JSON.stringify(target.table)} names unknown column ${JSON.stringify(columnName)}`);
|
|
47
44
|
}
|
|
48
45
|
if (column.type !== 'string' || column.encrypted === true) {
|
|
49
|
-
|
|
46
|
+
throw invalidRequest(`local purge selector ${JSON.stringify(target.table)}.${JSON.stringify(columnName)} must be a plaintext string column`);
|
|
50
47
|
}
|
|
51
48
|
if (rawValues.length === 0 ||
|
|
52
49
|
rawValues.length > MAX_VALUES_PER_SELECTOR) {
|
|
53
|
-
|
|
50
|
+
throw invalidRequest(`local purge selector ${JSON.stringify(target.table)}.${JSON.stringify(columnName)} needs between 1 and ${MAX_VALUES_PER_SELECTOR} values`);
|
|
54
51
|
}
|
|
55
52
|
const values = [...new Set(rawValues)];
|
|
56
53
|
for (const value of values) {
|
|
@@ -58,7 +55,7 @@ export function compileLocalDataPurge(schema, input) {
|
|
|
58
55
|
value.length === 0 ||
|
|
59
56
|
value.length > MAX_ROUTING_VALUE_LENGTH ||
|
|
60
57
|
!CODE_LIKE_VALUE.test(value)) {
|
|
61
|
-
|
|
58
|
+
throw invalidRequest(`local purge selector values must be 1–${MAX_ROUTING_VALUE_LENGTH} character code-like identifiers`);
|
|
62
59
|
}
|
|
63
60
|
}
|
|
64
61
|
values.sort();
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* lease state, and protected bookkeeping. It only discards server-derived
|
|
7
7
|
* projection state so the registered subscriptions can bootstrap it again.
|
|
8
8
|
*/
|
|
9
|
-
import { ClientSyncError } from './errors.js';
|
|
9
|
+
import { ClientSyncError, invalidRequest } from './errors.js';
|
|
10
10
|
const CODE_LIKE_VALUE = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
|
|
11
11
|
const RESULT_KEYS = [
|
|
12
12
|
'alreadyApplied',
|
|
@@ -51,7 +51,7 @@ export function compileLocalDataRebootstrap(input) {
|
|
|
51
51
|
if (input.rebootstrapId.length === 0 ||
|
|
52
52
|
input.rebootstrapId.length > 128 ||
|
|
53
53
|
!CODE_LIKE_VALUE.test(input.rebootstrapId)) {
|
|
54
|
-
throw
|
|
54
|
+
throw invalidRequest('local rebootstrap rebootstrapId must be a 1–128 character code-like identifier');
|
|
55
55
|
}
|
|
56
56
|
return input.rebootstrapId;
|
|
57
57
|
}
|