@powerhousedao/reactor-api 6.2.3-dev.1 → 6.2.3-dev.100

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 (65) hide show
  1. package/README.md +7 -2
  2. package/dist/{adapter-gateway-apollo-DdamNLPT.mjs → adapter-gateway-apollo-D-EdZ4e-.mjs} +23 -24
  3. package/dist/adapter-gateway-apollo-D-EdZ4e-.mjs.map +1 -0
  4. package/dist/{adapter-gateway-mercurius-CLmTtNJC.mjs → adapter-gateway-mercurius-CdxLge5p.mjs} +4 -11
  5. package/dist/adapter-gateway-mercurius-CdxLge5p.mjs.map +1 -0
  6. package/dist/{adapter-http-express-54gdI9bu.mjs → adapter-http-express-78KD77cI.mjs} +11 -11
  7. package/dist/adapter-http-express-78KD77cI.mjs.map +1 -0
  8. package/dist/{adapter-http-fastify-DmccBVOe.mjs → adapter-http-fastify-Dk7aT_xw.mjs} +14 -13
  9. package/dist/adapter-http-fastify-Dk7aT_xw.mjs.map +1 -0
  10. package/dist/base-document-models-caJpqTLw.mjs +2083 -0
  11. package/dist/base-document-models-caJpqTLw.mjs.map +1 -0
  12. package/dist/create-schema-BCArFBv9.d.mts +167 -0
  13. package/dist/create-schema-BCArFBv9.d.mts.map +1 -0
  14. package/dist/error-info-Cr6oQACe.mjs +601 -0
  15. package/dist/error-info-Cr6oQACe.mjs.map +1 -0
  16. package/dist/index.d.mts +3410 -1028
  17. package/dist/index.d.mts.map +1 -1
  18. package/dist/index.mjs +7549 -2724
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/package-subgraph-check-BxKx9kcQ.mjs +138 -0
  21. package/dist/package-subgraph-check-BxKx9kcQ.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-CcX2YT-l.mjs +744 -0
  25. package/dist/pglite-node-CcX2YT-l.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 +208 -88
  40. package/dist/src/packages/vite-loader.mjs.map +1 -1
  41. package/dist/src/pglite/pglite-node.d.mts +434 -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 +298 -0
  46. package/dist/src/pglite/worker/entry.mjs.map +1 -0
  47. package/dist/subgraph-extraction-C_hFvSaS.mjs +1884 -0
  48. package/dist/subgraph-extraction-C_hFvSaS.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-Bz_xjf8j.d.mts +105 -0
  52. package/dist/types-Bz_xjf8j.d.mts.map +1 -0
  53. package/package.json +42 -26
  54. package/dist/adapter-gateway-apollo-DdamNLPT.mjs.map +0 -1
  55. package/dist/adapter-gateway-mercurius-CLmTtNJC.mjs.map +0 -1
  56. package/dist/adapter-http-express-54gdI9bu.mjs.map +0 -1
  57. package/dist/adapter-http-fastify-DmccBVOe.mjs.map +0 -1
  58. package/dist/path-normalize-DWWFLiy6.mjs +0 -23
  59. package/dist/path-normalize-DWWFLiy6.mjs.map +0 -1
  60. package/dist/types-Bz2niABC.d.mts +0 -48
  61. package/dist/types-Bz2niABC.d.mts.map +0 -1
  62. package/dist/utils-XWVecaNn.mjs +0 -653
  63. package/dist/utils-XWVecaNn.mjs.map +0 -1
  64. package/dist/websocket-DncAB9XK.mjs +0 -18
  65. package/dist/websocket-DncAB9XK.mjs.map +0 -1
@@ -0,0 +1,601 @@
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]="32154524-8414-5e0c-bd0b-eb61f765c647")}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
+ /**
26
+ * A table rewrite waits for this long a gap between the store's statements.
27
+ * Short, because PGlite syncs after every statement and an idle reactor still
28
+ * reads every 2 s (catch-up, sync polls), so a longer gap never comes.
29
+ */
30
+ const DEFAULT_REWRITE_QUIET_MS = 1e3;
31
+ /** How long a table rewrite waits for that gap before it reports the store busy. */
32
+ const DEFAULT_REWRITE_MAX_WAIT_MS = 9e5;
33
+ const REWRITE_POLL_MS = 250;
34
+ var PgliteMaintenance = class {
35
+ intervalMs;
36
+ vacuumFullAboveBytes;
37
+ vacuumFullQuietMs;
38
+ vacuumFullMaxDeferMs;
39
+ gate;
40
+ logger;
41
+ now;
42
+ rewriteQuietMs;
43
+ rewriteMaxWaitMs;
44
+ pg;
45
+ label = "";
46
+ closing = false;
47
+ syncsSinceMaintenance = 0;
48
+ vacuumFullPending = false;
49
+ timer;
50
+ inFlight;
51
+ active = false;
52
+ deferralLogged = false;
53
+ lastSyncAt = 0;
54
+ openedAt = 0;
55
+ rewriting;
56
+ constructor(options = {}) {
57
+ this.intervalMs = Math.max(0, options.intervalMs ?? 3e5);
58
+ this.vacuumFullAboveBytes = Math.max(0, options.vacuumFullAboveBytes ?? 268435456);
59
+ this.vacuumFullQuietMs = Math.max(0, options.vacuumFullQuietMs ?? 6e4);
60
+ this.vacuumFullMaxDeferMs = Math.max(0, options.vacuumFullMaxDeferMs ?? 0);
61
+ this.gate = options.gate;
62
+ this.logger = options.logger;
63
+ this.now = options.now ?? Date.now;
64
+ this.rewriteQuietMs = options.rewriteQuietMs ?? 1e3;
65
+ this.rewriteMaxWaitMs = options.rewriteMaxWaitMs ?? 9e5;
66
+ }
67
+ get scheduled() {
68
+ return this.timer !== void 0;
69
+ }
70
+ get running() {
71
+ return this.inFlight !== void 0;
72
+ }
73
+ start(pg, label, baseBytes) {
74
+ this.pg = pg;
75
+ this.label = label;
76
+ this.vacuumFullPending = this.vacuumFullAboveBytes > 0 && baseBytes > this.vacuumFullAboveBytes;
77
+ this.lastSyncAt = this.now();
78
+ this.openedAt = this.lastSyncAt;
79
+ this.schedule(this.intervalMs);
80
+ }
81
+ noteSync() {
82
+ this.syncsSinceMaintenance++;
83
+ this.lastSyncAt = this.now();
84
+ }
85
+ /** Waits for a pass that has started; one still queued at the gate is left to skip itself. */
86
+ async stop() {
87
+ this.closing = true;
88
+ this.cancel();
89
+ if (this.active) await this.inFlight;
90
+ await this.rewriting;
91
+ }
92
+ async run() {
93
+ if (this.gate) return this.gate(() => this.runNow());
94
+ return this.runNow();
95
+ }
96
+ /**
97
+ * Rewrites one table with VACUUM FULL and a CHECKPOINT, in the turn of the
98
+ * store's other work, never the whole store. Waits for a gap in the store's
99
+ * statements first; nothing else runs on it while the table is rewritten.
100
+ */
101
+ async rewriteTable(request) {
102
+ const shortOfDisk = await this.diskShortage(request.requiredFreeBytes);
103
+ if (shortOfDisk !== void 0) return {
104
+ outcome: "refused",
105
+ reason: shortOfDisk
106
+ };
107
+ const relation = `${quoteIdentifier(request.schema)}.${quoteIdentifier(request.table)}`;
108
+ const deadline = this.now() + this.rewriteMaxWaitMs;
109
+ for (;;) {
110
+ if (this.closing || !this.pg?.ready) return {
111
+ outcome: "refused",
112
+ reason: "the store is closing"
113
+ };
114
+ if (this.now() - this.lastSyncAt >= this.rewriteQuietMs) {
115
+ const attempt = this.gate ? this.gate(() => this.rewriteNow(relation)) : this.rewriteNow(relation);
116
+ this.rewriting = attempt.catch(() => void 0);
117
+ const result = await attempt;
118
+ this.rewriting = void 0;
119
+ if (result !== void 0) return result;
120
+ }
121
+ if (this.now() >= deadline) return {
122
+ outcome: "busy",
123
+ reason: `The store had no gap of ${this.rewriteQuietMs} ms between statements in ${this.rewriteMaxWaitMs} ms, so ${relation} was not rewritten. Try again in a quieter moment.`
124
+ };
125
+ await new Promise((resolve) => {
126
+ setTimeout(resolve, REWRITE_POLL_MS);
127
+ });
128
+ }
129
+ }
130
+ async runNow() {
131
+ this.active = true;
132
+ try {
133
+ return await this.pass();
134
+ } finally {
135
+ this.active = false;
136
+ }
137
+ }
138
+ async pass() {
139
+ const pg = this.pg;
140
+ if (this.closing || !pg?.ready) return "not-ready";
141
+ const isReady = () => pg.ready && !this.closing;
142
+ const now = this.now();
143
+ const overdue = this.vacuumFullMaxDeferMs > 0 && now - this.openedAt >= this.vacuumFullMaxDeferMs;
144
+ const full = this.vacuumFullPending && (now - this.lastSyncAt >= this.vacuumFullQuietMs || overdue);
145
+ if (this.vacuumFullPending && !full && !this.deferralLogged) {
146
+ this.deferralLogged = true;
147
+ 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` : ""}`);
148
+ }
149
+ if (!full && this.syncsSinceMaintenance === 0) return "idle";
150
+ const baseDir = path.join(this.label, "base");
151
+ const bytesBefore = full ? await dirBytes(baseDir) : 0;
152
+ const startedAt = this.now();
153
+ let outcome;
154
+ try {
155
+ outcome = await pg._runExclusiveQuery(async () => {
156
+ if (!isReady()) return "not-ready";
157
+ const { messages } = await pg.execProtocol(protocol.serialize.query(""), { syncToFs: false });
158
+ if (transactionStatus(messages) !== "I") return "in-transaction";
159
+ if (full) this.logger?.warn(`DurableNodeFs: ${this.label}/base exceeds ${this.vacuumFullAboveBytes} bytes; running VACUUM FULL`);
160
+ for (const statement of [full ? "VACUUM FULL" : "VACUUM", "CHECKPOINT"]) {
161
+ if (!isReady()) return "not-ready";
162
+ await pg.execProtocol(protocol.serialize.query(statement), { syncToFs: false });
163
+ }
164
+ return full ? "vacuum-full" : "vacuum";
165
+ });
166
+ } catch (err) {
167
+ this.logger?.warn(`DurableNodeFs maintenance failed: ${errorMessage(err)}`);
168
+ return "failed";
169
+ }
170
+ if (outcome !== "vacuum" && outcome !== "vacuum-full") return outcome;
171
+ this.syncsSinceMaintenance = 0;
172
+ if (full) {
173
+ this.vacuumFullPending = false;
174
+ const bytesAfter = await dirBytes(baseDir);
175
+ const message = `DurableNodeFs: ${this.label}/base VACUUM FULL finished in ${this.now() - startedAt} ms; ${bytesBefore} -> ${bytesAfter} bytes`;
176
+ if (this.logger?.info) this.logger.info(message);
177
+ else this.logger?.warn(message);
178
+ }
179
+ return outcome;
180
+ }
181
+ /** Undefined when a transaction is open, so the caller waits and tries again. */
182
+ async rewriteNow(relation) {
183
+ const pg = this.pg;
184
+ if (this.closing || !pg?.ready) return {
185
+ outcome: "refused",
186
+ reason: "the store is closing"
187
+ };
188
+ const isReady = () => pg.ready && !this.closing;
189
+ const startedAt = this.now();
190
+ const bytesBefore = await dirBytes(path.join(this.label, "base"));
191
+ let completed;
192
+ try {
193
+ completed = await pg._runExclusiveQuery(async () => {
194
+ if (!isReady()) return false;
195
+ const { messages } = await pg.execProtocol(protocol.serialize.query(""), { syncToFs: false });
196
+ if (transactionStatus(messages) !== "I") return void 0;
197
+ this.logger?.warn(`DurableNodeFs: ${this.label}: running VACUUM FULL ${relation}`);
198
+ for (const statement of [`VACUUM FULL ${relation}`, "CHECKPOINT"]) {
199
+ if (!isReady()) return false;
200
+ await pg.execProtocol(protocol.serialize.query(statement), { syncToFs: false });
201
+ }
202
+ return true;
203
+ });
204
+ } catch (err) {
205
+ return {
206
+ outcome: "refused",
207
+ reason: `VACUUM FULL ${relation} failed: ${errorMessage(err)}`
208
+ };
209
+ }
210
+ if (completed === void 0) return void 0;
211
+ if (!completed) return {
212
+ outcome: "refused",
213
+ reason: "the store is closing"
214
+ };
215
+ const durationMs = this.now() - startedAt;
216
+ const bytesAfter = await dirBytes(path.join(this.label, "base"));
217
+ const message = `DurableNodeFs: ${this.label}/base VACUUM FULL ${relation} finished in ${durationMs} ms; ${bytesBefore} -> ${bytesAfter} bytes`;
218
+ if (this.logger?.info) this.logger.info(message);
219
+ else this.logger?.warn(message);
220
+ return {
221
+ outcome: "done",
222
+ durationMs
223
+ };
224
+ }
225
+ /** Why the disk cannot hold the rewrite; undefined when it can or nobody can tell. */
226
+ async diskShortage(requiredFreeBytes) {
227
+ if (requiredFreeBytes <= 0 || !this.label) return void 0;
228
+ let freeBytes;
229
+ try {
230
+ const stats = await promises.statfs(this.label);
231
+ freeBytes = stats.bavail * stats.bsize;
232
+ } catch {
233
+ return;
234
+ }
235
+ return freeBytes < requiredFreeBytes ? `The rewrite needs about ${requiredFreeBytes} bytes of free disk at ${this.label}; ${freeBytes} are free.` : void 0;
236
+ }
237
+ schedule(delayMs) {
238
+ if (this.intervalMs === 0 || this.closing) return;
239
+ this.timer = setTimeout(() => {
240
+ this.timer = void 0;
241
+ this.inFlight = this.run().then((outcome) => {
242
+ this.schedule(outcome === "in-transaction" ? Math.min(MAINTENANCE_RETRY_MS, this.intervalMs) : this.intervalMs);
243
+ return outcome;
244
+ }).finally(() => {
245
+ this.inFlight = void 0;
246
+ });
247
+ }, delayMs);
248
+ this.timer.unref();
249
+ }
250
+ cancel() {
251
+ if (!this.timer) return;
252
+ clearTimeout(this.timer);
253
+ this.timer = void 0;
254
+ }
255
+ };
256
+ /** Total size of the regular files under `dir`; 0 when `dir` is missing. */
257
+ async function dirBytes(dir) {
258
+ let entries;
259
+ try {
260
+ entries = await promises.readdir(dir, { withFileTypes: true });
261
+ } catch (err) {
262
+ if (err.code === "ENOENT") return 0;
263
+ throw err;
264
+ }
265
+ let total = 0;
266
+ for (const entry of entries) {
267
+ const full = path.join(dir, entry.name);
268
+ if (entry.isDirectory()) total += await dirBytes(full);
269
+ else if (entry.isFile()) total += (await promises.stat(full)).size;
270
+ }
271
+ return total;
272
+ }
273
+ function quoteIdentifier(name) {
274
+ return `"${name.replaceAll("\"", "\"\"")}"`;
275
+ }
276
+ /** The maintenance of a store opened on DurableNodeFs; undefined for any other. */
277
+ function maintenanceOf(store) {
278
+ const maintenance = store.fs?.maintenance;
279
+ return maintenance instanceof PgliteMaintenance ? maintenance : void 0;
280
+ }
281
+ function transactionStatus(messages) {
282
+ for (let i = messages.length - 1; i >= 0; i--) {
283
+ const m = messages[i];
284
+ if (m.name === "readyForQuery") return m.status;
285
+ }
286
+ }
287
+ function errorMessage(err) {
288
+ return err instanceof Error ? err.message : String(err);
289
+ }
290
+ //#endregion
291
+ //#region src/pglite/sync-tree.ts
292
+ /** One pass over a finished tree; interleaving fsync with writes costs seconds. */
293
+ function syncTree(root, hostFs = nodeFs) {
294
+ const result = {
295
+ files: 0,
296
+ dirs: 0
297
+ };
298
+ const pending = [path.resolve(root)];
299
+ while (pending.length > 0) {
300
+ const dir = pending.pop();
301
+ for (const entry of nodeFs.readdirSync(dir, { withFileTypes: true })) {
302
+ const full = path.join(dir, entry.name);
303
+ if (entry.isDirectory()) pending.push(full);
304
+ else if (entry.isFile()) {
305
+ syncFile(full, hostFs);
306
+ result.files++;
307
+ }
308
+ }
309
+ syncDirectory(dir, hostFs);
310
+ result.dirs++;
311
+ }
312
+ return result;
313
+ }
314
+ function syncFile(file, hostFs) {
315
+ const fd = nodeFs.openSync(file, "r+");
316
+ try {
317
+ hostFs.fsyncSync(fd);
318
+ } finally {
319
+ nodeFs.closeSync(fd);
320
+ }
321
+ }
322
+ /** fsyncs a directory's entries; false where the platform refuses (Windows). */
323
+ function syncDirectory(dir, hostFs = nodeFs) {
324
+ let fd;
325
+ try {
326
+ fd = nodeFs.openSync(dir, "r");
327
+ } catch {
328
+ return false;
329
+ }
330
+ try {
331
+ hostFs.fsyncSync(fd);
332
+ return true;
333
+ } catch {
334
+ return false;
335
+ } finally {
336
+ nodeFs.closeSync(fd);
337
+ }
338
+ }
339
+ //#endregion
340
+ //#region src/pglite/durable-node-fs.ts
341
+ const EIO = 29;
342
+ function resolvePgliteFsync(env) {
343
+ return env.PH_PGLITE_FSYNC !== "0";
344
+ }
345
+ const VACUUM_FULL_MODES = [
346
+ "off",
347
+ "quiet",
348
+ "forced"
349
+ ];
350
+ /**
351
+ * Reads the VACUUM FULL knobs. `PH_PGLITE_VACUUM_FULL` is `off` (the
352
+ * default: never), `quiet` (only after the quiet window, however long that
353
+ * takes) or `forced` (a deadline of 30 min from open, after which it runs
354
+ * under load). Off is the default because a full rewrite of a large store
355
+ * needs about twice its size in free disk and holds the only connection for
356
+ * minutes, and on a store that is live data rather than bloat it reclaims
357
+ * nothing; a quiet window of a minute arrives naturally between jobs, so
358
+ * `quiet` is an opt-in for stores known to be small or bloated.
359
+ * `PH_PGLITE_VACUUM_FULL_ABOVE_MB` sets the size that makes a store
360
+ * eligible; `PH_PGLITE_VACUUM_FULL_QUIET_MS` and
361
+ * `PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS` override the mode's timings. A value
362
+ * that is not a non-negative number is left to the default; an unknown mode
363
+ * throws, since silently running a rewrite is what this guards against.
364
+ */
365
+ function resolvePgliteMaintenance(env) {
366
+ const rawMode = env.PH_PGLITE_VACUUM_FULL?.trim().toLowerCase() || "off";
367
+ if (!isVacuumFullMode(rawMode)) throw new Error(`Invalid PH_PGLITE_VACUUM_FULL: ${String(env.PH_PGLITE_VACUUM_FULL)}. Expected "off", "quiet" or "forced".`);
368
+ const mode = rawMode;
369
+ const settings = {};
370
+ if (mode === "off") settings.vacuumFullAboveBytes = 0;
371
+ if (mode === "forced") settings.vacuumFullMaxDeferMs = FORCED_VACUUM_FULL_MAX_DEFER_MS;
372
+ const aboveMb = nonNegative(env.PH_PGLITE_VACUUM_FULL_ABOVE_MB);
373
+ if (aboveMb !== void 0 && mode !== "off") settings.vacuumFullAboveBytes = aboveMb * 1024 * 1024;
374
+ const quiet = nonNegative(env.PH_PGLITE_VACUUM_FULL_QUIET_MS);
375
+ if (quiet !== void 0) settings.vacuumFullQuietMs = quiet;
376
+ const maxDefer = nonNegative(env.PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS);
377
+ if (maxDefer !== void 0) settings.vacuumFullMaxDeferMs = maxDefer;
378
+ return settings;
379
+ }
380
+ function isVacuumFullMode(value) {
381
+ return VACUUM_FULL_MODES.includes(value);
382
+ }
383
+ function nonNegative(value) {
384
+ if (value === void 0 || value.trim() === "") return void 0;
385
+ const parsed = Number(value);
386
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
387
+ }
388
+ function isReadOnly(stream) {
389
+ return stream.flags !== void 0 && (stream.flags & 3) === 0;
390
+ }
391
+ const WASM_ENTRY_POINTS = [
392
+ "_interactive_one",
393
+ "_interactive_write",
394
+ "_pgl_backend",
395
+ "_pgl_initdb",
396
+ "_pgl_shutdown"
397
+ ];
398
+ function poisonAfterAbort(mod, what) {
399
+ if (!mod) return;
400
+ const message = `PGlite aborted: ${String(what) || "wasm runtime abort"}`;
401
+ for (const name of WASM_ENTRY_POINTS) {
402
+ if (typeof mod[name] !== "function") continue;
403
+ mod[name] = () => {
404
+ throw new Error(message);
405
+ };
406
+ }
407
+ try {
408
+ mod.FS.quit();
409
+ } catch {}
410
+ }
411
+ /** Built over the passed-in class so PG16 dirs on `pglite-legacy-02` get the same behaviour. */
412
+ function createDurableNodeFs(Base, dataDir, options = {}) {
413
+ const fsync = options.fsync ?? true;
414
+ const hostFs = options.hostFs ?? nodeFs;
415
+ const logger = options.logger;
416
+ const onAbort = options.onAbort;
417
+ const resolvedDir = path.resolve(dataDir);
418
+ const maintenance = new PgliteMaintenance({
419
+ intervalMs: options.maintenanceIntervalMs,
420
+ vacuumFullAboveBytes: options.vacuumFullAboveBytes,
421
+ vacuumFullQuietMs: options.vacuumFullQuietMs,
422
+ vacuumFullMaxDeferMs: options.vacuumFullMaxDeferMs,
423
+ gate: options.maintenanceGate,
424
+ now: options.now,
425
+ rewriteQuietMs: options.rewriteQuietMs,
426
+ rewriteMaxWaitMs: options.rewriteMaxWaitMs,
427
+ logger
428
+ });
429
+ class Durable extends Base {
430
+ maintenance = maintenance;
431
+ mod;
432
+ hostSyncs = fsync;
433
+ freshInit = false;
434
+ async init(pg, opts) {
435
+ const { emscriptenOpts: base } = await super.init(pg, opts);
436
+ const baseOpts = base;
437
+ const inner = baseOpts.instantiateWasm;
438
+ if (fsync && !inner) throw new Error("PGlite did not supply instantiateWasm");
439
+ return { emscriptenOpts: {
440
+ ...baseOpts,
441
+ onAbort: (what) => {
442
+ poisonAfterAbort(this.mod, what);
443
+ maintenance.stop();
444
+ onAbort?.(what);
445
+ },
446
+ preRun: [...baseOpts.preRun ?? [], (mod) => {
447
+ this.mod = mod;
448
+ if (!fsync) return;
449
+ mod.FS.filesystems.NODEFS.stream_ops.fsync = (stream) => this.fsyncStream(stream);
450
+ }],
451
+ instantiateWasm: fsync && inner ? (imports, done) => {
452
+ const original = imports.env.__syscall_fdatasync;
453
+ const replacement = (fd) => this.fdatasync(fd);
454
+ replacement.sig = original?.sig;
455
+ imports.env.__syscall_fdatasync = replacement;
456
+ return inner(imports, done);
457
+ } : inner
458
+ } };
459
+ }
460
+ async initialSyncFs() {
461
+ await super.initialSyncFs();
462
+ this.freshInit = fsync && !nodeFs.existsSync(path.join(resolvedDir, "PG_VERSION"));
463
+ if (this.freshInit) this.hostSyncs = false;
464
+ const baseBytes = await dirBytes(path.join(resolvedDir, "base"));
465
+ maintenance.start(this.pg, resolvedDir, baseBytes);
466
+ }
467
+ async syncToFs(relaxedDurability) {
468
+ maintenance.noteSync();
469
+ await super.syncToFs(relaxedDurability);
470
+ if (!this.freshInit) return;
471
+ this.freshInit = false;
472
+ this.hostSyncs = true;
473
+ syncTree(resolvedDir, hostFs);
474
+ }
475
+ async closeFs() {
476
+ try {
477
+ await maintenance.stop();
478
+ } finally {
479
+ await super.closeFs();
480
+ }
481
+ }
482
+ fsyncStream(stream) {
483
+ if (!this.hostSyncs) return 0;
484
+ if (typeof stream.nfd !== "number" || isReadOnly(stream)) return 0;
485
+ try {
486
+ hostFs.fsyncSync(stream.nfd);
487
+ } catch (err) {
488
+ logger?.warn(`DurableNodeFs fsync failed: ${String(err)}`);
489
+ return EIO;
490
+ }
491
+ return 0;
492
+ }
493
+ fdatasync(fd) {
494
+ if (!this.hostSyncs) return 0;
495
+ let stream;
496
+ try {
497
+ stream = this.mod.FS.getStreamChecked(fd);
498
+ } catch {
499
+ return -ERRNO_CODES.EBADF;
500
+ }
501
+ if (typeof stream.nfd !== "number" || isReadOnly(stream)) return 0;
502
+ try {
503
+ hostFs.fdatasyncSync(stream.nfd);
504
+ } catch (err) {
505
+ logger?.warn(`DurableNodeFs fdatasync failed: ${String(err)}`);
506
+ return -29;
507
+ }
508
+ return 0;
509
+ }
510
+ }
511
+ return new Durable(dataDir);
512
+ }
513
+ //#endregion
514
+ //#region src/pglite/worker/error-info.ts
515
+ const MAX_STACK_LENGTH = 8192;
516
+ const MAX_CAUSE_DEPTH = 8;
517
+ /** The string fields of PGlite's `DatabaseError`, plus the query PGlite attaches. */
518
+ const PG_ERROR_FIELDS = [
519
+ "code",
520
+ "severity",
521
+ "detail",
522
+ "hint",
523
+ "position",
524
+ "internalPosition",
525
+ "internalQuery",
526
+ "where",
527
+ "schema",
528
+ "table",
529
+ "column",
530
+ "dataType",
531
+ "constraint",
532
+ "file",
533
+ "line",
534
+ "routine",
535
+ "query"
536
+ ];
537
+ /** Flattens an error and its cause chain into a structured-clonable shape. */
538
+ function toPGliteErrorInfo(err, depth = 0) {
539
+ if (depth > MAX_CAUSE_DEPTH) return {
540
+ name: "Error",
541
+ message: "cause chain truncated",
542
+ fields: {}
543
+ };
544
+ if (!(err instanceof Error)) return {
545
+ name: "Error",
546
+ message: describe(err),
547
+ fields: {}
548
+ };
549
+ const info = {
550
+ name: err.name || "Error",
551
+ message: err.message,
552
+ fields: pgFieldsOf(err)
553
+ };
554
+ if (typeof err.stack === "string") info.stack = err.stack.slice(0, MAX_STACK_LENGTH);
555
+ if (err.cause !== void 0) info.cause = toPGliteErrorInfo(err.cause, depth + 1);
556
+ return info;
557
+ }
558
+ /** Rebuilds an `Error` carrying the original name, stack, Postgres fields and cause chain. */
559
+ function fromPGliteErrorInfo(info) {
560
+ const err = new Error(info.message);
561
+ define(err, "name", info.name);
562
+ if (info.stack !== void 0) err.stack = info.stack;
563
+ for (const [key, value] of Object.entries(info.fields)) define(err, key, value);
564
+ if (info.cause !== void 0) define(err, "cause", fromPGliteErrorInfo(info.cause));
565
+ return err;
566
+ }
567
+ function pgFieldsOf(err) {
568
+ const fields = {};
569
+ const record = err;
570
+ for (const key of PG_ERROR_FIELDS) {
571
+ const value = record[key];
572
+ if (typeof value === "string") fields[key] = value;
573
+ }
574
+ return fields;
575
+ }
576
+ function define(err, key, value) {
577
+ Object.defineProperty(err, key, {
578
+ value,
579
+ configurable: true,
580
+ writable: true,
581
+ enumerable: key !== "name" && key !== "cause"
582
+ });
583
+ }
584
+ function describe(value) {
585
+ if (typeof value === "string") return value;
586
+ if (value && typeof value === "object") {
587
+ const message = value.message;
588
+ if (typeof message === "string") return message;
589
+ }
590
+ if (value === void 0 || typeof value === "function") return String(value);
591
+ try {
592
+ return JSON.stringify(value);
593
+ } catch {
594
+ return "[unserializable]";
595
+ }
596
+ }
597
+ //#endregion
598
+ export { PGLITE_UTC_PARSERS as _, resolvePgliteMaintenance as a, DEFAULT_MAINTENANCE_INTERVAL_MS as c, DEFAULT_VACUUM_FULL_ABOVE_BYTES as d, DEFAULT_VACUUM_FULL_MAX_DEFER_MS as f, maintenanceOf as g, PgliteMaintenance as h, resolvePgliteFsync as i, DEFAULT_REWRITE_MAX_WAIT_MS as l, FORCED_VACUUM_FULL_MAX_DEFER_MS as m, toPGliteErrorInfo as n, syncDirectory as o, DEFAULT_VACUUM_FULL_QUIET_MS as p, createDurableNodeFs as r, syncTree as s, fromPGliteErrorInfo as t, DEFAULT_REWRITE_QUIET_MS as u };
599
+
600
+ //# sourceMappingURL=error-info-Cr6oQACe.mjs.map
601
+ //# debugId=32154524-8414-5e0c-bd0b-eb61f765c647