@pgxsinkit/client 0.1.31 → 0.1.36
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/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/index.d.ts +421 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7214 -2234
- package/dist/index.js.map +74 -44
- package/dist/lazy-guard.d.ts +58 -0
- package/dist/lazy-guard.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 +62 -0
- package/dist/mutation-state.d.ts.map +1 -0
- package/dist/mutation.d.ts +117 -4
- package/dist/mutation.d.ts.map +1 -1
- package/dist/schema.d.ts +49 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/shape-sync.d.ts +180 -0
- package/dist/shape-sync.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 +118 -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/worker/attach-sync-client.d.ts +75 -0
- package/dist/worker/attach-sync-client.d.ts.map +1 -0
- package/dist/worker/define-sync-worker.d.ts +75 -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 +260 -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 +19 -7
- package/skills/core/SKILL.md +197 -0
- package/skills/operating/SKILL.md +243 -0
- package/src/convergence.ts +197 -0
- package/src/debug.ts +151 -0
- package/src/index.ts +1104 -44
- package/src/lazy-guard.ts +121 -0
- package/src/local-store.ts +193 -0
- package/src/local-tables.ts +546 -0
- package/src/mutation-state.ts +90 -0
- package/src/mutation.ts +1868 -562
- package/src/schema.ts +352 -27
- package/src/shape-sync.ts +477 -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 +1076 -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 +132 -0
- package/src/sync-auth.ts +117 -0
- package/src/worker/attach-sync-client.ts +558 -0
- package/src/worker/define-sync-worker.ts +596 -0
- package/src/worker/live-diff.ts +140 -0
- package/src/worker/protocol.ts +325 -0
- package/src/worker/token-cache.ts +84 -0
package/README.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# @pgxsinkit/client
|
|
2
|
+
|
|
3
|
+
The [pgxsinkit](https://pgxsinkit.github.io) client: `createSyncClient` stages writes
|
|
4
|
+
into a local PGlite overlay and a durable mutation journal, flushes them to the write
|
|
5
|
+
API, and subscribes to Electric shapes that land in local PGlite.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
bun add @pgxsinkit/client @pgxsinkit/contracts
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
See the [documentation](https://pgxsinkit.github.io) for the read and write paths.
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The opt-in convergence driver (ADR-0005 decision 3).
|
|
3
|
+
*
|
|
4
|
+
* The mechanism primitives (`flush` / `reconcile` / `retryFailed`) stay public and manual.
|
|
5
|
+
* This driver is the *scheduling-policy seam*: the app decides WHEN to converge (online?
|
|
6
|
+
* foregrounded? on power?) and how it learns those conditions, while the library owns the
|
|
7
|
+
* convergence pass and the congestion policy (jittered backoff + attempt cap, already in the
|
|
8
|
+
* mutation runtime). Pass nothing to `createSyncClient` → fully manual, today's behaviour.
|
|
9
|
+
*
|
|
10
|
+
* A pass is `flush` → `reconcile`. It deliberately does NOT call `retryFailed`: `flush`
|
|
11
|
+
* already re-attempts `failed` mutations whose `next_retry_at_us` backoff has elapsed, so a
|
|
12
|
+
* pass leaves the jittered backoff intact. Calling `retryFailed` on every pass would reset
|
|
13
|
+
* every failed mutation to "due now" and, under a short trigger interval, burn the whole
|
|
14
|
+
* attempt budget during a transient outage and quarantine writes prematurely. `retryFailed`
|
|
15
|
+
* stays a manual, user-initiated primitive ("retry my failed writes now").
|
|
16
|
+
*/
|
|
17
|
+
/** The mechanism primitives a convergence pass schedules. */
|
|
18
|
+
export interface ConvergenceClient {
|
|
19
|
+
flush: () => Promise<void>;
|
|
20
|
+
reconcile: () => Promise<void>;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The scheduling-policy seam. Browser (`online` / `visibilitychange`) and React Native
|
|
24
|
+
* (`AppState` / `NetInfo`) are two genuine adapters — which is what earns this its place as a
|
|
25
|
+
* seam rather than being inlined.
|
|
26
|
+
*/
|
|
27
|
+
export interface ConvergenceTrigger {
|
|
28
|
+
/** Register a callback fired whenever the app wants a convergence attempt; returns an unsubscribe. */
|
|
29
|
+
subscribe: (onSignal: () => void) => () => void;
|
|
30
|
+
/** Whether a convergence pass should run right now (e.g. online and foregrounded). */
|
|
31
|
+
shouldConverge: () => boolean;
|
|
32
|
+
}
|
|
33
|
+
export interface ConvergenceDriverOptions {
|
|
34
|
+
client: ConvergenceClient;
|
|
35
|
+
trigger: ConvergenceTrigger;
|
|
36
|
+
/** Invoked after each convergence pass with the error it raised, or `null` on success. */
|
|
37
|
+
onPass?: (error: unknown) => void;
|
|
38
|
+
}
|
|
39
|
+
export interface ConvergenceDriver {
|
|
40
|
+
start: () => void;
|
|
41
|
+
/**
|
|
42
|
+
* Stop scheduling and **await any in-flight pass** before resolving, so a caller can then
|
|
43
|
+
* safely close or wipe the underlying database without a pass racing against it. Idempotent.
|
|
44
|
+
*/
|
|
45
|
+
stop: () => Promise<void>;
|
|
46
|
+
/**
|
|
47
|
+
* Request a convergence pass now — the event-driven path. The client calls this the moment a
|
|
48
|
+
* mutation is enqueued, so a local write flushes immediately instead of waiting for the trigger's
|
|
49
|
+
* next interval tick. Coalesced exactly like a trigger signal (one pass at a time; a request mid-pass
|
|
50
|
+
* queues a single follow-up) and still gated by `shouldConverge()`, so a write made while offline
|
|
51
|
+
* stages without flushing. With this, the trigger's interval is only a fallback (retries/recovery),
|
|
52
|
+
* which lets it run far less often — the interval, not real convergence, is what costs idle CPU.
|
|
53
|
+
*/
|
|
54
|
+
requestPass: () => void;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Drive convergence from a {@link ConvergenceTrigger}. Each signal runs at most one pass at a
|
|
58
|
+
* time (`flush` → `reconcile`); a signal arriving mid-pass coalesces into a single follow-up
|
|
59
|
+
* pass, so a burst of triggers never stampedes the server (the per-mutation backoff in the
|
|
60
|
+
* runtime handles the rest).
|
|
61
|
+
*/
|
|
62
|
+
export declare function createConvergenceDriver(options: ConvergenceDriverOptions): ConvergenceDriver;
|
|
63
|
+
/**
|
|
64
|
+
* Browser convergence trigger: fires on `online`, `visibilitychange`, and a fallback interval,
|
|
65
|
+
* and converges only while online and not backgrounded. The adapter most apps use.
|
|
66
|
+
*/
|
|
67
|
+
export declare function createBrowserConvergenceTrigger(options?: {
|
|
68
|
+
intervalMs?: number;
|
|
69
|
+
}): ConvergenceTrigger;
|
|
70
|
+
/**
|
|
71
|
+
* Interval convergence trigger: fires on a fixed cadence and always converges. The minimal
|
|
72
|
+
* non-browser adapter — usable directly in tests/servers and the base a React Native
|
|
73
|
+
* `AppState`/`NetInfo` adapter builds on — which is the second adapter that proves the seam.
|
|
74
|
+
*/
|
|
75
|
+
export declare function createIntervalConvergenceTrigger(intervalMs: number): ConvergenceTrigger;
|
|
76
|
+
//# sourceMappingURL=convergence.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"convergence.d.ts","sourceRoot":"","sources":["../src/convergence.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAIH,6DAA6D;AAC7D,MAAM,WAAW,iBAAiB;IAChC,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3B,SAAS,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAChC;AAED;;;;GAIG;AACH,MAAM,WAAW,kBAAkB;IACjC,sGAAsG;IACtG,SAAS,EAAE,CAAC,QAAQ,EAAE,MAAM,IAAI,KAAK,MAAM,IAAI,CAAC;IAChD,sFAAsF;IACtF,cAAc,EAAE,MAAM,OAAO,CAAC;CAC/B;AAED,MAAM,WAAW,wBAAwB;IACvC,MAAM,EAAE,iBAAiB,CAAC;IAC1B,OAAO,EAAE,kBAAkB,CAAC;IAC5B,0FAA0F;IAC1F,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;CACnC;AAED,MAAM,WAAW,iBAAiB;IAChC,KAAK,EAAE,MAAM,IAAI,CAAC;IAClB;;;OAGG;IACH,IAAI,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B;;;;;;;OAOG;IACH,WAAW,EAAE,MAAM,IAAI,CAAC;CACzB;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,wBAAwB,GAAG,iBAAiB,CAsE5F;AAaD;;;GAGG;AACH,wBAAgB,+BAA+B,CAAC,OAAO,GAAE;IAAE,UAAU,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,kBAAkB,CAqBzG;AAED;;;;GAIG;AACH,wBAAgB,gCAAgC,CAAC,UAAU,EAAE,MAAM,GAAG,kBAAkB,CAavF"}
|
package/dist/debug.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A sink that receives every `syncDebug` line (event, the worker's monotonic stamp, optional data),
|
|
3
|
+
* INDEPENDENT of the local `__pgxsinkitDebug` console gate. This is the seam `defineSyncWorker` installs
|
|
4
|
+
* to forward the debug rail to tabs (ADR-0032 decision 7): a SharedWorker's own console is invisible
|
|
5
|
+
* (`chrome://inspect`), so lines must cross the bridge and each tab re-prints them gated on ITS OWN flag.
|
|
6
|
+
* Unset by default → no forwarding and zero cost on the in-process path.
|
|
7
|
+
*/
|
|
8
|
+
type SyncDebugSink = (event: string, stamp: number, data?: Record<string, unknown>) => void;
|
|
9
|
+
/** Install (or clear, with `undefined`) the debug-rail sink. Idempotent; `defineSyncWorker` owns it. */
|
|
10
|
+
export declare function setSyncDebugSink(sink: SyncDebugSink | undefined): void;
|
|
11
|
+
/**
|
|
12
|
+
* Log one timestamped event. Prints to the console only when `globalThis.__pgxsinkitDebug` is on, but ALSO
|
|
13
|
+
* feeds any installed {@link setSyncDebugSink} sink (so the worker can forward the rail to tabs even when the
|
|
14
|
+
* worker's own console gate is off). No sink AND not enabled → an early return, so the off-path pays nothing.
|
|
15
|
+
*/
|
|
16
|
+
export declare function syncDebug(event: string, data?: Record<string, unknown>): void;
|
|
17
|
+
/**
|
|
18
|
+
* Wrap a `fetch` so every ShapeStream request (the Electric read-path long-poll/catch-up) emits a start
|
|
19
|
+
* line (shape/table, offset, live — derived from the request URL params) and a completion line (status,
|
|
20
|
+
* ms, and whether the response is up-to-date). Passthrough when instrumentation is off: the early return
|
|
21
|
+
* runs before any URL parsing, so the off-path pays nothing per request beyond this closure itself.
|
|
22
|
+
*
|
|
23
|
+
* Inject it as a ShapeStream `fetchClient`; pass the stream's existing `fetchClient` (if any) as the base
|
|
24
|
+
* so the instrumentation composes rather than replaces.
|
|
25
|
+
*/
|
|
26
|
+
export declare function instrumentShapeFetch(baseFetch?: typeof fetch): typeof fetch;
|
|
27
|
+
/**
|
|
28
|
+
* Run `fn`, logging `<event> done` with its wall-clock duration (and any extra `data`). When
|
|
29
|
+
* instrumentation is off this is a thin pass-through with no logging and no timing overhead beyond the
|
|
30
|
+
* call itself. Returns whatever `fn` returns.
|
|
31
|
+
*/
|
|
32
|
+
export declare function timeAsync<T>(event: string, fn: () => Promise<T>, data?: Record<string, unknown>): Promise<T>;
|
|
33
|
+
export {};
|
|
34
|
+
//# sourceMappingURL=debug.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"debug.d.ts","sourceRoot":"","sources":["../src/debug.ts"],"names":[],"mappings":"AAiBA;;;;;;GAMG;AACH,KAAK,aAAa,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;AAG5F,wGAAwG;AACxG,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,aAAa,GAAG,SAAS,GAAG,IAAI,CAEtE;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAa7E;AAYD;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,SAAS,GAAE,OAAO,KAAa,GAAG,OAAO,KAAK,CA+DlF;AAED;;;;GAIG;AACH,wBAAsB,SAAS,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CASlH"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,27 +1,187 @@
|
|
|
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 ConvergenceTrigger } from "./convergence";
|
|
6
|
+
import { type LocalStoreVersionEvent } from "./local-store";
|
|
6
7
|
import { type MutationBatchItem, type MutationDetail, type MutationKind } from "./mutation";
|
|
7
8
|
import { generateLocalSchemaSql } from "./schema";
|
|
9
|
+
import { type SyncEngine } from "./sync";
|
|
8
10
|
export { generateLocalSchemaSql };
|
|
9
|
-
export type
|
|
10
|
-
|
|
11
|
-
}
|
|
11
|
+
export { type ConvergenceClient, type ConvergenceDriver, type ConvergenceDriverOptions, type ConvergenceTrigger, createBrowserConvergenceTrigger, createConvergenceDriver, createIntervalConvergenceTrigger, } from "./convergence";
|
|
12
|
+
export { instrumentShapeFetch, setSyncDebugSink, syncDebug, timeAsync } from "./debug";
|
|
13
|
+
export { type AttachedSyncClient, attachSyncClient, type AttachSyncClientOptions, provisionSyncWorker, } from "./worker/attach-sync-client";
|
|
14
|
+
export { defineSyncWorker, type DefineSyncWorkerOptions, type SyncWorkerHost } from "./worker/define-sync-worker";
|
|
15
|
+
export { computeLiveDiff, type LiveDiffState, LiveRowsMaterializer, rowKey, seedLiveDiffState, } from "./worker/live-diff";
|
|
16
|
+
export { createWorkerTokenCache, type WorkerTokenCache } from "./worker/token-cache";
|
|
17
|
+
export { type AttachAckPayload, type AttachPayload, type AuthTokenSnapshot, BRIDGE_CHANNEL, BRIDGE_PROTOCOL_VERSION, type BridgeCodec, type BridgeEnvelope, type BridgeEvent, type BridgeMessageType, type BridgePort, encodeEnvelope, 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";
|
|
18
|
+
export { assertLazyRefsActivated, buildLazyGuardIndex, findReferencedLazyKeysInSql, type LazyGuardIndex, LazyRelationNotActivatedError, } from "./lazy-guard";
|
|
19
|
+
export { getJournalTable, getLocalMetaTable, getOverlayTable, getReadModelView, getSyncedLocalTable, getSyncStateView, type JournalTable, type LocalMetaTable, type OverlayTable, type ReadModelView, type SyncStateView, } from "./local-tables";
|
|
20
|
+
export type { LocalStoreVersionEvent };
|
|
21
|
+
export type ClientPGlite = PGliteWithLive & {
|
|
22
|
+
electric: SyncEngine["namespace"];
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* The pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), consumed by
|
|
26
|
+
* {@link createClientPGlite} / {@link CreateSyncClientOptions.pgliteBootAssets}. The host fetches +
|
|
27
|
+
* compiles these on an earlier screen and hands the promise in, so `PGlite.create` skips its own lazy
|
|
28
|
+
* asset load — see the field's JSDoc for the accelerator geometry.
|
|
29
|
+
*/
|
|
30
|
+
export interface PgliteBootAssets {
|
|
31
|
+
pgliteWasmModule?: WebAssembly.Module;
|
|
32
|
+
initdbWasmModule?: WebAssembly.Module;
|
|
33
|
+
fsBundle?: Blob;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Create the raw local PGlite store the sync client runs on — the SAME `PGlite.create` call
|
|
37
|
+
* {@link createSyncClient} makes internally (the `electric` + `live` extensions, pre-warmed boot-asset
|
|
38
|
+
* consumption, and the `boot pglite.create` rail stamp), extracted so exactly one implementation exists
|
|
39
|
+
* and a host can create the store EAGERLY on an earlier screen. Hand the returned (still-pending)
|
|
40
|
+
* instance to {@link CreateSyncClientOptions.precreatedPglite}: the client then owns schema exec, prepare
|
|
41
|
+
* hooks, journal recovery and store-version reconcile, exactly as its own `dataDir` path does.
|
|
42
|
+
*
|
|
43
|
+
* The instance is deliberately **schemaless** — the registry-derived local schema is role/registry
|
|
44
|
+
* dependent, so it is applied post-create by `createSyncClient`. The eager create buys only the expensive
|
|
45
|
+
* initdb (+ IDBFS open), which is the dominant cold-boot cost once the WASM is pre-warmed.
|
|
46
|
+
*
|
|
47
|
+
* `bootAssets` is the pre-warmed WASM/fs bundle (see {@link CreateSyncClientOptions.pgliteBootAssets}); a
|
|
48
|
+
* rejected warm is caught to `undefined`, so PGlite falls back to loading its own assets — never a failure.
|
|
49
|
+
*/
|
|
50
|
+
export declare function createClientPGlite(dataDir: string, options?: {
|
|
51
|
+
bootAssets?: Promise<PgliteBootAssets>;
|
|
52
|
+
}): Promise<ClientPGlite>;
|
|
12
53
|
export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
|
|
13
54
|
registry: TRegistry;
|
|
14
55
|
electricUrl: string;
|
|
15
56
|
writeUrl: string;
|
|
16
57
|
getAuthToken?: () => Promise<string | undefined>;
|
|
58
|
+
/**
|
|
59
|
+
* Static headers added to **every** read-shape and write request, alongside the per-request
|
|
60
|
+
* `Authorization` (which always wins). The toolkit is agnostic about deployment-gateway
|
|
61
|
+
* credentials, so this is the seam for them — e.g. a Supabase Cloud `apikey` header the platform
|
|
62
|
+
* function gateway expects. Sent even when no `getAuthToken` is supplied.
|
|
63
|
+
*/
|
|
64
|
+
requestHeaders?: Record<string, string>;
|
|
65
|
+
/**
|
|
66
|
+
* Extra static headers sent on the **write** path only (the mutation-flush POST), merged over
|
|
67
|
+
* {@link requestHeaders} (`{...requestHeaders, ...writeRequestHeaders}`). Read/shape requests never
|
|
68
|
+
* see these. The seam exists because the two ingress points have opposite geometry: the write
|
|
69
|
+
* function is DB-bound, so pinning it to the database's region (e.g. an `x-region` header) keeps its
|
|
70
|
+
* chatty function→DB protocol on a ~1ms loop; the read proxy's upstream is a globally-distributed
|
|
71
|
+
* CDN (Electric Cloud), so pinning reads away from the caller pays intercontinental round trips per
|
|
72
|
+
* catch-up hop. Put region/DB-affinity headers here; keep gateway credentials the reads also need
|
|
73
|
+
* (e.g. `apikey`) in the shared {@link requestHeaders}.
|
|
74
|
+
*/
|
|
75
|
+
writeRequestHeaders?: Record<string, string>;
|
|
17
76
|
syncEnabled?: boolean;
|
|
18
77
|
dataDir?: string;
|
|
78
|
+
/**
|
|
79
|
+
* Pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), awaited and passed straight
|
|
80
|
+
* into `PGlite.create`. The intent is to hide PGlite's ~2.5s cold `boot pglite.create` cost —
|
|
81
|
+
* dominated by the WASM fetch+compile — behind user think-time: the host starts fetching/compiling
|
|
82
|
+
* these on an earlier screen (e.g. the login/identity picker) and hands the still-pending promise
|
|
83
|
+
* here, so by the time a store is opened the assets are already resolved and `PGlite.create` skips
|
|
84
|
+
* its own lazy asset load. Ignored when {@link pgliteInstance} is supplied (the caller owns that
|
|
85
|
+
* instance's boot). A rejected/failed warm is caught to `undefined` and never fails the boot — PGlite
|
|
86
|
+
* falls back to loading its own assets, so this is a pure best-effort accelerator.
|
|
87
|
+
*/
|
|
88
|
+
pgliteBootAssets?: Promise<PgliteBootAssets>;
|
|
19
89
|
resetSubscriptionKeys?: string[];
|
|
20
90
|
prepareLocalDbBeforeSchema?: (pglite: ClientPGlite) => Promise<void>;
|
|
21
91
|
prepareLocalDb?: (pglite: ClientPGlite) => Promise<void>;
|
|
22
92
|
onStatusChange?: (status: SyncRuntimeStatus) => void;
|
|
23
93
|
onTableInitialSync?: (tableKey: string) => void;
|
|
94
|
+
/**
|
|
95
|
+
* A fully-provisioned PGlite instance the CALLER owns end-to-end. The client runs NONE of its
|
|
96
|
+
* post-create boot steps against it — no schema exec, prepare hooks, or store-version reconcile
|
|
97
|
+
* (journal recovery still runs, as it does on every path). Use it only when the caller has already
|
|
98
|
+
* applied the registry schema itself. Contrast the three PGlite-provenance seams:
|
|
99
|
+
* - {@link dataDir} (default) — the client creates the store AND runs every post-create step.
|
|
100
|
+
* - {@link precreatedPglite} — the caller creates the raw store (via {@link createClientPGlite}), but
|
|
101
|
+
* the client still runs every post-create step (schema/prepare/reconcile), exactly as `dataDir` does.
|
|
102
|
+
* - `pgliteInstance` — the caller creates AND provisions the store; the client runs none of them.
|
|
103
|
+
*
|
|
104
|
+
* Mutually exclusive with {@link precreatedPglite} (supplying both throws).
|
|
105
|
+
*/
|
|
24
106
|
pgliteInstance?: ClientPGlite;
|
|
107
|
+
/**
|
|
108
|
+
* A raw PGlite instance the caller created EAGERLY (via {@link createClientPGlite}) — typically on an
|
|
109
|
+
* earlier screen, to hide the ~1.9s cold `initdb`/IDBFS open behind user think-time — but for which the
|
|
110
|
+
* client still owns EVERYTHING else: schema exec, prepare hooks, journal recovery, and store-version
|
|
111
|
+
* reconcile all run exactly as on the {@link dataDir} path. This is the difference from
|
|
112
|
+
* {@link pgliteInstance} (which skips schema/prepare/reconcile because the caller owns them); see that
|
|
113
|
+
* option's JSDoc for the three-way distinction.
|
|
114
|
+
*
|
|
115
|
+
* The promise form lets the still-pending eager create be handed straight in. Precedence/validation:
|
|
116
|
+
* - Supplying both this and {@link pgliteInstance} throws — they claim different ownership.
|
|
117
|
+
* - {@link dataDir} is used ONLY as the fallback store id if this promise REJECTS: a failed eager
|
|
118
|
+
* create is caught, logged on the boot rail, and the normal `dataDir` create path runs instead (also
|
|
119
|
+
* consuming {@link pgliteBootAssets} if provided). The pattern is a pure accelerator, never a boot
|
|
120
|
+
* dependency.
|
|
121
|
+
*/
|
|
122
|
+
precreatedPglite?: Promise<ClientPGlite>;
|
|
123
|
+
/**
|
|
124
|
+
* PROVABLY-fresh store hint (ADR-0032 S4 / backlog-0003): the caller guarantees this store is brand-new
|
|
125
|
+
* and schemaless — no prior schema, no synced rows, no persisted subscription state. When set (and sync
|
|
126
|
+
* is enabled, and the client owns schema exec — i.e. not the {@link pgliteInstance} path), the shape
|
|
127
|
+
* catch-up is started BEFORE the local boot phases (schema exec, journal recovery, store-version
|
|
128
|
+
* reconcile) and buffered in memory, with commits gated until those phases finish — so the network
|
|
129
|
+
* catch-up overlaps them instead of running strictly after. On a far-from-database caller this collapses
|
|
130
|
+
* boot from `local-phases + catch-up` toward `max(local-phases, catch-up)`.
|
|
131
|
+
*
|
|
132
|
+
* MUST be set only when freshness is proven, never derived by probing — a claimed schemaless spare (the
|
|
133
|
+
* board's claim path knows: a claimed spare is always fresh; a mapped/returning store never is). A wrong
|
|
134
|
+
* `true` on a warm store would start the streams from offset 0 and skip the subscription-state read,
|
|
135
|
+
* re-snapshotting instead of resuming. Absent/false → the exact sequential path (the default, correct for
|
|
136
|
+
* every warm store).
|
|
137
|
+
*/
|
|
138
|
+
freshStore?: boolean;
|
|
139
|
+
/**
|
|
140
|
+
* Hard cap on send attempts before a still-failing mutation is quarantined
|
|
141
|
+
* (ADR-0005 congestion policy). Defaults to the library's built-in cap.
|
|
142
|
+
*/
|
|
143
|
+
maxMutationAttempts?: number;
|
|
144
|
+
/**
|
|
145
|
+
* Invoked when mutations are quarantined (permanently rejected by the server, terminal). The library
|
|
146
|
+
* surfaces them here rather than silently dropping or retry-looping (ADR-0006). Surface, then either
|
|
147
|
+
* re-author + resubmit or roll back via {@link SyncClient.discardQuarantined} — which clears the kept
|
|
148
|
+
* overlay + quarantined journal rows so the entity accepts new mutations again.
|
|
149
|
+
*/
|
|
150
|
+
onQuarantine?: (quarantined: MutationDetail[]) => void | Promise<void>;
|
|
151
|
+
/**
|
|
152
|
+
* Invoked when mutations are `conflicted` — a stale write the server declined under the
|
|
153
|
+
* `reject-if-stale` Conflict policy (ADR-0015). The optimistic Overlay is kept, so the app shows a
|
|
154
|
+
* resolution/diff UI and resolves each as a new write (`mutate.update`) or `discardConflict`s it.
|
|
155
|
+
*/
|
|
156
|
+
onConflict?: (conflicted: MutationDetail[]) => void | Promise<void>;
|
|
157
|
+
/**
|
|
158
|
+
* Invoked when a pessimistic write-unit is `rejected` (ADR-0022) — a business decline from the
|
|
159
|
+
* authoritative endpoint (capacity/quota/uniqueness). The inverse of `onConflict`: the optimistic Overlay
|
|
160
|
+
* was auto-discarded for the whole unit, so the app surfaces the typed reason rather than a resolve UI.
|
|
161
|
+
*/
|
|
162
|
+
onReject?: (rejected: MutationDetail[]) => void | Promise<void>;
|
|
163
|
+
/**
|
|
164
|
+
* Invoked on boot when the registry fingerprint differs from the one the local store was
|
|
165
|
+
* provisioned under (ADR-0006). `rebuilt` = the read cache was dropped and rebuilt at the
|
|
166
|
+
* new shape; `deferred` = un-flushed/quarantined writes are still owed, so the rebuild is
|
|
167
|
+
* postponed (and retried on a later boot) rather than dropping owed data.
|
|
168
|
+
*/
|
|
169
|
+
onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;
|
|
170
|
+
/**
|
|
171
|
+
* Opt-in convergence driver (ADR-0005). Supply a {@link ConvergenceTrigger} (e.g.
|
|
172
|
+
* `createBrowserConvergenceTrigger()`) and the client drives `flush`/`reconcile`/`retryFailed`
|
|
173
|
+
* on the trigger's schedule, started once sync is ready and stopped on `stop()`/`destroy()`.
|
|
174
|
+
* Omit it for fully-manual convergence (the mechanism primitives stay public either way).
|
|
175
|
+
*/
|
|
176
|
+
autoSync?: ConvergenceTrigger;
|
|
177
|
+
/** Invoked after each automatic convergence pass with its error, or `null` on success (only when `autoSync` is set). */
|
|
178
|
+
onConvergencePass?: (error: unknown) => void;
|
|
179
|
+
/**
|
|
180
|
+
* Invoked when a read-path sync commit fails after exhausting its retries (ADR-0009 decision 5).
|
|
181
|
+
* The runtime enters the `degraded` phase and holds the read cache at the last applied commit
|
|
182
|
+
* instead of silently diverging from the server; recovery is a later commit or a restart/refetch.
|
|
183
|
+
*/
|
|
184
|
+
onSyncError?: (error: Error) => void;
|
|
25
185
|
}
|
|
26
186
|
export interface SyncClientTableHandle<TRegistry extends SyncTableRegistry, TKey extends SyncTableName<TRegistry>> {
|
|
27
187
|
key: TKey;
|
|
@@ -30,6 +190,105 @@ export interface SyncClientTableHandle<TRegistry extends SyncTableRegistry, TKey
|
|
|
30
190
|
update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => Promise<void>;
|
|
31
191
|
delete: (entityKey: Record<string, string>) => Promise<void>;
|
|
32
192
|
}
|
|
193
|
+
/**
|
|
194
|
+
* A table handle inside a {@link SyncClient.transaction} block (ADR-0022 §2). It *collects* mutations into
|
|
195
|
+
* the open write-unit rather than enqueuing each immediately; the whole set is enqueued atomically when the
|
|
196
|
+
* block's callback returns. The calls are synchronous (collection only) — no per-call await needed.
|
|
197
|
+
*/
|
|
198
|
+
export interface SyncTransactionTableHandle<TRegistry extends SyncTableRegistry, TKey extends SyncTableName<TRegistry>> {
|
|
199
|
+
create: (input: SyncTableCreateInput<TRegistry, TKey>) => void;
|
|
200
|
+
update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => void;
|
|
201
|
+
delete: (entityKey: Record<string, string>) => void;
|
|
202
|
+
/**
|
|
203
|
+
* An **update-by-key with no local base row** (ADR-0022 addendum). Ordinary `update` requires the entity
|
|
204
|
+
* to be present in the actor's local read model (it seeds the optimistic overlay and captures the base
|
|
205
|
+
* server version); `updateBlind` skips that presence check and writes NO overlay — nothing appears in the
|
|
206
|
+
* read model. Use it when the write target is deliberately EXCLUDED from your read shape (a write-only
|
|
207
|
+
* flow, or an anonymity-scoped moderation write whose row streams only to a different projection), so there
|
|
208
|
+
* is no local row to update and nothing to show optimistically.
|
|
209
|
+
*
|
|
210
|
+
* **Pessimistic-only.** The /unit expander is authoritative for the outcome, so a blind write is meaningful
|
|
211
|
+
* only inside a `transaction({ mode: "pessimistic" })` block (or over a statically-pessimistic table). An
|
|
212
|
+
* optimistic-routed blind write has nothing to converge and THROWS at enqueue.
|
|
213
|
+
*
|
|
214
|
+
* The acked journal row **retires without a synced echo** (no visible row ever converges for it), so it does
|
|
215
|
+
* not linger — unlike the seed-a-phantom-row workaround this replaces, whose acked row + overlay lingered
|
|
216
|
+
* forever behind the echo barrier. A `conflicted` blind write stays dischargeable via `discardConflict`; a
|
|
217
|
+
* `rejected` one is surfaced via `onReject`, both with no overlay to clean up.
|
|
218
|
+
*/
|
|
219
|
+
updateBlind: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => void;
|
|
220
|
+
}
|
|
221
|
+
/** The handle passed to a {@link SyncClient.transaction} callback: collecting table handles for the unit. */
|
|
222
|
+
export interface SyncTransaction<TRegistry extends SyncTableRegistry> {
|
|
223
|
+
tables: {
|
|
224
|
+
[TKey in SyncTableName<TRegistry>]: SyncTransactionTableHandle<TRegistry, TKey>;
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* The result of a {@link SyncClient.transaction}. A `pessimistic` block carries the authoritative server
|
|
229
|
+
* `acks` (each `acked` / `conflicted` / `rejected`); an `optimistic` block enqueues atomically and flushes
|
|
230
|
+
* in the background, so its `acks` are empty.
|
|
231
|
+
*/
|
|
232
|
+
export interface SyncTransactionResult {
|
|
233
|
+
acks: MutationAck[];
|
|
234
|
+
}
|
|
235
|
+
/** Minimal shape of a Drizzle select builder: inspectable via `.toSQL()` and awaitable for its rows. */
|
|
236
|
+
export interface DrizzleQueryBuilder<TRows extends readonly unknown[]> extends PromiseLike<TRows> {
|
|
237
|
+
toSQL(): {
|
|
238
|
+
sql: string;
|
|
239
|
+
params: unknown[];
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* The builder callback for a guarded read (ADR-0021): it receives the client and returns a Drizzle
|
|
244
|
+
* select builder. Reach relations through `c.views` / `c.drizzle` / a directly-imported synced table.
|
|
245
|
+
*/
|
|
246
|
+
export type GuardedQueryFn<TRegistry extends SyncTableRegistry, TRows extends readonly unknown[]> = (client: SyncClient<TRegistry>) => DrizzleQueryBuilder<TRows>;
|
|
247
|
+
/**
|
|
248
|
+
* A guarded query whose builder MAY embed a raw `sql` template fragment (ADR-0021). A raw fragment can
|
|
249
|
+
* name a lazy relation as a bare/unquoted identifier the compiled-SQL scan cannot see, so declare those
|
|
250
|
+
* relations in `use` — they are activated and awaited before the query runs. Pure-Drizzle reads need no
|
|
251
|
+
* `use` (the scan detects every relation): pass the builder callback directly to `client.query`.
|
|
252
|
+
*/
|
|
253
|
+
export interface GuardedRawQuerySpec<TRegistry extends SyncTableRegistry, TRows extends readonly unknown[]> {
|
|
254
|
+
use?: readonly SyncTableName<TRegistry>[];
|
|
255
|
+
build: GuardedQueryFn<TRegistry, TRows>;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Inputs to the read-path safety seam {@link SyncClient.prepareQuery}. The lazy relations a query reads
|
|
259
|
+
* are detected by scanning the compiled `sql` (union with the optional explicit `use`), then activated.
|
|
260
|
+
* Shared by the live React hooks and the non-live facade.
|
|
261
|
+
*/
|
|
262
|
+
export interface PrepareQueryInput<TRegistry extends SyncTableRegistry> {
|
|
263
|
+
/** The compiled (parameterised) Drizzle SQL the query will run — the scan's ground-truth target. */
|
|
264
|
+
sql: string;
|
|
265
|
+
/** Lazy relations to also activate, beyond those scanned from `sql` — a pre-activation hint, not required. */
|
|
266
|
+
use?: readonly SyncTableName<TRegistry>[];
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* The narrow live-rows seam (ADR-0032 S2 §4) both client modes implement so the `@pgxsinkit/react` hooks
|
|
270
|
+
* work against either. Input for a reactive subscription: the compiled SQL + params (from a Drizzle
|
|
271
|
+
* builder's `.toSQL()` or a raw string) and the result's `pkColumns` (drives worker-side diff keying;
|
|
272
|
+
* omit for a keyless query). The in-process client runs it directly over `pglite.live`; the worker-attached
|
|
273
|
+
* client runs the live query in the worker and streams DIFFs across the bridge.
|
|
274
|
+
*/
|
|
275
|
+
export interface SubscribeLiveRowsInput {
|
|
276
|
+
sql: string;
|
|
277
|
+
params: readonly unknown[];
|
|
278
|
+
/** The result's PK columns — the diff-keying identity across the bridge (§4). Omit for a keyless query. */
|
|
279
|
+
pkColumns?: readonly string[];
|
|
280
|
+
/**
|
|
281
|
+
* Lazy relations (ADR-0021) to activate before the query runs — forwarded to the worker so it can
|
|
282
|
+
* `prepareQuery` before registering the live query (the tab's own `prepareQuery` is a no-op against the
|
|
283
|
+
* worker bridge). Ignored by the in-process client, whose `prepareQuery` already ran on the tab.
|
|
284
|
+
*/
|
|
285
|
+
use?: readonly string[];
|
|
286
|
+
}
|
|
287
|
+
/** A handle to a live-rows subscription: the initial ordered snapshot plus an idempotent unsubscribe. */
|
|
288
|
+
export interface LiveRowsSubscription<TRow> {
|
|
289
|
+
initialRows: TRow[];
|
|
290
|
+
unsubscribe: () => void;
|
|
291
|
+
}
|
|
33
292
|
export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
34
293
|
drizzle: PgliteDatabase<RegistryRelations<TRegistry>>;
|
|
35
294
|
pglite: ClientPGlite;
|
|
@@ -41,7 +300,20 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
41
300
|
status: SyncRuntimeStatus;
|
|
42
301
|
start: () => Promise<void>;
|
|
43
302
|
stop: () => Promise<void>;
|
|
44
|
-
|
|
303
|
+
/**
|
|
304
|
+
* Wipe the entire local store (synced cache + overlay + journal) and close the handle
|
|
305
|
+
* (ADR-0005). Refuses if mutations are still owed to the server unless `force` is set, so
|
|
306
|
+
* it never silently drops un-flushed writes. Distinct from `stop()`, which only halts sync.
|
|
307
|
+
*/
|
|
308
|
+
destroy: (options?: {
|
|
309
|
+
force?: boolean;
|
|
310
|
+
}) => Promise<void>;
|
|
311
|
+
/**
|
|
312
|
+
* Drop and rebuild the reconstructible synced read cache, preserving the overlay and
|
|
313
|
+
* mutation journal (ADR-0006). The next sync refills it. Use to recover from a corrupt or
|
|
314
|
+
* stale read cache without losing un-flushed writes.
|
|
315
|
+
*/
|
|
316
|
+
dropReadCache: () => Promise<void>;
|
|
45
317
|
flush: (table?: SyncTableName<TRegistry>) => Promise<void>;
|
|
46
318
|
reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;
|
|
47
319
|
retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;
|
|
@@ -53,10 +325,152 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
|
|
|
53
325
|
delete: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;
|
|
54
326
|
batch: (items: ReadonlyArray<MutationBatchItem<TRegistry>>) => Promise<void>;
|
|
55
327
|
};
|
|
328
|
+
/**
|
|
329
|
+
* Discard a `conflicted` entity (ADR-0015): clear its conflicted journal entry and kept optimistic
|
|
330
|
+
* Overlay, so the Read model falls back to the synced (server) value. Use when the user abandons a
|
|
331
|
+
* stale edit instead of resolving it as a new write.
|
|
332
|
+
*/
|
|
333
|
+
discardConflict: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;
|
|
334
|
+
/**
|
|
335
|
+
* Discard a `quarantined` entity (ADR-0006): clear its quarantined journal entry and kept optimistic
|
|
336
|
+
* Overlay, so the Read model falls back to the synced (server) value. The rollback path for a write
|
|
337
|
+
* the server permanently rejected — e.g. an RLS policy denial (42501) routed to quarantine. After the
|
|
338
|
+
* discard the phantom optimistic row is gone and the entity accepts new mutations again (no longer
|
|
339
|
+
* blocked behind the quarantined head). Symmetric to {@link SyncClient.discardConflict}; the overlay
|
|
340
|
+
* is kept when another still-owed write depends on it. No-op for an entity with no quarantined entry.
|
|
341
|
+
*/
|
|
342
|
+
discardQuarantined: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;
|
|
56
343
|
diagnostics: (table?: SyncTableName<TRegistry>) => Promise<{
|
|
57
344
|
mutation: MutationDiagnostics;
|
|
58
345
|
}>;
|
|
346
|
+
/**
|
|
347
|
+
* The INSPECTION read surface (debug pages, REPLs, ad-hoc counts) — identical on the in-process and
|
|
348
|
+
* worker-attached client (on the latter the statement runs in the worker). The statement runs raw
|
|
349
|
+
* against the local store: it BYPASSES the mutation journal and optimistic overlay, and any write it
|
|
350
|
+
* issues stays local and will NOT converge. For app data reads prefer the live-rows hooks /
|
|
351
|
+
* {@link subscribeLiveRows} (or the guarded {@link query} family); reach for this only to look at the
|
|
352
|
+
* store, not to read app state or mutate it.
|
|
353
|
+
*/
|
|
354
|
+
rawQuery: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;
|
|
355
|
+
/** {@link rawQuery} for multi-statement SQL, returning one {@link Results} per statement. */
|
|
356
|
+
rawExec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;
|
|
357
|
+
/**
|
|
358
|
+
* Run a one-shot (non-live) typed **pure-Drizzle** query with the lazy-relation safety net (ADR-0021).
|
|
359
|
+
* Pass the builder callback directly — pgxsinkit scans the compiled SQL and activates + awaits every
|
|
360
|
+
* lazy relation it reads (FROM, JOIN, subquery, WHERE) before it runs, and the tripwire rejects any
|
|
361
|
+
* lazy relation the SQL still references but that is not active, so the result is never silently
|
|
362
|
+
* empty/stale. The guaranteed-safe alternative to a bare `client.drizzle` read. If the builder embeds
|
|
363
|
+
* a raw `sql` template fragment, use {@link queryRaw} and declare the lazy relations in `use`.
|
|
364
|
+
*/
|
|
365
|
+
query: <TRows extends readonly unknown[]>(build: GuardedQueryFn<TRegistry, TRows>) => Promise<TRows>;
|
|
366
|
+
/** {@link query} returning the first row, or null when empty. */
|
|
367
|
+
queryRow: <TRows extends readonly unknown[]>(build: GuardedQueryFn<TRegistry, TRows>) => Promise<TRows[number] | null>;
|
|
368
|
+
/**
|
|
369
|
+
* {@link query} for a builder that embeds a raw `sql` template fragment (ADR-0021). The compiled-SQL
|
|
370
|
+
* scan can miss a lazy relation named as a bare/unquoted identifier inside raw SQL, so declare those
|
|
371
|
+
* in `use` — they are activated and awaited before the query runs. Pure-Drizzle reads should use
|
|
372
|
+
* {@link query} instead (no `use` needed).
|
|
373
|
+
*/
|
|
374
|
+
queryRaw: <TRows extends readonly unknown[]>(spec: GuardedRawQuerySpec<TRegistry, TRows>) => Promise<TRows>;
|
|
375
|
+
/** {@link queryRaw} returning the first row, or null when empty. */
|
|
376
|
+
queryRawRow: <TRows extends readonly unknown[]>(spec: GuardedRawQuerySpec<TRegistry, TRows>) => Promise<TRows[number] | null>;
|
|
377
|
+
/**
|
|
378
|
+
* Activate one or more lazy relations (ADR-0021): open their consistency-group subscription if held
|
|
379
|
+
* out of the eager boot, resolving once their initial sync completes. Idempotent — eager or
|
|
380
|
+
* already-started relations resolve immediately. Use to pre-activate before a raw/`client.drizzle`
|
|
381
|
+
* read, or as the manual escape hatch the tripwire points to.
|
|
382
|
+
*/
|
|
383
|
+
ensureSynced: (keys: readonly SyncTableName<TRegistry>[]) => Promise<void>;
|
|
384
|
+
/**
|
|
385
|
+
* Whether a relation's group has started and hydrated (ADR-0021). False for a still-dormant `lazy`
|
|
386
|
+
* relation; true for eager relations once boot completes (and always when sync is disabled).
|
|
387
|
+
*/
|
|
388
|
+
isSynced: (key: SyncTableName<TRegistry>) => boolean;
|
|
389
|
+
/**
|
|
390
|
+
* Revert a `lazy` relation to dormant (ADR-0021 §2) — the inverse of on-demand activation: stop its
|
|
391
|
+
* consistency group's stream, clear any persisted `lazy + persistent` activation (so the next boot
|
|
392
|
+
* holds it dormant again), and clean-truncate its local read cache. A later reference re-activates it
|
|
393
|
+
* from scratch. Refuses when the relation is `eager` (always-on, would immediately re-sync) or owes
|
|
394
|
+
* the server unsettled writes (the truncate would drop them — flush or discard first). The reclaim
|
|
395
|
+
* primitive a host wires to navigation/idle for a rarely-opened lazy view; for an `ephemeral`
|
|
396
|
+
* relation, idle-eviction is otherwise automatic at session end.
|
|
397
|
+
*/
|
|
398
|
+
desync: (key: SyncTableName<TRegistry>) => Promise<void>;
|
|
399
|
+
/**
|
|
400
|
+
* The read-path safety seam (ADR-0021): scan the compiled `sql` for the lazy relations it reads
|
|
401
|
+
* (∪ the optional `use`), activate them, and await their initial sync — so a lazy relation
|
|
402
|
+
* auto-activates on *any* reference (FROM, JOIN, subquery, WHERE). Resolves once it is safe to run the
|
|
403
|
+
* query; a backstop throws {@link LazyRelationNotActivatedError} only if a referenced relation could
|
|
404
|
+
* not be activated. Exposed for the React live hooks (which own their query build); `query`/`queryRow`
|
|
405
|
+
* are the higher-level non-live wrappers. Raw, non-Drizzle SQL is out of scope — pass `use`, or
|
|
406
|
+
* `ensureSynced` first.
|
|
407
|
+
*/
|
|
408
|
+
prepareQuery: (input: PrepareQueryInput<TRegistry>) => Promise<void>;
|
|
409
|
+
/**
|
|
410
|
+
* Author an atomic write-**unit** (ADR-0022 §2). The callback receives collecting table handles; every
|
|
411
|
+
* mutation it issues is tagged into one unit and enqueued atomically when the callback returns.
|
|
412
|
+
*
|
|
413
|
+
* - `mode: "pessimistic"` — **server-authoritative**: the unit flush-routes to the authoritative endpoint
|
|
414
|
+
* and this call resolves only once the server has decided. The result's `acks` carry each member's
|
|
415
|
+
* outcome — `acked`, `conflicted` (overlay kept, ADR-0015), or `rejected` (overlay auto-discarded for
|
|
416
|
+
* the whole unit, surfaced via `onReject`, ADR-0022 §4). Throws on transport failure (overlay kept). A
|
|
417
|
+
* pessimistic block may also issue {@link SyncTransactionTableHandle.updateBlind} — an update-by-key with
|
|
418
|
+
* no local base row and no overlay, for a write target excluded from the actor's read shape.
|
|
419
|
+
* - `mode: "optimistic"` — an atomic batch enqueue that flushes in the background (empty `acks`).
|
|
420
|
+
*/
|
|
421
|
+
transaction: (options: {
|
|
422
|
+
mode: WriteMode;
|
|
423
|
+
}, run: (tx: SyncTransaction<TRegistry>) => void | Promise<void>) => Promise<SyncTransactionResult>;
|
|
424
|
+
/**
|
|
425
|
+
* Per-group readiness (ADR-0032 decision 6): a promise resolving the moment the given table's
|
|
426
|
+
* consistency group is up-to-date. Resolves immediately for an already-ready (or sync-disabled)
|
|
427
|
+
* group; stays pending for a still-dormant `lazy` relation until it is activated and caught up. The
|
|
428
|
+
* opt-in progressive-paint signal beside the all-eager-groups `ready` gate. `status.groups` carries the
|
|
429
|
+
* same readiness as a synchronous snapshot.
|
|
430
|
+
*/
|
|
431
|
+
groupReady: (table: SyncTableName<TRegistry>) => Promise<void>;
|
|
432
|
+
/**
|
|
433
|
+
* The live-rows seam (ADR-0032 S2 §4): register a reactive query and receive its initial ordered
|
|
434
|
+
* snapshot plus subsequent updates via `onRows`. The React live hooks consume THIS (not `pglite.live`
|
|
435
|
+
* directly), so they run unchanged against both the in-process client (which implements it over
|
|
436
|
+
* `pglite.live`) and the worker-attached client (which implements it over the bridge). Prefer the
|
|
437
|
+
* higher-level `@pgxsinkit/react` hooks; this is the lower-level primitive they build on.
|
|
438
|
+
*/
|
|
439
|
+
subscribeLiveRows: <TRow extends Record<string, unknown> = Record<string, unknown>>(input: SubscribeLiveRowsInput, onRows: (rows: TRow[]) => void) => Promise<LiveRowsSubscription<TRow>>;
|
|
59
440
|
}
|
|
60
441
|
export type { MutationBatchItem, MutationDetail, MutationDiagnostics, MutationKind };
|
|
442
|
+
/**
|
|
443
|
+
* The structured-clone-safe subset of PGlite's `QueryOptions` the inspection surface carries. Kept
|
|
444
|
+
* narrow ON PURPOSE: on a worker-attached client the options object crosses the bridge via
|
|
445
|
+
* `postMessage`, so function-valued options (`parsers`, `serializers`, `onNotice`) can never be part
|
|
446
|
+
* of this contract. `rowMode: "array"` is what `@electric-sql/pglite-repl` asks for on every exec.
|
|
447
|
+
*/
|
|
448
|
+
export interface RawQueryOptions {
|
|
449
|
+
rowMode?: "object" | "array";
|
|
450
|
+
}
|
|
451
|
+
/** The `{ query, exec }` duck `@electric-sql/pglite-repl` drives, backed by a client's inspection surface. */
|
|
452
|
+
export interface ReplInspectionSurface {
|
|
453
|
+
query: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;
|
|
454
|
+
exec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* Shape a {@link SyncClient}'s inspection surface (`rawQuery`/`rawExec`) as the `{ query, exec }` duck
|
|
458
|
+
* `@electric-sql/pglite-repl` needs. Identical on the in-process and worker-attached client — on the latter
|
|
459
|
+
* each statement routes through the worker bridge, so the REPL works even though `client.pglite` is
|
|
460
|
+
* unavailable. Cast the result at the `<Repl pg={...}>` prop (the REPL types the prop as a full `PGlite`).
|
|
461
|
+
* The surface is registry-independent, so it accepts any client's `rawQuery`/`rawExec` pair.
|
|
462
|
+
*/
|
|
463
|
+
export declare function replAdapter(client: Pick<SyncClient<SyncTableRegistry>, "rawQuery" | "rawExec">): ReplInspectionSurface;
|
|
61
464
|
export declare function createSyncClient<const TRegistry extends SyncTableRegistry>(options: CreateSyncClientOptions<TRegistry>): Promise<SyncClient<TRegistry>>;
|
|
465
|
+
/**
|
|
466
|
+
* The tab-side READ handles a worker-attached client exposes (ADR-0032 S2): a build-only Drizzle instance
|
|
467
|
+
* plus the registry views. On the attach client, Drizzle is used only to COMPILE queries to SQL
|
|
468
|
+
* (`.toSQL()`) on the tab — execution happens in the worker via the live-rows bridge / RPC — so it is
|
|
469
|
+
* constructed over a stub client that is never invoked (`construct` stores the client without calling it).
|
|
470
|
+
* The same builders `createSyncClient` uses, so a query built on either client compiles identically.
|
|
471
|
+
*/
|
|
472
|
+
export declare function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(registry: TRegistry): {
|
|
473
|
+
drizzle: PgliteDatabase<RegistryRelations<TRegistry>>;
|
|
474
|
+
views: RegistryViews<TRegistry>;
|
|
475
|
+
};
|
|
62
476
|
//# sourceMappingURL=index.d.ts.map
|