@powerhousedao/reactor-api 6.2.3-dev.8 → 6.2.3-dev.80

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 (68) hide show
  1. package/README.md +7 -2
  2. package/dist/{adapter-gateway-apollo-CxJNBVyD.mjs → adapter-gateway-apollo-D-EdZ4e-.mjs} +23 -23
  3. package/dist/adapter-gateway-apollo-D-EdZ4e-.mjs.map +1 -0
  4. package/dist/{adapter-gateway-mercurius-CZVy88Za.mjs → adapter-gateway-mercurius-CdxLge5p.mjs} +4 -12
  5. package/dist/adapter-gateway-mercurius-CdxLge5p.mjs.map +1 -0
  6. package/dist/{adapter-http-express-B39rPhqH.mjs → adapter-http-express-P0t-mdMV.mjs} +10 -10
  7. package/dist/adapter-http-express-P0t-mdMV.mjs.map +1 -0
  8. package/dist/{adapter-http-fastify-BwXO6rqE.mjs → adapter-http-fastify-D0OP5q9K.mjs} +13 -12
  9. package/dist/adapter-http-fastify-D0OP5q9K.mjs.map +1 -0
  10. package/dist/base-document-models-D-cmBBYJ.mjs +1583 -0
  11. package/dist/base-document-models-D-cmBBYJ.mjs.map +1 -0
  12. package/dist/create-schema-Dio_7akA.d.mts +159 -0
  13. package/dist/create-schema-Dio_7akA.d.mts.map +1 -0
  14. package/dist/error-info-BaEL50f5.mjs +486 -0
  15. package/dist/error-info-BaEL50f5.mjs.map +1 -0
  16. package/dist/index.d.mts +3083 -980
  17. package/dist/index.d.mts.map +1 -1
  18. package/dist/index.mjs +6848 -2736
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/package-subgraph-check-C0PD_Tj9.mjs +138 -0
  21. package/dist/package-subgraph-check-C0PD_Tj9.mjs.map +1 -0
  22. package/dist/pglite-like-CKQEL_Q0.d.mts +27 -0
  23. package/dist/pglite-like-CKQEL_Q0.d.mts.map +1 -0
  24. package/dist/pglite-node-DGms6Ssa.mjs +715 -0
  25. package/dist/pglite-node-DGms6Ssa.mjs.map +1 -0
  26. package/dist/rolldown-runtime-8H4AJuhK.mjs +16 -0
  27. package/dist/run-node-handler-CQjyjOuN.mjs +52 -0
  28. package/dist/run-node-handler-CQjyjOuN.mjs.map +1 -0
  29. package/dist/src/graphql/subgraph-types.d.mts +43 -0
  30. package/dist/src/graphql/subgraph-types.d.mts.map +1 -0
  31. package/dist/src/graphql/subgraph-types.mjs +14 -0
  32. package/dist/src/graphql/subgraph-types.mjs.map +1 -0
  33. package/dist/src/packages/https-hooks.d.mts +4 -4
  34. package/dist/src/packages/https-hooks.d.mts.map +1 -1
  35. package/dist/src/packages/https-hooks.mjs +2 -2
  36. package/dist/src/packages/https-hooks.mjs.map +1 -1
  37. package/dist/src/packages/vite-loader.d.mts +30 -9
  38. package/dist/src/packages/vite-loader.d.mts.map +1 -1
  39. package/dist/src/packages/vite-loader.mjs +198 -85
  40. package/dist/src/packages/vite-loader.mjs.map +1 -1
  41. package/dist/src/pglite/pglite-node.d.mts +393 -0
  42. package/dist/src/pglite/pglite-node.d.mts.map +1 -0
  43. package/dist/src/pglite/pglite-node.mjs +5 -0
  44. package/dist/src/pglite/worker/entry.d.mts +2 -0
  45. package/dist/src/pglite/worker/entry.mjs +251 -0
  46. package/dist/src/pglite/worker/entry.mjs.map +1 -0
  47. package/dist/subgraph-extraction-BA9WKjn1.mjs +1877 -0
  48. package/dist/subgraph-extraction-BA9WKjn1.mjs.map +1 -0
  49. package/dist/subgraph-schema-owner-BEjuk2Xv.mjs +10 -0
  50. package/dist/subgraph-schema-owner-BEjuk2Xv.mjs.map +1 -0
  51. package/dist/types-PXB1ctpi.d.mts +99 -0
  52. package/dist/types-PXB1ctpi.d.mts.map +1 -0
  53. package/package.json +30 -21
  54. package/dist/adapter-gateway-apollo-CxJNBVyD.mjs.map +0 -1
  55. package/dist/adapter-gateway-apollo-DowrX6E_.mjs +0 -4
  56. package/dist/adapter-gateway-mercurius-CZVy88Za.mjs.map +0 -1
  57. package/dist/adapter-gateway-stitching-CaZjvRzx.mjs +0 -316
  58. package/dist/adapter-gateway-stitching-CaZjvRzx.mjs.map +0 -1
  59. package/dist/adapter-http-express-B39rPhqH.mjs.map +0 -1
  60. package/dist/adapter-http-fastify-BwXO6rqE.mjs.map +0 -1
  61. package/dist/path-normalize-BOQwY9wR.mjs +0 -23
  62. package/dist/path-normalize-BOQwY9wR.mjs.map +0 -1
  63. package/dist/types-DcYyNcHJ.d.mts +0 -48
  64. package/dist/types-DcYyNcHJ.d.mts.map +0 -1
  65. package/dist/utils-XWVecaNn.mjs +0 -653
  66. package/dist/utils-XWVecaNn.mjs.map +0 -1
  67. package/dist/websocket-DncAB9XK.mjs +0 -18
  68. package/dist/websocket-DncAB9XK.mjs.map +0 -1
@@ -0,0 +1,393 @@
1
+ import { n as PGLITE_UTC_PARSERS, t as PGliteLike } from "../../pglite-like-CKQEL_Q0.mjs";
2
+ import { ILogger } from "document-model";
3
+ import nodeFs from "node:fs";
4
+ import { PGlite, QueryOptions, Results } from "@electric-sql/pglite";
5
+ import { NodeFS } from "@electric-sql/pglite/nodefs";
6
+ import { ResourceLimits } from "node:worker_threads";
7
+ //#region src/pglite/maintenance.d.ts
8
+ export declare const DEFAULT_MAINTENANCE_INTERVAL_MS: number;
9
+ export declare const DEFAULT_VACUUM_FULL_ABOVE_BYTES: number;
10
+ export declare const DEFAULT_VACUUM_FULL_QUIET_MS: number;
11
+ /**
12
+ * How long a pending VACUUM FULL waits for a quiet store before it runs
13
+ * anyway: by default it never does (0), because a forced rewrite of a large
14
+ * store under load holds the only connection for minutes, every caller times
15
+ * out, and the dir needs about twice its size in free space meanwhile.
16
+ * `PH_PGLITE_VACUUM_FULL=forced` restores a deadline.
17
+ */
18
+ export declare const DEFAULT_VACUUM_FULL_MAX_DEFER_MS = 0;
19
+ /** The deadline `PH_PGLITE_VACUUM_FULL=forced` sets. */
20
+ export declare const FORCED_VACUUM_FULL_MAX_DEFER_MS: number;
21
+ type MaintenanceOutcome = "vacuum" | "vacuum-full" | "idle" | "not-ready" | "in-transaction" | "failed";
22
+ interface MaintenanceLogger {
23
+ warn(message: string): void;
24
+ /** A finished VACUUM FULL is reported here; `warn` when absent. */
25
+ info?(message: string): void;
26
+ }
27
+ /** Runs a maintenance pass in the owner's turn; see {@link MaintenanceOptions.gate}. */
28
+ type MaintenanceGate = <T>(task: () => Promise<T>) => Promise<T>;
29
+ interface MaintenanceOptions {
30
+ /** VACUUM + CHECKPOINT cadence; PGlite has no autovacuum. Default 5 min; 0 disables. */
31
+ intervalMs?: number;
32
+ /** First pass runs VACUUM FULL when `base/` exceeds this at open. Default 256 MB; 0 disables. */
33
+ vacuumFullAboveBytes?: number;
34
+ /**
35
+ * VACUUM FULL holds the store for minutes on a large dir, so it waits for a
36
+ * store with no synced statement (no write, no catch-up) for this long,
37
+ * counted from open; until then a pass runs plain VACUUM and keeps the
38
+ * VACUUM FULL pending. Default 60 s; 0 runs it on the first pass.
39
+ */
40
+ vacuumFullQuietMs?: number;
41
+ /**
42
+ * The longest a pending VACUUM FULL waits for that quiet window, counted
43
+ * from open; past it the next pass runs VACUUM FULL anyway. Default 0,
44
+ * which waits for the quiet window however long it takes.
45
+ */
46
+ vacuumFullMaxDeferMs?: number;
47
+ /**
48
+ * Queues each pass with the store's other work, e.g. behind a worker's
49
+ * pending requests, so a pass never starts ahead of a statement already
50
+ * admitted. A pass still waiting here when the store closes is skipped.
51
+ */
52
+ gate?: MaintenanceGate;
53
+ logger?: MaintenanceLogger;
54
+ /** Clock for the quiet window; tests pass their own. */
55
+ now?: () => number;
56
+ }
57
+ export declare class PgliteMaintenance {
58
+ private readonly intervalMs;
59
+ private readonly vacuumFullAboveBytes;
60
+ private readonly vacuumFullQuietMs;
61
+ private readonly vacuumFullMaxDeferMs;
62
+ private readonly gate?;
63
+ private readonly logger?;
64
+ private readonly now;
65
+ private pg?;
66
+ private label;
67
+ private closing;
68
+ private syncsSinceMaintenance;
69
+ private vacuumFullPending;
70
+ private timer?;
71
+ private inFlight?;
72
+ private active;
73
+ private deferralLogged;
74
+ private lastSyncAt;
75
+ private openedAt;
76
+ constructor(options?: MaintenanceOptions);
77
+ get scheduled(): boolean;
78
+ get running(): boolean;
79
+ start(pg: PGlite, label: string, baseBytes: number): void;
80
+ noteSync(): void;
81
+ /** Waits for a pass that has started; one still queued at the gate is left to skip itself. */
82
+ stop(): Promise<void>;
83
+ run(): Promise<MaintenanceOutcome>;
84
+ private runNow;
85
+ private pass;
86
+ private schedule;
87
+ private cancel;
88
+ }
89
+ //#endregion
90
+ //#region src/pglite/durable-node-fs.d.ts
91
+ type NodeFsClass = typeof NodeFS;
92
+ interface DurableNodeFsOptions {
93
+ /** Default true; `PH_PGLITE_FSYNC=0` turns it off (power-loss durability off). */
94
+ fsync?: boolean;
95
+ /** Default 5 min; 0 disables. */
96
+ maintenanceIntervalMs?: number;
97
+ /** `base/` size at open; default 256 MB; 0 disables. */
98
+ vacuumFullAboveBytes?: number;
99
+ /** See `MaintenanceOptions.vacuumFullQuietMs`; default 60 s. */
100
+ vacuumFullQuietMs?: number;
101
+ /** See `MaintenanceOptions.vacuumFullMaxDeferMs`; default 0 (quiet window only). */
102
+ vacuumFullMaxDeferMs?: number;
103
+ /** See `MaintenanceOptions.gate`. */
104
+ maintenanceGate?: MaintenanceGate;
105
+ /** Clock for the maintenance quiet window; tests pass their own. */
106
+ now?: () => number;
107
+ logger?: {
108
+ warn(message: string): void;
109
+ info?(message: string): void;
110
+ };
111
+ /** Emscripten abort (a Postgres PANIC, e.g. ENOSPC on WAL). */
112
+ onAbort?: (what: unknown) => void;
113
+ hostFs?: Pick<typeof nodeFs, "fsyncSync" | "fdatasyncSync">;
114
+ }
115
+ type DurableNodeFs = InstanceType<NodeFsClass> & {
116
+ readonly maintenance: PgliteMaintenance;
117
+ };
118
+ export declare function resolvePgliteFsync(env: Record<string, string | undefined>): boolean;
119
+ /** `PH_PGLITE_VACUUM_FULL`: when an oversized store's one-time VACUUM FULL may run. */
120
+ type PgliteVacuumFullMode = "off" | "quiet" | "forced";
121
+ /** The VACUUM FULL settings an environment selects; see {@link resolvePgliteMaintenance}. */
122
+ type PgliteMaintenanceSettings = Pick<DurableNodeFsOptions, "vacuumFullAboveBytes" | "vacuumFullQuietMs" | "vacuumFullMaxDeferMs">;
123
+ /**
124
+ * Reads the VACUUM FULL knobs. `PH_PGLITE_VACUUM_FULL` is `off` (the
125
+ * default: never), `quiet` (only after the quiet window, however long that
126
+ * takes) or `forced` (a deadline of 30 min from open, after which it runs
127
+ * under load). Off is the default because a full rewrite of a large store
128
+ * needs about twice its size in free disk and holds the only connection for
129
+ * minutes, and on a store that is live data rather than bloat it reclaims
130
+ * nothing; a quiet window of a minute arrives naturally between jobs, so
131
+ * `quiet` is an opt-in for stores known to be small or bloated.
132
+ * `PH_PGLITE_VACUUM_FULL_ABOVE_MB` sets the size that makes a store
133
+ * eligible; `PH_PGLITE_VACUUM_FULL_QUIET_MS` and
134
+ * `PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS` override the mode's timings. A value
135
+ * that is not a non-negative number is left to the default; an unknown mode
136
+ * throws, since silently running a rewrite is what this guards against.
137
+ */
138
+ export declare function resolvePgliteMaintenance(env: Record<string, string | undefined>): PgliteMaintenanceSettings;
139
+ /** Built over the passed-in class so PG16 dirs on `pglite-legacy-02` get the same behaviour. */
140
+ export declare function createDurableNodeFs(Base: NodeFsClass, dataDir: string, options?: DurableNodeFsOptions): DurableNodeFs;
141
+ //#endregion
142
+ //#region src/pglite/sync-tree.d.ts
143
+ interface SyncTreeHostFs {
144
+ fsyncSync(fd: number): void;
145
+ }
146
+ interface SyncTreeResult {
147
+ files: number;
148
+ dirs: number;
149
+ }
150
+ /** One pass over a finished tree; interleaving fsync with writes costs seconds. */
151
+ export declare function syncTree(root: string, hostFs?: SyncTreeHostFs): SyncTreeResult;
152
+ /** fsyncs a directory's entries; false where the platform refuses (Windows). */
153
+ export declare function syncDirectory(dir: string, hostFs?: SyncTreeHostFs): boolean;
154
+ //#endregion
155
+ //#region src/pglite/snapshot-reader.d.ts
156
+ export declare const SNAPSHOT_FILE_NAME = "snapshot.bin";
157
+ interface ExtractSnapshotOptions {
158
+ chunkSize?: number;
159
+ /** Default true: one fsync pass over the tree after the last write. */
160
+ sync?: boolean;
161
+ hostFs?: SyncTreeHostFs;
162
+ }
163
+ interface ExtractedSnapshot {
164
+ pgVersionMajor: number;
165
+ /** `global/pg_control` bytes; absent only in synthetic trees. */
166
+ pgControl?: Buffer;
167
+ /** Entries written to disk; skipped entries are not counted. */
168
+ entries: number;
169
+ /** Size of the snapshot file. */
170
+ bytes: number;
171
+ }
172
+ /** Unpacks a snapshot into the existing `outDir`. */
173
+ export declare function extractSnapshot(snapshotPath: string, outDir: string, options?: ExtractSnapshotOptions): Promise<ExtractedSnapshot>;
174
+ //#endregion
175
+ //#region src/pglite/convert-snapshot-dir.d.ts
176
+ interface VerifyHandle {
177
+ query<T>(sql: string): Promise<{
178
+ rows: T[];
179
+ }>;
180
+ close(): Promise<void>;
181
+ }
182
+ type ConversionStep = "extract" | "verify" | "renameOld" | "renameNew" | "removeOld";
183
+ interface ConversionDeps {
184
+ /** Opens `dataDir` with the stock NodeFS of the PGlite module for `major`. */
185
+ openForVerify: (major: number, dataDir: string) => Promise<VerifyHandle>;
186
+ logger: ILogger;
187
+ /** Test hook: throw after a named step to simulate a crash there. */
188
+ afterStep?: (step: ConversionStep) => void | Promise<void>;
189
+ hostFs?: SyncTreeHostFs;
190
+ }
191
+ /** Settles the debris of an interrupted conversion; runs before it at boot. */
192
+ export declare function recoverConversion(dir: string, deps: ConversionDeps): Promise<void>;
193
+ /** Extracts into `.converting`, verifies by opening it, swaps through `.old`. */
194
+ export declare function convertSnapshotDir(dir: string, deps: ConversionDeps): Promise<"converted" | "none">;
195
+ //#endregion
196
+ //#region src/pglite/preflight.d.ts
197
+ /** PG major of the pinned @electric-sql/pglite; it exports none, so the test checks initdb. */
198
+ export declare const CURRENT_PGLITE_MAJOR = 17;
199
+ /** `openForVerify` over the loaded PGlite module only. */
200
+ export declare function openCurrentPgliteForVerify(major: number, dataDir: string): Promise<VerifyHandle>;
201
+ /** Converts a snapshot store and clears the files a previous run leaves behind. */
202
+ export declare function preparePgliteDataDir(dir: string, deps: ConversionDeps): Promise<void>;
203
+ /** PGlite leaves `postmaster.pid` after every close and `pg_wal/xlogtemp.*` after some. */
204
+ export declare function removeStalePgliteFiles(dir: string, logger: Pick<ILogger, "debug">): Promise<void>;
205
+ //#endregion
206
+ //#region src/pglite/wasm-wrapper-tiering.d.ts
207
+ export declare const WASM_WRAPPER_TIERING_FLAG = "--wasm-wrapper-tiering-budget=1000000000";
208
+ /** Node 24 V8 double-frees tiered wasm wrappers as instances die (#66366). */
209
+ export declare function disableWasmWrapperTiering(): boolean;
210
+ //#endregion
211
+ //#region src/pglite/worker/protocol.d.ts
212
+ /**
213
+ * Wire protocol between a {@link ThreadedPGlite} stand-in on the main thread
214
+ * and the worker thread that owns one PGlite store.
215
+ *
216
+ * Every payload is structured-cloned, so it holds data only: functions such as
217
+ * row parsers are named by preset and built inside the worker.
218
+ */
219
+ /** Module specifiers the worker imports PGlite and its NodeFS from. */
220
+ type PGliteModuleSpec = {
221
+ /** Specifier or file URL of the PGlite package entry, e.g. `@electric-sql/pglite`. */
222
+ pglite: string;
223
+ /** Specifier or file URL of the matching NodeFS entry, e.g. `@electric-sql/pglite/nodefs`. */
224
+ nodefs: string;
225
+ };
226
+ export declare const CURRENT_PGLITE_MODULE: PGliteModuleSpec;
227
+ /** Row parser sets the worker knows how to build. */
228
+ type PGliteParserPreset = "none" | "utc-timestamps";
229
+ /** DurableNodeFs settings; see `DurableNodeFsOptions`. */
230
+ type PGliteWorkerDurableFsOptions = {
231
+ fsync: boolean;
232
+ /** Undefined keeps the DurableNodeFs default (5 min); 0 disables. */
233
+ maintenanceIntervalMs?: number;
234
+ /** Undefined keeps the DurableNodeFs default (256 MB); 0 disables. */
235
+ vacuumFullAboveBytes?: number;
236
+ /** Undefined keeps the DurableNodeFs default (60 s); 0 runs VACUUM FULL on the first pass. */
237
+ vacuumFullQuietMs?: number;
238
+ /** Undefined keeps the DurableNodeFs default (0: the quiet window only); a deadline in ms forces the run past it. */
239
+ vacuumFullMaxDeferMs?: number;
240
+ };
241
+ /** What the worker opens. */
242
+ type PGliteWorkerStoreOptions = {
243
+ /** Names the store in logs and errors, e.g. `read-storage`. */
244
+ label: string;
245
+ /** PGlite data dir; null opens an in-memory store. */
246
+ dataDir: string | null;
247
+ module: PGliteModuleSpec;
248
+ /** DurableNodeFs over `dataDir`; null uses the module's stock NodeFS. Ignored in memory. */
249
+ durableFs: PGliteWorkerDurableFsOptions | null;
250
+ parsers: PGliteParserPreset;
251
+ };
252
+ type PGliteErrorInfo = {
253
+ name: string;
254
+ message: string;
255
+ stack?: string;
256
+ cause?: PGliteErrorInfo;
257
+ /** Postgres error fields, copied when present. */
258
+ fields: Record<string, string>;
259
+ };
260
+ //#endregion
261
+ //#region src/pglite/worker/error-info.d.ts
262
+ /** Flattens an error and its cause chain into a structured-clonable shape. */
263
+ export declare function toPGliteErrorInfo(err: unknown, depth?: number): PGliteErrorInfo;
264
+ /** Rebuilds an `Error` carrying the original name, stack, Postgres fields and cause chain. */
265
+ export declare function fromPGliteErrorInfo(info: PGliteErrorInfo): Error;
266
+ //#endregion
267
+ //#region src/pglite/worker/errors.d.ts
268
+ /** Base class for failures of the worker itself, as opposed to SQL errors. */
269
+ export declare class PGliteWorkerError extends Error {
270
+ readonly label: string;
271
+ constructor(label: string, message: string, options?: {
272
+ cause?: unknown;
273
+ });
274
+ }
275
+ /** The worker could not open its store; every call on the stand-in fails with this. */
276
+ export declare class PGliteWorkerInitError extends PGliteWorkerError {
277
+ constructor(label: string, options?: {
278
+ cause?: unknown;
279
+ });
280
+ }
281
+ /** The worker thread exited (crash, terminate, out of memory) before answering. */
282
+ export declare class PGliteWorkerExitedError extends PGliteWorkerError {
283
+ readonly exitCode: number;
284
+ constructor(label: string, exitCode: number, options?: {
285
+ cause?: unknown;
286
+ });
287
+ }
288
+ /** A call was made after `close()` started. */
289
+ export declare class PGliteWorkerClosedError extends PGliteWorkerError {
290
+ constructor(label: string);
291
+ }
292
+ //#endregion
293
+ //#region src/pglite/worker/threaded-pglite.d.ts
294
+ export declare const DEFAULT_PGLITE_WORKER_MEMORY_MB = 1024;
295
+ export declare const DEFAULT_PGLITE_WORKER_CLOSE_GRACE_MS = 60000;
296
+ type ThreadedPGliteOptions = {
297
+ store: PGliteWorkerStoreOptions;
298
+ /** Caps the worker's JS heap; defaults to {@link resolvePgliteWorkerMemoryMb}. WebAssembly memory is outside it. */
299
+ memoryLimitMb?: number;
300
+ /** The worker script; defaults to the built entry next to this module. Tests pass a tsx bootstrap. */
301
+ workerScript?: string | URL;
302
+ /** Bound on PGlite's own close (its shutdown checkpoint) before the thread is terminated. */
303
+ closeGraceMs?: number;
304
+ logger?: ILogger;
305
+ };
306
+ /** Called once, when the worker reports that the wasm runtime aborted. */
307
+ type PGliteAbortListener = (reason: string) => void;
308
+ /** Called once, when the worker thread is gone; `error` is null after a clean close. */
309
+ type PGliteExitListener = (error: Error | null) => void;
310
+ /** `PH_PGLITE_WORKER_MEMORY_MB`, else {@link DEFAULT_PGLITE_WORKER_MEMORY_MB}. */
311
+ export declare function resolvePgliteWorkerMemoryMb(env: Record<string, string | undefined>): number;
312
+ /**
313
+ * Main-thread stand-in for a PGlite instance whose store lives in a worker
314
+ * thread. It has the surface knex-pglite, kysely-pglite-dialect and
315
+ * `HardenedPGliteDialect` use: `waitReady`, `query`, `exec`, a synchronous
316
+ * `isInTransaction()`, `closed` and `close()`.
317
+ *
318
+ * Construction is synchronous and starts the worker; calls made before the
319
+ * worker is ready are queued behind its open. The worker runs requests one at
320
+ * a time in arrival order, and every answer carries the transaction status.
321
+ * The instance is a plain extensible object, since knex stores its own
322
+ * bookkeeping on the connection.
323
+ */
324
+ export declare class ThreadedPGlite implements PGliteLike {
325
+ readonly label: string;
326
+ /** Settles once the worker has opened the store; rejects with {@link PGliteWorkerInitError}. */
327
+ readonly waitReady: Promise<void>;
328
+ private readonly worker;
329
+ private readonly logger;
330
+ private readonly closeGraceMs;
331
+ private readonly pending;
332
+ /** The reservation an `admit` run is executing under, carried through its async calls. */
333
+ private readonly admission;
334
+ private readonly abortListeners;
335
+ private readonly exitListeners;
336
+ private nextId;
337
+ private phase;
338
+ private inTransaction;
339
+ private terminalError;
340
+ private workerError;
341
+ private abortReason;
342
+ private closePromise;
343
+ constructor(options: ThreadedPGliteOptions);
344
+ /** True once the store is open and until close starts. */
345
+ get ready(): boolean;
346
+ /** True once close has started or the worker is gone. */
347
+ get closed(): boolean;
348
+ /** The reason the worker reported for a wasm abort, or null. */
349
+ get aborted(): string | null;
350
+ /** The limits the worker thread runs under (empty once it has exited). */
351
+ get resourceLimits(): ResourceLimits;
352
+ /** The worker's thread id, for diagnostics. */
353
+ get threadId(): number;
354
+ query<T = Record<string, unknown>>(sql: string, params?: unknown[], options?: QueryOptions): Promise<Results<T>>;
355
+ exec(sql: string, options?: QueryOptions): Promise<Results[]>;
356
+ /**
357
+ * `HardenedPGliteDialect`'s admission hook: `run` starts only once the worker
358
+ * can run its statements at once, with nothing queued ahead and no
359
+ * maintenance pass in progress, so the dialect's statement deadline (which
360
+ * starts inside `run`) never counts time spent waiting behind other work.
361
+ * Statements `run` issues bypass the queue until it settles; everything
362
+ * else waits behind them.
363
+ */
364
+ admit<T>(run: () => Promise<T>): Promise<T>;
365
+ /** The status after the most recently answered request, as PGlite reported it. */
366
+ isInTransaction(): boolean;
367
+ /** Closes PGlite inside the worker (its shutdown checkpoint), then terminates the thread. */
368
+ close(): Promise<void>;
369
+ /** Stops the thread at once, without PGlite's close; pending calls reject. */
370
+ terminate(): Promise<void>;
371
+ onAbort(listener: PGliteAbortListener): () => void;
372
+ onExit(listener: PGliteExitListener): () => void;
373
+ private closeWorker;
374
+ private currentAdmission;
375
+ private release;
376
+ private request;
377
+ private handleMessage;
378
+ private settle;
379
+ private settleError;
380
+ private handleAbort;
381
+ private handleLog;
382
+ private handleWorkerError;
383
+ private handleExit;
384
+ /** Records a fatal error and stops the thread; the exit rejects what is pending. */
385
+ private fail;
386
+ private rejectPending;
387
+ }
388
+ /** Absolute path of the worker script for `new Worker(...)`; null when none can run here. */
389
+ export declare const pgliteWorkerEntryPath: string | null;
390
+ //#endregion
391
+ export { type ConversionDeps, type ConversionStep, type DurableNodeFs, type DurableNodeFsOptions, type ExtractSnapshotOptions, type ExtractedSnapshot, type MaintenanceGate, type MaintenanceLogger, type MaintenanceOptions, type MaintenanceOutcome, type NodeFsClass, PGLITE_UTC_PARSERS, type PGliteAbortListener, type PGliteErrorInfo, type PGliteExitListener, type PGliteLike, type PGliteModuleSpec, type PGliteParserPreset, type PGliteWorkerDurableFsOptions, type PGliteWorkerStoreOptions, type PgliteMaintenanceSettings, type PgliteVacuumFullMode, type SyncTreeHostFs, type SyncTreeResult, type ThreadedPGliteOptions, type VerifyHandle };
392
+ export {};
393
+ //# sourceMappingURL=pglite-node.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pglite-node.d.mts","names":[],"sources":["../../../src/pglite/maintenance.ts","../../../src/pglite/durable-node-fs.ts","../../../src/pglite/sync-tree.ts","../../../src/pglite/snapshot-reader.ts","../../../src/pglite/convert-snapshot-dir.ts","../../../src/pglite/preflight.ts","../../../src/pglite/wasm-wrapper-tiering.ts","../../../src/pglite/worker/protocol.ts","../../../src/pglite/worker/error-info.ts","../../../src/pglite/worker/errors.ts","../../../src/pglite/worker/threaded-pglite.ts"],"mappings":";;;;;;;qBAIa;qBACA;qBACA;;;;;;;;qBAQA;;qBAEA;KAGD;UAQK;EACf,KAAK;;EAEL,MAAM;;;KAII,mBAAmB,GAAG,YAAY,QAAQ,OAAO,QAAQ;UAEpD;;EAEf;;EAEA;;;;;;;EAOA;;;;;;EAMA;;;;;;EAMA,OAAO;EACP,SAAS;;EAET;;qBAGW;mBACM;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;UAET;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;EAER,YAAY,UAAS;MAsBjB;MAIA;EAIJ,MAAM,IAAI,QAAQ,eAAe;EAUjC;;EAMM,QAAQ;EAMR,OAAO,QAAQ;UAKP;UASA;UAoEN;UAoBA;;;;KCnOE,qBAAqB;UAKhB;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,kBAAkB;;EAElB;EACA;IAAW,KAAK;IAAwB,MAAM;;;EAE9C,WAAW;EACX,SAAS,YAAY;;KAGX,gBAAgB,aAAa;WAC9B,aAAa;;wBAGR,mBACd,KAAK;;KAMK;;KASA,4BAA4B,KACtC;;;;;;;;;;;;;;;;wBAmBc,yBACd,KAAK,qCACJ;;wBAyGa,oBACd,MAAM,aACN,iBACA,UAAS,uBACR;;;UC3Lc;EACf,UAAU;;UAGK;EACf;EACA;;;wBAIc,SACd,cACA,SAAQ,iBACP;;wBA+Ba,cACd,aACA,SAAQ;;;qBC3CG;UASI;EACf;;EAEA;EACA,SAAS;;UAGM;EACf;;EAEA,YAAY;;EAEZ;;EAEA;;;wBAIoB,gBACpB,sBACA,gBACA,UAAS,yBACR,QAAQ;;;UC/BM;EACf,MAAM,GAAG,cAAc;IAAU,MAAM;;EACvC,SAAS;;KAGC;UAOK;;EAEf,gBAAgB,eAAe,oBAAoB,QAAQ;EAC3D,QAAQ;;EAER,aAAa,MAAM,0BAA0B;EAC7C,SAAS;;;wBA6BW,kBACpB,aACA,MAAM,iBACL;;wBA6CmB,mBACpB,aACA,MAAM,iBACL;;;;qBC3FU;;wBAGS,2BACpB,eACA,kBACC,QAAQ;;wBAYW,qBACpB,aACA,MAAM,iBACL;;wBAOmB,uBACpB,aACA,QAAQ,KAAK,oBACZ;;;qBC1CU;;wBAMG;;;;;;;;;;;KCCJ;;EAEV;;EAEA;;qBAGW,uBAAuB;;KAMxB;;KAGA;EACV;;EAEA;;EAEA;;EAEA;;EAEA;;;KAIU;;EAEV;;EAEA;EACA,QAAQ;;EAER,WAAW;EACX,SAAS;;KASC;EACV;EACA;EACA;EACA,QAAQ;;EAER,QAAQ;;;;;wBClCM,kBAAkB,cAAc,iBAAY;;wBAsB5C,oBAAoB,MAAM,kBAAkB;;;;qBChD/C,0BAA0B;WAE1B;EADX,YACW,eACT,iBACA;IAAY;;;;qBAQH,8BAA8B;EACzC,YAAY,eAAe;IAAY;;;;qBAW5B,gCAAgC;WAGhC;EAFX,YACE,eACS,kBACT;IAAY;;;;qBAYH,gCAAgC;EAC3C,YAAY;;;;qBCnBD;qBACA;KAED;EACV,OAAO;;EAEP;;EAEA,wBAAwB;;EAExB;EACA,SAAS;;;KAIC,uBAAuB;;KAGvB,sBAAsB,OAAO;;wBAazB,4BACd,KAAK;;;;;;;;;;;;;qBA2BM,0BAA0B;WAC5B;;WAEA,WAAW;mBAEH;mBACA;mBACA;mBACA;;mBAEA;mBACA;mBACA;UACT;UACA;UACA;UACA;UACA;UACA;UACA;EAER,YAAY,SAAS;;MAgDjB;;MAKA;;MAKA;;MAKA,kBAAkB;;MAKlB;EAIE,MAAM,IAAI,yBACd,aACA,oBACA,UAAU,eACT,QAAQ,QAAQ;EAab,KAAK,aAAa,UAAU,eAAe,QAAQ;;;;;;;;;EAoBnD,MAAM,GAAG,WAAW,QAAQ,KAAK,QAAQ;;EAc/C;;EAKA,SAAS;;EAYH,aAAa;EAOnB,QAAQ,UAAU;EAOlB,OAAO,UAAU;UAOH;UAsCN;UAIA;UAQA;UAsBA;UAqCA;UAUA;UAUA;UAkBA;UAyBA;UAKA;;UA0BA;UAQA;;;qBAyFG"}
@@ -0,0 +1,5 @@
1
+ import { a as resolvePgliteMaintenance, c as DEFAULT_MAINTENANCE_INTERVAL_MS, d as DEFAULT_VACUUM_FULL_QUIET_MS, f as FORCED_VACUUM_FULL_MAX_DEFER_MS, i as resolvePgliteFsync, l as DEFAULT_VACUUM_FULL_ABOVE_BYTES, m as PGLITE_UTC_PARSERS, n as toPGliteErrorInfo, o as syncDirectory, p as PgliteMaintenance, r as createDurableNodeFs, s as syncTree, t as fromPGliteErrorInfo, u as DEFAULT_VACUUM_FULL_MAX_DEFER_MS } from "../../error-info-BaEL50f5.mjs";
2
+ import { _ as convertSnapshotDir, a as resolvePgliteWorkerMemoryMb, b as extractSnapshot, c as PGliteWorkerError, d as WASM_WRAPPER_TIERING_FLAG, f as disableWasmWrapperTiering, g as removeStalePgliteFiles, h as preparePgliteDataDir, i as pgliteWorkerEntryPath, l as PGliteWorkerExitedError, m as openCurrentPgliteForVerify, n as DEFAULT_PGLITE_WORKER_MEMORY_MB, o as CURRENT_PGLITE_MODULE, p as CURRENT_PGLITE_MAJOR, r as ThreadedPGlite, s as PGliteWorkerClosedError, t as DEFAULT_PGLITE_WORKER_CLOSE_GRACE_MS, u as PGliteWorkerInitError, v as recoverConversion, y as SNAPSHOT_FILE_NAME } from "../../pglite-node-DGms6Ssa.mjs";
3
+ export { CURRENT_PGLITE_MAJOR, CURRENT_PGLITE_MODULE, DEFAULT_MAINTENANCE_INTERVAL_MS, DEFAULT_PGLITE_WORKER_CLOSE_GRACE_MS, DEFAULT_PGLITE_WORKER_MEMORY_MB, DEFAULT_VACUUM_FULL_ABOVE_BYTES, DEFAULT_VACUUM_FULL_MAX_DEFER_MS, DEFAULT_VACUUM_FULL_QUIET_MS, FORCED_VACUUM_FULL_MAX_DEFER_MS, PGLITE_UTC_PARSERS, PGliteWorkerClosedError, PGliteWorkerError, PGliteWorkerExitedError, PGliteWorkerInitError, PgliteMaintenance, SNAPSHOT_FILE_NAME, ThreadedPGlite, WASM_WRAPPER_TIERING_FLAG, convertSnapshotDir, createDurableNodeFs, disableWasmWrapperTiering, extractSnapshot, fromPGliteErrorInfo, openCurrentPgliteForVerify, pgliteWorkerEntryPath, preparePgliteDataDir, recoverConversion, removeStalePgliteFiles, resolvePgliteFsync, resolvePgliteMaintenance, resolvePgliteWorkerMemoryMb, syncDirectory, syncTree, toPGliteErrorInfo };
4
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a5b1cd7a-ad0f-553e-a374-f8e7c53e2ff9")}catch(e){}}();
5
+ //# debugId=a5b1cd7a-ad0f-553e-a374-f8e7c53e2ff9
@@ -0,0 +1,2 @@
1
+ export {}
2
+ export {};
@@ -0,0 +1,251 @@
1
+
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="190de489-10fe-547d-8123-7e3a65865685")}catch(e){}}();
3
+ import { m as PGLITE_UTC_PARSERS, n as toPGliteErrorInfo, r as createDurableNodeFs } from "../../../error-info-BaEL50f5.mjs";
4
+ import { isMainThread, parentPort } from "node:worker_threads";
5
+ //#region src/pglite/worker/run-worker.ts
6
+ /** A wasm runtime abort, as opposed to a Postgres error (which carries a code). */
7
+ const ABORT_PATTERN = /PGlite aborted|Aborted\(/;
8
+ /**
9
+ * Worker side of a threaded PGlite store: owns the PGlite instance (and its
10
+ * DurableNodeFs and maintenance), and runs the host's requests one at a time
11
+ * in arrival order, so a transaction opened by SQL holds the single
12
+ * connection until it commits or rolls back.
13
+ */
14
+ function runPGliteWorker(port) {
15
+ let pg = null;
16
+ let initError = null;
17
+ let closed = false;
18
+ let abortReported = false;
19
+ let tail = Promise.resolve();
20
+ let admission = null;
21
+ function post(message) {
22
+ port.postMessage(message);
23
+ }
24
+ function log(level, message, error) {
25
+ post({
26
+ type: "log",
27
+ level,
28
+ message,
29
+ error: error === void 0 ? void 0 : toPGliteErrorInfo(error)
30
+ });
31
+ }
32
+ function reportAbort(reason) {
33
+ if (abortReported) return;
34
+ abortReported = true;
35
+ post({
36
+ type: "abort",
37
+ reason
38
+ });
39
+ }
40
+ function inTransaction() {
41
+ if (pg === null || pg.closed) return false;
42
+ try {
43
+ return pg.isInTransaction();
44
+ } catch {
45
+ return false;
46
+ }
47
+ }
48
+ function postError(id, error) {
49
+ const info = toPGliteErrorInfo(error);
50
+ if (!("code" in info.fields) && ABORT_PATTERN.test(info.message)) reportAbort(info.message);
51
+ post({
52
+ type: "error",
53
+ id,
54
+ error: info,
55
+ inTransaction: inTransaction()
56
+ });
57
+ }
58
+ function openStore() {
59
+ if (pg !== null && !closed) return pg;
60
+ throw new Error(`PGlite worker cannot run the request: ${closed ? "the store is closed" : "the store did not open"}`, { cause: initError ?? void 0 });
61
+ }
62
+ async function handleInit(msg) {
63
+ if (pg !== null) {
64
+ postError(msg.id, /* @__PURE__ */ new Error("PGlite worker is already initialised"));
65
+ return;
66
+ }
67
+ let instance;
68
+ try {
69
+ instance = await createPGlite(msg.store, {
70
+ warn: (message) => log("warn", message),
71
+ onAbort: (what) => reportAbort(`PGlite aborted: ${String(what)}`),
72
+ maintenanceGate: enqueue
73
+ });
74
+ } catch (error) {
75
+ initError = error;
76
+ postError(msg.id, error);
77
+ return;
78
+ }
79
+ try {
80
+ await instance.waitReady;
81
+ } catch (error) {
82
+ initError = error;
83
+ postError(msg.id, error);
84
+ return;
85
+ }
86
+ pg = instance;
87
+ post({
88
+ type: "ready",
89
+ id: msg.id,
90
+ inTransaction: inTransaction()
91
+ });
92
+ }
93
+ async function handleQuery(msg) {
94
+ let result;
95
+ try {
96
+ result = await openStore().query(msg.sql, msg.params, msg.options);
97
+ } catch (error) {
98
+ postError(msg.id, error);
99
+ return;
100
+ }
101
+ post({
102
+ type: "query-result",
103
+ id: msg.id,
104
+ result: toWorkerResults(result),
105
+ inTransaction: inTransaction()
106
+ });
107
+ }
108
+ async function handleExec(msg) {
109
+ let results;
110
+ try {
111
+ results = await openStore().exec(msg.sql, msg.options);
112
+ } catch (error) {
113
+ postError(msg.id, error);
114
+ return;
115
+ }
116
+ post({
117
+ type: "exec-result",
118
+ id: msg.id,
119
+ results: results.map(toWorkerResults),
120
+ inTransaction: inTransaction()
121
+ });
122
+ }
123
+ async function handleClose(id) {
124
+ const instance = pg;
125
+ closed = true;
126
+ if (instance === null || instance.closed) {
127
+ post({
128
+ type: "closed",
129
+ id
130
+ });
131
+ return;
132
+ }
133
+ try {
134
+ await instance.close();
135
+ } catch (error) {
136
+ postError(id, error);
137
+ return;
138
+ }
139
+ post({
140
+ type: "closed",
141
+ id
142
+ });
143
+ }
144
+ /** Runs `task` after everything queued so far: requests, reservations, maintenance passes. */
145
+ function enqueue(task) {
146
+ const result = tail.then(task);
147
+ tail = result.catch(() => void 0);
148
+ return result;
149
+ }
150
+ /** Holds the queue for one reservation: only its tagged statements run until it is released. */
151
+ async function handleReserve(id) {
152
+ const state = {
153
+ id,
154
+ release: () => void 0,
155
+ statements: Promise.resolve()
156
+ };
157
+ const released = new Promise((resolve) => {
158
+ state.release = resolve;
159
+ });
160
+ admission = state;
161
+ post({
162
+ type: "admitted",
163
+ id,
164
+ inTransaction: inTransaction()
165
+ });
166
+ await released;
167
+ await state.statements;
168
+ admission = null;
169
+ }
170
+ function handle(msg) {
171
+ switch (msg.type) {
172
+ case "reserve": return handleReserve(msg.id);
173
+ case "release": return Promise.resolve();
174
+ case "init": return handleInit(msg);
175
+ case "query": return handleQuery(msg);
176
+ case "exec": return handleExec(msg);
177
+ case "close": return handleClose(msg.id);
178
+ default: return Promise.resolve();
179
+ }
180
+ }
181
+ process.on("uncaughtException", (err) => {
182
+ try {
183
+ log("error", "PGlite worker uncaughtException", err);
184
+ } catch {}
185
+ throw err;
186
+ });
187
+ process.on("unhandledRejection", (reason) => {
188
+ try {
189
+ log("error", "PGlite worker unhandledRejection", reason);
190
+ } catch {}
191
+ });
192
+ port.on("message", (msg) => {
193
+ if (msg.type === "release") {
194
+ if (admission?.id === msg.id) admission.release();
195
+ return;
196
+ }
197
+ const current = admission;
198
+ if ((msg.type === "query" || msg.type === "exec") && current !== null && msg.admission === current.id) {
199
+ current.statements = current.statements.then(() => handle(msg));
200
+ return;
201
+ }
202
+ enqueue(() => handle(msg));
203
+ });
204
+ }
205
+ async function createPGlite(store, hooks) {
206
+ const { PGlite: PGliteClass } = await import(store.module.pglite);
207
+ const options = { parsers: parsersFor(store.parsers) };
208
+ if (store.dataDir === null) return new PGliteClass(options);
209
+ const { NodeFS } = await import(store.module.nodefs);
210
+ const durable = store.durableFs;
211
+ const fs = durable === null ? new NodeFS(store.dataDir) : createDurableNodeFs(NodeFS, store.dataDir, {
212
+ fsync: durable.fsync,
213
+ maintenanceIntervalMs: durable.maintenanceIntervalMs,
214
+ vacuumFullAboveBytes: durable.vacuumFullAboveBytes,
215
+ vacuumFullQuietMs: durable.vacuumFullQuietMs,
216
+ vacuumFullMaxDeferMs: durable.vacuumFullMaxDeferMs,
217
+ maintenanceGate: hooks.maintenanceGate,
218
+ logger: { warn: hooks.warn },
219
+ onAbort: hooks.onAbort
220
+ });
221
+ return new PGliteClass({
222
+ ...options,
223
+ fs
224
+ });
225
+ }
226
+ function parsersFor(preset) {
227
+ switch (preset) {
228
+ case "utc-timestamps": return { ...PGLITE_UTC_PARSERS };
229
+ case "none": return {};
230
+ default: throw new Error(`Unknown PGlite parser preset: ${String(preset)}`);
231
+ }
232
+ }
233
+ function toWorkerResults(result) {
234
+ return {
235
+ rows: result.rows,
236
+ affectedRows: result.affectedRows,
237
+ fields: result.fields.map((field) => ({
238
+ name: field.name,
239
+ dataTypeID: field.dataTypeID
240
+ }))
241
+ };
242
+ }
243
+ //#endregion
244
+ //#region src/pglite/worker/entry.ts
245
+ if (isMainThread || parentPort === null) throw new Error("pglite worker entry must be run as a worker thread");
246
+ runPGliteWorker(parentPort);
247
+ //#endregion
248
+ export {};
249
+
250
+ //# sourceMappingURL=entry.mjs.map
251
+ //# debugId=190de489-10fe-547d-8123-7e3a65865685