@pgxsinkit/client 0.1.32 → 0.1.40
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 +11 -0
- package/dist/boot-report.d.ts +134 -0
- package/dist/boot-report.d.ts.map +1 -0
- package/dist/convergence.d.ts +76 -0
- package/dist/convergence.d.ts.map +1 -0
- package/dist/debug.d.ts +34 -0
- package/dist/debug.d.ts.map +1 -0
- package/dist/export-data.d.ts +100 -0
- package/dist/export-data.d.ts.map +1 -0
- package/dist/export-dump.d.ts +92 -0
- package/dist/export-dump.d.ts.map +1 -0
- package/dist/export-store.d.ts +214 -0
- package/dist/export-store.d.ts.map +1 -0
- package/dist/index.d.ts +615 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8083 -2286
- package/dist/index.js.map +81 -44
- package/dist/lazy-guard.d.ts +59 -0
- package/dist/lazy-guard.d.ts.map +1 -0
- package/dist/lifecycle-slot.d.ts +31 -0
- package/dist/lifecycle-slot.d.ts.map +1 -0
- package/dist/live-rows-sql.d.ts +21 -0
- package/dist/live-rows-sql.d.ts.map +1 -0
- package/dist/local-store.d.ts +56 -0
- package/dist/local-store.d.ts.map +1 -0
- package/dist/local-tables.d.ts +707 -0
- package/dist/local-tables.d.ts.map +1 -0
- package/dist/mutation-state.d.ts +69 -0
- package/dist/mutation-state.d.ts.map +1 -0
- package/dist/mutation.d.ts +129 -4
- package/dist/mutation.d.ts.map +1 -1
- package/dist/schema.d.ts +82 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/shape-sync.d.ts +190 -0
- package/dist/shape-sync.d.ts.map +1 -0
- package/dist/store-path.d.ts +132 -0
- package/dist/store-path.d.ts.map +1 -0
- package/dist/sync/apply.d.ts +51 -0
- package/dist/sync/apply.d.ts.map +1 -0
- package/dist/sync/copy.d.ts +43 -0
- package/dist/sync/copy.d.ts.map +1 -0
- package/dist/sync/drizzle-executor.d.ts +5 -0
- package/dist/sync/drizzle-executor.d.ts.map +1 -0
- package/dist/sync/index.d.ts +32 -0
- package/dist/sync/index.d.ts.map +1 -0
- package/dist/sync/metadata-tables.d.ts +131 -0
- package/dist/sync/metadata-tables.d.ts.map +1 -0
- package/dist/sync/nudge.d.ts +49 -0
- package/dist/sync/nudge.d.ts.map +1 -0
- package/dist/sync/shape-inbox.d.ts +215 -0
- package/dist/sync/shape-inbox.d.ts.map +1 -0
- package/dist/sync/subscription-state.d.ts +39 -0
- package/dist/sync/subscription-state.d.ts.map +1 -0
- package/dist/sync/tags.d.ts +130 -0
- package/dist/sync/tags.d.ts.map +1 -0
- package/dist/sync/types.d.ts +126 -0
- package/dist/sync/types.d.ts.map +1 -0
- package/dist/sync-auth.d.ts +53 -0
- package/dist/sync-auth.d.ts.map +1 -0
- package/dist/testing.d.ts +27 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +17 -0
- package/dist/testing.js.map +11 -0
- package/dist/worker/attach-sync-client.d.ts +96 -0
- package/dist/worker/attach-sync-client.d.ts.map +1 -0
- package/dist/worker/define-sync-worker.d.ts +76 -0
- package/dist/worker/define-sync-worker.d.ts.map +1 -0
- package/dist/worker/live-diff.d.ts +44 -0
- package/dist/worker/live-diff.d.ts.map +1 -0
- package/dist/worker/protocol.d.ts +341 -0
- package/dist/worker/protocol.d.ts.map +1 -0
- package/dist/worker/token-cache.d.ts +26 -0
- package/dist/worker/token-cache.d.ts.map +1 -0
- package/oxlint-plugin.js +143 -0
- package/package.json +20 -7
- package/skills/core/SKILL.md +210 -0
- package/skills/operating/SKILL.md +303 -0
- package/src/boot-report.ts +287 -0
- package/src/convergence.ts +197 -0
- package/src/debug.ts +151 -0
- package/src/export-data.ts +300 -0
- package/src/export-dump.ts +239 -0
- package/src/export-store.ts +309 -0
- package/src/index.ts +1652 -51
- package/src/lazy-guard.ts +135 -0
- package/src/lifecycle-slot.ts +66 -0
- package/src/live-rows-sql.ts +45 -0
- package/src/local-store.ts +193 -0
- package/src/local-tables.ts +546 -0
- package/src/mutation-state.ts +99 -0
- package/src/mutation.ts +1910 -562
- package/src/schema.ts +472 -28
- package/src/shape-sync.ts +498 -0
- package/src/store-path.ts +249 -0
- package/src/sync/apply.ts +530 -0
- package/src/sync/copy.ts +206 -0
- package/src/sync/drizzle-executor.ts +48 -0
- package/src/sync/index.ts +1087 -0
- package/src/sync/metadata-tables.ts +67 -0
- package/src/sync/nudge.ts +110 -0
- package/src/sync/shape-inbox.ts +566 -0
- package/src/sync/subscription-state.ts +135 -0
- package/src/sync/tags.ts +365 -0
- package/src/sync/types.ts +141 -0
- package/src/sync-auth.ts +117 -0
- package/src/testing.ts +53 -0
- package/src/worker/attach-sync-client.ts +653 -0
- package/src/worker/define-sync-worker.ts +762 -0
- package/src/worker/live-diff.ts +140 -0
- package/src/worker/protocol.ts +425 -0
- package/src/worker/token-cache.ts +84 -0
|
@@ -0,0 +1,653 @@
|
|
|
1
|
+
// The tab facade (ADR-0032 S2, decisions 3/4/6/7). `attachSyncClient` returns the SAME client shape as
|
|
2
|
+
// `createSyncClient` wherever semantics allow — the write API (RPC-backed), per-group readiness, the
|
|
3
|
+
// live-rows seam, `ready`/`status`/`stop` — transparently proxied to the one shared worker engine. The tab
|
|
4
|
+
// stays the single auth owner: it pushes its token at attach and on `notifyAuthChanged`, and answers the
|
|
5
|
+
// worker's expiry pull-requests via `getToken`.
|
|
6
|
+
//
|
|
7
|
+
// One-shot Drizzle reads (`query`/`queryRaw`/…), local `pglite`/`ensureSynced`/`destroy` are NOT proxied in
|
|
8
|
+
// S2 (the mandated attach surface is the write API + live rows + readiness) — they throw a clear
|
|
9
|
+
// not-supported error. Query BUILDING still works on the tab: `drizzle`/`views` are the same build-only
|
|
10
|
+
// handles `createSyncClient` exposes, compiled to SQL here and executed in the worker.
|
|
11
|
+
|
|
12
|
+
import type { Results } from "@electric-sql/pglite";
|
|
13
|
+
|
|
14
|
+
import type {
|
|
15
|
+
MutationDiagnostics,
|
|
16
|
+
SyncRuntimeStatus,
|
|
17
|
+
SyncTableName,
|
|
18
|
+
SyncTableRegistry,
|
|
19
|
+
WriteMode,
|
|
20
|
+
} from "@pgxsinkit/contracts";
|
|
21
|
+
|
|
22
|
+
import type { BootReport } from "../boot-report";
|
|
23
|
+
import type { DataExportOptions, DataExportResult } from "../export-data";
|
|
24
|
+
import type { DiagnosticExportOptions, DiagnosticExportResult } from "../export-dump";
|
|
25
|
+
import type { StoreExportOptions, StoreExportResult } from "../export-store";
|
|
26
|
+
import {
|
|
27
|
+
buildRegistryReadHandles,
|
|
28
|
+
type LiveRowsSubscription,
|
|
29
|
+
type MutationBatchItem,
|
|
30
|
+
type MutationDetail,
|
|
31
|
+
type SubscribeLiveRowsInput,
|
|
32
|
+
type SyncClient,
|
|
33
|
+
type SyncTransaction,
|
|
34
|
+
type SyncTransactionResult,
|
|
35
|
+
} from "../index";
|
|
36
|
+
import type { LocalStoreVersionEvent } from "../local-store";
|
|
37
|
+
import { readTestStoreMarker } from "../store-path";
|
|
38
|
+
import { LiveRowsMaterializer } from "./live-diff";
|
|
39
|
+
import {
|
|
40
|
+
type AttachAckPayload,
|
|
41
|
+
type AttachPayload,
|
|
42
|
+
type AuthTokenSnapshot,
|
|
43
|
+
type BridgeCodec,
|
|
44
|
+
type BridgeEvent,
|
|
45
|
+
type BridgePort,
|
|
46
|
+
type BridgeTransferable,
|
|
47
|
+
type ExportArtefactWire,
|
|
48
|
+
identityCodec,
|
|
49
|
+
isBridgeEnvelope,
|
|
50
|
+
type LiveDiffPayload,
|
|
51
|
+
type LiveInitialPayload,
|
|
52
|
+
postBridgeMessage,
|
|
53
|
+
type ProvisionAckPayload,
|
|
54
|
+
type RestoreArtefactWire,
|
|
55
|
+
type RpcOp,
|
|
56
|
+
type RpcResultPayload,
|
|
57
|
+
type TokenRequestPayload,
|
|
58
|
+
} from "./protocol";
|
|
59
|
+
|
|
60
|
+
/** A `Worker`/`SharedWorker`-shaped handle: a dedicated `Worker` IS the port; a `SharedWorker` carries `.port`. */
|
|
61
|
+
interface WorkerLike {
|
|
62
|
+
port?: BridgePort;
|
|
63
|
+
postMessage?: (message: unknown, transfer?: BridgeTransferable[]) => void;
|
|
64
|
+
addEventListener?: (type: "message", listener: (event: { data: unknown }) => void) => void;
|
|
65
|
+
removeEventListener?: (type: "message", listener: (event: { data: unknown }) => void) => void;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
69
|
+
registry: TRegistry;
|
|
70
|
+
/** A native `Worker` or `SharedWorker` (or anything port-shaped). Provide this OR {@link port}. */
|
|
71
|
+
worker?: WorkerLike;
|
|
72
|
+
/** A raw transport port (a `MessageChannel` port in tests, a `SharedWorker.port` in a browser). */
|
|
73
|
+
port?: BridgePort;
|
|
74
|
+
/**
|
|
75
|
+
* The tab's token provider (ADR-0032 decision 3). Richer than `createSyncClient`'s string form: the
|
|
76
|
+
* worker needs the EXPIRY to apply its pull margin, so this yields `{accessToken, expiresAt}` (or null
|
|
77
|
+
* when unauthenticated). Pushed at attach and answered on every worker pull-request.
|
|
78
|
+
*/
|
|
79
|
+
getToken?: () => Promise<AuthTokenSnapshot | null>;
|
|
80
|
+
/** The bound store id (resolved tab-side before attach — SharedWorker naming, ADR-0032 decision 5). */
|
|
81
|
+
storeId?: string;
|
|
82
|
+
/**
|
|
83
|
+
* The plain store PATH (ADR-0036) the worker opens if it must create its own store — a name, not a
|
|
84
|
+
* storage URL. Spread `memoryStoreForTests(...)` from `@pgxsinkit/client/testing` here for a memory store
|
|
85
|
+
* in tests (it also carries the internal marker forwarded to the worker as the memory-backend override).
|
|
86
|
+
*/
|
|
87
|
+
storePath?: string;
|
|
88
|
+
syncEnabled?: boolean;
|
|
89
|
+
/**
|
|
90
|
+
* Which baked registry the worker boots (ADR-0032 S3) — forwarded in the attach `config.role`. A worker
|
|
91
|
+
* file that bakes multiple role variants (the board's admin/member) picks by this; single-registry
|
|
92
|
+
* workers ignore it.
|
|
93
|
+
*/
|
|
94
|
+
role?: string;
|
|
95
|
+
/**
|
|
96
|
+
* Fresh-store prefetch-overlap hint (ADR-0032 S4), forwarded in the attach `config.freshStore`. Set true
|
|
97
|
+
* ONLY when the tab knows the store is a claimed schemaless spare (never for a mapped/returning store);
|
|
98
|
+
* the worker's `createSyncClient` then overlaps the shape catch-up with its local boot phases.
|
|
99
|
+
*/
|
|
100
|
+
freshStore?: boolean;
|
|
101
|
+
/**
|
|
102
|
+
* Restore the worker's store from a backup on attach (ADR-0035 decision 6) — the worker-mode `restoreFrom`.
|
|
103
|
+
* A `File`/`Blob` as produced by {@link SyncClient.exportStore}; the facade decomposes it into a transferred
|
|
104
|
+
* `ArrayBuffer` + name/mime ({@link RestoreArtefactWire}) and the worker recomposes it for `createSyncClient`.
|
|
105
|
+
* Restore rides the FIRST (boot) attach: passing it when the worker's engine has ALREADY booted rejects the
|
|
106
|
+
* attach with a typed error (you cannot restore into a running store). The restored engine boots offline and
|
|
107
|
+
* its recovered journal is quarantined, exactly as in-process — see `restoreFrom` on `createSyncClient`.
|
|
108
|
+
*/
|
|
109
|
+
restoreFrom?: File | Blob;
|
|
110
|
+
codec?: BridgeCodec;
|
|
111
|
+
onStatusChange?: (status: SyncRuntimeStatus) => void;
|
|
112
|
+
onConflict?: (details: MutationDetail[]) => void;
|
|
113
|
+
onQuarantine?: (details: MutationDetail[]) => void;
|
|
114
|
+
onReject?: (details: MutationDetail[]) => void;
|
|
115
|
+
onSchemaChange?: (event: LocalStoreVersionEvent) => void;
|
|
116
|
+
onSyncError?: (error: Error) => void;
|
|
117
|
+
/**
|
|
118
|
+
* Boot observability (ADR-0034): invoked once with the worker engine's finalized {@link BootReport} if the
|
|
119
|
+
* engine's boot finalizes WHILE this tab is attached (the one-shot `boot-report` broadcast). A tab that
|
|
120
|
+
* attaches AFTER the boot never receives the push — it reads the report via {@link SyncClient.bootReport}.
|
|
121
|
+
*/
|
|
122
|
+
onBootReport?: (report: BootReport) => void;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* The worker-attached client: `SyncClient`'s shape, worker-proxied, plus `notifyAuthChanged` (re-push the
|
|
127
|
+
* token after an app auth-state change, ADR-0032 decision 3). The unsupported one-shot-read members throw.
|
|
128
|
+
*/
|
|
129
|
+
export type AttachedSyncClient<TRegistry extends SyncTableRegistry> = SyncClient<TRegistry> & {
|
|
130
|
+
notifyAuthChanged: () => void;
|
|
131
|
+
/**
|
|
132
|
+
* Forward the app's Offline toggle to the worker (ADR-0032 S3). The worker owns convergence, so the
|
|
133
|
+
* tab cannot gate a local trigger; this sends `set-online`, which suppresses/resumes the worker's flush
|
|
134
|
+
* passes (resuming fires one immediate pass). The in-process client gates its own `autoSync` instead.
|
|
135
|
+
*/
|
|
136
|
+
setOnline: (online: boolean) => void;
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
export async function attachSyncClient<const TRegistry extends SyncTableRegistry>(
|
|
140
|
+
options: AttachSyncClientOptions<TRegistry>,
|
|
141
|
+
): Promise<AttachedSyncClient<TRegistry>> {
|
|
142
|
+
const codec = options.codec ?? identityCodec;
|
|
143
|
+
const port = resolvePort(options);
|
|
144
|
+
|
|
145
|
+
// ─── Correlation + subscription bookkeeping ──────────────────────────────────────────────────────
|
|
146
|
+
let nextId = 0;
|
|
147
|
+
const newId = (prefix: string) => `${prefix}-${++nextId}`;
|
|
148
|
+
const rpcPending = new Map<string, { resolve: (value: unknown) => void; reject: (error: Error) => void }>();
|
|
149
|
+
const initialPending = new Map<
|
|
150
|
+
string,
|
|
151
|
+
{ resolve: (payload: LiveInitialPayload) => void; reject: (error: Error) => void }
|
|
152
|
+
>();
|
|
153
|
+
const diffHandlers = new Map<string, (diff: Omit<LiveDiffPayload, "queryId">) => void>();
|
|
154
|
+
|
|
155
|
+
// ─── Status + readiness ──────────────────────────────────────────────────────────────────────────
|
|
156
|
+
const status: SyncRuntimeStatus = { phase: "booting", isRunning: false };
|
|
157
|
+
let resolveReady!: () => void;
|
|
158
|
+
const ready = new Promise<void>((resolve) => {
|
|
159
|
+
resolveReady = resolve;
|
|
160
|
+
});
|
|
161
|
+
let readyResolved = false;
|
|
162
|
+
const readyGroups = new Set<string>();
|
|
163
|
+
const groupWaiters = new Map<string, Array<() => void>>();
|
|
164
|
+
|
|
165
|
+
// ─── Auth: push at attach + on notifyAuthChanged, answer pull-requests ────────────────────────────
|
|
166
|
+
const pushToken = async () => {
|
|
167
|
+
const token = options.getToken ? await options.getToken() : null;
|
|
168
|
+
postBridgeMessage(port, codec, "token-push", token);
|
|
169
|
+
};
|
|
170
|
+
const answerPull = async (requestId: string) => {
|
|
171
|
+
const token = options.getToken ? await options.getToken() : null;
|
|
172
|
+
postBridgeMessage(port, codec, "token-response", { requestId, token });
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
// ─── Inbound message routing ─────────────────────────────────────────────────────────────────────
|
|
176
|
+
const markReady = () => {
|
|
177
|
+
if (readyResolved) return;
|
|
178
|
+
readyResolved = true;
|
|
179
|
+
resolveReady();
|
|
180
|
+
};
|
|
181
|
+
// Record a group as ready and settle any waiters — shared by the discrete `groupReady` edge and the
|
|
182
|
+
// status snapshot's `status.groups` merge (ADR-0032 FIX 4), so a tab attaching after the edge fired
|
|
183
|
+
// still resolves `client.groupReady(table)` off the snapshot it gets at attach.
|
|
184
|
+
const markGroupReady = (groupKey: string) => {
|
|
185
|
+
readyGroups.add(groupKey);
|
|
186
|
+
const waiters = groupWaiters.get(groupKey);
|
|
187
|
+
if (waiters) {
|
|
188
|
+
groupWaiters.delete(groupKey);
|
|
189
|
+
for (const resolve of waiters) resolve();
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
const onEvent = (event: BridgeEvent) => {
|
|
193
|
+
switch (event.kind) {
|
|
194
|
+
case "status": {
|
|
195
|
+
Object.assign(status, event.status);
|
|
196
|
+
options.onStatusChange?.(event.status);
|
|
197
|
+
// Match the in-process contract EXACTLY (ADR-0032 FIX 3): `ready` resolves ONLY from phase
|
|
198
|
+
// "ready" (all eager groups caught up, or the syncEnabled:false path). `auth-needed`/`degraded`
|
|
199
|
+
// do NOT resolve it — an engine stuck retrying auth keeps `ready` pending, as in-process.
|
|
200
|
+
if (event.status.phase === "ready") markReady();
|
|
201
|
+
// Late-attach group merge (ADR-0032 FIX 4): fold every already-ready group from the snapshot.
|
|
202
|
+
for (const [groupKey, ready] of Object.entries(event.status.groups ?? {})) {
|
|
203
|
+
if (ready) markGroupReady(groupKey);
|
|
204
|
+
}
|
|
205
|
+
break;
|
|
206
|
+
}
|
|
207
|
+
case "groupReady": {
|
|
208
|
+
markGroupReady(event.groupKey);
|
|
209
|
+
break;
|
|
210
|
+
}
|
|
211
|
+
case "conflict":
|
|
212
|
+
options.onConflict?.(event.details as MutationDetail[]);
|
|
213
|
+
break;
|
|
214
|
+
case "quarantine":
|
|
215
|
+
options.onQuarantine?.(event.details as MutationDetail[]);
|
|
216
|
+
break;
|
|
217
|
+
case "reject":
|
|
218
|
+
options.onReject?.(event.details as MutationDetail[]);
|
|
219
|
+
break;
|
|
220
|
+
case "schema-change":
|
|
221
|
+
options.onSchemaChange?.(event.event as LocalStoreVersionEvent);
|
|
222
|
+
break;
|
|
223
|
+
case "sync-error":
|
|
224
|
+
options.onSyncError?.(new Error(event.message));
|
|
225
|
+
break;
|
|
226
|
+
case "boot-report":
|
|
227
|
+
// Boot observability (ADR-0034): the one-shot push for a tab attached at finalize. A late tab never
|
|
228
|
+
// gets this event and pulls the report via `client.bootReport()` instead.
|
|
229
|
+
options.onBootReport?.(event.report);
|
|
230
|
+
break;
|
|
231
|
+
case "debug": {
|
|
232
|
+
// Re-print the worker's rail line gated on THIS tab's own flag, origin-tagged with the worker's
|
|
233
|
+
// monotonic stamp (ADR-0032 decision 7) — a SharedWorker's own console is otherwise invisible.
|
|
234
|
+
if ((globalThis as { __pgxsinkitDebug?: boolean }).__pgxsinkitDebug === true) {
|
|
235
|
+
const line = `[pgxsinkit·w ${event.stamp.toFixed(0)}ms] ${event.line}`;
|
|
236
|
+
if (event.data) console.debug(line, event.data);
|
|
237
|
+
else console.debug(line);
|
|
238
|
+
}
|
|
239
|
+
break;
|
|
240
|
+
}
|
|
241
|
+
case "timing":
|
|
242
|
+
break;
|
|
243
|
+
default:
|
|
244
|
+
break;
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
const listener = (message: { data: unknown }) => {
|
|
249
|
+
if (!isBridgeEnvelope(message.data)) return;
|
|
250
|
+
const envelope = message.data;
|
|
251
|
+
const payload = codec.decode(envelope.payload);
|
|
252
|
+
switch (envelope.type) {
|
|
253
|
+
case "attach-ack": {
|
|
254
|
+
const ack = payload as AttachAckPayload;
|
|
255
|
+
// A boot failure crosses in the ack's `error` (ADR-0032 FIX 1): reject the handshake so
|
|
256
|
+
// `attachSyncClient` rejects instead of hanging forever. On success, the engine exists and the
|
|
257
|
+
// status event that follows drives `ready`; `engineReady` covers a LATE attach whose engine already
|
|
258
|
+
// fired its monotonic `ready` before this ack (FIX 3), so resolve `ready` straight away.
|
|
259
|
+
if (ack.error) {
|
|
260
|
+
attachAckReject?.(rebuildError(ack.error));
|
|
261
|
+
} else {
|
|
262
|
+
if (ack.engineReady) markReady();
|
|
263
|
+
attachAckResolve?.(ack);
|
|
264
|
+
}
|
|
265
|
+
break;
|
|
266
|
+
}
|
|
267
|
+
case "token-request":
|
|
268
|
+
void answerPull((payload as TokenRequestPayload).requestId);
|
|
269
|
+
break;
|
|
270
|
+
case "rpc-result": {
|
|
271
|
+
const id = envelope.id;
|
|
272
|
+
if (id == null) break;
|
|
273
|
+
const result = payload as RpcResultPayload;
|
|
274
|
+
const pending = rpcPending.get(id);
|
|
275
|
+
if (pending) {
|
|
276
|
+
rpcPending.delete(id);
|
|
277
|
+
if (result.ok) pending.resolve(result.value);
|
|
278
|
+
else pending.reject(rebuildError(result.error));
|
|
279
|
+
break;
|
|
280
|
+
}
|
|
281
|
+
// A failed `subscribe` is reported as an `rpc-result` correlated by the subscribe's envelope id
|
|
282
|
+
// (the worker has no client to hand an initial snapshot), so route the miss to the initial waiter
|
|
283
|
+
// (ADR-0032 FIX 2). A successful subscribe never lands here — it resolves via `live-initial`.
|
|
284
|
+
const initial = initialPending.get(id);
|
|
285
|
+
if (initial && !result.ok) {
|
|
286
|
+
initialPending.delete(id);
|
|
287
|
+
initial.reject(rebuildError(result.error));
|
|
288
|
+
}
|
|
289
|
+
break;
|
|
290
|
+
}
|
|
291
|
+
case "live-initial": {
|
|
292
|
+
const id = envelope.id;
|
|
293
|
+
const initial = payload as LiveInitialPayload;
|
|
294
|
+
if (id != null) {
|
|
295
|
+
const pending = initialPending.get(id);
|
|
296
|
+
if (pending) {
|
|
297
|
+
initialPending.delete(id);
|
|
298
|
+
pending.resolve(initial);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
break;
|
|
302
|
+
}
|
|
303
|
+
case "live-diff": {
|
|
304
|
+
const diff = payload as LiveDiffPayload;
|
|
305
|
+
diffHandlers.get(diff.queryId)?.(diff);
|
|
306
|
+
break;
|
|
307
|
+
}
|
|
308
|
+
case "event":
|
|
309
|
+
onEvent(payload as BridgeEvent);
|
|
310
|
+
break;
|
|
311
|
+
default:
|
|
312
|
+
break;
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
port.addEventListener("message", listener);
|
|
316
|
+
port.start?.();
|
|
317
|
+
|
|
318
|
+
// ─── RPC helper ──────────────────────────────────────────────────────────────────────────────────
|
|
319
|
+
const rpc = <T>(op: RpcOp, args: unknown[]): Promise<T> => {
|
|
320
|
+
const id = newId("rpc");
|
|
321
|
+
return new Promise<T>((resolve, reject) => {
|
|
322
|
+
rpcPending.set(id, { resolve: resolve as (value: unknown) => void, reject });
|
|
323
|
+
postBridgeMessage(port, codec, "rpc", { op, args }, id);
|
|
324
|
+
});
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
// ─── Attach handshake ────────────────────────────────────────────────────────────────────────────
|
|
328
|
+
let attachAckResolve: ((ack: AttachAckPayload) => void) | null = null;
|
|
329
|
+
let attachAckReject: ((error: Error) => void) | null = null;
|
|
330
|
+
const attachAck = new Promise<AttachAckPayload>((resolve, reject) => {
|
|
331
|
+
attachAckResolve = resolve;
|
|
332
|
+
attachAckReject = reject;
|
|
333
|
+
});
|
|
334
|
+
const initialToken = options.getToken ? await options.getToken() : null;
|
|
335
|
+
// The testing memory-backend override travels as an explicit wire field, not the symbol marker — a symbol
|
|
336
|
+
// does not survive `postMessage` structured clone (ADR-0036). Read it off the spread helper's options here.
|
|
337
|
+
const memoryOverride = readTestStoreMarker(options) === "memory";
|
|
338
|
+
// Restore (ADR-0035 decision 6): a `File`/`Blob` cannot cross as a transferable, so decompose it into a
|
|
339
|
+
// zero-copy `ArrayBuffer` + name/mime (the `ExportArtefactWire` pattern in reverse) and list the buffer on
|
|
340
|
+
// the attach `postMessage`'s transfer list. Read the bytes BEFORE building the payload (async).
|
|
341
|
+
const restoreWire: RestoreArtefactWire | undefined = options.restoreFrom
|
|
342
|
+
? {
|
|
343
|
+
buffer: await options.restoreFrom.arrayBuffer(),
|
|
344
|
+
fileName: options.restoreFrom instanceof File ? options.restoreFrom.name : "restore.pgdata.tar",
|
|
345
|
+
mimeType: options.restoreFrom.type || "application/octet-stream",
|
|
346
|
+
}
|
|
347
|
+
: undefined;
|
|
348
|
+
const attachPayload: AttachPayload = {
|
|
349
|
+
token: initialToken,
|
|
350
|
+
...(options.storeId ? { storeId: options.storeId } : {}),
|
|
351
|
+
...(options.storePath ? { storePath: options.storePath } : {}),
|
|
352
|
+
...(memoryOverride ? { testStoreBackend: "memory" as const } : {}),
|
|
353
|
+
...(restoreWire ? { restore: restoreWire } : {}),
|
|
354
|
+
...(options.syncEnabled != null || options.role != null || options.freshStore != null
|
|
355
|
+
? {
|
|
356
|
+
config: {
|
|
357
|
+
...(options.syncEnabled != null ? { syncEnabled: options.syncEnabled } : {}),
|
|
358
|
+
...(options.role != null ? { role: options.role } : {}),
|
|
359
|
+
...(options.freshStore != null ? { freshStore: options.freshStore } : {}),
|
|
360
|
+
},
|
|
361
|
+
}
|
|
362
|
+
: {}),
|
|
363
|
+
};
|
|
364
|
+
postBridgeMessage(port, codec, "attach", attachPayload, undefined, restoreWire ? [restoreWire.buffer] : undefined);
|
|
365
|
+
try {
|
|
366
|
+
await attachAck;
|
|
367
|
+
} catch (error) {
|
|
368
|
+
// The worker's engine boot failed (ADR-0032 FIX 1): tear down this tab's listener so no port handler
|
|
369
|
+
// leaks, then let the boot error propagate out of `attachSyncClient`.
|
|
370
|
+
port.removeEventListener("message", listener);
|
|
371
|
+
throw error;
|
|
372
|
+
}
|
|
373
|
+
status.isRunning = true;
|
|
374
|
+
|
|
375
|
+
// ─── Live-rows seam (ADR-0032 S2 §4) ─────────────────────────────────────────────────────────────
|
|
376
|
+
const subscribeLiveRows = async <TRow extends Record<string, unknown>>(
|
|
377
|
+
input: SubscribeLiveRowsInput,
|
|
378
|
+
onRows: (rows: TRow[]) => void,
|
|
379
|
+
): Promise<LiveRowsSubscription<TRow>> => {
|
|
380
|
+
const queryId = newId("live");
|
|
381
|
+
const id = newId("sub");
|
|
382
|
+
const materializer = new LiveRowsMaterializer<TRow>(input.pkColumns);
|
|
383
|
+
diffHandlers.set(queryId, (diff) => {
|
|
384
|
+
onRows(materializer.apply(diff));
|
|
385
|
+
});
|
|
386
|
+
let initial: LiveInitialPayload;
|
|
387
|
+
try {
|
|
388
|
+
initial = await new Promise<LiveInitialPayload>((resolve, reject) => {
|
|
389
|
+
initialPending.set(id, { resolve, reject });
|
|
390
|
+
postBridgeMessage(
|
|
391
|
+
port,
|
|
392
|
+
codec,
|
|
393
|
+
"subscribe",
|
|
394
|
+
{
|
|
395
|
+
queryId,
|
|
396
|
+
sql: input.sql,
|
|
397
|
+
params: [...input.params],
|
|
398
|
+
...(input.fields ? { fields: [...input.fields] } : {}),
|
|
399
|
+
...(input.pkColumns ? { pkColumns: [...input.pkColumns] } : {}),
|
|
400
|
+
...(input.use ? { use: [...input.use] } : {}),
|
|
401
|
+
},
|
|
402
|
+
id,
|
|
403
|
+
);
|
|
404
|
+
});
|
|
405
|
+
} catch (error) {
|
|
406
|
+
// The worker rejected the subscribe (invalid SQL, etc.); the initial-payload waiter rejected via the
|
|
407
|
+
// `rpc-result` route (ADR-0032 FIX 2). Drop the pre-registered diff handler so no orphan survives.
|
|
408
|
+
diffHandlers.delete(queryId);
|
|
409
|
+
throw error;
|
|
410
|
+
}
|
|
411
|
+
const initialRows = materializer.seed(initial.rows as TRow[]);
|
|
412
|
+
return {
|
|
413
|
+
initialRows,
|
|
414
|
+
unsubscribe: () => {
|
|
415
|
+
diffHandlers.delete(queryId);
|
|
416
|
+
postBridgeMessage(port, codec, "unsubscribe", { queryId });
|
|
417
|
+
},
|
|
418
|
+
};
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
// ─── Assembled client ────────────────────────────────────────────────────────────────────────────
|
|
422
|
+
const { drizzle, views } = buildRegistryReadHandles(options.registry);
|
|
423
|
+
const notSupported = (name: string) => (): never => {
|
|
424
|
+
throw new Error(
|
|
425
|
+
`[pgxsinkit] ${name} is not available on a worker-attached client (ADR-0032 S2). Use the live-rows hooks / subscribeLiveRows for reads, the write API for mutations.`,
|
|
426
|
+
);
|
|
427
|
+
};
|
|
428
|
+
|
|
429
|
+
const groupKeyForTable = (table: SyncTableName<TRegistry>): string | undefined => {
|
|
430
|
+
const entry = options.registry[table];
|
|
431
|
+
return entry?.consistencyGroup ?? entry?.shape?.shapeKey;
|
|
432
|
+
};
|
|
433
|
+
|
|
434
|
+
const client: AttachedSyncClient<TRegistry> = {
|
|
435
|
+
drizzle,
|
|
436
|
+
views,
|
|
437
|
+
// The tab has no local PGlite; reads go through the live-rows bridge. Touching `.pglite` is a misuse.
|
|
438
|
+
pglite: new Proxy(
|
|
439
|
+
{},
|
|
440
|
+
{
|
|
441
|
+
get: notSupported("client.pglite"),
|
|
442
|
+
},
|
|
443
|
+
) as never,
|
|
444
|
+
tables: Object.fromEntries(
|
|
445
|
+
Object.keys(options.registry).map((tableKey) => [
|
|
446
|
+
tableKey,
|
|
447
|
+
{
|
|
448
|
+
key: tableKey,
|
|
449
|
+
mode: options.registry[tableKey as SyncTableName<TRegistry>]!.mode,
|
|
450
|
+
create: (input: unknown) => rpc<void>("create", [tableKey, input]),
|
|
451
|
+
update: (entityKey: Record<string, string>, patch: unknown) =>
|
|
452
|
+
rpc<void>("update", [tableKey, entityKey, patch]),
|
|
453
|
+
delete: (entityKey: Record<string, string>) => rpc<void>("delete", [tableKey, entityKey]),
|
|
454
|
+
},
|
|
455
|
+
]),
|
|
456
|
+
) as SyncClient<TRegistry>["tables"],
|
|
457
|
+
ready,
|
|
458
|
+
status,
|
|
459
|
+
start: async () => {
|
|
460
|
+
await ready;
|
|
461
|
+
},
|
|
462
|
+
stop: async () => {
|
|
463
|
+
// Detach THIS tab; the worker engine keeps running for other tabs (ADR-0032 decision 2).
|
|
464
|
+
status.isRunning = false;
|
|
465
|
+
for (const queryId of diffHandlers.keys()) postBridgeMessage(port, codec, "unsubscribe", { queryId });
|
|
466
|
+
diffHandlers.clear();
|
|
467
|
+
postBridgeMessage(port, codec, "detach", null);
|
|
468
|
+
port.removeEventListener("message", listener);
|
|
469
|
+
port.close?.();
|
|
470
|
+
},
|
|
471
|
+
destroy: notSupported("client.destroy"),
|
|
472
|
+
dropReadCache: notSupported("client.dropReadCache"),
|
|
473
|
+
flush: (table) => rpc<void>("flush", [table]),
|
|
474
|
+
reconcile: (table) => rpc<void>("reconcile", [table]),
|
|
475
|
+
retryFailed: (table) => rpc<void>("retryFailed", [table]),
|
|
476
|
+
recoverSending: (table) => rpc<void>("recoverSending", [table]),
|
|
477
|
+
readMutationDetails: (table) => rpc<MutationDetail[]>("readMutationDetails", [table]),
|
|
478
|
+
// Inspection reads run in the worker (ADR-0032 S2) — the same surface as the in-process client. `pglite`
|
|
479
|
+
// itself stays blocked (below); these route the raw statement over the RPC round-trip instead.
|
|
480
|
+
rawQuery: (sql, params, options) => rpc<Results>("rawQuery", [sql, params, options]),
|
|
481
|
+
rawExec: (sql, options) => rpc<Results[]>("rawExec", [sql, options]),
|
|
482
|
+
mutate: {
|
|
483
|
+
create: (table, input) => rpc<void>("create", [table, input]),
|
|
484
|
+
update: (table, entityKey, patch) => rpc<void>("update", [table, entityKey, patch]),
|
|
485
|
+
delete: (table, entityKey) => rpc<void>("delete", [table, entityKey]),
|
|
486
|
+
batch: (items) => rpc<void>("batch", [items]),
|
|
487
|
+
},
|
|
488
|
+
discardConflict: (table, entityKey) => rpc<void>("discardConflict", [table, entityKey]),
|
|
489
|
+
discardQuarantined: (table, entityKey) => rpc<void>("discardQuarantined", [table, entityKey]),
|
|
490
|
+
diagnostics: (table) => rpc<{ mutation: MutationDiagnostics }>("diagnostics", [table]),
|
|
491
|
+
query: notSupported("client.query"),
|
|
492
|
+
queryRow: notSupported("client.queryRow"),
|
|
493
|
+
queryRaw: notSupported("client.queryRaw"),
|
|
494
|
+
queryRawRow: notSupported("client.queryRawRow"),
|
|
495
|
+
ensureSynced: notSupported("client.ensureSynced"),
|
|
496
|
+
isSynced: notSupported("client.isSynced"),
|
|
497
|
+
// In SharedWorker mode the engine is SHARED, so a desync from one tab reverts the consistency group for
|
|
498
|
+
// EVERY attached tab — inherent to desync's group-wide semantics (that footgun is why the narrower
|
|
499
|
+
// `discardEphemeral` exists). The RPC runs the worker's real `desync` (same refusals as in-process).
|
|
500
|
+
desync: (key) => rpc<void>("desync", [key]),
|
|
501
|
+
// Scoped, multi-tab-safe finalize (ADR-0021): drops an ephemeral relation's local rows and reverts it to
|
|
502
|
+
// dormant. Safe under a shared engine because an ephemeral window is per-delivery-session and inherently
|
|
503
|
+
// single-consumer; the RPC runs the worker's real `discardEphemeral` (refuses persistent members).
|
|
504
|
+
discardEphemeral: (key) => rpc<void>("discardEphemeral", [key]),
|
|
505
|
+
// The worker activates lazy relations inside its `subscribe` handler (via the `use` hint), so the tab's
|
|
506
|
+
// `prepareQuery` is a no-op — the live-rows subscription is already guarded worker-side (ADR-0021).
|
|
507
|
+
prepareQuery: async () => undefined,
|
|
508
|
+
transaction: async ({ mode }: { mode: WriteMode }, run) => {
|
|
509
|
+
// Collect the unit's mutations tab-side (the run callback cannot cross the wire), then RPC the
|
|
510
|
+
// serialized items + mode; the worker replays them into a real `client.transaction` (matching acks).
|
|
511
|
+
const collected: MutationBatchItem<TRegistry>[] = [];
|
|
512
|
+
const txTables = Object.fromEntries(
|
|
513
|
+
Object.keys(options.registry).map((tableKey) => [
|
|
514
|
+
tableKey,
|
|
515
|
+
{
|
|
516
|
+
create: (input: unknown) => {
|
|
517
|
+
collected.push({ table: tableKey, kind: "create", input } as MutationBatchItem<TRegistry>);
|
|
518
|
+
},
|
|
519
|
+
update: (entityKey: Record<string, string>, patch: unknown) => {
|
|
520
|
+
collected.push({ table: tableKey, kind: "update", entityKey, patch } as MutationBatchItem<TRegistry>);
|
|
521
|
+
},
|
|
522
|
+
updateBlind: (entityKey: Record<string, string>, patch: unknown) => {
|
|
523
|
+
// ADR-0022 addendum: the `blind` flag rides the serialized item across the wire; the worker
|
|
524
|
+
// replays it through `client.transaction`'s `updateBlind`, identical to the in-process client.
|
|
525
|
+
collected.push({
|
|
526
|
+
table: tableKey,
|
|
527
|
+
kind: "update",
|
|
528
|
+
entityKey,
|
|
529
|
+
patch,
|
|
530
|
+
blind: true,
|
|
531
|
+
} as MutationBatchItem<TRegistry>);
|
|
532
|
+
},
|
|
533
|
+
delete: (entityKey: Record<string, string>) => {
|
|
534
|
+
collected.push({ table: tableKey, kind: "delete", entityKey } as MutationBatchItem<TRegistry>);
|
|
535
|
+
},
|
|
536
|
+
},
|
|
537
|
+
]),
|
|
538
|
+
) as SyncTransaction<TRegistry>["tables"];
|
|
539
|
+
await run({ tables: txTables });
|
|
540
|
+
if (collected.length === 0) return { acks: [] };
|
|
541
|
+
return rpc<SyncTransactionResult>("transaction", [{ mode, items: collected }]);
|
|
542
|
+
},
|
|
543
|
+
groupReady: async (table) => {
|
|
544
|
+
const groupKey = groupKeyForTable(table);
|
|
545
|
+
if (groupKey == null || readyGroups.has(groupKey)) return;
|
|
546
|
+
await new Promise<void>((resolve) => {
|
|
547
|
+
const waiters = groupWaiters.get(groupKey) ?? [];
|
|
548
|
+
waiters.push(resolve);
|
|
549
|
+
groupWaiters.set(groupKey, waiters);
|
|
550
|
+
});
|
|
551
|
+
},
|
|
552
|
+
subscribeLiveRows,
|
|
553
|
+
// Boot observability (ADR-0034): pull the worker engine's stored boot report over the bridge — returns
|
|
554
|
+
// the same report regardless of when this tab attached (a late tab reads a boot that predates it).
|
|
555
|
+
bootReport: () => rpc<BootReport | null>("bootReport", []),
|
|
556
|
+
// Store backup (ADR-0035): the worker runs the live export on its owned client (its lifecycle slot
|
|
557
|
+
// serialises it against every tab). The dump crosses back as a transferred `ArrayBuffer`; rebuild the
|
|
558
|
+
// `File` tab-side from the wire form — NOT in the notSupported set (unlike the local `pglite` reads).
|
|
559
|
+
exportStore: async (exportOptions?: StoreExportOptions): Promise<StoreExportResult> => {
|
|
560
|
+
const wire = await rpc<ExportArtefactWire>("exportStore", [exportOptions]);
|
|
561
|
+
return {
|
|
562
|
+
file: new File([wire.buffer], wire.fileName, { type: wire.mimeType }),
|
|
563
|
+
// The wire carries the discriminated union; `exportStore` always round-trips a store-backup report.
|
|
564
|
+
report: wire.report as StoreExportResult["report"],
|
|
565
|
+
};
|
|
566
|
+
},
|
|
567
|
+
// Diagnostic dump (ADR-0035): the worker runs the throwaway-clone dump on its owned client (same
|
|
568
|
+
// lifecycle slot as every tab). The SQL crosses back as the same transferred `ArrayBuffer`; rebuild the
|
|
569
|
+
// `File` tab-side. NOT in the notSupported set (unlike the local `pglite` reads).
|
|
570
|
+
exportDiagnostics: async (exportOptions?: DiagnosticExportOptions): Promise<DiagnosticExportResult> => {
|
|
571
|
+
const wire = await rpc<ExportArtefactWire>("exportDiagnostics", [exportOptions]);
|
|
572
|
+
return {
|
|
573
|
+
file: new File([wire.buffer], wire.fileName, { type: wire.mimeType }),
|
|
574
|
+
// The wire carries the discriminated union; `exportDiagnostics` always round-trips a diagnostic-dump report.
|
|
575
|
+
report: wire.report as DiagnosticExportResult["report"],
|
|
576
|
+
};
|
|
577
|
+
},
|
|
578
|
+
// Data export (ADR-0035): the worker runs the drain-guarded `pg_dump -t` export on its owned client (same
|
|
579
|
+
// lifecycle slot as every tab). The portable SQL crosses back as the same transferred `ArrayBuffer`;
|
|
580
|
+
// rebuild the `File` tab-side. A `DataExportDrainError` surfaces as the rejected RPC (deserialised tab-side).
|
|
581
|
+
exportData: async (exportOptions?: DataExportOptions): Promise<DataExportResult> => {
|
|
582
|
+
const wire = await rpc<ExportArtefactWire>("exportData", [exportOptions]);
|
|
583
|
+
return {
|
|
584
|
+
file: new File([wire.buffer], wire.fileName, { type: wire.mimeType }),
|
|
585
|
+
// The wire carries the discriminated union; `exportData` always round-trips a data-export report.
|
|
586
|
+
report: wire.report as DataExportResult["report"],
|
|
587
|
+
};
|
|
588
|
+
},
|
|
589
|
+
notifyAuthChanged: () => {
|
|
590
|
+
void pushToken();
|
|
591
|
+
},
|
|
592
|
+
setOnline: (online: boolean) => {
|
|
593
|
+
postBridgeMessage(port, codec, "set-online", { online });
|
|
594
|
+
},
|
|
595
|
+
};
|
|
596
|
+
|
|
597
|
+
return client;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/**
|
|
601
|
+
* Pre-spawn a worker's store WITHOUT attaching (ADR-0032 decision 5). Sent at the board's login screen
|
|
602
|
+
* against a freshly-named spare `SharedWorker`: the worker runs PGlite `create`/initdb only and holds the
|
|
603
|
+
* raw store idle until the real {@link attachSyncClient} claim adopts it. Resolves when the worker acks the
|
|
604
|
+
* provision (its initdb settled); rejects only if the worker reports the create failed — the caller treats
|
|
605
|
+
* either outcome as best-effort, since attach falls back to a fresh create regardless.
|
|
606
|
+
*/
|
|
607
|
+
export function provisionSyncWorker<TRegistry extends SyncTableRegistry>(
|
|
608
|
+
options: Pick<AttachSyncClientOptions<TRegistry>, "worker" | "port" | "storeId" | "storePath" | "codec">,
|
|
609
|
+
): Promise<void> {
|
|
610
|
+
const codec = options.codec ?? identityCodec;
|
|
611
|
+
const port = resolvePort(options);
|
|
612
|
+
// The testing memory-backend override travels as an explicit wire field (a symbol does not survive
|
|
613
|
+
// structured clone, ADR-0036) — read it off the spread helper's options and forward it to the worker.
|
|
614
|
+
const memoryOverride = readTestStoreMarker(options) === "memory";
|
|
615
|
+
return new Promise<void>((resolve, reject) => {
|
|
616
|
+
const listener = (message: { data: unknown }) => {
|
|
617
|
+
if (!isBridgeEnvelope(message.data)) return;
|
|
618
|
+
if (message.data.type !== "provision-ack") return;
|
|
619
|
+
port.removeEventListener("message", listener);
|
|
620
|
+
const ack = codec.decode(message.data.payload) as ProvisionAckPayload;
|
|
621
|
+
if (ack.ok) resolve();
|
|
622
|
+
else reject(new Error(ack.error?.message ?? "worker provision failed"));
|
|
623
|
+
};
|
|
624
|
+
port.addEventListener("message", listener);
|
|
625
|
+
port.start?.();
|
|
626
|
+
postBridgeMessage(port, codec, "provision", {
|
|
627
|
+
...(options.storeId ? { storeId: options.storeId } : {}),
|
|
628
|
+
...(options.storePath ? { storePath: options.storePath } : {}),
|
|
629
|
+
...(memoryOverride ? { testStoreBackend: "memory" as const } : {}),
|
|
630
|
+
});
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/** Resolve the transport port from the options: an explicit port, a SharedWorker's `.port`, or a Worker itself. */
|
|
635
|
+
function resolvePort(options: { port?: BridgePort; worker?: WorkerLike }): BridgePort {
|
|
636
|
+
if (options.port) return options.port;
|
|
637
|
+
const worker = options.worker;
|
|
638
|
+
if (!worker) throw new Error("attachSyncClient: provide a `worker` or a `port`.");
|
|
639
|
+
if (worker.port) return worker.port;
|
|
640
|
+
if (worker.postMessage && worker.addEventListener && worker.removeEventListener) {
|
|
641
|
+
return worker as BridgePort;
|
|
642
|
+
}
|
|
643
|
+
throw new Error("attachSyncClient: the provided `worker` is neither a Worker nor a SharedWorker port.");
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** Rebuild an Error from the bridge's serialized `{message, detail}` shape, carrying `detail` through. */
|
|
647
|
+
function rebuildError(error: RpcResultPayload["error"]): Error {
|
|
648
|
+
const rebuilt = new Error(error?.message ?? "worker rpc failed");
|
|
649
|
+
if (error && "detail" in error && error.detail !== undefined) {
|
|
650
|
+
(rebuilt as Error & { detail?: unknown }).detail = error.detail;
|
|
651
|
+
}
|
|
652
|
+
return rebuilt;
|
|
653
|
+
}
|