@powerhousedao/reactor-api 6.2.3-dev.6 → 6.2.3-dev.60
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.
- package/README.md +7 -2
- package/dist/{adapter-gateway-apollo-DowrX6E_.mjs → adapter-gateway-apollo-DTcAJpfN.mjs} +3 -3
- package/dist/{adapter-gateway-apollo-CxJNBVyD.mjs → adapter-gateway-apollo-DwAmdCYz.mjs} +17 -15
- package/dist/{adapter-gateway-apollo-CxJNBVyD.mjs.map → adapter-gateway-apollo-DwAmdCYz.mjs.map} +1 -1
- package/dist/{adapter-gateway-mercurius-CZVy88Za.mjs → adapter-gateway-mercurius-BhO0nwH_.mjs} +5 -5
- package/dist/{adapter-gateway-mercurius-CZVy88Za.mjs.map → adapter-gateway-mercurius-BhO0nwH_.mjs.map} +1 -1
- package/dist/adapter-gateway-stitching-969ZPot-.mjs +4 -0
- package/dist/{adapter-gateway-stitching-CaZjvRzx.mjs → adapter-gateway-stitching-ClVkjojb.mjs} +31 -14
- package/dist/adapter-gateway-stitching-ClVkjojb.mjs.map +1 -0
- package/dist/{adapter-http-express-B39rPhqH.mjs → adapter-http-express-P0t-mdMV.mjs} +10 -10
- package/dist/adapter-http-express-P0t-mdMV.mjs.map +1 -0
- package/dist/{adapter-http-fastify-BwXO6rqE.mjs → adapter-http-fastify-D0OP5q9K.mjs} +13 -12
- package/dist/adapter-http-fastify-D0OP5q9K.mjs.map +1 -0
- package/dist/base-document-models-69WRTSfH.mjs +1243 -0
- package/dist/base-document-models-69WRTSfH.mjs.map +1 -0
- package/dist/create-schema-DLTPkNpK.d.mts +138 -0
- package/dist/create-schema-DLTPkNpK.d.mts.map +1 -0
- package/dist/index.d.mts +2021 -732
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3900 -1548
- package/dist/index.mjs.map +1 -1
- package/dist/pglite-node-Ow9i5Rb4.mjs +573 -0
- package/dist/pglite-node-Ow9i5Rb4.mjs.map +1 -0
- package/dist/rolldown-runtime-8H4AJuhK.mjs +16 -0
- package/dist/run-node-handler-CQjyjOuN.mjs +52 -0
- package/dist/run-node-handler-CQjyjOuN.mjs.map +1 -0
- package/dist/src/graphql/subgraph-types.d.mts +37 -0
- package/dist/src/graphql/subgraph-types.d.mts.map +1 -0
- package/dist/src/graphql/subgraph-types.mjs +105 -0
- package/dist/src/graphql/subgraph-types.mjs.map +1 -0
- package/dist/src/packages/https-hooks.d.mts +4 -4
- package/dist/src/packages/https-hooks.d.mts.map +1 -1
- package/dist/src/packages/https-hooks.mjs +2 -2
- package/dist/src/packages/https-hooks.mjs.map +1 -1
- package/dist/src/packages/vite-loader.d.mts +21 -10
- package/dist/src/packages/vite-loader.d.mts.map +1 -1
- package/dist/src/packages/vite-loader.mjs +121 -59
- package/dist/src/packages/vite-loader.mjs.map +1 -1
- package/dist/src/pglite/pglite-node.d.mts +130 -0
- package/dist/src/pglite/pglite-node.d.mts.map +1 -0
- package/dist/src/pglite/pglite-node.mjs +4 -0
- package/dist/{utils-XWVecaNn.mjs → subgraph-extraction-CcgWd0De.mjs} +540 -17
- package/dist/subgraph-extraction-CcgWd0De.mjs.map +1 -0
- package/dist/{types-DcYyNcHJ.d.mts → types-D3pD6fvQ.d.mts} +40 -5
- package/dist/types-D3pD6fvQ.d.mts.map +1 -0
- package/dist/{websocket-DncAB9XK.mjs → websocket-_SH5aBcy.mjs} +3 -3
- package/dist/{websocket-DncAB9XK.mjs.map → websocket-_SH5aBcy.mjs.map} +1 -1
- package/package.json +29 -19
- package/dist/adapter-gateway-stitching-CaZjvRzx.mjs.map +0 -1
- package/dist/adapter-http-express-B39rPhqH.mjs.map +0 -1
- package/dist/adapter-http-fastify-BwXO6rqE.mjs.map +0 -1
- package/dist/path-normalize-BOQwY9wR.mjs +0 -23
- package/dist/path-normalize-BOQwY9wR.mjs.map +0 -1
- package/dist/types-DcYyNcHJ.d.mts.map +0 -1
- package/dist/utils-XWVecaNn.mjs.map +0 -1
|
@@ -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]="
|
|
3
|
-
import { a as
|
|
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]="a46f476a-896c-5e31-8f57-aa722ea238e9")}catch(e){}}();
|
|
3
|
+
import { _ as debounce, a as packageRootOf, c as piecesFromListModule, g as runDetached, l as extractDocumentModels, n as BUILT_PIECE_LIST, o as pieceListLocation, r as PIECES_SUBPATH, t as extractSubgraphs, v as extractUpgradeManifests, y as isSubpath } from "../../subgraph-extraction-CcgWd0De.mjs";
|
|
4
4
|
import { childLogger } from "document-model";
|
|
5
5
|
import path from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
6
7
|
import { viteCommonjs } from "@originjs/vite-plugin-commonjs";
|
|
7
8
|
import { readPackage } from "read-pkg";
|
|
8
9
|
import { createLogger, createServer } from "vite";
|
|
@@ -17,12 +18,44 @@ function createViteLogger(logger, prefix = "") {
|
|
|
17
18
|
var VitePackageLoader = class VitePackageLoader {
|
|
18
19
|
logger = childLogger(["reactor-api", "vite-loader"]);
|
|
19
20
|
vite;
|
|
21
|
+
importers;
|
|
22
|
+
#reportError;
|
|
20
23
|
name = "VitePackageLoader";
|
|
21
|
-
static build(vite) {
|
|
22
|
-
return new VitePackageLoader(vite);
|
|
24
|
+
static build(vite, options) {
|
|
25
|
+
return new VitePackageLoader(vite, options);
|
|
23
26
|
}
|
|
24
|
-
constructor(vite) {
|
|
27
|
+
constructor(vite, options = {}) {
|
|
25
28
|
this.vite = vite;
|
|
29
|
+
this.importers = [...options.resolveFrom ?? [], import.meta.url].map((from) => from.startsWith("file:") ? fileURLToPath(from) : from);
|
|
30
|
+
this.#reportError = options.reportError;
|
|
31
|
+
}
|
|
32
|
+
async #resolve(identifier, subpath) {
|
|
33
|
+
const aliased = path.isAbsolute(identifier) ? void 0 : this.aliasedRoot(identifier);
|
|
34
|
+
const specifier = path.posix.join(aliased ?? identifier, subpath);
|
|
35
|
+
const importers = !aliased && !path.isAbsolute(identifier) ? [void 0, ...this.importers] : [void 0];
|
|
36
|
+
const container = this.vite.environments.ssr.pluginContainer;
|
|
37
|
+
for (const importer of importers) try {
|
|
38
|
+
const resolved = await container.resolveId(specifier, importer);
|
|
39
|
+
if (resolved && !resolved.external) return resolved.id;
|
|
40
|
+
} catch (e) {
|
|
41
|
+
this.logger.debug("Could not resolve @specifier: @error", specifier, e);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
async #load(identifier, subpath) {
|
|
45
|
+
const id = await this.#resolve(identifier, subpath);
|
|
46
|
+
if (id === void 0) {
|
|
47
|
+
this.logger.debug("No @subpath module in @pkg", subpath, identifier);
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
try {
|
|
51
|
+
return {
|
|
52
|
+
id,
|
|
53
|
+
namespace: await this.vite.ssrLoadModule(id)
|
|
54
|
+
};
|
|
55
|
+
} catch (e) {
|
|
56
|
+
this.logger.error("Failed to load @subpath of @pkg from @id: @error", subpath, identifier, id, e instanceof Error ? e.message : e);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
26
59
|
}
|
|
27
60
|
getDocumentModelsPath(identifier) {
|
|
28
61
|
return path.posix.join(identifier, "./document-models");
|
|
@@ -33,75 +66,93 @@ var VitePackageLoader = class VitePackageLoader {
|
|
|
33
66
|
getProcessorsPath(identifier) {
|
|
34
67
|
return path.posix.join(identifier, "./processors");
|
|
35
68
|
}
|
|
36
|
-
|
|
37
|
-
return
|
|
69
|
+
getPiecesPath(identifier) {
|
|
70
|
+
return path.posix.join(identifier, `./${PIECES_SUBPATH}`);
|
|
38
71
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
const
|
|
42
|
-
|
|
72
|
+
aliasedRoot(identifier) {
|
|
73
|
+
const alias = this.vite.config.resolve.alias;
|
|
74
|
+
const hit = (Array.isArray(alias) ? alias : []).find((entry) => entry.find === identifier);
|
|
75
|
+
return typeof hit?.replacement === "string" ? hit.replacement : void 0;
|
|
76
|
+
}
|
|
77
|
+
pieceRoot(identifier, listId) {
|
|
78
|
+
if (!path.isAbsolute(identifier)) {
|
|
79
|
+
const aliased = this.aliasedRoot(identifier);
|
|
80
|
+
if (aliased) return aliased;
|
|
81
|
+
if (listId) return packageRootOf(path.dirname(listId));
|
|
82
|
+
}
|
|
43
83
|
try {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
for (const dm of exports) if (dm.documentModel) documentModels.push(dm);
|
|
48
|
-
this.logger.verbose(` ➜ Loaded ${documentModels.length} Document Models from: ${identifier}`);
|
|
49
|
-
return documentModels;
|
|
50
|
-
} catch (e) {
|
|
51
|
-
this.logger.debug(` ➜ No Document Models found for: ${identifier}`, e);
|
|
84
|
+
return pieceListLocation(identifier).root;
|
|
85
|
+
} catch {
|
|
86
|
+
return;
|
|
52
87
|
}
|
|
53
|
-
|
|
88
|
+
}
|
|
89
|
+
async loadDocumentModels(identifier) {
|
|
90
|
+
this.logger.debug("Loading document models from", this.getDocumentModelsPath(identifier));
|
|
91
|
+
const loaded = await this.#load(identifier, "document-models");
|
|
92
|
+
if (!loaded) return [];
|
|
93
|
+
const documentModels = extractDocumentModels(loaded.namespace);
|
|
94
|
+
this.logger.verbose(` ➜ Loaded ${documentModels.length} Document Models from: ${identifier}`);
|
|
95
|
+
return documentModels;
|
|
54
96
|
}
|
|
55
97
|
async loadUpgradeManifests(identifier) {
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
98
|
+
for (const subpath of ["document-models", "document-models/upgrade-manifests"]) {
|
|
99
|
+
const loaded = await this.#load(identifier, subpath);
|
|
100
|
+
if (!loaded) continue;
|
|
101
|
+
const manifests = extractUpgradeManifests(loaded.namespace);
|
|
59
102
|
if (manifests.length > 0) {
|
|
60
103
|
this.logger.verbose(` ➜ Loaded ${manifests.length} Upgrade Manifests from: ${identifier}`);
|
|
61
104
|
return manifests;
|
|
62
105
|
}
|
|
63
|
-
} catch (e) {
|
|
64
|
-
this.logger.debug(` ➜ No Upgrade Manifests found at ${fullPath} for: ${identifier}`, e);
|
|
65
106
|
}
|
|
66
107
|
return [];
|
|
67
108
|
}
|
|
68
109
|
async loadSubgraphs(identifier) {
|
|
69
|
-
|
|
70
|
-
this
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
localSubgraphs = await this.vite.ssrLoadModule(fullPath);
|
|
74
|
-
} catch (e) {
|
|
75
|
-
this.logger.debug(` ➜ No Subgraphs found for: ${identifier}`, e);
|
|
76
|
-
return [];
|
|
77
|
-
}
|
|
78
|
-
const subgraphs = [];
|
|
79
|
-
for (const [name, subgraph] of Object.entries(localSubgraphs)) {
|
|
80
|
-
const SubgraphClass = subgraph[name];
|
|
81
|
-
if (isSubgraphClass(SubgraphClass)) subgraphs.push(SubgraphClass);
|
|
82
|
-
}
|
|
110
|
+
this.logger.verbose("Loading subgraphs from", this.getSubgraphsPath(identifier));
|
|
111
|
+
const loaded = await this.#load(identifier, "subgraphs");
|
|
112
|
+
if (!loaded) return [];
|
|
113
|
+
const subgraphs = extractSubgraphs(loaded.namespace);
|
|
83
114
|
this.logger.debug(` ➜ Loaded ${subgraphs.length} Subgraphs from: ${identifier}`);
|
|
84
115
|
return subgraphs;
|
|
85
116
|
}
|
|
86
117
|
async loadProcessors(identifier) {
|
|
87
|
-
|
|
88
|
-
this
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
this.logger.verbose(` ➜ Loaded Processor Factory from: ${identifier}`);
|
|
93
|
-
return factory;
|
|
94
|
-
}
|
|
95
|
-
} catch (e) {
|
|
96
|
-
this.logger.debug(` ➜ No Processor Factory found for: ${identifier}`, e);
|
|
118
|
+
this.logger.verbose("Loading processors from", this.getProcessorsPath(identifier));
|
|
119
|
+
const factory = (await this.#load(identifier, "processors"))?.namespace.processorFactory;
|
|
120
|
+
if (typeof factory === "function") {
|
|
121
|
+
this.logger.verbose(` ➜ Loaded Processor Factory from: ${identifier}`);
|
|
122
|
+
return factory;
|
|
97
123
|
}
|
|
98
124
|
this.logger.verbose(` ➜ No Processor Factory found for: ${identifier}`);
|
|
99
125
|
return null;
|
|
100
126
|
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
127
|
+
async loadPieces(identifier) {
|
|
128
|
+
this.logger.verbose("Loading pieces from", this.getPiecesPath(identifier));
|
|
129
|
+
const loaded = await this.#load(identifier, PIECES_SUBPATH);
|
|
130
|
+
if (!loaded) return [];
|
|
131
|
+
const root = this.pieceRoot(identifier, loaded.id);
|
|
132
|
+
if (root === void 0) {
|
|
133
|
+
this.logger.debug(` ➜ No package root found for: ${identifier}`);
|
|
134
|
+
return [];
|
|
135
|
+
}
|
|
136
|
+
const pieces = piecesFromListModule(loaded.namespace, {
|
|
137
|
+
root,
|
|
138
|
+
identifier,
|
|
139
|
+
logger: this.logger
|
|
140
|
+
});
|
|
141
|
+
this.logger.debug(` ➜ Loaded ${pieces.length} Pieces from: ${identifier}`);
|
|
142
|
+
return pieces;
|
|
143
|
+
}
|
|
144
|
+
#watcherListener(label, matches, reload, options) {
|
|
145
|
+
const reloadOnce = debounce(() => runDetached(label, reload, {
|
|
146
|
+
logger: this.logger,
|
|
147
|
+
report: this.#reportError
|
|
148
|
+
}), options?.debounce ?? 100);
|
|
149
|
+
return (changedPath) => {
|
|
150
|
+
if (matches(changedPath)) reloadOnce();
|
|
104
151
|
};
|
|
152
|
+
}
|
|
153
|
+
onDocumentModelsChange(identifier, handler, options) {
|
|
154
|
+
const documentModelsPath = this.getDocumentModelsPath(identifier);
|
|
155
|
+
const listener = this.#watcherListener(`Reloading the document models of ${identifier}`, (changedPath) => isSubpath(documentModelsPath, changedPath), async () => handler(await this.loadDocumentModels(identifier)), options);
|
|
105
156
|
this.vite.watcher.on("change", listener);
|
|
106
157
|
this.vite.watcher.on("add", listener);
|
|
107
158
|
this.vite.watcher.on("unlink", listener);
|
|
@@ -113,9 +164,7 @@ var VitePackageLoader = class VitePackageLoader {
|
|
|
113
164
|
}
|
|
114
165
|
onSubgraphsChange(identifier, handler, options) {
|
|
115
166
|
const subgraphsPath = this.getSubgraphsPath(identifier);
|
|
116
|
-
const listener =
|
|
117
|
-
if (isSubpath(subgraphsPath, changedPath)) handler(await this.loadSubgraphs(identifier));
|
|
118
|
-
};
|
|
167
|
+
const listener = this.#watcherListener(`Reloading the subgraphs of ${identifier}`, (changedPath) => isSubpath(subgraphsPath, changedPath), async () => handler(await this.loadSubgraphs(identifier)), options);
|
|
119
168
|
this.vite.watcher.on("change", listener);
|
|
120
169
|
this.vite.watcher.on("add", listener);
|
|
121
170
|
this.vite.watcher.on("unlink", listener);
|
|
@@ -127,9 +176,21 @@ var VitePackageLoader = class VitePackageLoader {
|
|
|
127
176
|
}
|
|
128
177
|
onProcessorsChange(identifier, handler, options) {
|
|
129
178
|
const processorsPath = this.getProcessorsPath(identifier);
|
|
130
|
-
const listener =
|
|
131
|
-
|
|
179
|
+
const listener = this.#watcherListener(`Reloading the processors of ${identifier}`, (changedPath) => isSubpath(processorsPath, changedPath), async () => handler(await this.loadProcessors(identifier)), options);
|
|
180
|
+
this.vite.watcher.on("change", listener);
|
|
181
|
+
this.vite.watcher.on("add", listener);
|
|
182
|
+
this.vite.watcher.on("unlink", listener);
|
|
183
|
+
return () => {
|
|
184
|
+
this.vite.watcher.off("change", listener);
|
|
185
|
+
this.vite.watcher.off("add", listener);
|
|
186
|
+
this.vite.watcher.off("unlink", listener);
|
|
132
187
|
};
|
|
188
|
+
}
|
|
189
|
+
onPiecesChange(identifier, handler, options) {
|
|
190
|
+
const watched = [this.getPiecesPath(identifier)];
|
|
191
|
+
const root = this.pieceRoot(identifier);
|
|
192
|
+
if (root !== void 0) watched.push(path.dirname(path.resolve(root, BUILT_PIECE_LIST)));
|
|
193
|
+
const listener = this.#watcherListener(`Reloading the pieces of ${identifier}`, (changedPath) => watched.some((dir) => isSubpath(dir, changedPath)), async () => handler(await this.loadPieces(identifier)), options);
|
|
133
194
|
this.vite.watcher.on("change", listener);
|
|
134
195
|
this.vite.watcher.on("add", listener);
|
|
135
196
|
this.vite.watcher.on("unlink", listener);
|
|
@@ -141,6 +202,7 @@ var VitePackageLoader = class VitePackageLoader {
|
|
|
141
202
|
}
|
|
142
203
|
};
|
|
143
204
|
async function startViteServer(root, logger) {
|
|
205
|
+
const packageJson = await readPackage({ cwd: root });
|
|
144
206
|
return await createServer({
|
|
145
207
|
root,
|
|
146
208
|
configFile: false,
|
|
@@ -153,7 +215,7 @@ async function startViteServer(root, logger) {
|
|
|
153
215
|
build: { rollupOptions: { input: [] } },
|
|
154
216
|
resolve: {
|
|
155
217
|
tsconfigPaths: true,
|
|
156
|
-
alias: { [
|
|
218
|
+
alias: { [packageJson.name]: root }
|
|
157
219
|
},
|
|
158
220
|
plugins: [viteCommonjs(), {
|
|
159
221
|
name: "suppress-hmr",
|
|
@@ -167,4 +229,4 @@ async function startViteServer(root, logger) {
|
|
|
167
229
|
export { VitePackageLoader, createViteLogger, startViteServer };
|
|
168
230
|
|
|
169
231
|
//# sourceMappingURL=vite-loader.mjs.map
|
|
170
|
-
//# debugId=
|
|
232
|
+
//# debugId=a46f476a-896c-5e31-8f57-aa722ea238e9
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite-loader.mjs","sources":["../../../src/packages/vite-loader.mts"],"sourcesContent":["import { viteCommonjs } from \"@originjs/vite-plugin-commonjs\";\nimport type {\n ProcessorFactoryBuilder,\n SubgraphClass,\n} from \"@powerhousedao/reactor-api\";\nimport type {\n DocumentModelModule,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport { childLogger, type ILogger } from \"document-model\";\nimport path from \"node:path\";\nimport { readPackage } from \"read-pkg\";\nimport type { Logger, PluginOption, ViteDevServer } from \"vite\";\nimport { createLogger, createServer } from \"vite\";\nimport { isSubgraphClass } from \"../graphql/utils.js\";\nimport type {\n ISubscribablePackageLoader,\n ISubscriptionOptions,\n} from \"./types.js\";\nimport { debounce, extractUpgradeManifests, isSubpath } from \"./util.js\";\n\nexport function createViteLogger(logger: ILogger, prefix = \"\") {\n const customLogger = createLogger(\"info\", {\n prefix,\n });\n // Wrapped rather than assigned: the logger methods are bound to their own\n // instance, and re-homing them onto Vite's logger object made every Vite\n // log line throw.\n //\n // Vite's text goes through as a replacement, never as the format string: it\n // is somebody else's prose, not a template. `ILogger` substitutes `@token`,\n // and Vite log lines are full of npm scopes, so `pre-transforming\n // @powerhousedao/design-system` came out as `pre-transforming\n // null/design-system`. Substituting into `@line` instead emits it verbatim.\n //\n // Vite's second argument is dropped for the same reason. It is `LogOptions`\n // -- `{ clear, timestamp }` -- and forwarding it made it the replacement for\n // whatever `@token` the line happened to contain, or got appended as JSON.\n // Only `error` keeps it, where it carries the error itself.\n customLogger.info = (msg) => logger.info(\"@line\", msg);\n customLogger.warn = (msg) => logger.warn(\"@line\", msg);\n customLogger.error = (msg, options) =>\n options?.error\n ? logger.error(\"@line\", msg, options.error)\n : logger.error(\"@line\", msg);\n return customLogger;\n}\n\nexport class VitePackageLoader implements ISubscribablePackageLoader {\n private readonly logger = childLogger([\"reactor-api\", \"vite-loader\"]);\n\n private readonly vite: ViteDevServer;\n\n readonly name = \"VitePackageLoader\";\n\n static build(vite: ViteDevServer) {\n return new VitePackageLoader(vite);\n }\n\n constructor(vite: ViteDevServer) {\n this.vite = vite;\n }\n\n private getDocumentModelsPath(identifier: string): string {\n return path.posix.join(identifier, \"./document-models\");\n }\n\n private getSubgraphsPath(identifier: string): string {\n return path.posix.join(identifier, \"./subgraphs\");\n }\n\n private getProcessorsPath(identifier: string): string {\n return path.posix.join(identifier, \"./processors\");\n }\n\n public loadDocumentModels(identifier: string, immediate = false) {\n return this.#loadDocumentModelsWithDebounce(immediate, identifier);\n }\n\n #loadDocumentModelsWithDebounce = debounce(\n this.#loadDocumentModels.bind(this),\n 500,\n );\n\n async #loadDocumentModels(\n identifier: string,\n ): Promise<DocumentModelModule[]> {\n const fullPath = this.getDocumentModelsPath(identifier);\n this.logger.debug(\"Loading document models from\", fullPath);\n\n try {\n const localDMs = (await this.vite.ssrLoadModule(fullPath)) as Record<\n string,\n DocumentModelModule\n >;\n\n const exports = Object.values(localDMs);\n\n // duck type\n const documentModels: DocumentModelModule[] = [];\n for (const dm of exports) {\n if (dm.documentModel) {\n documentModels.push(dm);\n }\n }\n\n this.logger.verbose(\n ` ➜ Loaded ${documentModels.length} Document Models from: ${identifier}`,\n );\n\n return documentModels;\n } catch (e) {\n this.logger.debug(` ➜ No Document Models found for: ${identifier}`, e);\n }\n\n return [];\n }\n\n async loadUpgradeManifests(\n identifier: string,\n ): Promise<UpgradeManifest<readonly number[]>[]> {\n // Projects generated before the aggregate index re-exported the\n // manifests only expose them at document-models/upgrade-manifests, so\n // try both without requiring a regeneration.\n const candidatePaths = [\n this.getDocumentModelsPath(identifier),\n path.posix.join(this.getDocumentModelsPath(identifier), \"upgrade-manifests\"),\n ];\n for (const fullPath of candidatePaths) {\n try {\n const namespace = (await this.vite.ssrLoadModule(fullPath)) as Record<\n string,\n unknown\n >;\n const manifests = extractUpgradeManifests(namespace);\n if (manifests.length > 0) {\n this.logger.verbose(\n ` ➜ Loaded ${manifests.length} Upgrade Manifests from: ${identifier}`,\n );\n return manifests;\n }\n } catch (e) {\n this.logger.debug(\n ` ➜ No Upgrade Manifests found at ${fullPath} for: ${identifier}`,\n e,\n );\n }\n }\n return [];\n }\n\n async loadSubgraphs(identifier: string): Promise<SubgraphClass[]> {\n const fullPath = this.getSubgraphsPath(identifier);\n\n this.logger.verbose(\"Loading subgraphs from\", fullPath);\n\n let localSubgraphs: Record<string, Record<string, SubgraphClass>> = {};\n try {\n localSubgraphs = await this.vite.ssrLoadModule(fullPath);\n } catch (e) {\n this.logger.debug(` ➜ No Subgraphs found for: ${identifier}`, e);\n return [];\n }\n\n const subgraphs: SubgraphClass[] = [];\n for (const [name, subgraph] of Object.entries(localSubgraphs)) {\n const SubgraphClass = subgraph[name];\n if (isSubgraphClass(SubgraphClass)) {\n subgraphs.push(SubgraphClass);\n }\n }\n\n this.logger.debug(\n ` ➜ Loaded ${subgraphs.length} Subgraphs from: ${identifier}`,\n );\n\n return subgraphs;\n }\n\n async loadProcessors(\n identifier: string,\n ): Promise<ProcessorFactoryBuilder | null> {\n const fullPath = this.getProcessorsPath(identifier);\n\n this.logger.verbose(\"Loading processors from\", fullPath);\n\n try {\n const pkgModule = await this.vite.ssrLoadModule(fullPath);\n\n const factory = (\n pkgModule as Record<string, ProcessorFactoryBuilder | undefined>\n )?.processorFactory;\n\n if (factory && typeof factory === \"function\") {\n this.logger.verbose(\n ` ➜ Loaded Processor Factory from: ${identifier}`,\n );\n return factory;\n }\n } catch (e) {\n this.logger.debug(\n ` ➜ No Processor Factory found for: ${identifier}`,\n e,\n );\n }\n\n this.logger.verbose(` ➜ No Processor Factory found for: ${identifier}`);\n\n // return empty processor factory\n return null;\n }\n\n onDocumentModelsChange(\n identifier: string,\n handler: (documentModels: DocumentModelModule[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const listener = async (changedPath: string) => {\n const documentModelsPath = this.getDocumentModelsPath(identifier);\n if (isSubpath(documentModelsPath, changedPath)) {\n const documentModels = await this.loadDocumentModels(identifier);\n handler(documentModels);\n }\n };\n\n // \"change\" alone misses files that are created or deleted: a removed\n // document-models/ entry would never report an empty result, and the\n // package's registered models would leak.\n this.vite.watcher.on(\"change\", listener);\n this.vite.watcher.on(\"add\", listener);\n this.vite.watcher.on(\"unlink\", listener);\n\n return () => {\n this.vite.watcher.off(\"change\", listener);\n this.vite.watcher.off(\"add\", listener);\n this.vite.watcher.off(\"unlink\", listener);\n };\n }\n\n onSubgraphsChange(\n identifier: string,\n handler: (subgraphs: SubgraphClass[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const subgraphsPath = this.getSubgraphsPath(identifier);\n const listener = async (changedPath: string) => {\n if (isSubpath(subgraphsPath, changedPath)) {\n const subgraphs = await this.loadSubgraphs(identifier);\n handler(subgraphs);\n }\n };\n // \"change\" alone misses files that are created or deleted: a removed\n // subgraphs/ entry would never report an empty result, and the\n // package's registered subgraphs would leak.\n this.vite.watcher.on(\"change\", listener);\n this.vite.watcher.on(\"add\", listener);\n this.vite.watcher.on(\"unlink\", listener);\n\n return () => {\n this.vite.watcher.off(\"change\", listener);\n this.vite.watcher.off(\"add\", listener);\n this.vite.watcher.off(\"unlink\", listener);\n };\n }\n\n onProcessorsChange(\n identifier: string,\n handler: (processors: ProcessorFactoryBuilder | null) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const processorsPath = this.getProcessorsPath(identifier);\n const listener = async (changedPath: string) => {\n if (isSubpath(processorsPath, changedPath)) {\n const processors = await this.loadProcessors(identifier);\n handler(processors);\n }\n };\n // \"change\" alone misses files that are created or deleted: a removed\n // processors/ entry would never report an empty result, and the\n // package's registered processor factories would leak.\n this.vite.watcher.on(\"change\", listener);\n this.vite.watcher.on(\"add\", listener);\n this.vite.watcher.on(\"unlink\", listener);\n\n return () => {\n this.vite.watcher.off(\"change\", listener);\n this.vite.watcher.off(\"add\", listener);\n this.vite.watcher.off(\"unlink\", listener);\n };\n }\n}\n\nexport async function startViteServer(root: string, logger?: Logger) {\n const packageJson = await readPackage({ cwd: root });\n\n const vite = await createServer({\n root,\n configFile: false,\n logger,\n server: { middlewareMode: true, watch: { ignored: [\"**/.ph/**\"] } },\n appType: \"custom\",\n build: {\n rollupOptions: {\n input: [],\n },\n },\n resolve: {\n tsconfigPaths: true,\n alias: {\n [packageJson.name]: root,\n },\n },\n plugins: [\n // cast: the plugin ships types built against an older vite, and the\n // mismatched Plugin type crashes tsc 6 during assignability checking\n viteCommonjs() as PluginOption,\n {\n name: \"suppress-hmr\",\n handleHotUpdate() {\n return []; // return empty array to suppress server refresh\n },\n },\n ],\n });\n\n return vite;\n}\n"],"names":["#loadDocumentModelsWithDebounce","#loadDocumentModels"],"mappings":";;;;;;;;;AAqBA,SAAgB,iBAAiB,QAAiB,SAAS,IAAI;CAC7D,MAAM,eAAe,aAAa,QAAQ,EACxC,QACD,CAAC;AAeF,cAAa,QAAQ,QAAQ,OAAO,KAAK,SAAS,IAAI;AACtD,cAAa,QAAQ,QAAQ,OAAO,KAAK,SAAS,IAAI;AACtD,cAAa,SAAS,KAAK,YACzB,SAAS,QACL,OAAO,MAAM,SAAS,KAAK,QAAQ,MAAM,GACzC,OAAO,MAAM,SAAS,IAAI;AAChC,QAAO;;AAGT,IAAa,oBAAb,MAAa,kBAAwD;CACnE,SAA0B,YAAY,CAAC,eAAe,cAAc,CAAC;CAErE;CAEA,OAAgB;CAEhB,OAAO,MAAM,MAAqB;AAChC,SAAO,IAAI,kBAAkB,KAAK;;CAGpC,YAAY,MAAqB;AAC/B,OAAK,OAAO;;CAGd,sBAA8B,YAA4B;AACxD,SAAO,KAAK,MAAM,KAAK,YAAY,oBAAoB;;CAGzD,iBAAyB,YAA4B;AACnD,SAAO,KAAK,MAAM,KAAK,YAAY,cAAc;;CAGnD,kBAA0B,YAA4B;AACpD,SAAO,KAAK,MAAM,KAAK,YAAY,eAAe;;CAGpD,mBAA0B,YAAoB,YAAY,OAAO;AAC/D,SAAO,MAAA,+BAAqC,WAAW,WAAW;;CAGpE,kCAAkC,SAChC,MAAA,mBAAyB,KAAK,KAAK,EACnC,IACD;CAED,OAAA,mBACE,YACgC;EAChC,MAAM,WAAW,KAAK,sBAAsB,WAAW;AACvD,OAAK,OAAO,MAAM,gCAAgC,SAAS;AAE3D,MAAI;GACF,MAAM,WAAY,MAAM,KAAK,KAAK,cAAc,SAAS;GAKzD,MAAM,UAAU,OAAO,OAAO,SAAS;GAGvC,MAAM,iBAAwC,EAAE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,OAAO,gBAAwB;AAC9C,OAAI,UAAU,gBAAgB,YAAY,CAExC,SADmB,MAAM,KAAK,eAAe,WAAW,CACrC;;AAMvB,OAAK,KAAK,QAAQ,GAAG,UAAU,SAAS;AACxC,OAAK,KAAK,QAAQ,GAAG,OAAO,SAAS;AACrC,OAAK,KAAK,QAAQ,GAAG,UAAU,SAAS;AAExC,eAAa;AACX,QAAK,KAAK,QAAQ,IAAI,UAAU,SAAS;AACzC,QAAK,KAAK,QAAQ,IAAI,OAAO,SAAS;AACtC,QAAK,KAAK,QAAQ,IAAI,UAAU,SAAS;;;;AAK/C,eAAsB,gBAAgB,MAAc,QAAiB;AAiCnE,QA9Ba,MAAM,aAAa;EAC9B;EACA,YAAY;EACZ;EACA,QAAQ;GAAE,gBAAgB;GAAM,OAAO,EAAE,SAAS,CAAC,YAAY,EAAE;GAAE;EACnE,SAAS;EACT,OAAO,EACL,eAAe,EACb,OAAO,EAAE,EACV,EACF;EACD,SAAS;GACP,eAAe;GACf,OAAO,IAfS,MAAM,YAAY,EAAE,KAAK,MAAM,CAAC,EAgBjC,OAAO,MACrB;GACF;EACD,SAAS,CAGP,cAAc,EACd;GACE,MAAM;GACN,kBAAkB;AAChB,WAAO,EAAE;;GAEZ,CACF;EACF,CAAC","debug_id":"9da64ff1-d15d-5b85-94b1-f1b0dad67551"}
|
|
1
|
+
{"version":3,"file":"vite-loader.mjs","sources":["../../../src/packages/vite-loader.mts"],"sourcesContent":["import { viteCommonjs } from \"@originjs/vite-plugin-commonjs\";\nimport type {\n ProcessorFactoryBuilder,\n SubgraphClass,\n} from \"@powerhousedao/reactor-api\";\nimport type {\n DocumentModelModule,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport { childLogger, type ILogger } from \"document-model\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { readPackage } from \"read-pkg\";\nimport type { Logger, PluginOption, ViteDevServer } from \"vite\";\nimport { createLogger, createServer } from \"vite\";\nimport { extractDocumentModels } from \"./document-model-detection.js\";\nimport { extractSubgraphs } from \"./subgraph-extraction.js\";\nimport {\n BUILT_PIECE_LIST,\n PIECES_SUBPATH,\n packageRootOf,\n pieceListLocation,\n piecesFromListModule,\n} from \"./pieces.js\";\nimport type {\n ISubscribablePackageLoader,\n ISubscriptionOptions,\n PackagePieceEntry,\n} from \"./types.js\";\nimport { debounce, extractUpgradeManifests, isSubpath } from \"./util.js\";\nimport { runDetached, type ReportError } from \"../utils/detached.js\";\n\nexport function createViteLogger(logger: ILogger, prefix = \"\") {\n const customLogger = createLogger(\"info\", {\n prefix,\n });\n // Wrapped rather than assigned: the logger methods are bound to their own\n // instance, and re-homing them onto Vite's logger object made every Vite\n // log line throw.\n //\n // Vite's text goes through as a replacement, never as the format string: it\n // is somebody else's prose, not a template. `ILogger` substitutes `@token`,\n // and Vite log lines are full of npm scopes, so `pre-transforming\n // @powerhousedao/design-system` came out as `pre-transforming\n // null/design-system`. Substituting into `@line` instead emits it verbatim.\n //\n // Vite's second argument is dropped for the same reason. It is `LogOptions`\n // -- `{ clear, timestamp }` -- and forwarding it made it the replacement for\n // whatever `@token` the line happened to contain, or got appended as JSON.\n // Only `error` keeps it, where it carries the error itself.\n customLogger.info = (msg) => logger.info(\"@line\", msg);\n customLogger.warn = (msg) => logger.warn(\"@line\", msg);\n customLogger.error = (msg, options) =>\n options?.error\n ? logger.error(\"@line\", msg, options.error)\n : logger.error(\"@line\", msg);\n return customLogger;\n}\n\nexport interface VitePackageLoaderOptions {\n /** Modules, as paths or file URLs, whose dependencies a package the project\n * does not install may resolve from. This loader's own module always is. */\n resolveFrom?: string[];\n reportError?: ReportError;\n}\n\ninterface LoadedModule {\n id: string;\n namespace: Record<string, unknown>;\n}\n\nexport class VitePackageLoader implements ISubscribablePackageLoader {\n private readonly logger = childLogger([\"reactor-api\", \"vite-loader\"]);\n\n private readonly vite: ViteDevServer;\n\n private readonly importers: string[];\n\n readonly #reportError?: ReportError;\n\n readonly name = \"VitePackageLoader\";\n\n static build(vite: ViteDevServer, options?: VitePackageLoaderOptions) {\n return new VitePackageLoader(vite, options);\n }\n\n constructor(vite: ViteDevServer, options: VitePackageLoaderOptions = {}) {\n this.vite = vite;\n this.importers = [...(options.resolveFrom ?? []), import.meta.url].map(\n (from) => (from.startsWith(\"file:\") ? fileURLToPath(from) : from),\n );\n this.#reportError = options.reportError;\n }\n\n // The project first, then the host's own dependencies. A bare name or a path\n // Vite cannot resolve is a package without that module, not an error.\n async #resolve(identifier: string, subpath: string) {\n const aliased = path.isAbsolute(identifier)\n ? undefined\n : this.aliasedRoot(identifier);\n const specifier = path.posix.join(aliased ?? identifier, subpath);\n const bare = !aliased && !path.isAbsolute(identifier);\n const importers = bare ? [undefined, ...this.importers] : [undefined];\n const container = this.vite.environments.ssr.pluginContainer;\n for (const importer of importers) {\n try {\n const resolved = await container.resolveId(specifier, importer);\n if (resolved && !resolved.external) return resolved.id;\n } catch (e) {\n this.logger.debug(\"Could not resolve @specifier: @error\", specifier, e);\n }\n }\n return undefined;\n }\n\n // Resolved before it is loaded, so only a module that exists and fails is\n // reported; one a package does not have is a debug-level miss.\n async #load(\n identifier: string,\n subpath: string,\n ): Promise<LoadedModule | undefined> {\n const id = await this.#resolve(identifier, subpath);\n if (id === undefined) {\n this.logger.debug(\"No @subpath module in @pkg\", subpath, identifier);\n return undefined;\n }\n try {\n const namespace = (await this.vite.ssrLoadModule(id)) as Record<\n string,\n unknown\n >;\n return { id, namespace };\n } catch (e) {\n this.logger.error(\n \"Failed to load @subpath of @pkg from @id: @error\",\n subpath,\n identifier,\n id,\n e instanceof Error ? e.message : e,\n );\n return undefined;\n }\n }\n\n private getDocumentModelsPath(identifier: string): string {\n return path.posix.join(identifier, \"./document-models\");\n }\n\n private getSubgraphsPath(identifier: string): string {\n return path.posix.join(identifier, \"./subgraphs\");\n }\n\n private getProcessorsPath(identifier: string): string {\n return path.posix.join(identifier, \"./processors\");\n }\n\n private getPiecesPath(identifier: string): string {\n return path.posix.join(identifier, `./${PIECES_SUBPATH}`);\n }\n\n // The dev server aliases the local project by its own package name, so a\n // package that is this project is rooted at the source tree vite serves.\n private aliasedRoot(identifier: string): string | undefined {\n const alias = this.vite.config.resolve.alias;\n const entries = Array.isArray(alias) ? alias : [];\n const hit = entries.find((entry) => entry.find === identifier);\n return typeof hit?.replacement === \"string\" ? hit.replacement : undefined;\n }\n\n // What a declared piece path is relative to. Not the module vite loaded: a\n // list read from source still points at the built output beside it.\n private pieceRoot(identifier: string, listId?: string): string | undefined {\n if (!path.isAbsolute(identifier)) {\n const aliased = this.aliasedRoot(identifier);\n if (aliased) return aliased;\n // A built list resolved from wherever the package is installed.\n if (listId) return packageRootOf(path.dirname(listId));\n }\n try {\n return pieceListLocation(identifier).root;\n } catch {\n return undefined;\n }\n }\n\n async loadDocumentModels(identifier: string): Promise<DocumentModelModule[]> {\n this.logger.debug(\n \"Loading document models from\",\n this.getDocumentModelsPath(identifier),\n );\n const loaded = await this.#load(identifier, \"document-models\");\n if (!loaded) return [];\n\n const documentModels = extractDocumentModels(loaded.namespace);\n this.logger.verbose(\n ` ➜ Loaded ${documentModels.length} Document Models from: ${identifier}`,\n );\n return documentModels;\n }\n\n async loadUpgradeManifests(\n identifier: string,\n ): Promise<UpgradeManifest<readonly number[]>[]> {\n // Projects generated before the aggregate index re-exported the\n // manifests only expose them at document-models/upgrade-manifests.\n for (const subpath of [\n \"document-models\",\n \"document-models/upgrade-manifests\",\n ]) {\n const loaded = await this.#load(identifier, subpath);\n if (!loaded) continue;\n const manifests = extractUpgradeManifests(loaded.namespace);\n if (manifests.length > 0) {\n this.logger.verbose(\n ` ➜ Loaded ${manifests.length} Upgrade Manifests from: ${identifier}`,\n );\n return manifests;\n }\n }\n return [];\n }\n\n async loadSubgraphs(identifier: string): Promise<SubgraphClass[]> {\n this.logger.verbose(\n \"Loading subgraphs from\",\n this.getSubgraphsPath(identifier),\n );\n const loaded = await this.#load(identifier, \"subgraphs\");\n if (!loaded) return [];\n\n const subgraphs = extractSubgraphs(loaded.namespace);\n\n this.logger.debug(\n ` ➜ Loaded ${subgraphs.length} Subgraphs from: ${identifier}`,\n );\n\n return subgraphs;\n }\n\n async loadProcessors(\n identifier: string,\n ): Promise<ProcessorFactoryBuilder | null> {\n this.logger.verbose(\n \"Loading processors from\",\n this.getProcessorsPath(identifier),\n );\n const loaded = await this.#load(identifier, \"processors\");\n const factory = loaded?.namespace.processorFactory;\n if (typeof factory === \"function\") {\n this.logger.verbose(` ➜ Loaded Processor Factory from: ${identifier}`);\n return factory as ProcessorFactoryBuilder;\n }\n\n this.logger.verbose(` ➜ No Processor Factory found for: ${identifier}`);\n return null;\n }\n\n // The list only, never a piece: in dev it is usually the TypeScript source,\n // and what it names is still the built bundle a worker will load.\n async loadPieces(identifier: string): Promise<PackagePieceEntry[]> {\n this.logger.verbose(\"Loading pieces from\", this.getPiecesPath(identifier));\n const loaded = await this.#load(identifier, PIECES_SUBPATH);\n if (!loaded) return [];\n\n const root = this.pieceRoot(identifier, loaded.id);\n if (root === undefined) {\n this.logger.debug(` ➜ No package root found for: ${identifier}`);\n return [];\n }\n\n const pieces = piecesFromListModule(loaded.namespace, {\n root,\n identifier,\n logger: this.logger,\n });\n this.logger.debug(\n ` ➜ Loaded ${pieces.length} Pieces from: ${identifier}`,\n );\n return pieces;\n }\n\n // One reload per burst of file events, run detached.\n #watcherListener(\n label: string,\n matches: (changedPath: string) => unknown,\n reload: () => Promise<void>,\n options?: ISubscriptionOptions,\n ): (changedPath: string) => void {\n const reloadOnce = debounce(\n () =>\n runDetached(label, reload, {\n logger: this.logger,\n report: this.#reportError,\n }),\n options?.debounce ?? 100,\n );\n return (changedPath) => {\n if (matches(changedPath)) void reloadOnce();\n };\n }\n\n onDocumentModelsChange(\n identifier: string,\n handler: (documentModels: DocumentModelModule[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const documentModelsPath = this.getDocumentModelsPath(identifier);\n const listener = this.#watcherListener(\n `Reloading the document models of ${identifier}`,\n (changedPath) => isSubpath(documentModelsPath, changedPath),\n async () => handler(await this.loadDocumentModels(identifier)),\n options,\n );\n\n // \"change\" alone misses files that are created or deleted: a removed\n // document-models/ entry would never report an empty result, and the\n // package's registered models would leak.\n this.vite.watcher.on(\"change\", listener);\n this.vite.watcher.on(\"add\", listener);\n this.vite.watcher.on(\"unlink\", listener);\n\n return () => {\n this.vite.watcher.off(\"change\", listener);\n this.vite.watcher.off(\"add\", listener);\n this.vite.watcher.off(\"unlink\", listener);\n };\n }\n\n onSubgraphsChange(\n identifier: string,\n handler: (subgraphs: SubgraphClass[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const subgraphsPath = this.getSubgraphsPath(identifier);\n const listener = this.#watcherListener(\n `Reloading the subgraphs of ${identifier}`,\n (changedPath) => isSubpath(subgraphsPath, changedPath),\n async () => handler(await this.loadSubgraphs(identifier)),\n options,\n );\n // \"change\" alone misses files that are created or deleted: a removed\n // subgraphs/ entry would never report an empty result, and the\n // package's registered subgraphs would leak.\n this.vite.watcher.on(\"change\", listener);\n this.vite.watcher.on(\"add\", listener);\n this.vite.watcher.on(\"unlink\", listener);\n\n return () => {\n this.vite.watcher.off(\"change\", listener);\n this.vite.watcher.off(\"add\", listener);\n this.vite.watcher.off(\"unlink\", listener);\n };\n }\n\n onProcessorsChange(\n identifier: string,\n handler: (processors: ProcessorFactoryBuilder | null) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const processorsPath = this.getProcessorsPath(identifier);\n const listener = this.#watcherListener(\n `Reloading the processors of ${identifier}`,\n (changedPath) => isSubpath(processorsPath, changedPath),\n async () => handler(await this.loadProcessors(identifier)),\n options,\n );\n // \"change\" alone misses files that are created or deleted: a removed\n // processors/ entry would never report an empty result, and the\n // package's registered processor factories would leak.\n this.vite.watcher.on(\"change\", listener);\n this.vite.watcher.on(\"add\", listener);\n this.vite.watcher.on(\"unlink\", listener);\n\n return () => {\n this.vite.watcher.off(\"change\", listener);\n this.vite.watcher.off(\"add\", listener);\n this.vite.watcher.off(\"unlink\", listener);\n };\n }\n\n onPiecesChange(\n identifier: string,\n handler: (pieces: PackagePieceEntry[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n // Both the source list and the build output: the list says which pieces a\n // package ships, and only the build decides whether one is there to run.\n const watched = [this.getPiecesPath(identifier)];\n const root = this.pieceRoot(identifier);\n if (root !== undefined) {\n watched.push(path.dirname(path.resolve(root, BUILT_PIECE_LIST)));\n }\n const listener = this.#watcherListener(\n `Reloading the pieces of ${identifier}`,\n (changedPath) => watched.some((dir) => isSubpath(dir, changedPath)),\n async () => handler(await this.loadPieces(identifier)),\n options,\n );\n // \"change\" alone misses files that are created or deleted, and a piece\n // appearing for the first time is exactly the build this watches for.\n this.vite.watcher.on(\"change\", listener);\n this.vite.watcher.on(\"add\", listener);\n this.vite.watcher.on(\"unlink\", listener);\n\n return () => {\n this.vite.watcher.off(\"change\", listener);\n this.vite.watcher.off(\"add\", listener);\n this.vite.watcher.off(\"unlink\", listener);\n };\n }\n}\n\nexport async function startViteServer(root: string, logger?: Logger) {\n const packageJson = await readPackage({ cwd: root });\n\n const vite = await createServer({\n root,\n configFile: false,\n logger,\n server: { middlewareMode: true, watch: { ignored: [\"**/.ph/**\"] } },\n appType: \"custom\",\n build: {\n rollupOptions: {\n input: [],\n },\n },\n resolve: {\n tsconfigPaths: true,\n alias: {\n [packageJson.name]: root,\n },\n },\n plugins: [\n // cast: the plugin ships types built against an older vite, and the\n // mismatched Plugin type crashes tsc 6 during assignability checking\n viteCommonjs() as PluginOption,\n {\n name: \"suppress-hmr\",\n handleHotUpdate() {\n return []; // return empty array to suppress server refresh\n },\n },\n ],\n });\n\n return vite;\n}\n"],"names":[],"mappings":";;;;;;;;;;AAgCA,SAAgB,iBAAiB,QAAiB,SAAS,IAAI;CAC7D,MAAM,eAAe,aAAa,QAAQ,EACxC,OACF,CAAC;CAeD,aAAa,QAAQ,QAAQ,OAAO,KAAK,SAAS,GAAG;CACrD,aAAa,QAAQ,QAAQ,OAAO,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;GACrC,KAAK,KAAK,QAAQ,IAAI,UAAU,QAAQ;EAC1C;CACF;AACF;AAEA,eAAsB,gBAAgB,MAAc,QAAiB;CACnE,MAAM,cAAc,MAAM,YAAY,EAAE,KAAK,KAAK,CAAC;CAgCnD,OAAO,MA9BY,aAAa;EAC9B;EACA,YAAY;EACZ;EACA,QAAQ;GAAE,gBAAgB;GAAM,OAAO,EAAE,SAAS,CAAC,WAAW,EAAE;EAAE;EAClE,SAAS;EACT,OAAO,EACL,eAAe,EACb,OAAO,CAAC,EACV,EACF;EACA,SAAS;GACP,eAAe;GACf,OAAO,GACJ,YAAY,OAAO,KACtB;EACF;EACA,SAAS,CAGP,aAAa,GACb;GACE,MAAM;GACN,kBAAkB;IAChB,OAAO,CAAC;GACV;EACF,CACF;CACF,CAAC;AAGH","debug_id":"a46f476a-896c-5e31-8f57-aa722ea238e9"}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { ILogger } from "document-model";
|
|
2
|
+
import nodeFs from "node:fs";
|
|
3
|
+
import { PGlite } from "@electric-sql/pglite";
|
|
4
|
+
import { NodeFS } from "@electric-sql/pglite/nodefs";
|
|
5
|
+
//#region src/pglite/maintenance.d.ts
|
|
6
|
+
export declare const DEFAULT_MAINTENANCE_INTERVAL_MS: number;
|
|
7
|
+
export declare const DEFAULT_VACUUM_FULL_ABOVE_BYTES: number;
|
|
8
|
+
type MaintenanceOutcome = "vacuum" | "vacuum-full" | "idle" | "not-ready" | "in-transaction" | "failed";
|
|
9
|
+
interface MaintenanceLogger {
|
|
10
|
+
warn(message: string): void;
|
|
11
|
+
}
|
|
12
|
+
interface MaintenanceOptions {
|
|
13
|
+
/** VACUUM + CHECKPOINT cadence; PGlite has no autovacuum. Default 5 min; 0 disables. */
|
|
14
|
+
intervalMs?: number;
|
|
15
|
+
/** First pass runs VACUUM FULL when `base/` exceeds this at open. Default 256 MB; 0 disables. */
|
|
16
|
+
vacuumFullAboveBytes?: number;
|
|
17
|
+
logger?: MaintenanceLogger;
|
|
18
|
+
}
|
|
19
|
+
export declare class PgliteMaintenance {
|
|
20
|
+
private readonly intervalMs;
|
|
21
|
+
private readonly vacuumFullAboveBytes;
|
|
22
|
+
private readonly logger?;
|
|
23
|
+
private pg?;
|
|
24
|
+
private label;
|
|
25
|
+
private closing;
|
|
26
|
+
private syncsSinceMaintenance;
|
|
27
|
+
private vacuumFullPending;
|
|
28
|
+
private timer?;
|
|
29
|
+
private inFlight?;
|
|
30
|
+
constructor(options?: MaintenanceOptions);
|
|
31
|
+
get scheduled(): boolean;
|
|
32
|
+
get running(): boolean;
|
|
33
|
+
start(pg: PGlite, label: string, baseBytes: number): void;
|
|
34
|
+
noteSync(): void;
|
|
35
|
+
stop(): Promise<void>;
|
|
36
|
+
run(): Promise<MaintenanceOutcome>;
|
|
37
|
+
private schedule;
|
|
38
|
+
private cancel;
|
|
39
|
+
}
|
|
40
|
+
//#endregion
|
|
41
|
+
//#region src/pglite/durable-node-fs.d.ts
|
|
42
|
+
type NodeFsClass = typeof NodeFS;
|
|
43
|
+
interface DurableNodeFsOptions {
|
|
44
|
+
/** Default true; `PH_PGLITE_FSYNC=0` turns it off (power-loss durability off). */
|
|
45
|
+
fsync?: boolean;
|
|
46
|
+
/** Default 5 min; 0 disables. */
|
|
47
|
+
maintenanceIntervalMs?: number;
|
|
48
|
+
/** `base/` size at open; default 256 MB; 0 disables. */
|
|
49
|
+
vacuumFullAboveBytes?: number;
|
|
50
|
+
logger?: {
|
|
51
|
+
warn(message: string): void;
|
|
52
|
+
};
|
|
53
|
+
/** Emscripten abort (a Postgres PANIC, e.g. ENOSPC on WAL). */
|
|
54
|
+
onAbort?: (what: unknown) => void;
|
|
55
|
+
hostFs?: Pick<typeof nodeFs, "fsyncSync" | "fdatasyncSync">;
|
|
56
|
+
}
|
|
57
|
+
type DurableNodeFs = InstanceType<NodeFsClass> & {
|
|
58
|
+
readonly maintenance: PgliteMaintenance;
|
|
59
|
+
};
|
|
60
|
+
export declare function resolvePgliteFsync(env: Record<string, string | undefined>): boolean;
|
|
61
|
+
/** Built over the passed-in class so PG16 dirs on `pglite-legacy-02` get the same behaviour. */
|
|
62
|
+
export declare function createDurableNodeFs(Base: NodeFsClass, dataDir: string, options?: DurableNodeFsOptions): DurableNodeFs;
|
|
63
|
+
//#endregion
|
|
64
|
+
//#region src/pglite/sync-tree.d.ts
|
|
65
|
+
interface SyncTreeHostFs {
|
|
66
|
+
fsyncSync(fd: number): void;
|
|
67
|
+
}
|
|
68
|
+
interface SyncTreeResult {
|
|
69
|
+
files: number;
|
|
70
|
+
dirs: number;
|
|
71
|
+
}
|
|
72
|
+
/** One pass over a finished tree; interleaving fsync with writes costs seconds. */
|
|
73
|
+
export declare function syncTree(root: string, hostFs?: SyncTreeHostFs): SyncTreeResult;
|
|
74
|
+
/** fsyncs a directory's entries; false where the platform refuses (Windows). */
|
|
75
|
+
export declare function syncDirectory(dir: string, hostFs?: SyncTreeHostFs): boolean;
|
|
76
|
+
//#endregion
|
|
77
|
+
//#region src/pglite/snapshot-reader.d.ts
|
|
78
|
+
export declare const SNAPSHOT_FILE_NAME = "snapshot.bin";
|
|
79
|
+
interface ExtractSnapshotOptions {
|
|
80
|
+
chunkSize?: number;
|
|
81
|
+
/** Default true: one fsync pass over the tree after the last write. */
|
|
82
|
+
sync?: boolean;
|
|
83
|
+
hostFs?: SyncTreeHostFs;
|
|
84
|
+
}
|
|
85
|
+
interface ExtractedSnapshot {
|
|
86
|
+
pgVersionMajor: number;
|
|
87
|
+
/** `global/pg_control` bytes; absent only in synthetic trees. */
|
|
88
|
+
pgControl?: Buffer;
|
|
89
|
+
/** Entries written to disk; skipped entries are not counted. */
|
|
90
|
+
entries: number;
|
|
91
|
+
/** Size of the snapshot file. */
|
|
92
|
+
bytes: number;
|
|
93
|
+
}
|
|
94
|
+
/** Unpacks a snapshot into the existing `outDir`. */
|
|
95
|
+
export declare function extractSnapshot(snapshotPath: string, outDir: string, options?: ExtractSnapshotOptions): Promise<ExtractedSnapshot>;
|
|
96
|
+
//#endregion
|
|
97
|
+
//#region src/pglite/convert-snapshot-dir.d.ts
|
|
98
|
+
interface VerifyHandle {
|
|
99
|
+
query<T>(sql: string): Promise<{
|
|
100
|
+
rows: T[];
|
|
101
|
+
}>;
|
|
102
|
+
close(): Promise<void>;
|
|
103
|
+
}
|
|
104
|
+
type ConversionStep = "extract" | "verify" | "renameOld" | "renameNew" | "removeOld";
|
|
105
|
+
interface ConversionDeps {
|
|
106
|
+
/** Opens `dataDir` with the stock NodeFS of the PGlite module for `major`. */
|
|
107
|
+
openForVerify: (major: number, dataDir: string) => Promise<VerifyHandle>;
|
|
108
|
+
logger: ILogger;
|
|
109
|
+
/** Test hook: throw after a named step to simulate a crash there. */
|
|
110
|
+
afterStep?: (step: ConversionStep) => void | Promise<void>;
|
|
111
|
+
hostFs?: SyncTreeHostFs;
|
|
112
|
+
}
|
|
113
|
+
/** Settles the debris of an interrupted conversion; runs before it at boot. */
|
|
114
|
+
export declare function recoverConversion(dir: string, deps: ConversionDeps): Promise<void>;
|
|
115
|
+
/** Extracts into `.converting`, verifies by opening it, swaps through `.old`. */
|
|
116
|
+
export declare function convertSnapshotDir(dir: string, deps: ConversionDeps): Promise<"converted" | "none">;
|
|
117
|
+
//#endregion
|
|
118
|
+
//#region src/pglite/preflight.d.ts
|
|
119
|
+
/** PG major of the pinned @electric-sql/pglite; it exports none, so the test checks initdb. */
|
|
120
|
+
export declare const CURRENT_PGLITE_MAJOR = 17;
|
|
121
|
+
/** `openForVerify` over the loaded PGlite module only. */
|
|
122
|
+
export declare function openCurrentPgliteForVerify(major: number, dataDir: string): Promise<VerifyHandle>;
|
|
123
|
+
/** Converts a snapshot store and clears the files a previous run leaves behind. */
|
|
124
|
+
export declare function preparePgliteDataDir(dir: string, deps: ConversionDeps): Promise<void>;
|
|
125
|
+
/** PGlite leaves `postmaster.pid` after every close and `pg_wal/xlogtemp.*` after some. */
|
|
126
|
+
export declare function removeStalePgliteFiles(dir: string, logger: Pick<ILogger, "debug">): Promise<void>;
|
|
127
|
+
//#endregion
|
|
128
|
+
export type { ConversionDeps, ConversionStep, DurableNodeFs, DurableNodeFsOptions, ExtractSnapshotOptions, ExtractedSnapshot, MaintenanceLogger, MaintenanceOptions, MaintenanceOutcome, NodeFsClass, SyncTreeHostFs, SyncTreeResult, VerifyHandle };
|
|
129
|
+
export {};
|
|
130
|
+
//# sourceMappingURL=pglite-node.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pglite-node.d.mts","names":[],"sources":["../../../src/pglite/maintenance.ts","../../../src/pglite/durable-node-fs.ts","../../../src/pglite/sync-tree.ts","../../../src/pglite/snapshot-reader.ts","../../../src/pglite/convert-snapshot-dir.ts","../../../src/pglite/preflight.ts"],"mappings":";;;;;qBAIa;qBACA;KAGD;UAQK;EACf,KAAK;;UAGU;;EAEf;;EAEA;EACA,SAAS;;qBAGE;mBACM;mBACA;mBACA;UAET;UACA;UACA;UACA;UACA;UACA;UACA;EAER,YAAY,UAAS;MAYjB;MAIA;EAIJ,MAAM,IAAI,QAAQ,eAAe;EAQjC;EAIM,QAAQ;EAMR,OAAO,QAAQ;UA+Cb;UAoBA;;;;KC1IE,qBAAqB;UAKhB;;EAEf;;EAEA;;EAEA;EACA;IAAW,KAAK;;;EAEhB,WAAW;EACX,SAAS,YAAY;;KAGX,gBAAgB,aAAa;WAC9B,aAAa;;wBAGR,mBACd,KAAK;;wBAmES,oBACd,MAAM,aACN,iBACA,UAAS,uBACR;;;UCnGc;EACf,UAAU;;UAGK;EACf;EACA;;;wBAIc,SACd,cACA,SAAQ,iBACP;;wBA+Ba,cACd,aACA,SAAQ;;;qBC3CG;UASI;EACf;;EAEA;EACA,SAAS;;UAGM;EACf;;EAEA,YAAY;;EAEZ;;EAEA;;;wBAIoB,gBACpB,sBACA,gBACA,UAAS,yBACR,QAAQ;;;UC/BM;EACf,MAAM,GAAG,cAAc;IAAU,MAAM;;EACvC,SAAS;;KAGC;UAOK;;EAEf,gBAAgB,eAAe,oBAAoB,QAAQ;EAC3D,QAAQ;;EAER,aAAa,MAAM,0BAA0B;EAC7C,SAAS;;;wBA6BW,kBACpB,aACA,MAAM,iBACL;;wBA6CmB,mBACpB,aACA,MAAM,iBACL;;;;qBC3FU;;wBAGS,2BACpB,eACA,kBACC,QAAQ;;wBAYW,qBACpB,aACA,MAAM,iBACL;;wBAOmB,uBACpB,aACA,QAAQ,KAAK,oBACZ"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { a as convertSnapshotDir, c as extractSnapshot, d as syncDirectory, f as syncTree, h as PgliteMaintenance, i as removeStalePgliteFiles, l as createDurableNodeFs, m as DEFAULT_VACUUM_FULL_ABOVE_BYTES, n as openCurrentPgliteForVerify, o as recoverConversion, p as DEFAULT_MAINTENANCE_INTERVAL_MS, r as preparePgliteDataDir, s as SNAPSHOT_FILE_NAME, t as CURRENT_PGLITE_MAJOR, u as resolvePgliteFsync } from "../../pglite-node-Ow9i5Rb4.mjs";
|
|
2
|
+
export { CURRENT_PGLITE_MAJOR, DEFAULT_MAINTENANCE_INTERVAL_MS, DEFAULT_VACUUM_FULL_ABOVE_BYTES, PgliteMaintenance, SNAPSHOT_FILE_NAME, convertSnapshotDir, createDurableNodeFs, extractSnapshot, openCurrentPgliteForVerify, preparePgliteDataDir, recoverConversion, removeStalePgliteFiles, resolvePgliteFsync, syncDirectory, syncTree };
|
|
3
|
+
!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]="6dd4c09b-2fd7-5402-83f6-a92c933064b1")}catch(e){}}();
|
|
4
|
+
//# debugId=6dd4c09b-2fd7-5402-83f6-a92c933064b1
|