@powerhousedao/builder-tools 6.2.3-dev.7 → 6.2.3-dev.70
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/dist/index.d.mts +669 -83
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2128 -282
- package/dist/index.mjs.map +1 -1
- package/dist/service-worker/service-worker.ts +23 -23
- package/package.json +14 -11
package/dist/index.mjs
CHANGED
|
@@ -1,17 +1,20 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
4
|
-
import
|
|
2
|
+
import fs, { chmodSync, cpSync, createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
|
|
3
|
+
import path, { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { createLogger, createServer, esmExternalRequirePlugin, loadEnv, normalizePath, searchForWorkspaceRoot } from "vite";
|
|
5
5
|
import { exec, execSync, spawn } from "node:child_process";
|
|
6
|
-
import { fileURLToPath } from "node:url";
|
|
7
|
-
import MagicString from "magic-string";
|
|
8
6
|
import { readFile, writeFile } from "node:fs/promises";
|
|
9
7
|
import { cwd } from "node:process";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
8
|
+
import { Generator, getConfig } from "@tanstack/router-generator";
|
|
9
|
+
import { tanstackRouter } from "@tanstack/router-plugin/vite";
|
|
10
|
+
import { index, layout, physical, rootRoute, route } from "@tanstack/virtual-file-routes";
|
|
11
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
12
|
+
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { DYNAMIC_BASE_PLACEHOLDER, PWA_FILE_HANDLER_ACTION, buildRuntimeConfig, deepMerge, loadConnectEnv, mergeManifest, mergePwaConfig, normalizeBasePath, phConnectRuntimeConfigSchema, powerhousePackageSchema, resolveSourceConnect, setConnectEnv, unionStrings, withInferredCategory, workerPackageFileName, workflowsSettingConflict } from "@powerhousedao/shared/connect";
|
|
14
|
+
import MagicString from "magic-string";
|
|
15
|
+
import { getConfig as getConfig$1 } from "@powerhousedao/config/node";
|
|
12
16
|
import tailwind from "@tailwindcss/vite";
|
|
13
17
|
import react from "@vitejs/plugin-react";
|
|
14
|
-
import { createLogger, esmExternalRequirePlugin, loadEnv, searchForWorkspaceRoot } from "vite";
|
|
15
18
|
import { createHtmlPlugin } from "vite-plugin-html";
|
|
16
19
|
import { PwaConfigSchema } from "@powerhousedao/shared/document-model";
|
|
17
20
|
import { toCdnUrl } from "@powerhousedao/shared/registry/urls";
|
|
@@ -22,6 +25,788 @@ const IMPORT_SCRIPT_FILE = "external-packages.js";
|
|
|
22
25
|
const LOCAL_PACKAGE_ID = "ph:local-package";
|
|
23
26
|
const PH_DIR_NAME = ".ph";
|
|
24
27
|
//#endregion
|
|
28
|
+
//#region connect-utils/helpers.ts
|
|
29
|
+
const DEFAULT_CONNECT_OUTDIR = ".ph/connect-build/dist/";
|
|
30
|
+
function resolveViteConfigPath(options) {
|
|
31
|
+
const { projectRoot = cwd(), viteConfigFile } = options;
|
|
32
|
+
return viteConfigFile || join(projectRoot, "vite.config.ts");
|
|
33
|
+
}
|
|
34
|
+
function resolvePackage(packageName, root = process.cwd()) {
|
|
35
|
+
return createRequire(root).resolve(packageName, { paths: [root] });
|
|
36
|
+
}
|
|
37
|
+
function resolveConnectPackageJson(root = process.cwd()) {
|
|
38
|
+
try {
|
|
39
|
+
const connectPackageJsonPath = resolvePackage("@powerhousedao/connect/package.json", root);
|
|
40
|
+
const fileContents = fs.readFileSync(connectPackageJsonPath, "utf-8");
|
|
41
|
+
return JSON.parse(fileContents);
|
|
42
|
+
} catch (error) {
|
|
43
|
+
console.error(`Error reading Connect package.json:`, error);
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Finds the dist dir of Connect on the local machine
|
|
49
|
+
*/
|
|
50
|
+
function resolveConnectBundle(root = process.cwd()) {
|
|
51
|
+
const connectIndexPath = resolvePackage("@powerhousedao/connect", root);
|
|
52
|
+
const connectRootPath = connectIndexPath.substring(0, connectIndexPath.indexOf("connect") + 7);
|
|
53
|
+
return join(connectRootPath, "dist/");
|
|
54
|
+
}
|
|
55
|
+
function resolveConnectPublicDir(root = process.cwd()) {
|
|
56
|
+
const connectIconPath = resolvePackage("@powerhousedao/connect/public/icon.ico", root);
|
|
57
|
+
return path.join(connectIconPath, "../");
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Copies the Connect dist dir to the target path
|
|
61
|
+
*/
|
|
62
|
+
function copyConnect(sourcePath, targetPath) {
|
|
63
|
+
try {
|
|
64
|
+
fs.rmSync(targetPath, {
|
|
65
|
+
recursive: true,
|
|
66
|
+
force: true
|
|
67
|
+
});
|
|
68
|
+
fs.cpSync(sourcePath, targetPath, { recursive: true });
|
|
69
|
+
} catch (error) {
|
|
70
|
+
console.error(`❌ Error copying ${sourcePath} to ${targetPath}:`, error);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Backs up the index.html file
|
|
75
|
+
*
|
|
76
|
+
* Needed when running the Connect Studio dev server on Windows
|
|
77
|
+
*/
|
|
78
|
+
function backupIndexHtml(appPath, restore = false) {
|
|
79
|
+
const filePath = join(appPath, "index.html");
|
|
80
|
+
const backupPath = join(appPath, "index.html.bak");
|
|
81
|
+
const paths = restore ? [backupPath, filePath] : [filePath, backupPath];
|
|
82
|
+
if (fs.existsSync(paths[0])) fs.copyFileSync(paths[0], paths[1]);
|
|
83
|
+
}
|
|
84
|
+
function removeBase64EnvValues(appPath) {
|
|
85
|
+
backupIndexHtml(appPath);
|
|
86
|
+
const filePath = join(appPath, "index.html");
|
|
87
|
+
fs.readFile(filePath, "utf-8", (err, data) => {
|
|
88
|
+
if (err) {
|
|
89
|
+
console.error("Error reading file:", err);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
const modifiedData = data.replace(/"LOCAL_DOCUMENT_MODELS":\s*".*?",/, `"LOCAL_DOCUMENT_MODELS": "",`).replace(/"LOCAL_DOCUMENT_EDITORS":\s*".*?"/, `"LOCAL_DOCUMENT_EDITORS": ""`);
|
|
93
|
+
console.log("Modified data:", modifiedData);
|
|
94
|
+
fs.writeFile(filePath, modifiedData, "utf-8", (err) => {
|
|
95
|
+
if (err) {
|
|
96
|
+
console.error("Error writing file:", err);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
function readJsonFile(filePath) {
|
|
103
|
+
try {
|
|
104
|
+
const absolutePath = resolve(filePath);
|
|
105
|
+
const fileContents = fs.readFileSync(absolutePath, "utf-8");
|
|
106
|
+
return JSON.parse(fileContents);
|
|
107
|
+
} catch (_error) {
|
|
108
|
+
console.error(`Error reading file: ${filePath}`);
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Takes a list of Powerhouse project packages and optionally local Powerhouse packages and outputs a js file which exports those packages for use in Connect Studio.
|
|
114
|
+
*/
|
|
115
|
+
function makeImportScriptFromPackages(args) {
|
|
116
|
+
const { packages, localJsPath, localCssPath, importStyles = true } = args;
|
|
117
|
+
const imports = [];
|
|
118
|
+
const moduleNames = [];
|
|
119
|
+
let counter = 0;
|
|
120
|
+
for (const packageName of packages) {
|
|
121
|
+
const moduleName = `module${counter}`;
|
|
122
|
+
moduleNames.push(moduleName);
|
|
123
|
+
imports.push(`import * as ${moduleName} from '${packageName}';`);
|
|
124
|
+
if (importStyles) imports.push(`import '${packageName}/style.css';`);
|
|
125
|
+
counter++;
|
|
126
|
+
}
|
|
127
|
+
const exports = moduleNames.map((name, index) => `{
|
|
128
|
+
id: "${packages[index]}",
|
|
129
|
+
...${name},
|
|
130
|
+
}`);
|
|
131
|
+
const hasModule = localJsPath !== void 0;
|
|
132
|
+
const hasStyles = importStyles && localCssPath !== void 0;
|
|
133
|
+
if (hasModule || hasStyles) {
|
|
134
|
+
if (hasStyles) imports.push(`import '${localCssPath}';`);
|
|
135
|
+
if (hasModule) {
|
|
136
|
+
const moduleName = `module${counter}`;
|
|
137
|
+
imports.push(`import * as ${moduleName} from '${localJsPath}';`);
|
|
138
|
+
exports.push(`{
|
|
139
|
+
id: "${LOCAL_PACKAGE_ID}",
|
|
140
|
+
...${moduleName},
|
|
141
|
+
}`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
const exportStatement = `export default [${exports.length ? `
|
|
145
|
+
${exports.join(",\n")}
|
|
146
|
+
` : ""}];`;
|
|
147
|
+
return `${imports.join("\n")}\n\n${exportStatement}`;
|
|
148
|
+
}
|
|
149
|
+
function ensureNodeVersion(minVersion = "24") {
|
|
150
|
+
const version = process.versions.node;
|
|
151
|
+
if (!version) return;
|
|
152
|
+
if (version < minVersion) {
|
|
153
|
+
console.error(`Node version ${minVersion} or higher is required. Current version: ${version}`);
|
|
154
|
+
process.exit(1);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
function runShellScriptPlugin(scriptName, connectPath) {
|
|
158
|
+
return {
|
|
159
|
+
name: "vite-plugin-run-shell-script",
|
|
160
|
+
buildStart() {
|
|
161
|
+
const scriptPath = join(connectPath, scriptName);
|
|
162
|
+
if (fs.existsSync(scriptPath)) exec(`sh ${scriptPath}`, (error, stdout, stderr) => {
|
|
163
|
+
if (error) {
|
|
164
|
+
console.error(`Error executing the script: ${error.message}`);
|
|
165
|
+
removeBase64EnvValues(connectPath);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (stderr) console.error(stderr);
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Shared helper to modify the <head> tag of an HTML file by transforming its contents.
|
|
175
|
+
*/
|
|
176
|
+
async function modifyHtmlHead(pathToHtml, contents, transform) {
|
|
177
|
+
if (!existsSync(pathToHtml)) throw new Error(`File ${pathToHtml} does not exist.`);
|
|
178
|
+
let html = await readFile(pathToHtml, "utf8");
|
|
179
|
+
html = transform(html, contents);
|
|
180
|
+
await writeFile(pathToHtml, html, "utf8");
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Appends the contents to the <head> tag of the index.html file
|
|
184
|
+
*/
|
|
185
|
+
async function appendToHtmlHead(pathToHtml, contents) {
|
|
186
|
+
return modifyHtmlHead(pathToHtml, contents, (html, contents) => {
|
|
187
|
+
if (!html.includes("</head>")) throw new Error("No </head> tag found in the HTML file.");
|
|
188
|
+
return html.replace("</head>", `\n${contents}\n</head>`);
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Prepends the contents to the <head> tag of the index.html file
|
|
193
|
+
*/
|
|
194
|
+
async function prependToHtmlHead(pathToHtml, contents) {
|
|
195
|
+
return modifyHtmlHead(pathToHtml, contents, (html, contents) => {
|
|
196
|
+
if (!html.includes("</head>")) throw new Error("No </head> tag found in the HTML file.");
|
|
197
|
+
return html.replace("<head>", `<head>\n${contents}\n`);
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
function runTsc(outDir) {
|
|
201
|
+
execSync(`npx tsc --outDir ${outDir}`, { stdio: "inherit" });
|
|
202
|
+
}
|
|
203
|
+
function stripVersionFromPackage(packageName) {
|
|
204
|
+
const trimmed = packageName.trim();
|
|
205
|
+
if (!trimmed) return "";
|
|
206
|
+
const lastAtIndex = trimmed.lastIndexOf("@");
|
|
207
|
+
if (lastAtIndex > 0) return trimmed.substring(0, lastAtIndex);
|
|
208
|
+
return trimmed;
|
|
209
|
+
}
|
|
210
|
+
//#endregion
|
|
211
|
+
//#region connect-utils/vite-plugins/connect-routes.ts
|
|
212
|
+
/** A project's routes for its Connect deployment, beside Connect's own. */
|
|
213
|
+
const HOST_ROUTES_DIR = "hosts/connect/routes";
|
|
214
|
+
/** The generated tree of Connect's and the project's routes. */
|
|
215
|
+
const CONNECT_ROUTES_GEN = ".ph/connect-routes.gen.ts";
|
|
216
|
+
/** Connect's dist imports its route tree by this specifier. */
|
|
217
|
+
const ROUTE_TREE_SPECIFIER = "@powerhousedao/connect/route-tree";
|
|
218
|
+
/** Core's types name the app's tree by this one; both resolve to one tree. */
|
|
219
|
+
const CORE_ROUTE_TREE_SPECIFIER = "@powerhousedao/connect-core/route-tree";
|
|
220
|
+
const ROUTE_TREE_FIND = new RegExp(`^(${[ROUTE_TREE_SPECIFIER, CORE_ROUTE_TREE_SPECIFIER].map(escapeRegExp).join("|")})$`);
|
|
221
|
+
/** A host's routes folder: `routes` (a host's `runner.routes`), relative to the
|
|
222
|
+
* project, else `hosts/connect/routes/`; undefined if none or `false`. */
|
|
223
|
+
function resolveConnectRoutesDir(projectRoot, routes) {
|
|
224
|
+
if (routes === false) return void 0;
|
|
225
|
+
if (routes !== void 0) {
|
|
226
|
+
const dir = resolve(projectRoot, routes);
|
|
227
|
+
if (!existsSync(dir)) throw new Error(`The routes folder ${routes} does not exist.`);
|
|
228
|
+
return dir;
|
|
229
|
+
}
|
|
230
|
+
const dir = join(projectRoot, HOST_ROUTES_DIR);
|
|
231
|
+
return existsSync(dir) ? dir : void 0;
|
|
232
|
+
}
|
|
233
|
+
const isDefaultRoutesDir = (projectRoot, routesDir) => resolve(routesDir) === join(resolve(projectRoot), HOST_ROUTES_DIR);
|
|
234
|
+
/** The tree generated from `routesDir`: `.ph/connect-routes.gen.ts` for
|
|
235
|
+
* `hosts/connect/routes/`, else `.ph/<folder>.gen.ts`. */
|
|
236
|
+
function connectRoutesTreeOf(projectRoot, routesDir) {
|
|
237
|
+
if (isDefaultRoutesDir(projectRoot, routesDir)) return join(projectRoot, CONNECT_ROUTES_GEN);
|
|
238
|
+
return join(projectRoot, ".ph", `${relative(projectRoot, routesDir)}.gen.ts`);
|
|
239
|
+
}
|
|
240
|
+
/** Connect's pathless sidebar layout; a project's routes in `_app/` render in it. */
|
|
241
|
+
const APP_LAYOUT = "_app";
|
|
242
|
+
function findRouteFile(dir, name) {
|
|
243
|
+
return [
|
|
244
|
+
".tsx",
|
|
245
|
+
".ts",
|
|
246
|
+
".jsx",
|
|
247
|
+
".js"
|
|
248
|
+
].map((ext) => join(dir, `${name}${ext}`)).find((file) => existsSync(file));
|
|
249
|
+
}
|
|
250
|
+
/** Connect's route files: core's routes with Connect's views. */
|
|
251
|
+
function connectRoutesDirOf(connectDir) {
|
|
252
|
+
return join(connectDir, "src/routes");
|
|
253
|
+
}
|
|
254
|
+
const ROUTE_FILE = /\.[cm]?[jt]sx?$/;
|
|
255
|
+
const isRouteEntry = (name) => !name.startsWith(".") && !name.startsWith("-");
|
|
256
|
+
/** The route files under `dir`, by path relative to it. */
|
|
257
|
+
function routeFilesIn(dir, at = "") {
|
|
258
|
+
if (!existsSync(dir)) return [];
|
|
259
|
+
return readdirSync(join(dir, at), { withFileTypes: true }).filter((entry) => isRouteEntry(entry.name)).flatMap((entry) => {
|
|
260
|
+
const path = at ? `${at}/${entry.name}` : entry.name;
|
|
261
|
+
if (entry.isDirectory()) return routeFilesIn(dir, path);
|
|
262
|
+
return ROUTE_FILE.test(entry.name) ? [path] : [];
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
/** A route file's id below its folder: route groups and `route` files
|
|
266
|
+
* resolved, flat `a.b` names read as folders. */
|
|
267
|
+
function routeIdOf(file) {
|
|
268
|
+
const segments = file.replace(ROUTE_FILE, "").split("/").filter((segment) => !/^\(.+\)$/.test(segment));
|
|
269
|
+
if (segments.at(-1) === "route") segments.pop();
|
|
270
|
+
return segments.join("/").replaceAll(".", "/");
|
|
271
|
+
}
|
|
272
|
+
/** Connect's `_app/` route files that a project file at the same id replaces. */
|
|
273
|
+
function overriddenConnectRoutes(connectAppDir, projectAppDir) {
|
|
274
|
+
const projectIds = new Set(routeFilesIn(projectAppDir).map(routeIdOf));
|
|
275
|
+
return new Set(routeFilesIn(connectAppDir).filter((file) => projectIds.has(routeIdOf(file))));
|
|
276
|
+
}
|
|
277
|
+
const stemOf = (name) => name.replace(ROUTE_FILE, "");
|
|
278
|
+
/** Mounts Connect's routes in `dir` without the `overridden` files: a folder
|
|
279
|
+
* whole when none is in it, else file by file. */
|
|
280
|
+
function mountConnectRoutes(routesDirectory, dir, overridden, prefix = "") {
|
|
281
|
+
if (![...overridden].some((file) => file.startsWith(`${dir}/`))) return [physical(prefix, dir)];
|
|
282
|
+
const entries = readdirSync(join(routesDirectory, dir), { withFileTypes: true }).filter((entry) => isRouteEntry(entry.name));
|
|
283
|
+
const files = entries.filter((entry) => entry.isFile() && ROUTE_FILE.test(entry.name)).map((entry) => entry.name);
|
|
284
|
+
const folders = entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
|
|
285
|
+
const at = (name) => prefix ? `${prefix}/${name}` : name;
|
|
286
|
+
const nodes = [];
|
|
287
|
+
for (const name of files) {
|
|
288
|
+
const file = `${dir}/${name}`;
|
|
289
|
+
const stem = stemOf(name);
|
|
290
|
+
const folder = folders.includes(stem) ? `${dir}/${stem}` : void 0;
|
|
291
|
+
if (overridden.has(file)) {
|
|
292
|
+
if (folder) nodes.push(physical(at(stem), folder));
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
const children = folder && mountConnectRoutes(routesDirectory, folder, overridden);
|
|
296
|
+
if (stem === "index") nodes.push(prefix ? route(`${prefix}/`, file) : index(file));
|
|
297
|
+
else if (!prefix && stem.startsWith("_")) nodes.push(layout(stem, file, children || []));
|
|
298
|
+
else nodes.push(children ? route(at(stem), file, children) : route(at(stem), file));
|
|
299
|
+
}
|
|
300
|
+
for (const name of folders) {
|
|
301
|
+
if (files.some((file) => stemOf(file) === name)) continue;
|
|
302
|
+
nodes.push(...mountConnectRoutes(routesDirectory, `${dir}/${name}`, overridden, at(name)));
|
|
303
|
+
}
|
|
304
|
+
return nodes;
|
|
305
|
+
}
|
|
306
|
+
/** The routes a package offers other Connects, as `ph build` publishes them
|
|
307
|
+
* (`./connect-routes`); generated beside the route tree. */
|
|
308
|
+
const PACKAGE_ROUTES_MODULE = ".ph/connect-routes.package.ts";
|
|
309
|
+
/** Writes the package's routes for registerPackageRoutes: its files but its
|
|
310
|
+
* `_app` layout and its overrides of Connect's `_app/` routes, parents first. */
|
|
311
|
+
function writePackageRoutesModule(projectRoot, projectRoutes, routeNodes, options) {
|
|
312
|
+
const module = join(projectRoot, PACKAGE_ROUTES_MODULE);
|
|
313
|
+
const appDir = join(projectRoutes, APP_LAYOUT);
|
|
314
|
+
const offered = routeNodes.map((node) => ({
|
|
315
|
+
node,
|
|
316
|
+
file: join(options.routesDirectory, node.filePath)
|
|
317
|
+
})).filter(({ node, file }) => {
|
|
318
|
+
if (!file.startsWith(`${projectRoutes}${sep}`)) return false;
|
|
319
|
+
if (node.routePath === `/_app`) return false;
|
|
320
|
+
if (!file.startsWith(`${appDir}${sep}`)) return true;
|
|
321
|
+
const id = routeIdOf(relative(appDir, file).split(sep).join("/"));
|
|
322
|
+
return !options.connectAppIds.has(id);
|
|
323
|
+
}).sort((a, b) => (a.node.routePath ?? "").split("/").length - (b.node.routePath ?? "").split("/").length);
|
|
324
|
+
if (offered.length === 0) {
|
|
325
|
+
rmSync(module, { force: true });
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
const from = (file) => {
|
|
329
|
+
return relative(dirname(module), file).split(sep).join("/").replace(ROUTE_FILE, ".js");
|
|
330
|
+
};
|
|
331
|
+
const lines = [
|
|
332
|
+
"// Generated by ph build: the routes this package offers other Connects.",
|
|
333
|
+
"import type { PackageRoute } from \"@powerhousedao/connect-core/router\";",
|
|
334
|
+
...offered.map(({ file }, i) => `import { Route as r${i} } from "${from(file)}";`),
|
|
335
|
+
"",
|
|
336
|
+
"export const connectRoutes: PackageRoute[] = [",
|
|
337
|
+
...offered.map(({ node }, i) => {
|
|
338
|
+
const pathless = node._fsRouteType === "pathless_layout";
|
|
339
|
+
const entry = {
|
|
340
|
+
id: node.routePath,
|
|
341
|
+
...pathless ? {} : { path: node.path },
|
|
342
|
+
parentId: node.parent?.routePath ?? "__root__"
|
|
343
|
+
};
|
|
344
|
+
return ` { route: r${i}, ${Object.entries(entry).map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join(", ")} },`;
|
|
345
|
+
}),
|
|
346
|
+
"];",
|
|
347
|
+
""
|
|
348
|
+
];
|
|
349
|
+
mkdirSync(dirname(module), { recursive: true });
|
|
350
|
+
const text = lines.join("\n");
|
|
351
|
+
if (!existsSync(module) || readFileSync(module, "utf8") !== text) writeFileSync(module, text);
|
|
352
|
+
}
|
|
353
|
+
/** The router plugin's config: Connect's root and routes, and the project's. */
|
|
354
|
+
function connectRoutesGeneratorConfig(connectDir, projectRoot, projectRoutes) {
|
|
355
|
+
const routesDirectory = connectRoutesDirOf(connectDir);
|
|
356
|
+
const fromRoutes = (path) => relative(routesDirectory, path);
|
|
357
|
+
const virtualRouteConfig = () => {
|
|
358
|
+
const appLayout = findRouteFile(projectRoutes, APP_LAYOUT);
|
|
359
|
+
const appRoutes = join(projectRoutes, APP_LAYOUT);
|
|
360
|
+
const overridden = new Set([...overriddenConnectRoutes(join(routesDirectory, APP_LAYOUT), appRoutes)].map((file) => `${APP_LAYOUT}/${file}`));
|
|
361
|
+
return rootRoute("__root.tsx", [layout(APP_LAYOUT, appLayout ? fromRoutes(appLayout) : `${APP_LAYOUT}.tsx`, [...mountConnectRoutes(routesDirectory, APP_LAYOUT, overridden), ...existsSync(appRoutes) ? [physical("", fromRoutes(appRoutes))] : []]), physical("", fromRoutes(projectRoutes))]);
|
|
362
|
+
};
|
|
363
|
+
const overrides = {
|
|
364
|
+
name: "ph-connect-route-overrides",
|
|
365
|
+
init: ({ generator }) => {
|
|
366
|
+
Object.defineProperty(generator.config, "virtualRouteConfig", {
|
|
367
|
+
get: virtualRouteConfig,
|
|
368
|
+
configurable: true,
|
|
369
|
+
enumerable: true
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
const offers = isDefaultRoutesDir(projectRoot, projectRoutes);
|
|
374
|
+
return getConfig({
|
|
375
|
+
target: "react",
|
|
376
|
+
routesDirectory,
|
|
377
|
+
generatedRouteTree: connectRoutesTreeOf(projectRoot, projectRoutes),
|
|
378
|
+
virtualRouteConfig: virtualRouteConfig(),
|
|
379
|
+
plugins: offers ? [overrides, {
|
|
380
|
+
name: "ph-connect-offered-routes",
|
|
381
|
+
onRouteTreeChanged: ({ routeNodes }) => {
|
|
382
|
+
writePackageRoutesModule(projectRoot, projectRoutes, routeNodes, {
|
|
383
|
+
routesDirectory,
|
|
384
|
+
connectAppIds: new Set(routeFilesIn(join(routesDirectory, APP_LAYOUT)).map(routeIdOf))
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
}] : [overrides],
|
|
388
|
+
routeFileIgnorePattern: `^${APP_LAYOUT}(\\.[cm]?[jt]sx?)?$`,
|
|
389
|
+
quoteStyle: "double",
|
|
390
|
+
semicolons: true,
|
|
391
|
+
addExtensions: "js",
|
|
392
|
+
autoCodeSplitting: true,
|
|
393
|
+
disableLogging: true,
|
|
394
|
+
routeTreeFileFooter: [
|
|
395
|
+
"import type { ConnectRouterFor } from \"@powerhousedao/connect/router\";",
|
|
396
|
+
"declare module \"@tanstack/react-router\" {",
|
|
397
|
+
" interface Register {",
|
|
398
|
+
" router: ConnectRouterFor<typeof routeTree>;",
|
|
399
|
+
" }",
|
|
400
|
+
"}"
|
|
401
|
+
]
|
|
402
|
+
}, projectRoot);
|
|
403
|
+
}
|
|
404
|
+
/** Writes the route tree of Connect's and the project's routes; throws on a
|
|
405
|
+
* collision that is not an override, which the router plugin would only log. */
|
|
406
|
+
async function generateConnectRoutes(projectRoot, routesDir, config = connectRoutesGeneratorConfig(connectDirOf(projectRoot), projectRoot, routesDir)) {
|
|
407
|
+
mkdirSync(dirname(config.generatedRouteTree), { recursive: true });
|
|
408
|
+
try {
|
|
409
|
+
await new Generator({
|
|
410
|
+
config,
|
|
411
|
+
root: projectRoot
|
|
412
|
+
}).run();
|
|
413
|
+
assertNoDuplicateRoutes(config.generatedRouteTree);
|
|
414
|
+
importConnectRoutesByPackage(config.generatedRouteTree, config.routesDirectory);
|
|
415
|
+
} catch (error) {
|
|
416
|
+
const message = (Array.isArray(error) ? error : [error]).map((e) => e instanceof Error ? e.message : String(e)).join("\n");
|
|
417
|
+
const shown = relative(projectRoot, routesDir).split(sep).join("/");
|
|
418
|
+
throw new Error(`Connect could not mount the routes in ${shown}/:\n${message}`, { cause: error });
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
/** Connect's route files, as the generated tree imports them: by Connect's
|
|
422
|
+
* package name, which a project depends on. */
|
|
423
|
+
const CONNECT_ROUTES_SPECIFIER = "@powerhousedao/connect/routes";
|
|
424
|
+
function importConnectRoutesByPackage(treeFile, routesDirectory) {
|
|
425
|
+
const prefix = `"./${relative(dirname(treeFile), routesDirectory).split(sep).join("/")}/`;
|
|
426
|
+
const tree = readFileSync(treeFile, "utf8");
|
|
427
|
+
const rewritten = tree.replace(new RegExp(`${escapeRegExp(prefix)}([^"]+)\\.js"`, "g"), `"${CONNECT_ROUTES_SPECIFIER}/$1"`);
|
|
428
|
+
if (rewritten !== tree) writeFileSync(treeFile, rewritten);
|
|
429
|
+
}
|
|
430
|
+
function assertNoDuplicateRoutes(treeFile) {
|
|
431
|
+
const tree = readFileSync(treeFile, "utf8");
|
|
432
|
+
const files = /* @__PURE__ */ new Map();
|
|
433
|
+
for (const [, name, file] of tree.matchAll(/^import \{ Route as (\w+) \} from "([^"]+)";$/gm)) files.set(name, [...files.get(name) ?? [], file]);
|
|
434
|
+
const conflicts = [...files.values()].filter((list) => list.length > 1);
|
|
435
|
+
if (conflicts.length === 0) return;
|
|
436
|
+
throw new Error(`Conflicting configuration paths were found for a layout route.\nConflicting files: \n ${conflicts.flat().join("\n ")}\n`);
|
|
437
|
+
}
|
|
438
|
+
function escapeRegExp(text) {
|
|
439
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
440
|
+
}
|
|
441
|
+
/** Generates the tree when the project has routes, else drops a stale one. */
|
|
442
|
+
async function syncConnectRoutes(projectRoot, routesDir = resolveConnectRoutesDir(projectRoot)) {
|
|
443
|
+
if (routesDir) await generateConnectRoutes(projectRoot, routesDir);
|
|
444
|
+
else {
|
|
445
|
+
rmSync(join(projectRoot, CONNECT_ROUTES_GEN), { force: true });
|
|
446
|
+
rmSync(join(projectRoot, PACKAGE_ROUTES_MODULE), { force: true });
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
function connectDirOf(projectRoot) {
|
|
450
|
+
return dirname(resolvePackage("@powerhousedao/connect/package.json", projectRoot));
|
|
451
|
+
}
|
|
452
|
+
/** Mounts a project's routes folder over Connect's routes; without one,
|
|
453
|
+
* Connect keeps its prebuilt tree and no router plugin runs. */
|
|
454
|
+
function connectRoutes(projectRoot, routesDir = resolveConnectRoutesDir(projectRoot)) {
|
|
455
|
+
const connectDir = connectDirOf(projectRoot);
|
|
456
|
+
const find = ROUTE_TREE_FIND;
|
|
457
|
+
if (!routesDir) {
|
|
458
|
+
if (!resolveConnectRoutesDir(projectRoot)) rmSync(join(projectRoot, CONNECT_ROUTES_GEN), { force: true });
|
|
459
|
+
return {
|
|
460
|
+
aliases: [{
|
|
461
|
+
find,
|
|
462
|
+
replacement: join(connectDir, "dist/route-tree.js")
|
|
463
|
+
}],
|
|
464
|
+
plugins: [],
|
|
465
|
+
dedupe: []
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
const config = connectRoutesGeneratorConfig(connectDir, projectRoot, routesDir);
|
|
469
|
+
mkdirSync(dirname(config.generatedRouteTree), { recursive: true });
|
|
470
|
+
return {
|
|
471
|
+
aliases: [{
|
|
472
|
+
find,
|
|
473
|
+
replacement: config.generatedRouteTree
|
|
474
|
+
}, {
|
|
475
|
+
find: /^@powerhousedao\/connect\/route-views$/,
|
|
476
|
+
replacement: join(connectDir, "dist/route-views.js")
|
|
477
|
+
}],
|
|
478
|
+
plugins: [{
|
|
479
|
+
name: "ph-connect-routes-check",
|
|
480
|
+
buildStart: () => generateConnectRoutes(projectRoot, routesDir, config)
|
|
481
|
+
}, tanstackRouter(config)],
|
|
482
|
+
dedupe: ["@tanstack/react-router"]
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
const ROUTER_PACKAGES = /[\\/]node_modules[\\/]@tanstack[\\/](react-router|router-core|history|react-store|store)[\\/]/;
|
|
486
|
+
/** One chunk for the router and the project's route configs, which the split
|
|
487
|
+
* route components would otherwise spread over several shared chunks. */
|
|
488
|
+
function connectRouterChunkGroups(routesDir) {
|
|
489
|
+
const routes = routesDir && join(routesDir, sep);
|
|
490
|
+
return [
|
|
491
|
+
{
|
|
492
|
+
name: "preload-helper",
|
|
493
|
+
test: /vite[\\/]preload-helper/,
|
|
494
|
+
priority: 1
|
|
495
|
+
},
|
|
496
|
+
{
|
|
497
|
+
name: "use-sync-external-store",
|
|
498
|
+
test: /[\\/]node_modules[\\/]use-sync-external-store[\\/]/,
|
|
499
|
+
priority: 1
|
|
500
|
+
},
|
|
501
|
+
{
|
|
502
|
+
name: "router",
|
|
503
|
+
test: (id) => ROUTER_PACKAGES.test(id) || !!routes && id.startsWith(routes) && !id.includes("tsr-split")
|
|
504
|
+
}
|
|
505
|
+
];
|
|
506
|
+
}
|
|
507
|
+
//#endregion
|
|
508
|
+
//#region connect-utils/vite-plugins/host-stylesheet.ts
|
|
509
|
+
/** The host's stylesheet, which may not exist yet: `style.css` beside its routes
|
|
510
|
+
* folder, so `hosts/connect/style.css` by default. `ph build` never reads it. */
|
|
511
|
+
function hostStylesheetPath(projectRoot, routesDir) {
|
|
512
|
+
const hostDir = routesDir ? dirname(routesDir) : join(projectRoot, dirname(HOST_ROUTES_DIR));
|
|
513
|
+
return join(hostDir, "style.css");
|
|
514
|
+
}
|
|
515
|
+
const importOf = (stylesheet, file) => `@import ${JSON.stringify(`./${normalizePath(relative(dirname(stylesheet), file))}`)};`;
|
|
516
|
+
/** The project's `style.css` with the host's stylesheet imported last when it
|
|
517
|
+
* exists (else `missing`), so the host's theme wins in the page's one build. */
|
|
518
|
+
function withHostStylesheet(css, stylesheet, hostStylesheet, missing) {
|
|
519
|
+
const file = hostStylesheet && existsSync(hostStylesheet) ? hostStylesheet : missing;
|
|
520
|
+
return file ? `${css}\n${importOf(stylesheet, file)}\n` : css;
|
|
521
|
+
}
|
|
522
|
+
/** Serves the project's `style.css` with the host's stylesheet in it. */
|
|
523
|
+
function hostStylesheetPlugin(projectRoot, hostStylesheet) {
|
|
524
|
+
const stylesheet = join(projectRoot, "style.css");
|
|
525
|
+
const stylesheetId = normalizePath(stylesheet);
|
|
526
|
+
const hostId = normalizePath(hostStylesheet);
|
|
527
|
+
let placeholder;
|
|
528
|
+
return {
|
|
529
|
+
name: "ph-host-stylesheet",
|
|
530
|
+
enforce: "pre",
|
|
531
|
+
configResolved(config) {
|
|
532
|
+
if (config.command !== "serve") return;
|
|
533
|
+
placeholder = join(config.cacheDir, "ph-host-stylesheet.css");
|
|
534
|
+
mkdirSync(dirname(placeholder), { recursive: true });
|
|
535
|
+
writeFileSync(placeholder, "/* Until the host's style.css exists. */\n");
|
|
536
|
+
},
|
|
537
|
+
load(id) {
|
|
538
|
+
if (normalizePath(id.split("?")[0]) !== stylesheetId) return null;
|
|
539
|
+
return withHostStylesheet(readFileSync(stylesheet, "utf8"), stylesheet, hostStylesheet, placeholder);
|
|
540
|
+
},
|
|
541
|
+
hotUpdate(ctx) {
|
|
542
|
+
if (normalizePath(ctx.file) !== hostId) return;
|
|
543
|
+
if (ctx.type === "create" && placeholder && existsSync(placeholder)) {
|
|
544
|
+
const now = /* @__PURE__ */ new Date();
|
|
545
|
+
utimesSync(placeholder, now, now);
|
|
546
|
+
}
|
|
547
|
+
const modules = this.environment.moduleGraph.getModulesByFile(stylesheetId);
|
|
548
|
+
return [...ctx.modules, ...modules ?? []];
|
|
549
|
+
}
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
//#endregion
|
|
553
|
+
//#region connect-utils/vite-plugins/app-shell.ts
|
|
554
|
+
/** On the prerendered shell's elements; marks an index.html that has it. */
|
|
555
|
+
const APP_SHELL_MARKER = "data-ph-shell";
|
|
556
|
+
/** In Connect's dist, and copied to a project's: the plugins that pick a shell. */
|
|
557
|
+
const SHELL_PLUGINS_FILE = "shell-plugins.json";
|
|
558
|
+
/** In a project's dist: every variant, for a server that swaps the shell to the served composition. */
|
|
559
|
+
const APP_SHELLS_FILE = "app-shells.json";
|
|
560
|
+
const SHELL_FILES = {
|
|
561
|
+
generic: "shell",
|
|
562
|
+
core: "shell-core"
|
|
563
|
+
};
|
|
564
|
+
/** The shell of the composition's first plugin that has one, else core's; no composition is classic.
|
|
565
|
+
* Without `plugins` (an older Connect): core for a composition, generic for classic. */
|
|
566
|
+
function appShellVariant(composition, plugins) {
|
|
567
|
+
if (!plugins) return composition ? "core" : "generic";
|
|
568
|
+
if (!composition) return Object.values(plugins)[0] ?? "core";
|
|
569
|
+
for (const { module } of composition) if (Object.hasOwn(plugins, module)) return plugins[module];
|
|
570
|
+
return "core";
|
|
571
|
+
}
|
|
572
|
+
function connectDistDir(projectRoot) {
|
|
573
|
+
try {
|
|
574
|
+
return join(dirname(resolvePackage("@powerhousedao/connect/package.json", projectRoot)), "dist");
|
|
575
|
+
} catch {
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
/** The plugins' shell manifest in `dir`, if there is a valid one. */
|
|
580
|
+
function readShellPluginsIn(dir) {
|
|
581
|
+
const file = join(dir, SHELL_PLUGINS_FILE);
|
|
582
|
+
if (!existsSync(file)) return void 0;
|
|
583
|
+
try {
|
|
584
|
+
const manifest = JSON.parse(readFileSync(file, "utf8"));
|
|
585
|
+
if (!manifest || typeof manifest !== "object") return void 0;
|
|
586
|
+
const plugins = {};
|
|
587
|
+
for (const [module, variant] of Object.entries(manifest)) if (variant === "generic" || variant === "core") plugins[module] = variant;
|
|
588
|
+
return plugins;
|
|
589
|
+
} catch {
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
/** The shell manifest of the installed Connect, if it ships one. */
|
|
594
|
+
function readShellPlugins(projectRoot) {
|
|
595
|
+
const distDir = connectDistDir(projectRoot);
|
|
596
|
+
return distDir ? readShellPluginsIn(distDir) : void 0;
|
|
597
|
+
}
|
|
598
|
+
/** The shell Connect's build prerendered, if the installed Connect ships one. */
|
|
599
|
+
function readAppShell(projectRoot, variant = "generic") {
|
|
600
|
+
const distDir = connectDistDir(projectRoot);
|
|
601
|
+
if (!distDir) return void 0;
|
|
602
|
+
const body = join(distDir, `${SHELL_FILES[variant]}.html`);
|
|
603
|
+
const head = join(distDir, `${SHELL_FILES[variant]}-head.html`);
|
|
604
|
+
if (!existsSync(body) || !existsSync(head)) return void 0;
|
|
605
|
+
return {
|
|
606
|
+
body: readFileSync(body, "utf8"),
|
|
607
|
+
head: readFileSync(head, "utf8")
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
/** Every variant the installed Connect ships. */
|
|
611
|
+
function readAppShells(projectRoot) {
|
|
612
|
+
const shells = {};
|
|
613
|
+
for (const variant of Object.keys(SHELL_FILES)) {
|
|
614
|
+
const shell = readAppShell(projectRoot, variant);
|
|
615
|
+
if (shell) shells[variant] = shell;
|
|
616
|
+
}
|
|
617
|
+
return shells;
|
|
618
|
+
}
|
|
619
|
+
/** On the boot-recovery script; its sessionStorage key guards against reload loops. */
|
|
620
|
+
const BOOT_RECOVER_MARKER = "data-ph-boot-recover";
|
|
621
|
+
const BOOT_RECOVER_KEY = "ph:sw-recover";
|
|
622
|
+
const BOOT_RECOVER_SCRIPT = `(function(){try{var K='${BOOT_RECOVER_KEY}',n=navigator.serviceWorker,done=0;if(!n||sessionStorage.getItem(K))return;var up=function(){return !document.querySelector('style[${APP_SHELL_MARKER}]')};var reload=function(){location.reload()};var skip=function(w){try{sessionStorage.setItem(K,'1')}catch(e){}n.addEventListener('controllerchange',reload);w.postMessage({type:'SKIP_WAITING'});setTimeout(reload,3000)};var watch=function(w){w.addEventListener('statechange',function(){if(w.state==='installed')skip(w)})};var go=function(){if(done||up())return;done=1;n.getRegistration().then(function(r){if(!r)return;if(r.waiting)return skip(r.waiting);if(r.installing)return watch(r.installing);r.addEventListener('updatefound',function(){if(r.installing)watch(r.installing)});return r.update()}).catch(function(){})};addEventListener('error',function(e){var t=e.target;if(e.error instanceof SyntaxError||e.error instanceof TypeError||(t&&t.tagName==='SCRIPT'))go()},true);addEventListener('unhandledrejection',function(e){if(e.reason instanceof SyntaxError||e.reason instanceof TypeError)go()});setTimeout(go,8000)}catch(e){}})();`;
|
|
623
|
+
/** Prefixes the shell's root-relative links with the deploy base. */
|
|
624
|
+
function rebaseShellLinks(body, base) {
|
|
625
|
+
if (base === "/" || !base) return body;
|
|
626
|
+
const prefix = base.endsWith("/") ? base : `${base}/`;
|
|
627
|
+
return body.replace(/(\shref=")\/(?!\/)/g, `$1${prefix}`);
|
|
628
|
+
}
|
|
629
|
+
const STYLESHEET_LINK = /<link\b(?=[^>]*\brel=["']?stylesheet\b)[^>]*>/gi;
|
|
630
|
+
function deferStylesheet(link) {
|
|
631
|
+
return `${link.replace(/\brel=["']?stylesheet["']?/i, "rel=\"preload\" as=\"style\"").replace(/\/?>$/, ` onload="this.onload=null;this.rel='stylesheet'">`)}<noscript>${link}</noscript>`;
|
|
632
|
+
}
|
|
633
|
+
const region = (name, content) => `<!--ph-shell:${name}-->${content}<!--/ph-shell:${name}-->`;
|
|
634
|
+
const REGION = (name) => new RegExp(`<!--ph-shell:${name}-->[\\s\\S]*?<!--/ph-shell:${name}-->`);
|
|
635
|
+
/** The app's title without `connect.branding.appName`; core's `appTitle` fallback. */
|
|
636
|
+
const DEFAULT_APP_NAME = "Connect";
|
|
637
|
+
const APP_NAME = /(<!--ph-shell:app-name-->)[\s\S]*?(<!--\/ph-shell:app-name-->)/g;
|
|
638
|
+
const escapeHtml = (text) => text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
639
|
+
/** Fills the shell's app name as the app resolves it: the branding name, else the default. */
|
|
640
|
+
function withShellAppName(html, appName) {
|
|
641
|
+
const name = escapeHtml(appName || "Connect");
|
|
642
|
+
return html.replace(APP_NAME, (_m, open, close) => [
|
|
643
|
+
open,
|
|
644
|
+
name,
|
|
645
|
+
close
|
|
646
|
+
].join(""));
|
|
647
|
+
}
|
|
648
|
+
/** Inlines `shell` into an empty `#root`, adds its critical CSS and, unless
|
|
649
|
+
* `deferStyles` is false, defers the stylesheets; React replaces the markup when the app renders. */
|
|
650
|
+
function injectAppShell(html, shell, base = "/", { deferStyles = true, appName } = {}) {
|
|
651
|
+
if (html.includes("data-ph-shell")) return html;
|
|
652
|
+
const root = /<div id="root"><\/div>/;
|
|
653
|
+
if (!root.test(html)) return html;
|
|
654
|
+
const firstSheet = html.search(STYLESHEET_LINK);
|
|
655
|
+
const at = firstSheet >= 0 ? firstSheet : html.indexOf("</head>");
|
|
656
|
+
const recover = `<script ${BOOT_RECOVER_MARKER}>${BOOT_RECOVER_SCRIPT}<\/script>`;
|
|
657
|
+
const body = withShellAppName(rebaseShellLinks(shell.body, base), appName);
|
|
658
|
+
const withHead = html.slice(0, at) + region("head", shell.head) + recover + html.slice(at);
|
|
659
|
+
return (deferStyles ? withHead.replace(STYLESHEET_LINK, deferStylesheet) : withHead).replace(root, () => `<div id="root">${region("body", body)}</div>`);
|
|
660
|
+
}
|
|
661
|
+
/** The variant an index.html carries, from its shell's marker value. */
|
|
662
|
+
function appShellVariantOf(html) {
|
|
663
|
+
const head = REGION("head").exec(html)?.[0];
|
|
664
|
+
const value = head && new RegExp(`data-ph-shell="(\\w+)"`).exec(head);
|
|
665
|
+
if (!value) return void 0;
|
|
666
|
+
return value[1] === "core" ? "core" : "generic";
|
|
667
|
+
}
|
|
668
|
+
/** Replaces the shell an index.html carries with `shell`, titled `appName`; a page without one is unchanged. */
|
|
669
|
+
function swapAppShell(html, shell, base = "/", appName) {
|
|
670
|
+
if (!REGION("head").test(html) || !REGION("body").test(html)) return html;
|
|
671
|
+
const body = withShellAppName(rebaseShellLinks(shell.body, base), appName);
|
|
672
|
+
return html.replace(REGION("head"), () => region("head", shell.head)).replace(REGION("body"), () => region("body", body));
|
|
673
|
+
}
|
|
674
|
+
const DEV_SHELL_WAIT_MS = 1e4;
|
|
675
|
+
async function renderProjectAppShells(projectRoot, config, routeAliases, hostStylesheet) {
|
|
676
|
+
const server = await createServer({
|
|
677
|
+
configFile: false,
|
|
678
|
+
root: projectRoot,
|
|
679
|
+
logLevel: "error",
|
|
680
|
+
appType: "custom",
|
|
681
|
+
server: {
|
|
682
|
+
middlewareMode: true,
|
|
683
|
+
hmr: false,
|
|
684
|
+
ws: false
|
|
685
|
+
},
|
|
686
|
+
oxc: { jsx: { runtime: "automatic" } },
|
|
687
|
+
resolve: {
|
|
688
|
+
alias: routeAliases,
|
|
689
|
+
dedupe: config.resolve.dedupe,
|
|
690
|
+
tsconfigPaths: true
|
|
691
|
+
},
|
|
692
|
+
define: config.define,
|
|
693
|
+
cacheDir: join(projectRoot, "node_modules/.vite-ph-prerender"),
|
|
694
|
+
optimizeDeps: {
|
|
695
|
+
noDiscovery: true,
|
|
696
|
+
include: [],
|
|
697
|
+
entries: []
|
|
698
|
+
},
|
|
699
|
+
ssr: { optimizeDeps: {
|
|
700
|
+
noDiscovery: true,
|
|
701
|
+
include: []
|
|
702
|
+
} }
|
|
703
|
+
});
|
|
704
|
+
try {
|
|
705
|
+
const renderer = await server.ssrLoadModule("@powerhousedao/connect/prerender");
|
|
706
|
+
const stylesheet = join(projectRoot, "style.css");
|
|
707
|
+
const css = withHostStylesheet(readFileSync(stylesheet, "utf8"), stylesheet, hostStylesheet);
|
|
708
|
+
return await renderer.renderProjectShells(stylesheet, css);
|
|
709
|
+
} finally {
|
|
710
|
+
await server.close();
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
const sourceText = (source) => typeof source === "string" ? source : new TextDecoder().decode(source);
|
|
714
|
+
/** Build: the composition's shell in #root and every variant in the dist, from
|
|
715
|
+
* the project's routes when it has them. Dev: the shell from the project's routes
|
|
716
|
+
* when it has them, else core's for a core composition. */
|
|
717
|
+
function connectAppShellPlugin(projectRoot, { composition, appName, routeAliases, routesDir, hostStylesheet } = {}) {
|
|
718
|
+
let variant = "generic";
|
|
719
|
+
let shells = {};
|
|
720
|
+
let shellPlugins;
|
|
721
|
+
let base = "/";
|
|
722
|
+
let isBuild = true;
|
|
723
|
+
let config;
|
|
724
|
+
const fromRoutes = () => isBuild && !!routeAliases;
|
|
725
|
+
const shell = () => {
|
|
726
|
+
if (fromRoutes()) return void 0;
|
|
727
|
+
return isBuild || variant === "core" ? shells[variant] : void 0;
|
|
728
|
+
};
|
|
729
|
+
let devShells;
|
|
730
|
+
let devRender;
|
|
731
|
+
const renderDevShells = () => {
|
|
732
|
+
if (!config || !routeAliases) return;
|
|
733
|
+
const logger = config.logger;
|
|
734
|
+
devShells = renderProjectAppShells(projectRoot, config, routeAliases, hostStylesheet).catch((error) => {
|
|
735
|
+
logger.warn(`[connect] the loading shell failed to render from the project's routes: ${String(error)}`);
|
|
736
|
+
return {};
|
|
737
|
+
});
|
|
738
|
+
};
|
|
739
|
+
const devShell = async () => {
|
|
740
|
+
if (!devShells) return void 0;
|
|
741
|
+
let timer;
|
|
742
|
+
const wait = new Promise((resolve) => {
|
|
743
|
+
timer = setTimeout(() => resolve(void 0), DEV_SHELL_WAIT_MS);
|
|
744
|
+
});
|
|
745
|
+
try {
|
|
746
|
+
return (await Promise.race([devShells, wait]))?.[variant];
|
|
747
|
+
} finally {
|
|
748
|
+
clearTimeout(timer);
|
|
749
|
+
}
|
|
750
|
+
};
|
|
751
|
+
return {
|
|
752
|
+
name: "ph-connect-app-shell",
|
|
753
|
+
configureServer(server) {
|
|
754
|
+
if (!routeAliases) return;
|
|
755
|
+
renderDevShells();
|
|
756
|
+
const stylesheet = join(projectRoot, "style.css");
|
|
757
|
+
const rerender = (file) => {
|
|
758
|
+
if (!(file === stylesheet || file === hostStylesheet || !!routesDir && file.startsWith(`${routesDir}${sep}`))) return;
|
|
759
|
+
clearTimeout(devRender);
|
|
760
|
+
devRender = setTimeout(renderDevShells, 300);
|
|
761
|
+
};
|
|
762
|
+
server.watcher.on("change", rerender);
|
|
763
|
+
server.watcher.on("add", rerender);
|
|
764
|
+
server.watcher.on("unlink", rerender);
|
|
765
|
+
},
|
|
766
|
+
configResolved(resolved) {
|
|
767
|
+
config = resolved;
|
|
768
|
+
base = resolved.base;
|
|
769
|
+
isBuild = resolved.command === "build";
|
|
770
|
+
shells = readAppShells(projectRoot);
|
|
771
|
+
shellPlugins = readShellPlugins(projectRoot);
|
|
772
|
+
variant = appShellVariant(composition, shellPlugins);
|
|
773
|
+
},
|
|
774
|
+
transformIndexHtml: {
|
|
775
|
+
order: "post",
|
|
776
|
+
handler: async (html) => {
|
|
777
|
+
const current = !isBuild && routeAliases ? await devShell() : shell();
|
|
778
|
+
return current ? injectAppShell(html, current, base, {
|
|
779
|
+
deferStyles: isBuild,
|
|
780
|
+
appName
|
|
781
|
+
}) : html;
|
|
782
|
+
}
|
|
783
|
+
},
|
|
784
|
+
generateBundle: {
|
|
785
|
+
order: "post",
|
|
786
|
+
async handler(_options, bundle) {
|
|
787
|
+
if (!isBuild) return;
|
|
788
|
+
if (fromRoutes() && config && routeAliases) {
|
|
789
|
+
shells = await renderProjectAppShells(projectRoot, config, routeAliases, hostStylesheet);
|
|
790
|
+
const index = bundle["index.html"];
|
|
791
|
+
const current = shells[variant];
|
|
792
|
+
if (index?.type === "asset" && current) index.source = injectAppShell(sourceText(index.source), current, base, { appName });
|
|
793
|
+
}
|
|
794
|
+
if (!Object.keys(shells).length) return;
|
|
795
|
+
this.emitFile({
|
|
796
|
+
type: "asset",
|
|
797
|
+
fileName: APP_SHELLS_FILE,
|
|
798
|
+
source: JSON.stringify(shells)
|
|
799
|
+
});
|
|
800
|
+
if (shellPlugins) this.emitFile({
|
|
801
|
+
type: "asset",
|
|
802
|
+
fileName: SHELL_PLUGINS_FILE,
|
|
803
|
+
source: JSON.stringify(shellPlugins)
|
|
804
|
+
});
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
//#endregion
|
|
25
810
|
//#region connect-utils/vite-plugins/build-hash.ts
|
|
26
811
|
/** Name of the build-identity file emitted into the build output. */
|
|
27
812
|
const BUILD_HASH_FILE = "build-hash.json";
|
|
@@ -44,7 +829,8 @@ function computeBuildHash(input) {
|
|
|
44
829
|
*/
|
|
45
830
|
function readConnectVersion(projectRoot) {
|
|
46
831
|
try {
|
|
47
|
-
|
|
832
|
+
const entry = createRequire(join(projectRoot, "package.json")).resolve("@powerhousedao/connect", { paths: [projectRoot] });
|
|
833
|
+
let dir = dirname(entry);
|
|
48
834
|
for (;;) {
|
|
49
835
|
try {
|
|
50
836
|
const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8"));
|
|
@@ -91,16 +877,6 @@ function connectBuildHashPlugin(buildHash) {
|
|
|
91
877
|
//#endregion
|
|
92
878
|
//#region connect-utils/vite-plugins/dynamic-base.ts
|
|
93
879
|
/**
|
|
94
|
-
* Placeholder base used when Connect is built in dynamic-base mode. The Vite
|
|
95
|
-
* `base` option is set to this token; this plugin rewrites it in the emitted
|
|
96
|
-
* output so the effective base is resolved at serve time from a global instead
|
|
97
|
-
* of being baked at build time.
|
|
98
|
-
*
|
|
99
|
-
* Trailing slash matches `normalizeBasePath` output, so the token sits in the
|
|
100
|
-
* same syntactic position as a concrete base would.
|
|
101
|
-
*/
|
|
102
|
-
const DYNAMIC_BASE_PLACEHOLDER = "/__PH_DYNAMIC_BASE__/";
|
|
103
|
-
/**
|
|
104
880
|
* Global the runtime (ph-clint proxy) must set before the entry bundle loads.
|
|
105
881
|
* Value is the normalized deploy base, e.g. "/myagent/" or "/". The JS rewrite
|
|
106
882
|
* below resolves all asset / lazy-chunk / BASE_URL references against it.
|
|
@@ -108,9 +884,19 @@ const DYNAMIC_BASE_PLACEHOLDER = "/__PH_DYNAMIC_BASE__/";
|
|
|
108
884
|
const RUNTIME_GLOBAL = "globalThis.__PH_DYNAMIC_BASE__";
|
|
109
885
|
const BASE_EXPR = `(${RUNTIME_GLOBAL}||"/")`;
|
|
110
886
|
function workerPrelude(stripPrefix) {
|
|
111
|
-
|
|
887
|
+
const prefix = escapeForRegExp(stripPrefix).replace(/\//g, "\\/");
|
|
888
|
+
return `${RUNTIME_GLOBAL}=self.location.pathname.replace(/${prefix}assets\\/[^/]*$/,"");\n`;
|
|
112
889
|
}
|
|
113
890
|
const PLACEHOLDER_LITERAL = new RegExp(`(["'\`])${escapeForRegExp(DYNAMIC_BASE_PLACEHOLDER)}((?:(?!\\1)[^$])*)\\1`, "g");
|
|
891
|
+
const PLACEHOLDER_CSS_URL = new RegExp(`url\\(\\s*(["']?)${escapeForRegExp(DYNAMIC_BASE_PLACEHOLDER)}([^"')]*)\\1\\s*\\)`, "g");
|
|
892
|
+
/** Rewrites `url(<placeholder>assets/x)` relative to the stylesheet at `fileName`. */
|
|
893
|
+
function relativeCssUrls(css, fileName) {
|
|
894
|
+
const dir = path.posix.dirname(fileName);
|
|
895
|
+
return css.replace(PLACEHOLDER_CSS_URL, (_match, quote, target) => {
|
|
896
|
+
const relative = path.posix.relative(dir, target);
|
|
897
|
+
return `url(${quote}${relative.startsWith(".") ? relative : `./${relative}`}${quote})`;
|
|
898
|
+
});
|
|
899
|
+
}
|
|
114
900
|
/**
|
|
115
901
|
* Rewrites the placeholder base in emitted JS chunks to a runtime expression so
|
|
116
902
|
* one built `dist/connect` serves under any subpath. Rolldown-native: per-match
|
|
@@ -135,16 +921,16 @@ const PLACEHOLDER_LITERAL = new RegExp(`(["'\`])${escapeForRegExp(DYNAMIC_BASE_P
|
|
|
135
921
|
* (the same proxy also sets the runtime global for the JS rewrite). See the
|
|
136
922
|
* plugin's module doc / report for the exact serve-time contract.
|
|
137
923
|
*
|
|
138
|
-
* CSS `url(...)` references
|
|
139
|
-
*
|
|
140
|
-
*
|
|
924
|
+
* CSS `url(...)` references that Vite emits with the placeholder (e.g. bundled
|
|
925
|
+
* fonts) are rewritten relative to the stylesheet, which the HTML substitution
|
|
926
|
+
* already loads from the right prefix.
|
|
141
927
|
*/
|
|
142
928
|
function connectDynamicBasePlugin(options = {}) {
|
|
143
929
|
return {
|
|
144
930
|
name: "ph-connect-dynamic-base",
|
|
145
931
|
enforce: "post",
|
|
146
932
|
renderChunk(code, chunk) {
|
|
147
|
-
if (!code.includes(
|
|
933
|
+
if (!code.includes(DYNAMIC_BASE_PLACEHOLDER)) return null;
|
|
148
934
|
const s = new MagicString(code);
|
|
149
935
|
for (const match of code.matchAll(PLACEHOLDER_LITERAL)) {
|
|
150
936
|
const rest = match[2];
|
|
@@ -161,7 +947,8 @@ function connectDynamicBasePlugin(options = {}) {
|
|
|
161
947
|
};
|
|
162
948
|
},
|
|
163
949
|
generateBundle(_options, bundle) {
|
|
164
|
-
for (const file of Object.values(bundle)) if (
|
|
950
|
+
for (const file of Object.values(bundle)) if (file.type === "asset" && file.fileName.endsWith(".css")) file.source = relativeCssUrls(String(file.source), file.fileName);
|
|
951
|
+
for (const file of Object.values(bundle)) if ((file.type === "chunk" ? file.code : file.fileName.endsWith(".css") && typeof file.source === "string" ? file.source : void 0)?.includes(DYNAMIC_BASE_PLACEHOLDER)) this.error(`dynamic-base: unrewritten placeholder ${DYNAMIC_BASE_PLACEHOLDER} remains in ${file.fileName}`);
|
|
165
952
|
}
|
|
166
953
|
};
|
|
167
954
|
}
|
|
@@ -212,8 +999,18 @@ const DEFAULT_VENDOR_INCLUDE = [
|
|
|
212
999
|
"zod",
|
|
213
1000
|
"@powerhousedao/design-system/connect",
|
|
214
1001
|
"@powerhousedao/reactor-browser",
|
|
215
|
-
"@powerhousedao/document-engineering"
|
|
1002
|
+
"@powerhousedao/document-engineering",
|
|
1003
|
+
"@powerhousedao/connect-core",
|
|
1004
|
+
"@tanstack/react-router"
|
|
216
1005
|
];
|
|
1006
|
+
/** Never vendored: the route tree is the project's, the config path the app's
|
|
1007
|
+
* base, and SSR server-only. */
|
|
1008
|
+
const VENDOR_SKIP_SUBPATHS = /* @__PURE__ */ new Set([
|
|
1009
|
+
"@powerhousedao/connect-core/route-tree",
|
|
1010
|
+
"@powerhousedao/connect-core/runtime-config",
|
|
1011
|
+
"@tanstack/react-router/ssr/client",
|
|
1012
|
+
"@tanstack/react-router/ssr/server"
|
|
1013
|
+
]);
|
|
217
1014
|
/**
|
|
218
1015
|
* React-family specifiers kept external to the vendor build. The vendor's chunks
|
|
219
1016
|
* emit bare imports for these; `devReactImportmapPlugin`'s import map resolves
|
|
@@ -237,35 +1034,44 @@ const VENDOR_DYNAMIC_BASE = `${DYNAMIC_BASE_PLACEHOLDER}${VENDOR_URL_PREFIX.repl
|
|
|
237
1034
|
*/
|
|
238
1035
|
async function prebuildConnectVendor(options) {
|
|
239
1036
|
const include = expandIncludeSubpaths(options.dirname, options.include ?? DEFAULT_VENDOR_INCLUDE);
|
|
1037
|
+
const own = options.ownDeps ? resolveOwnDeps(options.ownDeps.from, options.ownDeps.specs) : {};
|
|
1038
|
+
for (const spec of Object.keys(own)) if (!include.includes(spec)) include.push(spec);
|
|
240
1039
|
const external = options.external ?? VENDOR_EXTERNAL;
|
|
241
1040
|
const vendorDir = options.vendorDir ?? join(options.dirname, "node_modules/.ph-vendor");
|
|
242
1041
|
const importMapPath = join(vendorDir, "import-map.json");
|
|
243
|
-
const
|
|
1042
|
+
const stamps = /* @__PURE__ */ new Map();
|
|
1043
|
+
const versions = resolveDepVersions(options.dirname, [...include, ...external], stamps);
|
|
1044
|
+
const base = options.base ?? DYNAMIC_BASE_PLACEHOLDER;
|
|
1045
|
+
const nodeEnv = options.nodeEnv ?? "development";
|
|
1046
|
+
const versionDigest = resolveVersionDigest(versions, own, stamps, {
|
|
1047
|
+
base,
|
|
1048
|
+
nodeEnv
|
|
1049
|
+
});
|
|
244
1050
|
try {
|
|
245
1051
|
const hit = readCacheHit(importMapPath, include, external, versionDigest);
|
|
246
1052
|
if (hit) return {
|
|
247
1053
|
vendorDir,
|
|
248
|
-
|
|
1054
|
+
...hit
|
|
249
1055
|
};
|
|
250
1056
|
const lockDir = `${vendorDir}.lock`;
|
|
251
1057
|
const lock = acquireLock(lockDir);
|
|
252
1058
|
if (!lock) {
|
|
253
|
-
const
|
|
254
|
-
return
|
|
1059
|
+
const hit = await waitForCacheHit(importMapPath, include, external, versionDigest, lockDir);
|
|
1060
|
+
return hit ? {
|
|
255
1061
|
vendorDir,
|
|
256
|
-
|
|
1062
|
+
...hit
|
|
257
1063
|
} : null;
|
|
258
1064
|
}
|
|
259
1065
|
try {
|
|
260
1066
|
const raced = readCacheHit(importMapPath, include, external, versionDigest);
|
|
261
1067
|
if (raced) return {
|
|
262
1068
|
vendorDir,
|
|
263
|
-
|
|
1069
|
+
...raced
|
|
264
1070
|
};
|
|
265
|
-
const
|
|
266
|
-
return
|
|
1071
|
+
const result = await buildVendorAtomic(options.dirname, vendorDir, include, external, versionDigest, versions, base, nodeEnv, own);
|
|
1072
|
+
return result ? {
|
|
267
1073
|
vendorDir,
|
|
268
|
-
|
|
1074
|
+
...result
|
|
269
1075
|
} : null;
|
|
270
1076
|
} finally {
|
|
271
1077
|
releaseLock(lock);
|
|
@@ -279,27 +1085,105 @@ function readCacheHit(importMapPath, include, external, versionDigest) {
|
|
|
279
1085
|
if (!existsSync(importMapPath)) return null;
|
|
280
1086
|
try {
|
|
281
1087
|
const cached = JSON.parse(readFileSync(importMapPath, "utf8"));
|
|
282
|
-
if (sameSet(cached.include, include) && sameSet(cached.external, external) && cached.versionDigest === versionDigest) return
|
|
1088
|
+
if (sameSet(cached.include, include) && sameSet(cached.external, external) && cached.versionDigest === versionDigest && typeof cached.sharedDeps === "string") return {
|
|
1089
|
+
imports: cached.imports,
|
|
1090
|
+
versions: cached.versions ?? {},
|
|
1091
|
+
sharedDeps: cached.sharedDeps
|
|
1092
|
+
};
|
|
283
1093
|
} catch {}
|
|
284
1094
|
return null;
|
|
285
1095
|
}
|
|
286
|
-
|
|
287
|
-
|
|
1096
|
+
const NON_RUNTIME_FILE = /\.(map|d\.[cm]?ts|tsbuildinfo)$/;
|
|
1097
|
+
function linkedBuildStamp(pkgRoot) {
|
|
1098
|
+
if (pkgRoot.split(/[\\/]/).includes("node_modules")) return "";
|
|
1099
|
+
let newest = 0;
|
|
1100
|
+
try {
|
|
1101
|
+
const entries = readdirSync(join(pkgRoot, "dist"), {
|
|
1102
|
+
recursive: true,
|
|
1103
|
+
withFileTypes: true
|
|
1104
|
+
});
|
|
1105
|
+
for (const entry of entries) {
|
|
1106
|
+
if (!entry.isFile() || NON_RUNTIME_FILE.test(entry.name)) continue;
|
|
1107
|
+
const { mtimeMs } = statSync(join(entry.parentPath, entry.name));
|
|
1108
|
+
if (mtimeMs > newest) newest = mtimeMs;
|
|
1109
|
+
}
|
|
1110
|
+
} catch {
|
|
1111
|
+
return "";
|
|
1112
|
+
}
|
|
1113
|
+
return newest ? `+dist.${Math.trunc(newest)}` : "";
|
|
1114
|
+
}
|
|
1115
|
+
function cachedStamp(stamps, pkgRoot) {
|
|
1116
|
+
let stamp = stamps.get(pkgRoot);
|
|
1117
|
+
if (stamp === void 0) {
|
|
1118
|
+
stamp = linkedBuildStamp(pkgRoot);
|
|
1119
|
+
stamps.set(pkgRoot, stamp);
|
|
1120
|
+
}
|
|
1121
|
+
return stamp;
|
|
1122
|
+
}
|
|
1123
|
+
/**
|
|
1124
|
+
* Resolve the installed version of each spec's owning package, deduped by
|
|
1125
|
+
* package name. Resolution order per spec:
|
|
1126
|
+
* 1. the project itself, when it IS the owning package (a self-vendoring
|
|
1127
|
+
* app has no node_modules self-link);
|
|
1128
|
+
* 2. the project's own node_modules link (works for pnpm-strict and
|
|
1129
|
+
* hoisted layouts alike, and — unlike `require.resolve` — for
|
|
1130
|
+
* ESM-only packages whose exports map has no CJS condition);
|
|
1131
|
+
* 3. Node's own module resolution (covers transitive installs), walking
|
|
1132
|
+
* the entry up to the owning package's package.json.
|
|
1133
|
+
* Unresolvable specs contribute a "missing" sentinel, unknown versions
|
|
1134
|
+
* "unknown".
|
|
1135
|
+
*/
|
|
1136
|
+
function resolveDepVersions(dirname$3, specs, stamps = /* @__PURE__ */ new Map()) {
|
|
1137
|
+
const req = createRequire(join(dirname$3, "noop.js"));
|
|
1138
|
+
const seen = {};
|
|
1139
|
+
let selfMeta = null;
|
|
288
1140
|
for (const spec of specs) {
|
|
289
1141
|
const { pkg } = parsePkg(spec);
|
|
290
|
-
if (seen
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
1142
|
+
if (pkg in seen) continue;
|
|
1143
|
+
if (selfMeta === null) try {
|
|
1144
|
+
selfMeta = JSON.parse(readFileSync(join(dirname$3, "package.json"), "utf8"));
|
|
1145
|
+
} catch {
|
|
1146
|
+
selfMeta = {};
|
|
1147
|
+
}
|
|
1148
|
+
let version;
|
|
1149
|
+
if (typeof selfMeta.name === "string" && selfMeta.name === pkg && typeof selfMeta.version === "string") version = selfMeta.version;
|
|
1150
|
+
else {
|
|
1151
|
+
version = "missing";
|
|
1152
|
+
try {
|
|
1153
|
+
const pkgRoot = realpathSync(join(dirname$3, "node_modules", pkg));
|
|
1154
|
+
const meta = JSON.parse(readFileSync(join(pkgRoot, "package.json"), "utf8"));
|
|
1155
|
+
version = String(meta.version ?? "unknown") + cachedStamp(stamps, pkgRoot);
|
|
1156
|
+
} catch {
|
|
1157
|
+
try {
|
|
1158
|
+
const entry = req.resolve(spec);
|
|
1159
|
+
let dir = dirname(entry);
|
|
1160
|
+
for (let depth = 0; depth < 8; depth++) {
|
|
1161
|
+
if (existsSync(join(dir, "package.json"))) {
|
|
1162
|
+
const meta = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
|
|
1163
|
+
version = String(meta.version ?? "unknown");
|
|
1164
|
+
break;
|
|
1165
|
+
}
|
|
1166
|
+
const parent = dirname(dir);
|
|
1167
|
+
if (parent === dir) break;
|
|
1168
|
+
dir = parent;
|
|
1169
|
+
}
|
|
1170
|
+
} catch {}
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
seen[pkg] = version;
|
|
298
1174
|
}
|
|
1175
|
+
return seen;
|
|
1176
|
+
}
|
|
1177
|
+
function resolveVersionDigest(versions, own, stamps, build) {
|
|
299
1178
|
const h = createHash("sha256");
|
|
1179
|
+
h.update(`base:${build.base}\nnodeEnv:${build.nodeEnv}\n`);
|
|
300
1180
|
const workerHash = createHash("sha256").update(VENDOR_BUILD_WORKER).digest("hex");
|
|
301
1181
|
h.update(`worker:${workerHash}\n`);
|
|
302
|
-
for (const pkg of
|
|
1182
|
+
for (const pkg of Object.keys(versions).sort()) h.update(`${pkg}@${versions[pkg]}\n`);
|
|
1183
|
+
for (const spec of Object.keys(own).sort()) {
|
|
1184
|
+
const stamp = cachedStamp(stamps, ownPackageRoot(own[spec]));
|
|
1185
|
+
h.update(`own:${spec}=${own[spec]}${stamp}\n`);
|
|
1186
|
+
}
|
|
303
1187
|
return h.digest("hex").slice(0, 16);
|
|
304
1188
|
}
|
|
305
1189
|
function sameSet(a, b) {
|
|
@@ -307,7 +1191,7 @@ function sameSet(a, b) {
|
|
|
307
1191
|
const s = new Set(a);
|
|
308
1192
|
return b.every((x) => s.has(x));
|
|
309
1193
|
}
|
|
310
|
-
const LOCK_STALE_MS =
|
|
1194
|
+
const LOCK_STALE_MS = 3e5;
|
|
311
1195
|
const LOCK_HEARTBEAT_MS = 6e4;
|
|
312
1196
|
const ownerFile = (lockDir) => join(lockDir, "owner");
|
|
313
1197
|
function lockIsStale(lockDir) {
|
|
@@ -382,7 +1266,63 @@ function importTarget$1(value) {
|
|
|
382
1266
|
const t = importTarget$1(o[c]);
|
|
383
1267
|
if (t) return t;
|
|
384
1268
|
}
|
|
385
|
-
return null;
|
|
1269
|
+
return null;
|
|
1270
|
+
}
|
|
1271
|
+
/** The package root at or above `from` that Node would load `pkg` from, or null. */
|
|
1272
|
+
function findPackageRoot(from, pkg) {
|
|
1273
|
+
let dir = from;
|
|
1274
|
+
for (;;) {
|
|
1275
|
+
const candidate = join(dir, "node_modules", pkg);
|
|
1276
|
+
if (existsSync(join(candidate, "package.json"))) return realpathSync(candidate);
|
|
1277
|
+
const parent = dirname(dir);
|
|
1278
|
+
if (parent === dir) return null;
|
|
1279
|
+
dir = parent;
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
function ownRoots(own) {
|
|
1283
|
+
const roots = /* @__PURE__ */ new Set();
|
|
1284
|
+
for (const file of Object.values(own)) {
|
|
1285
|
+
const root = ownPackageRoot(file);
|
|
1286
|
+
try {
|
|
1287
|
+
const meta = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
|
1288
|
+
if (Object.keys(meta.dependencies ?? {}).length === 0) roots.add(root + sep);
|
|
1289
|
+
} catch {}
|
|
1290
|
+
}
|
|
1291
|
+
return [...roots];
|
|
1292
|
+
}
|
|
1293
|
+
function ownPackageRoot(file) {
|
|
1294
|
+
let dir = dirname(file);
|
|
1295
|
+
for (;;) {
|
|
1296
|
+
try {
|
|
1297
|
+
if (JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).name) return dir;
|
|
1298
|
+
} catch {}
|
|
1299
|
+
const parent = dirname(dir);
|
|
1300
|
+
if (parent === dir) return dir;
|
|
1301
|
+
dir = parent;
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
/** Each spec's browser/import entry file when resolved from `from`; unresolvable specs are left out. */
|
|
1305
|
+
function resolveOwnDeps(from, specs) {
|
|
1306
|
+
const out = {};
|
|
1307
|
+
for (const spec of specs) {
|
|
1308
|
+
const { pkg, sub } = parsePkg(spec);
|
|
1309
|
+
const root = findPackageRoot(from, pkg);
|
|
1310
|
+
if (!root) continue;
|
|
1311
|
+
try {
|
|
1312
|
+
const meta = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
|
1313
|
+
const key = sub ? `./${sub}` : ".";
|
|
1314
|
+
let target = null;
|
|
1315
|
+
if (meta.exports && typeof meta.exports === "object") {
|
|
1316
|
+
const exp = meta.exports;
|
|
1317
|
+
target = Object.keys(exp).some((k) => k.startsWith(".")) ? key in exp ? importTarget$1(exp[key]) : null : sub ? null : importTarget$1(exp);
|
|
1318
|
+
} else if (typeof meta.exports === "string") target = sub ? null : meta.exports;
|
|
1319
|
+
else if (!sub) target = meta.module ?? meta.main ?? null;
|
|
1320
|
+
if (!target || /\.(css|json|scss)$/.test(target)) continue;
|
|
1321
|
+
const file = join(root, target);
|
|
1322
|
+
if (existsSync(file)) out[spec] = realpathSync(file);
|
|
1323
|
+
} catch {}
|
|
1324
|
+
}
|
|
1325
|
+
return out;
|
|
386
1326
|
}
|
|
387
1327
|
function parsePkg(spec) {
|
|
388
1328
|
if (spec.startsWith("@")) {
|
|
@@ -406,11 +1346,16 @@ function parsePkg(spec) {
|
|
|
406
1346
|
* `@powerhousedao/design-system/connect/toast`, `zod/v4/core`). Those bare
|
|
407
1347
|
* imports need their own import-map entry, so expand each listed spec to its
|
|
408
1348
|
* package's concrete (non-wildcard, JS) subpath exports that share the spec's
|
|
409
|
-
* prefix. Unresolvable / CSS / JSON targets are skipped.
|
|
410
|
-
*
|
|
1349
|
+
* prefix. Unresolvable / CSS / JSON targets are skipped.
|
|
1350
|
+
*
|
|
1351
|
+
* A spec whose package isn't installed in `dirname` is dropped entirely
|
|
1352
|
+
* rather than kept for the worker: the worker cannot build an entry for a
|
|
1353
|
+
* missing package (its `await import` and the vite resolution both fail),
|
|
1354
|
+
* and a bare re-export entry would fail the whole vendor build. The
|
|
1355
|
+
* importer of a missing shared dep simply bundles its own copy.
|
|
411
1356
|
*/
|
|
412
1357
|
function expandIncludeSubpaths(dirname, include) {
|
|
413
|
-
const out = new Set(
|
|
1358
|
+
const out = /* @__PURE__ */ new Set();
|
|
414
1359
|
for (const spec of include) {
|
|
415
1360
|
const { pkg, sub } = parsePkg(spec);
|
|
416
1361
|
let exp;
|
|
@@ -421,6 +1366,7 @@ function expandIncludeSubpaths(dirname, include) {
|
|
|
421
1366
|
} catch {
|
|
422
1367
|
continue;
|
|
423
1368
|
}
|
|
1369
|
+
out.add(sub ? spec : pkg);
|
|
424
1370
|
if (!exp || typeof exp !== "object") continue;
|
|
425
1371
|
const expMap = exp;
|
|
426
1372
|
const prefixKey = sub ? `./${sub}` : ".";
|
|
@@ -431,40 +1377,86 @@ function expandIncludeSubpaths(dirname, include) {
|
|
|
431
1377
|
const target = importTarget$1(expMap[key]);
|
|
432
1378
|
if (!target || /\.(css|json|scss)$/.test(target)) continue;
|
|
433
1379
|
if (!existsSync(join(pkgRoot, target))) continue;
|
|
434
|
-
|
|
1380
|
+
const expanded = key === "." ? pkg : pkg + key.slice(1);
|
|
1381
|
+
if (!VENDOR_SKIP_SUBPATHS.has(expanded)) out.add(expanded);
|
|
435
1382
|
}
|
|
436
1383
|
}
|
|
437
1384
|
return [...out];
|
|
438
1385
|
}
|
|
439
1386
|
/**
|
|
1387
|
+
* The published specifiers whose entry file the vendor build never emitted.
|
|
1388
|
+
* URLs are base-less (`/__vendor__/x.js`) and resolve inside `vendorDir`.
|
|
1389
|
+
*/
|
|
1390
|
+
function missingVendorEntries(vendorDir, imports) {
|
|
1391
|
+
const prefix = VENDOR_URL_PREFIX;
|
|
1392
|
+
return Object.entries(imports).filter(([, url]) => {
|
|
1393
|
+
const rel = url.startsWith(prefix) ? url.slice(12) : url;
|
|
1394
|
+
return !existsSync(join(vendorDir, rel));
|
|
1395
|
+
}).map(([spec, url]) => ({
|
|
1396
|
+
spec,
|
|
1397
|
+
url
|
|
1398
|
+
}));
|
|
1399
|
+
}
|
|
1400
|
+
/**
|
|
1401
|
+
* Rebase the vendor's base-less entry URLs (`/__vendor__/x.js`) onto the
|
|
1402
|
+
* deploy base, so a consumer that resolves them against the page origin lands
|
|
1403
|
+
* under that base rather than the server root. A dynamic-base build keeps its
|
|
1404
|
+
* placeholder, which the runtime substitutes.
|
|
1405
|
+
*
|
|
1406
|
+
* `base` is the app base from `prebuildConnectVendor` callers; a base that
|
|
1407
|
+
* already carries the vendor segment has it dropped first so it is never
|
|
1408
|
+
* doubled.
|
|
1409
|
+
*/
|
|
1410
|
+
function withVendorBase(imports, base) {
|
|
1411
|
+
const segment = VENDOR_URL_PREFIX.replace(/^\/+/, "");
|
|
1412
|
+
const appBase = base.endsWith(segment) ? base.slice(0, base.length - segment.length) : base;
|
|
1413
|
+
return Object.fromEntries(Object.entries(imports).map(([spec, url]) => [spec, `${appBase}/${url}`.replace(/([^:])\/{2,}/g, "$1/").replace(/^\/{2,}/, "/")]));
|
|
1414
|
+
}
|
|
1415
|
+
/**
|
|
440
1416
|
* Build the vendor into a unique temp dir, then atomically swap it into place,
|
|
441
1417
|
* so a concurrent reader never sees a partial bundle or import-map.json. Runs
|
|
442
1418
|
* the build in a throwaway subprocess (its peak memory is reclaimed on exit);
|
|
443
|
-
* the parent augments the import map with the version digest
|
|
444
|
-
*
|
|
1419
|
+
* the parent augments the import map with the version digest + the version
|
|
1420
|
+
* table, writes the runtime shared-deps module, and does the swap.
|
|
1421
|
+
* Returns the published import map + versions, or null on failure.
|
|
445
1422
|
*/
|
|
446
|
-
async function buildVendorAtomic(dirname$
|
|
1423
|
+
async function buildVendorAtomic(dirname$4, vendorDir, include, external, versionDigest, versions, base, nodeEnv, own = {}) {
|
|
447
1424
|
const parent = dirname(vendorDir);
|
|
448
1425
|
mkdirSync(parent, { recursive: true });
|
|
449
1426
|
const tmpDir = mkdtempSync(join(parent, ".ph-vendor.tmp-"));
|
|
450
1427
|
try {
|
|
451
|
-
const { ok, stderr } = await runBuildWorker(dirname$
|
|
1428
|
+
const { ok, stderr } = await runBuildWorker(dirname$4, tmpDir, include, external, base, nodeEnv, own);
|
|
452
1429
|
const tmpMap = join(tmpDir, "import-map.json");
|
|
453
1430
|
if (!ok || !existsSync(tmpMap)) {
|
|
454
1431
|
const detail = stderr.trim();
|
|
455
1432
|
throw new Error(`vendor build failed${detail ? `:\n${detail}` : " (no output captured)"}`);
|
|
456
1433
|
}
|
|
457
1434
|
const meta = JSON.parse(readFileSync(tmpMap, "utf8"));
|
|
1435
|
+
const unbacked = missingVendorEntries(tmpDir, meta.imports);
|
|
1436
|
+
if (unbacked.length > 0) throw new Error(`vendor build published ${unbacked.length} import-map ${unbacked.length === 1 ? "entry" : "entries"} with no file behind ${unbacked.length === 1 ? "it" : "them"}:\n` + unbacked.map((e) => ` ${e.spec} -> ${e.url}`).join("\n"));
|
|
458
1437
|
meta.versionDigest = versionDigest;
|
|
1438
|
+
meta.versions = versions;
|
|
1439
|
+
meta.base = base;
|
|
1440
|
+
meta.nodeEnv = nodeEnv;
|
|
1441
|
+
const sharedDepsSource = `export const imports = ${JSON.stringify(withVendorBase(meta.imports, base))};\nexport const versions = ${JSON.stringify(versions)};\n`;
|
|
1442
|
+
const sharedDepsFile = `shared-deps-${createHash("sha256").update(sharedDepsSource).digest("hex").slice(0, 12)}.js`;
|
|
1443
|
+
writeFileSync(join(tmpDir, sharedDepsFile), sharedDepsSource);
|
|
1444
|
+
writeFileSync(join(tmpDir, "shared-deps.js"), sharedDepsSource);
|
|
1445
|
+
meta.sharedDeps = VENDOR_URL_PREFIX + sharedDepsFile;
|
|
459
1446
|
writeFileSync(tmpMap, JSON.stringify(meta, null, 2));
|
|
460
1447
|
const oldDir = `${vendorDir}.old-${process.pid}-${Date.now()}`;
|
|
461
1448
|
if (existsSync(vendorDir)) renameSync(vendorDir, oldDir);
|
|
462
1449
|
renameSync(tmpDir, vendorDir);
|
|
1450
|
+
chmodSync(vendorDir, 493);
|
|
463
1451
|
rmSync(oldDir, {
|
|
464
1452
|
recursive: true,
|
|
465
1453
|
force: true
|
|
466
1454
|
});
|
|
467
|
-
return
|
|
1455
|
+
return {
|
|
1456
|
+
imports: meta.imports,
|
|
1457
|
+
versions,
|
|
1458
|
+
sharedDeps: meta.sharedDeps
|
|
1459
|
+
};
|
|
468
1460
|
} catch (err) {
|
|
469
1461
|
rmSync(tmpDir, {
|
|
470
1462
|
recursive: true,
|
|
@@ -473,16 +1465,29 @@ async function buildVendorAtomic(dirname$2, vendorDir, include, external, versio
|
|
|
473
1465
|
throw err;
|
|
474
1466
|
}
|
|
475
1467
|
}
|
|
1468
|
+
function resolveSelfModulePath() {
|
|
1469
|
+
const selfPath = fileURLToPath(import.meta.url);
|
|
1470
|
+
if (!selfPath.endsWith(".ts")) return selfPath;
|
|
1471
|
+
let dir = dirname(selfPath);
|
|
1472
|
+
for (let depth = 0; depth < 4; depth++) {
|
|
1473
|
+
const candidate = join(dir, "dist", "index.mjs");
|
|
1474
|
+
if (existsSync(candidate)) return candidate;
|
|
1475
|
+
const parent = dirname(dir);
|
|
1476
|
+
if (parent === dir) break;
|
|
1477
|
+
dir = parent;
|
|
1478
|
+
}
|
|
1479
|
+
throw new Error("vendor build needs the built builder-tools bundle (dist/index.mjs); build the package first");
|
|
1480
|
+
}
|
|
476
1481
|
/**
|
|
477
1482
|
* Spawn a throwaway worker that generates one entry per specifier (CJS deps get
|
|
478
1483
|
* explicit named re-exports, ESM deps `export *`), `vite build`s them into the
|
|
479
1484
|
* given out dir, and writes the import map. Captures stdout/stderr so a failure
|
|
480
1485
|
* is debuggable; the normal path stays quiet.
|
|
481
1486
|
*/
|
|
482
|
-
function runBuildWorker(dirname, outDir, include, external) {
|
|
1487
|
+
function runBuildWorker(dirname, outDir, include, external, base, nodeEnv, own = {}) {
|
|
483
1488
|
const workerPath = join(outDir, "build-worker.mjs");
|
|
484
1489
|
writeFileSync(workerPath, VENDOR_BUILD_WORKER);
|
|
485
|
-
const selfModulePath =
|
|
1490
|
+
const selfModulePath = resolveSelfModulePath();
|
|
486
1491
|
return new Promise((resolve) => {
|
|
487
1492
|
const child = spawn(process.execPath, [
|
|
488
1493
|
workerPath,
|
|
@@ -492,7 +1497,13 @@ function runBuildWorker(dirname, outDir, include, external) {
|
|
|
492
1497
|
VENDOR_URL_PREFIX,
|
|
493
1498
|
JSON.stringify(external),
|
|
494
1499
|
VENDOR_DYNAMIC_BASE,
|
|
495
|
-
selfModulePath
|
|
1500
|
+
selfModulePath,
|
|
1501
|
+
base,
|
|
1502
|
+
nodeEnv,
|
|
1503
|
+
JSON.stringify({
|
|
1504
|
+
files: own,
|
|
1505
|
+
roots: ownRoots(own)
|
|
1506
|
+
})
|
|
496
1507
|
], {
|
|
497
1508
|
cwd: dirname,
|
|
498
1509
|
stdio: [
|
|
@@ -522,14 +1533,27 @@ function runBuildWorker(dirname, outDir, include, external) {
|
|
|
522
1533
|
* The vendor build worker, written to disk and run as a subprocess. Loads
|
|
523
1534
|
* `vite` from the project and `connectDynamicBasePlugin` from builder-tools' own
|
|
524
1535
|
* built bundle (selfModulePath). argv: dirname, vendorDir, includeJSON,
|
|
525
|
-
* urlPrefix, externalJSON, dynamicBase, selfModulePath
|
|
1536
|
+
* urlPrefix, externalJSON, dynamicBase, selfModulePath, base (app base),
|
|
1537
|
+
* nodeEnv.
|
|
526
1538
|
*/
|
|
527
1539
|
const VENDOR_BUILD_WORKER = `
|
|
528
1540
|
import { createRequire } from 'node:module';
|
|
529
1541
|
import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
|
|
530
1542
|
import { join, isAbsolute } from 'node:path';
|
|
531
1543
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
532
|
-
const [dirname, vendorDir, includeJSON, urlPrefix, externalJSON, dynamicBase, selfModulePath] = process.argv.slice(2);
|
|
1544
|
+
const [dirname, vendorDir, includeJSON, urlPrefix, externalJSON, dynamicBase, selfModulePath, baseArg, nodeEnvArg, ownJSON] = process.argv.slice(2);
|
|
1545
|
+
// ownDeps: spec -> absolute entry file, plus each one's package root.
|
|
1546
|
+
const { files: own = {}, roots: ownRootList = [] } = JSON.parse(ownJSON || '{}');
|
|
1547
|
+
// One chunk per own-dep package: split between an entry and a shared chunk, a
|
|
1548
|
+
// barrel can re-export from the entry and run before the classes it extends.
|
|
1549
|
+
const ownGroups = ownRootList.map((root, i) => ({ name: 'own-' + i, test: (id) => id.startsWith(root) }));
|
|
1550
|
+
// Trailing argv are optional (older callers): base defaults to the dynamic
|
|
1551
|
+
// placeholder behavior, nodeEnv to development. baseArg is the APP base —
|
|
1552
|
+
// the same string the app build uses; the build base appends the vendor
|
|
1553
|
+
// segment so emitted asset URLs land under <app-base>__vendor__/.
|
|
1554
|
+
const segment = urlPrefix.replace(/^\\/+/, '');
|
|
1555
|
+
const base = baseArg ? baseArg + segment : dynamicBase;
|
|
1556
|
+
const nodeEnv = nodeEnvArg ?? 'development';
|
|
533
1557
|
const include = JSON.parse(includeJSON);
|
|
534
1558
|
const external = JSON.parse(externalJSON ?? '[]');
|
|
535
1559
|
const externalSet = new Set(external);
|
|
@@ -547,23 +1571,42 @@ const RESERVED = new Set('enum void null function in instanceof typeof new delet
|
|
|
547
1571
|
const input = {};
|
|
548
1572
|
for (const spec of include) {
|
|
549
1573
|
const name = entryName(spec);
|
|
1574
|
+
const from = own[spec] ?? spec;
|
|
550
1575
|
let src;
|
|
551
1576
|
try {
|
|
552
1577
|
// Import the bare spec (not reqProj.resolve(spec)) so Node picks the same
|
|
553
1578
|
// import/browser-condition module the build resolves — resolving first can
|
|
554
1579
|
// pick a CJS sibling whose default-export shape differs from the ESM build.
|
|
555
|
-
const ns = await import(spec);
|
|
1580
|
+
const ns = await import(own[spec] ? pathToFileURL(own[spec]).href : spec);
|
|
556
1581
|
// Only fall back to re-exporting from default when the module exposes NO
|
|
557
1582
|
// top-level named exports (a true CJS-interop module). If it does (e.g. zod
|
|
558
1583
|
// exposes \`z\`), \`export *\` captures them; destructuring default would miss
|
|
559
1584
|
// top-level names that aren't keys of the default object.
|
|
560
1585
|
const named = Object.keys(ns).filter((k) => k !== 'default');
|
|
561
1586
|
const cjs = named.length === 0 && ns.default && typeof ns.default === 'object';
|
|
562
|
-
|
|
1587
|
+
// A strict entry keeps every export, and zod's \`locales\` (also reachable via \`z\`) pins
|
|
1588
|
+
// ~50 locales; publish them without it. zod/locales stays its own entry.
|
|
1589
|
+
const zodNs = (spec === 'zod' || spec.startsWith('zod/')) && !spec.includes('locales') && named.includes('locales');
|
|
1590
|
+
if (zodNs) {
|
|
1591
|
+
const keep = named.filter((k) => k !== 'locales' && k !== 'z' && /^[A-Za-z_$][\\w$]*$/.test(k));
|
|
1592
|
+
// \`core\` is zod/v4/core's namespace, which exports locales too: rebuild it without them.
|
|
1593
|
+
const coreKeys = keep.includes('core') ? Object.keys(await import('zod/v4/core')).filter((k) => k !== 'locales' && k !== 'default') : [];
|
|
1594
|
+
const reexport = keep.filter((k) => !(k === 'core' && coreKeys.length));
|
|
1595
|
+
src = 'export { ' + reexport.join(', ') + ' } from ' + JSON.stringify(from) + ';\\n'
|
|
1596
|
+
+ 'import { ' + reexport.map((k) => k + ' as __z_' + k).join(', ') + ' } from ' + JSON.stringify(from) + ';\\n';
|
|
1597
|
+
if (coreKeys.length) {
|
|
1598
|
+
src += 'import { ' + coreKeys.map((k) => k + ' as __c_' + k).join(', ') + ' } from "zod/v4/core";\\n'
|
|
1599
|
+
+ 'const __z_core = Object.freeze({ ' + coreKeys.map((k) => JSON.stringify(k) + ': __c_' + k).join(', ') + ' });\\n'
|
|
1600
|
+
+ 'export { __z_core as core };\\n';
|
|
1601
|
+
}
|
|
1602
|
+
src += 'const z = Object.freeze({ ' + keep.map((k) => JSON.stringify(k) + ': __z_' + k).join(', ') + ' });\\n'
|
|
1603
|
+
+ (named.includes('z') ? 'export { z };\\n' : '')
|
|
1604
|
+
+ (('default' in ns) && ns.default === ns.z ? 'export { z as default };\\n' : '');
|
|
1605
|
+
} else if (cjs) {
|
|
563
1606
|
const names = Object.keys(ns.default).filter((k) => k !== 'default' && k !== '__esModule' && /^[A-Za-z_$][\\w$]*$/.test(k));
|
|
564
1607
|
const plain = names.filter((n) => !RESERVED.has(n));
|
|
565
1608
|
const reserved = names.filter((n) => RESERVED.has(n));
|
|
566
|
-
src = 'import d from ' + JSON.stringify(
|
|
1609
|
+
src = 'import d from ' + JSON.stringify(from) + ';\\nexport default d;\\n'
|
|
567
1610
|
+ (plain.length ? 'export const { ' + plain.join(', ') + ' } = d;\\n' : '');
|
|
568
1611
|
// reserved words are invalid as const-binding names but valid as export
|
|
569
1612
|
// aliases (export { x as enum }).
|
|
@@ -571,11 +1614,11 @@ for (const spec of include) {
|
|
|
571
1614
|
src += 'const __r' + i + ' = d[' + JSON.stringify(n) + '];\\nexport { __r' + i + ' as ' + n + ' };\\n';
|
|
572
1615
|
});
|
|
573
1616
|
} else {
|
|
574
|
-
src = 'export * from ' + JSON.stringify(
|
|
575
|
-
+ (('default' in ns) ? 'export { default } from ' + JSON.stringify(
|
|
1617
|
+
src = 'export * from ' + JSON.stringify(from) + ';\\n'
|
|
1618
|
+
+ (('default' in ns) ? 'export { default } from ' + JSON.stringify(from) + ';\\n' : '');
|
|
576
1619
|
}
|
|
577
1620
|
} catch {
|
|
578
|
-
src = 'export * from ' + JSON.stringify(
|
|
1621
|
+
src = 'export * from ' + JSON.stringify(from) + ';\\n';
|
|
579
1622
|
}
|
|
580
1623
|
const file = join(srcDir, name + '.js');
|
|
581
1624
|
writeFileSync(file, src);
|
|
@@ -600,16 +1643,19 @@ const phVendorResolve = {
|
|
|
600
1643
|
return resolved;
|
|
601
1644
|
},
|
|
602
1645
|
};
|
|
603
|
-
await build({
|
|
1646
|
+
const result = await build({
|
|
604
1647
|
root: dirname, configFile: false, logLevel: 'error',
|
|
605
|
-
//
|
|
606
|
-
// emitted chunk/asset URLs to resolve
|
|
607
|
-
base
|
|
1648
|
+
// Caller-provided build base (or the dynamic placeholder default):
|
|
1649
|
+
// connectDynamicBasePlugin rewrites emitted chunk/asset URLs to resolve
|
|
1650
|
+
// against the deploy base at serve time.
|
|
1651
|
+
base,
|
|
608
1652
|
define: {
|
|
609
|
-
'process.env.NODE_ENV':
|
|
1653
|
+
'process.env.NODE_ENV': JSON.stringify(nodeEnv),
|
|
610
1654
|
// BASE_URL resolves to the deploy base (not the vendor prefix) so vendored
|
|
611
1655
|
// Connect's router basename + BASE_URL-relative fetches use the right path.
|
|
612
|
-
|
|
1656
|
+
// The app base when provided (concrete or placeholder), the placeholder
|
|
1657
|
+
// otherwise (dev flow — rewritten at serve time by the dynamic-base plugin).
|
|
1658
|
+
'import.meta.env.BASE_URL': JSON.stringify(baseArg ?? DYNAMIC_BASE_PLACEHOLDER),
|
|
613
1659
|
},
|
|
614
1660
|
// phVendorResolve (pre) resolves bares from the worker; esmExternalRequirePlugin owns
|
|
615
1661
|
// react/virtual externalization; connectDynamicBasePlugin (post) rewrites the placeholder base.
|
|
@@ -618,199 +1664,758 @@ await build({
|
|
|
618
1664
|
// segment so the worker recovers the deploy base, not the vendor prefix.
|
|
619
1665
|
worker: { format: 'es', plugins: () => [connectDynamicBasePlugin({ forWorker: true, workerStripPrefix: urlPrefix.replace(/^\\/+/, '') })] },
|
|
620
1666
|
build: {
|
|
621
|
-
|
|
1667
|
+
// Production ships this to every visitor, so minify it like the app's own
|
|
1668
|
+
// chunks; dev keeps readable output and the faster build.
|
|
1669
|
+
outDir: vendorDir, emptyOutDir: false, minify: nodeEnv === 'production', target: 'esnext', cssCodeSplit: true,
|
|
622
1670
|
rollupOptions: {
|
|
623
1671
|
input, preserveEntrySignatures: 'strict',
|
|
624
|
-
|
|
1672
|
+
// Content-hashed entry names: each build's import map points at new URLs.
|
|
1673
|
+
output: { format: 'es', entryFileNames: '[name]-[hash].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]', ...(ownGroups.length ? { codeSplitting: { groups: ownGroups } } : {}) },
|
|
625
1674
|
},
|
|
626
1675
|
},
|
|
627
1676
|
});
|
|
628
1677
|
rmSync(srcDir, { recursive: true, force: true });
|
|
1678
|
+
const emitted = {};
|
|
1679
|
+
for (const out of Array.isArray(result) ? result : [result]) {
|
|
1680
|
+
for (const chunk of out?.output ?? []) {
|
|
1681
|
+
if (chunk.type === 'chunk' && chunk.isEntry) emitted[chunk.name] = chunk.fileName;
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
629
1684
|
const imports = {};
|
|
630
|
-
|
|
1685
|
+
// An entry the build never emitted keeps its unhashed name; the caller reports it as missing.
|
|
1686
|
+
for (const spec of include) imports[spec] = urlPrefix + (emitted[entryName(spec)] ?? entryName(spec) + '.js');
|
|
631
1687
|
writeFileSync(join(vendorDir, 'import-map.json'), JSON.stringify({ include, external, imports }, null, 2));
|
|
632
1688
|
`;
|
|
633
1689
|
//#endregion
|
|
634
|
-
//#region connect-utils/
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
1690
|
+
//#region connect-utils/reactor-worker-build.ts
|
|
1691
|
+
/**
|
|
1692
|
+
* Prebuild Connect's reactor SharedWorker into a browser-loadable bundle.
|
|
1693
|
+
*
|
|
1694
|
+
* The published `@powerhousedao/connect` dist ships `reactor.worker.js` as a
|
|
1695
|
+
* library artifact: its dependencies are externalized onto bare specifiers
|
|
1696
|
+
* (`@powerhousedao/reactor`, `kysely`, ...). The page resolves those through
|
|
1697
|
+
* its `<script type="importmap">`, but import maps are a document feature —
|
|
1698
|
+
* a worker never inherits one and no Worker/SharedWorker constructor option
|
|
1699
|
+
* can supply one. A bare specifier inside a worker is unresolvable by the
|
|
1700
|
+
* platform, so the shipped file can never run as a worker script.
|
|
1701
|
+
*
|
|
1702
|
+
* This module builds the worker's module graph into a self-contained bundle
|
|
1703
|
+
* (one `vite build` in a throwaway subprocess, same pattern as the vendor
|
|
1704
|
+
* prebuild). Two modes:
|
|
1705
|
+
*
|
|
1706
|
+
* - With `vendorImports` (production builds that also ship the `__vendor__/`
|
|
1707
|
+
* bundle): specifiers present in the vendor import map are externalized and
|
|
1708
|
+
* rewritten to `../__vendor__/<entry>.js`. The worker bundle is served as a
|
|
1709
|
+
* sibling of `__vendor__/`, so those relative imports hit the exact URLs
|
|
1710
|
+
* the page's import map uses — one fetch and one HTTP-cache entry per
|
|
1711
|
+
* shared dep for the page and the worker together.
|
|
1712
|
+
* - Without (dev servers, `PH_CONNECT_VENDOR=0` builds): everything is
|
|
1713
|
+
* bundled; the worker is self-contained.
|
|
1714
|
+
*
|
|
1715
|
+
* The build uses Vite's relative base (`"./"`), so emitted chunk and asset
|
|
1716
|
+
* URLs resolve against the worker script's own URL. That sidesteps the
|
|
1717
|
+
* dynamic-base machinery entirely: the bundle works under any deploy base,
|
|
1718
|
+
* concrete or proxy-substituted, as long as it is served under
|
|
1719
|
+
* `<app-base>/__reactor_worker__/`.
|
|
1720
|
+
*/
|
|
1721
|
+
/** URL prefix the worker bundle is served under, next to `__vendor__/`. */
|
|
1722
|
+
const REACTOR_WORKER_URL_PREFIX = "/__reactor_worker__/";
|
|
1723
|
+
/** Entry filename of the bundle; the tab constructs its SharedWorker from it. */
|
|
1724
|
+
const REACTOR_WORKER_ENTRY = "reactor.worker.js";
|
|
1725
|
+
/** Metadata file the cache check reads; lives inside the bundle dir. */
|
|
1726
|
+
const META_FILE = "worker-meta.json";
|
|
1727
|
+
/** Content-Type for the extensions the worker build emits; JS is the default. */
|
|
1728
|
+
const REACTOR_WORKER_MIME = {
|
|
1729
|
+
".map": "application/json",
|
|
1730
|
+
".json": "application/json",
|
|
1731
|
+
".wasm": "application/wasm",
|
|
1732
|
+
".data": "application/octet-stream"
|
|
1733
|
+
};
|
|
1734
|
+
/**
|
|
1735
|
+
* The installed Connect dist's worker entry, or null when the installed
|
|
1736
|
+
* version predates the worker (the feature is then unavailable, not broken).
|
|
1737
|
+
*/
|
|
1738
|
+
function resolveReactorWorkerSource(dirname) {
|
|
1739
|
+
try {
|
|
1740
|
+
const candidate = join(realpathSync(join(dirname, "node_modules", "@powerhousedao/connect")), "dist", REACTOR_WORKER_ENTRY);
|
|
1741
|
+
return existsSync(candidate) ? candidate : null;
|
|
1742
|
+
} catch {
|
|
1743
|
+
return null;
|
|
1744
|
+
}
|
|
639
1745
|
}
|
|
640
|
-
|
|
641
|
-
|
|
1746
|
+
/** `/__vendor__/<entry>.js` -> `../__vendor__/<entry>.js` (sibling dirs). */
|
|
1747
|
+
function vendorRelativePath(vendorUrl) {
|
|
1748
|
+
return `../__vendor__/${vendorUrl.slice(vendorUrl.lastIndexOf("/") + 1)}`;
|
|
642
1749
|
}
|
|
643
|
-
|
|
1750
|
+
const SPECIFIER_PATTERNS = [
|
|
1751
|
+
/(?<![.\w$])import\s*\(\s*["']([^"']+)["']/g,
|
|
1752
|
+
/(?<![.\w$])import\s*[^"'()]*?from\s*["']([^"']+)["']/g,
|
|
1753
|
+
/(?<![.\w$])export\s*[^"'()]*?from\s*["']([^"']+)["']/g,
|
|
1754
|
+
/(?<![.\w$])import\s*["']([^"']+)["']/g
|
|
1755
|
+
];
|
|
1756
|
+
/**
|
|
1757
|
+
* Module specifiers a worker cannot resolve: anything that is not relative,
|
|
1758
|
+
* root-relative, or an http(s)/data/blob URL. Used as a post-build guard so a
|
|
1759
|
+
* leftover bare (or `node:`) import fails the build with a name instead of
|
|
1760
|
+
* shipping a worker that dies on its first import statement.
|
|
1761
|
+
*
|
|
1762
|
+
* Expects minified (comment-free) output: a raw-text scan cannot tell a real
|
|
1763
|
+
* import from a JSDoc code sample, and unminified kysely/viem are full of the
|
|
1764
|
+
* latter. The build below always minifies for exactly this reason.
|
|
1765
|
+
*/
|
|
1766
|
+
function findDisallowedSpecifiers(code) {
|
|
1767
|
+
const found = /* @__PURE__ */ new Set();
|
|
1768
|
+
for (const pattern of SPECIFIER_PATTERNS) for (const match of code.matchAll(pattern)) {
|
|
1769
|
+
const spec = match[1];
|
|
1770
|
+
if (!spec.startsWith("./") && !spec.startsWith("../") && !spec.startsWith("/") && !/^(https?:|data:|blob:)/.test(spec)) found.add(spec);
|
|
1771
|
+
}
|
|
1772
|
+
return [...found].sort();
|
|
1773
|
+
}
|
|
1774
|
+
/**
|
|
1775
|
+
* Fallback list of packages whose BUILT dist shapes the worker bundle's output,
|
|
1776
|
+
* used only when the installed Connect's package.json cannot be read (see
|
|
1777
|
+
* {@link upstreamWorkerPackages}).
|
|
1778
|
+
*/
|
|
1779
|
+
const FALLBACK_UPSTREAM_WORKER_PACKAGES = ["@powerhousedao/reactor", "@powerhousedao/reactor-browser"];
|
|
1780
|
+
/** Dependency scopes whose installed dist can change the bundle's output. */
|
|
1781
|
+
const UPSTREAM_SCOPES = ["@powerhousedao/", "@renown/"];
|
|
1782
|
+
/**
|
|
1783
|
+
* Packages whose BUILT dist shapes the worker bundle's output even when
|
|
1784
|
+
* connect's own dist/reactor.worker.js entry file did not change.
|
|
1785
|
+
*
|
|
1786
|
+
* That entry is a library artifact whose bare imports this build resolves
|
|
1787
|
+
* through node_modules at BUILD time, so a rebuilt dist anywhere in its
|
|
1788
|
+
* closure changes the bundle output without touching the entry file's own
|
|
1789
|
+
* size/mtime. The list is DERIVED from the installed Connect's own
|
|
1790
|
+
* dependencies rather than hardcoded: the bundle pulls `@renown/sdk`,
|
|
1791
|
+
* `@powerhousedao/powerhouse-vetra-packages` and `@powerhousedao/shared` out
|
|
1792
|
+
* of node_modules too, and a hardcoded pair left every one of those able to be
|
|
1793
|
+
* rebuilt behind a cache hit. Connect's dependency list is the cheap stand-in
|
|
1794
|
+
* for the resolved bundle graph: every workspace package the worker can reach
|
|
1795
|
+
* is reachable through it, and a package not in the bundle only costs a readdir.
|
|
1796
|
+
*/
|
|
1797
|
+
function upstreamWorkerPackages(dirname) {
|
|
1798
|
+
const connectDir = resolveWorkspacePackageDir(dirname, "@powerhousedao/connect");
|
|
1799
|
+
if (!connectDir) return [...FALLBACK_UPSTREAM_WORKER_PACKAGES];
|
|
1800
|
+
let meta;
|
|
644
1801
|
try {
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
return
|
|
648
|
-
}
|
|
649
|
-
|
|
1802
|
+
meta = JSON.parse(readFileSync(join(connectDir, "package.json"), "utf8"));
|
|
1803
|
+
} catch {
|
|
1804
|
+
return [...FALLBACK_UPSTREAM_WORKER_PACKAGES];
|
|
1805
|
+
}
|
|
1806
|
+
const names = Object.keys(meta.dependencies ?? {}).filter((name) => UPSTREAM_SCOPES.some((scope) => name.startsWith(scope)));
|
|
1807
|
+
for (const name of FALLBACK_UPSTREAM_WORKER_PACKAGES) if (!names.includes(name)) names.push(name);
|
|
1808
|
+
return names.sort();
|
|
1809
|
+
}
|
|
1810
|
+
/**
|
|
1811
|
+
* This module's own installed version, read by walking up from its file to
|
|
1812
|
+
* the nearest `package.json` named "@powerhousedao/builder-tools" (same
|
|
1813
|
+
* technique as `build-hash.ts`'s `readConnectVersion`: builder-tools'
|
|
1814
|
+
* `exports` map has no `./package.json` subpath, so node resolution can't
|
|
1815
|
+
* get there). Works whether this runs from source (tests, this monorepo) or
|
|
1816
|
+
* the built dist.
|
|
1817
|
+
*/
|
|
1818
|
+
function resolveOwnPackageVersion() {
|
|
1819
|
+
try {
|
|
1820
|
+
let dir = dirname(fileURLToPath(import.meta.url));
|
|
1821
|
+
for (;;) {
|
|
1822
|
+
try {
|
|
1823
|
+
const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
|
|
1824
|
+
if (pkg.name === "@powerhousedao/builder-tools") return pkg.version ?? "unknown";
|
|
1825
|
+
} catch {}
|
|
1826
|
+
const parent = dirname(dir);
|
|
1827
|
+
if (parent === dir) break;
|
|
1828
|
+
dir = parent;
|
|
1829
|
+
}
|
|
1830
|
+
} catch {}
|
|
1831
|
+
return "unknown";
|
|
1832
|
+
}
|
|
1833
|
+
/**
|
|
1834
|
+
* This package's own version, computed once. Folded into the worker bundle
|
|
1835
|
+
* cache key so a builder-tools release — which can change how the bundle is
|
|
1836
|
+
* built (anything in this module beyond {@link WORKER_BUILD_WORKER} itself,
|
|
1837
|
+
* e.g. `workerSafeVendorImports`, the resolve plugin) — invalidates bundles
|
|
1838
|
+
* a prior builder-tools version cached.
|
|
1839
|
+
*/
|
|
1840
|
+
const BUILDER_TOOLS_VERSION = resolveOwnPackageVersion();
|
|
1841
|
+
/**
|
|
1842
|
+
* A workspace package's real directory, resolved the way Node's resolver
|
|
1843
|
+
* would (through `node_modules`), or null when it is not installed (e.g. a
|
|
1844
|
+
* non-monorepo consumer project — graceful, not an error). pnpm's
|
|
1845
|
+
* node_modules symlinks resolve to the real package directory, so this
|
|
1846
|
+
* reflects the monorepo's actual dist state, not a stale symlink target.
|
|
1847
|
+
*/
|
|
1848
|
+
function resolveWorkspacePackageDir(dirname, pkgName) {
|
|
1849
|
+
try {
|
|
1850
|
+
return realpathSync(join(dirname, "node_modules", ...pkgName.split("/")));
|
|
1851
|
+
} catch {
|
|
650
1852
|
return null;
|
|
651
1853
|
}
|
|
652
1854
|
}
|
|
653
1855
|
/**
|
|
654
|
-
*
|
|
1856
|
+
* Cheap content fingerprint of a directory's immediate files: no file bytes
|
|
1857
|
+
* are read, just each entry's name/size/mtime, so it stays fast even for a
|
|
1858
|
+
* large dist. Sensitive to a rebuild in the common cases: Vite's
|
|
1859
|
+
* content-hashed chunk filenames change the name itself; a stable-named file
|
|
1860
|
+
* (an entry point) changes size or mtime. Bounded (`maxFiles`) so a
|
|
1861
|
+
* pathological directory cannot make this slow — deliberately not a
|
|
1862
|
+
* full-tree hash.
|
|
1863
|
+
*
|
|
1864
|
+
* The names are sorted BEFORE the bound is applied, so the subset the bound
|
|
1865
|
+
* keeps is the same subset on every run: readdir order is unspecified, and
|
|
1866
|
+
* truncating it first made the fingerprint of a directory past the bound a
|
|
1867
|
+
* function of whatever order the filesystem happened to report.
|
|
655
1868
|
*/
|
|
656
|
-
function
|
|
657
|
-
|
|
658
|
-
|
|
1869
|
+
function distDirFingerprint(dir, maxFiles = 1e3) {
|
|
1870
|
+
try {
|
|
1871
|
+
return readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile()).map((e) => e.name).sort().slice(0, maxFiles).map((name) => {
|
|
1872
|
+
const stat = statSync(join(dir, name));
|
|
1873
|
+
return `${name}:${stat.size}:${Math.round(stat.mtimeMs)}`;
|
|
1874
|
+
}).join("|");
|
|
1875
|
+
} catch {
|
|
1876
|
+
return "unreadable";
|
|
1877
|
+
}
|
|
659
1878
|
}
|
|
660
|
-
function
|
|
661
|
-
const
|
|
662
|
-
|
|
1879
|
+
function computeSourceDigest(dirname, entryPath, vendorDir, builderToolsVersion = BUILDER_TOOLS_VERSION) {
|
|
1880
|
+
const h = createHash("sha256");
|
|
1881
|
+
h.update(`builder:${WORKER_BUILD_WORKER_HASH}\n`);
|
|
1882
|
+
h.update(`builder-tools:${builderToolsVersion}\n`);
|
|
1883
|
+
try {
|
|
1884
|
+
const pkgRoot = resolveWorkspacePackageDir(dirname, "@powerhousedao/connect");
|
|
1885
|
+
if (!pkgRoot) throw new Error("unresolved");
|
|
1886
|
+
const meta = JSON.parse(readFileSync(join(pkgRoot, "package.json"), "utf8"));
|
|
1887
|
+
h.update(`connect:${meta.version ?? "unknown"}\n`);
|
|
1888
|
+
} catch {
|
|
1889
|
+
h.update("connect:unresolved\n");
|
|
1890
|
+
}
|
|
1891
|
+
try {
|
|
1892
|
+
const stat = statSync(entryPath);
|
|
1893
|
+
h.update(`entry:${stat.size}:${Math.round(stat.mtimeMs)}\n`);
|
|
1894
|
+
} catch {
|
|
1895
|
+
h.update("entry:unstatable\n");
|
|
1896
|
+
}
|
|
1897
|
+
for (const pkg of upstreamWorkerPackages(dirname)) {
|
|
1898
|
+
const pkgDir = resolveWorkspacePackageDir(dirname, pkg);
|
|
1899
|
+
h.update(`${pkg}:${pkgDir ? distDirFingerprint(join(pkgDir, "dist")) : "unresolved"}\n`);
|
|
1900
|
+
}
|
|
1901
|
+
if (vendorDir) try {
|
|
1902
|
+
h.update(`vendor:${createHash("sha256").update(readFileSync(join(vendorDir, "import-map.json"))).digest("hex")}\n`);
|
|
1903
|
+
} catch {
|
|
1904
|
+
h.update("vendor:unreadable\n");
|
|
1905
|
+
}
|
|
1906
|
+
return h.digest("hex").slice(0, 16);
|
|
1907
|
+
}
|
|
1908
|
+
function vendorKeyOf(vendorImports) {
|
|
1909
|
+
const entries = Object.entries(vendorImports).sort(([a], [b]) => a.localeCompare(b));
|
|
1910
|
+
return createHash("sha256").update(JSON.stringify(entries)).digest("hex").slice(0, 16);
|
|
1911
|
+
}
|
|
1912
|
+
function readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv) {
|
|
1913
|
+
if (!existsSync(metaPath)) return false;
|
|
1914
|
+
try {
|
|
1915
|
+
const cached = JSON.parse(readFileSync(metaPath, "utf8"));
|
|
1916
|
+
return cached.sourceDigest === sourceDigest && cached.vendorKey === vendorKey && cached.nodeEnv === nodeEnv && existsSync(join(dirname(metaPath), "reactor.worker.js"));
|
|
1917
|
+
} catch {
|
|
1918
|
+
return false;
|
|
1919
|
+
}
|
|
1920
|
+
}
|
|
1921
|
+
/** Content digest of a directory tree (relative paths + bytes; source maps skipped). */
|
|
1922
|
+
function directoryContentDigest(dir) {
|
|
1923
|
+
const h = createHash("sha256");
|
|
1924
|
+
const files = readdirSync(dir, {
|
|
1925
|
+
recursive: true,
|
|
1926
|
+
withFileTypes: true
|
|
1927
|
+
}).filter((e) => e.isFile() && !e.name.endsWith(".map")).map((e) => join(e.parentPath, e.name)).sort();
|
|
1928
|
+
for (const file of files) {
|
|
1929
|
+
h.update(`${file.slice(dir.length).split("\\").join("/")}\n`);
|
|
1930
|
+
h.update(readFileSync(file));
|
|
1931
|
+
}
|
|
1932
|
+
return h.digest("hex").slice(0, 16);
|
|
1933
|
+
}
|
|
1934
|
+
async function waitForWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv, lockDir) {
|
|
1935
|
+
const deadline = Date.now() + LOCK_STALE_MS;
|
|
1936
|
+
while (Date.now() < deadline) {
|
|
1937
|
+
if (readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv)) return true;
|
|
1938
|
+
if (!existsSync(lockDir)) return readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv);
|
|
1939
|
+
await new Promise((r) => setTimeout(r, 250));
|
|
1940
|
+
}
|
|
1941
|
+
return false;
|
|
1942
|
+
}
|
|
1943
|
+
/**
|
|
1944
|
+
* Build the worker bundle (once, in a throwaway subprocess) into `outDir`.
|
|
1945
|
+
* Idempotent: reuses a cached bundle built from the same connect dist, vendor
|
|
1946
|
+
* mapping, and builder logic. Returns null on failure (`errorRef` carries the
|
|
1947
|
+
* cause) or when the installed Connect has no worker entry.
|
|
1948
|
+
*/
|
|
1949
|
+
async function prebuildReactorWorker(options) {
|
|
1950
|
+
const entryPath = options.entryPath ?? resolveReactorWorkerSource(options.dirname);
|
|
1951
|
+
if (!entryPath) {
|
|
1952
|
+
if (options.errorRef) options.errorRef.message = "the installed @powerhousedao/connect ships no dist/reactor.worker.js";
|
|
1953
|
+
return null;
|
|
1954
|
+
}
|
|
1955
|
+
const vendorImports = options.vendor ? workerSafeVendorImports(options.vendor.dir, options.vendor.imports) : {};
|
|
1956
|
+
const nodeEnv = options.nodeEnv ?? "development";
|
|
1957
|
+
const outDir = options.outDir;
|
|
1958
|
+
const metaPath = join(outDir, META_FILE);
|
|
1959
|
+
const sourceDigest = computeSourceDigest(options.dirname, entryPath, options.vendor?.dir);
|
|
1960
|
+
const vendorKey = vendorKeyOf(vendorImports);
|
|
1961
|
+
const result = {
|
|
1962
|
+
outDir,
|
|
1963
|
+
entry: REACTOR_WORKER_ENTRY,
|
|
1964
|
+
sourceDigest,
|
|
1965
|
+
vendorImports
|
|
1966
|
+
};
|
|
1967
|
+
try {
|
|
1968
|
+
if (readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv)) return result;
|
|
1969
|
+
const lockDir = `${outDir}.lock`;
|
|
1970
|
+
const lock = acquireLock(lockDir);
|
|
1971
|
+
if (!lock) return await waitForWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv, lockDir) ? result : null;
|
|
1972
|
+
try {
|
|
1973
|
+
if (readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv)) return result;
|
|
1974
|
+
await buildWorkerAtomic(options.dirname, outDir, entryPath, vendorImports, nodeEnv, {
|
|
1975
|
+
sourceDigest,
|
|
1976
|
+
vendorKey,
|
|
1977
|
+
nodeEnv
|
|
1978
|
+
});
|
|
1979
|
+
return result;
|
|
1980
|
+
} finally {
|
|
1981
|
+
releaseLock(lock);
|
|
1982
|
+
}
|
|
1983
|
+
} catch (err) {
|
|
1984
|
+
if (options.errorRef) options.errorRef.message = err instanceof Error ? err.message : String(err);
|
|
1985
|
+
return null;
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
async function buildWorkerAtomic(dirname$2, outDir, entryPath, vendorImports, nodeEnv, meta) {
|
|
1989
|
+
const parent = dirname(outDir);
|
|
1990
|
+
mkdirSync(parent, { recursive: true });
|
|
1991
|
+
const tmpDir = mkdtempSync(join(parent, ".ph-reactor-worker.tmp-"));
|
|
1992
|
+
try {
|
|
1993
|
+
const { ok, stderr } = await runWorkerBuild(dirname$2, tmpDir, { "reactor.worker": entryPath }, vendorImports, nodeEnv);
|
|
1994
|
+
if (!ok || !existsSync(join(tmpDir, "reactor.worker.js"))) {
|
|
1995
|
+
const detail = stderr.trim();
|
|
1996
|
+
throw new Error(`reactor worker build failed${detail ? `:\n${detail}` : " (no output captured)"}`);
|
|
1997
|
+
}
|
|
1998
|
+
assertWorkerResolvable(tmpDir);
|
|
1999
|
+
writeFileSync(join(tmpDir, META_FILE), JSON.stringify(meta, null, 2));
|
|
2000
|
+
publishDirAtomic(tmpDir, outDir);
|
|
2001
|
+
} catch (err) {
|
|
2002
|
+
rmSync(tmpDir, {
|
|
2003
|
+
recursive: true,
|
|
2004
|
+
force: true
|
|
2005
|
+
});
|
|
2006
|
+
throw err;
|
|
2007
|
+
}
|
|
2008
|
+
}
|
|
2009
|
+
/** Replace `outDir` with the finished `tmpDir`, old contents removed last. */
|
|
2010
|
+
function publishDirAtomic(tmpDir, outDir) {
|
|
2011
|
+
const oldDir = `${outDir}.old-${process.pid}-${Date.now()}`;
|
|
2012
|
+
if (existsSync(outDir)) renameSync(outDir, oldDir);
|
|
2013
|
+
renameSync(tmpDir, outDir);
|
|
2014
|
+
chmodSync(outDir, 493);
|
|
2015
|
+
rmSync(oldDir, {
|
|
2016
|
+
recursive: true,
|
|
2017
|
+
force: true
|
|
2018
|
+
});
|
|
2019
|
+
}
|
|
2020
|
+
const RELATIVE_SPECIFIER_PATTERNS = SPECIFIER_PATTERNS;
|
|
2021
|
+
function findRelativeSpecifiers(code) {
|
|
2022
|
+
const found = /* @__PURE__ */ new Set();
|
|
2023
|
+
for (const pattern of RELATIVE_SPECIFIER_PATTERNS) for (const match of code.matchAll(pattern)) {
|
|
2024
|
+
const spec = match[1];
|
|
2025
|
+
if (spec.startsWith("./") || spec.startsWith("../")) found.add(spec);
|
|
2026
|
+
}
|
|
2027
|
+
return [...found];
|
|
2028
|
+
}
|
|
2029
|
+
function normalizeBundlePath(fromFile, spec) {
|
|
2030
|
+
const segments = fromFile.split("/").slice(0, -1);
|
|
2031
|
+
for (const part of spec.split("/")) {
|
|
2032
|
+
if (part === "" || part === ".") continue;
|
|
2033
|
+
if (part === "..") {
|
|
2034
|
+
if (segments.length === 0) return "";
|
|
2035
|
+
segments.pop();
|
|
2036
|
+
continue;
|
|
2037
|
+
}
|
|
2038
|
+
segments.push(part);
|
|
2039
|
+
}
|
|
2040
|
+
return segments.join("/");
|
|
2041
|
+
}
|
|
2042
|
+
/**
|
|
2043
|
+
* Scan the emitted JS files REACHABLE from the entry via import statements
|
|
2044
|
+
* for specifiers a worker cannot resolve. Vendor externals were rewritten to
|
|
2045
|
+
* ../__vendor__/ relative paths, so anything bare that survives in the graph
|
|
2046
|
+
* is a real defect.
|
|
2047
|
+
*
|
|
2048
|
+
* Deliberately a graph walk, not a directory walk: the bundled reactor code
|
|
2049
|
+
* carries `new URL(..., import.meta.url)` references to its node
|
|
2050
|
+
* worker-thread entries (executor/projection workers), which Vite emits as
|
|
2051
|
+
* stray assets full of node-only imports. They are unreachable dead weight in
|
|
2052
|
+
* a browser bundle — the production vendor output tolerates the same files —
|
|
2053
|
+
* and must not fail the build.
|
|
2054
|
+
*/
|
|
2055
|
+
function findBundleSpecifierOffenders(bundleDir, entry = REACTOR_WORKER_ENTRY) {
|
|
2056
|
+
const offenders = [];
|
|
2057
|
+
walkBundleGraph(bundleDir, entry, (file, code) => {
|
|
2058
|
+
const specs = findDisallowedSpecifiers(code);
|
|
2059
|
+
if (specs.length > 0) offenders.push({
|
|
2060
|
+
file,
|
|
2061
|
+
specs
|
|
2062
|
+
});
|
|
2063
|
+
return true;
|
|
2064
|
+
});
|
|
2065
|
+
return offenders;
|
|
2066
|
+
}
|
|
2067
|
+
function walkBundleGraph(bundleDir, entry, visit) {
|
|
2068
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2069
|
+
const queue = [entry];
|
|
2070
|
+
while (queue.length > 0) {
|
|
2071
|
+
const rel = queue.shift();
|
|
2072
|
+
if (seen.has(rel)) continue;
|
|
2073
|
+
seen.add(rel);
|
|
2074
|
+
const full = join(bundleDir, rel);
|
|
2075
|
+
if (!existsSync(full) || statSync(full).isDirectory()) continue;
|
|
2076
|
+
if (!rel.endsWith(".js") && !rel.endsWith(".mjs")) continue;
|
|
2077
|
+
const code = readFileSync(full, "utf8");
|
|
2078
|
+
if (!visit(rel, code)) return false;
|
|
2079
|
+
for (const spec of findRelativeSpecifiers(code)) {
|
|
2080
|
+
const next = normalizeBundlePath(rel, spec);
|
|
2081
|
+
if (next) queue.push(next);
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
return true;
|
|
2085
|
+
}
|
|
2086
|
+
function assertWorkerResolvable(bundleDir) {
|
|
2087
|
+
const offenders = findBundleSpecifierOffenders(bundleDir);
|
|
2088
|
+
if (offenders.length > 0) throw new Error("reactor worker bundle contains module specifiers a worker cannot resolve:\n" + offenders.map((o) => ` ${o.file}: ${o.specs.join(", ")}`).join("\n"));
|
|
2089
|
+
}
|
|
2090
|
+
const WORKER_UNSAFE_MARKERS = ["__PH_DYNAMIC_BASE__", "vite:preloadError"];
|
|
2091
|
+
/** The page-only markers present in `code`, in a fixed order. */
|
|
2092
|
+
function findWorkerUnsafeMarkers(code) {
|
|
2093
|
+
return WORKER_UNSAFE_MARKERS.filter((marker) => code.includes(marker));
|
|
2094
|
+
}
|
|
2095
|
+
/**
|
|
2096
|
+
* The subset of the vendor's entries a worker may import.
|
|
2097
|
+
*
|
|
2098
|
+
* The vendor build keeps the React family external: its chunks carry bare
|
|
2099
|
+
* `import "react"` statements that the PAGE resolves through its import map.
|
|
2100
|
+
* A worker resolves no import map, so externalizing a vendor spec whose chunk
|
|
2101
|
+
* closure reaches such an import would kill the worker on its first load —
|
|
2102
|
+
* and the chunk graph is shared across vendor entries, so even a React-free
|
|
2103
|
+
* module (e.g. an rpc subpath) can be entangled with React through a shared
|
|
2104
|
+
* chunk. The vendor is also built for the page: a dynamic-base build rewrites
|
|
2105
|
+
* its asset URLs onto a global only the page sets, and its dynamic imports go
|
|
2106
|
+
* through Vite's preload helper, which needs `document`. Each entry's own
|
|
2107
|
+
* closure inside the vendor dir decides: clean closure, worker-safe; anything
|
|
2108
|
+
* bare or page-only in it (see {@link findWorkerUnsafeMarkers}), or a missing
|
|
2109
|
+
* entry file, bundled into the worker instead.
|
|
2110
|
+
*/
|
|
2111
|
+
function workerSafeVendorImports(vendorDir, vendorImports) {
|
|
2112
|
+
const safe = {};
|
|
2113
|
+
for (const [spec, url] of Object.entries(vendorImports)) {
|
|
2114
|
+
const entryFile = url.slice(url.lastIndexOf("/") + 1);
|
|
2115
|
+
if (!existsSync(join(vendorDir, entryFile))) continue;
|
|
2116
|
+
if (walkBundleGraph(vendorDir, entryFile, (_file, code) => findDisallowedSpecifiers(code).length === 0 && findWorkerUnsafeMarkers(code).length === 0)) safe[spec] = url;
|
|
2117
|
+
}
|
|
2118
|
+
return safe;
|
|
2119
|
+
}
|
|
2120
|
+
/**
|
|
2121
|
+
* Builds arbitrary worker-loadable entries with the worker build config.
|
|
2122
|
+
* Exported for the local-package bundles, which need the same self-contained
|
|
2123
|
+
* output and vendor externalization at a different depth.
|
|
2124
|
+
*/
|
|
2125
|
+
function runWorkerBuildEntries(dirname, outDir, entries, vendorImports, nodeEnv, vendorPrefix = "../__vendor__/") {
|
|
2126
|
+
return runWorkerBuild(dirname, outDir, entries, vendorImports, nodeEnv, vendorPrefix);
|
|
2127
|
+
}
|
|
2128
|
+
function runWorkerBuild(dirname, outDir, entries, vendorImports, nodeEnv, vendorPrefix = "../__vendor__/") {
|
|
2129
|
+
const workerPath = join(outDir, "build-worker.mjs");
|
|
2130
|
+
writeFileSync(workerPath, WORKER_BUILD_WORKER);
|
|
2131
|
+
return new Promise((resolve) => {
|
|
2132
|
+
const child = spawn(process.execPath, [
|
|
2133
|
+
workerPath,
|
|
2134
|
+
dirname,
|
|
2135
|
+
outDir,
|
|
2136
|
+
JSON.stringify(entries),
|
|
2137
|
+
JSON.stringify(vendorImports),
|
|
2138
|
+
nodeEnv,
|
|
2139
|
+
resolveBuilderVite() ?? "",
|
|
2140
|
+
vendorPrefix
|
|
2141
|
+
], {
|
|
2142
|
+
cwd: dirname,
|
|
2143
|
+
stdio: [
|
|
2144
|
+
"ignore",
|
|
2145
|
+
"pipe",
|
|
2146
|
+
"pipe"
|
|
2147
|
+
]
|
|
2148
|
+
});
|
|
2149
|
+
let stderr = "";
|
|
2150
|
+
child.stdout.on("data", (d) => {
|
|
2151
|
+
stderr += String(d);
|
|
2152
|
+
});
|
|
2153
|
+
child.stderr.on("data", (d) => {
|
|
2154
|
+
stderr += String(d);
|
|
2155
|
+
});
|
|
2156
|
+
child.on("exit", (code) => {
|
|
2157
|
+
rmSync(workerPath, { force: true });
|
|
2158
|
+
resolve({
|
|
2159
|
+
ok: code === 0,
|
|
2160
|
+
stderr
|
|
2161
|
+
});
|
|
2162
|
+
});
|
|
2163
|
+
child.on("error", (e) => resolve({
|
|
2164
|
+
ok: false,
|
|
2165
|
+
stderr: String(e)
|
|
2166
|
+
}));
|
|
2167
|
+
});
|
|
2168
|
+
}
|
|
2169
|
+
/**
|
|
2170
|
+
* The vite installed next to this module. The subprocess must run the vite
|
|
2171
|
+
* this build config was written against: a consumer project can pin an older
|
|
2172
|
+
* vite/rolldown (overrides) whose bundler leaves unresolvable specifiers bare
|
|
2173
|
+
* instead of erroring and shims node builtins differently — the output guard
|
|
2174
|
+
* then correctly rejects the bundle. builder-tools declares vite as a direct
|
|
2175
|
+
* dependency, so this resolution works wherever builder-tools is installed.
|
|
2176
|
+
*/
|
|
2177
|
+
function resolveBuilderVite() {
|
|
2178
|
+
try {
|
|
2179
|
+
return createRequire(import.meta.url).resolve("vite");
|
|
2180
|
+
} catch {
|
|
2181
|
+
return null;
|
|
2182
|
+
}
|
|
663
2183
|
}
|
|
664
2184
|
/**
|
|
665
|
-
*
|
|
2185
|
+
* The build subprocess (same pattern as the vendor's). Loads builder-tools'
|
|
2186
|
+
* own vite (argv; project fallback) and builds the given entries with
|
|
2187
|
+
* relative base, so chunk/asset URLs resolve against each script's own URL
|
|
2188
|
+
* under any deploy base. argv: dirname, outDir, entriesJSON (name ->
|
|
2189
|
+
* absolute entry path), vendorImportsJSON, nodeEnv, vitePath, vendorPrefix
|
|
2190
|
+
* (relative path from the out dir to __vendor__/, e.g. "../__vendor__/").
|
|
2191
|
+
*/
|
|
2192
|
+
const WORKER_BUILD_WORKER = `
|
|
2193
|
+
import { createRequire } from 'node:module';
|
|
2194
|
+
import { isAbsolute } from 'node:path';
|
|
2195
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
2196
|
+
const [dirname, outDir, entriesJSON, vendorImportsJSON, nodeEnvArg, vitePathArg, vendorPrefixArg] = process.argv.slice(2);
|
|
2197
|
+
const nodeEnv = nodeEnvArg ?? 'development';
|
|
2198
|
+
const entries = JSON.parse(entriesJSON);
|
|
2199
|
+
const vendorImports = JSON.parse(vendorImportsJSON ?? '{}');
|
|
2200
|
+
const vendorPrefix = vendorPrefixArg || '../__vendor__/';
|
|
2201
|
+
const externalSet = new Set(Object.keys(vendorImports));
|
|
2202
|
+
const vendorPath = (spec) => {
|
|
2203
|
+
const url = vendorImports[spec];
|
|
2204
|
+
return vendorPrefix + url.slice(url.lastIndexOf('/') + 1);
|
|
2205
|
+
};
|
|
2206
|
+
const reqProj = createRequire(dirname + '/noop.js');
|
|
2207
|
+
// pathToFileURL: on Windows import('D:\\\\...') parses "D:" as a URL scheme.
|
|
2208
|
+
const vitePath = vitePathArg || reqProj.resolve('vite');
|
|
2209
|
+
const { build } = await import(pathToFileURL(vitePath).href);
|
|
2210
|
+
// Resolve bare specifiers from the project (same plugin as the vendor build):
|
|
2211
|
+
// prefer the bundler's browser-condition-aware resolution, fall back to the
|
|
2212
|
+
// worker's own resolution for Rolldown's realpath-anchoring bug.
|
|
2213
|
+
const phResolveCache = new Map();
|
|
2214
|
+
const phWorkerResolve = {
|
|
2215
|
+
name: 'ph-reactor-worker-resolve', enforce: 'pre',
|
|
2216
|
+
async resolveId(source, importer, options) {
|
|
2217
|
+
if (externalSet.has(source)) return null;
|
|
2218
|
+
if (source[0] === '\\0' || source[0] === '.' || isAbsolute(source)) return null;
|
|
2219
|
+
if (source.startsWith('node:') || source.startsWith('data:')) return null;
|
|
2220
|
+
let viaBundler = null;
|
|
2221
|
+
try { viaBundler = await this.resolve(source, importer, { ...options, skipSelf: true }); } catch {}
|
|
2222
|
+
if (viaBundler) return viaBundler;
|
|
2223
|
+
if (phResolveCache.has(source)) return phResolveCache.get(source);
|
|
2224
|
+
let resolved = null;
|
|
2225
|
+
try { resolved = fileURLToPath(import.meta.resolve(source)); } catch {}
|
|
2226
|
+
phResolveCache.set(source, resolved);
|
|
2227
|
+
return resolved;
|
|
2228
|
+
},
|
|
2229
|
+
};
|
|
2230
|
+
// A worker has no window: on a failed dynamic import, the preload helper's
|
|
2231
|
+
// window.dispatchEvent would throw a ReferenceError in place of the real error.
|
|
2232
|
+
const PRELOAD_HELPER_ID = '\\0vite/preload-helper.js';
|
|
2233
|
+
const PRELOAD_DISPATCH = 'window.dispatchEvent(';
|
|
2234
|
+
const phWorkerPreloadHelper = {
|
|
2235
|
+
name: 'ph-reactor-worker-preload-helper',
|
|
2236
|
+
transform(code, id) {
|
|
2237
|
+
if (id !== PRELOAD_HELPER_ID) return null;
|
|
2238
|
+
if (code.split(PRELOAD_DISPATCH).length !== 2) {
|
|
2239
|
+
this.error('expected exactly one ' + PRELOAD_DISPATCH + ' in ' + PRELOAD_HELPER_ID);
|
|
2240
|
+
}
|
|
2241
|
+
return { code: code.replace(PRELOAD_DISPATCH, 'globalThis.dispatchEvent?.('), map: null };
|
|
2242
|
+
},
|
|
2243
|
+
};
|
|
2244
|
+
await build({
|
|
2245
|
+
root: dirname, configFile: false, logLevel: 'error',
|
|
2246
|
+
// The project's public/ dir belongs to the app build, not this bundle.
|
|
2247
|
+
publicDir: false,
|
|
2248
|
+
// Relative base: emitted chunk/asset URLs resolve against the worker
|
|
2249
|
+
// script's own URL, so the bundle works under any deploy base.
|
|
2250
|
+
base: './',
|
|
2251
|
+
define: {
|
|
2252
|
+
'process.env.NODE_ENV': JSON.stringify(nodeEnv),
|
|
2253
|
+
'import.meta.env.BASE_URL': JSON.stringify('./'),
|
|
2254
|
+
},
|
|
2255
|
+
plugins: [phWorkerResolve, phWorkerPreloadHelper],
|
|
2256
|
+
// pglite ships nested web workers as ES-module chunks.
|
|
2257
|
+
worker: { format: 'es' },
|
|
2258
|
+
build: {
|
|
2259
|
+
// Always minified, dev included: the bundle is browser-served output
|
|
2260
|
+
// (sourcemaps carry the debugging story), and minification strips the
|
|
2261
|
+
// JSDoc comments whose embedded code samples (kysely's, viem's) would
|
|
2262
|
+
// otherwise trip the bare-specifier guard below.
|
|
2263
|
+
outDir, emptyOutDir: false, minify: true, target: 'esnext', sourcemap: true,
|
|
2264
|
+
// No document in a worker: the module-preload polyfill and preload helper
|
|
2265
|
+
// touch the DOM, so dynamic imports must stay plain import().
|
|
2266
|
+
modulePreload: false,
|
|
2267
|
+
rollupOptions: {
|
|
2268
|
+
input: entries,
|
|
2269
|
+
// A models entry is pure re-exports; without this the bundler treats
|
|
2270
|
+
// its exports as unused and tree-shakes the whole file to nothing.
|
|
2271
|
+
// Harmless for the worker entry, which exports nothing to preserve.
|
|
2272
|
+
preserveEntrySignatures: 'strict',
|
|
2273
|
+
external: (id) => externalSet.has(id),
|
|
2274
|
+
output: {
|
|
2275
|
+
format: 'es', entryFileNames: '[name].js',
|
|
2276
|
+
// Chunks live at the bundle root, not a chunks/ subdir: the vendor
|
|
2277
|
+
// paths below are emitted VERBATIM into every chunk, so all modules
|
|
2278
|
+
// must sit at the same depth for ../__vendor__/ to resolve.
|
|
2279
|
+
chunkFileNames: '[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]',
|
|
2280
|
+
paths: (id) => (externalSet.has(id) ? vendorPath(id) : id),
|
|
2281
|
+
},
|
|
2282
|
+
},
|
|
2283
|
+
},
|
|
2284
|
+
});
|
|
2285
|
+
`;
|
|
2286
|
+
const WORKER_BUILD_WORKER_HASH = createHash("sha256").update(WORKER_BUILD_WORKER).digest("hex").slice(0, 16);
|
|
2287
|
+
//#endregion
|
|
2288
|
+
//#region connect-utils/worker-packages-build.ts
|
|
2289
|
+
/**
|
|
2290
|
+
* Prebuild a project's local packages into worker-loadable model bundles.
|
|
2291
|
+
*
|
|
2292
|
+
* The reactor worker gets document models from the registry CDN or from what
|
|
2293
|
+
* Connect statically bundled. A project's own (`provider: "local"`) package is
|
|
2294
|
+
* in neither, so its document types have no reducer in the worker and their
|
|
2295
|
+
* load jobs fail. Dev solves this by pointing the worker at the dev server's
|
|
2296
|
+
* transformed models entry; a production deployment has no dev server, so the
|
|
2297
|
+
* entry is prebuilt here, next to the worker bundle it is loaded beside.
|
|
2298
|
+
*
|
|
2299
|
+
* Each package's `browser/document-models/index.js` (reducers only: no React,
|
|
2300
|
+
* no CSS, no editors) is built self-contained, with the worker-safe subset of
|
|
2301
|
+
* the vendor externalized onto `../../__vendor__/` - two levels up, since
|
|
2302
|
+
* these land in `__reactor_worker__/packages/`. A `manifest.json` names what
|
|
2303
|
+
* was built so the tab can turn it into package sources without guessing.
|
|
666
2304
|
*/
|
|
667
|
-
|
|
2305
|
+
/** Served under `<base>__reactor_worker__/packages/`. */
|
|
2306
|
+
const WORKER_PACKAGES_MANIFEST = "manifest.json";
|
|
2307
|
+
/** Vendor is two levels up from `__reactor_worker__/packages/`. */
|
|
2308
|
+
const VENDOR_PREFIX = "../../__vendor__/";
|
|
2309
|
+
function readVersion(root) {
|
|
668
2310
|
try {
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
fs.cpSync(sourcePath, targetPath, { recursive: true });
|
|
674
|
-
} catch (error) {
|
|
675
|
-
console.error(`❌ Error copying ${sourcePath} to ${targetPath}:`, error);
|
|
2311
|
+
const meta = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
|
2312
|
+
return typeof meta.version === "string" ? meta.version : void 0;
|
|
2313
|
+
} catch {
|
|
2314
|
+
return;
|
|
676
2315
|
}
|
|
677
2316
|
}
|
|
678
2317
|
/**
|
|
679
|
-
*
|
|
2318
|
+
* A package root's models entry, or null when it ships none.
|
|
680
2319
|
*
|
|
681
|
-
*
|
|
2320
|
+
* Two roots are possible and both are normal: an installed dependency under
|
|
2321
|
+
* `node_modules/<name>`, and the project itself - the vetra case, where the
|
|
2322
|
+
* project *is* the local package and has no self-link in node_modules.
|
|
682
2323
|
*/
|
|
683
|
-
function
|
|
684
|
-
const
|
|
685
|
-
const backupPath = join(appPath, "index.html.bak");
|
|
686
|
-
const paths = restore ? [backupPath, filePath] : [filePath, backupPath];
|
|
687
|
-
if (fs.existsSync(paths[0])) fs.copyFileSync(paths[0], paths[1]);
|
|
688
|
-
}
|
|
689
|
-
function removeBase64EnvValues(appPath) {
|
|
690
|
-
backupIndexHtml(appPath);
|
|
691
|
-
const filePath = join(appPath, "index.html");
|
|
692
|
-
fs.readFile(filePath, "utf-8", (err, data) => {
|
|
693
|
-
if (err) {
|
|
694
|
-
console.error("Error reading file:", err);
|
|
695
|
-
return;
|
|
696
|
-
}
|
|
697
|
-
const modifiedData = data.replace(/"LOCAL_DOCUMENT_MODELS":\s*".*?",/, `"LOCAL_DOCUMENT_MODELS": "",`).replace(/"LOCAL_DOCUMENT_EDITORS":\s*".*?"/, `"LOCAL_DOCUMENT_EDITORS": ""`);
|
|
698
|
-
console.log("Modified data:", modifiedData);
|
|
699
|
-
fs.writeFile(filePath, modifiedData, "utf-8", (err) => {
|
|
700
|
-
if (err) {
|
|
701
|
-
console.error("Error writing file:", err);
|
|
702
|
-
return;
|
|
703
|
-
}
|
|
704
|
-
});
|
|
705
|
-
});
|
|
706
|
-
}
|
|
707
|
-
function readJsonFile(filePath) {
|
|
2324
|
+
function resolvePackageModels(dirname, name) {
|
|
2325
|
+
const roots = [];
|
|
708
2326
|
try {
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
return
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
* Takes a list of Powerhouse project packages and optionally local Powerhouse packages and outputs a js file which exports those packages for use in Connect Studio.
|
|
719
|
-
*/
|
|
720
|
-
function makeImportScriptFromPackages(args) {
|
|
721
|
-
const { packages, localJsPath, localCssPath, importStyles = true } = args;
|
|
722
|
-
const imports = [];
|
|
723
|
-
const moduleNames = [];
|
|
724
|
-
let counter = 0;
|
|
725
|
-
for (const packageName of packages) {
|
|
726
|
-
const moduleName = `module${counter}`;
|
|
727
|
-
moduleNames.push(moduleName);
|
|
728
|
-
imports.push(`import * as ${moduleName} from '${packageName}';`);
|
|
729
|
-
if (importStyles) imports.push(`import '${packageName}/style.css';`);
|
|
730
|
-
counter++;
|
|
731
|
-
}
|
|
732
|
-
const exports = moduleNames.map((name, index) => `{
|
|
733
|
-
id: "${packages[index]}",
|
|
734
|
-
...${name},
|
|
735
|
-
}`);
|
|
736
|
-
const hasModule = localJsPath !== void 0;
|
|
737
|
-
const hasStyles = importStyles && localCssPath !== void 0;
|
|
738
|
-
if (hasModule || hasStyles) {
|
|
739
|
-
if (hasStyles) imports.push(`import '${localCssPath}';`);
|
|
740
|
-
if (hasModule) {
|
|
741
|
-
const moduleName = `module${counter}`;
|
|
742
|
-
imports.push(`import * as ${moduleName} from '${localJsPath}';`);
|
|
743
|
-
exports.push(`{
|
|
744
|
-
id: "${LOCAL_PACKAGE_ID}",
|
|
745
|
-
...${moduleName},
|
|
746
|
-
}`);
|
|
747
|
-
}
|
|
2327
|
+
roots.push(realpathSync(join(dirname, "node_modules", name)));
|
|
2328
|
+
} catch {}
|
|
2329
|
+
if (readProjectName(dirname) === name) roots.push(dirname);
|
|
2330
|
+
for (const root of roots) {
|
|
2331
|
+
const entryPath = join(root, "dist", "browser", "document-models", "index.js");
|
|
2332
|
+
if (existsSync(entryPath)) return {
|
|
2333
|
+
entryPath,
|
|
2334
|
+
version: readVersion(root)
|
|
2335
|
+
};
|
|
748
2336
|
}
|
|
749
|
-
|
|
750
|
-
${exports.join(",\n")}
|
|
751
|
-
` : ""}];`;
|
|
752
|
-
return `${imports.join("\n")}\n\n${exportStatement}`;
|
|
2337
|
+
return null;
|
|
753
2338
|
}
|
|
754
|
-
function
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
2339
|
+
function readProjectName(dirname) {
|
|
2340
|
+
try {
|
|
2341
|
+
const meta = JSON.parse(readFileSync(join(dirname, "package.json"), "utf8"));
|
|
2342
|
+
return typeof meta.name === "string" ? meta.name : void 0;
|
|
2343
|
+
} catch {
|
|
2344
|
+
return;
|
|
760
2345
|
}
|
|
761
2346
|
}
|
|
762
|
-
function runShellScriptPlugin(scriptName, connectPath) {
|
|
763
|
-
return {
|
|
764
|
-
name: "vite-plugin-run-shell-script",
|
|
765
|
-
buildStart() {
|
|
766
|
-
const scriptPath = join(connectPath, scriptName);
|
|
767
|
-
if (fs.existsSync(scriptPath)) exec(`sh ${scriptPath}`, (error, stdout, stderr) => {
|
|
768
|
-
if (error) {
|
|
769
|
-
console.error(`Error executing the script: ${error.message}`);
|
|
770
|
-
removeBase64EnvValues(connectPath);
|
|
771
|
-
return;
|
|
772
|
-
}
|
|
773
|
-
if (stderr) console.error(stderr);
|
|
774
|
-
});
|
|
775
|
-
}
|
|
776
|
-
};
|
|
777
|
-
}
|
|
778
2347
|
/**
|
|
779
|
-
*
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
let html = await readFile(pathToHtml, "utf8");
|
|
784
|
-
html = transform(html, contents);
|
|
785
|
-
await writeFile(pathToHtml, html, "utf8");
|
|
786
|
-
}
|
|
787
|
-
/**
|
|
788
|
-
* Appends the contents to the <head> tag of the index.html file
|
|
2348
|
+
* The project's own package name when it ships a models bundle, so a caller
|
|
2349
|
+
* can include it beside the configured `provider: "local"` packages. A vetra
|
|
2350
|
+
* project declares no package entry for itself, yet its models are exactly
|
|
2351
|
+
* the ones the worker is missing.
|
|
789
2352
|
*/
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
});
|
|
2353
|
+
function ownProjectPackage(dirname) {
|
|
2354
|
+
const name = readProjectName(dirname);
|
|
2355
|
+
if (!name) return void 0;
|
|
2356
|
+
return resolvePackageModels(dirname, name) ? name : void 0;
|
|
795
2357
|
}
|
|
796
2358
|
/**
|
|
797
|
-
*
|
|
2359
|
+
* Build each local package's models entry into `outDir` and write the
|
|
2360
|
+
* manifest the tab reads. Returns the manifest entries (empty when no local
|
|
2361
|
+
* package ships a models bundle), or null when the build itself failed -
|
|
2362
|
+
* `errorRef` then carries the cause. Both of those remove `outDir`, so a
|
|
2363
|
+
* previous build's bundles never outlive the packages they came from.
|
|
798
2364
|
*/
|
|
799
|
-
async function
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
2365
|
+
async function prebuildWorkerPackages(options) {
|
|
2366
|
+
const nodeEnv = options.nodeEnv ?? "production";
|
|
2367
|
+
const resolved = [];
|
|
2368
|
+
for (const name of options.packages) {
|
|
2369
|
+
const models = resolvePackageModels(options.dirname, name);
|
|
2370
|
+
if (!models) continue;
|
|
2371
|
+
resolved.push({
|
|
2372
|
+
entry: {
|
|
2373
|
+
name,
|
|
2374
|
+
version: models.version,
|
|
2375
|
+
file: workerPackageFileName(name)
|
|
2376
|
+
},
|
|
2377
|
+
entryPath: models.entryPath
|
|
2378
|
+
});
|
|
2379
|
+
}
|
|
2380
|
+
if (resolved.length === 0) {
|
|
2381
|
+
rmSync(options.outDir, {
|
|
2382
|
+
recursive: true,
|
|
2383
|
+
force: true
|
|
2384
|
+
});
|
|
2385
|
+
return [];
|
|
2386
|
+
}
|
|
2387
|
+
const vendorImports = options.safeVendorImports ?? (options.vendor ? workerSafeVendorImports(options.vendor.dir, options.vendor.imports) : {});
|
|
2388
|
+
const entries = Object.fromEntries(resolved.map((item) => [item.entry.file.replace(/\.js$/, ""), item.entryPath]));
|
|
2389
|
+
const parent = dirname(options.outDir);
|
|
2390
|
+
mkdirSync(parent, { recursive: true });
|
|
2391
|
+
const tmpDir = mkdtempSync(join(parent, ".ph-worker-packages.tmp-"));
|
|
2392
|
+
try {
|
|
2393
|
+
const { ok, stderr } = await runWorkerBuildEntries(options.dirname, tmpDir, entries, vendorImports, nodeEnv, VENDOR_PREFIX);
|
|
2394
|
+
const missing = resolved.filter((item) => !existsSync(join(tmpDir, item.entry.file)));
|
|
2395
|
+
if (!ok || missing.length > 0) {
|
|
2396
|
+
const detail = stderr.trim();
|
|
2397
|
+
throw new Error(`worker package bundles failed to build${missing.length > 0 ? ` (missing: ${missing.map((m) => m.entry.name).join(", ")})` : ""}${detail ? `:\n${detail}` : ""}`);
|
|
2398
|
+
}
|
|
2399
|
+
for (const item of resolved) {
|
|
2400
|
+
const offenders = findBundleSpecifierOffenders(tmpDir, item.entry.file);
|
|
2401
|
+
if (offenders.length > 0) throw new Error(`worker package bundle for ${item.entry.name} contains module specifiers a worker cannot resolve:\n` + offenders.map((o) => ` ${o.file}: ${o.specs.join(", ")}`).join("\n"));
|
|
2402
|
+
}
|
|
2403
|
+
const manifest = resolved.map((item) => item.entry);
|
|
2404
|
+
writeFileSync(join(tmpDir, WORKER_PACKAGES_MANIFEST), JSON.stringify(manifest, null, 2));
|
|
2405
|
+
publishDirAtomic(tmpDir, options.outDir);
|
|
2406
|
+
return manifest;
|
|
2407
|
+
} catch (err) {
|
|
2408
|
+
rmSync(tmpDir, {
|
|
2409
|
+
recursive: true,
|
|
2410
|
+
force: true
|
|
2411
|
+
});
|
|
2412
|
+
rmSync(options.outDir, {
|
|
2413
|
+
recursive: true,
|
|
2414
|
+
force: true
|
|
2415
|
+
});
|
|
2416
|
+
if (options.errorRef) options.errorRef.message = err instanceof Error ? err.message : String(err);
|
|
2417
|
+
return null;
|
|
2418
|
+
}
|
|
814
2419
|
}
|
|
815
2420
|
//#endregion
|
|
816
2421
|
//#region connect-utils/runtime-config-schema.ts
|
|
@@ -872,6 +2477,10 @@ function readBundledPackageVersion(projectRoot, name) {
|
|
|
872
2477
|
return;
|
|
873
2478
|
}
|
|
874
2479
|
}
|
|
2480
|
+
function offeredRoutesFile(projectRoot, name) {
|
|
2481
|
+
const file = path.join(projectRoot, "node_modules", name, "dist/browser/connect-routes.js");
|
|
2482
|
+
return fs.existsSync(file) ? file : void 0;
|
|
2483
|
+
}
|
|
875
2484
|
function makeRegisterModule(packages, projectRoot) {
|
|
876
2485
|
if (packages.length === 0) return "export default () => {};\n";
|
|
877
2486
|
const imports = [];
|
|
@@ -881,7 +2490,9 @@ function makeRegisterModule(packages, projectRoot) {
|
|
|
881
2490
|
const version = readBundledPackageVersion(projectRoot, name);
|
|
882
2491
|
imports.push(`import * as ${moduleName} from ${JSON.stringify(name)};`);
|
|
883
2492
|
imports.push(`import ${JSON.stringify(`${name}/style.css`)};`);
|
|
884
|
-
|
|
2493
|
+
const routesFile = offeredRoutesFile(projectRoot, name);
|
|
2494
|
+
const routes = routesFile ? `, () => import(${JSON.stringify(routesFile)})` : "";
|
|
2495
|
+
calls.push(` pm.addLocalPackage(${JSON.stringify(name)}, ${moduleName}, ${JSON.stringify(version)}${routes});`);
|
|
885
2496
|
});
|
|
886
2497
|
return `${imports.join("\n")}\n\nexport default function register(pm) {\n${calls.join("\n")}\n};\n`;
|
|
887
2498
|
}
|
|
@@ -939,7 +2550,8 @@ const VENDOR_MIME = {
|
|
|
939
2550
|
const VENDOR_MODE = process.env.PH_CONNECT_EXTERNALIZE_VENDOR === "1";
|
|
940
2551
|
const VENDOR_EXTRA = (process.env.PH_CONNECT_VENDOR_EXTRA ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
941
2552
|
const HEAVY_LIBS = [...DEFAULT_VENDOR_INCLUDE, ...VENDOR_EXTRA];
|
|
942
|
-
|
|
2553
|
+
const heavyLibsFor = (routesDir) => routesDir ? HEAVY_LIBS.filter((lib) => lib !== "@powerhousedao/connect") : HEAVY_LIBS;
|
|
2554
|
+
function withBase$1(base, p) {
|
|
943
2555
|
return `${base}${p}`.replace(/\/{2,}/g, "/");
|
|
944
2556
|
}
|
|
945
2557
|
function externalizePlugin(externals) {
|
|
@@ -974,15 +2586,16 @@ function externalizePlugin(externals) {
|
|
|
974
2586
|
* the React shims above → one React instance across Connect, the vendor, and
|
|
975
2587
|
* CDN editors.
|
|
976
2588
|
*/
|
|
977
|
-
async function devReactImportmapPlugin(projectRoot = process.cwd()) {
|
|
2589
|
+
async function devReactImportmapPlugin(projectRoot = process.cwd(), routesDir = resolveConnectRoutesDir(projectRoot)) {
|
|
978
2590
|
let namedExports = /* @__PURE__ */ new Map();
|
|
979
2591
|
let base = "/";
|
|
980
2592
|
let vendor = null;
|
|
2593
|
+
const heavyLibs = heavyLibsFor(routesDir);
|
|
981
2594
|
if (VENDOR_MODE) {
|
|
982
2595
|
const errorRef = {};
|
|
983
2596
|
vendor = await prebuildConnectVendor({
|
|
984
2597
|
dirname: projectRoot,
|
|
985
|
-
include:
|
|
2598
|
+
include: heavyLibs,
|
|
986
2599
|
errorRef
|
|
987
2600
|
});
|
|
988
2601
|
if (!vendor) {
|
|
@@ -1001,8 +2614,8 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
|
|
|
1001
2614
|
const include = new Set(cfg.optimizeDeps.include ?? []);
|
|
1002
2615
|
REACT_DEPS.forEach((d) => include.add(d));
|
|
1003
2616
|
if (vendorActive) {
|
|
1004
|
-
|
|
1005
|
-
cfg.optimizeDeps.exclude = [
|
|
2617
|
+
heavyLibs.forEach((d) => include.delete(d));
|
|
2618
|
+
cfg.optimizeDeps.exclude = [.../* @__PURE__ */ new Set([...cfg.optimizeDeps.exclude ?? [], ...heavyLibs])];
|
|
1006
2619
|
}
|
|
1007
2620
|
cfg.optimizeDeps.include = [...include];
|
|
1008
2621
|
},
|
|
@@ -1021,7 +2634,7 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
|
|
|
1021
2634
|
}));
|
|
1022
2635
|
if (vendorActive) {
|
|
1023
2636
|
const vendorDir = vendor.vendorDir;
|
|
1024
|
-
const vendorPrefixes = [withBase(base, VENDOR_URL_PREFIX), VENDOR_URL_PREFIX];
|
|
2637
|
+
const vendorPrefixes = [withBase$1(base, VENDOR_URL_PREFIX), VENDOR_URL_PREFIX];
|
|
1025
2638
|
server.middlewares.use((req, res, next) => {
|
|
1026
2639
|
const url = (req.url ?? "").split("?")[0];
|
|
1027
2640
|
const prefix = vendorPrefixes.find((p) => url.startsWith(p));
|
|
@@ -1043,7 +2656,7 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
|
|
|
1043
2656
|
});
|
|
1044
2657
|
});
|
|
1045
2658
|
}
|
|
1046
|
-
const shimPrefixes = [withBase(base, SHIM_PATH), `/${SHIM_PATH}`];
|
|
2659
|
+
const shimPrefixes = [withBase$1(base, SHIM_PATH), `/${SHIM_PATH}`];
|
|
1047
2660
|
server.middlewares.use((req, res, next) => {
|
|
1048
2661
|
const prefix = shimPrefixes.find((p) => req.url?.startsWith(p));
|
|
1049
2662
|
if (!prefix) return next();
|
|
@@ -1057,7 +2670,7 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
|
|
|
1057
2670
|
return;
|
|
1058
2671
|
}
|
|
1059
2672
|
const browserHash = info.browserHash ?? optimizer.metadata.browserHash;
|
|
1060
|
-
const depUrl = `${withBase(base, VITE_DEPS_PATH)}/${path.basename(info.file)}?v=${browserHash}`;
|
|
2673
|
+
const depUrl = `${withBase$1(base, VITE_DEPS_PATH)}/${path.basename(info.file)}?v=${browserHash}`;
|
|
1061
2674
|
const names = namedExports.get(id) ?? [];
|
|
1062
2675
|
res.setHeader("Content-Type", "application/javascript");
|
|
1063
2676
|
res.end(`import * as M from ${JSON.stringify(depUrl)};\nconst ns = M.default ?? M;\nexport default ns;\n` + (names.length ? `export const { ${names.join(", ")} } = ns;\n` : ""));
|
|
@@ -1068,12 +2681,12 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
|
|
|
1068
2681
|
handler(html, ctx) {
|
|
1069
2682
|
const browserHash = ctx.server?.environments.client.depsOptimizer?.metadata.browserHash;
|
|
1070
2683
|
if (!browserHash) return;
|
|
1071
|
-
const shimPrefix = withBase(base, SHIM_PATH);
|
|
2684
|
+
const shimPrefix = withBase$1(base, SHIM_PATH);
|
|
1072
2685
|
const imports = Object.fromEntries(REACT_DEPS.map((id) => [id, `${shimPrefix}${id}.js?v=${browserHash}`]));
|
|
1073
2686
|
let dynamicBaseScript = "";
|
|
1074
2687
|
if (vendorActive) {
|
|
1075
|
-
for (const [spec, url] of Object.entries(vendor.imports)) imports[spec] = withBase(base, url);
|
|
1076
|
-
if (vendor.imports["@powerhousedao/connect"]) imports["ph-bundled-packages-virtual"] = withBase(base, BUNDLED_PACKAGES_DEV_URL);
|
|
2688
|
+
for (const [spec, url] of Object.entries(vendor.imports)) imports[spec] = withBase$1(base, url);
|
|
2689
|
+
if (vendor.imports["@powerhousedao/connect"]) imports["ph-bundled-packages-virtual"] = withBase$1(base, BUNDLED_PACKAGES_DEV_URL);
|
|
1077
2690
|
dynamicBaseScript = `<script>globalThis.__PH_DYNAMIC_BASE__=${JSON.stringify(base)};<\/script>\n`;
|
|
1078
2691
|
}
|
|
1079
2692
|
return html.replace(/<script type="importmap">[\s\S]*?<\/script>/, `${dynamicBaseScript}<script type="importmap">${JSON.stringify({ imports }, null, 2)}<\/script>`);
|
|
@@ -1118,7 +2731,7 @@ function connectFaviconPlugin(opts = {}) {
|
|
|
1118
2731
|
res.end(readFileSync(resolved.id));
|
|
1119
2732
|
}).catch(() => next());
|
|
1120
2733
|
};
|
|
1121
|
-
const paths = new Set([faviconRoute, "/icon.ico"]);
|
|
2734
|
+
const paths = /* @__PURE__ */ new Set([faviconRoute, "/icon.ico"]);
|
|
1122
2735
|
for (const path of paths) server.middlewares.use(path, handler);
|
|
1123
2736
|
},
|
|
1124
2737
|
async generateBundle(_options, bundle) {
|
|
@@ -1156,21 +2769,44 @@ function readProjectPackageInfo(projectRoot) {
|
|
|
1156
2769
|
return null;
|
|
1157
2770
|
}
|
|
1158
2771
|
}
|
|
2772
|
+
/** `html` with its `<title>` text set to `appName`, when one is configured. */
|
|
2773
|
+
function withAppTitle(html, appName) {
|
|
2774
|
+
if (!appName) return html;
|
|
2775
|
+
const escaped = appName.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
2776
|
+
return html.replace(/<title>[^<]*<\/title>/, () => `<title>${escaped}</title>`);
|
|
2777
|
+
}
|
|
2778
|
+
/** `api.connect`: the connect config the app is served, for plugins that render
|
|
2779
|
+
* ahead of it; `api.favicon`: its `branding.favicon`, which it leaves out. */
|
|
1159
2780
|
function phConfigPlugin(options) {
|
|
1160
2781
|
const localPackage = readProjectPackageInfo(options.projectRoot ?? process.cwd());
|
|
1161
|
-
const
|
|
2782
|
+
const sourceSettings = {
|
|
2783
|
+
connect: options.connect,
|
|
2784
|
+
workflows: options.workflows
|
|
2785
|
+
};
|
|
2786
|
+
const conflict = workflowsSettingConflict(sourceSettings);
|
|
2787
|
+
if (conflict) console.warn(`[powerhouse] ${conflict}`);
|
|
2788
|
+
const withDefaults = resolveSourceConnect(sourceSettings);
|
|
1162
2789
|
const mergedConnect = options.cliConnectOverride ? deepMerge(withDefaults, options.cliConnectOverride) : withDefaults;
|
|
1163
|
-
const
|
|
2790
|
+
const { favicon, ...branding } = mergedConnect.branding ?? {};
|
|
2791
|
+
const source = {
|
|
1164
2792
|
packages: options.packages,
|
|
1165
2793
|
packageRegistryUrl: options.packageRegistryUrl,
|
|
1166
|
-
connect: mergedConnect
|
|
1167
|
-
|
|
2794
|
+
connect: mergedConnect.branding ? {
|
|
2795
|
+
...mergedConnect,
|
|
2796
|
+
branding
|
|
2797
|
+
} : mergedConnect
|
|
2798
|
+
};
|
|
2799
|
+
const runtimeConfig = buildRuntimeConfig(source, localPackage);
|
|
1168
2800
|
const content = JSON.stringify({
|
|
1169
2801
|
$schema: RUNTIME_CONFIG_SCHEMA_URL,
|
|
1170
2802
|
...runtimeConfig
|
|
1171
2803
|
}, null, 2);
|
|
1172
2804
|
return {
|
|
1173
2805
|
name: "vite-plugin-ph-config",
|
|
2806
|
+
api: {
|
|
2807
|
+
connect: runtimeConfig.connect,
|
|
2808
|
+
favicon: favicon ?? void 0
|
|
2809
|
+
},
|
|
1174
2810
|
configureServer(server) {
|
|
1175
2811
|
server.middlewares.use((req, res, next) => {
|
|
1176
2812
|
if (req.url?.endsWith("/powerhouse.config.json")) {
|
|
@@ -1191,6 +2827,9 @@ function phConfigPlugin(options) {
|
|
|
1191
2827
|
});
|
|
1192
2828
|
}
|
|
1193
2829
|
},
|
|
2830
|
+
transformIndexHtml(html) {
|
|
2831
|
+
return withAppTitle(html, runtimeConfig.connect.branding?.appName);
|
|
2832
|
+
},
|
|
1194
2833
|
generateBundle() {
|
|
1195
2834
|
this.emitFile({
|
|
1196
2835
|
type: "asset",
|
|
@@ -1217,11 +2856,13 @@ function toPwaContribution(manifest, fallbackLabel, onWarn) {
|
|
|
1217
2856
|
if (!isPlainObject(manifest)) return null;
|
|
1218
2857
|
const label = typeof manifest.name === "string" && manifest.name ? manifest.name : fallbackLabel;
|
|
1219
2858
|
let config = {};
|
|
1220
|
-
if (manifest.pwa !== void 0)
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
2859
|
+
if (manifest.pwa !== void 0) {
|
|
2860
|
+
if (!isPlainObject(manifest.pwa)) onWarn(`PWA config: ${label} declares a non-object 'pwa' field in its manifest; ignored.`);
|
|
2861
|
+
else {
|
|
2862
|
+
const parsed = PwaConfigSchema.safeParse(manifest.pwa);
|
|
2863
|
+
if (!parsed.success) onWarn(`PWA config: ${label}'s pwa fragment is invalid; ignored. ${formatZodIssues(parsed.error)}`);
|
|
2864
|
+
else config = parsed.data;
|
|
2865
|
+
}
|
|
1225
2866
|
}
|
|
1226
2867
|
config = withInferredCategory(config, manifest.category);
|
|
1227
2868
|
if (Object.keys(config).length === 0) return null;
|
|
@@ -1330,7 +2971,8 @@ function collectProjectPwaContribution(options) {
|
|
|
1330
2971
|
}
|
|
1331
2972
|
if (!isPlainObject(manifest)) return null;
|
|
1332
2973
|
const label = typeof manifest.name === "string" && manifest.name ? manifest.name : "project manifest";
|
|
1333
|
-
const
|
|
2974
|
+
const config = manifest.pwa === void 0 ? {} : parsePwaConfigStrict(manifest.pwa, `pwa in ${manifestPath}`);
|
|
2975
|
+
const withCategory = withInferredCategory(config, manifest.category);
|
|
1334
2976
|
if (Object.keys(withCategory).length === 0) return null;
|
|
1335
2977
|
return {
|
|
1336
2978
|
source: label,
|
|
@@ -1471,12 +3113,13 @@ const BASE_MANIFEST = {
|
|
|
1471
3113
|
* declarative runtimeCaching option.
|
|
1472
3114
|
*/
|
|
1473
3115
|
const BASE_PRECACHE = {
|
|
1474
|
-
maximumFileSizeToCacheInBytes:
|
|
1475
|
-
globPatterns: ["**/*.{js,css,html,wasm,data,ico,png,svg,webp,woff,woff2}"],
|
|
3116
|
+
maximumFileSizeToCacheInBytes: 16777216,
|
|
3117
|
+
globPatterns: ["**/*.{js,css,html,wasm,data,ico,png,svg,webp,woff,woff2}", "__reactor_worker__/**/*.json"],
|
|
1476
3118
|
globIgnores: [
|
|
1477
3119
|
"**/powerhouse.config.json",
|
|
1478
3120
|
"**/*.map",
|
|
1479
|
-
"index.html"
|
|
3121
|
+
"index.html",
|
|
3122
|
+
"**/*.gz"
|
|
1480
3123
|
]
|
|
1481
3124
|
};
|
|
1482
3125
|
const SW_FILENAME = "service-worker.ts";
|
|
@@ -1613,17 +3256,40 @@ function resolveReactEntries(dirname$1) {
|
|
|
1613
3256
|
}
|
|
1614
3257
|
return out;
|
|
1615
3258
|
}
|
|
3259
|
+
function reactImportMap(base, files) {
|
|
3260
|
+
const map = {};
|
|
3261
|
+
for (const [spec, file] of Object.entries(files)) {
|
|
3262
|
+
map[spec] = `${base}${REACT_URL_DIR}/${file}`;
|
|
3263
|
+
if (spec.includes("/")) map[`${spec}.js`] = map[spec];
|
|
3264
|
+
}
|
|
3265
|
+
return map;
|
|
3266
|
+
}
|
|
1616
3267
|
function reactSelfHostPlugin(options) {
|
|
1617
3268
|
const entries = resolveReactEntries(options.dirname);
|
|
1618
3269
|
let absOutDir = resolve(options.dirname, "dist");
|
|
3270
|
+
let base = "/";
|
|
3271
|
+
let staging;
|
|
3272
|
+
let files = {};
|
|
1619
3273
|
let importMap = {};
|
|
1620
3274
|
return {
|
|
1621
3275
|
name: "ph-react-self-host",
|
|
1622
3276
|
apply: "build",
|
|
1623
3277
|
configResolved(config) {
|
|
1624
3278
|
absOutDir = resolve(config.root, config.build.outDir);
|
|
1625
|
-
|
|
1626
|
-
|
|
3279
|
+
base = config.base;
|
|
3280
|
+
},
|
|
3281
|
+
async buildStart() {
|
|
3282
|
+
files = {};
|
|
3283
|
+
importMap = {};
|
|
3284
|
+
if (!Object.keys(entries).length) return;
|
|
3285
|
+
const stagingParent = join(options.dirname, "node_modules");
|
|
3286
|
+
staging = mkdtempSync(join(existsSync(stagingParent) ? stagingParent : options.dirname, ".ph-react-self-host-"));
|
|
3287
|
+
const { ok, stderr } = await runReactBuild(options.dirname, staging, entries, options.dev ? "development" : "production");
|
|
3288
|
+
if (!ok) this.error(`react self-host build failed${stderr.trim() ? `:\n${stderr.trim()}` : ""}`);
|
|
3289
|
+
const manifest = join(staging, FILES_MANIFEST);
|
|
3290
|
+
files = JSON.parse(readFileSync(manifest, "utf8"));
|
|
3291
|
+
rmSync(manifest, { force: true });
|
|
3292
|
+
importMap = reactImportMap(base, files);
|
|
1627
3293
|
},
|
|
1628
3294
|
transformIndexHtml() {
|
|
1629
3295
|
if (!Object.keys(importMap).length) return;
|
|
@@ -1634,13 +3300,27 @@ function reactSelfHostPlugin(options) {
|
|
|
1634
3300
|
injectTo: "head-prepend"
|
|
1635
3301
|
}];
|
|
1636
3302
|
},
|
|
1637
|
-
|
|
1638
|
-
if (!
|
|
1639
|
-
const
|
|
1640
|
-
|
|
3303
|
+
closeBundle() {
|
|
3304
|
+
if (!staging) return;
|
|
3305
|
+
const dest = join(absOutDir, REACT_URL_DIR);
|
|
3306
|
+
rmSync(dest, {
|
|
3307
|
+
recursive: true,
|
|
3308
|
+
force: true
|
|
3309
|
+
});
|
|
3310
|
+
mkdirSync(absOutDir, { recursive: true });
|
|
3311
|
+
cpSync(staging, dest, { recursive: true });
|
|
3312
|
+
chmodSync(dest, 493);
|
|
3313
|
+
rmSync(staging, {
|
|
3314
|
+
recursive: true,
|
|
3315
|
+
force: true
|
|
3316
|
+
});
|
|
3317
|
+
staging = void 0;
|
|
3318
|
+
const missing = Object.entries(files).filter(([, file]) => !existsSync(join(dest, file)));
|
|
3319
|
+
if (missing.length) this.error(`react self-host: import map entries have no file in ${dest}:\n` + missing.map(([spec, file]) => ` ${spec} -> ${file}`).join("\n"));
|
|
1641
3320
|
}
|
|
1642
3321
|
};
|
|
1643
3322
|
}
|
|
3323
|
+
const FILES_MANIFEST = "files.json";
|
|
1644
3324
|
function runReactBuild(dirname, outDir, entries, nodeEnv) {
|
|
1645
3325
|
mkdirSync(outDir, { recursive: true });
|
|
1646
3326
|
const workerPath = join(outDir, "build-worker.mjs");
|
|
@@ -1715,7 +3395,7 @@ for (const [spec, file] of Object.entries(entries)) {
|
|
|
1715
3395
|
input[spec] = entryFile;
|
|
1716
3396
|
}
|
|
1717
3397
|
try {
|
|
1718
|
-
await build({
|
|
3398
|
+
const result = await build({
|
|
1719
3399
|
root: dirname, configFile: false, logLevel: 'error',
|
|
1720
3400
|
base: './', publicDir: false,
|
|
1721
3401
|
define: { 'process.env.NODE_ENV': JSON.stringify(nodeEnv) },
|
|
@@ -1724,11 +3404,18 @@ try {
|
|
|
1724
3404
|
outDir, emptyOutDir: false, minify: nodeEnv === 'production', target: 'esnext',
|
|
1725
3405
|
rollupOptions: {
|
|
1726
3406
|
input, preserveEntrySignatures: 'strict',
|
|
1727
|
-
output: { format: 'es', entryFileNames: '[name].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]' },
|
|
3407
|
+
output: { format: 'es', entryFileNames: '[name]-[hash].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]' },
|
|
1728
3408
|
},
|
|
1729
3409
|
},
|
|
1730
3410
|
});
|
|
1731
3411
|
rmSync(srcDir, { recursive: true, force: true });
|
|
3412
|
+
const files = {};
|
|
3413
|
+
for (const out of Array.isArray(result) ? result : [result]) {
|
|
3414
|
+
for (const chunk of out?.output ?? []) {
|
|
3415
|
+
if (chunk.type === 'chunk' && chunk.isEntry) files[chunk.name] = chunk.fileName;
|
|
3416
|
+
}
|
|
3417
|
+
}
|
|
3418
|
+
writeFileSync(join(outDir, 'files.json'), JSON.stringify(files));
|
|
1732
3419
|
// Force exit: rolldown can leave native worker threads alive that keep the
|
|
1733
3420
|
// event loop open, hanging the parent's spawn() promise indefinitely.
|
|
1734
3421
|
process.exit(0);
|
|
@@ -1738,6 +3425,91 @@ try {
|
|
|
1738
3425
|
}
|
|
1739
3426
|
`;
|
|
1740
3427
|
//#endregion
|
|
3428
|
+
//#region connect-utils/vite-plugins/reactor-worker-dev.ts
|
|
3429
|
+
const DEV_BUNDLE_DIR = "node_modules/.ph-reactor-worker";
|
|
3430
|
+
function withBase(base, p) {
|
|
3431
|
+
return `${base}${p}`.replace(/\/{2,}/g, "/");
|
|
3432
|
+
}
|
|
3433
|
+
/**
|
|
3434
|
+
* Dev-only: serve Connect's reactor SharedWorker bundle under
|
|
3435
|
+
* `<base>__reactor_worker__/`, building it lazily on first request.
|
|
3436
|
+
*
|
|
3437
|
+
* The dev server serves Connect from its prebuilt dist in node_modules, where
|
|
3438
|
+
* `dist/reactor.worker.js` is a library artifact no worker can resolve. The
|
|
3439
|
+
* tab GETs `worker-meta.json` here (JSON, no-cache, written by
|
|
3440
|
+
* `prebuildReactorWorker`) to find the bundle and fold its `sourceDigest`
|
|
3441
|
+
* into its version fingerprint; without this plugin that GET fails and the
|
|
3442
|
+
* worker feature reports itself unavailable instead of dying opaquely.
|
|
3443
|
+
*
|
|
3444
|
+
* Lazy because it is a full `vite build` of the reactor + PGlite graph. The
|
|
3445
|
+
* result is cached in node_modules/.ph-reactor-worker until the installed
|
|
3446
|
+
* Connect, its upstream dists, or builder-tools change (`computeSourceDigest`).
|
|
3447
|
+
*/
|
|
3448
|
+
function reactorWorkerDevPlugin(projectRoot) {
|
|
3449
|
+
let base = "/";
|
|
3450
|
+
let building = null;
|
|
3451
|
+
const ensureBuilt = () => {
|
|
3452
|
+
building ??= (async () => {
|
|
3453
|
+
const errorRef = {};
|
|
3454
|
+
const built = await prebuildReactorWorker({
|
|
3455
|
+
dirname: projectRoot,
|
|
3456
|
+
outDir: path.join(projectRoot, DEV_BUNDLE_DIR),
|
|
3457
|
+
nodeEnv: "development",
|
|
3458
|
+
errorRef
|
|
3459
|
+
});
|
|
3460
|
+
if (!built) {
|
|
3461
|
+
console.warn(`[connect] reactor worker bundle build failed${errorRef.message ? `: ${errorRef.message}` : ""}`);
|
|
3462
|
+
building = null;
|
|
3463
|
+
}
|
|
3464
|
+
return built;
|
|
3465
|
+
})();
|
|
3466
|
+
return building;
|
|
3467
|
+
};
|
|
3468
|
+
return {
|
|
3469
|
+
name: "ph-reactor-worker-dev",
|
|
3470
|
+
apply: "serve",
|
|
3471
|
+
configResolved(config) {
|
|
3472
|
+
base = config.base;
|
|
3473
|
+
},
|
|
3474
|
+
configureServer(server) {
|
|
3475
|
+
const prefixes = [withBase(base, REACTOR_WORKER_URL_PREFIX), REACTOR_WORKER_URL_PREFIX];
|
|
3476
|
+
server.middlewares.use((req, res, next) => {
|
|
3477
|
+
const url = (req.url ?? "").split("?")[0];
|
|
3478
|
+
const prefix = prefixes.find((p) => url.startsWith(p));
|
|
3479
|
+
if (!prefix) return next();
|
|
3480
|
+
const name = url.slice(prefix.length).replace(/^\/+/, "");
|
|
3481
|
+
if (!name) return next();
|
|
3482
|
+
(async () => {
|
|
3483
|
+
const built = await ensureBuilt();
|
|
3484
|
+
if (!built) {
|
|
3485
|
+
res.statusCode = 503;
|
|
3486
|
+
res.setHeader("Content-Type", "text/plain");
|
|
3487
|
+
res.end("reactor worker bundle unavailable (build failed; see server log)");
|
|
3488
|
+
return;
|
|
3489
|
+
}
|
|
3490
|
+
const file = path.join(built.outDir, name);
|
|
3491
|
+
const rel = path.relative(built.outDir, file);
|
|
3492
|
+
if (rel.startsWith("..") || path.isAbsolute(rel)) {
|
|
3493
|
+
next();
|
|
3494
|
+
return;
|
|
3495
|
+
}
|
|
3496
|
+
const stream = createReadStream(file);
|
|
3497
|
+
stream.on("error", () => {
|
|
3498
|
+
if (!res.headersSent) next();
|
|
3499
|
+
});
|
|
3500
|
+
stream.once("open", () => {
|
|
3501
|
+
const ext = file.slice(file.lastIndexOf("."));
|
|
3502
|
+
res.setHeader("Content-Type", REACTOR_WORKER_MIME[ext] ?? "text/javascript");
|
|
3503
|
+
const hashed = !name.startsWith("reactor.worker.js") && !name.endsWith(".json");
|
|
3504
|
+
res.setHeader("Cache-Control", hashed ? "public, max-age=31536000, immutable" : "no-cache");
|
|
3505
|
+
stream.pipe(res);
|
|
3506
|
+
});
|
|
3507
|
+
})();
|
|
3508
|
+
});
|
|
3509
|
+
}
|
|
3510
|
+
};
|
|
3511
|
+
}
|
|
3512
|
+
//#endregion
|
|
1741
3513
|
//#region connect-utils/vite-plugins/theme-boot.ts
|
|
1742
3514
|
/**
|
|
1743
3515
|
* Marker attribute on the injected script. Serve-time injectors (e.g. the
|
|
@@ -1752,7 +3524,7 @@ const THEME_BOOT_MARKER = "data-ph-theme-boot";
|
|
|
1752
3524
|
* Keep semantically identical to the runtime store in
|
|
1753
3525
|
* `@powerhousedao/reactor-browser` (hooks/theme.ts).
|
|
1754
3526
|
*/
|
|
1755
|
-
const THEME_BOOT_SCRIPT = "(function(){try{var p=new URLSearchParams(location.search).get('theme');if(p==='dark'||p==='light')localStorage.setItem('ph:theme',p);var s=localStorage.getItem('ph:theme');var d=s==='dark'||((!s||s==='system')&&
|
|
3527
|
+
const THEME_BOOT_SCRIPT = "(function(){try{var p=new URLSearchParams(location.search).get('theme');if(p==='dark'||p==='light')localStorage.setItem('ph:theme',p);var s=localStorage.getItem('ph:theme');var m=matchMedia('(prefers-color-scheme: dark)');var d=s==='dark'||((!s||s==='system')&&m.matches);document.documentElement.classList.toggle('dark',d);if(!s||s==='system'){var f=function(){var t=localStorage.getItem('ph:theme');if(!t||t==='system')document.documentElement.classList.toggle('dark',m.matches);};m.addEventListener('change',f);requestAnimationFrame(f);}}catch(e){}})();";
|
|
1756
3528
|
/**
|
|
1757
3529
|
* Injects the theme boot script at the top of `<head>` of every emitted
|
|
1758
3530
|
* index.html, so built Connect apps render the stored theme from first paint
|
|
@@ -1776,6 +3548,48 @@ function connectThemeBootPlugin() {
|
|
|
1776
3548
|
};
|
|
1777
3549
|
}
|
|
1778
3550
|
//#endregion
|
|
3551
|
+
//#region connect-utils/vite-plugins/vendor-import-map.ts
|
|
3552
|
+
function extractImports(raw) {
|
|
3553
|
+
if (typeof raw !== "object" || raw === null) return {};
|
|
3554
|
+
const imports = "imports" in raw ? raw.imports : void 0;
|
|
3555
|
+
if (typeof imports !== "object" || imports === null) return {};
|
|
3556
|
+
const out = {};
|
|
3557
|
+
for (const [key, value] of Object.entries(imports)) if (typeof value === "string") out[key] = value;
|
|
3558
|
+
return out;
|
|
3559
|
+
}
|
|
3560
|
+
function parseImportMap(raw) {
|
|
3561
|
+
try {
|
|
3562
|
+
return extractImports(JSON.parse(raw));
|
|
3563
|
+
} catch {
|
|
3564
|
+
return {};
|
|
3565
|
+
}
|
|
3566
|
+
}
|
|
3567
|
+
const INLINE_IMPORTMAP = /<script type="importmap">([\s\S]*?)<\/script>/;
|
|
3568
|
+
function vendorImportMapPlugin(options) {
|
|
3569
|
+
const vendorEntries = Object.keys(options.imports).length;
|
|
3570
|
+
return {
|
|
3571
|
+
name: "ph-vendor-import-map",
|
|
3572
|
+
apply: "build",
|
|
3573
|
+
transformIndexHtml(html) {
|
|
3574
|
+
if (!vendorEntries) return;
|
|
3575
|
+
const match = INLINE_IMPORTMAP.exec(html);
|
|
3576
|
+
if (match) {
|
|
3577
|
+
const merged = { imports: {
|
|
3578
|
+
...parseImportMap(match[1]),
|
|
3579
|
+
...options.imports
|
|
3580
|
+
} };
|
|
3581
|
+
return html.replace(INLINE_IMPORTMAP, `<script type="importmap">${JSON.stringify(merged)}<\/script>`);
|
|
3582
|
+
}
|
|
3583
|
+
return [{
|
|
3584
|
+
tag: "script",
|
|
3585
|
+
attrs: { type: "importmap" },
|
|
3586
|
+
children: JSON.stringify({ imports: options.imports }),
|
|
3587
|
+
injectTo: "head-prepend"
|
|
3588
|
+
}];
|
|
3589
|
+
}
|
|
3590
|
+
};
|
|
3591
|
+
}
|
|
3592
|
+
//#endregion
|
|
1779
3593
|
//#region connect-utils/vite-config.ts
|
|
1780
3594
|
function getConnectHtmlTags(options = {}) {
|
|
1781
3595
|
const { registryUrl, injectTo = "head" } = options;
|
|
@@ -1896,20 +3710,30 @@ function getLocalPackageNamesFromPowerhouseConfig({ packages }) {
|
|
|
1896
3710
|
}
|
|
1897
3711
|
function getConnectBaseViteConfig(options) {
|
|
1898
3712
|
const mode = options.mode;
|
|
1899
|
-
const
|
|
3713
|
+
const envDir = options.envDir ?? options.dirname;
|
|
3714
|
+
const fileEnv = loadEnv(mode, envDir, "PH_");
|
|
1900
3715
|
const env = loadConnectEnv({
|
|
1901
3716
|
processEnv: process.env,
|
|
1902
3717
|
fileEnv
|
|
1903
3718
|
});
|
|
1904
3719
|
setConnectEnv(env);
|
|
1905
3720
|
const phConfigPath = join(options.dirname, "powerhouse.config.json");
|
|
1906
|
-
const phConfig = options.powerhouseConfig ?? getConfig(phConfigPath);
|
|
3721
|
+
const phConfig = options.powerhouseConfig ?? getConfig$1(phConfigPath);
|
|
1907
3722
|
const packagesFromConfig = phConfig.packages ?? [];
|
|
1908
3723
|
const localPackagesFromConfig = getLocalPackageNamesFromPowerhouseConfig(phConfig);
|
|
1909
3724
|
const phPackagesStr = env.PH_PACKAGES;
|
|
1910
3725
|
const phPackages = (phPackagesStr ? parsePackagesEnvOverride(phPackagesStr) : void 0) ?? packagesFromConfig;
|
|
1911
3726
|
const phPackageRegistryUrl = options.cliPackageRegistryUrl ?? phConfig.packageRegistryUrl ?? null;
|
|
1912
3727
|
const connectBasePath = options.cliConnectOverride?.app?.basePath ?? phConfig.connect?.app?.basePath;
|
|
3728
|
+
const configPlugin = phConfigPlugin({
|
|
3729
|
+
packages: phPackages,
|
|
3730
|
+
projectRoot: options.dirname,
|
|
3731
|
+
connect: phConfig.connect,
|
|
3732
|
+
workflows: phConfig.workflows,
|
|
3733
|
+
packageRegistryUrl: phPackageRegistryUrl ?? void 0,
|
|
3734
|
+
cliConnectOverride: options.cliConnectOverride
|
|
3735
|
+
});
|
|
3736
|
+
const servedConnect = configPlugin.api.connect;
|
|
1913
3737
|
const offlineEnabled = options.cliConnectOverride?.app?.offline ?? phConfig.connect?.app?.offline ?? true;
|
|
1914
3738
|
const authToken = env.PH_SENTRY_AUTH_TOKEN;
|
|
1915
3739
|
const org = env.PH_SENTRY_ORG;
|
|
@@ -1968,9 +3792,10 @@ function getConnectBaseViteConfig(options) {
|
|
|
1968
3792
|
});
|
|
1969
3793
|
const projectContribution = collectProjectPwaContribution({ projectRoot: options.dirname });
|
|
1970
3794
|
if (projectContribution) contributions.push(projectContribution);
|
|
3795
|
+
const mergedPwa = mergePwaConfig(contributions, projectPwa, pwaWarn);
|
|
1971
3796
|
return connectPwaPlugins({
|
|
1972
3797
|
offlineEnabled,
|
|
1973
|
-
pwa:
|
|
3798
|
+
pwa: mergedPwa
|
|
1974
3799
|
});
|
|
1975
3800
|
})();
|
|
1976
3801
|
const reactExternal = [
|
|
@@ -1990,6 +3815,9 @@ function getConnectBaseViteConfig(options) {
|
|
|
1990
3815
|
return null;
|
|
1991
3816
|
}
|
|
1992
3817
|
}).filter((p) => p !== null);
|
|
3818
|
+
const routesDir = resolveConnectRoutesDir(options.dirname, options.routes) ?? false;
|
|
3819
|
+
const routes = connectRoutes(options.dirname, routesDir);
|
|
3820
|
+
const hostStylesheet = hostStylesheetPath(options.dirname, routesDir);
|
|
1993
3821
|
return {
|
|
1994
3822
|
configFile: false,
|
|
1995
3823
|
mode,
|
|
@@ -1999,12 +3827,19 @@ function getConnectBaseViteConfig(options) {
|
|
|
1999
3827
|
fs: { allow: [searchForWorkspaceRoot(options.dirname), ...linkedRoots] }
|
|
2000
3828
|
},
|
|
2001
3829
|
resolve: {
|
|
2002
|
-
|
|
3830
|
+
alias: routes.aliases,
|
|
3831
|
+
dedupe: [
|
|
3832
|
+
"react",
|
|
3833
|
+
"react-dom",
|
|
3834
|
+
...routes.dedupe
|
|
3835
|
+
],
|
|
2003
3836
|
tsconfigPaths: true
|
|
2004
3837
|
},
|
|
2005
3838
|
define: {
|
|
2006
3839
|
PH_CONNECT_SENTRY_RELEASE: JSON.stringify(release || "unknown"),
|
|
2007
|
-
PH_CONNECT_BUILD_HASH: JSON.stringify(buildHash)
|
|
3840
|
+
PH_CONNECT_BUILD_HASH: JSON.stringify(buildHash),
|
|
3841
|
+
...options.vendor?.sharedDeps && mode === "production" ? { PH_CONNECT_SHARED_DEPS_URL: JSON.stringify(options.vendor.sharedDeps) } : {},
|
|
3842
|
+
...options.reactorWorkerVersion ? { PH_CONNECT_REACTOR_WORKER_VERSION: JSON.stringify(options.reactorWorkerVersion) } : {}
|
|
2008
3843
|
},
|
|
2009
3844
|
customLogger,
|
|
2010
3845
|
envPrefix: ["PH_CONNECT_"],
|
|
@@ -2019,26 +3854,31 @@ function getConnectBaseViteConfig(options) {
|
|
|
2019
3854
|
exclude: ["@electric-sql/pglite", "@electric-sql/pglite-tools"]
|
|
2020
3855
|
},
|
|
2021
3856
|
plugins: [
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
projectRoot: options.dirname,
|
|
2025
|
-
connect: phConfig.connect,
|
|
2026
|
-
packageRegistryUrl: phPackageRegistryUrl ?? void 0,
|
|
2027
|
-
cliConnectOverride: options.cliConnectOverride
|
|
2028
|
-
}),
|
|
3857
|
+
configPlugin,
|
|
3858
|
+
hostStylesheetPlugin(options.dirname, hostStylesheet),
|
|
2029
3859
|
phBundledPackagesPlugin({
|
|
2030
3860
|
packages: localPackagesFromConfig,
|
|
2031
3861
|
projectRoot: options.dirname
|
|
2032
3862
|
}),
|
|
2033
|
-
devReactImportmapPlugin(options.dirname),
|
|
3863
|
+
devReactImportmapPlugin(options.dirname, routesDir),
|
|
3864
|
+
reactorWorkerDevPlugin(options.dirname),
|
|
3865
|
+
...routes.plugins,
|
|
2034
3866
|
...plugins,
|
|
2035
|
-
esmExternalRequirePlugin({ external: reactExternal }),
|
|
3867
|
+
esmExternalRequirePlugin({ external: [...reactExternal, ...options.vendor && mode === "production" ? Object.keys(options.vendor.imports) : []] }),
|
|
2036
3868
|
reactSelfHostPlugin({
|
|
2037
3869
|
dirname: options.dirname,
|
|
2038
3870
|
dev: mode !== "production" || isDebug
|
|
2039
3871
|
}),
|
|
2040
|
-
|
|
3872
|
+
...options.vendor && mode === "production" ? [vendorImportMapPlugin({ imports: options.vendor.imports })] : [],
|
|
3873
|
+
connectFaviconPlugin({ faviconPath: options.favicon ?? configPlugin.api.favicon }),
|
|
2041
3874
|
connectThemeBootPlugin(),
|
|
3875
|
+
connectAppShellPlugin(options.dirname, {
|
|
3876
|
+
composition: servedConnect.composition,
|
|
3877
|
+
appName: servedConnect.branding?.appName,
|
|
3878
|
+
routeAliases: routesDir ? routes.aliases : void 0,
|
|
3879
|
+
routesDir: routesDir || void 0,
|
|
3880
|
+
hostStylesheet
|
|
3881
|
+
}),
|
|
2042
3882
|
connectBuildHashPlugin(buildHash),
|
|
2043
3883
|
...options.dynamicBase ? [connectDynamicBasePlugin()] : [],
|
|
2044
3884
|
pwaPlugins
|
|
@@ -2047,10 +3887,16 @@ function getConnectBaseViteConfig(options) {
|
|
|
2047
3887
|
format: "es",
|
|
2048
3888
|
...options.dynamicBase ? { plugins: () => [connectDynamicBasePlugin({ forWorker: true })] } : {}
|
|
2049
3889
|
},
|
|
2050
|
-
build: {
|
|
3890
|
+
build: {
|
|
3891
|
+
sourcemap: true,
|
|
3892
|
+
rolldownOptions: {
|
|
3893
|
+
shimMissingExports: true,
|
|
3894
|
+
output: { codeSplitting: { groups: connectRouterChunkGroups(routesDir) } }
|
|
3895
|
+
}
|
|
3896
|
+
}
|
|
2051
3897
|
};
|
|
2052
3898
|
}
|
|
2053
3899
|
//#endregion
|
|
2054
|
-
export { BUILD_HASH_FILE, DEFAULT_CONNECT_OUTDIR, DEFAULT_VENDOR_INCLUDE, DYNAMIC_BASE_PLACEHOLDER, EXTERNAL_PACKAGES_IMPORT, IMPORT_SCRIPT_FILE, LOCAL_PACKAGE_ID, PH_DIR_NAME, RUNTIME_CONFIG_SCHEMA_ID, RUNTIME_CONFIG_SCHEMA_URL, THEME_BOOT_MARKER, VENDOR_EXTERNAL, VENDOR_URL_PREFIX, appendToHtmlHead, backupIndexHtml, buildHashFromBuildOptions, computeBuildHash, connectBuildHashPlugin, connectDynamicBasePlugin, connectThemeBootPlugin, copyConnect, ensureNodeVersion, escapeForRegExp, getConnectBaseViteConfig, getConnectHtmlTags, makeImportScriptFromPackages, phConfigPlugin, prebuildConnectVendor, prependToHtmlHead, readJsonFile, removeBase64EnvValues, resolveConnectBundle, resolveConnectPackageJson, resolveConnectPublicDir, resolvePackage, resolveViteConfigPath, runShellScriptPlugin, runTsc, runtimeConfigSchema, stripVersionFromPackage };
|
|
3900
|
+
export { APP_LAYOUT, APP_SHELLS_FILE, APP_SHELL_MARKER, BOOT_RECOVER_KEY, BOOT_RECOVER_MARKER, BOOT_RECOVER_SCRIPT, BUILDER_TOOLS_VERSION, BUILD_HASH_FILE, CONNECT_ROUTES_GEN, CONNECT_ROUTES_SPECIFIER, CORE_ROUTE_TREE_SPECIFIER, DEFAULT_APP_NAME, DEFAULT_CONNECT_OUTDIR, DEFAULT_VENDOR_INCLUDE, DYNAMIC_BASE_PLACEHOLDER, EXTERNAL_PACKAGES_IMPORT, HOST_ROUTES_DIR, IMPORT_SCRIPT_FILE, LOCAL_PACKAGE_ID, LOCK_STALE_MS, PACKAGE_ROUTES_MODULE, PH_DIR_NAME, REACTOR_WORKER_ENTRY, REACTOR_WORKER_MIME, REACTOR_WORKER_URL_PREFIX, ROUTE_TREE_SPECIFIER, RUNTIME_CONFIG_SCHEMA_ID, RUNTIME_CONFIG_SCHEMA_URL, SHELL_PLUGINS_FILE, THEME_BOOT_MARKER, VENDOR_EXTERNAL, VENDOR_SKIP_SUBPATHS, VENDOR_URL_PREFIX, WORKER_PACKAGES_MANIFEST, acquireLock, appShellVariant, appShellVariantOf, appendToHtmlHead, backupIndexHtml, buildHashFromBuildOptions, computeBuildHash, computeSourceDigest, connectAppShellPlugin, connectBuildHashPlugin, connectDynamicBasePlugin, connectRouterChunkGroups, connectRoutes, connectRoutesDirOf, connectRoutesGeneratorConfig, connectRoutesTreeOf, connectThemeBootPlugin, copyConnect, directoryContentDigest, distDirFingerprint, ensureNodeVersion, escapeForRegExp, findBundleSpecifierOffenders, findDisallowedSpecifiers, findPackageRoot, findWorkerUnsafeMarkers, generateConnectRoutes, getConnectBaseViteConfig, getConnectHtmlTags, hostStylesheetPath, hostStylesheetPlugin, injectAppShell, linkedBuildStamp, makeImportScriptFromPackages, missingVendorEntries, overriddenConnectRoutes, ownProjectPackage, phConfigPlugin, prebuildConnectVendor, prebuildReactorWorker, prebuildWorkerPackages, prependToHtmlHead, publishDirAtomic, readAppShell, readAppShells, readJsonFile, readShellPlugins, readShellPluginsIn, rebaseShellLinks, relativeCssUrls, releaseLock, removeBase64EnvValues, resolveConnectBundle, resolveConnectPackageJson, resolveConnectPublicDir, resolveConnectRoutesDir, resolveOwnDeps, resolveOwnPackageVersion, resolvePackage, resolveReactorWorkerSource, resolveVersionDigest, resolveViteConfigPath, resolveWorkspacePackageDir, routeIdOf, runShellScriptPlugin, runTsc, runWorkerBuildEntries, runtimeConfigSchema, stripVersionFromPackage, swapAppShell, syncConnectRoutes, upstreamWorkerPackages, vendorImportMapPlugin, vendorRelativePath, withAppTitle, withHostStylesheet, withShellAppName, withVendorBase, workerSafeVendorImports };
|
|
2055
3901
|
|
|
2056
3902
|
//# sourceMappingURL=index.mjs.map
|