@pgxsinkit/client 0.1.36 → 0.1.41

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.
Files changed (64) hide show
  1. package/dist/boot-report.d.ts +134 -0
  2. package/dist/boot-report.d.ts.map +1 -0
  3. package/dist/export-data.d.ts +100 -0
  4. package/dist/export-data.d.ts.map +1 -0
  5. package/dist/export-dump.d.ts +92 -0
  6. package/dist/export-dump.d.ts.map +1 -0
  7. package/dist/export-store.d.ts +214 -0
  8. package/dist/export-store.d.ts.map +1 -0
  9. package/dist/index.d.ts +206 -13
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +1373 -8308
  12. package/dist/index.js.map +25 -131
  13. package/dist/lazy-guard.d.ts +4 -3
  14. package/dist/lazy-guard.d.ts.map +1 -1
  15. package/dist/lifecycle-slot.d.ts +31 -0
  16. package/dist/lifecycle-slot.d.ts.map +1 -0
  17. package/dist/live-rows-sql.d.ts +21 -0
  18. package/dist/live-rows-sql.d.ts.map +1 -0
  19. package/dist/mutation-state.d.ts +9 -2
  20. package/dist/mutation-state.d.ts.map +1 -1
  21. package/dist/mutation.d.ts +12 -0
  22. package/dist/mutation.d.ts.map +1 -1
  23. package/dist/schema.d.ts +33 -0
  24. package/dist/schema.d.ts.map +1 -1
  25. package/dist/shape-sync.d.ts +10 -0
  26. package/dist/shape-sync.d.ts.map +1 -1
  27. package/dist/store-path.d.ts +132 -0
  28. package/dist/store-path.d.ts.map +1 -0
  29. package/dist/sync/index.d.ts +1 -1
  30. package/dist/sync/index.d.ts.map +1 -1
  31. package/dist/sync/types.d.ts +8 -0
  32. package/dist/sync/types.d.ts.map +1 -1
  33. package/dist/testing.d.ts +27 -0
  34. package/dist/testing.d.ts.map +1 -0
  35. package/dist/testing.js +17 -0
  36. package/dist/testing.js.map +11 -0
  37. package/dist/worker/attach-sync-client.d.ts +23 -2
  38. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  39. package/dist/worker/define-sync-worker.d.ts +5 -4
  40. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  41. package/dist/worker/protocol.d.ts +89 -8
  42. package/dist/worker/protocol.d.ts.map +1 -1
  43. package/package.json +9 -4
  44. package/skills/core/SKILL.md +14 -1
  45. package/skills/operating/SKILL.md +75 -15
  46. package/src/boot-report.ts +287 -0
  47. package/src/export-data.ts +300 -0
  48. package/src/export-dump.ts +239 -0
  49. package/src/export-store.ts +309 -0
  50. package/src/index.ts +623 -82
  51. package/src/lazy-guard.ts +23 -9
  52. package/src/lifecycle-slot.ts +66 -0
  53. package/src/live-rows-sql.ts +45 -0
  54. package/src/mutation-state.ts +11 -2
  55. package/src/mutation.ts +42 -0
  56. package/src/schema.ts +120 -1
  57. package/src/shape-sync.ts +21 -0
  58. package/src/store-path.ts +249 -0
  59. package/src/sync/index.ts +11 -0
  60. package/src/sync/types.ts +9 -0
  61. package/src/testing.ts +53 -0
  62. package/src/worker/attach-sync-client.ts +101 -6
  63. package/src/worker/define-sync-worker.ts +196 -30
  64. package/src/worker/protocol.ts +110 -10
@@ -0,0 +1,239 @@
1
+ // Diagnostic dump (ADR-0035, via the throwaway clone of the addendum). Where a store backup keeps the
2
+ // datadir tarball as its artefact, a diagnostic dump turns the store into human-readable SQL — every table
3
+ // (synced + the `_overlay`/`_mutations` journal), the `pgxsinkit` metadata schema, the read-model views,
4
+ // and the reconcile functions/triggers — so a support engineer sees the misbehaving store EXACTLY as it
5
+ // holds it, unflushed writes and all.
6
+ //
7
+ // The mechanism is the addendum's throwaway clone, NOT the abandoned suspend/reopen seam: (1) take a LIVE
8
+ // datadir dump of the running store (the SAME checkpoint + `dumpDataDir` core the store backup uses, but
9
+ // uncompressed — the clone consumes it immediately, so the gzip+gunzip round trip is pure waste); (2) boot
10
+ // a memory-backed THROWAWAY PGlite from that dump via `loadDataDir` — engine-less, no `live` extension,
11
+ // nothing `pg_dump`'s `DEALLOCATE ALL` can corrupt; (3) run `pg_dump` against the throwaway; (4) discard
12
+ // it. The live engine is never touched — the addendum's whole point — so tabs never notice beyond the
13
+ // lifecycle slot reporting busy.
14
+ //
15
+ // `@electric-sql/pglite-tools` is loaded ONLY via the dynamic `import()` below (ADR-0035 decision 7): its
16
+ // ~700 kB `pg_dump.wasm` (+ ~100 kB JS) stays off boot and off every non-exporting bundle, fetched on first
17
+ // `exportDiagnostics`.
18
+
19
+ import { PGlite } from "@electric-sql/pglite";
20
+
21
+ import type { MutationDiagnostics } from "@pgxsinkit/contracts";
22
+
23
+ import { compactTimestamp, type DiagnosticDumpReport, deriveStoreId, nowMs, performDatadirDump } from "./export-store";
24
+ import type { ClientPGlite } from "./index";
25
+ import { resolveStoreDataDir } from "./store-path";
26
+
27
+ /** Options for {@link SyncClient.exportDiagnostics}. */
28
+ export interface DiagnosticExportOptions {
29
+ /**
30
+ * Override the generated artefact file name. When omitted, the name is
31
+ * `<storeId>-<timestamp>-diagnostics.sql`, where `storeId` is a filesystem-safe derivation of the store
32
+ * path (see `deriveStoreId`).
33
+ */
34
+ fileName?: string;
35
+ }
36
+
37
+ /** The SQL artefact + its report — the resolved value of {@link SyncClient.exportDiagnostics}. */
38
+ export interface DiagnosticExportResult {
39
+ /** The `pg_dump` output as a named `File` (`application/sql`), loadable into a vanilla Postgres. */
40
+ file: File;
41
+ /** The structured record of the export (ADR-0035). */
42
+ report: DiagnosticDumpReport;
43
+ }
44
+
45
+ /** The dependencies {@link performDiagnosticExport} needs from the owning client — narrow, so it is unit-testable. */
46
+ export interface DiagnosticExportDeps {
47
+ /** The live store to checkpoint and dump (the clone source; the live engine is never suspended). */
48
+ pglite: Pick<ClientPGlite, "exec" | "dumpDataDir">;
49
+ /** The Mutation diagnostics seam (`client.diagnostics().mutation` / `readMutationStats`). */
50
+ readMutationStats: () => Promise<MutationDiagnostics>;
51
+ /**
52
+ * The store's configured plain store PATH (ADR-0036) — reduced to the `storeId` in the default artefact
53
+ * file name. The resolved PGlite dataDir URL is deliberately NOT used: it is internal plumbing and must
54
+ * not leak into an artefact name as something to imitate.
55
+ */
56
+ storePath?: string;
57
+ }
58
+
59
+ /**
60
+ * The shape of `@electric-sql/pglite-tools/pg_dump` — declared locally so the dynamic `import()` stays
61
+ * typed without a static top-level dependency on the module (which would pull its WASM into the boot
62
+ * bundle). `pgDump` runs the WASM `pg_dump` on the given instance's single connection and returns the SQL
63
+ * as a `File`. We run it against the THROWAWAY clone only, never the live engine.
64
+ */
65
+ interface PgliteToolsModule {
66
+ pgDump: (opts: { pg: PGlite; args?: string[]; fileName?: string }) => Promise<File>;
67
+ }
68
+
69
+ /**
70
+ * A process-unique suffix source for the throwaway clone's store name. The clone is memory-backed and
71
+ * closed in a `finally`, so a collision would only matter if two dumps overlapped — the lifecycle slot
72
+ * already forbids that — but a monotonic counter plus a random token makes the name collision-free by
73
+ * construction regardless, so a stray second clone can never adopt a live one's memory namespace.
74
+ */
75
+ let cloneCounter = 0;
76
+ const nextCloneStorePath = (): string =>
77
+ `pgxsinkit-export-clone-${++cloneCounter}-${Math.random().toString(36).slice(2, 10)}`;
78
+
79
+ /** The four extra phase walls the throwaway-clone pipeline adds on top of the shared checkpoint/dump pair. */
80
+ export interface CloneDumpPhases {
81
+ /** Offset from `startPerf` when the internal `dumpDataDir` (the clone's source) began. */
82
+ dumpStartedAtMs: number;
83
+ /** `dumpDataDir` wall — the uncompressed internal tarball the throwaway clone boots from (`compression: "none"`). */
84
+ dumpMs: number;
85
+ /** Offset from `startPerf` when the `CHECKPOINT` began. */
86
+ checkpointStartedAtMs: number;
87
+ /** `CHECKPOINT` wall — flushing dirty buffers before the internal datadir dump the clone consumes. */
88
+ checkpointMs: number;
89
+ /** Offset from `startPerf` when the throwaway clone's `PGlite.create({ loadDataDir })` began. */
90
+ cloneBootStartedAtMs: number;
91
+ /** Clone boot wall — booting the memory-backed throwaway from the internal dump. */
92
+ cloneBootMs: number;
93
+ /** Offset from `startPerf` when `pg_dump` began running against the clone. */
94
+ pgDumpStartedAtMs: number;
95
+ /** `pg_dump` wall — the WASM `pg_dump` reading the clone out to SQL. */
96
+ pgDumpMs: number;
97
+ }
98
+
99
+ /** The raw SQL bytes plus the pipeline phase walls — {@link runThrowawayCloneDump}'s result. */
100
+ export interface CloneDumpResult {
101
+ /** The `pg_dump` output bytes (unwrapped from pglite-tools' `File` polyfill). */
102
+ sqlBytes: Uint8Array<ArrayBuffer>;
103
+ /** The pipeline phase timings, all offset from the caller's `startPerf` anchor. */
104
+ phases: CloneDumpPhases;
105
+ }
106
+
107
+ /**
108
+ * The throwaway-clone dump core shared by BOTH `pgDump` exports (ADR-0035 addendum): (1) a LIVE datadir dump
109
+ * of the running store (`compression: "none"` — the clone consumes the bytes immediately, so gzip+gunzip is
110
+ * pure waste); (2) a memory-backed THROWAWAY PGlite booted from it via `loadDataDir` — engine-less, no
111
+ * `live` extension, nothing `pg_dump`'s `DEALLOCATE ALL` can corrupt; (3) `pg_dump` against the throwaway
112
+ * with the caller's `args` (none for a diagnostic dump; the `-t` allowlist + `--no-owner` for a data
113
+ * export); (4) discard the clone in a `finally`. Factored out so `performDiagnosticExport` and
114
+ * `performDataExport` cannot drift on the clone plumbing, the memory-scheme selection, or the timing house
115
+ * style — the ONLY differences between the two dumps are the `pg_dump` args and the artefact assembly.
116
+ *
117
+ * `@electric-sql/pglite-tools` is loaded ONLY via the dynamic `import()` here (ADR-0035 decision 7): its
118
+ * ~700 kB `pg_dump.wasm` (+ ~100 kB JS) stays off boot and off every non-exporting bundle.
119
+ */
120
+ export interface CloneDumpOptions {
121
+ /** The `pg_dump` args (none for a diagnostic dump; `-t` allowlist + `--no-owner` for a data export). */
122
+ pgDumpArgs?: string[];
123
+ /**
124
+ * A hook run on the throwaway clone AFTER boot, BEFORE `pg_dump` — its one legitimate window to mutate the
125
+ * clone (which is fully owned and discarded straight after). The data export uses it to drop the reconcile
126
+ * triggers `pg_dump -t` would otherwise pull into the artefact (see `buildDataExportCloneCleanupSql`); a
127
+ * diagnostic dump passes none (it wants the store verbatim).
128
+ */
129
+ prepareClone?: (clone: PGlite) => Promise<void>;
130
+ }
131
+
132
+ export async function runThrowawayCloneDump(
133
+ pglite: Pick<ClientPGlite, "exec" | "dumpDataDir">,
134
+ startPerf: number,
135
+ options: CloneDumpOptions = {},
136
+ ): Promise<CloneDumpResult> {
137
+ // Step 1 — the LIVE datadir dump the clone boots from (checkpoint → `dumpDataDir`, the shared core).
138
+ const { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs } = await performDatadirDump(
139
+ pglite,
140
+ "none",
141
+ startPerf,
142
+ );
143
+
144
+ // Step 2 — boot the throwaway. Memory-backed via the resolution module's SCHEME selection (ADR-0036
145
+ // decision 5: NEVER PGlite's explicit `fs: new MemoryFS()` — on 0.5.4 a `dumpDataDir` from an explicit-fs
146
+ // instance silently omits post-initdb relation files). No extensions, no `electric` engine, no `live`:
147
+ // the clone exists only to be read out by `pg_dump`, and `DEALLOCATE ALL` has nothing here to corrupt.
148
+ const cloneDataDir = resolveStoreDataDir(nextCloneStorePath(), "memory");
149
+ const cloneBootStartedAtMs = nowMs() - startPerf;
150
+ const cloneBootStartPerf = nowMs();
151
+ const throwaway = await PGlite.create({ dataDir: cloneDataDir, loadDataDir: dumped });
152
+ const cloneBootMs = nowMs() - cloneBootStartPerf;
153
+
154
+ let sqlBytes: Uint8Array<ArrayBuffer>;
155
+ let pgDumpStartedAtMs: number;
156
+ let pgDumpMs: number;
157
+ try {
158
+ // Between boot and dump — the clone's one mutation window (owned, discarded next) — run the caller's
159
+ // prepare hook. The data export drops the reconcile triggers `-t` would otherwise capture; timed inside
160
+ // the pgDump-prep gap, it is a couple of tiny DROPs, so it is not given its own report phase.
161
+ if (options.prepareClone) {
162
+ await options.prepareClone(throwaway);
163
+ }
164
+
165
+ // Step 3 — the lazy `pg_dump`. The subpath specifier (its export map's `./pg_dump` entry) keeps the
166
+ // main pglite-tools entry — and its WASM — off this import. The caller rebuilds the artefact `File`
167
+ // from the returned bytes, so `fileName` here is cosmetic only.
168
+ pgDumpStartedAtMs = nowMs() - startPerf;
169
+ const pgDumpStartPerf = nowMs();
170
+ const { pgDump } = (await import("@electric-sql/pglite-tools/pg_dump")) as PgliteToolsModule;
171
+ const dumpFile = await pgDump({
172
+ pg: throwaway,
173
+ ...(options.pgDumpArgs != null ? { args: options.pgDumpArgs } : {}),
174
+ fileName: "pgxsinkit-export.sql",
175
+ });
176
+ pgDumpMs = nowMs() - pgDumpStartPerf;
177
+ sqlBytes = new Uint8Array(await dumpFile.arrayBuffer());
178
+ } finally {
179
+ // Step 4 — discard the throwaway in a `finally`, so a THROWING `pg_dump` never leaks the clone (its
180
+ // memory is co-resident with the live engine for the export's duration; leaking one is a real cost).
181
+ await throwaway.close();
182
+ }
183
+
184
+ return {
185
+ sqlBytes,
186
+ phases: {
187
+ checkpointStartedAtMs,
188
+ checkpointMs,
189
+ dumpStartedAtMs,
190
+ dumpMs,
191
+ cloneBootStartedAtMs,
192
+ cloneBootMs,
193
+ pgDumpStartedAtMs,
194
+ pgDumpMs,
195
+ },
196
+ };
197
+ }
198
+
199
+ /**
200
+ * Run a diagnostic dump (ADR-0035): live datadir dump → memory-backed throwaway clone → `pg_dump` → discard
201
+ * the clone → assemble the report. The caller (`createSyncClient`) awaits engine-ready and enters the
202
+ * lifecycle slot BEFORE calling this, exactly as it does for the store backup — kept out of here so the
203
+ * helper stays a pure "do the dump" unit.
204
+ */
205
+ export async function performDiagnosticExport(
206
+ deps: DiagnosticExportDeps,
207
+ options: DiagnosticExportOptions = {},
208
+ ): Promise<DiagnosticExportResult> {
209
+ const startedAt = Date.now();
210
+ const startPerf = nowMs();
211
+
212
+ // A diagnostic dump takes the WHOLE store (no `-t`): synced + overlay + journal + metadata + views +
213
+ // functions — everything a support engineer needs to read a misbehaving store.
214
+ const { sqlBytes, phases } = await runThrowawayCloneDump(deps.pglite, startPerf);
215
+
216
+ const storeId = deriveStoreId(deps.storePath);
217
+ const fileName = options.fileName ?? `${storeId}-${compactTimestamp()}-diagnostics.sql`;
218
+ // Build the artefact `File` from the raw bytes, NOT by re-wrapping pglite-tools' `File`: it is a polyfill
219
+ // in non-browser hosts, and `new File([polyfillFile], name)` keeps the polyfill's own name (the same bun
220
+ // quirk the store backup hit) — the bytes-first path guarantees the store-scoped name/mime stick.
221
+ const file = new File([sqlBytes], fileName, { type: "application/sql" });
222
+
223
+ // Snapshot diagnostics of the LIVE store (the clone is already closed) — the journal state whose rows the
224
+ // SQL also carries, so the report and the artefact agree on what was unflushed at dump time.
225
+ const diagnostics = await deps.readMutationStats();
226
+
227
+ const report: DiagnosticDumpReport = {
228
+ reportVersion: 1,
229
+ kind: "diagnostic-dump",
230
+ scope: "everything",
231
+ startedAt,
232
+ totalMs: nowMs() - startPerf,
233
+ byteLength: file.size,
234
+ phases,
235
+ diagnostics,
236
+ };
237
+
238
+ return { file, report };
239
+ }
@@ -0,0 +1,309 @@
1
+ // Local store export (ADR-0035). Slice 1 ships the **store backup**: a full-fidelity, PGlite-restorable
2
+ // tarball of the whole local store, taken LIVE (no engine suspension). It is a `CHECKPOINT` — run through
3
+ // the engine's normal query serialisation so it orders behind in-flight engine work — followed by
4
+ // PGlite's `dumpDataDir`. Because the dump is of the datadir itself, the Mutation journal and Overlay
5
+ // travel INSIDE the artefact: a store backup is the lossless option, the only export an offline device
6
+ // with unflushed writes can take (CONTEXT.md → Store backup).
7
+ //
8
+ // Every export resolves to an {@link ExportReport} alongside the artefact, extending the ADR-0034
9
+ // observability rule (the BootReport house style) to exports: a versioned, allocation-light plain object
10
+ // (structured-clones across the worker bridge unchanged) carrying phase timings, a {@link MutationDiagnostics}
11
+ // snapshot, and a `startedAt` epoch anchor with every other value a monotonic offset/duration relative to it.
12
+
13
+ import type { MutationDiagnostics } from "@pgxsinkit/contracts";
14
+
15
+ import type { ClientPGlite } from "./index";
16
+
17
+ /**
18
+ * Monotonic clock (ms) — `performance.now()` where available, else `Date.now()` (mirrors BootReport).
19
+ * Exported so the sibling diagnostic-dump path ({@link file://./export-dump.ts}) times its extra phases
20
+ * (clone boot, pg_dump) on the SAME clock as this module's checkpoint/dump pair.
21
+ */
22
+ export const nowMs = (): number => (typeof performance !== "undefined" ? performance.now() : Date.now());
23
+
24
+ /** Options for {@link SyncClient.exportStore}. */
25
+ export interface StoreExportOptions {
26
+ /**
27
+ * How to compress the tarball, forwarded to PGlite's `dumpDataDir`. `"auto"` (the default) gzips when a
28
+ * `CompressionStream` is available and falls back to an uncompressed tar otherwise; `"gzip"` forces
29
+ * compression; `"none"` skips it. The report's `compression` records the compression that was actually
30
+ * applied (which, under `"auto"`, is resolved at runtime).
31
+ */
32
+ compression?: "auto" | "gzip" | "none";
33
+ /**
34
+ * Override the generated artefact file name. When omitted, the name is
35
+ * `<storeId>-<timestamp>.pgdata.tar[.gz]`, where `storeId` is a filesystem-safe derivation of the store
36
+ * path and the extension reflects the applied compression.
37
+ */
38
+ fileName?: string;
39
+ }
40
+
41
+ /**
42
+ * The fields EVERY export report carries, whatever its kind — built in the BootReport house style
43
+ * (ADR-0034): `reportVersion` is a contract number (additive fields keep it, a breaking reshape bumps it);
44
+ * all `*Ms` are milliseconds; `startedAt` is the only wall-clock value and every `*AtMs` is a monotonic
45
+ * offset from it. The per-kind interfaces below add their `kind`/`scope`/`phases` discriminant on top.
46
+ */
47
+ export interface ExportReportCommon {
48
+ reportVersion: 1;
49
+ /** Epoch anchor (`Date.now()`) at export start; every other duration/offset is monotonic relative to it. */
50
+ startedAt: number;
51
+ /** Export start → artefact ready. */
52
+ totalMs: number;
53
+ /** The artefact's byte length — the size the caller downloads / persists. */
54
+ byteLength: number;
55
+ /**
56
+ * The {@link MutationDiagnostics} snapshot at export time — the journal state captured alongside the
57
+ * artefact (for the store backup, the very journal that travels INSIDE the tarball; for the diagnostic
58
+ * dump, the live store's journal at dump time, whose rows the SQL also carries).
59
+ */
60
+ diagnostics: MutationDiagnostics;
61
+ }
62
+
63
+ /**
64
+ * A live **store backup** (ADR-0035): the whole datadir as a PGlite-restorable tarball, journal and overlay
65
+ * included. `checkpoint`/`dump` are the only phases — a store backup is a `CHECKPOINT` + `dumpDataDir`, no
66
+ * clone. Slice-1 shape, kept unchanged (the union is additive).
67
+ */
68
+ export interface StoreBackupReport extends ExportReportCommon {
69
+ /** Which export produced this artefact. */
70
+ kind: "store-backup";
71
+ /** What the artefact covers. A store backup is always the whole store, journal and overlay included. */
72
+ scope: "whole-store";
73
+ /** The compression actually applied to the tarball (resolved from `"auto"` at dump time). */
74
+ compression: "gzip" | "none";
75
+ phases: {
76
+ /** Offset from export start when the `CHECKPOINT` began. */
77
+ checkpointStartedAtMs: number;
78
+ /** `CHECKPOINT` wall — flushing dirty buffers to the datadir before it is tarred, serialised behind engine work. */
79
+ checkpointMs: number;
80
+ /** Offset from export start when `dumpDataDir` began. */
81
+ dumpStartedAtMs: number;
82
+ /** `dumpDataDir` wall — reading the datadir out and assembling (optionally compressing) the tarball. */
83
+ dumpMs: number;
84
+ };
85
+ }
86
+
87
+ /**
88
+ * A **diagnostic dump** (ADR-0035, via the throwaway clone of the addendum): human-readable SQL of
89
+ * EVERYTHING the store holds — synced tables, the `_overlay`/`_mutations` journal, the `pgxsinkit` metadata
90
+ * schema, the read-model views, and the reconcile functions/triggers. It is a live datadir dump (checkpoint
91
+ * + `dumpDataDir`) fed into a memory-backed throwaway PGlite via `loadDataDir`, against which `pg_dump` runs
92
+ * — so the live engine is never touched (the addendum's whole point). Its phases add the clone boot and the
93
+ * `pg_dump` walls to the shared checkpoint/dump pair.
94
+ */
95
+ export interface DiagnosticDumpReport extends ExportReportCommon {
96
+ kind: "diagnostic-dump";
97
+ /** A diagnostic dump covers everything the store holds — synced data, journal, metadata, views, functions. */
98
+ scope: "everything";
99
+ phases: {
100
+ /** Offset from export start when the `CHECKPOINT` began. */
101
+ checkpointStartedAtMs: number;
102
+ /** `CHECKPOINT` wall — flushing dirty buffers before the internal datadir dump the clone consumes. */
103
+ checkpointMs: number;
104
+ /** Offset from export start when the internal `dumpDataDir` began. */
105
+ dumpStartedAtMs: number;
106
+ /** `dumpDataDir` wall — the uncompressed internal tarball the throwaway clone boots from (`compression: "none"`). */
107
+ dumpMs: number;
108
+ /** Offset from export start when the throwaway clone's `PGlite.create({ loadDataDir })` began. */
109
+ cloneBootStartedAtMs: number;
110
+ /** Clone boot wall — booting the memory-backed throwaway from the internal dump. */
111
+ cloneBootMs: number;
112
+ /** Offset from export start when `pg_dump` began running against the clone. */
113
+ pgDumpStartedAtMs: number;
114
+ /** `pg_dump` wall — the WASM `pg_dump` reading the clone out to SQL. */
115
+ pgDumpMs: number;
116
+ };
117
+ }
118
+
119
+ /**
120
+ * A **data export** (ADR-0035 decision 1, via the throwaway clone of the addendum): the PORTABLE artefact —
121
+ * the synced tables and the enum types they depend on, schema + data, nothing of pgxsinkit's machinery,
122
+ * loadable into a vanilla Postgres. It is a generated enum DDL header concatenated ahead of a `pg_dump -t`
123
+ * (per synced table) `--no-owner` run against the same memory-backed throwaway clone the diagnostic dump
124
+ * uses. Unlike the other two exports it GUARDS: it requires a drained Mutation journal (or the explicit
125
+ * `drainJournal: false` escape hatch), so its phases add the drain wall ahead of the clone pipeline, and it
126
+ * records its provenance (`tables` = the `-t` allowlist actually applied, `escapeHatch` = whether the drain
127
+ * was skipped).
128
+ */
129
+ export interface DataExportReport extends ExportReportCommon {
130
+ kind: "data-export";
131
+ /** A data export covers the synced tables + their enum types only — never pgxsinkit's overlay/journal/metadata. */
132
+ scope: "synced-tables";
133
+ /**
134
+ * The schema-qualified physical synced tables the `-t` allowlist targeted, in registry order — the
135
+ * self-describing provenance of exactly what the artefact carries (ephemeral/read-projection entries
136
+ * excluded by construction). May be empty when the registry declares no owning persistent table.
137
+ */
138
+ tables: string[];
139
+ /**
140
+ * `true` when `drainJournal: false` skipped the drain and the artefact reflects the SYNCED state as-is
141
+ * (unflushed local writes silently absent). `false` on the strict path (a drained or empty journal).
142
+ */
143
+ escapeHatch: boolean;
144
+ phases: {
145
+ /** Offset from export start when the drain guard began (`0` when the escape hatch skipped it). */
146
+ drainStartedAtMs: number;
147
+ /** Drain wall — flushing + awaiting the journal reach fully-drained (`0` under the escape hatch). */
148
+ drainMs: number;
149
+ /** Offset from export start when the `CHECKPOINT` began. */
150
+ checkpointStartedAtMs: number;
151
+ /** `CHECKPOINT` wall — flushing dirty buffers before the internal datadir dump the clone consumes. */
152
+ checkpointMs: number;
153
+ /** Offset from export start when the internal `dumpDataDir` began. */
154
+ dumpStartedAtMs: number;
155
+ /** `dumpDataDir` wall — the uncompressed internal tarball the throwaway clone boots from (`compression: "none"`). */
156
+ dumpMs: number;
157
+ /** Offset from export start when the throwaway clone's `PGlite.create({ loadDataDir })` began. */
158
+ cloneBootStartedAtMs: number;
159
+ /** Clone boot wall — booting the memory-backed throwaway from the internal dump. */
160
+ cloneBootMs: number;
161
+ /** Offset from export start when `pg_dump -t` began running against the clone. */
162
+ pgDumpStartedAtMs: number;
163
+ /** `pg_dump -t` wall — the WASM `pg_dump` reading the allowlisted tables out to SQL. */
164
+ pgDumpMs: number;
165
+ };
166
+ }
167
+
168
+ /**
169
+ * A structured, versioned record of one local-store export (ADR-0035) — a discriminated union on `kind`.
170
+ * Every member shares {@link ExportReportCommon}; the `kind`/`scope`/`phases` discriminant tells the three
171
+ * exports apart. `exportStore` resolves a {@link StoreBackupReport}; `exportDiagnostics` a
172
+ * {@link DiagnosticDumpReport}; `exportData` a {@link DataExportReport}.
173
+ */
174
+ export type ExportReport = StoreBackupReport | DiagnosticDumpReport | DataExportReport;
175
+
176
+ /** The artefact + its report — the resolved value of {@link SyncClient.exportStore}. */
177
+ export interface StoreExportResult {
178
+ /** The store-backup tarball as a named `File` (PGlite-restorable via `loadDataDir`, a later slice). */
179
+ file: File;
180
+ /** The structured record of the export (ADR-0035). */
181
+ report: StoreBackupReport;
182
+ }
183
+
184
+ /**
185
+ * Reduce a plain store PATH (ADR-0036) to a filesystem-safe token for the backup file name. Takes the
186
+ * path's LAST segment (as PGlite's own `dumpDataDir` does when it names the inner db), then keeps only
187
+ * `[A-Za-z0-9._-]`. No scheme stripping — the store path is a plain name, never a storage URL. Falls back
188
+ * to a fixed token for an empty path so the name is always well formed.
189
+ */
190
+ export function deriveStoreId(storePath: string | undefined): string {
191
+ if (!storePath) return "pgxsinkit-store";
192
+ const lastSegment = storePath.split("/").filter(Boolean).pop() ?? storePath;
193
+ const safe = lastSegment.replace(/[^A-Za-z0-9._-]/g, "-").replace(/^-+|-+$/g, "");
194
+ return safe.length > 0 ? safe : "pgxsinkit-store";
195
+ }
196
+
197
+ /**
198
+ * An ISO-ish, filesystem-safe timestamp (colons/dots → hyphens) for a default artefact file name. Exported
199
+ * so the diagnostic-dump path names its `.sql` artefact with the identical timestamp shape.
200
+ */
201
+ export const compactTimestamp = (): string => new Date().toISOString().replace(/[:.]/g, "-");
202
+
203
+ /**
204
+ * The datadir dump both exports share (ADR-0035): a `CHECKPOINT` through the store's normal query path,
205
+ * then `dumpDataDir`. The store backup keeps its bytes as the artefact; the diagnostic dump feeds them to a
206
+ * throwaway clone. Factored out so exactly one implementation of "flush + tar the live datadir" exists —
207
+ * `performStoreExport` and `performDiagnosticExport` cannot drift on the checkpoint ordering or the timing
208
+ * house style. Returns the raw `dumpDataDir` output plus the two phase walls, both offset from `startPerf`
209
+ * (the caller's export-start monotonic anchor) so the timings compose into either report.
210
+ *
211
+ * The `CHECKPOINT` is a utility statement — Drizzle has no builder for it, so a raw `exec` is the justified
212
+ * tier-③ form here. Running it via `pglite.exec` serialises it behind any in-flight engine work on PGlite's
213
+ * single connection, flushing dirty buffers to the datadir the dump then reads — so the tarball reflects
214
+ * committed state, not a torn mid-write datadir.
215
+ */
216
+ export async function performDatadirDump(
217
+ pglite: Pick<ClientPGlite, "exec" | "dumpDataDir">,
218
+ compression: "auto" | "gzip" | "none",
219
+ startPerf: number,
220
+ ): Promise<{
221
+ dumped: Awaited<ReturnType<ClientPGlite["dumpDataDir"]>>;
222
+ checkpointStartedAtMs: number;
223
+ checkpointMs: number;
224
+ dumpStartedAtMs: number;
225
+ dumpMs: number;
226
+ }> {
227
+ const checkpointStartedAtMs = nowMs() - startPerf;
228
+ const checkpointStartPerf = nowMs();
229
+ await pglite.exec("CHECKPOINT");
230
+ const checkpointMs = nowMs() - checkpointStartPerf;
231
+
232
+ const dumpStartedAtMs = nowMs() - startPerf;
233
+ const dumpStartPerf = nowMs();
234
+ const dumped = await pglite.dumpDataDir(compression);
235
+ const dumpMs = nowMs() - dumpStartPerf;
236
+
237
+ return { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs };
238
+ }
239
+
240
+ /** The dependencies {@link performStoreExport} needs from the owning client — narrow, so it is unit-testable. */
241
+ export interface StoreExportDeps {
242
+ /** The live store to checkpoint and dump. */
243
+ pglite: Pick<ClientPGlite, "exec" | "dumpDataDir">;
244
+ /** The Mutation diagnostics seam (`client.diagnostics().mutation` / `readMutationStats`). */
245
+ readMutationStats: () => Promise<MutationDiagnostics>;
246
+ /**
247
+ * The store's configured plain store PATH (ADR-0036) — reduced to the `storeId` in the default backup
248
+ * file name (`deriveStoreId`). The resolved PGlite dataDir URL is deliberately NOT used here: it is
249
+ * internal plumbing and must not leak into an artefact name as something to imitate.
250
+ */
251
+ storePath?: string;
252
+ }
253
+
254
+ /**
255
+ * Run a live store backup (ADR-0035): checkpoint → dump → snapshot diagnostics → assemble the report. The
256
+ * caller (`createSyncClient`) is responsible for awaiting engine-ready and entering the lifecycle slot
257
+ * BEFORE calling this — kept out of here so the helper stays a pure "do the dump" unit. No engine
258
+ * suspension: the backup is live by design.
259
+ */
260
+ export async function performStoreExport(
261
+ deps: StoreExportDeps,
262
+ options: StoreExportOptions = {},
263
+ ): Promise<StoreExportResult> {
264
+ const startedAt = Date.now();
265
+ const startPerf = nowMs();
266
+ const compression = options.compression ?? "auto";
267
+
268
+ // Live dump of the whole datadir (checkpoint → `dumpDataDir`, the shared core) — the journal and overlay
269
+ // ride inside it (the lossless backup, ADR-0035).
270
+ const { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs } = await performDatadirDump(
271
+ deps.pglite,
272
+ compression,
273
+ startPerf,
274
+ );
275
+
276
+ // PGlite names its dump `<db>.tar.gz` (type `application/x-gzip`) when it compressed, `<db>.tar`
277
+ // (`application/x-tar`) otherwise — so the RESULT, not the requested option, tells us what `"auto"`
278
+ // resolved to. Detect from whichever of name/type the runtime populated (its `File` is a polyfill in
279
+ // non-browser hosts, so trust both).
280
+ const dumpedName = dumped instanceof File ? dumped.name : "";
281
+ const gzipped = dumpedName.endsWith(".gz") || dumped.type.includes("gzip");
282
+ const appliedCompression: "gzip" | "none" = gzipped ? "gzip" : "none";
283
+ const extension = gzipped ? ".pgdata.tar.gz" : ".pgdata.tar";
284
+ const mimeType = gzipped ? "application/x-gzip" : "application/x-tar";
285
+ const storeId = deriveStoreId(deps.storePath);
286
+ const fileName = options.fileName ?? `${storeId}-${compactTimestamp()}${extension}`;
287
+ // Build the artefact `File` from the raw bytes, NOT by re-wrapping `dumped`: PGlite's dump is a File
288
+ // polyfill in non-browser hosts, and `new File([polyfillFile], name)` keeps the polyfill's own name
289
+ // rather than the one we pass. Extracting the bytes first guarantees the store-scoped name sticks.
290
+ const bytes = new Uint8Array(await dumped.arrayBuffer());
291
+ const file = new File([bytes], fileName, { type: mimeType });
292
+
293
+ // Snapshot diagnostics AFTER the dump so it describes the journal state the artefact actually holds.
294
+ const diagnostics = await deps.readMutationStats();
295
+
296
+ const report: StoreBackupReport = {
297
+ reportVersion: 1,
298
+ kind: "store-backup",
299
+ scope: "whole-store",
300
+ compression: appliedCompression,
301
+ startedAt,
302
+ totalMs: nowMs() - startPerf,
303
+ byteLength: file.size,
304
+ phases: { checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs },
305
+ diagnostics,
306
+ };
307
+
308
+ return { file, report };
309
+ }