@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
package/dist/index.d.ts
CHANGED
|
@@ -1,27 +1,288 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type Results } from "@electric-sql/pglite";
|
|
2
2
|
import { type PGliteWithLive } from "@electric-sql/pglite/live";
|
|
3
3
|
import type { PgliteDatabase } from "drizzle-orm/pglite";
|
|
4
|
-
import type { MutationDiagnostics, RegistryRelations, RegistryViews, SyncRuntimeStatus, SyncTableCreateInput, SyncTableName, SyncTableRegistry, SyncTableUpdateInput } from "@pgxsinkit/contracts";
|
|
5
|
-
import {
|
|
4
|
+
import type { MutationAck, MutationDiagnostics, RegistryRelations, RegistryViews, SyncRuntimeStatus, SyncTableCreateInput, SyncTableName, SyncTableRegistry, SyncTableUpdateInput, WriteMode } from "@pgxsinkit/contracts";
|
|
5
|
+
import { type BootReport } from "./boot-report";
|
|
6
|
+
import { type ConvergenceTrigger } from "./convergence";
|
|
7
|
+
import { type DataExportOptions, type DataExportResult } from "./export-data";
|
|
8
|
+
import { type DiagnosticExportOptions, type DiagnosticExportResult } from "./export-dump";
|
|
9
|
+
import { type StoreExportOptions, type StoreExportResult } from "./export-store";
|
|
10
|
+
import { type LocalStoreVersionEvent } from "./local-store";
|
|
6
11
|
import { type MutationBatchItem, type MutationDetail, type MutationKind } from "./mutation";
|
|
7
12
|
import { generateLocalSchemaSql } from "./schema";
|
|
13
|
+
import { type StorePathInput } from "./store-path";
|
|
14
|
+
import { type SyncEngine } from "./sync";
|
|
8
15
|
export { generateLocalSchemaSql };
|
|
9
|
-
export
|
|
10
|
-
|
|
11
|
-
}
|
|
16
|
+
export { wrapLiveQueryForMaterialization } from "./live-rows-sql";
|
|
17
|
+
export type { BootReport } from "./boot-report";
|
|
18
|
+
export { type CloneDumpPhases, type CloneDumpResult, type DiagnosticExportDeps, type DiagnosticExportOptions, type DiagnosticExportResult, performDiagnosticExport, runThrowawayCloneDump, } from "./export-dump";
|
|
19
|
+
export { type DataExportDeps, DataExportDrainError, type DataExportOptions, type DataExportResult, DEFAULT_DRAIN_TIMEOUT_MS, type DrainJournalOption, type DrainJournalOptions, performDataExport, } from "./export-data";
|
|
20
|
+
export { type DataExportReport, deriveStoreId, type DiagnosticDumpReport, type ExportReport, type ExportReportCommon, performDatadirDump, performStoreExport, type StoreBackupReport, type StoreExportDeps, type StoreExportOptions, type StoreExportResult, } from "./export-store";
|
|
21
|
+
export { createLifecycleSlot, LifecycleBusyError, type LifecycleSlot } from "./lifecycle-slot";
|
|
22
|
+
export { InvalidStorePathError, NonPersistentStoreError, resolveStoreDataDir, RestoreTargetExistsError, storeIndexedDbDatabaseName, storeTargetExists, } from "./store-path";
|
|
23
|
+
export { type ConvergenceClient, type ConvergenceDriver, type ConvergenceDriverOptions, type ConvergenceTrigger, createBrowserConvergenceTrigger, createConvergenceDriver, createIntervalConvergenceTrigger, } from "./convergence";
|
|
24
|
+
export { instrumentShapeFetch, setSyncDebugSink, syncDebug, timeAsync } from "./debug";
|
|
25
|
+
export { type AttachedSyncClient, attachSyncClient, type AttachSyncClientOptions, provisionSyncWorker, } from "./worker/attach-sync-client";
|
|
26
|
+
export { defineSyncWorker, type DefineSyncWorkerOptions, type SyncWorkerHost } from "./worker/define-sync-worker";
|
|
27
|
+
export { computeLiveDiff, type LiveDiffState, LiveRowsMaterializer, rowKey, seedLiveDiffState, } from "./worker/live-diff";
|
|
28
|
+
export { createWorkerTokenCache, type WorkerTokenCache } from "./worker/token-cache";
|
|
29
|
+
export { type AttachAckPayload, type AttachPayload, type AuthTokenSnapshot, BRIDGE_CHANNEL, BRIDGE_PROTOCOL_VERSION, type BridgeCodec, type BridgeEnvelope, type BridgeEvent, type BridgeMessageType, type BridgePort, encodeEnvelope, type ExportArtefactWire, identityCodec, isBridgeEnvelope, type LiveDiffPayload, type LiveInitialPayload, postBridgeMessage, type ProvisionAckPayload, type ProvisionPayload, type RpcOp, type RpcPayload, type RpcResultPayload, type SetOnlinePayload, type SubscribePayload, type TokenRequestPayload, type TokenResponsePayload, type WakePayload, } from "./worker/protocol";
|
|
30
|
+
export { assertLazyRefsActivated, buildLazyGuardIndex, findReferencedLazyKeysInSql, type LazyGuardIndex, LazyRelationNotActivatedError, } from "./lazy-guard";
|
|
31
|
+
export { getJournalTable, getLocalMetaTable, getOverlayTable, getReadModelView, getSyncedLocalTable, getSyncStateView, type JournalTable, type LocalMetaTable, type OverlayTable, type ReadModelView, type SyncStateView, } from "./local-tables";
|
|
32
|
+
export type { LocalStoreVersionEvent };
|
|
33
|
+
export type ClientPGlite = PGliteWithLive & {
|
|
34
|
+
electric: SyncEngine["namespace"];
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* The pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), consumed by
|
|
38
|
+
* {@link createClientPGlite} / {@link CreateSyncClientOptions.pgliteBootAssets}. The host fetches +
|
|
39
|
+
* compiles these on an earlier screen and hands the promise in, so `PGlite.create` skips its own lazy
|
|
40
|
+
* asset load — see the field's JSDoc for the accelerator geometry.
|
|
41
|
+
*/
|
|
42
|
+
export interface PgliteBootAssets {
|
|
43
|
+
pgliteWasmModule?: WebAssembly.Module;
|
|
44
|
+
initdbWasmModule?: WebAssembly.Module;
|
|
45
|
+
fsBundle?: Blob;
|
|
46
|
+
}
|
|
47
|
+
/** Options for {@link createClientPGlite}. */
|
|
48
|
+
export interface CreateClientPGliteOptions {
|
|
49
|
+
/**
|
|
50
|
+
* Pre-warmed PGlite boot assets (see {@link CreateSyncClientOptions.pgliteBootAssets}). Awaited and
|
|
51
|
+
* passed into `PGlite.create`; a rejected warm is caught to `undefined` (falls back to PGlite's own
|
|
52
|
+
* asset load), so it never fails the create.
|
|
53
|
+
*/
|
|
54
|
+
bootAssets?: Promise<PgliteBootAssets>;
|
|
55
|
+
/**
|
|
56
|
+
* @internal Test-only storage-backend override (ADR-0036). `"memory"` resolves the store to a
|
|
57
|
+
* scheme-selected in-memory store — the sanctioned unit-test/ephemeral lane. Never a product
|
|
58
|
+
* configuration: reached only through `@pgxsinkit/client/testing`, never consumer-facing.
|
|
59
|
+
*/
|
|
60
|
+
backendOverride?: "memory";
|
|
61
|
+
/**
|
|
62
|
+
* A store-backup tarball to seed the new store from (ADR-0035 decision 6, restore) — a `File`/`Blob` as
|
|
63
|
+
* produced by {@link SyncClient.exportStore}. Passed straight to PGlite's `loadDataDir`, so the created
|
|
64
|
+
* store boots ON the backup's datadir. Restore is a CREATION-path feature: the caller (`createSyncClient`)
|
|
65
|
+
* has already proven the target does not yet exist ({@link storeTargetExists}); this option carries no
|
|
66
|
+
* freshness check of its own. A corrupt/foreign tarball surfaces as a PGlite boot failure here.
|
|
67
|
+
*/
|
|
68
|
+
restoreFrom?: File | Blob;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Create the raw local PGlite store the sync client runs on — the SAME `PGlite.create` call
|
|
72
|
+
* {@link createSyncClient} makes internally (the `electric` + `live` extensions, pre-warmed boot-asset
|
|
73
|
+
* consumption, and the `boot pglite.create` rail stamp), extracted so exactly one implementation exists
|
|
74
|
+
* and a host can create the store EAGERLY on an earlier screen. Hand the returned (still-pending)
|
|
75
|
+
* instance to {@link CreateSyncClientOptions.precreatedPglite}: the client then owns schema exec, prepare
|
|
76
|
+
* hooks, journal recovery and store-version reconcile, exactly as its own `storePath` path does.
|
|
77
|
+
*
|
|
78
|
+
* Takes a plain store path (ADR-0036), never a storage URL — the backend is DERIVED (IndexedDB in a
|
|
79
|
+
* browser/worker, the filesystem on Bun/Node); a scheme-bearing path throws {@link InvalidStorePathError}.
|
|
80
|
+
* Also accepts the testing helper's output (`createClientPGlite(memoryStoreForTests("x"))`) so a test can
|
|
81
|
+
* mint a memory store without naming a backend.
|
|
82
|
+
*
|
|
83
|
+
* The instance is deliberately **schemaless** — the registry-derived local schema is role/registry
|
|
84
|
+
* dependent, so it is applied post-create by `createSyncClient`. The eager create buys only the expensive
|
|
85
|
+
* initdb (+ IDBFS open), which is the dominant cold-boot cost once the WASM is pre-warmed.
|
|
86
|
+
*
|
|
87
|
+
* `bootAssets` is the pre-warmed WASM/fs bundle (see {@link CreateSyncClientOptions.pgliteBootAssets}); a
|
|
88
|
+
* rejected warm is caught to `undefined`, so PGlite falls back to loading its own assets — never a failure.
|
|
89
|
+
*/
|
|
90
|
+
export declare function createClientPGlite(store: StorePathInput, options?: CreateClientPGliteOptions): Promise<ClientPGlite>;
|
|
12
91
|
export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
13
92
|
registry: TRegistry;
|
|
14
93
|
electricUrl: string;
|
|
15
94
|
writeUrl: string;
|
|
16
95
|
getAuthToken?: () => Promise<string | undefined>;
|
|
96
|
+
/**
|
|
97
|
+
* Static headers added to **every** read-shape and write request, alongside the per-request
|
|
98
|
+
* `Authorization` (which always wins). The toolkit is agnostic about deployment-gateway
|
|
99
|
+
* credentials, so this is the seam for them — e.g. a Supabase Cloud `apikey` header the platform
|
|
100
|
+
* function gateway expects. Sent even when no `getAuthToken` is supplied.
|
|
101
|
+
*/
|
|
102
|
+
requestHeaders?: Record<string, string>;
|
|
103
|
+
/**
|
|
104
|
+
* Extra static headers sent on the **write** path only (the mutation-flush POST), merged over
|
|
105
|
+
* {@link requestHeaders} (`{...requestHeaders, ...writeRequestHeaders}`). Read/shape requests never
|
|
106
|
+
* see these. The seam exists because the two ingress points have opposite geometry: the write
|
|
107
|
+
* function is DB-bound, so pinning it to the database's region (e.g. an `x-region` header) keeps its
|
|
108
|
+
* chatty function→DB protocol on a ~1ms loop; the read proxy's upstream is a globally-distributed
|
|
109
|
+
* CDN (Electric Cloud), so pinning reads away from the caller pays intercontinental round trips per
|
|
110
|
+
* catch-up hop. Put region/DB-affinity headers here; keep gateway credentials the reads also need
|
|
111
|
+
* (e.g. `apikey`) in the shared {@link requestHeaders}.
|
|
112
|
+
*/
|
|
113
|
+
writeRequestHeaders?: Record<string, string>;
|
|
17
114
|
syncEnabled?: boolean;
|
|
18
|
-
|
|
115
|
+
/**
|
|
116
|
+
* The local store's name (ADR-0036) — a PLAIN path/name, never a PGlite storage URL. The storage backend
|
|
117
|
+
* is DERIVED from the environment (IndexedDB in a browser/worker, the filesystem on Bun/Node); a
|
|
118
|
+
* scheme-bearing string (anything containing `://`) is rejected with {@link InvalidStorePathError}
|
|
119
|
+
* at boot. Defaults to a built-in overlay store name when omitted. A memory-backed store is not a product
|
|
120
|
+
* configuration — for the test/ephemeral lane, spread `memoryStoreForTests(...)` from
|
|
121
|
+
* `@pgxsinkit/client/testing` instead of naming one here.
|
|
122
|
+
*/
|
|
123
|
+
storePath?: string;
|
|
124
|
+
/**
|
|
125
|
+
* Pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), awaited and passed straight
|
|
126
|
+
* into `PGlite.create`. The intent is to hide PGlite's ~2.5s cold `boot pglite.create` cost —
|
|
127
|
+
* dominated by the WASM fetch+compile — behind user think-time: the host starts fetching/compiling
|
|
128
|
+
* these on an earlier screen (e.g. the login/identity picker) and hands the still-pending promise
|
|
129
|
+
* here, so by the time a store is opened the assets are already resolved and `PGlite.create` skips
|
|
130
|
+
* its own lazy asset load. Ignored when {@link pgliteInstance} is supplied (the caller owns that
|
|
131
|
+
* instance's boot). A rejected/failed warm is caught to `undefined` and never fails the boot — PGlite
|
|
132
|
+
* falls back to loading its own assets, so this is a pure best-effort accelerator.
|
|
133
|
+
*/
|
|
134
|
+
pgliteBootAssets?: Promise<PgliteBootAssets>;
|
|
19
135
|
resetSubscriptionKeys?: string[];
|
|
20
136
|
prepareLocalDbBeforeSchema?: (pglite: ClientPGlite) => Promise<void>;
|
|
21
137
|
prepareLocalDb?: (pglite: ClientPGlite) => Promise<void>;
|
|
22
138
|
onStatusChange?: (status: SyncRuntimeStatus) => void;
|
|
23
139
|
onTableInitialSync?: (tableKey: string) => void;
|
|
140
|
+
/**
|
|
141
|
+
* A fully-provisioned PGlite instance the CALLER owns end-to-end. The client runs NONE of its
|
|
142
|
+
* post-create boot steps against it — no schema exec, prepare hooks, or store-version reconcile
|
|
143
|
+
* (journal recovery still runs, as it does on every path). Use it only when the caller has already
|
|
144
|
+
* applied the registry schema itself. Contrast the three PGlite-provenance seams:
|
|
145
|
+
* - {@link storePath} (default) — the client creates the store AND runs every post-create step.
|
|
146
|
+
* - {@link precreatedPglite} — the caller creates the raw store (via {@link createClientPGlite}), but
|
|
147
|
+
* the client still runs every post-create step (schema/prepare/reconcile), exactly as `storePath` does.
|
|
148
|
+
* - `pgliteInstance` — the caller creates AND provisions the store; the client runs none of them.
|
|
149
|
+
*
|
|
150
|
+
* A caller-owned instance is REFUSED with {@link NonPersistentStoreError} if it is provably
|
|
151
|
+
* non-persistent (a `new PGlite()` default, or an in-memory store) — pgxsinkit's durability semantics
|
|
152
|
+
* assume a persisted store (ADR-0036). Acknowledge a deliberate test store by spreading
|
|
153
|
+
* `testStoreAcknowledgment()` from `@pgxsinkit/client/testing`.
|
|
154
|
+
*
|
|
155
|
+
* Mutually exclusive with {@link precreatedPglite} (supplying both throws).
|
|
156
|
+
*/
|
|
24
157
|
pgliteInstance?: ClientPGlite;
|
|
158
|
+
/**
|
|
159
|
+
* A raw PGlite instance the caller created EAGERLY (via {@link createClientPGlite}) — typically on an
|
|
160
|
+
* earlier screen, to hide the ~1.9s cold `initdb`/IDBFS open behind user think-time — but for which the
|
|
161
|
+
* client still owns EVERYTHING else: schema exec, prepare hooks, journal recovery, and store-version
|
|
162
|
+
* reconcile all run exactly as on the {@link storePath} path. This is the difference from
|
|
163
|
+
* {@link pgliteInstance} (which skips schema/prepare/reconcile because the caller owns them); see that
|
|
164
|
+
* option's JSDoc for the three-way distinction.
|
|
165
|
+
*
|
|
166
|
+
* The promise form lets the still-pending eager create be handed straight in. Precedence/validation:
|
|
167
|
+
* - Supplying both this and {@link pgliteInstance} throws — they claim different ownership.
|
|
168
|
+
* - {@link storePath} is used ONLY as the fallback store name if this promise REJECTS: a failed eager
|
|
169
|
+
* create is caught, logged on the boot rail, and the normal `storePath` create path runs instead (also
|
|
170
|
+
* consuming {@link pgliteBootAssets} if provided). The pattern is a pure accelerator, never a boot
|
|
171
|
+
* dependency.
|
|
172
|
+
* - A successfully-adopted instance is subject to the same {@link NonPersistentStoreError} refusal as
|
|
173
|
+
* {@link pgliteInstance} (checked after resolution, so the refusal propagates rather than being
|
|
174
|
+
* swallowed by the reject-fallback).
|
|
175
|
+
*/
|
|
176
|
+
precreatedPglite?: Promise<ClientPGlite>;
|
|
177
|
+
/**
|
|
178
|
+
* Restore the store from a **store backup** (ADR-0035 decision 6) — a `File`/`Blob` tarball as produced by
|
|
179
|
+
* {@link SyncClient.exportStore}. The client creates its store with the backup handed to PGlite's
|
|
180
|
+
* `loadDataDir`, so it boots ON the backup's datadir (synced cache + Overlay + Mutation journal, all the
|
|
181
|
+
* bytes that travelled inside it). Three restore-only rules apply, none of them optional:
|
|
182
|
+
*
|
|
183
|
+
* - **Fresh target only.** Refused with {@link RestoreTargetExistsError} if a store already exists at the
|
|
184
|
+
* resolved {@link storePath} — restore never overlays a live store (that would corrupt the datadir); the
|
|
185
|
+
* remedy is a deliberate {@link SyncClient.destroy} of the existing store first.
|
|
186
|
+
* - **Always boots offline.** The engine boots with sync OFF regardless of {@link syncEnabled}/{@link autoSync}
|
|
187
|
+
* or anything captured in the backup — no shape streams, no read fetch, no flush, no convergence passes.
|
|
188
|
+
* Restore wins over an explicit online option (a debug-rail warning notes the override). The app inspects
|
|
189
|
+
* {@link SyncClient.diagnostics}, releases/discards the quarantined rows, then a subsequent NORMAL boot of
|
|
190
|
+
* the (now-persisted) store brings sync online — `loadDataDir` happens exactly once, on this restore boot.
|
|
191
|
+
* - **Journal quarantined.** Every non-terminal recovered row (`pending`/`sending`/`failed`) is moved to
|
|
192
|
+
* `quarantined` — nothing recovered from a backup auto-flushes (the write path has no `mutationId` dedupe
|
|
193
|
+
* ledger, so replay is unsafe on last-write-wins tables). Release (`retryFailed`) or discard
|
|
194
|
+
* (`discardQuarantined`) them explicitly.
|
|
195
|
+
*
|
|
196
|
+
* Mutually exclusive with {@link pgliteInstance} AND {@link precreatedPglite} — restore owns the store's
|
|
197
|
+
* creation (`loadDataDir` is a create-time seed), so a caller-supplied instance conflicts (supplying either
|
|
198
|
+
* with `restoreFrom` throws).
|
|
199
|
+
*/
|
|
200
|
+
restoreFrom?: File | Blob;
|
|
201
|
+
/**
|
|
202
|
+
* PROVABLY-fresh store hint (ADR-0032 S4 / backlog-0003): the caller guarantees this store is brand-new
|
|
203
|
+
* and schemaless — no prior schema, no synced rows, no persisted subscription state. When set (and sync
|
|
204
|
+
* is enabled, and the client owns schema exec — i.e. not the {@link pgliteInstance} path), the shape
|
|
205
|
+
* catch-up is started BEFORE the local boot phases (schema exec, journal recovery, store-version
|
|
206
|
+
* reconcile) and buffered in memory, with commits gated until those phases finish — so the network
|
|
207
|
+
* catch-up overlaps them instead of running strictly after. On a far-from-database caller this collapses
|
|
208
|
+
* boot from `local-phases + catch-up` toward `max(local-phases, catch-up)`.
|
|
209
|
+
*
|
|
210
|
+
* MUST be set only when freshness is proven, never derived by probing — a claimed schemaless spare (the
|
|
211
|
+
* board's claim path knows: a claimed spare is always fresh; a mapped/returning store never is). A wrong
|
|
212
|
+
* `true` on a warm store would start the streams from offset 0 and skip the subscription-state read,
|
|
213
|
+
* re-snapshotting instead of resuming. Absent/false → the exact sequential path (the default, correct for
|
|
214
|
+
* every warm store).
|
|
215
|
+
*/
|
|
216
|
+
freshStore?: boolean;
|
|
217
|
+
/**
|
|
218
|
+
* Hard cap on send attempts before a still-failing mutation is quarantined
|
|
219
|
+
* (ADR-0005 congestion policy). Defaults to the library's built-in cap.
|
|
220
|
+
*/
|
|
221
|
+
maxMutationAttempts?: number;
|
|
222
|
+
/**
|
|
223
|
+
* Invoked when mutations are quarantined (permanently rejected by the server, terminal). The library
|
|
224
|
+
* surfaces them here rather than silently dropping or retry-looping (ADR-0006). Surface, then either
|
|
225
|
+
* re-author + resubmit or roll back via {@link SyncClient.discardQuarantined} — which clears the kept
|
|
226
|
+
* overlay + quarantined journal rows so the entity accepts new mutations again.
|
|
227
|
+
*/
|
|
228
|
+
onQuarantine?: (quarantined: MutationDetail[]) => void | Promise<void>;
|
|
229
|
+
/**
|
|
230
|
+
* Invoked when mutations are `conflicted` — a stale write the server declined under the
|
|
231
|
+
* `reject-if-stale` Conflict policy (ADR-0015). The optimistic Overlay is kept, so the app shows a
|
|
232
|
+
* resolution/diff UI and resolves each as a new write (`mutate.update`) or `discardConflict`s it.
|
|
233
|
+
*/
|
|
234
|
+
onConflict?: (conflicted: MutationDetail[]) => void | Promise<void>;
|
|
235
|
+
/**
|
|
236
|
+
* Invoked when a pessimistic write-unit is `rejected` (ADR-0022) — a business decline from the
|
|
237
|
+
* authoritative endpoint (capacity/quota/uniqueness). The inverse of `onConflict`: the optimistic Overlay
|
|
238
|
+
* was auto-discarded for the whole unit, so the app surfaces the typed reason rather than a resolve UI.
|
|
239
|
+
*/
|
|
240
|
+
onReject?: (rejected: MutationDetail[]) => void | Promise<void>;
|
|
241
|
+
/**
|
|
242
|
+
* Invoked on boot when the registry fingerprint differs from the one the local store was
|
|
243
|
+
* provisioned under (ADR-0006). `rebuilt` = the read cache was dropped and rebuilt at the
|
|
244
|
+
* new shape; `deferred` = un-flushed/quarantined writes are still owed, so the rebuild is
|
|
245
|
+
* postponed (and retried on a later boot) rather than dropping owed data.
|
|
246
|
+
*/
|
|
247
|
+
onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;
|
|
248
|
+
/**
|
|
249
|
+
* Opt-in convergence driver (ADR-0005). Supply a {@link ConvergenceTrigger} (e.g.
|
|
250
|
+
* `createBrowserConvergenceTrigger()`) and the client drives `flush`/`reconcile`/`retryFailed`
|
|
251
|
+
* on the trigger's schedule, started once sync is ready and stopped on `stop()`/`destroy()`.
|
|
252
|
+
* Omit it for fully-manual convergence (the mechanism primitives stay public either way).
|
|
253
|
+
*/
|
|
254
|
+
autoSync?: ConvergenceTrigger;
|
|
255
|
+
/** Invoked after each automatic convergence pass with its error, or `null` on success (only when `autoSync` is set). */
|
|
256
|
+
onConvergencePass?: (error: unknown) => void;
|
|
257
|
+
/**
|
|
258
|
+
* Invoked when a read-path sync commit fails after exhausting its retries (ADR-0009 decision 5).
|
|
259
|
+
* The runtime enters the `degraded` phase and holds the read cache at the last applied commit
|
|
260
|
+
* instead of silently diverging from the server; recovery is a later commit or a restart/refetch.
|
|
261
|
+
*/
|
|
262
|
+
onSyncError?: (error: Error) => void;
|
|
263
|
+
/**
|
|
264
|
+
* Boot observability (ADR-0034): invoked exactly once, at boot completion, with the finalized
|
|
265
|
+
* {@link BootReport}. The push counterpart of {@link SyncClient.bootReport} (the pull) for consumers that
|
|
266
|
+
* want the numbers without polling — dashboards, CI budget gates. Never fired before initial sync; a
|
|
267
|
+
* `stop()`/`destroy()` before then means it never fires.
|
|
268
|
+
*/
|
|
269
|
+
onBootReport?: (report: BootReport) => void;
|
|
270
|
+
/**
|
|
271
|
+
* @internal Boot mode stamped into the {@link BootReport} (ADR-0034). `defineSyncWorker` sets `"worker"`;
|
|
272
|
+
* absent → `"in-process"`. Not a behavior knob — it only labels the report.
|
|
273
|
+
*/
|
|
274
|
+
bootMode?: BootReport["mode"];
|
|
275
|
+
/**
|
|
276
|
+
* @internal Provision timing for a boot that ADOPTS a pre-provisioned store (ADR-0034). When the store was
|
|
277
|
+
* minted ahead of boot (a spare's off-thread initdb), the provisioner stamps its create cost and ready
|
|
278
|
+
* time here; the boot reports them as {@link BootReport.provision} and sets `phases.pgliteCreateMs = null`.
|
|
279
|
+
* A promise because the stamp settles with the spare's `create`. Only honoured on the {@link precreatedPglite}
|
|
280
|
+
* adoption path (ignored on a fallback create). `provisionReadyAt` must share this process's monotonic clock.
|
|
281
|
+
*/
|
|
282
|
+
provisionStamp?: Promise<{
|
|
283
|
+
initdbMs: number;
|
|
284
|
+
provisionReadyAt: number;
|
|
285
|
+
}>;
|
|
25
286
|
}
|
|
26
287
|
export interface SyncClientTableHandle<TRegistry extends SyncTableRegistry, TKey extends SyncTableName<TRegistry>> {
|
|
27
288
|
key: TKey;
|
|
@@ -30,6 +291,120 @@ export interface SyncClientTableHandle<TRegistry extends SyncTableRegistry, TKey
|
|
|
30
291
|
update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => Promise<void>;
|
|
31
292
|
delete: (entityKey: Record<string, string>) => Promise<void>;
|
|
32
293
|
}
|
|
294
|
+
/**
|
|
295
|
+
* A table handle inside a {@link SyncClient.transaction} block (ADR-0022 §2). It *collects* mutations into
|
|
296
|
+
* the open write-unit rather than enqueuing each immediately; the whole set is enqueued atomically when the
|
|
297
|
+
* block's callback returns. The calls are synchronous (collection only) — no per-call await needed.
|
|
298
|
+
*/
|
|
299
|
+
export interface SyncTransactionTableHandle<TRegistry extends SyncTableRegistry, TKey extends SyncTableName<TRegistry>> {
|
|
300
|
+
create: (input: SyncTableCreateInput<TRegistry, TKey>) => void;
|
|
301
|
+
update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => void;
|
|
302
|
+
delete: (entityKey: Record<string, string>) => void;
|
|
303
|
+
/**
|
|
304
|
+
* An **update-by-key with no local base row** (ADR-0022 addendum). Ordinary `update` requires the entity
|
|
305
|
+
* to be present in the actor's local read model (it seeds the optimistic overlay and captures the base
|
|
306
|
+
* server version); `updateBlind` skips that presence check and writes NO overlay — nothing appears in the
|
|
307
|
+
* read model. Use it when the write target is deliberately EXCLUDED from your read shape (a write-only
|
|
308
|
+
* flow, or an anonymity-scoped moderation write whose row streams only to a different projection), so there
|
|
309
|
+
* is no local row to update and nothing to show optimistically.
|
|
310
|
+
*
|
|
311
|
+
* **Pessimistic-only.** The /unit expander is authoritative for the outcome, so a blind write is meaningful
|
|
312
|
+
* only inside a `transaction({ mode: "pessimistic" })` block (or over a statically-pessimistic table). An
|
|
313
|
+
* optimistic-routed blind write has nothing to converge and THROWS at enqueue.
|
|
314
|
+
*
|
|
315
|
+
* The acked journal row **retires without a synced echo** (no visible row ever converges for it), so it does
|
|
316
|
+
* not linger — unlike the seed-a-phantom-row workaround this replaces, whose acked row + overlay lingered
|
|
317
|
+
* forever behind the echo barrier. A `conflicted` blind write stays dischargeable via `discardConflict`; a
|
|
318
|
+
* `rejected` one is surfaced via `onReject`, both with no overlay to clean up.
|
|
319
|
+
*/
|
|
320
|
+
updateBlind: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => void;
|
|
321
|
+
}
|
|
322
|
+
/** The handle passed to a {@link SyncClient.transaction} callback: collecting table handles for the unit. */
|
|
323
|
+
export interface SyncTransaction<TRegistry extends SyncTableRegistry> {
|
|
324
|
+
tables: {
|
|
325
|
+
[TKey in SyncTableName<TRegistry>]: SyncTransactionTableHandle<TRegistry, TKey>;
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* The result of a {@link SyncClient.transaction}. A `pessimistic` block carries the authoritative server
|
|
330
|
+
* `acks` (each `acked` / `conflicted` / `rejected`); an `optimistic` block enqueues atomically and flushes
|
|
331
|
+
* in the background, so its `acks` are empty.
|
|
332
|
+
*/
|
|
333
|
+
export interface SyncTransactionResult {
|
|
334
|
+
acks: MutationAck[];
|
|
335
|
+
}
|
|
336
|
+
/** Minimal shape of a Drizzle select builder: inspectable via `.toSQL()` and awaitable for its rows. */
|
|
337
|
+
export interface DrizzleQueryBuilder<TRows extends readonly unknown[]> extends PromiseLike<TRows> {
|
|
338
|
+
toSQL(): {
|
|
339
|
+
sql: string;
|
|
340
|
+
params: unknown[];
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* The builder callback for a guarded read (ADR-0021): it receives the client and returns a Drizzle
|
|
345
|
+
* select builder. Reach relations through `c.views` / `c.drizzle` / a directly-imported synced table.
|
|
346
|
+
*/
|
|
347
|
+
export type GuardedQueryFn<TRegistry extends SyncTableRegistry, TRows extends readonly unknown[]> = (client: SyncClient<TRegistry>) => DrizzleQueryBuilder<TRows>;
|
|
348
|
+
/**
|
|
349
|
+
* A guarded query whose builder MAY embed a raw `sql` template fragment (ADR-0021). A raw fragment can
|
|
350
|
+
* name a lazy relation as a bare/unquoted identifier the compiled-SQL scan cannot see, so declare those
|
|
351
|
+
* relations in `use` — they are activated and awaited before the query runs. Pure-Drizzle reads need no
|
|
352
|
+
* `use` (the scan detects every relation): pass the builder callback directly to `client.query`.
|
|
353
|
+
*/
|
|
354
|
+
export interface GuardedRawQuerySpec<TRegistry extends SyncTableRegistry, TRows extends readonly unknown[]> {
|
|
355
|
+
use?: readonly SyncTableName<TRegistry>[];
|
|
356
|
+
build: GuardedQueryFn<TRegistry, TRows>;
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Inputs to the read-path safety seam {@link SyncClient.prepareQuery}. The lazy relations a query reads
|
|
360
|
+
* are detected by scanning the compiled `sql` (union with the optional explicit `use`), then activated.
|
|
361
|
+
* Shared by the live React hooks and the non-live facade.
|
|
362
|
+
*/
|
|
363
|
+
export interface PrepareQueryInput<TRegistry extends SyncTableRegistry> {
|
|
364
|
+
/** The compiled (parameterised) Drizzle SQL the query will run — the scan's ground-truth target. */
|
|
365
|
+
sql: string;
|
|
366
|
+
/** Lazy relations to also activate, beyond those scanned from `sql` — a pre-activation hint, not required. */
|
|
367
|
+
use?: readonly SyncTableName<TRegistry>[];
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* The narrow live-rows seam (ADR-0032 S2 §4) both client modes implement so the `@pgxsinkit/react` hooks
|
|
371
|
+
* work against either. Input for a reactive subscription: the compiled SQL + params (from a Drizzle
|
|
372
|
+
* builder's `.toSQL()` or a raw string) and the result's `pkColumns` (drives worker-side diff keying;
|
|
373
|
+
* omit for a keyless query). The in-process client runs it directly over `pglite.live`; the worker-attached
|
|
374
|
+
* client runs the live query in the worker and streams DIFFs across the bridge.
|
|
375
|
+
*/
|
|
376
|
+
export interface SubscribeLiveRowsInput {
|
|
377
|
+
sql: string;
|
|
378
|
+
params: readonly unknown[];
|
|
379
|
+
/**
|
|
380
|
+
* The unique output aliases to render the query's columns under so it is SAFE TO MATERIALISE, in the
|
|
381
|
+
* compiled SQL's column order (one per output column). Drizzle emits no output aliases, so a JOIN whose
|
|
382
|
+
* tables share a column name compiles to duplicate output names — which PGlite's `live` extension
|
|
383
|
+
* refuses to materialise (`column "title" specified more than once`) and which silently collapse
|
|
384
|
+
* same-named columns even in a plain query. When supplied, the seam wraps the query so every output
|
|
385
|
+
* column gets its alias and rows come back KEYED BY THESE ALIASES; the consumer's row-mapper must read
|
|
386
|
+
* by alias (the `@pgxsinkit/react` hooks do). Omit for a raw or non-colliding query — the seam then
|
|
387
|
+
* leaves the SQL untouched and rows stay keyed by the underlying column names (backward-compatible).
|
|
388
|
+
*/
|
|
389
|
+
fields?: readonly string[];
|
|
390
|
+
/**
|
|
391
|
+
* The result's PK columns — the diff-keying identity across the bridge (§4). Omit for a keyless query.
|
|
392
|
+
* When {@link fields} is supplied the result columns are the aliases, so a PK column here must be named
|
|
393
|
+
* by its ALIAS (the aliased result column), not the underlying source column.
|
|
394
|
+
*/
|
|
395
|
+
pkColumns?: readonly string[];
|
|
396
|
+
/**
|
|
397
|
+
* Lazy relations (ADR-0021) to activate before the query runs — forwarded to the worker so it can
|
|
398
|
+
* `prepareQuery` before registering the live query (the tab's own `prepareQuery` is a no-op against the
|
|
399
|
+
* worker bridge). Ignored by the in-process client, whose `prepareQuery` already ran on the tab.
|
|
400
|
+
*/
|
|
401
|
+
use?: readonly string[];
|
|
402
|
+
}
|
|
403
|
+
/** A handle to a live-rows subscription: the initial ordered snapshot plus an idempotent unsubscribe. */
|
|
404
|
+
export interface LiveRowsSubscription<TRow> {
|
|
405
|
+
initialRows: TRow[];
|
|
406
|
+
unsubscribe: () => void;
|
|
407
|
+
}
|
|
33
408
|
export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
34
409
|
drizzle: PgliteDatabase<RegistryRelations<TRegistry>>;
|
|
35
410
|
pglite: ClientPGlite;
|
|
@@ -41,7 +416,26 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
41
416
|
status: SyncRuntimeStatus;
|
|
42
417
|
start: () => Promise<void>;
|
|
43
418
|
stop: () => Promise<void>;
|
|
44
|
-
|
|
419
|
+
/**
|
|
420
|
+
* Wipe the entire local store (synced cache + overlay + journal) and close the handle
|
|
421
|
+
* (ADR-0005). Refuses if mutations are still owed to the server unless `force` is set, so
|
|
422
|
+
* it never silently drops un-flushed writes. Distinct from `stop()`, which only halts sync.
|
|
423
|
+
* Runs under the single lifecycle slot (ADR-0035 decision 4): a concurrent export — or another
|
|
424
|
+
* `destroy`/`discardEphemeral`/`dropReadCache` — rejects with a {@link LifecycleBusyError} rather
|
|
425
|
+
* than interleaving the wipe with a running export.
|
|
426
|
+
*/
|
|
427
|
+
destroy: (options?: {
|
|
428
|
+
force?: boolean;
|
|
429
|
+
}) => Promise<void>;
|
|
430
|
+
/**
|
|
431
|
+
* Drop and rebuild the reconstructible synced read cache, preserving the overlay and
|
|
432
|
+
* mutation journal (ADR-0006). The next sync refills it. Use to recover from a corrupt or
|
|
433
|
+
* stale read cache without losing un-flushed writes. Runs under the single lifecycle slot
|
|
434
|
+
* (ADR-0035 decision 4) — it drops and rebuilds the synced tables, so an export must not capture a
|
|
435
|
+
* half-rebuilt cache; a concurrent export (or `destroy`/`discardEphemeral`) rejects with a
|
|
436
|
+
* {@link LifecycleBusyError}.
|
|
437
|
+
*/
|
|
438
|
+
dropReadCache: () => Promise<void>;
|
|
45
439
|
flush: (table?: SyncTableName<TRegistry>) => Promise<void>;
|
|
46
440
|
reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;
|
|
47
441
|
retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;
|
|
@@ -53,10 +447,223 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
53
447
|
delete: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;
|
|
54
448
|
batch: (items: ReadonlyArray<MutationBatchItem<TRegistry>>) => Promise<void>;
|
|
55
449
|
};
|
|
450
|
+
/**
|
|
451
|
+
* Discard a `conflicted` entity (ADR-0015): clear its conflicted journal entry and kept optimistic
|
|
452
|
+
* Overlay, so the Read model falls back to the synced (server) value. Use when the user abandons a
|
|
453
|
+
* stale edit instead of resolving it as a new write.
|
|
454
|
+
*/
|
|
455
|
+
discardConflict: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;
|
|
456
|
+
/**
|
|
457
|
+
* Discard a `quarantined` entity (ADR-0006): clear its quarantined journal entry and kept optimistic
|
|
458
|
+
* Overlay, so the Read model falls back to the synced (server) value. The rollback path for a write
|
|
459
|
+
* the server permanently rejected — e.g. an RLS policy denial (42501) routed to quarantine. After the
|
|
460
|
+
* discard the phantom optimistic row is gone and the entity accepts new mutations again (no longer
|
|
461
|
+
* blocked behind the quarantined head). Symmetric to {@link SyncClient.discardConflict}; the overlay
|
|
462
|
+
* is kept when another still-owed write depends on it. No-op for an entity with no quarantined entry.
|
|
463
|
+
*/
|
|
464
|
+
discardQuarantined: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;
|
|
56
465
|
diagnostics: (table?: SyncTableName<TRegistry>) => Promise<{
|
|
57
466
|
mutation: MutationDiagnostics;
|
|
58
467
|
}>;
|
|
468
|
+
/**
|
|
469
|
+
* The INSPECTION read surface (debug pages, REPLs, ad-hoc counts) — identical on the in-process and
|
|
470
|
+
* worker-attached client (on the latter the statement runs in the worker). The statement runs raw
|
|
471
|
+
* against the local store: it BYPASSES the mutation journal and optimistic overlay, and any write it
|
|
472
|
+
* issues stays local and will NOT converge. For app data reads prefer the live-rows hooks /
|
|
473
|
+
* {@link subscribeLiveRows} (or the guarded {@link query} family); reach for this only to look at the
|
|
474
|
+
* store, not to read app state or mutate it.
|
|
475
|
+
*/
|
|
476
|
+
rawQuery: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;
|
|
477
|
+
/** {@link rawQuery} for multi-statement SQL, returning one {@link Results} per statement. */
|
|
478
|
+
rawExec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;
|
|
479
|
+
/**
|
|
480
|
+
* Run a one-shot (non-live) typed **pure-Drizzle** query with the lazy-relation safety net (ADR-0021).
|
|
481
|
+
* Pass the builder callback directly — pgxsinkit scans the compiled SQL and activates + awaits every
|
|
482
|
+
* lazy relation it reads (FROM, JOIN, subquery, WHERE) before it runs, and the tripwire rejects any
|
|
483
|
+
* lazy relation the SQL still references but that is not active, so the result is never silently
|
|
484
|
+
* empty/stale. The guaranteed-safe alternative to a bare `client.drizzle` read. If the builder embeds
|
|
485
|
+
* a raw `sql` template fragment, use {@link queryRaw} and declare the lazy relations in `use`.
|
|
486
|
+
*/
|
|
487
|
+
query: <TRows extends readonly unknown[]>(build: GuardedQueryFn<TRegistry, TRows>) => Promise<TRows>;
|
|
488
|
+
/** {@link query} returning the first row, or null when empty. */
|
|
489
|
+
queryRow: <TRows extends readonly unknown[]>(build: GuardedQueryFn<TRegistry, TRows>) => Promise<TRows[number] | null>;
|
|
490
|
+
/**
|
|
491
|
+
* {@link query} for a builder that embeds a raw `sql` template fragment (ADR-0021). The compiled-SQL
|
|
492
|
+
* scan can miss a lazy relation named as a bare/unquoted identifier inside raw SQL, so declare those
|
|
493
|
+
* in `use` — they are activated and awaited before the query runs. Pure-Drizzle reads should use
|
|
494
|
+
* {@link query} instead (no `use` needed).
|
|
495
|
+
*/
|
|
496
|
+
queryRaw: <TRows extends readonly unknown[]>(spec: GuardedRawQuerySpec<TRegistry, TRows>) => Promise<TRows>;
|
|
497
|
+
/** {@link queryRaw} returning the first row, or null when empty. */
|
|
498
|
+
queryRawRow: <TRows extends readonly unknown[]>(spec: GuardedRawQuerySpec<TRegistry, TRows>) => Promise<TRows[number] | null>;
|
|
499
|
+
/**
|
|
500
|
+
* Activate one or more lazy relations (ADR-0021): open their consistency-group subscription if held
|
|
501
|
+
* out of the eager boot, resolving once their initial sync completes. Idempotent — eager or
|
|
502
|
+
* already-started relations resolve immediately. Use to pre-activate before a raw/`client.drizzle`
|
|
503
|
+
* read, or as the manual escape hatch the tripwire points to.
|
|
504
|
+
*/
|
|
505
|
+
ensureSynced: (keys: readonly SyncTableName<TRegistry>[]) => Promise<void>;
|
|
506
|
+
/**
|
|
507
|
+
* Whether a relation's group has started and hydrated (ADR-0021). False for a still-dormant `lazy`
|
|
508
|
+
* relation; true for eager relations once boot completes (and always when sync is disabled).
|
|
509
|
+
*/
|
|
510
|
+
isSynced: (key: SyncTableName<TRegistry>) => boolean;
|
|
511
|
+
/**
|
|
512
|
+
* Revert a `lazy` relation to dormant (ADR-0021 §2) — the inverse of on-demand activation: stop its
|
|
513
|
+
* consistency group's stream, clear any persisted `lazy + persistent` activation (so the next boot
|
|
514
|
+
* holds it dormant again), and clean-truncate its local read cache. A later reference re-activates it
|
|
515
|
+
* from scratch. Refuses when the relation is `eager` (always-on, would immediately re-sync) or owes
|
|
516
|
+
* the server unsettled writes (the truncate would drop them — flush or discard first). The reclaim
|
|
517
|
+
* primitive a host wires to navigation/idle for a rarely-opened lazy view; for an `ephemeral`
|
|
518
|
+
* relation, idle-eviction is otherwise automatic at session end.
|
|
519
|
+
*/
|
|
520
|
+
desync: (key: SyncTableName<TRegistry>) => Promise<void>;
|
|
521
|
+
/**
|
|
522
|
+
* Drop an **ephemeral** relation's local rows and revert it to dormant (ADR-0021) — the narrow,
|
|
523
|
+
* scoped twin of {@link desync}. It runs the identical group-teardown machinery (stop the group stream,
|
|
524
|
+
* clear the persisted lazy activation, reset the persisted subscription, clean-truncate every member),
|
|
525
|
+
* but under a STRICTER gate: EVERY member of the relation's consistency group must be `retention:
|
|
526
|
+
* "ephemeral"` — it refuses (naming the offender) if any member is persistent. Where a `desync` from one
|
|
527
|
+
* tab reverts the shared group for every attached tab (the SharedWorker footgun), `discardEphemeral` is
|
|
528
|
+
* safe under multi-tab because an ephemeral window is per-delivery-session and inherently single-consumer
|
|
529
|
+
* — nothing durable, and no other tab, depends on it. Refuses an `eager` relation (always-on, would
|
|
530
|
+
* immediately re-sync) and a group that owes the server unsettled writes, exactly as `desync` does. The
|
|
531
|
+
* finalize primitive for a secure-delivery window: drop the local rows at session end without touching a
|
|
532
|
+
* durable relation. Note the drop is local-lifecycle only: a later re-subscription re-activates the lazy
|
|
533
|
+
* group and re-streams whatever the SERVER still serves — post-finalize non-redelivery is the server
|
|
534
|
+
* gate's guarantee (e.g. a consumed server-owned cursor), not this method's. Runs under the single
|
|
535
|
+
* lifecycle slot (ADR-0035 decision 4): a concurrent export (or `destroy`/`dropReadCache`) rejects with a
|
|
536
|
+
* {@link LifecycleBusyError} rather than interleaving the cache truncate with a running export.
|
|
537
|
+
*/
|
|
538
|
+
discardEphemeral: (key: SyncTableName<TRegistry>) => Promise<void>;
|
|
539
|
+
/**
|
|
540
|
+
* The read-path safety seam (ADR-0021): scan the compiled `sql` for the lazy relations it reads
|
|
541
|
+
* (∪ the optional `use`), activate them, and await their initial sync — so a lazy relation
|
|
542
|
+
* auto-activates on *any* reference (FROM, JOIN, subquery, WHERE). Resolves once it is safe to run the
|
|
543
|
+
* query; a backstop throws {@link LazyRelationNotActivatedError} only if a referenced relation could
|
|
544
|
+
* not be activated. Exposed for the React live hooks (which own their query build); `query`/`queryRow`
|
|
545
|
+
* are the higher-level non-live wrappers. Raw, non-Drizzle SQL is out of scope — pass `use`, or
|
|
546
|
+
* `ensureSynced` first.
|
|
547
|
+
*/
|
|
548
|
+
prepareQuery: (input: PrepareQueryInput<TRegistry>) => Promise<void>;
|
|
549
|
+
/**
|
|
550
|
+
* Author an atomic write-**unit** (ADR-0022 §2). The callback receives collecting table handles; every
|
|
551
|
+
* mutation it issues is tagged into one unit and enqueued atomically when the callback returns.
|
|
552
|
+
*
|
|
553
|
+
* - `mode: "pessimistic"` — **server-authoritative**: the unit flush-routes to the authoritative endpoint
|
|
554
|
+
* and this call resolves only once the server has decided. The result's `acks` carry each member's
|
|
555
|
+
* outcome — `acked`, `conflicted` (overlay kept, ADR-0015), or `rejected` (overlay auto-discarded for
|
|
556
|
+
* the whole unit, surfaced via `onReject`, ADR-0022 §4). Throws on transport failure (overlay kept). A
|
|
557
|
+
* pessimistic block may also issue {@link SyncTransactionTableHandle.updateBlind} — an update-by-key with
|
|
558
|
+
* no local base row and no overlay, for a write target excluded from the actor's read shape.
|
|
559
|
+
* - `mode: "optimistic"` — an atomic batch enqueue that flushes in the background (empty `acks`).
|
|
560
|
+
*/
|
|
561
|
+
transaction: (options: {
|
|
562
|
+
mode: WriteMode;
|
|
563
|
+
}, run: (tx: SyncTransaction<TRegistry>) => void | Promise<void>) => Promise<SyncTransactionResult>;
|
|
564
|
+
/**
|
|
565
|
+
* Per-group readiness (ADR-0032 decision 6): a promise resolving the moment the given table's
|
|
566
|
+
* consistency group is up-to-date. Resolves immediately for an already-ready (or sync-disabled)
|
|
567
|
+
* group; stays pending for a still-dormant `lazy` relation until it is activated and caught up. The
|
|
568
|
+
* opt-in progressive-paint signal beside the all-eager-groups `ready` gate. `status.groups` carries the
|
|
569
|
+
* same readiness as a synchronous snapshot.
|
|
570
|
+
*/
|
|
571
|
+
groupReady: (table: SyncTableName<TRegistry>) => Promise<void>;
|
|
572
|
+
/**
|
|
573
|
+
* The live-rows seam (ADR-0032 S2 §4): register a reactive query and receive its initial ordered
|
|
574
|
+
* snapshot plus subsequent updates via `onRows`. The React live hooks consume THIS (not `pglite.live`
|
|
575
|
+
* directly), so they run unchanged against both the in-process client (which implements it over
|
|
576
|
+
* `pglite.live`) and the worker-attached client (which implements it over the bridge). Prefer the
|
|
577
|
+
* higher-level `@pgxsinkit/react` hooks; this is the lower-level primitive they build on.
|
|
578
|
+
*/
|
|
579
|
+
subscribeLiveRows: <TRow extends Record<string, unknown> = Record<string, unknown>>(input: SubscribeLiveRowsInput, onRows: (rows: TRow[]) => void) => Promise<LiveRowsSubscription<TRow>>;
|
|
580
|
+
/**
|
|
581
|
+
* Boot observability (ADR-0034): the engine's most recent COMPLETED boot report, or `null` before the
|
|
582
|
+
* first boot finalizes (and after a `stop()`/`destroy()` that preceded initial sync). Pull — so a
|
|
583
|
+
* late-attaching tab can read a boot that predates it; in worker mode it round-trips to the worker's
|
|
584
|
+
* stored report. The push counterpart is the `onBootReport` client option.
|
|
585
|
+
*/
|
|
586
|
+
bootReport: () => Promise<BootReport | null>;
|
|
587
|
+
/**
|
|
588
|
+
* Take a **store backup** (ADR-0035): a full-fidelity, PGlite-restorable tarball of the whole local
|
|
589
|
+
* store — synced cache, Overlay, and Mutation journal (unflushed writes included) — via PGlite's
|
|
590
|
+
* `dumpDataDir`. Taken LIVE (a `CHECKPOINT` serialised behind engine work, then the dump; no engine
|
|
591
|
+
* suspension, no tab disruption), so it never blocks and is the only lossless export an offline device
|
|
592
|
+
* with unflushed writes can take. Awaits engine-ready rather than rejecting during boot, then runs under
|
|
593
|
+
* the single lifecycle slot: a second export (or, later, `destroy`/`discardEphemeral`) attempted while
|
|
594
|
+
* one is in flight rejects immediately with a {@link LifecycleBusyError} — retry once it settles.
|
|
595
|
+
* Resolves to the artefact `File` plus an {@link ExportReport} (phase timings + a diagnostics snapshot).
|
|
596
|
+
*/
|
|
597
|
+
exportStore: (options?: StoreExportOptions) => Promise<StoreExportResult>;
|
|
598
|
+
/**
|
|
599
|
+
* Take a **diagnostic dump** (ADR-0035): human-readable SQL of EVERYTHING the store holds — synced tables,
|
|
600
|
+
* the `_overlay`/`_mutations` journal (unflushed writes included — the evidence a diagnostic exists for),
|
|
601
|
+
* the `pgxsinkit` metadata schema, the read-model views, and the reconcile functions/triggers — via
|
|
602
|
+
* `pg_dump`. To keep `pg_dump`'s `DEALLOCATE ALL` away from the live engine, the dump runs against a
|
|
603
|
+
* memory-backed THROWAWAY clone booted from a live datadir dump (ADR-0035 addendum): the running store is
|
|
604
|
+
* never suspended and no tab is disrupted. Awaits engine-ready rather than rejecting during boot, then
|
|
605
|
+
* runs under the single lifecycle slot — a concurrent export (or `destroy`/`discardEphemeral`) rejects
|
|
606
|
+
* immediately with a {@link LifecycleBusyError}. Resolves to the SQL `File` (`application/sql`) plus a
|
|
607
|
+
* {@link DiagnosticDumpReport} (phase timings + a diagnostics snapshot). Active ephemeral (`pg_temp`)
|
|
608
|
+
* clusters are absent by construction (ADR-0035 decision 5 — `pg_dump` ignores temp objects).
|
|
609
|
+
*/
|
|
610
|
+
exportDiagnostics: (options?: DiagnosticExportOptions) => Promise<DiagnosticExportResult>;
|
|
611
|
+
/**
|
|
612
|
+
* Take a **data export** (ADR-0035): the PORTABLE artefact — the synced tables and the enum types they
|
|
613
|
+
* depend on, schema + data, nothing of pgxsinkit's machinery — as SQL loadable into a vanilla Postgres. It
|
|
614
|
+
* is a generated enum DDL header concatenated ahead of `pg_dump -t <table> ... --no-owner` (one `-t` per
|
|
615
|
+
* physical synced table; ephemeral/read-projection entries excluded by construction), run against the same
|
|
616
|
+
* memory-backed THROWAWAY clone the diagnostic dump uses — so the live engine is never touched.
|
|
617
|
+
*
|
|
618
|
+
* Unlike the other two exports it GUARDS the journal (decision 3): a strict export requires a DRAINED
|
|
619
|
+
* journal — all mutation counts zero, including `acked` writes whose synced echo has not landed (they live
|
|
620
|
+
* only in the Overlay). The drain flushes drainable rows and awaits convergence up to
|
|
621
|
+
* `drainJournal.timeoutMs` (default `15_000`); non-drainable states (`failed`/`quarantined`/`conflicted`)
|
|
622
|
+
* fail FAST with a {@link DataExportDrainError} carrying the diagnostics. `drainJournal: false` is the
|
|
623
|
+
* escape hatch — export synced state as-is (unflushed writes absent; `report.escapeHatch` records it). An
|
|
624
|
+
* offline device with a clean journal exports strictly and instantly; one with a dirty journal cannot
|
|
625
|
+
* produce a strict export (its lossless option is `exportStore`).
|
|
626
|
+
*
|
|
627
|
+
* Awaits engine-ready rather than rejecting during boot, then runs the whole drain+dump under the single
|
|
628
|
+
* lifecycle slot — a concurrent export (or `destroy`/`discardEphemeral`) rejects with a
|
|
629
|
+
* {@link LifecycleBusyError}. Resolves to the SQL `File` (`application/sql`) plus a {@link DataExportReport}
|
|
630
|
+
* (drain + clone-pipeline phase timings, the applied `-t` table list, and the escape-hatch flag).
|
|
631
|
+
*/
|
|
632
|
+
exportData: (options?: DataExportOptions) => Promise<DataExportResult>;
|
|
59
633
|
}
|
|
60
634
|
export type { MutationBatchItem, MutationDetail, MutationDiagnostics, MutationKind };
|
|
635
|
+
/**
|
|
636
|
+
* The structured-clone-safe subset of PGlite's `QueryOptions` the inspection surface carries. Kept
|
|
637
|
+
* narrow ON PURPOSE: on a worker-attached client the options object crosses the bridge via
|
|
638
|
+
* `postMessage`, so function-valued options (`parsers`, `serializers`, `onNotice`) can never be part
|
|
639
|
+
* of this contract. `rowMode: "array"` is what `@electric-sql/pglite-repl` asks for on every exec.
|
|
640
|
+
*/
|
|
641
|
+
export interface RawQueryOptions {
|
|
642
|
+
rowMode?: "object" | "array";
|
|
643
|
+
}
|
|
644
|
+
/** The `{ query, exec }` duck `@electric-sql/pglite-repl` drives, backed by a client's inspection surface. */
|
|
645
|
+
export interface ReplInspectionSurface {
|
|
646
|
+
query: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;
|
|
647
|
+
exec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Shape a {@link SyncClient}'s inspection surface (`rawQuery`/`rawExec`) as the `{ query, exec }` duck
|
|
651
|
+
* `@electric-sql/pglite-repl` needs. Identical on the in-process and worker-attached client — on the latter
|
|
652
|
+
* each statement routes through the worker bridge, so the REPL works even though `client.pglite` is
|
|
653
|
+
* unavailable. Cast the result at the `<Repl pg={...}>` prop (the REPL types the prop as a full `PGlite`).
|
|
654
|
+
* The surface is registry-independent, so it accepts any client's `rawQuery`/`rawExec` pair.
|
|
655
|
+
*/
|
|
656
|
+
export declare function replAdapter(client: Pick<SyncClient<SyncTableRegistry>, "rawQuery" | "rawExec">): ReplInspectionSurface;
|
|
61
657
|
export declare function createSyncClient<const TRegistry extends SyncTableRegistry>(options: CreateSyncClientOptions<TRegistry>): Promise<SyncClient<TRegistry>>;
|
|
658
|
+
/**
|
|
659
|
+
* The tab-side READ handles a worker-attached client exposes (ADR-0032 S2): a build-only Drizzle instance
|
|
660
|
+
* plus the registry views. On the attach client, Drizzle is used only to COMPILE queries to SQL
|
|
661
|
+
* (`.toSQL()`) on the tab — execution happens in the worker via the live-rows bridge / RPC — so it is
|
|
662
|
+
* constructed over a stub client that is never invoked (`construct` stores the client without calling it).
|
|
663
|
+
* The same builders `createSyncClient` uses, so a query built on either client compiles identically.
|
|
664
|
+
*/
|
|
665
|
+
export declare function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(registry: TRegistry): {
|
|
666
|
+
drizzle: PgliteDatabase<RegistryRelations<TRegistry>>;
|
|
667
|
+
views: RegistryViews<TRegistry>;
|
|
668
|
+
};
|
|
62
669
|
//# sourceMappingURL=index.d.ts.map
|