@powerhousedao/reactor-api 6.2.3-dev.85 → 6.2.3-dev.87

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.
@@ -1,6 +1,6 @@
1
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]="1acd2579-f9fe-501c-8ca3-de218d2e0d6c")}catch(e){}}();
3
- import { E as findSubgraphTypeCollisions, N as reservedTypeNames, O as generatedTypesOf, a as inspectionAdminTypeDefs, f as decideAdmission, g as collectSubgraphClaims, h as supergraphClaimLosers, i as inspectionTypeDefs, j as getGeneratedDocumentModelTypes, k as getDocumentModelSubgraphName, l as RegistrationOrder, m as documentModelSubgraphSources, n as systemTypeDefs, o as CORE_ORIGIN, p as describeOrigin, r as schema_default, s as DOCUMENT_MODEL_ORIGIN, t as baseDocumentModels, u as admitDocumentModels, v as DocumentModelSchemaCache, z as schema_default$1 } from "./base-document-models-DZfYOd9M.mjs";
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]="4f582a0b-6c59-577b-8c0b-9a6b344d95fa")}catch(e){}}();
3
+ import { E as findSubgraphTypeCollisions, N as reservedTypeNames, O as generatedTypesOf, a as inspectionAdminTypeDefs, f as decideAdmission, g as collectSubgraphClaims, h as supergraphClaimLosers, i as inspectionTypeDefs, j as getGeneratedDocumentModelTypes, k as getDocumentModelSubgraphName, l as RegistrationOrder, m as documentModelSubgraphSources, n as systemTypeDefs, o as CORE_ORIGIN, p as describeOrigin, r as schema_default, s as DOCUMENT_MODEL_ORIGIN, t as baseDocumentModels, u as admitDocumentModels, v as DocumentModelSchemaCache, z as schema_default$1 } from "./base-document-models-CNHrVpOU.mjs";
4
4
  import "./subgraph-schema-owner-BEjuk2Xv.mjs";
5
5
  import { typedefs } from "@powerhousedao/analytics-engine-graphql";
6
6
  import { gql } from "graphql-tag";
@@ -134,5 +134,5 @@ function checkPackageSubgraphs(subgraphs, documentModels) {
134
134
  //#endregion
135
135
  export { checkPackageSubgraphs };
136
136
 
137
- //# sourceMappingURL=package-subgraph-check-DxZhf2lB.mjs.map
138
- //# debugId=1acd2579-f9fe-501c-8ca3-de218d2e0d6c
137
+ //# sourceMappingURL=package-subgraph-check-DdZLhOHW.mjs.map
138
+ //# debugId=4f582a0b-6c59-577b-8c0b-9a6b344d95fa
@@ -1 +1 @@
1
- {"version":3,"file":"package-subgraph-check-DxZhf2lB.mjs","sources":["../src/graphql/package-subgraph-check.ts"],"sourcesContent":["import { typedefs as analyticsTypeDefs } from \"@powerhousedao/analytics-engine-graphql\";\nimport type { DocumentModelGlobalState } from \"@powerhousedao/shared/document-model\";\nimport type { DocumentNode } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport { baseDocumentModels } from \"../packages/base-document-models.js\";\nimport {\n DocumentModelSchemaCache,\n type DocumentModelSource,\n findSubgraphTypeCollisions,\n generatedTypesOf,\n getDocumentModelSubgraphName,\n getGeneratedDocumentModelTypes,\n reservedTypeNames,\n} from \"../utils/create-schema.js\";\nimport authSchema from \"./auth/schema.graphql\";\nimport { inspectionAdminTypeDefs } from \"./inspection/admin-schema.js\";\nimport { inspectionTypeDefs } from \"./inspection/schema.js\";\nimport reactorSchema from \"./reactor/schema.graphql\";\nimport {\n type Admission,\n admitDocumentModels,\n CORE_ORIGIN,\n decideAdmission,\n describeOrigin,\n DOCUMENT_MODEL_ORIGIN,\n documentModelSubgraphSources,\n RegistrationOrder,\n type SubgraphOrigin,\n supergraphClaimLosers,\n} from \"./subgraph-admission.js\";\nimport {\n collectSubgraphClaims,\n type SubgraphClaims,\n} from \"./subgraph-type-ownership.js\";\nimport { systemTypeDefs } from \"./system/schema.js\";\nimport { DOCUMENT_MODEL_SCHEMA_OWNER } from \"./subgraph-schema-owner.js\";\nimport type {\n PackageSubgraph,\n PackageSubgraphConflicts,\n PackageSubgraphReport,\n RefusedDocumentModel,\n} from \"./subgraph-types.js\";\n\n/** The type definitions of every core subgraph, by subgraph name. */\nexport const coreSubgraphTypeDefs: ReadonlyMap<string, DocumentNode> = new Map([\n [\"analytics\", gql(analyticsTypeDefs)],\n [\"system\", systemTypeDefs],\n [\"r\", gql(reactorSchema)],\n [\"inspection\", inspectionTypeDefs],\n [\"inspection-admin\", inspectionAdminTypeDefs],\n [\"auth\", gql(authSchema)],\n]);\n\nconst PACKAGE_ORIGIN: SubgraphOrigin = \"package\";\n\ntype Registered = {\n name: string;\n origin: SubgraphOrigin;\n typeDefs: DocumentNode;\n ownTypeNames?: ReadonlySet<string>;\n};\n\ntype Rejection = Extract<Admission<Registered>, { action: \"reject\" }>;\n\nfunction claimsOf(typeDefs: DocumentNode, generated: ReadonlySet<string>) {\n try {\n return collectSubgraphClaims(typeDefs, generated);\n } catch {\n // Malformed typeDefs fail where the schema is built, so claim nothing.\n return new Map() as SubgraphClaims;\n }\n}\n\nfunction describeModelSubgraphRejection(rejection: Rejection): string {\n switch (rejection.reason) {\n case \"core name\":\n return `its subgraph name is taken by a subgraph from ${describeOrigin(CORE_ORIGIN)}`;\n case \"rank\":\n return `its subgraph name is taken by a subgraph from ${describeOrigin(rejection.holderOrigin)}`;\n case \"collision\":\n return `its subgraph defines generated types: ${rejection.collisions.join(\", \")}`;\n }\n}\n\nfunction packageConflict(\n rejection: Rejection,\n owners: ReadonlyMap<string, string>,\n): PackageSubgraphConflicts {\n switch (rejection.reason) {\n case \"core name\":\n return { nameHeldBy: \"core\", claims: [] };\n case \"rank\":\n return { nameHeldBy: \"document model\", claims: [] };\n case \"collision\":\n return {\n claims: rejection.collisions.map((claim) => ({\n claim,\n owner: owners.get(claim) ?? DOCUMENT_MODEL_SCHEMA_OWNER,\n })),\n };\n }\n}\n\n/** Server admission replayed for one package; hosts and other packages unknown. */\nexport function checkPackageSubgraphs(\n subgraphs: readonly PackageSubgraph[],\n documentModels: readonly DocumentModelGlobalState[],\n): PackageSubgraphReport {\n const packageModels: DocumentModelSource[] = documentModels.map((global) => ({\n documentModel: { global },\n }));\n const { admitted, schemas, refusals } = admitDocumentModels(\n new DocumentModelSchemaCache<DocumentModelSource>().resolve([\n ...baseDocumentModels.map(([, model]) => model),\n ...packageModels,\n ]),\n reservedTypeNames(coreSubgraphTypeDefs.values()),\n );\n const generated = getGeneratedDocumentModelTypes(admitted, schemas);\n const fixed = generatedTypesOf([]).names;\n const generatedOwners = new Map<string, string>();\n for (const model of admitted) {\n const owner = getDocumentModelSubgraphName(model.documentModel.global);\n const { names } = getGeneratedDocumentModelTypes([model], schemas);\n for (const name of names) {\n if (!fixed.has(name)) generatedOwners.set(name, owner);\n }\n }\n\n const holders = new Map<string, Registered>();\n const order = new RegistrationOrder();\n const register = (entry: Registered): Admission<Registered> => {\n const holder = holders.get(entry.name);\n const admission = decideAdmission(\n entry,\n entry.origin,\n holder ? [{ holder, origin: holder.origin }] : [],\n () => {\n try {\n return findSubgraphTypeCollisions(\n generated,\n entry.typeDefs,\n entry.ownTypeNames,\n );\n } catch {\n return [];\n }\n },\n );\n if (admission.action === \"add\") {\n holders.set(entry.name, entry);\n order.record(entry.origin, entry.name);\n }\n return admission;\n };\n\n for (const [name, typeDefs] of coreSubgraphTypeDefs) {\n register({ name, origin: CORE_ORIGIN, typeDefs });\n }\n\n const refusedModels: RefusedDocumentModel[] = refusals\n .filter(({ model }) => packageModels.includes(model))\n .map(({ model, reason, subgraphOnly }) => ({\n name: model.documentModel.global.name,\n reason,\n subgraphOnly,\n }));\n for (const { model, types } of documentModelSubgraphSources(\n admitted,\n schemas,\n )) {\n const admission = register({\n name: getDocumentModelSubgraphName(model.documentModel.global),\n origin: DOCUMENT_MODEL_ORIGIN,\n typeDefs: types.typeDefs,\n ownTypeNames: types.typeNames,\n });\n if (admission.action === \"reject\" && packageModels.includes(model)) {\n refusedModels.push({\n name: model.documentModel.global.name,\n reason: describeModelSubgraphRejection(admission),\n subgraphOnly: true,\n });\n }\n }\n\n const conflicts = new Map<string, PackageSubgraphConflicts>();\n for (const { name, typeDefs } of subgraphs) {\n const admission = register({ name, origin: PACKAGE_ORIGIN, typeDefs });\n if (admission.action === \"reject\") {\n conflicts.set(name, packageConflict(admission, generatedOwners));\n } else if (admission.action === \"add\" && admission.replaces.length > 0) {\n conflicts.set(name, { nameHeldBy: \"package\", claims: [] });\n }\n }\n\n const excluded = supergraphClaimLosers(\n Array.from(holders.values(), (entry) => ({\n member: entry,\n name: entry.name,\n origin: entry.origin,\n claims: claimsOf(entry.typeDefs, generated.names),\n })),\n order,\n );\n for (const [entry, claims] of excluded) {\n if (entry.origin !== PACKAGE_ORIGIN) continue;\n conflicts.set(entry.name, { ...conflicts.get(entry.name), claims });\n }\n return { conflicts, refusedModels };\n}\n"],"names":["analyticsTypeDefs","reactorSchema","authSchema"],"mappings":";;;;;;;;AA4CA,MAAa,uCAA0D,IAAI,IAAI;CAC7E,CAAC,aAAa,IAAIA,QAAiB,CAAC;CACpC,CAAC,UAAU,cAAc;CACzB,CAAC,KAAK,IAAIC,cAAa,CAAC;CACxB,CAAC,cAAc,kBAAkB;CACjC,CAAC,oBAAoB,uBAAuB;CAC5C,CAAC,QAAQ,IAAIC,gBAAU,CAAC;AAC1B,CAAC;AAED,MAAM,iBAAiC;AAWvC,SAAS,SAAS,UAAwB,WAAgC;CACxE,IAAI;EACF,OAAO,sBAAsB,UAAU,SAAS;CAClD,QAAQ;EAEN,uBAAO,IAAI,IAAI;CACjB;AACF;AAEA,SAAS,+BAA+B,WAA8B;CACpE,QAAQ,UAAU,QAAlB;EACE,KAAK,aACH,OAAO,iDAAiD,eAAe,WAAW;EACpF,KAAK,QACH,OAAO,iDAAiD,eAAe,UAAU,YAAY;EAC/F,KAAK,aACH,OAAO,yCAAyC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I,WAAW;EACvC,QAAQ;EACR,MAAM,MAAM;EACZ,QAAQ,MAAM;EACd,QAAQ,SAAS,MAAM,UAAU,UAAU,KAAK;CAClD,EAAE,GACF,KACF;CACA,KAAK,MAAM,CAAC,OAAO,WAAW,UAAU;EACtC,IAAI,MAAM,WAAW,gBAAgB;EACrC,UAAU,IAAI,MAAM,MAAM;GAAE,GAAG,UAAU,IAAI,MAAM,IAAI;GAAG;EAAO,CAAC;CACpE;CACA,OAAO;EAAE;EAAW;CAAc;AACpC","debug_id":"1acd2579-f9fe-501c-8ca3-de218d2e0d6c"}
1
+ {"version":3,"file":"package-subgraph-check-DdZLhOHW.mjs","sources":["../src/graphql/package-subgraph-check.ts"],"sourcesContent":["import { typedefs as analyticsTypeDefs } from \"@powerhousedao/analytics-engine-graphql\";\nimport type { DocumentModelGlobalState } from \"@powerhousedao/shared/document-model\";\nimport type { DocumentNode } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport { baseDocumentModels } from \"../packages/base-document-models.js\";\nimport {\n DocumentModelSchemaCache,\n type DocumentModelSource,\n findSubgraphTypeCollisions,\n generatedTypesOf,\n getDocumentModelSubgraphName,\n getGeneratedDocumentModelTypes,\n reservedTypeNames,\n} from \"../utils/create-schema.js\";\nimport authSchema from \"./auth/schema.graphql\";\nimport { inspectionAdminTypeDefs } from \"./inspection/admin-schema.js\";\nimport { inspectionTypeDefs } from \"./inspection/schema.js\";\nimport reactorSchema from \"./reactor/schema.graphql\";\nimport {\n type Admission,\n admitDocumentModels,\n CORE_ORIGIN,\n decideAdmission,\n describeOrigin,\n DOCUMENT_MODEL_ORIGIN,\n documentModelSubgraphSources,\n RegistrationOrder,\n type SubgraphOrigin,\n supergraphClaimLosers,\n} from \"./subgraph-admission.js\";\nimport {\n collectSubgraphClaims,\n type SubgraphClaims,\n} from \"./subgraph-type-ownership.js\";\nimport { systemTypeDefs } from \"./system/schema.js\";\nimport { DOCUMENT_MODEL_SCHEMA_OWNER } from \"./subgraph-schema-owner.js\";\nimport type {\n PackageSubgraph,\n PackageSubgraphConflicts,\n PackageSubgraphReport,\n RefusedDocumentModel,\n} from \"./subgraph-types.js\";\n\n/** The type definitions of every core subgraph, by subgraph name. */\nexport const coreSubgraphTypeDefs: ReadonlyMap<string, DocumentNode> = new Map([\n [\"analytics\", gql(analyticsTypeDefs)],\n [\"system\", systemTypeDefs],\n [\"r\", gql(reactorSchema)],\n [\"inspection\", inspectionTypeDefs],\n [\"inspection-admin\", inspectionAdminTypeDefs],\n [\"auth\", gql(authSchema)],\n]);\n\nconst PACKAGE_ORIGIN: SubgraphOrigin = \"package\";\n\ntype Registered = {\n name: string;\n origin: SubgraphOrigin;\n typeDefs: DocumentNode;\n ownTypeNames?: ReadonlySet<string>;\n};\n\ntype Rejection = Extract<Admission<Registered>, { action: \"reject\" }>;\n\nfunction claimsOf(typeDefs: DocumentNode, generated: ReadonlySet<string>) {\n try {\n return collectSubgraphClaims(typeDefs, generated);\n } catch {\n // Malformed typeDefs fail where the schema is built, so claim nothing.\n return new Map() as SubgraphClaims;\n }\n}\n\nfunction describeModelSubgraphRejection(rejection: Rejection): string {\n switch (rejection.reason) {\n case \"core name\":\n return `its subgraph name is taken by a subgraph from ${describeOrigin(CORE_ORIGIN)}`;\n case \"rank\":\n return `its subgraph name is taken by a subgraph from ${describeOrigin(rejection.holderOrigin)}`;\n case \"collision\":\n return `its subgraph defines generated types: ${rejection.collisions.join(\", \")}`;\n }\n}\n\nfunction packageConflict(\n rejection: Rejection,\n owners: ReadonlyMap<string, string>,\n): PackageSubgraphConflicts {\n switch (rejection.reason) {\n case \"core name\":\n return { nameHeldBy: \"core\", claims: [] };\n case \"rank\":\n return { nameHeldBy: \"document model\", claims: [] };\n case \"collision\":\n return {\n claims: rejection.collisions.map((claim) => ({\n claim,\n owner: owners.get(claim) ?? DOCUMENT_MODEL_SCHEMA_OWNER,\n })),\n };\n }\n}\n\n/** Server admission replayed for one package; hosts and other packages unknown. */\nexport function checkPackageSubgraphs(\n subgraphs: readonly PackageSubgraph[],\n documentModels: readonly DocumentModelGlobalState[],\n): PackageSubgraphReport {\n const packageModels: DocumentModelSource[] = documentModels.map((global) => ({\n documentModel: { global },\n }));\n const { admitted, schemas, refusals } = admitDocumentModels(\n new DocumentModelSchemaCache<DocumentModelSource>().resolve([\n ...baseDocumentModels.map(([, model]) => model),\n ...packageModels,\n ]),\n reservedTypeNames(coreSubgraphTypeDefs.values()),\n );\n const generated = getGeneratedDocumentModelTypes(admitted, schemas);\n const fixed = generatedTypesOf([]).names;\n const generatedOwners = new Map<string, string>();\n for (const model of admitted) {\n const owner = getDocumentModelSubgraphName(model.documentModel.global);\n const { names } = getGeneratedDocumentModelTypes([model], schemas);\n for (const name of names) {\n if (!fixed.has(name)) generatedOwners.set(name, owner);\n }\n }\n\n const holders = new Map<string, Registered>();\n const order = new RegistrationOrder();\n const register = (entry: Registered): Admission<Registered> => {\n const holder = holders.get(entry.name);\n const admission = decideAdmission(\n entry,\n entry.origin,\n holder ? [{ holder, origin: holder.origin }] : [],\n () => {\n try {\n return findSubgraphTypeCollisions(\n generated,\n entry.typeDefs,\n entry.ownTypeNames,\n );\n } catch {\n return [];\n }\n },\n );\n if (admission.action === \"add\") {\n holders.set(entry.name, entry);\n order.record(entry.origin, entry.name);\n }\n return admission;\n };\n\n for (const [name, typeDefs] of coreSubgraphTypeDefs) {\n register({ name, origin: CORE_ORIGIN, typeDefs });\n }\n\n const refusedModels: RefusedDocumentModel[] = refusals\n .filter(({ model }) => packageModels.includes(model))\n .map(({ model, reason, subgraphOnly }) => ({\n name: model.documentModel.global.name,\n reason,\n subgraphOnly,\n }));\n for (const { model, types } of documentModelSubgraphSources(\n admitted,\n schemas,\n )) {\n const admission = register({\n name: getDocumentModelSubgraphName(model.documentModel.global),\n origin: DOCUMENT_MODEL_ORIGIN,\n typeDefs: types.typeDefs,\n ownTypeNames: types.typeNames,\n });\n if (admission.action === \"reject\" && packageModels.includes(model)) {\n refusedModels.push({\n name: model.documentModel.global.name,\n reason: describeModelSubgraphRejection(admission),\n subgraphOnly: true,\n });\n }\n }\n\n const conflicts = new Map<string, PackageSubgraphConflicts>();\n for (const { name, typeDefs } of subgraphs) {\n const admission = register({ name, origin: PACKAGE_ORIGIN, typeDefs });\n if (admission.action === \"reject\") {\n conflicts.set(name, packageConflict(admission, generatedOwners));\n } else if (admission.action === \"add\" && admission.replaces.length > 0) {\n conflicts.set(name, { nameHeldBy: \"package\", claims: [] });\n }\n }\n\n const excluded = supergraphClaimLosers(\n Array.from(holders.values(), (entry) => ({\n member: entry,\n name: entry.name,\n origin: entry.origin,\n claims: claimsOf(entry.typeDefs, generated.names),\n })),\n order,\n );\n for (const [entry, claims] of excluded) {\n if (entry.origin !== PACKAGE_ORIGIN) continue;\n conflicts.set(entry.name, { ...conflicts.get(entry.name), claims });\n }\n return { conflicts, refusedModels };\n}\n"],"names":["analyticsTypeDefs","reactorSchema","authSchema"],"mappings":";;;;;;;;AA4CA,MAAa,uCAA0D,IAAI,IAAI;CAC7E,CAAC,aAAa,IAAIA,QAAiB,CAAC;CACpC,CAAC,UAAU,cAAc;CACzB,CAAC,KAAK,IAAIC,cAAa,CAAC;CACxB,CAAC,cAAc,kBAAkB;CACjC,CAAC,oBAAoB,uBAAuB;CAC5C,CAAC,QAAQ,IAAIC,gBAAU,CAAC;AAC1B,CAAC;AAED,MAAM,iBAAiC;AAWvC,SAAS,SAAS,UAAwB,WAAgC;CACxE,IAAI;EACF,OAAO,sBAAsB,UAAU,SAAS;CAClD,QAAQ;EAEN,uBAAO,IAAI,IAAI;CACjB;AACF;AAEA,SAAS,+BAA+B,WAA8B;CACpE,QAAQ,UAAU,QAAlB;EACE,KAAK,aACH,OAAO,iDAAiD,eAAe,WAAW;EACpF,KAAK,QACH,OAAO,iDAAiD,eAAe,UAAU,YAAY;EAC/F,KAAK,aACH,OAAO,yCAAyC,UAAU,WAAW,KAAK,IAAI;CAClF;AACF;AAEA,SAAS,gBACP,WACA,QAC0B;CAC1B,QAAQ,U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UAAU,UAAU,KAAK;CAClD,EAAE,GACF,KACF;CACA,KAAK,MAAM,CAAC,OAAO,WAAW,UAAU;EACtC,IAAI,MAAM,WAAW,gBAAgB;EACrC,UAAU,IAAI,MAAM,MAAM;GAAE,GAAG,UAAU,IAAI,MAAM,IAAI;GAAG;EAAO,CAAC;CACpE;CACA,OAAO;EAAE;EAAW;CAAc;AACpC","debug_id":"4f582a0b-6c59-577b-8c0b-9a6b344d95fa"}
@@ -1,8 +1,9 @@
1
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]="b7d7a36c-32db-57bb-9cd6-53a5320d5650")}catch(e){}}();
3
- import { o as syncDirectory, s as syncTree, t as fromPGliteErrorInfo } from "./error-info-BaEL50f5.mjs";
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]="8c5d8636-4e82-5d46-982c-c40ed34f74ce")}catch(e){}}();
3
+ import { o as syncDirectory, s as syncTree, t as fromPGliteErrorInfo } from "./error-info-Cr6oQACe.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import { childLogger } from "document-model";
6
+ import { registerTelemetryWorker } from "@powerhousedao/reactor";
6
7
  import { AsyncLocalStorage } from "node:async_hooks";
7
8
  import path from "node:path";
8
9
  import { existsSync, promises } from "node:fs";
@@ -380,6 +381,7 @@ var ThreadedPGlite = class {
380
381
  workerError = null;
381
382
  abortReason = null;
382
383
  closePromise = null;
384
+ forgetTelemetry;
383
385
  constructor(options) {
384
386
  this.label = options.store.label;
385
387
  this.logger = options.logger ?? childLogger([
@@ -399,6 +401,7 @@ var ThreadedPGlite = class {
399
401
  this.worker.on("message", (msg) => this.handleMessage(msg));
400
402
  this.worker.on("error", (err) => this.handleWorkerError(err));
401
403
  this.worker.on("exit", (code) => this.handleExit(code));
404
+ this.forgetTelemetry = registerTelemetryWorker(`pglite:${this.label}`, () => this.memoryStats());
402
405
  this.waitReady = this.request("init", (id) => ({
403
406
  type: "init",
404
407
  id,
@@ -412,6 +415,17 @@ var ThreadedPGlite = class {
412
415
  });
413
416
  this.waitReady.catch(() => void 0);
414
417
  }
418
+ /** JS heap of the worker and the WASM linear memory, which only grows. */
419
+ async memoryStats() {
420
+ const [heap, wasm] = await Promise.all([this.worker.getHeapStatistics(), this.request("stats", (id) => ({
421
+ type: "stats",
422
+ id
423
+ }))]);
424
+ return {
425
+ heapUsed: heap.used_heap_size,
426
+ wasm
427
+ };
428
+ }
415
429
  /** True once the store is open and until close starts. */
416
430
  get ready() {
417
431
  return this.phase === "ready";
@@ -476,6 +490,14 @@ var ThreadedPGlite = class {
476
490
  this.release(reservation);
477
491
  }
478
492
  }
493
+ /** Rewrites one table through the store's maintenance inside the worker. */
494
+ rewriteTable(request) {
495
+ return this.request("rewrite", (id) => ({
496
+ type: "rewrite-table",
497
+ id,
498
+ request
499
+ }));
500
+ }
479
501
  /** The status after the most recently answered request, as PGlite reported it. */
480
502
  isInTransaction() {
481
503
  return this.inTransaction;
@@ -571,6 +593,12 @@ var ThreadedPGlite = class {
571
593
  case "exec-result":
572
594
  this.settle(msg.id, msg.inTransaction, msg.results);
573
595
  return;
596
+ case "stats-result":
597
+ this.settle(msg.id, this.inTransaction, msg.wasmBytes);
598
+ return;
599
+ case "rewrite-table-result":
600
+ this.settle(msg.id, msg.inTransaction, msg.result);
601
+ return;
574
602
  case "closed":
575
603
  this.settle(msg.id, false, void 0);
576
604
  return;
@@ -634,6 +662,7 @@ var ThreadedPGlite = class {
634
662
  this.logger.error(`PGlite worker for ${this.label} failed: @error`, err);
635
663
  }
636
664
  handleExit(code) {
665
+ this.forgetTelemetry();
637
666
  const graceful = this.phase === "closing" && this.terminalError === null;
638
667
  this.phase = "closed";
639
668
  this.inTransaction = false;
@@ -711,5 +740,5 @@ const pgliteWorkerEntryPath = resolvePgliteWorkerEntryPath();
711
740
  //#endregion
712
741
  export { convertSnapshotDir as _, resolvePgliteWorkerMemoryMb as a, extractSnapshot as b, PGliteWorkerError as c, WASM_WRAPPER_TIERING_FLAG as d, disableWasmWrapperTiering as f, removeStalePgliteFiles as g, preparePgliteDataDir as h, pgliteWorkerEntryPath as i, PGliteWorkerExitedError as l, openCurrentPgliteForVerify as m, DEFAULT_PGLITE_WORKER_MEMORY_MB as n, CURRENT_PGLITE_MODULE as o, CURRENT_PGLITE_MAJOR as p, ThreadedPGlite as r, PGliteWorkerClosedError as s, DEFAULT_PGLITE_WORKER_CLOSE_GRACE_MS as t, PGliteWorkerInitError as u, recoverConversion as v, SNAPSHOT_FILE_NAME as y };
713
742
 
714
- //# sourceMappingURL=pglite-node-DGms6Ssa.mjs.map
715
- //# debugId=b7d7a36c-32db-57bb-9cd6-53a5320d5650
743
+ //# sourceMappingURL=pglite-node-CcX2YT-l.mjs.map
744
+ //# debugId=8c5d8636-4e82-5d46-982c-c40ed34f74ce
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pglite-node-CcX2YT-l.mjs","sources":["../src/pglite/snapshot-reader.ts","../src/pglite/convert-snapshot-dir.ts","../src/pglite/preflight.ts","../src/pglite/wasm-wrapper-tiering.ts","../src/pglite/worker/errors.ts","../src/pglite/worker/protocol.ts","../src/pglite/worker/threaded-pglite.ts"],"sourcesContent":["import { promises as fs } from \"node:fs\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { syncTree, type SyncTreeHostFs } from \"./sync-tree.js\";\n\n// v1: magic, u32 version, u32 count; then u8 type, u32 mode, path, u32 len, data.\nexport const SNAPSHOT_FILE_NAME = \"snapshot.bin\";\nconst MAGIC = new Uint8Array([0x50, 0x47, 0x4c, 0x41]);\nconst FORMAT_VERSION = 1;\nconst HEADER_SIZE = 12;\nconst ENTRY_PREFIX_SIZE = 9;\nconst SKIPPED_ENTRIES = new Set([\"postmaster.pid\"]);\n// Node rejects a single read above 2^31-1 bytes.\nconst DEFAULT_IO_CHUNK_SIZE = 64 * 1024 * 1024;\n\nexport interface ExtractSnapshotOptions {\n chunkSize?: number;\n /** Default true: one fsync pass over the tree after the last write. */\n sync?: boolean;\n hostFs?: SyncTreeHostFs;\n}\n\nexport interface ExtractedSnapshot {\n pgVersionMajor: number;\n /** `global/pg_control` bytes; absent only in synthetic trees. */\n pgControl?: Buffer;\n /** Entries written to disk; skipped entries are not counted. */\n entries: number;\n /** Size of the snapshot file. */\n bytes: number;\n}\n\n/** Unpacks a snapshot into the existing `outDir`. */\nexport async function extractSnapshot(\n snapshotPath: string,\n outDir: string,\n options: ExtractSnapshotOptions = {},\n): Promise<ExtractedSnapshot> {\n const fh = await fs.open(snapshotPath, \"r\");\n try {\n const { size } = await fh.stat();\n return await extractFromHandle(fh, size, outDir, options);\n } finally {\n await fh.close();\n }\n}\n\nasync function extractFromHandle(\n fh: FileHandle,\n fileSize: number,\n outDir: string,\n options: ExtractSnapshotOptions,\n): Promise<ExtractedSnapshot> {\n const root = path.resolve(outDir);\n const chunkSize = Math.min(\n options.chunkSize ?? DEFAULT_IO_CHUNK_SIZE,\n Math.max(1, fileSize),\n );\n const reader = new ChunkedReader(fh, chunkSize);\n\n const header = await reader.take(HEADER_SIZE);\n for (let i = 0; i < MAGIC.length; i++) {\n if (header[i] !== MAGIC[i]) {\n throw new Error(\"snapshot.bin: invalid snapshot magic\");\n }\n }\n const version = header.readUInt32LE(4);\n if (version !== FORMAT_VERSION) {\n throw new Error(`snapshot.bin: unsupported snapshot version ${version}`);\n }\n const count = header.readUInt32LE(8);\n\n const decoder = new TextDecoder();\n let pgVersionText: string | undefined;\n let pgControl: Buffer | undefined;\n let written = 0;\n\n for (let i = 0; i < count; i++) {\n const prefix = await reader.take(ENTRY_PREFIX_SIZE);\n const type = prefix.readUInt8(0);\n const mode = prefix.readUInt32LE(1) & 0o7777;\n const pathLen = prefix.readUInt32LE(5);\n const relPath = decoder.decode(await reader.take(pathLen));\n const dataLen = (await reader.take(4)).readUInt32LE(0);\n const data = await reader.take(dataLen);\n\n const full = resolveInside(root, relPath);\n if (SKIPPED_ENTRIES.has(relPath)) continue;\n\n if (type === 0) {\n await fs.mkdir(full, { recursive: true });\n await fs.chmod(full, dirMode(mode));\n } else if (type === 1) {\n await fs.mkdir(path.dirname(full), { recursive: true });\n await fs.writeFile(full, data);\n await fs.chmod(full, mode);\n if (relPath === \"PG_VERSION\") pgVersionText = data.toString(\"utf8\");\n if (relPath === \"global/pg_control\") pgControl = data;\n } else {\n throw new Error(`snapshot.bin: unknown entry type ${type}`);\n }\n written++;\n }\n\n if (pgVersionText === undefined) {\n throw new Error(\"snapshot.bin: no PG_VERSION entry\");\n }\n const pgVersionMajor = Number.parseInt(pgVersionText.trim(), 10);\n if (!Number.isInteger(pgVersionMajor) || pgVersionMajor <= 0) {\n throw new Error(\n `snapshot.bin: unreadable PG_VERSION ${JSON.stringify(pgVersionText)}`,\n );\n }\n\n if (options.sync ?? true) syncTree(root, options.hostFs);\n\n return { pgVersionMajor, pgControl, entries: written, bytes: fileSize };\n}\n\nfunction resolveInside(root: string, relPath: string): string {\n const full = path.resolve(root, relPath);\n if (full !== root && !full.startsWith(root + path.sep)) {\n throw new Error(`snapshot.bin: entry escapes the data dir: ${relPath}`);\n }\n return full;\n}\n\n/** NTFS has no execute bit; a Windows snapshot can carry untraversable dirs. */\nexport function dirMode(mode: number): number {\n return (mode & 0o7777) | 0o111;\n}\n\nclass ChunkedReader {\n private readonly buf: Buffer;\n private start = 0;\n private end = 0;\n private position = 0;\n\n constructor(\n private readonly fh: Pick<FileHandle, \"read\">,\n chunkSize: number,\n ) {\n this.buf = Buffer.allocUnsafe(Math.max(1, chunkSize));\n }\n\n async take(n: number): Promise<Buffer> {\n const out = Buffer.allocUnsafe(n);\n let filled = 0;\n while (filled < n) {\n if (this.start === this.end) {\n if (n - filled >= this.buf.byteLength) {\n filled += await this.readInto(out, filled, n - filled);\n continue;\n }\n this.start = 0;\n this.end = await this.readInto(this.buf, 0, this.buf.byteLength);\n }\n const k = Math.min(this.end - this.start, n - filled);\n this.buf.copy(out, filled, this.start, this.start + k);\n this.start += k;\n filled += k;\n }\n return out;\n }\n\n private async readInto(\n target: Buffer,\n offset: number,\n length: number,\n ): Promise<number> {\n const { bytesRead } = await this.fh.read(\n target,\n offset,\n Math.min(length, this.buf.byteLength),\n this.position,\n );\n if (bytesRead <= 0) {\n throw new Error(\"snapshot.bin: truncated snapshot\");\n }\n this.position += bytesRead;\n return bytesRead;\n }\n}\n","import type { ILogger } from \"document-model\";\nimport { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { extractSnapshot, SNAPSHOT_FILE_NAME } from \"./snapshot-reader.js\";\nimport { syncDirectory, syncTree, type SyncTreeHostFs } from \"./sync-tree.js\";\n\nexport interface VerifyHandle {\n query<T>(sql: string): Promise<{ rows: T[] }>;\n close(): Promise<void>;\n}\n\nexport type ConversionStep =\n | \"extract\"\n | \"verify\"\n | \"renameOld\"\n | \"renameNew\"\n | \"removeOld\";\n\nexport interface ConversionDeps {\n /** Opens `dataDir` with the stock NodeFS of the PGlite module for `major`. */\n openForVerify: (major: number, dataDir: string) => Promise<VerifyHandle>;\n logger: ILogger;\n /** Test hook: throw after a named step to simulate a crash there. */\n afterStep?: (step: ConversionStep) => void | Promise<void>;\n hostFs?: SyncTreeHostFs;\n}\n\n// Backoff doubles per retry; five keeps a scanner-held file to ~3 s.\nconst RM_OPTIONS = {\n recursive: true,\n force: true,\n maxRetries: 5,\n retryDelay: 100,\n} as const;\n\ninterface Siblings {\n dir: string;\n converting: string;\n old: string;\n snapshot: string;\n}\n\nfunction siblingsOf(dir: string): Siblings {\n const resolved = path.resolve(dir);\n return {\n dir: resolved,\n converting: `${resolved}.converting`,\n old: `${resolved}.old`,\n snapshot: path.join(resolved, SNAPSHOT_FILE_NAME),\n };\n}\n\n/** Settles the debris of an interrupted conversion; runs before it at boot. */\nexport async function recoverConversion(\n dir: string,\n deps: ConversionDeps,\n): Promise<void> {\n const s = siblingsOf(dir);\n const [dirExists, convertingExists, oldExists] = await Promise.all([\n exists(s.dir),\n exists(s.converting),\n exists(s.old),\n ]);\n\n if (!dirExists) {\n if (convertingExists) {\n // Died between the two renames: finish the swap.\n await fs.rename(s.converting, s.dir);\n if (oldExists) await fs.rm(s.old, RM_OPTIONS);\n deps.logger.warn(\n `PGlite conversion of ${s.dir} was interrupted after the swap started; completed it`,\n );\n return;\n }\n if (oldExists) {\n throw new Error(\n `PGlite data dir ${s.dir} is missing but ${s.old} exists; refusing to initialize beside it. Inspect and rename or remove ${s.old}.`,\n );\n }\n return;\n }\n\n const snapshotExists = await exists(s.snapshot);\n if (snapshotExists) {\n // The snapshot is authoritative; anything beside it is debris.\n if (convertingExists) await fs.rm(s.converting, RM_OPTIONS);\n if (oldExists) await fs.rm(s.old, RM_OPTIONS);\n return;\n }\n\n // dir is a converted PGDATA; anything beside it is superseded.\n if (oldExists) await fs.rm(s.old, RM_OPTIONS);\n if (convertingExists) {\n deps.logger.warn(\n `Removing stray ${s.converting}; ${s.dir} holds no snapshot and is authoritative`,\n );\n await fs.rm(s.converting, RM_OPTIONS);\n }\n}\n\n/** Extracts into `.converting`, verifies by opening it, swaps through `.old`. */\nexport async function convertSnapshotDir(\n dir: string,\n deps: ConversionDeps,\n): Promise<\"converted\" | \"none\"> {\n const s = siblingsOf(dir);\n if (!(await exists(s.snapshot))) return \"none\";\n\n const startedAt = performance.now();\n await fs.rm(s.converting, RM_OPTIONS);\n await fs.mkdir(s.converting, { mode: 0o700 });\n\n let snapshotBytes: number;\n let entries: number;\n try {\n ({ bytes: snapshotBytes, entries } = await extractAndVerify(s, deps));\n } catch (err) {\n await fs.rm(s.converting, RM_OPTIONS);\n throw err;\n }\n\n // Parent synced after each rename: a power loss lands on one recovery row.\n const parent = path.dirname(s.dir);\n await fs.rename(s.dir, s.old);\n syncDirectory(parent, deps.hostFs);\n await deps.afterStep?.(\"renameOld\");\n await fs.rename(s.converting, s.dir);\n syncDirectory(parent, deps.hostFs);\n await deps.afterStep?.(\"renameNew\");\n try {\n await fs.rm(s.old, RM_OPTIONS);\n } catch (err) {\n // The converted dir is in place; recoverConversion removes .old next boot.\n deps.logger.warn(\n `Could not remove ${s.old} after conversion; it is removed at the next boot: ${String(err)}`,\n );\n }\n await deps.afterStep?.(\"removeOld\");\n\n const convertedBytes = await treeBytes(s.dir);\n const durationMs = Math.round(performance.now() - startedAt);\n deps.logger.info(\n `Converted PGlite snapshot at ${s.dir}: snapshot ${snapshotBytes} bytes -> ${convertedBytes} bytes on disk, ${entries} entries, ${durationMs} ms`,\n );\n return \"converted\";\n}\n\nasync function extractAndVerify(\n s: Siblings,\n deps: ConversionDeps,\n): Promise<{ bytes: number; entries: number }> {\n const extracted = await extractSnapshot(s.snapshot, s.converting, {\n sync: false,\n });\n await deps.afterStep?.(\"extract\");\n\n if (!extracted.pgControl) {\n throw new Error(`${s.snapshot} has no global/pg_control entry`);\n }\n const expectedIdentifier = extracted.pgControl.readBigUInt64LE(0).toString();\n const handle = await deps.openForVerify(\n extracted.pgVersionMajor,\n s.converting,\n );\n try {\n await verifyOpenStore(handle, expectedIdentifier);\n } finally {\n // Must close before the renames; Windows refuses to rename an open dir.\n await handle.close();\n }\n await fs.rm(path.join(s.converting, \"postmaster.pid\"), { force: true });\n if (await exists(path.join(s.converting, SNAPSHOT_FILE_NAME))) {\n throw new Error(\n `Extracted PGlite data dir ${s.converting} contains ${SNAPSHOT_FILE_NAME}`,\n );\n }\n // One pass covers the extraction and the verify open's own writes.\n syncTree(s.converting, deps.hostFs);\n await deps.afterStep?.(\"verify\");\n return { bytes: extracted.bytes, entries: extracted.entries };\n}\n\nasync function verifyOpenStore(\n handle: VerifyHandle,\n expectedIdentifier: string,\n): Promise<void> {\n // numeric parses to a float above 2^53; compare as text.\n const ident = await handle.query<{ system_identifier: string }>(\n \"SELECT system_identifier::text AS system_identifier FROM pg_control_system()\",\n );\n const actual = ident.rows[0]?.system_identifier;\n if (actual !== expectedIdentifier) {\n throw new Error(\n `PGlite system identifier mismatch after extraction: pg_control says ${expectedIdentifier}, server says ${String(actual)}`,\n );\n }\n const tables = await handle.query<{ qualified: string }>(\n \"SELECT format('%I.%I', schemaname, tablename) AS qualified FROM pg_tables WHERE schemaname NOT IN ('pg_catalog', 'information_schema') ORDER BY 1\",\n );\n for (const { qualified } of tables.rows) {\n await handle.query(`SELECT count(*) FROM ${qualified}`);\n }\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await fs.lstat(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function treeBytes(dir: string): Promise<number> {\n let total = 0;\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n total += await treeBytes(full);\n } else if (entry.isFile()) {\n total += (await fs.stat(full)).size;\n }\n }\n return total;\n}\n","import { PGlite } from \"@electric-sql/pglite\";\nimport { NodeFS } from \"@electric-sql/pglite/nodefs\";\nimport type { ILogger } from \"document-model\";\nimport { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n convertSnapshotDir,\n recoverConversion,\n type ConversionDeps,\n type VerifyHandle,\n} from \"./convert-snapshot-dir.js\";\n\n/** PG major of the pinned @electric-sql/pglite; it exports none, so the test checks initdb. */\nexport const CURRENT_PGLITE_MAJOR = 17;\n\n/** `openForVerify` over the loaded PGlite module only. */\nexport async function openCurrentPgliteForVerify(\n major: number,\n dataDir: string,\n): Promise<VerifyHandle> {\n if (major !== CURRENT_PGLITE_MAJOR) {\n throw new Error(\n `PGlite snapshot at ${dataDir} is PG${major}; this process only opens PG${CURRENT_PGLITE_MAJOR} data dirs`,\n );\n }\n const pg = new PGlite({ fs: new NodeFS(dataDir) });\n await pg.waitReady;\n return pg;\n}\n\n/** Converts a snapshot store and clears the files a previous run leaves behind. */\nexport async function preparePgliteDataDir(\n dir: string,\n deps: ConversionDeps,\n): Promise<void> {\n await recoverConversion(dir, deps);\n await convertSnapshotDir(dir, deps);\n await removeStalePgliteFiles(dir, deps.logger);\n}\n\n/** PGlite leaves `postmaster.pid` after every close and `pg_wal/xlogtemp.*` after some. */\nexport async function removeStalePgliteFiles(\n dir: string,\n logger: Pick<ILogger, \"debug\">,\n): Promise<void> {\n const lockfile = path.join(dir, \"postmaster.pid\");\n let hadLockfile = true;\n try {\n await fs.unlink(lockfile);\n } catch {\n hadLockfile = false;\n }\n if (hadLockfile) logger.debug(`Removed PGlite lockfile ${lockfile}`);\n\n const walDir = path.join(dir, \"pg_wal\");\n let names: string[];\n try {\n names = await fs.readdir(walDir);\n } catch {\n return;\n }\n for (const name of names) {\n if (!name.startsWith(\"xlogtemp.\")) continue;\n await fs.rm(path.join(walDir, name), { force: true });\n logger.debug(`Removed PGlite temp WAL file ${path.join(walDir, name)}`);\n }\n}\n","import v8 from \"node:v8\";\n\nexport const WASM_WRAPPER_TIERING_FLAG =\n \"--wasm-wrapper-tiering-budget=1000000000\";\n\nlet applied = false;\n\n/** Node 24 V8 double-frees tiered wasm wrappers as instances die (#66366). */\nexport function disableWasmWrapperTiering(): boolean {\n // TODO(nodejs/node#66376): narrow to 24.x releases older than the backport.\n if (applied || process.versions.node.split(\".\")[0] !== \"24\") return false;\n v8.setFlagsFromString(WASM_WRAPPER_TIERING_FLAG);\n applied = true;\n return true;\n}\n","/** Base class for failures of the worker itself, as opposed to SQL errors. */\nexport class PGliteWorkerError extends Error {\n constructor(\n readonly label: string,\n message: string,\n options?: { cause?: unknown },\n ) {\n super(message, options);\n this.name = \"PGliteWorkerError\";\n }\n}\n\n/** The worker could not open its store; every call on the stand-in fails with this. */\nexport class PGliteWorkerInitError extends PGliteWorkerError {\n constructor(label: string, options?: { cause?: unknown }) {\n super(\n label,\n `PGlite worker for ${label} failed to open its store`,\n options,\n );\n this.name = \"PGliteWorkerInitError\";\n }\n}\n\n/** The worker thread exited (crash, terminate, out of memory) before answering. */\nexport class PGliteWorkerExitedError extends PGliteWorkerError {\n constructor(\n label: string,\n readonly exitCode: number,\n options?: { cause?: unknown },\n ) {\n super(\n label,\n `PGlite worker for ${label} exited with code ${exitCode}`,\n options,\n );\n this.name = \"PGliteWorkerExitedError\";\n }\n}\n\n/** A call was made after `close()` started. */\nexport class PGliteWorkerClosedError extends PGliteWorkerError {\n constructor(label: string) {\n super(label, `PGlite worker for ${label} is closed`);\n this.name = \"PGliteWorkerClosedError\";\n }\n}\n","import type {\n TableRewriteRequest,\n TableRewriteResult,\n} from \"@powerhousedao/reactor\";\n\n/**\n * Wire protocol between a {@link ThreadedPGlite} stand-in on the main thread\n * and the worker thread that owns one PGlite store.\n *\n * Every payload is structured-cloned, so it holds data only: functions such as\n * row parsers are named by preset and built inside the worker.\n */\n\n/** Module specifiers the worker imports PGlite and its NodeFS from. */\nexport type PGliteModuleSpec = {\n /** Specifier or file URL of the PGlite package entry, e.g. `@electric-sql/pglite`. */\n pglite: string;\n /** Specifier or file URL of the matching NodeFS entry, e.g. `@electric-sql/pglite/nodefs`. */\n nodefs: string;\n};\n\nexport const CURRENT_PGLITE_MODULE: PGliteModuleSpec = {\n pglite: \"@electric-sql/pglite\",\n nodefs: \"@electric-sql/pglite/nodefs\",\n};\n\n/** Row parser sets the worker knows how to build. */\nexport type PGliteParserPreset = \"none\" | \"utc-timestamps\";\n\n/** DurableNodeFs settings; see `DurableNodeFsOptions`. */\nexport type PGliteWorkerDurableFsOptions = {\n fsync: boolean;\n /** Undefined keeps the DurableNodeFs default (5 min); 0 disables. */\n maintenanceIntervalMs?: number;\n /** Undefined keeps the DurableNodeFs default (256 MB); 0 disables. */\n vacuumFullAboveBytes?: number;\n /** Undefined keeps the DurableNodeFs default (60 s); 0 runs VACUUM FULL on the first pass. */\n vacuumFullQuietMs?: number;\n /** Undefined keeps the DurableNodeFs default (0: the quiet window only); a deadline in ms forces the run past it. */\n vacuumFullMaxDeferMs?: number;\n /** Undefined keeps the DurableNodeFs default (1 s). */\n rewriteQuietMs?: number;\n};\n\n/** What the worker opens. */\nexport type PGliteWorkerStoreOptions = {\n /** Names the store in logs and errors, e.g. `read-storage`. */\n label: string;\n /** PGlite data dir; null opens an in-memory store. */\n dataDir: string | null;\n module: PGliteModuleSpec;\n /** DurableNodeFs over `dataDir`; null uses the module's stock NodeFS. Ignored in memory. */\n durableFs: PGliteWorkerDurableFsOptions | null;\n parsers: PGliteParserPreset;\n};\n\n/** The structured-clonable subset of PGlite's `QueryOptions`. */\nexport type WorkerQueryOptions = {\n rowMode?: \"object\" | \"array\";\n paramTypes?: number[];\n};\n\nexport type PGliteErrorInfo = {\n name: string;\n message: string;\n stack?: string;\n cause?: PGliteErrorInfo;\n /** Postgres error fields, copied when present. */\n fields: Record<string, string>;\n};\n\nexport type WorkerResults = {\n rows: unknown[];\n affectedRows?: number;\n fields: { name: string; dataTypeID: number }[];\n};\n\nexport type InitRequest = {\n type: \"init\";\n id: number;\n store: PGliteWorkerStoreOptions;\n};\n\nexport type QueryRequest = {\n type: \"query\";\n id: number;\n /** The reservation this statement runs under, or null for the request queue. */\n admission: number | null;\n sql: string;\n params: unknown[];\n options: WorkerQueryOptions;\n};\n\nexport type ExecRequest = {\n type: \"exec\";\n id: number;\n admission: number | null;\n sql: string;\n options: WorkerQueryOptions;\n};\n\nexport type CloseRequest = {\n type: \"close\";\n id: number;\n};\n\n/**\n * Asks for the connection: answered with `admitted` once everything queued\n * ahead (requests and maintenance passes) has finished. Until the matching\n * `release`, the worker runs only statements tagged with this reservation.\n */\nexport type ReserveRequest = {\n type: \"reserve\";\n id: number;\n};\n\n/**\n * Rewrites one table through the store's maintenance. Runs beside the request\n * queue, since it waits for a quiet store; the rewrite itself takes its turn.\n */\nexport type RewriteTableRequest = {\n type: \"rewrite-table\";\n id: number;\n request: TableRewriteRequest;\n};\n\n/** Ends a reservation; the request queue resumes. Not answered. */\nexport type ReleaseRequest = {\n type: \"release\";\n id: number;\n};\n\n/** Asks for the store's memory; answered outside the admission queue. */\nexport type StatsRequest = {\n type: \"stats\";\n id: number;\n};\n\nexport type HostMessage =\n | StatsRequest\n | InitRequest\n | QueryRequest\n | ExecRequest\n | CloseRequest\n | ReserveRequest\n | ReleaseRequest\n | RewriteTableRequest;\n\nexport type StatsMessage = {\n type: \"stats-result\";\n id: number;\n /** Bytes of WASM linear memory; 0 before the store has opened. */\n wasmBytes: number;\n};\n\nexport type AdmittedMessage = {\n type: \"admitted\";\n id: number;\n inTransaction: boolean;\n};\n\nexport type ReadyMessage = {\n type: \"ready\";\n id: number;\n inTransaction: boolean;\n};\n\nexport type QueryResultMessage = {\n type: \"query-result\";\n id: number;\n result: WorkerResults;\n inTransaction: boolean;\n};\n\nexport type ExecResultMessage = {\n type: \"exec-result\";\n id: number;\n results: WorkerResults[];\n inTransaction: boolean;\n};\n\nexport type RewriteTableResultMessage = {\n type: \"rewrite-table-result\";\n id: number;\n result: TableRewriteResult;\n inTransaction: boolean;\n};\n\nexport type ClosedMessage = {\n type: \"closed\";\n id: number;\n};\n\nexport type ErrorMessage = {\n type: \"error\";\n id: number;\n error: PGliteErrorInfo;\n inTransaction: boolean;\n};\n\n/** The wasm runtime aborted (a Postgres PANIC); the store is dead. */\nexport type AbortMessage = {\n type: \"abort\";\n reason: string;\n};\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport type LogMessage = {\n type: \"log\";\n level: LogLevel;\n message: string;\n error?: PGliteErrorInfo;\n};\n\nexport type WorkerMessage =\n | StatsMessage\n | AdmittedMessage\n | ReadyMessage\n | QueryResultMessage\n | ExecResultMessage\n | RewriteTableResultMessage\n | ClosedMessage\n | ErrorMessage\n | AbortMessage\n | LogMessage;\n","import type { QueryOptions, Results } from \"@electric-sql/pglite\";\nimport {\n registerTelemetryWorker,\n type IStoreMaintenance,\n type TableRewriteRequest,\n type TableRewriteResult,\n type WorkerMemorySample,\n} from \"@powerhousedao/reactor\";\nimport { childLogger, type ILogger } from \"document-model\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { Worker, type ResourceLimits } from \"node:worker_threads\";\nimport type { PGliteLike } from \"../pglite-like.js\";\nimport { disableWasmWrapperTiering } from \"../wasm-wrapper-tiering.js\";\nimport { fromPGliteErrorInfo } from \"./error-info.js\";\nimport {\n PGliteWorkerClosedError,\n PGliteWorkerExitedError,\n PGliteWorkerInitError,\n} from \"./errors.js\";\nimport type {\n HostMessage,\n LogMessage,\n PGliteWorkerStoreOptions,\n WorkerMessage,\n WorkerQueryOptions,\n WorkerResults,\n} from \"./protocol.js\";\n\nexport const DEFAULT_PGLITE_WORKER_MEMORY_MB = 1024;\nexport const DEFAULT_PGLITE_WORKER_CLOSE_GRACE_MS = 60_000;\n\nexport type ThreadedPGliteOptions = {\n store: PGliteWorkerStoreOptions;\n /** Caps the worker's JS heap; defaults to {@link resolvePgliteWorkerMemoryMb}. WebAssembly memory is outside it. */\n memoryLimitMb?: number;\n /** The worker script; defaults to the built entry next to this module. Tests pass a tsx bootstrap. */\n workerScript?: string | URL;\n /** Bound on PGlite's own close (its shutdown checkpoint) before the thread is terminated. */\n closeGraceMs?: number;\n logger?: ILogger;\n};\n\n/** Called once, when the worker reports that the wasm runtime aborted. */\nexport type PGliteAbortListener = (reason: string) => void;\n\n/** Called once, when the worker thread is gone; `error` is null after a clean close. */\nexport type PGliteExitListener = (error: Error | null) => void;\n\ntype PendingKind =\n | \"init\"\n | \"query\"\n | \"exec\"\n | \"close\"\n | \"reserve\"\n | \"stats\"\n | \"rewrite\";\n\ntype Pending = {\n kind: PendingKind;\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n};\n\ntype Phase = \"starting\" | \"ready\" | \"closing\" | \"closed\";\n\n/** `PH_PGLITE_WORKER_MEMORY_MB`, else {@link DEFAULT_PGLITE_WORKER_MEMORY_MB}. */\nexport function resolvePgliteWorkerMemoryMb(\n env: Record<string, string | undefined>,\n): number {\n const raw = env.PH_PGLITE_WORKER_MEMORY_MB;\n if (raw === undefined || raw.trim() === \"\") {\n return DEFAULT_PGLITE_WORKER_MEMORY_MB;\n }\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(\n `PH_PGLITE_WORKER_MEMORY_MB must be a positive integer (got: ${raw})`,\n );\n }\n return parsed;\n}\n\n/**\n * Main-thread stand-in for a PGlite instance whose store lives in a worker\n * thread. It has the surface knex-pglite, kysely-pglite-dialect and\n * `HardenedPGliteDialect` use: `waitReady`, `query`, `exec`, a synchronous\n * `isInTransaction()`, `closed` and `close()`.\n *\n * Construction is synchronous and starts the worker; calls made before the\n * worker is ready are queued behind its open. The worker runs requests one at\n * a time in arrival order, and every answer carries the transaction status.\n * The instance is a plain extensible object, since knex stores its own\n * bookkeeping on the connection.\n */\nexport class ThreadedPGlite implements PGliteLike, IStoreMaintenance {\n readonly label: string;\n /** Settles once the worker has opened the store; rejects with {@link PGliteWorkerInitError}. */\n readonly waitReady: Promise<void>;\n\n private readonly worker: Worker;\n private readonly logger: ILogger;\n private readonly closeGraceMs: number;\n private readonly pending = new Map<number, Pending>();\n /** The reservation an `admit` run is executing under, carried through its async calls. */\n private readonly admission = new AsyncLocalStorage<number>();\n private readonly abortListeners = new Set<PGliteAbortListener>();\n private readonly exitListeners = new Set<PGliteExitListener>();\n private nextId = 1;\n private phase: Phase = \"starting\";\n private inTransaction = false;\n private terminalError: Error | null = null;\n private workerError: Error | null = null;\n private abortReason: string | null = null;\n private closePromise: Promise<void> | null = null;\n private readonly forgetTelemetry: () => void;\n\n constructor(options: ThreadedPGliteOptions) {\n this.label = options.store.label;\n this.logger =\n options.logger ??\n childLogger([\"reactor-api\", \"pglite-worker\", this.label]);\n this.closeGraceMs =\n options.closeGraceMs ?? DEFAULT_PGLITE_WORKER_CLOSE_GRACE_MS;\n const memoryLimitMb =\n options.memoryLimitMb ?? resolvePgliteWorkerMemoryMb(process.env);\n\n const workerScript = options.workerScript ?? pgliteWorkerEntryPath;\n if (workerScript === null) {\n throw new Error(\n \"No PGlite worker script is available: build @powerhousedao/reactor-api or pass workerScript\",\n );\n }\n disableWasmWrapperTiering();\n this.worker = new Worker(workerScript, {\n name: `pglite:${this.label}`,\n resourceLimits: { maxOldGenerationSizeMb: memoryLimitMb },\n });\n this.worker.on(\"message\", (msg: WorkerMessage) => this.handleMessage(msg));\n this.worker.on(\"error\", (err: Error) => this.handleWorkerError(err));\n this.worker.on(\"exit\", (code: number) => this.handleExit(code));\n this.forgetTelemetry = registerTelemetryWorker(`pglite:${this.label}`, () =>\n this.memoryStats(),\n );\n\n this.waitReady = this.request<void>(\"init\", (id) => ({\n type: \"init\",\n id,\n store: options.store,\n })).then(\n () => {\n if (this.phase === \"starting\") {\n this.phase = \"ready\";\n }\n },\n (error: unknown) => {\n const initError =\n error instanceof PGliteWorkerInitError\n ? error\n : new PGliteWorkerInitError(this.label, { cause: error });\n this.fail(initError);\n throw initError;\n },\n );\n this.waitReady.catch(() => undefined);\n }\n\n /** JS heap of the worker and the WASM linear memory, which only grows. */\n async memoryStats(): Promise<WorkerMemorySample> {\n const [heap, wasm] = await Promise.all([\n this.worker.getHeapStatistics(),\n this.request<number>(\"stats\", (id) => ({ type: \"stats\", id })),\n ]);\n return { heapUsed: heap.used_heap_size, wasm };\n }\n\n /** True once the store is open and until close starts. */\n get ready(): boolean {\n return this.phase === \"ready\";\n }\n\n /** True once close has started or the worker is gone. */\n get closed(): boolean {\n return this.phase === \"closing\" || this.phase === \"closed\";\n }\n\n /** The reason the worker reported for a wasm abort, or null. */\n get aborted(): string | null {\n return this.abortReason;\n }\n\n /** The limits the worker thread runs under (empty once it has exited). */\n get resourceLimits(): ResourceLimits {\n return this.worker.resourceLimits ?? {};\n }\n\n /** The worker's thread id, for diagnostics. */\n get threadId(): number {\n return this.worker.threadId;\n }\n\n async query<T = Record<string, unknown>>(\n sql: string,\n params?: unknown[],\n options?: QueryOptions,\n ): Promise<Results<T>> {\n const wireOptions = toWireOptions(options);\n const result = await this.request<WorkerResults>(\"query\", (id) => ({\n type: \"query\",\n id,\n admission: this.currentAdmission(),\n sql,\n params: params ?? [],\n options: wireOptions,\n }));\n return toResults<T>(result);\n }\n\n async exec(sql: string, options?: QueryOptions): Promise<Results[]> {\n const wireOptions = toWireOptions(options);\n const results = await this.request<WorkerResults[]>(\"exec\", (id) => ({\n type: \"exec\",\n id,\n admission: this.currentAdmission(),\n sql,\n options: wireOptions,\n }));\n return results.map((result) => toResults(result));\n }\n\n /**\n * `HardenedPGliteDialect`'s admission hook: `run` starts only once the worker\n * can run its statements at once, with nothing queued ahead and no\n * maintenance pass in progress, so the dialect's statement deadline (which\n * starts inside `run`) never counts time spent waiting behind other work.\n * Statements `run` issues bypass the queue until it settles; everything\n * else waits behind them.\n */\n async admit<T>(run: () => Promise<T>): Promise<T> {\n let reservation = 0;\n await this.request<void>(\"reserve\", (id) => {\n reservation = id;\n return { type: \"reserve\", id };\n });\n try {\n return await this.admission.run(reservation, run);\n } finally {\n this.release(reservation);\n }\n }\n\n /** Rewrites one table through the store's maintenance inside the worker. */\n rewriteTable(request: TableRewriteRequest): Promise<TableRewriteResult> {\n return this.request<TableRewriteResult>(\"rewrite\", (id) => ({\n type: \"rewrite-table\",\n id,\n request,\n }));\n }\n\n /** The status after the most recently answered request, as PGlite reported it. */\n isInTransaction(): boolean {\n return this.inTransaction;\n }\n\n /** Closes PGlite inside the worker (its shutdown checkpoint), then terminates the thread. */\n close(): Promise<void> {\n if (this.closePromise !== null) {\n return this.closePromise;\n }\n if (this.phase === \"closed\") {\n return Promise.resolve();\n }\n this.closePromise = this.closeWorker();\n return this.closePromise;\n }\n\n /** Stops the thread at once, without PGlite's close; pending calls reject. */\n async terminate(): Promise<void> {\n if (this.phase === \"closed\") {\n return;\n }\n await this.worker.terminate();\n }\n\n onAbort(listener: PGliteAbortListener): () => void {\n this.abortListeners.add(listener);\n return () => {\n this.abortListeners.delete(listener);\n };\n }\n\n onExit(listener: PGliteExitListener): () => void {\n this.exitListeners.add(listener);\n return () => {\n this.exitListeners.delete(listener);\n };\n }\n\n private async closeWorker(): Promise<void> {\n if (this.terminalError !== null) {\n this.phase = \"closing\";\n await this.worker.terminate();\n return;\n }\n const closing = this.request<void>(\"close\", (id) => ({\n type: \"close\",\n id,\n }));\n this.phase = \"closing\";\n let timer: ReturnType<typeof setTimeout> | undefined;\n const grace = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), this.closeGraceMs);\n });\n let outcome: \"closed\" | \"timeout\" = \"closed\";\n let closeError: Error | null = null;\n try {\n outcome = await Promise.race([\n closing.then(() => \"closed\" as const),\n grace,\n ]);\n } catch (error) {\n closeError = error instanceof Error ? error : new Error(String(error));\n } finally {\n clearTimeout(timer);\n }\n if (outcome === \"timeout\") {\n this.logger.warn(\n `PGlite worker for ${this.label} did not close within ${this.closeGraceMs}ms; terminating`,\n );\n }\n await this.worker.terminate();\n if (closeError !== null) {\n throw closeError;\n }\n }\n\n private currentAdmission(): number | null {\n return this.admission.getStore() ?? null;\n }\n\n private release(reservation: number): void {\n if (this.phase === \"closed\") {\n return;\n }\n const message: HostMessage = { type: \"release\", id: reservation };\n this.worker.postMessage(message);\n }\n\n private request<T>(\n kind: PendingKind,\n build: (id: number) => HostMessage,\n ): Promise<T> {\n if (this.terminalError !== null) {\n return Promise.reject(this.terminalError);\n }\n if (kind !== \"init\" && this.closed) {\n return Promise.reject(new PGliteWorkerClosedError(this.label));\n }\n const id = this.nextId++;\n const promise = new Promise<T>((resolve, reject) => {\n this.pending.set(id, {\n kind,\n resolve: resolve as (value: unknown) => void,\n reject,\n });\n });\n this.worker.postMessage(build(id));\n return promise;\n }\n\n private handleMessage(msg: WorkerMessage): void {\n switch (msg.type) {\n case \"admitted\":\n this.settle(msg.id, msg.inTransaction, undefined);\n return;\n case \"ready\":\n this.settle(msg.id, msg.inTransaction, undefined);\n return;\n case \"query-result\":\n this.settle(msg.id, msg.inTransaction, msg.result);\n return;\n case \"exec-result\":\n this.settle(msg.id, msg.inTransaction, msg.results);\n return;\n case \"stats-result\":\n this.settle(msg.id, this.inTransaction, msg.wasmBytes);\n return;\n case \"rewrite-table-result\":\n this.settle(msg.id, msg.inTransaction, msg.result);\n return;\n case \"closed\":\n this.settle(msg.id, false, undefined);\n return;\n case \"error\":\n this.settleError(\n msg.id,\n msg.inTransaction,\n fromPGliteErrorInfo(msg.error),\n );\n return;\n case \"abort\":\n this.handleAbort(msg.reason);\n return;\n case \"log\":\n this.handleLog(msg);\n return;\n default: {\n const exhaustive: never = msg;\n void exhaustive;\n }\n }\n }\n\n private settle(id: number, inTransaction: boolean, value: unknown): void {\n this.inTransaction = inTransaction;\n const entry = this.pending.get(id);\n if (entry === undefined) {\n return;\n }\n this.pending.delete(id);\n entry.resolve(value);\n }\n\n private settleError(id: number, inTransaction: boolean, error: Error): void {\n this.inTransaction = inTransaction;\n const entry = this.pending.get(id);\n if (entry === undefined) {\n return;\n }\n this.pending.delete(id);\n entry.reject(error);\n }\n\n private handleAbort(reason: string): void {\n if (this.abortReason !== null) {\n return;\n }\n this.abortReason = reason;\n this.logger.error(\n `PGlite worker for ${this.label} aborted: @reason`,\n reason,\n );\n for (const listener of [...this.abortListeners]) {\n try {\n listener(reason);\n } catch (error) {\n this.logger.error(\"PGlite abort listener threw: @error\", error);\n }\n }\n }\n\n private handleLog(msg: LogMessage): void {\n const message = `[${this.label}] ${msg.message}`;\n const args =\n msg.error === undefined ? [] : [fromPGliteErrorInfo(msg.error)];\n const template = args.length > 0 ? `${message}: @error` : message;\n switch (msg.level) {\n case \"debug\":\n this.logger.debug(template, ...args);\n return;\n case \"info\":\n this.logger.info(template, ...args);\n return;\n case \"warn\":\n this.logger.warn(template, ...args);\n return;\n case \"error\":\n this.logger.error(template, ...args);\n return;\n default: {\n const exhaustive: never = msg.level;\n void exhaustive;\n }\n }\n }\n\n private handleWorkerError(err: Error): void {\n this.workerError = err;\n this.logger.error(`PGlite worker for ${this.label} failed: @error`, err);\n }\n\n private handleExit(code: number): void {\n this.forgetTelemetry();\n const graceful = this.phase === \"closing\" && this.terminalError === null;\n this.phase = \"closed\";\n this.inTransaction = false;\n const error = graceful\n ? null\n : (this.terminalError ??\n new PGliteWorkerExitedError(this.label, code, {\n cause: this.workerError ?? undefined,\n }));\n if (error !== null && this.terminalError === null) {\n this.terminalError = error;\n }\n this.rejectPending(error ?? new PGliteWorkerClosedError(this.label));\n for (const listener of [...this.exitListeners]) {\n try {\n listener(error);\n } catch (listenerError) {\n this.logger.error(\"PGlite exit listener threw: @error\", listenerError);\n }\n }\n this.exitListeners.clear();\n this.abortListeners.clear();\n }\n\n /** Records a fatal error and stops the thread; the exit rejects what is pending. */\n private fail(error: Error): void {\n if (this.terminalError === null) {\n this.terminalError = error;\n }\n this.rejectPending(error);\n void this.worker.terminate();\n }\n\n private rejectPending(error: Error): void {\n const entries = [...this.pending.values()];\n this.pending.clear();\n for (const entry of entries) {\n entry.reject(error);\n }\n }\n}\n\nfunction toWireOptions(options: QueryOptions | undefined): WorkerQueryOptions {\n if (options === undefined) {\n return {};\n }\n if (\n options.parsers !== undefined ||\n options.serializers !== undefined ||\n options.blob !== undefined ||\n options.onNotice !== undefined\n ) {\n throw new Error(\n \"ThreadedPGlite does not support parsers, serializers, blob or onNotice per query; configure parsers on the worker\",\n );\n }\n const wire: WorkerQueryOptions = {};\n if (options.rowMode !== undefined) {\n wire.rowMode = options.rowMode;\n }\n if (options.paramTypes !== undefined) {\n wire.paramTypes = options.paramTypes;\n }\n return wire;\n}\n\nfunction toResults<T>(result: WorkerResults): Results<T> {\n const out: Results<T> = {\n rows: result.rows as T[],\n fields: result.fields,\n };\n if (result.affectedRows !== undefined) {\n out.affectedRows = result.affectedRows;\n }\n return out;\n}\n\n/**\n * The worker script: the built entry (chunking may place this module in\n * `dist/` or `dist/src/pglite/`), or, when this module runs from its\n * TypeScript source, a bootstrap that loads the entry through tsx. Null when\n * neither is available.\n */\nfunction resolvePgliteWorkerEntryPath(): string | null {\n if (/\\.m?ts$/.test(new URL(import.meta.url).pathname)) {\n return resolveSourceBootstrap();\n }\n const candidates = [\n \"./src/pglite/worker/entry.mjs\",\n \"./worker/entry.mjs\",\n \"./entry.mjs\",\n ].map((relative) => fileUrlToPath(new URL(relative, import.meta.url)));\n return candidates.find((candidate) => existsSync(candidate)) ?? null;\n}\n\nfunction resolveSourceBootstrap(): string | null {\n const bootstrap = fileUrlToPath(\n new URL(\"./source-bootstrap.mjs\", import.meta.url),\n );\n if (!existsSync(bootstrap)) {\n return null;\n }\n try {\n createRequire(import.meta.url).resolve(\"tsx/esm/api\");\n } catch {\n return null;\n }\n return bootstrap;\n}\n\nfunction fileUrlToPath(url: URL): string {\n if (url.protocol !== \"file:\") {\n return url.href;\n }\n let pathname = decodeURIComponent(url.pathname);\n if (/^\\/[A-Za-z]:[/\\\\]/.test(pathname)) {\n pathname = pathname.slice(1);\n }\n return pathname;\n}\n\n/** Absolute path of the worker script for `new Worker(...)`; null when none can run here. */\nexport const pgliteWorkerEntryPath = resolvePgliteWorkerEntryPath();\n"],"names":["fs","fs","fs"],"mappings":";;;;;;;;;;;;;;AAMA,MAAa,qBAAqB;AAClC,MAAM,QAAQ,IAAI,WAAW;CAAC;CAAM;CAAM;CAAM;AAAI,CAAC;AACrD,MAAM,iBAAiB;AACvB,MAAM,cAAc;AACpB,MAAM,oBAAoB;AAC1B,MAAM,kCAAkB,IAAI,IAAI,CAAC,gBAAgB,CAAC;AAElD,MAAM,wBAAwB;;AAoB9B,eAAsB,gBACpB,cACA,QACA,UAAkC,CAAC,GACP;CAC5B,MAAM,KAAK,MAAMA,SAAG,KAAK,cAAc,GAAG;CAC1C,IAAI;EACF,MAAM,EAAE,SAAS,MAAM,GAAG,KAAK;EAC/B,OAAO,MAAM,kBAAkB,IAAI,MAAM,QAAQ,OAAO;CAC1D,UAAU;EACR,MAAM,GAAG,MAAM;CACjB;AACF;AAEA,eAAe,kBACb,IACA,UACA,QACA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e82-5d46-982c-c40ed34f74ce"}
@@ -4,7 +4,7 @@ import { t as DOCUMENT_MODEL_SCHEMA_OWNER } from "../../subgraph-schema-owner-BE
4
4
  //#region src/graphql/subgraph-types.ts
5
5
  /** Loaded on call: the check pulls in the base models and core schemas. */
6
6
  async function findPackageSubgraphConflicts(subgraphs, documentModels) {
7
- const { checkPackageSubgraphs } = await import("../../package-subgraph-check-DxZhf2lB.mjs");
7
+ const { checkPackageSubgraphs } = await import("../../package-subgraph-check-DdZLhOHW.mjs");
8
8
  return checkPackageSubgraphs(subgraphs, documentModels);
9
9
  }
10
10
  //#endregion
@@ -1,5 +1,6 @@
1
1
  import { n as PGLITE_UTC_PARSERS, t as PGliteLike } from "../../pglite-like-CKQEL_Q0.mjs";
2
2
  import { ILogger } from "document-model";
3
+ import { IStoreMaintenance, TableRewriteRequest, TableRewriteResult, WorkerMemorySample } from "@powerhousedao/reactor";
3
4
  import nodeFs from "node:fs";
4
5
  import { PGlite, QueryOptions, Results } from "@electric-sql/pglite";
5
6
  import { NodeFS } from "@electric-sql/pglite/nodefs";
@@ -18,6 +19,14 @@ export declare const DEFAULT_VACUUM_FULL_QUIET_MS: number;
18
19
  export declare const DEFAULT_VACUUM_FULL_MAX_DEFER_MS = 0;
19
20
  /** The deadline `PH_PGLITE_VACUUM_FULL=forced` sets. */
20
21
  export declare const FORCED_VACUUM_FULL_MAX_DEFER_MS: number;
22
+ /**
23
+ * A table rewrite waits for this long a gap between the store's statements.
24
+ * Short, because PGlite syncs after every statement and an idle reactor still
25
+ * reads every 2 s (catch-up, sync polls), so a longer gap never comes.
26
+ */
27
+ export declare const DEFAULT_REWRITE_QUIET_MS = 1000;
28
+ /** How long a table rewrite waits for that gap before it reports the store busy. */
29
+ export declare const DEFAULT_REWRITE_MAX_WAIT_MS: number;
21
30
  type MaintenanceOutcome = "vacuum" | "vacuum-full" | "idle" | "not-ready" | "in-transaction" | "failed";
22
31
  interface MaintenanceLogger {
23
32
  warn(message: string): void;
@@ -53,8 +62,12 @@ interface MaintenanceOptions {
53
62
  logger?: MaintenanceLogger;
54
63
  /** Clock for the quiet window; tests pass their own. */
55
64
  now?: () => number;
65
+ /** The gap between statements a table rewrite waits for. Default 1 s. */
66
+ rewriteQuietMs?: number;
67
+ /** How long a table rewrite waits for that gap. Default 15 min. */
68
+ rewriteMaxWaitMs?: number;
56
69
  }
57
- export declare class PgliteMaintenance {
70
+ export declare class PgliteMaintenance implements IStoreMaintenance {
58
71
  private readonly intervalMs;
59
72
  private readonly vacuumFullAboveBytes;
60
73
  private readonly vacuumFullQuietMs;
@@ -62,6 +75,8 @@ export declare class PgliteMaintenance {
62
75
  private readonly gate?;
63
76
  private readonly logger?;
64
77
  private readonly now;
78
+ private readonly rewriteQuietMs;
79
+ private readonly rewriteMaxWaitMs;
65
80
  private pg?;
66
81
  private label;
67
82
  private closing;
@@ -73,6 +88,7 @@ export declare class PgliteMaintenance {
73
88
  private deferralLogged;
74
89
  private lastSyncAt;
75
90
  private openedAt;
91
+ private rewriting?;
76
92
  constructor(options?: MaintenanceOptions);
77
93
  get scheduled(): boolean;
78
94
  get running(): boolean;
@@ -81,11 +97,25 @@ export declare class PgliteMaintenance {
81
97
  /** Waits for a pass that has started; one still queued at the gate is left to skip itself. */
82
98
  stop(): Promise<void>;
83
99
  run(): Promise<MaintenanceOutcome>;
100
+ /**
101
+ * Rewrites one table with VACUUM FULL and a CHECKPOINT, in the turn of the
102
+ * store's other work, never the whole store. Waits for a gap in the store's
103
+ * statements first; nothing else runs on it while the table is rewritten.
104
+ */
105
+ rewriteTable(request: TableRewriteRequest): Promise<TableRewriteResult>;
84
106
  private runNow;
85
107
  private pass;
108
+ /** Undefined when a transaction is open, so the caller waits and tries again. */
109
+ private rewriteNow;
110
+ /** Why the disk cannot hold the rewrite; undefined when it can or nobody can tell. */
111
+ private diskShortage;
86
112
  private schedule;
87
113
  private cancel;
88
114
  }
115
+ /** The maintenance of a store opened on DurableNodeFs; undefined for any other. */
116
+ export declare function maintenanceOf(store: {
117
+ fs?: unknown;
118
+ }): PgliteMaintenance | undefined;
89
119
  //#endregion
90
120
  //#region src/pglite/durable-node-fs.d.ts
91
121
  type NodeFsClass = typeof NodeFS;
@@ -102,6 +132,10 @@ interface DurableNodeFsOptions {
102
132
  vacuumFullMaxDeferMs?: number;
103
133
  /** See `MaintenanceOptions.gate`. */
104
134
  maintenanceGate?: MaintenanceGate;
135
+ /** The gap between statements a table rewrite waits for. Default 1 s. */
136
+ rewriteQuietMs?: number;
137
+ /** How long a table rewrite waits for that gap. Default 15 min. */
138
+ rewriteMaxWaitMs?: number;
105
139
  /** Clock for the maintenance quiet window; tests pass their own. */
106
140
  now?: () => number;
107
141
  logger?: {
@@ -237,6 +271,8 @@ type PGliteWorkerDurableFsOptions = {
237
271
  vacuumFullQuietMs?: number;
238
272
  /** Undefined keeps the DurableNodeFs default (0: the quiet window only); a deadline in ms forces the run past it. */
239
273
  vacuumFullMaxDeferMs?: number;
274
+ /** Undefined keeps the DurableNodeFs default (1 s). */
275
+ rewriteQuietMs?: number;
240
276
  };
241
277
  /** What the worker opens. */
242
278
  type PGliteWorkerStoreOptions = {
@@ -321,7 +357,7 @@ export declare function resolvePgliteWorkerMemoryMb(env: Record<string, string |
321
357
  * The instance is a plain extensible object, since knex stores its own
322
358
  * bookkeeping on the connection.
323
359
  */
324
- export declare class ThreadedPGlite implements PGliteLike {
360
+ export declare class ThreadedPGlite implements PGliteLike, IStoreMaintenance {
325
361
  readonly label: string;
326
362
  /** Settles once the worker has opened the store; rejects with {@link PGliteWorkerInitError}. */
327
363
  readonly waitReady: Promise<void>;
@@ -340,7 +376,10 @@ export declare class ThreadedPGlite implements PGliteLike {
340
376
  private workerError;
341
377
  private abortReason;
342
378
  private closePromise;
379
+ private readonly forgetTelemetry;
343
380
  constructor(options: ThreadedPGliteOptions);
381
+ /** JS heap of the worker and the WASM linear memory, which only grows. */
382
+ memoryStats(): Promise<WorkerMemorySample>;
344
383
  /** True once the store is open and until close starts. */
345
384
  get ready(): boolean;
346
385
  /** True once close has started or the worker is gone. */
@@ -362,6 +401,8 @@ export declare class ThreadedPGlite implements PGliteLike {
362
401
  * else waits behind them.
363
402
  */
364
403
  admit<T>(run: () => Promise<T>): Promise<T>;
404
+ /** Rewrites one table through the store's maintenance inside the worker. */
405
+ rewriteTable(request: TableRewriteRequest): Promise<TableRewriteResult>;
365
406
  /** The status after the most recently answered request, as PGlite reported it. */
366
407
  isInTransaction(): boolean;
367
408
  /** Closes PGlite inside the worker (its shutdown checkpoint), then terminates the thread. */
@@ -1 +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;;;EAE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,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"}
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":";;;;;;;;qBASa;qBACA;qBACA;;;;;;;;qBAQA;;qBAEA;;;;;;qBAOA;;qBAEA;KAGD;UAQK;EACf,KAAK;;EAEL,MAAM;;;KAII,mBAAmB,GAAG,YAAY,QAAQ,OAAO,QAAQ;UAEpD;;EAEf;;EAEA;;;;;;;EAOA;;;;;;EAMA;;;;;;EAMA,OAAO;EACP,SAAS;;EAET;;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UAQA;;;qBAyFG"}
@@ -1,5 +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
1
+ import { _ as PGLITE_UTC_PARSERS, a as resolvePgliteMaintenance, c as DEFAULT_MAINTENANCE_INTERVAL_MS, d as DEFAULT_VACUUM_FULL_ABOVE_BYTES, f as DEFAULT_VACUUM_FULL_MAX_DEFER_MS, g as maintenanceOf, h as PgliteMaintenance, i as resolvePgliteFsync, l as DEFAULT_REWRITE_MAX_WAIT_MS, m as FORCED_VACUUM_FULL_MAX_DEFER_MS, n as toPGliteErrorInfo, o as syncDirectory, p as DEFAULT_VACUUM_FULL_QUIET_MS, r as createDurableNodeFs, s as syncTree, t as fromPGliteErrorInfo, u as DEFAULT_REWRITE_QUIET_MS } from "../../error-info-Cr6oQACe.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-CcX2YT-l.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_REWRITE_MAX_WAIT_MS, DEFAULT_REWRITE_QUIET_MS, 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, maintenanceOf, 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]="afdaa565-b941-5b93-a8c8-f1f4270baa52")}catch(e){}}();
5
+ //# debugId=afdaa565-b941-5b93-a8c8-f1f4270baa52
@@ -1,6 +1,6 @@
1
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";
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]="b63aadff-40cc-540a-9612-3dfde5cfbb3c")}catch(e){}}();
3
+ import { _ as PGLITE_UTC_PARSERS, g as maintenanceOf, n as toPGliteErrorInfo, r as createDurableNodeFs } from "../../../error-info-Cr6oQACe.mjs";
4
4
  import { isMainThread, parentPort } from "node:worker_threads";
5
5
  //#region src/pglite/worker/run-worker.ts
6
6
  /** A wasm runtime abort, as opposed to a Postgres error (which carries a code). */
@@ -120,6 +120,34 @@ function runPGliteWorker(port) {
120
120
  inTransaction: inTransaction()
121
121
  });
122
122
  }
123
+ async function handleRewriteTable(msg) {
124
+ const maintenance = pg === null ? void 0 : maintenanceOf(pg);
125
+ if (maintenance === void 0) {
126
+ post({
127
+ type: "rewrite-table-result",
128
+ id: msg.id,
129
+ result: {
130
+ outcome: "refused",
131
+ reason: "this store has no maintenance: it is in memory"
132
+ },
133
+ inTransaction: inTransaction()
134
+ });
135
+ return;
136
+ }
137
+ let result;
138
+ try {
139
+ result = await maintenance.rewriteTable(msg.request);
140
+ } catch (error) {
141
+ postError(msg.id, error);
142
+ return;
143
+ }
144
+ post({
145
+ type: "rewrite-table-result",
146
+ id: msg.id,
147
+ result,
148
+ inTransaction: inTransaction()
149
+ });
150
+ }
123
151
  async function handleClose(id) {
124
152
  const instance = pg;
125
153
  closed = true;
@@ -170,11 +198,13 @@ function runPGliteWorker(port) {
170
198
  function handle(msg) {
171
199
  switch (msg.type) {
172
200
  case "reserve": return handleReserve(msg.id);
173
- case "release": return Promise.resolve();
201
+ case "release":
202
+ case "stats": return Promise.resolve();
174
203
  case "init": return handleInit(msg);
175
204
  case "query": return handleQuery(msg);
176
205
  case "exec": return handleExec(msg);
177
206
  case "close": return handleClose(msg.id);
207
+ case "rewrite-table": return handleRewriteTable(msg);
178
208
  default: return Promise.resolve();
179
209
  }
180
210
  }
@@ -194,14 +224,30 @@ function runPGliteWorker(port) {
194
224
  if (admission?.id === msg.id) admission.release();
195
225
  return;
196
226
  }
227
+ if (msg.type === "stats") {
228
+ post({
229
+ type: "stats-result",
230
+ id: msg.id,
231
+ wasmBytes: wasmBytesOf(pg)
232
+ });
233
+ return;
234
+ }
197
235
  const current = admission;
198
236
  if ((msg.type === "query" || msg.type === "exec") && current !== null && msg.admission === current.id) {
199
237
  current.statements = current.statements.then(() => handle(msg));
200
238
  return;
201
239
  }
240
+ if (msg.type === "rewrite-table") {
241
+ handle(msg);
242
+ return;
243
+ }
202
244
  enqueue(() => handle(msg));
203
245
  });
204
246
  }
247
+ /** PGlite's types leave the Emscripten heap out of `Module`. */
248
+ function wasmBytesOf(pg) {
249
+ return (pg?.Module)?.HEAPU8.byteLength ?? 0;
250
+ }
205
251
  async function createPGlite(store, hooks) {
206
252
  const { PGlite: PGliteClass } = await import(store.module.pglite);
207
253
  const options = { parsers: parsersFor(store.parsers) };
@@ -214,6 +260,7 @@ async function createPGlite(store, hooks) {
214
260
  vacuumFullAboveBytes: durable.vacuumFullAboveBytes,
215
261
  vacuumFullQuietMs: durable.vacuumFullQuietMs,
216
262
  vacuumFullMaxDeferMs: durable.vacuumFullMaxDeferMs,
263
+ rewriteQuietMs: durable.rewriteQuietMs,
217
264
  maintenanceGate: hooks.maintenanceGate,
218
265
  logger: { warn: hooks.warn },
219
266
  onAbort: hooks.onAbort
@@ -248,4 +295,4 @@ runPGliteWorker(parentPort);
248
295
  export {};
249
296
 
250
297
  //# sourceMappingURL=entry.mjs.map
251
- //# debugId=190de489-10fe-547d-8123-7e3a65865685
298
+ //# debugId=b63aadff-40cc-540a-9612-3dfde5cfbb3c