@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,486 @@
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]="67ef2060-b4e7-5104-b280-60179cc2bdd7")}catch(e){}}();
3
+ import path from "node:path";
4
+ import nodeFs, { promises } from "node:fs";
5
+ import { protocol } from "@electric-sql/pglite";
6
+ import { ERRNO_CODES } from "@electric-sql/pglite/basefs";
7
+ //#region src/pglite/parsers.ts
8
+ const PGLITE_UTC_PARSERS = { 1114: (value) => /* @__PURE__ */ new Date(`${value.replace(" ", "T")}Z`) };
9
+ //#endregion
10
+ //#region src/pglite/maintenance.ts
11
+ const DEFAULT_MAINTENANCE_INTERVAL_MS = 3e5;
12
+ const DEFAULT_VACUUM_FULL_ABOVE_BYTES = 268435456;
13
+ const DEFAULT_VACUUM_FULL_QUIET_MS = 6e4;
14
+ /**
15
+ * How long a pending VACUUM FULL waits for a quiet store before it runs
16
+ * anyway: by default it never does (0), because a forced rewrite of a large
17
+ * store under load holds the only connection for minutes, every caller times
18
+ * out, and the dir needs about twice its size in free space meanwhile.
19
+ * `PH_PGLITE_VACUUM_FULL=forced` restores a deadline.
20
+ */
21
+ const DEFAULT_VACUUM_FULL_MAX_DEFER_MS = 0;
22
+ /** The deadline `PH_PGLITE_VACUUM_FULL=forced` sets. */
23
+ const FORCED_VACUUM_FULL_MAX_DEFER_MS = 18e5;
24
+ const MAINTENANCE_RETRY_MS = 1e3;
25
+ var PgliteMaintenance = class {
26
+ intervalMs;
27
+ vacuumFullAboveBytes;
28
+ vacuumFullQuietMs;
29
+ vacuumFullMaxDeferMs;
30
+ gate;
31
+ logger;
32
+ now;
33
+ pg;
34
+ label = "";
35
+ closing = false;
36
+ syncsSinceMaintenance = 0;
37
+ vacuumFullPending = false;
38
+ timer;
39
+ inFlight;
40
+ active = false;
41
+ deferralLogged = false;
42
+ lastSyncAt = 0;
43
+ openedAt = 0;
44
+ constructor(options = {}) {
45
+ this.intervalMs = Math.max(0, options.intervalMs ?? 3e5);
46
+ this.vacuumFullAboveBytes = Math.max(0, options.vacuumFullAboveBytes ?? 268435456);
47
+ this.vacuumFullQuietMs = Math.max(0, options.vacuumFullQuietMs ?? 6e4);
48
+ this.vacuumFullMaxDeferMs = Math.max(0, options.vacuumFullMaxDeferMs ?? 0);
49
+ this.gate = options.gate;
50
+ this.logger = options.logger;
51
+ this.now = options.now ?? Date.now;
52
+ }
53
+ get scheduled() {
54
+ return this.timer !== void 0;
55
+ }
56
+ get running() {
57
+ return this.inFlight !== void 0;
58
+ }
59
+ start(pg, label, baseBytes) {
60
+ this.pg = pg;
61
+ this.label = label;
62
+ this.vacuumFullPending = this.vacuumFullAboveBytes > 0 && baseBytes > this.vacuumFullAboveBytes;
63
+ this.lastSyncAt = this.now();
64
+ this.openedAt = this.lastSyncAt;
65
+ this.schedule(this.intervalMs);
66
+ }
67
+ noteSync() {
68
+ this.syncsSinceMaintenance++;
69
+ this.lastSyncAt = this.now();
70
+ }
71
+ /** Waits for a pass that has started; one still queued at the gate is left to skip itself. */
72
+ async stop() {
73
+ this.closing = true;
74
+ this.cancel();
75
+ if (this.active) await this.inFlight;
76
+ }
77
+ async run() {
78
+ if (this.gate) return this.gate(() => this.runNow());
79
+ return this.runNow();
80
+ }
81
+ async runNow() {
82
+ this.active = true;
83
+ try {
84
+ return await this.pass();
85
+ } finally {
86
+ this.active = false;
87
+ }
88
+ }
89
+ async pass() {
90
+ const pg = this.pg;
91
+ if (this.closing || !pg?.ready) return "not-ready";
92
+ const isReady = () => pg.ready && !this.closing;
93
+ const now = this.now();
94
+ const overdue = this.vacuumFullMaxDeferMs > 0 && now - this.openedAt >= this.vacuumFullMaxDeferMs;
95
+ const full = this.vacuumFullPending && (now - this.lastSyncAt >= this.vacuumFullQuietMs || overdue);
96
+ if (this.vacuumFullPending && !full && !this.deferralLogged) {
97
+ this.deferralLogged = true;
98
+ this.logger?.warn(`DurableNodeFs: ${this.label}/base exceeds ${this.vacuumFullAboveBytes} bytes; VACUUM FULL waits until the store has had no writes for ${this.vacuumFullQuietMs} ms${this.vacuumFullMaxDeferMs > 0 ? `, or at most ${this.vacuumFullMaxDeferMs} ms from open` : ""}`);
99
+ }
100
+ if (!full && this.syncsSinceMaintenance === 0) return "idle";
101
+ const baseDir = path.join(this.label, "base");
102
+ const bytesBefore = full ? await dirBytes(baseDir) : 0;
103
+ const startedAt = this.now();
104
+ let outcome;
105
+ try {
106
+ outcome = await pg._runExclusiveQuery(async () => {
107
+ if (!isReady()) return "not-ready";
108
+ const { messages } = await pg.execProtocol(protocol.serialize.query(""), { syncToFs: false });
109
+ if (transactionStatus(messages) !== "I") return "in-transaction";
110
+ if (full) this.logger?.warn(`DurableNodeFs: ${this.label}/base exceeds ${this.vacuumFullAboveBytes} bytes; running VACUUM FULL`);
111
+ for (const statement of [full ? "VACUUM FULL" : "VACUUM", "CHECKPOINT"]) {
112
+ if (!isReady()) return "not-ready";
113
+ await pg.execProtocol(protocol.serialize.query(statement), { syncToFs: false });
114
+ }
115
+ return full ? "vacuum-full" : "vacuum";
116
+ });
117
+ } catch (err) {
118
+ this.logger?.warn(`DurableNodeFs maintenance failed: ${errorMessage(err)}`);
119
+ return "failed";
120
+ }
121
+ if (outcome !== "vacuum" && outcome !== "vacuum-full") return outcome;
122
+ this.syncsSinceMaintenance = 0;
123
+ if (full) {
124
+ this.vacuumFullPending = false;
125
+ const bytesAfter = await dirBytes(baseDir);
126
+ const message = `DurableNodeFs: ${this.label}/base VACUUM FULL finished in ${this.now() - startedAt} ms; ${bytesBefore} -> ${bytesAfter} bytes`;
127
+ if (this.logger?.info) this.logger.info(message);
128
+ else this.logger?.warn(message);
129
+ }
130
+ return outcome;
131
+ }
132
+ schedule(delayMs) {
133
+ if (this.intervalMs === 0 || this.closing) return;
134
+ this.timer = setTimeout(() => {
135
+ this.timer = void 0;
136
+ this.inFlight = this.run().then((outcome) => {
137
+ this.schedule(outcome === "in-transaction" ? Math.min(MAINTENANCE_RETRY_MS, this.intervalMs) : this.intervalMs);
138
+ return outcome;
139
+ }).finally(() => {
140
+ this.inFlight = void 0;
141
+ });
142
+ }, delayMs);
143
+ this.timer.unref();
144
+ }
145
+ cancel() {
146
+ if (!this.timer) return;
147
+ clearTimeout(this.timer);
148
+ this.timer = void 0;
149
+ }
150
+ };
151
+ /** Total size of the regular files under `dir`; 0 when `dir` is missing. */
152
+ async function dirBytes(dir) {
153
+ let entries;
154
+ try {
155
+ entries = await promises.readdir(dir, { withFileTypes: true });
156
+ } catch (err) {
157
+ if (err.code === "ENOENT") return 0;
158
+ throw err;
159
+ }
160
+ let total = 0;
161
+ for (const entry of entries) {
162
+ const full = path.join(dir, entry.name);
163
+ if (entry.isDirectory()) total += await dirBytes(full);
164
+ else if (entry.isFile()) total += (await promises.stat(full)).size;
165
+ }
166
+ return total;
167
+ }
168
+ function transactionStatus(messages) {
169
+ for (let i = messages.length - 1; i >= 0; i--) {
170
+ const m = messages[i];
171
+ if (m.name === "readyForQuery") return m.status;
172
+ }
173
+ }
174
+ function errorMessage(err) {
175
+ return err instanceof Error ? err.message : String(err);
176
+ }
177
+ //#endregion
178
+ //#region src/pglite/sync-tree.ts
179
+ /** One pass over a finished tree; interleaving fsync with writes costs seconds. */
180
+ function syncTree(root, hostFs = nodeFs) {
181
+ const result = {
182
+ files: 0,
183
+ dirs: 0
184
+ };
185
+ const pending = [path.resolve(root)];
186
+ while (pending.length > 0) {
187
+ const dir = pending.pop();
188
+ for (const entry of nodeFs.readdirSync(dir, { withFileTypes: true })) {
189
+ const full = path.join(dir, entry.name);
190
+ if (entry.isDirectory()) pending.push(full);
191
+ else if (entry.isFile()) {
192
+ syncFile(full, hostFs);
193
+ result.files++;
194
+ }
195
+ }
196
+ syncDirectory(dir, hostFs);
197
+ result.dirs++;
198
+ }
199
+ return result;
200
+ }
201
+ function syncFile(file, hostFs) {
202
+ const fd = nodeFs.openSync(file, "r+");
203
+ try {
204
+ hostFs.fsyncSync(fd);
205
+ } finally {
206
+ nodeFs.closeSync(fd);
207
+ }
208
+ }
209
+ /** fsyncs a directory's entries; false where the platform refuses (Windows). */
210
+ function syncDirectory(dir, hostFs = nodeFs) {
211
+ let fd;
212
+ try {
213
+ fd = nodeFs.openSync(dir, "r");
214
+ } catch {
215
+ return false;
216
+ }
217
+ try {
218
+ hostFs.fsyncSync(fd);
219
+ return true;
220
+ } catch {
221
+ return false;
222
+ } finally {
223
+ nodeFs.closeSync(fd);
224
+ }
225
+ }
226
+ //#endregion
227
+ //#region src/pglite/durable-node-fs.ts
228
+ const EIO = 29;
229
+ function resolvePgliteFsync(env) {
230
+ return env.PH_PGLITE_FSYNC !== "0";
231
+ }
232
+ const VACUUM_FULL_MODES = [
233
+ "off",
234
+ "quiet",
235
+ "forced"
236
+ ];
237
+ /**
238
+ * Reads the VACUUM FULL knobs. `PH_PGLITE_VACUUM_FULL` is `off` (the
239
+ * default: never), `quiet` (only after the quiet window, however long that
240
+ * takes) or `forced` (a deadline of 30 min from open, after which it runs
241
+ * under load). Off is the default because a full rewrite of a large store
242
+ * needs about twice its size in free disk and holds the only connection for
243
+ * minutes, and on a store that is live data rather than bloat it reclaims
244
+ * nothing; a quiet window of a minute arrives naturally between jobs, so
245
+ * `quiet` is an opt-in for stores known to be small or bloated.
246
+ * `PH_PGLITE_VACUUM_FULL_ABOVE_MB` sets the size that makes a store
247
+ * eligible; `PH_PGLITE_VACUUM_FULL_QUIET_MS` and
248
+ * `PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS` override the mode's timings. A value
249
+ * that is not a non-negative number is left to the default; an unknown mode
250
+ * throws, since silently running a rewrite is what this guards against.
251
+ */
252
+ function resolvePgliteMaintenance(env) {
253
+ const rawMode = env.PH_PGLITE_VACUUM_FULL?.trim().toLowerCase() || "off";
254
+ if (!isVacuumFullMode(rawMode)) throw new Error(`Invalid PH_PGLITE_VACUUM_FULL: ${String(env.PH_PGLITE_VACUUM_FULL)}. Expected "off", "quiet" or "forced".`);
255
+ const mode = rawMode;
256
+ const settings = {};
257
+ if (mode === "off") settings.vacuumFullAboveBytes = 0;
258
+ if (mode === "forced") settings.vacuumFullMaxDeferMs = FORCED_VACUUM_FULL_MAX_DEFER_MS;
259
+ const aboveMb = nonNegative(env.PH_PGLITE_VACUUM_FULL_ABOVE_MB);
260
+ if (aboveMb !== void 0 && mode !== "off") settings.vacuumFullAboveBytes = aboveMb * 1024 * 1024;
261
+ const quiet = nonNegative(env.PH_PGLITE_VACUUM_FULL_QUIET_MS);
262
+ if (quiet !== void 0) settings.vacuumFullQuietMs = quiet;
263
+ const maxDefer = nonNegative(env.PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS);
264
+ if (maxDefer !== void 0) settings.vacuumFullMaxDeferMs = maxDefer;
265
+ return settings;
266
+ }
267
+ function isVacuumFullMode(value) {
268
+ return VACUUM_FULL_MODES.includes(value);
269
+ }
270
+ function nonNegative(value) {
271
+ if (value === void 0 || value.trim() === "") return void 0;
272
+ const parsed = Number(value);
273
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
274
+ }
275
+ function isReadOnly(stream) {
276
+ return stream.flags !== void 0 && (stream.flags & 3) === 0;
277
+ }
278
+ const WASM_ENTRY_POINTS = [
279
+ "_interactive_one",
280
+ "_interactive_write",
281
+ "_pgl_backend",
282
+ "_pgl_initdb",
283
+ "_pgl_shutdown"
284
+ ];
285
+ function poisonAfterAbort(mod, what) {
286
+ if (!mod) return;
287
+ const message = `PGlite aborted: ${String(what) || "wasm runtime abort"}`;
288
+ for (const name of WASM_ENTRY_POINTS) {
289
+ if (typeof mod[name] !== "function") continue;
290
+ mod[name] = () => {
291
+ throw new Error(message);
292
+ };
293
+ }
294
+ try {
295
+ mod.FS.quit();
296
+ } catch {}
297
+ }
298
+ /** Built over the passed-in class so PG16 dirs on `pglite-legacy-02` get the same behaviour. */
299
+ function createDurableNodeFs(Base, dataDir, options = {}) {
300
+ const fsync = options.fsync ?? true;
301
+ const hostFs = options.hostFs ?? nodeFs;
302
+ const logger = options.logger;
303
+ const onAbort = options.onAbort;
304
+ const resolvedDir = path.resolve(dataDir);
305
+ const maintenance = new PgliteMaintenance({
306
+ intervalMs: options.maintenanceIntervalMs,
307
+ vacuumFullAboveBytes: options.vacuumFullAboveBytes,
308
+ vacuumFullQuietMs: options.vacuumFullQuietMs,
309
+ vacuumFullMaxDeferMs: options.vacuumFullMaxDeferMs,
310
+ gate: options.maintenanceGate,
311
+ now: options.now,
312
+ logger
313
+ });
314
+ class Durable extends Base {
315
+ maintenance = maintenance;
316
+ mod;
317
+ hostSyncs = fsync;
318
+ freshInit = false;
319
+ async init(pg, opts) {
320
+ const { emscriptenOpts: base } = await super.init(pg, opts);
321
+ const baseOpts = base;
322
+ const inner = baseOpts.instantiateWasm;
323
+ if (fsync && !inner) throw new Error("PGlite did not supply instantiateWasm");
324
+ return { emscriptenOpts: {
325
+ ...baseOpts,
326
+ onAbort: (what) => {
327
+ poisonAfterAbort(this.mod, what);
328
+ maintenance.stop();
329
+ onAbort?.(what);
330
+ },
331
+ preRun: [...baseOpts.preRun ?? [], (mod) => {
332
+ this.mod = mod;
333
+ if (!fsync) return;
334
+ mod.FS.filesystems.NODEFS.stream_ops.fsync = (stream) => this.fsyncStream(stream);
335
+ }],
336
+ instantiateWasm: fsync && inner ? (imports, done) => {
337
+ const original = imports.env.__syscall_fdatasync;
338
+ const replacement = (fd) => this.fdatasync(fd);
339
+ replacement.sig = original?.sig;
340
+ imports.env.__syscall_fdatasync = replacement;
341
+ return inner(imports, done);
342
+ } : inner
343
+ } };
344
+ }
345
+ async initialSyncFs() {
346
+ await super.initialSyncFs();
347
+ this.freshInit = fsync && !nodeFs.existsSync(path.join(resolvedDir, "PG_VERSION"));
348
+ if (this.freshInit) this.hostSyncs = false;
349
+ const baseBytes = await dirBytes(path.join(resolvedDir, "base"));
350
+ maintenance.start(this.pg, resolvedDir, baseBytes);
351
+ }
352
+ async syncToFs(relaxedDurability) {
353
+ maintenance.noteSync();
354
+ await super.syncToFs(relaxedDurability);
355
+ if (!this.freshInit) return;
356
+ this.freshInit = false;
357
+ this.hostSyncs = true;
358
+ syncTree(resolvedDir, hostFs);
359
+ }
360
+ async closeFs() {
361
+ try {
362
+ await maintenance.stop();
363
+ } finally {
364
+ await super.closeFs();
365
+ }
366
+ }
367
+ fsyncStream(stream) {
368
+ if (!this.hostSyncs) return 0;
369
+ if (typeof stream.nfd !== "number" || isReadOnly(stream)) return 0;
370
+ try {
371
+ hostFs.fsyncSync(stream.nfd);
372
+ } catch (err) {
373
+ logger?.warn(`DurableNodeFs fsync failed: ${String(err)}`);
374
+ return EIO;
375
+ }
376
+ return 0;
377
+ }
378
+ fdatasync(fd) {
379
+ if (!this.hostSyncs) return 0;
380
+ let stream;
381
+ try {
382
+ stream = this.mod.FS.getStreamChecked(fd);
383
+ } catch {
384
+ return -ERRNO_CODES.EBADF;
385
+ }
386
+ if (typeof stream.nfd !== "number" || isReadOnly(stream)) return 0;
387
+ try {
388
+ hostFs.fdatasyncSync(stream.nfd);
389
+ } catch (err) {
390
+ logger?.warn(`DurableNodeFs fdatasync failed: ${String(err)}`);
391
+ return -29;
392
+ }
393
+ return 0;
394
+ }
395
+ }
396
+ return new Durable(dataDir);
397
+ }
398
+ //#endregion
399
+ //#region src/pglite/worker/error-info.ts
400
+ const MAX_STACK_LENGTH = 8192;
401
+ const MAX_CAUSE_DEPTH = 8;
402
+ /** The string fields of PGlite's `DatabaseError`, plus the query PGlite attaches. */
403
+ const PG_ERROR_FIELDS = [
404
+ "code",
405
+ "severity",
406
+ "detail",
407
+ "hint",
408
+ "position",
409
+ "internalPosition",
410
+ "internalQuery",
411
+ "where",
412
+ "schema",
413
+ "table",
414
+ "column",
415
+ "dataType",
416
+ "constraint",
417
+ "file",
418
+ "line",
419
+ "routine",
420
+ "query"
421
+ ];
422
+ /** Flattens an error and its cause chain into a structured-clonable shape. */
423
+ function toPGliteErrorInfo(err, depth = 0) {
424
+ if (depth > MAX_CAUSE_DEPTH) return {
425
+ name: "Error",
426
+ message: "cause chain truncated",
427
+ fields: {}
428
+ };
429
+ if (!(err instanceof Error)) return {
430
+ name: "Error",
431
+ message: describe(err),
432
+ fields: {}
433
+ };
434
+ const info = {
435
+ name: err.name || "Error",
436
+ message: err.message,
437
+ fields: pgFieldsOf(err)
438
+ };
439
+ if (typeof err.stack === "string") info.stack = err.stack.slice(0, MAX_STACK_LENGTH);
440
+ if (err.cause !== void 0) info.cause = toPGliteErrorInfo(err.cause, depth + 1);
441
+ return info;
442
+ }
443
+ /** Rebuilds an `Error` carrying the original name, stack, Postgres fields and cause chain. */
444
+ function fromPGliteErrorInfo(info) {
445
+ const err = new Error(info.message);
446
+ define(err, "name", info.name);
447
+ if (info.stack !== void 0) err.stack = info.stack;
448
+ for (const [key, value] of Object.entries(info.fields)) define(err, key, value);
449
+ if (info.cause !== void 0) define(err, "cause", fromPGliteErrorInfo(info.cause));
450
+ return err;
451
+ }
452
+ function pgFieldsOf(err) {
453
+ const fields = {};
454
+ const record = err;
455
+ for (const key of PG_ERROR_FIELDS) {
456
+ const value = record[key];
457
+ if (typeof value === "string") fields[key] = value;
458
+ }
459
+ return fields;
460
+ }
461
+ function define(err, key, value) {
462
+ Object.defineProperty(err, key, {
463
+ value,
464
+ configurable: true,
465
+ writable: true,
466
+ enumerable: key !== "name" && key !== "cause"
467
+ });
468
+ }
469
+ function describe(value) {
470
+ if (typeof value === "string") return value;
471
+ if (value && typeof value === "object") {
472
+ const message = value.message;
473
+ if (typeof message === "string") return message;
474
+ }
475
+ if (value === void 0 || typeof value === "function") return String(value);
476
+ try {
477
+ return JSON.stringify(value);
478
+ } catch {
479
+ return "[unserializable]";
480
+ }
481
+ }
482
+ //#endregion
483
+ export { resolvePgliteMaintenance as a, DEFAULT_MAINTENANCE_INTERVAL_MS as c, DEFAULT_VACUUM_FULL_QUIET_MS as d, FORCED_VACUUM_FULL_MAX_DEFER_MS as f, resolvePgliteFsync as i, DEFAULT_VACUUM_FULL_ABOVE_BYTES as l, PGLITE_UTC_PARSERS as m, toPGliteErrorInfo as n, syncDirectory as o, PgliteMaintenance as p, createDurableNodeFs as r, syncTree as s, fromPGliteErrorInfo as t, DEFAULT_VACUUM_FULL_MAX_DEFER_MS as u };
484
+
485
+ //# sourceMappingURL=error-info-BaEL50f5.mjs.map
486
+ //# debugId=67ef2060-b4e7-5104-b280-60179cc2bdd7
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-info-BaEL50f5.mjs","sources":["../src/pglite/parsers.ts","../src/pglite/maintenance.ts","../src/pglite/sync-tree.ts","../src/pglite/durable-node-fs.ts","../src/pglite/worker/error-info.ts"],"sourcesContent":["// PGlite parses `timestamp` (no tz) columns as local time; read-model columns\n// store UTC, so parse them as UTC or values shift by the host's TZ offset.\nexport const PGLITE_UTC_PARSERS = {\n // 1114 = timestamp without time zone\n 1114: (value: string) => new Date(`${value.replace(\" \", \"T\")}Z`),\n} as const;\n","import { protocol, type PGlite } from \"@electric-sql/pglite\";\nimport { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\n\nexport const DEFAULT_MAINTENANCE_INTERVAL_MS = 5 * 60 * 1000;\nexport const DEFAULT_VACUUM_FULL_ABOVE_BYTES = 256 * 1024 * 1024;\nexport const DEFAULT_VACUUM_FULL_QUIET_MS = 60 * 1000;\n/**\n * How long a pending VACUUM FULL waits for a quiet store before it runs\n * anyway: by default it never does (0), because a forced rewrite of a large\n * store under load holds the only connection for minutes, every caller times\n * out, and the dir needs about twice its size in free space meanwhile.\n * `PH_PGLITE_VACUUM_FULL=forced` restores a deadline.\n */\nexport const DEFAULT_VACUUM_FULL_MAX_DEFER_MS = 0;\n/** The deadline `PH_PGLITE_VACUUM_FULL=forced` sets. */\nexport const FORCED_VACUUM_FULL_MAX_DEFER_MS = 30 * 60_000;\nconst MAINTENANCE_RETRY_MS = 1000;\n\nexport type MaintenanceOutcome =\n | \"vacuum\"\n | \"vacuum-full\"\n | \"idle\"\n | \"not-ready\"\n | \"in-transaction\"\n | \"failed\";\n\nexport interface MaintenanceLogger {\n warn(message: string): void;\n /** A finished VACUUM FULL is reported here; `warn` when absent. */\n info?(message: string): void;\n}\n\n/** Runs a maintenance pass in the owner's turn; see {@link MaintenanceOptions.gate}. */\nexport type MaintenanceGate = <T>(task: () => Promise<T>) => Promise<T>;\n\nexport interface MaintenanceOptions {\n /** VACUUM + CHECKPOINT cadence; PGlite has no autovacuum. Default 5 min; 0 disables. */\n intervalMs?: number;\n /** First pass runs VACUUM FULL when `base/` exceeds this at open. Default 256 MB; 0 disables. */\n vacuumFullAboveBytes?: number;\n /**\n * VACUUM FULL holds the store for minutes on a large dir, so it waits for a\n * store with no synced statement (no write, no catch-up) for this long,\n * counted from open; until then a pass runs plain VACUUM and keeps the\n * VACUUM FULL pending. Default 60 s; 0 runs it on the first pass.\n */\n vacuumFullQuietMs?: number;\n /**\n * The longest a pending VACUUM FULL waits for that quiet window, counted\n * from open; past it the next pass runs VACUUM FULL anyway. Default 0,\n * which waits for the quiet window however long it takes.\n */\n vacuumFullMaxDeferMs?: number;\n /**\n * Queues each pass with the store's other work, e.g. behind a worker's\n * pending requests, so a pass never starts ahead of a statement already\n * admitted. A pass still waiting here when the store closes is skipped.\n */\n gate?: MaintenanceGate;\n logger?: MaintenanceLogger;\n /** Clock for the quiet window; tests pass their own. */\n now?: () => number;\n}\n\nexport class PgliteMaintenance {\n private readonly intervalMs: number;\n private readonly vacuumFullAboveBytes: number;\n private readonly vacuumFullQuietMs: number;\n private readonly vacuumFullMaxDeferMs: number;\n private readonly gate?: MaintenanceGate;\n private readonly logger?: MaintenanceLogger;\n private readonly now: () => number;\n\n private pg?: PGlite;\n private label = \"\";\n private closing = false;\n private syncsSinceMaintenance = 0;\n private vacuumFullPending = false;\n private timer?: ReturnType<typeof setTimeout>;\n private inFlight?: Promise<MaintenanceOutcome>;\n private active = false;\n private deferralLogged = false;\n private lastSyncAt = 0;\n private openedAt = 0;\n\n constructor(options: MaintenanceOptions = {}) {\n this.intervalMs = Math.max(\n 0,\n options.intervalMs ?? DEFAULT_MAINTENANCE_INTERVAL_MS,\n );\n this.vacuumFullAboveBytes = Math.max(\n 0,\n options.vacuumFullAboveBytes ?? DEFAULT_VACUUM_FULL_ABOVE_BYTES,\n );\n this.vacuumFullQuietMs = Math.max(\n 0,\n options.vacuumFullQuietMs ?? DEFAULT_VACUUM_FULL_QUIET_MS,\n );\n this.vacuumFullMaxDeferMs = Math.max(\n 0,\n options.vacuumFullMaxDeferMs ?? DEFAULT_VACUUM_FULL_MAX_DEFER_MS,\n );\n this.gate = options.gate;\n this.logger = options.logger;\n this.now = options.now ?? Date.now;\n }\n\n get scheduled(): boolean {\n return this.timer !== undefined;\n }\n\n get running(): boolean {\n return this.inFlight !== undefined;\n }\n\n start(pg: PGlite, label: string, baseBytes: number): void {\n this.pg = pg;\n this.label = label;\n this.vacuumFullPending =\n this.vacuumFullAboveBytes > 0 && baseBytes > this.vacuumFullAboveBytes;\n this.lastSyncAt = this.now();\n this.openedAt = this.lastSyncAt;\n this.schedule(this.intervalMs);\n }\n\n noteSync(): void {\n this.syncsSinceMaintenance++;\n this.lastSyncAt = this.now();\n }\n\n /** Waits for a pass that has started; one still queued at the gate is left to skip itself. */\n async stop(): Promise<void> {\n this.closing = true;\n this.cancel();\n if (this.active) await this.inFlight;\n }\n\n async run(): Promise<MaintenanceOutcome> {\n if (this.gate) return this.gate(() => this.runNow());\n return this.runNow();\n }\n\n private async runNow(): Promise<MaintenanceOutcome> {\n this.active = true;\n try {\n return await this.pass();\n } finally {\n this.active = false;\n }\n }\n\n private async pass(): Promise<MaintenanceOutcome> {\n const pg = this.pg;\n if (this.closing || !pg?.ready) return \"not-ready\";\n // pg.close() does not take the query mutex; recheck before each statement.\n const isReady = (): boolean => pg.ready && !this.closing;\n const now = this.now();\n const overdue =\n this.vacuumFullMaxDeferMs > 0 &&\n now - this.openedAt >= this.vacuumFullMaxDeferMs;\n const full =\n this.vacuumFullPending &&\n (now - this.lastSyncAt >= this.vacuumFullQuietMs || overdue);\n if (this.vacuumFullPending && !full && !this.deferralLogged) {\n this.deferralLogged = true;\n this.logger?.warn(\n `DurableNodeFs: ${this.label}/base exceeds ${this.vacuumFullAboveBytes} bytes; VACUUM FULL waits until the store has had no writes for ${this.vacuumFullQuietMs} ms${this.vacuumFullMaxDeferMs > 0 ? `, or at most ${this.vacuumFullMaxDeferMs} ms from open` : \"\"}`,\n );\n }\n if (!full && this.syncsSinceMaintenance === 0) {\n return \"idle\";\n }\n const baseDir = path.join(this.label, \"base\");\n const bytesBefore = full ? await dirBytes(baseDir) : 0;\n const startedAt = this.now();\n let outcome: MaintenanceOutcome;\n try {\n outcome = await pg._runExclusiveQuery(async () => {\n // isInTransaction() misses START TRANSACTION; ReadyForQuery status does not.\n if (!isReady()) return \"not-ready\";\n const { messages } = await pg.execProtocol(\n protocol.serialize.query(\"\"),\n { syncToFs: false },\n );\n if (transactionStatus(messages) !== \"I\") return \"in-transaction\";\n if (full) {\n this.logger?.warn(\n `DurableNodeFs: ${this.label}/base exceeds ${this.vacuumFullAboveBytes} bytes; running VACUUM FULL`,\n );\n }\n for (const statement of [\n full ? \"VACUUM FULL\" : \"VACUUM\",\n \"CHECKPOINT\",\n ]) {\n if (!isReady()) return \"not-ready\";\n await pg.execProtocol(protocol.serialize.query(statement), {\n syncToFs: false,\n });\n }\n return full ? \"vacuum-full\" : \"vacuum\";\n });\n } catch (err) {\n this.logger?.warn(\n `DurableNodeFs maintenance failed: ${errorMessage(err)}`,\n );\n return \"failed\";\n }\n if (outcome !== \"vacuum\" && outcome !== \"vacuum-full\") return outcome;\n this.syncsSinceMaintenance = 0;\n if (full) {\n this.vacuumFullPending = false;\n const bytesAfter = await dirBytes(baseDir);\n const message = `DurableNodeFs: ${this.label}/base VACUUM FULL finished in ${this.now() - startedAt} ms; ${bytesBefore} -> ${bytesAfter} bytes`;\n if (this.logger?.info) this.logger.info(message);\n else this.logger?.warn(message);\n }\n return outcome;\n }\n\n private schedule(delayMs: number): void {\n if (this.intervalMs === 0 || this.closing) return;\n this.timer = setTimeout(() => {\n this.timer = undefined;\n this.inFlight = this.run()\n .then((outcome) => {\n this.schedule(\n outcome === \"in-transaction\"\n ? Math.min(MAINTENANCE_RETRY_MS, this.intervalMs)\n : this.intervalMs,\n );\n return outcome;\n })\n .finally(() => {\n this.inFlight = undefined;\n });\n }, delayMs);\n this.timer.unref();\n }\n\n private cancel(): void {\n if (!this.timer) return;\n clearTimeout(this.timer);\n this.timer = undefined;\n }\n}\n\n/** Total size of the regular files under `dir`; 0 when `dir` is missing. */\nexport async function dirBytes(dir: string): Promise<number> {\n let entries;\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return 0;\n throw err;\n }\n let total = 0;\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n total += await dirBytes(full);\n } else if (entry.isFile()) {\n total += (await fs.stat(full)).size;\n }\n }\n return total;\n}\n\nfunction transactionStatus(messages: readonly { name: string }[]): unknown {\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i];\n if (m.name === \"readyForQuery\") return (m as { status?: unknown }).status;\n }\n return undefined;\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","import nodeFs from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface SyncTreeHostFs {\n fsyncSync(fd: number): void;\n}\n\nexport interface SyncTreeResult {\n files: number;\n dirs: number;\n}\n\n/** One pass over a finished tree; interleaving fsync with writes costs seconds. */\nexport function syncTree(\n root: string,\n hostFs: SyncTreeHostFs = nodeFs,\n): SyncTreeResult {\n const result: SyncTreeResult = { files: 0, dirs: 0 };\n const pending = [path.resolve(root)];\n while (pending.length > 0) {\n const dir = pending.pop()!;\n for (const entry of nodeFs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n pending.push(full);\n } else if (entry.isFile()) {\n syncFile(full, hostFs);\n result.files++;\n }\n }\n syncDirectory(dir, hostFs);\n result.dirs++;\n }\n return result;\n}\n\n// Windows refuses FlushFileBuffers on a read-only handle (EPERM).\nfunction syncFile(file: string, hostFs: SyncTreeHostFs): void {\n const fd = nodeFs.openSync(file, \"r+\");\n try {\n hostFs.fsyncSync(fd);\n } finally {\n nodeFs.closeSync(fd);\n }\n}\n\n/** fsyncs a directory's entries; false where the platform refuses (Windows). */\nexport function syncDirectory(\n dir: string,\n hostFs: SyncTreeHostFs = nodeFs,\n): boolean {\n let fd: number;\n try {\n fd = nodeFs.openSync(dir, \"r\");\n } catch {\n return false;\n }\n try {\n hostFs.fsyncSync(fd);\n return true;\n } catch {\n return false;\n } finally {\n nodeFs.closeSync(fd);\n }\n}\n","import type { PGlite } from \"@electric-sql/pglite\";\nimport { ERRNO_CODES } from \"@electric-sql/pglite/basefs\";\nimport type { NodeFS } from \"@electric-sql/pglite/nodefs\";\nimport nodeFs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n dirBytes,\n FORCED_VACUUM_FULL_MAX_DEFER_MS,\n PgliteMaintenance,\n type MaintenanceGate,\n} from \"./maintenance.js\";\nimport { syncTree } from \"./sync-tree.js\";\n\nexport type NodeFsClass = typeof NodeFS;\n\n// Emscripten/WASI errno; the basefs ERRNO_CODES export lacks it.\nconst EIO = 29;\n\nexport interface DurableNodeFsOptions {\n /** Default true; `PH_PGLITE_FSYNC=0` turns it off (power-loss durability off). */\n fsync?: boolean;\n /** Default 5 min; 0 disables. */\n maintenanceIntervalMs?: number;\n /** `base/` size at open; default 256 MB; 0 disables. */\n vacuumFullAboveBytes?: number;\n /** See `MaintenanceOptions.vacuumFullQuietMs`; default 60 s. */\n vacuumFullQuietMs?: number;\n /** See `MaintenanceOptions.vacuumFullMaxDeferMs`; default 0 (quiet window only). */\n vacuumFullMaxDeferMs?: number;\n /** See `MaintenanceOptions.gate`. */\n maintenanceGate?: MaintenanceGate;\n /** Clock for the maintenance quiet window; tests pass their own. */\n now?: () => number;\n logger?: { warn(message: string): void; info?(message: string): void };\n /** Emscripten abort (a Postgres PANIC, e.g. ENOSPC on WAL). */\n onAbort?: (what: unknown) => void;\n hostFs?: Pick<typeof nodeFs, \"fsyncSync\" | \"fdatasyncSync\">;\n}\n\nexport type DurableNodeFs = InstanceType<NodeFsClass> & {\n readonly maintenance: PgliteMaintenance;\n};\n\nexport function resolvePgliteFsync(\n env: Record<string, string | undefined>,\n): boolean {\n return env.PH_PGLITE_FSYNC !== \"0\";\n}\n\n/** `PH_PGLITE_VACUUM_FULL`: when an oversized store's one-time VACUUM FULL may run. */\nexport type PgliteVacuumFullMode = \"off\" | \"quiet\" | \"forced\";\n\nconst VACUUM_FULL_MODES: readonly PgliteVacuumFullMode[] = [\n \"off\",\n \"quiet\",\n \"forced\",\n];\n\n/** The VACUUM FULL settings an environment selects; see {@link resolvePgliteMaintenance}. */\nexport type PgliteMaintenanceSettings = Pick<\n DurableNodeFsOptions,\n \"vacuumFullAboveBytes\" | \"vacuumFullQuietMs\" | \"vacuumFullMaxDeferMs\"\n>;\n\n/**\n * Reads the VACUUM FULL knobs. `PH_PGLITE_VACUUM_FULL` is `off` (the\n * default: never), `quiet` (only after the quiet window, however long that\n * takes) or `forced` (a deadline of 30 min from open, after which it runs\n * under load). Off is the default because a full rewrite of a large store\n * needs about twice its size in free disk and holds the only connection for\n * minutes, and on a store that is live data rather than bloat it reclaims\n * nothing; a quiet window of a minute arrives naturally between jobs, so\n * `quiet` is an opt-in for stores known to be small or bloated.\n * `PH_PGLITE_VACUUM_FULL_ABOVE_MB` sets the size that makes a store\n * eligible; `PH_PGLITE_VACUUM_FULL_QUIET_MS` and\n * `PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS` override the mode's timings. A value\n * that is not a non-negative number is left to the default; an unknown mode\n * throws, since silently running a rewrite is what this guards against.\n */\nexport function resolvePgliteMaintenance(\n env: Record<string, string | undefined>,\n): PgliteMaintenanceSettings {\n const rawMode = env.PH_PGLITE_VACUUM_FULL?.trim().toLowerCase() || \"off\";\n if (!isVacuumFullMode(rawMode)) {\n throw new Error(\n `Invalid PH_PGLITE_VACUUM_FULL: ${String(env.PH_PGLITE_VACUUM_FULL)}. Expected \"off\", \"quiet\" or \"forced\".`,\n );\n }\n const mode: PgliteVacuumFullMode = rawMode;\n const settings: PgliteMaintenanceSettings = {};\n if (mode === \"off\") settings.vacuumFullAboveBytes = 0;\n if (mode === \"forced\") {\n settings.vacuumFullMaxDeferMs = FORCED_VACUUM_FULL_MAX_DEFER_MS;\n }\n const aboveMb = nonNegative(env.PH_PGLITE_VACUUM_FULL_ABOVE_MB);\n if (aboveMb !== undefined && mode !== \"off\") {\n settings.vacuumFullAboveBytes = aboveMb * 1024 * 1024;\n }\n const quiet = nonNegative(env.PH_PGLITE_VACUUM_FULL_QUIET_MS);\n if (quiet !== undefined) settings.vacuumFullQuietMs = quiet;\n const maxDefer = nonNegative(env.PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS);\n if (maxDefer !== undefined) settings.vacuumFullMaxDeferMs = maxDefer;\n return settings;\n}\n\nfunction isVacuumFullMode(value: string): value is PgliteVacuumFullMode {\n return (VACUUM_FULL_MODES as readonly string[]).includes(value);\n}\n\nfunction nonNegative(value: string | undefined): number | undefined {\n if (value === undefined || value.trim() === \"\") return undefined;\n const parsed = Number(value);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;\n}\n\ninterface NodeFsStream {\n nfd?: number;\n /** Emscripten open flags; NODEFS opens the host fd with the same access mode. */\n flags?: number;\n}\n\n// Only PGlite's pg_flush_data (fsync on pre_sync_fname's O_RDONLY fd) syncs a\n// read-only fd: the result is discarded and an O_RDWR fsync of the same file\n// follows. Skipped, as Windows refuses FlushFileBuffers without write access.\nfunction isReadOnly(stream: NodeFsStream): boolean {\n return stream.flags !== undefined && (stream.flags & 3) === 0;\n}\n\ninterface EmscriptenFs {\n filesystems: { NODEFS: { stream_ops: Record<string, unknown> } };\n getStreamChecked(fd: number): NodeFsStream;\n quit(): void;\n}\n\ninterface EmscriptenMod {\n FS: EmscriptenFs;\n [wasmExport: string]: unknown;\n}\n\n// PGlite re-enters wasm from its own error handler after a query fails; on an\n// aborted runtime that spins forever, so every entry point is cut off first.\nconst WASM_ENTRY_POINTS = [\n \"_interactive_one\",\n \"_interactive_write\",\n \"_pgl_backend\",\n \"_pgl_initdb\",\n \"_pgl_shutdown\",\n];\n\nfunction poisonAfterAbort(mod: EmscriptenMod | undefined, what: unknown): void {\n if (!mod) return;\n const message = `PGlite aborted: ${String(what) || \"wasm runtime abort\"}`;\n for (const name of WASM_ENTRY_POINTS) {\n if (typeof mod[name] !== \"function\") continue;\n mod[name] = () => {\n throw new Error(message);\n };\n }\n // pg.close() rejects before closeFs(), so release the host fds here.\n try {\n mod.FS.quit();\n } catch {\n // already quit by an earlier abort\n }\n}\n\ntype SyscallImport = ((fd: number) => number) & { sig?: string };\n\ninterface WasmImports {\n env: Record<string, unknown> & { __syscall_fdatasync?: SyscallImport };\n}\n\ntype InstantiateWasm = (\n imports: WasmImports,\n done: (instance: WebAssembly.Instance, module: WebAssembly.Module) => void,\n) => unknown;\n\ninterface EmscriptenOpts {\n preRun?: ((mod: EmscriptenMod) => void)[];\n instantiateWasm?: InstantiateWasm;\n onAbort?: (what: unknown) => void;\n}\n\ntype InitOpts = Parameters<InstanceType<NodeFsClass>[\"init\"]>[1];\n\n/** Built over the passed-in class so PG16 dirs on `pglite-legacy-02` get the same behaviour. */\nexport function createDurableNodeFs(\n Base: NodeFsClass,\n dataDir: string,\n options: DurableNodeFsOptions = {},\n): DurableNodeFs {\n const fsync = options.fsync ?? true;\n const hostFs = options.hostFs ?? nodeFs;\n const logger = options.logger;\n const onAbort = options.onAbort;\n const resolvedDir = path.resolve(dataDir);\n const maintenance = new PgliteMaintenance({\n intervalMs: options.maintenanceIntervalMs,\n vacuumFullAboveBytes: options.vacuumFullAboveBytes,\n vacuumFullQuietMs: options.vacuumFullQuietMs,\n vacuumFullMaxDeferMs: options.vacuumFullMaxDeferMs,\n gate: options.maintenanceGate,\n now: options.now,\n logger,\n });\n\n class Durable extends Base {\n readonly maintenance = maintenance;\n private mod?: EmscriptenMod;\n // Off from initialSyncFs of a fresh dir until PGlite's first syncToFs.\n private hostSyncs = fsync;\n private freshInit = false;\n\n override async init(\n pg: PGlite,\n opts: InitOpts,\n ): Promise<{ emscriptenOpts: InitOpts }> {\n const { emscriptenOpts: base } = await super.init(pg, opts);\n const baseOpts = base as EmscriptenOpts;\n const inner = baseOpts.instantiateWasm;\n if (fsync && !inner) {\n throw new Error(\"PGlite did not supply instantiateWasm\");\n }\n const emscriptenOpts: EmscriptenOpts = {\n ...baseOpts,\n onAbort: (what) => {\n poisonAfterAbort(this.mod, what);\n void maintenance.stop();\n onAbort?.(what);\n },\n preRun: [\n ...(baseOpts.preRun ?? []),\n (mod) => {\n this.mod = mod;\n if (!fsync) return;\n mod.FS.filesystems.NODEFS.stream_ops.fsync = (\n stream: NodeFsStream,\n ) => this.fsyncStream(stream);\n },\n ],\n instantiateWasm:\n fsync && inner\n ? (imports, done) => {\n const original = imports.env.__syscall_fdatasync;\n const replacement: SyscallImport = (fd) => this.fdatasync(fd);\n replacement.sig = original?.sig;\n imports.env.__syscall_fdatasync = replacement;\n return inner(imports, done);\n }\n : inner,\n };\n return { emscriptenOpts: emscriptenOpts as InitOpts };\n }\n\n override async initialSyncFs(): Promise<void> {\n await super.initialSyncFs();\n // No PG_VERSION: initdb runs next; PGlite calls syncToFs once before ready.\n this.freshInit =\n fsync && !nodeFs.existsSync(path.join(resolvedDir, \"PG_VERSION\"));\n if (this.freshInit) this.hostSyncs = false;\n const baseBytes = await dirBytes(path.join(resolvedDir, \"base\"));\n maintenance.start(this.pg!, resolvedDir, baseBytes);\n }\n\n override async syncToFs(relaxedDurability?: boolean): Promise<void> {\n maintenance.noteSync();\n await super.syncToFs(relaxedDurability);\n if (!this.freshInit) return;\n this.freshInit = false;\n this.hostSyncs = true;\n syncTree(resolvedDir, hostFs);\n }\n\n override async closeFs(): Promise<void> {\n try {\n await maintenance.stop();\n } finally {\n await super.closeFs();\n }\n }\n\n // WASI fd_sync convention: 0 or a positive errno.\n private fsyncStream(stream: NodeFsStream): number {\n if (!this.hostSyncs) return 0;\n // Directory streams carry no host fd; only regular files do.\n if (typeof stream.nfd !== \"number\" || isReadOnly(stream)) return 0;\n try {\n hostFs.fsyncSync(stream.nfd);\n } catch (err) {\n logger?.warn(`DurableNodeFs fsync failed: ${String(err)}`);\n return EIO;\n }\n return 0;\n }\n\n // Linux syscall convention: 0 or a negative errno.\n private fdatasync(fd: number): number {\n if (!this.hostSyncs) return 0;\n let stream: NodeFsStream;\n try {\n stream = this.mod!.FS.getStreamChecked(fd);\n } catch {\n return -ERRNO_CODES.EBADF;\n }\n if (typeof stream.nfd !== \"number\" || isReadOnly(stream)) return 0;\n try {\n hostFs.fdatasyncSync(stream.nfd);\n } catch (err) {\n logger?.warn(`DurableNodeFs fdatasync failed: ${String(err)}`);\n return -EIO;\n }\n return 0;\n }\n }\n\n return new Durable(dataDir) as DurableNodeFs;\n}\n","import type { PGliteErrorInfo } from \"./protocol.js\";\n\nconst MAX_STACK_LENGTH = 8 * 1024;\nconst MAX_CAUSE_DEPTH = 8;\n\n/** The string fields of PGlite's `DatabaseError`, plus the query PGlite attaches. */\nexport const PG_ERROR_FIELDS = [\n \"code\",\n \"severity\",\n \"detail\",\n \"hint\",\n \"position\",\n \"internalPosition\",\n \"internalQuery\",\n \"where\",\n \"schema\",\n \"table\",\n \"column\",\n \"dataType\",\n \"constraint\",\n \"file\",\n \"line\",\n \"routine\",\n \"query\",\n] as const;\n\n/** Flattens an error and its cause chain into a structured-clonable shape. */\nexport function toPGliteErrorInfo(err: unknown, depth = 0): PGliteErrorInfo {\n if (depth > MAX_CAUSE_DEPTH) {\n return { name: \"Error\", message: \"cause chain truncated\", fields: {} };\n }\n if (!(err instanceof Error)) {\n return { name: \"Error\", message: describe(err), fields: {} };\n }\n const info: PGliteErrorInfo = {\n name: err.name || \"Error\",\n message: err.message,\n fields: pgFieldsOf(err),\n };\n if (typeof err.stack === \"string\") {\n info.stack = err.stack.slice(0, MAX_STACK_LENGTH);\n }\n if (err.cause !== undefined) {\n info.cause = toPGliteErrorInfo(err.cause, depth + 1);\n }\n return info;\n}\n\n/** Rebuilds an `Error` carrying the original name, stack, Postgres fields and cause chain. */\nexport function fromPGliteErrorInfo(info: PGliteErrorInfo): Error {\n const err = new Error(info.message);\n define(err, \"name\", info.name);\n if (info.stack !== undefined) {\n err.stack = info.stack;\n }\n for (const [key, value] of Object.entries(info.fields)) {\n define(err, key, value);\n }\n if (info.cause !== undefined) {\n define(err, \"cause\", fromPGliteErrorInfo(info.cause));\n }\n return err;\n}\n\nfunction pgFieldsOf(err: Error): Record<string, string> {\n const fields: Record<string, string> = {};\n const record = err as unknown as Record<string, unknown>;\n for (const key of PG_ERROR_FIELDS) {\n const value = record[key];\n if (typeof value === \"string\") {\n fields[key] = value;\n }\n }\n return fields;\n}\n\nfunction define(err: Error, key: string, value: unknown): void {\n Object.defineProperty(err, key, {\n value,\n configurable: true,\n writable: true,\n enumerable: key !== \"name\" && key !== \"cause\",\n });\n}\n\nfunction describe(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n if (value && typeof value === \"object\") {\n const message = (value as { message?: unknown }).message;\n if (typeof message === \"string\") {\n return message;\n }\n }\n if (value === undefined || typeof value === \"function\") {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return \"[unserializable]\";\n }\n}\n"],"names":["fs"],"mappings":";;;;;;;AAEA,MAAa,qBAAqB,EAEhC,OAAO,0BAAkB,IAAI,KAAK,GAAG,MAAM,QAAQ,KAAK,GAAG,EAAE,EAAE,EACjE;;;ACDA,MAAa,kCAAkC;AAC/C,MAAa,kCAAkC;AAC/C,MAAa,+BAA+B;;;;;;;;AAQ5C,MAAa,mCAAmC;;AAEhD,MAAa,kCAAkC;AAC/C,MAAM,uBAAuB;AAgD7B,IAAa,oBAAb,MAA+B;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA,QAAgB;CAChB,UAAkB;CAClB,wBAAgC;CAChC,oBAA4B;CAC5B;CACA;CACA,SAAiB;CACjB,iBAAyB;CACzB,aAAqB;CACrB,WAAmB;CAEnB,YAAY,UAA8B,CAAC,GAAG;EAC5C,KAAK,aAAa,KAAK,IACrB,GACA,QAAQ,cAAA,GACV;EACA,KAAK,uBAAuB,KAAK,IAC/B,GACA,QAAQ,wBAAA,SACV;EACA,KAAK,oBAAoB,KAAK,IAC5B,GACA,QAAQ,qBAAA,GACV;EACA,KAAK,uBAAuB,KAAK,IAC/B,GACA,QAAQ,wBAAA,CACV;EACA,KAAK,OAAO,QAAQ;EACpB,KAAK,SAAS,QAAQ;EACtB,KAAK,MAAM,QAAQ,OAAO,KAAK;CACjC;CAEA,IAAI,YAAqB;EACvB,OAAO,KAAK,UAAU,KAAA;CACxB;CAEA,IAAI,UAAmB;EACrB,OAAO,KAAK,aAAa,KAAA;CAC3B;CAEA,MAAM,IAAY,OAAe,WAAyB;EACxD,KAAK,KAAK;EACV,KAAK,QAAQ;EACb,KAAK,oBACH,KAAK,uBAAuB,KAAK,YAAY,KAAK;EACpD,KA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