@powerhousedao/builder-tools 6.2.3-dev.71 → 6.2.3-dev.73

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.mjs CHANGED
@@ -9,10 +9,11 @@ import { Generator, getConfig } from "@tanstack/router-generator";
9
9
  import { tanstackRouter } from "@tanstack/router-plugin/vite";
10
10
  import { index, layout, physical, rootRoute, route } from "@tanstack/virtual-file-routes";
11
11
  import { fileURLToPath, pathToFileURL } from "node:url";
12
- import { DEFAULT_CONNECT_CONFIG, DYNAMIC_BASE_PLACEHOLDER, PWA_FILE_HANDLER_ACTION, buildRuntimeConfig, deepMerge, loadConnectEnv, mapBackgroundImages, mergeManifest, mergePwaConfig, normalizeBasePath, phConnectRuntimeConfigSchema, powerhousePackageSchema, resolveSourceConnect, setConnectEnv, unionStrings, validateBackground, withInferredCategory, workerPackageFileName, workflowsSettingConflict } from "@powerhousedao/shared/connect";
12
+ import { DEFAULT_CONNECT_CONFIG, DYNAMIC_BASE_PLACEHOLDER, EXTERNALIZABLE_SHARED_SPECIFIERS, PWA_FILE_HANDLER_ACTION, buildRuntimeConfig, deepMerge, loadConnectEnv, mapBackgroundImages, mergeManifest, mergePwaConfig, normalizeBasePath, phConnectRuntimeConfigSchema, powerhousePackageSchema, resolveSourceConnect, setConnectEnv, unionStrings, validateBackground, withInferredCategory, workerPackageFileName, workflowsSettingConflict } from "@powerhousedao/shared/connect";
13
13
  import { APP_ICON_VARIANT_SIZES, BACKGROUND_MAX_BYTES, PWA_ICON_VARIANT_SIZES, UI_ICON_MAX_BYTES, iconVariantPath, imageMimeType, isPassthroughImageRef, resolveImageRef } from "@powerhousedao/shared/connect/image-ref";
14
14
  import { createHash, randomUUID } from "node:crypto";
15
15
  import MagicString from "magic-string";
16
+ import { initSync, parse } from "es-module-lexer";
16
17
  import { getConfig as getConfig$1 } from "@powerhousedao/config/node";
17
18
  import tailwind from "@tailwindcss/vite";
18
19
  import react from "@vitejs/plugin-react";
@@ -238,6 +239,16 @@ function connectRoutesTreeOf(projectRoot, routesDir) {
238
239
  if (isDefaultRoutesDir(projectRoot, routesDir)) return join(projectRoot, CONNECT_ROUTES_GEN);
239
240
  return join(projectRoot, ".ph", `${relative(projectRoot, routesDir)}.gen.ts`);
240
241
  }
242
+ /** The dev watcher's filter for `.ph/`, which holds build output: ignored but
243
+ * for the host's route tree, rewritten as route files come and go. */
244
+ function ignoreDotPhButRouteTree(projectRoot, routesDir) {
245
+ const tree = routesDir && normalizePath(connectRoutesTreeOf(projectRoot, routesDir));
246
+ return (file) => {
247
+ const path = normalizePath(resolve(projectRoot, file));
248
+ if (!path.includes("/.ph/")) return false;
249
+ return !tree || path !== tree && !tree.startsWith(`${path}/`);
250
+ };
251
+ }
241
252
  /** Connect's pathless sidebar layout; a project's routes in `_app/` render in it. */
242
253
  const APP_LAYOUT = "_app";
243
254
  function findRouteFile(dir, name) {
@@ -355,6 +366,13 @@ function writePackageRoutesModule(projectRoot, projectRoutes, routeNodes, option
355
366
  const text = lines.join("\n");
356
367
  if (!existsSync(module) || readFileSync(module, "utf8") !== text) writeFileSync(module, text);
357
368
  }
369
+ /** The `_app/` paths of the generic plugin's code routes, e.g. its settings
370
+ * tabs: a project file at one is an override, never offered. */
371
+ function genericAppRouteIds(connectDir) {
372
+ const file = join(connectDir, "generic-routes.json");
373
+ if (!existsSync(file)) return [];
374
+ return JSON.parse(readFileSync(file, "utf8")).appRoutes ?? [];
375
+ }
358
376
  /** The router plugin's config: Connect's root and routes, and the project's. */
359
377
  function connectRoutesGeneratorConfig(connectDir, projectRoot, projectRoutes) {
360
378
  const routesDirectory = connectRoutesDirOf(connectDir);
@@ -386,7 +404,7 @@ function connectRoutesGeneratorConfig(connectDir, projectRoot, projectRoutes) {
386
404
  onRouteTreeChanged: ({ routeNodes }) => {
387
405
  writePackageRoutesModule(projectRoot, projectRoutes, routeNodes, {
388
406
  routesDirectory,
389
- connectAppIds: new Set(routeFilesIn(join(routesDirectory, APP_LAYOUT)).map(routeIdOf))
407
+ connectAppIds: /* @__PURE__ */ new Set([...routeFilesIn(join(routesDirectory, APP_LAYOUT)).map(routeIdOf), ...genericAppRouteIds(connectDir)])
390
408
  });
391
409
  }
392
410
  }] : [overrides],
@@ -406,17 +424,42 @@ function connectRoutesGeneratorConfig(connectDir, projectRoot, projectRoutes) {
406
424
  ]
407
425
  }, projectRoot);
408
426
  }
427
+ const reported = /* @__PURE__ */ new Map();
428
+ function reportDrops(file, messages) {
429
+ const key = messages.join("\n");
430
+ if (reported.get(file) === key) return;
431
+ reported.set(file, key);
432
+ for (const message of messages) console.warn(`[connect] ${message}`);
433
+ }
409
434
  /** Writes the route tree of Connect's and the project's routes; throws on a
410
435
  * collision that is not an override, which the router plugin would only log. */
411
- async function generateConnectRoutes(projectRoot, routesDir, config = connectRoutesGeneratorConfig(connectDirOf(projectRoot), projectRoot, routesDir)) {
436
+ async function generateConnectRoutes(projectRoot, routesDir, config = connectRoutesGeneratorConfig(connectDirOf(projectRoot), projectRoot, routesDir), warn) {
412
437
  mkdirSync(dirname(config.generatedRouteTree), { recursive: true });
438
+ let routeNodes = [];
439
+ const collect = {
440
+ name: "ph-connect-route-urls",
441
+ onRouteTreeChanged: (tree) => {
442
+ routeNodes = tree.routeNodes;
443
+ }
444
+ };
413
445
  try {
414
446
  await new Generator({
415
- config,
447
+ config: {
448
+ ...config,
449
+ plugins: [...config.plugins ?? [], collect]
450
+ },
416
451
  root: projectRoot
417
452
  }).run();
453
+ assertNoSharedUrls(routeNodes);
418
454
  assertNoDuplicateRoutes(config.generatedRouteTree);
419
455
  importConnectRoutesByPackage(config.generatedRouteTree, config.routesDirectory);
456
+ const drops = dropsContext(projectRoot, routesDir, config.routesDirectory);
457
+ for (const node of routeNodes) {
458
+ const found = dropsOf(node, drops);
459
+ if (!found) continue;
460
+ if (warn) found.messages.forEach(warn);
461
+ else reportDrops(found.file, found.messages);
462
+ }
420
463
  } catch (error) {
421
464
  const message = (Array.isArray(error) ? error : [error]).map((e) => e instanceof Error ? e.message : String(e)).join("\n");
422
465
  const shown = relative(projectRoot, routesDir).split(sep).join("/");
@@ -440,6 +483,72 @@ function assertNoDuplicateRoutes(treeFile) {
440
483
  if (conflicts.length === 0) return;
441
484
  throw new Error(`Conflicting configuration paths were found for a layout route.\nConflicting files: \n ${conflicts.flat().join("\n ")}\n`);
442
485
  }
486
+ const urlOf = (routePath) => `/${routePath.split("/").filter((segment) => segment && !segment.startsWith("_")).join("/")}`;
487
+ function assertNoSharedUrls(routeNodes) {
488
+ const byUrl = /* @__PURE__ */ new Map();
489
+ for (const node of routeNodes) {
490
+ if (node._fsRouteType === "pathless_layout" || !node.routePath) continue;
491
+ const url = urlOf(node.routePath);
492
+ byUrl.set(url, [...byUrl.get(url) ?? [], node.fullPath]);
493
+ }
494
+ const shared = [...byUrl].filter(([, files]) => files.length > 1);
495
+ if (shared.length === 0) return;
496
+ throw new Error(shared.map(([url, files]) => `More than one route serves ${url}; override Connect's in _app/ instead:\n ${files.join("\n ")}`).join("\n"));
497
+ }
498
+ /** The object literal after `key:` in `source`, braces balanced; strings aren't parsed. */
499
+ function objectAfter(source, key) {
500
+ const start = source.search(new RegExp(`\\b${key}\\s*:\\s*\\{`));
501
+ if (start < 0) return void 0;
502
+ const open = source.indexOf("{", start);
503
+ let depth = 0;
504
+ for (let i = open; i < source.length; i++) if (source[i] === "{") depth++;
505
+ else if (source[i] === "}" && --depth === 0) return source.slice(open, i + 1);
506
+ }
507
+ function dropsContext(projectRoot, routesDir, routesDirectory) {
508
+ return {
509
+ projectRoot,
510
+ routesDir,
511
+ routesDirectory,
512
+ connectAppIds: new Set(routeFilesIn(join(routesDirectory, APP_LAYOUT)).map(routeIdOf)),
513
+ genericAppIds: new Set(genericAppRouteIds(dirname(dirname(routesDirectory))))
514
+ };
515
+ }
516
+ /** What the router drops from a project route file without a word: a nav item
517
+ * it can't link, and an override without the options of the route it replaces. */
518
+ function dropsOf(node, context) {
519
+ const file = join(context.routesDirectory, node.filePath);
520
+ if (!file.startsWith(`${context.routesDir}${sep}`) || !existsSync(file)) return;
521
+ const shown = relative(context.projectRoot, file).split(sep).join("/");
522
+ const source = readFileSync(file, "utf8");
523
+ const messages = [];
524
+ const staticData = objectAfter(source, "staticData");
525
+ if (node.routePath?.includes("$") && staticData?.match(/\bnav\s*:/)) messages.push(`${shown}: staticData.nav is ignored on ${node.routePath}, whose params the sidebar can't fill in.`);
526
+ const appDir = join(context.routesDir, APP_LAYOUT);
527
+ if (file.startsWith(`${appDir}${sep}`)) {
528
+ const id = routeIdOf(relative(appDir, file).split(sep).join("/"));
529
+ const connectFile = `@powerhousedao/connect/routes/${APP_LAYOUT}/${id}`;
530
+ if (context.connectAppIds.has(id) && !source.includes(`"${connectFile}"`)) messages.push(`${shown} replaces Connect's route without its options, so what Connect sets on it (loader, search params, pending view, title) is dropped; spread them: import { options } from "${connectFile}".`);
531
+ if (context.genericAppIds.has(id) && !source.includes("genericSettingsTabs")) {
532
+ const tab = id.split("/").at(-1);
533
+ messages.push(`${shown} replaces a settings tab without its options, so the tab isn't listed; spread genericSettingsTabs["${tab}"] from "@powerhousedao/connect/generic".`);
534
+ }
535
+ }
536
+ return {
537
+ file,
538
+ messages
539
+ };
540
+ }
541
+ /** Warns, as Studio regenerates the tree, about each route file it rewrites. */
542
+ function dropsPlugin(projectRoot, routesDir, routesDirectory) {
543
+ const context = dropsContext(projectRoot, routesDir, routesDirectory);
544
+ return {
545
+ name: "ph-connect-silent-drops",
546
+ afterTransform: ({ node }) => {
547
+ const found = dropsOf(node, context);
548
+ if (found) reportDrops(found.file, found.messages);
549
+ }
550
+ };
551
+ }
443
552
  function escapeRegExp(text) {
444
553
  return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
445
554
  }
@@ -455,7 +564,11 @@ function connectDirOf(projectRoot) {
455
564
  return dirname(resolvePackage("@powerhousedao/connect/package.json", projectRoot));
456
565
  }
457
566
  /** What Connect's route files import, besides each other. */
458
- const CONNECT_ROUTE_FILE_DEPS = ["@tanstack/react-router", "@powerhousedao/connect-core/router"];
567
+ const CONNECT_ROUTE_FILE_DEPS = [
568
+ "@tanstack/react-router",
569
+ "@powerhousedao/connect-core/router",
570
+ "@powerhousedao/connect/route-views"
571
+ ];
459
572
  const IN_NODE_MODULES = /[\\/]node_modules[\\/]/;
460
573
  /**
461
574
  * The `optimizeDeps.include` entries an installed Connect's route files need.
@@ -505,7 +618,10 @@ function connectRoutes(projectRoot, routesDir = resolveConnectRoutesDir(projectR
505
618
  plugins: [{
506
619
  name: "ph-connect-routes-check",
507
620
  buildStart: () => generateConnectRoutes(projectRoot, routesDir, config)
508
- }, tanstackRouter(config)],
621
+ }, tanstackRouter({
622
+ ...config,
623
+ plugins: [...config.plugins ?? [], dropsPlugin(projectRoot, routesDir, config.routesDirectory)]
624
+ })],
509
625
  dedupe: ["@tanstack/react-router"],
510
626
  include
511
627
  };
@@ -886,7 +1002,7 @@ function resolveProjectPwaBrand(projectRoot, branding, warn) {
886
1002
  * `branding.icon` (an SVG master is one scalable favicon). They replace
887
1003
  * Connect's static icon.ico link in index.html; none keeps it. A favicon
888
1004
  * named outright (`faviconPath`: `branding.favicon` or `--favicon`) wins: it
889
- * is built as icon.ico, so the icon's siblings stand aside.
1005
+ * is built as icon.ico (or icon.svg, icon.png), so the icon's siblings stand aside.
890
1006
  */
891
1007
  function resolveProjectFavicons(projectRoot, branding, warn, faviconPath) {
892
1008
  const app = branding?.icon;
@@ -1170,12 +1286,37 @@ async function renderProjectAppShells(projectRoot, config, routeAliases, hostSty
1170
1286
  const renderer = await server.ssrLoadModule("@powerhousedao/connect/prerender");
1171
1287
  const stylesheet = join(projectRoot, "style.css");
1172
1288
  const css = withHostStylesheet(readFileSync(stylesheet, "utf8"), stylesheet, hostStylesheet);
1173
- return renderer.renderProjectShells(stylesheet, css);
1289
+ try {
1290
+ return await renderer.renderProjectShells(stylesheet, css);
1291
+ } catch (error) {
1292
+ throw withSourceLocations(error, (stack) => server.ssrRewriteStacktrace(stack));
1293
+ }
1174
1294
  });
1175
1295
  } finally {
1176
1296
  await server.close();
1177
1297
  }
1178
1298
  }
1299
+ const RENDER_LOCATION = /\(at (\S+) \((.+?):(\d+):(\d+)\)\)/g;
1300
+ /** The prerender's error with each `(at <component> (<file>:<line>:<col>))` in
1301
+ * its message mapped back to the source, as React reports the transformed code. */
1302
+ function withSourceLocations(error, rewrite) {
1303
+ if (!(error instanceof Error)) return error;
1304
+ const before = error.message;
1305
+ const after = before.replace(RENDER_LOCATION, (found, name, file, line, column) => {
1306
+ const frame = /^ {4}at .*?\(?(\S+?):(\d+):(\d+)\)?$/.exec(rewrite(` at ${name} (${file}:${line}:${column})`));
1307
+ return frame ? `(at ${name} (${frame[1]}:${frame[2]}:${frame[3]}))` : found;
1308
+ });
1309
+ if (after !== before) {
1310
+ error.message = after;
1311
+ if (error.stack) error.stack = error.stack.replace(before, after);
1312
+ }
1313
+ return error;
1314
+ }
1315
+ /** Vite's error overlay over the page, for a failure no module request reports. */
1316
+ function withErrorOverlay(html, err, base) {
1317
+ const script = `<script type="module">import { ErrorOverlay } from "${base}@vite/client";document.body.appendChild(new ErrorOverlay(${JSON.stringify(err).replaceAll("<", "\\u003c")}));<\/script>`;
1318
+ return html.replace("</body>", `${script}</body>`);
1319
+ }
1179
1320
  const sourceText = (source) => typeof source === "string" ? source : new TextDecoder().decode(source);
1180
1321
  /** Build: the composition's shell in #root and every variant in the dist, from
1181
1322
  * the project's routes when it has them. Dev: the shell from the project's routes
@@ -1203,11 +1344,27 @@ function connectAppShellPlugin(projectRoot, { composition, appName, routeAliases
1203
1344
  };
1204
1345
  let devShells;
1205
1346
  let devRender;
1347
+ let devShellError;
1348
+ let devServer;
1206
1349
  const renderDevShells = () => {
1207
1350
  if (!config || !routeAliases) return;
1208
1351
  const logger = config.logger;
1209
- devShells = renderProjectAppShells(projectRoot, config, routeAliases, hostStylesheet).then(withLoader).catch((error) => {
1210
- logger.warn(`[connect] the loading shell failed to render from the project's routes: ${String(error)}`);
1352
+ devShellError = void 0;
1353
+ devShells = renderProjectAppShells(projectRoot, config, routeAliases, hostStylesheet).then((rendered) => {
1354
+ devShellError = void 0;
1355
+ return withLoader(rendered);
1356
+ }, (error) => {
1357
+ const cause = error instanceof Error ? error : new Error(String(error));
1358
+ devShellError = {
1359
+ message: `The loading shell failed to render from the project's routes, and the build will fail on it:\n${cause.message}`,
1360
+ stack: cause.stack ?? "",
1361
+ plugin: "ph-connect-app-shell"
1362
+ };
1363
+ logger.error(`[connect] ${devShellError.message}`, { timestamp: true });
1364
+ devServer?.ws.send({
1365
+ type: "error",
1366
+ err: devShellError
1367
+ });
1211
1368
  return {};
1212
1369
  });
1213
1370
  };
@@ -1227,6 +1384,7 @@ function connectAppShellPlugin(projectRoot, { composition, appName, routeAliases
1227
1384
  name: "ph-connect-app-shell",
1228
1385
  configureServer(server) {
1229
1386
  if (!routeAliases) return;
1387
+ devServer = server;
1230
1388
  renderDevShells();
1231
1389
  const stylesheet = join(projectRoot, "style.css");
1232
1390
  const rerender = (file) => {
@@ -1250,10 +1408,11 @@ function connectAppShellPlugin(projectRoot, { composition, appName, routeAliases
1250
1408
  order: "post",
1251
1409
  handler: async (html) => {
1252
1410
  const current = !isBuild && routeAliases ? await devShell() : shell();
1253
- return current ? injectAppShell(html, current, base, {
1411
+ const page = current ? injectAppShell(html, current, base, {
1254
1412
  deferStyles: isBuild,
1255
1413
  appName
1256
1414
  }) : html;
1415
+ return devShellError ? withErrorOverlay(page, devShellError, base) : page;
1257
1416
  }
1258
1417
  },
1259
1418
  generateBundle: {
@@ -2222,28 +2381,20 @@ function resolveReactorWorkerSource(dirname) {
2222
2381
  function vendorRelativePath(vendorUrl) {
2223
2382
  return `../__vendor__/${vendorUrl.slice(vendorUrl.lastIndexOf("/") + 1)}`;
2224
2383
  }
2225
- const SPECIFIER_PATTERNS = [
2226
- /(?<![.\w$])import\s*\(\s*["']([^"']+)["']/g,
2227
- /(?<![.\w$])import\s*[^"'()]*?from\s*["']([^"']+)["']/g,
2228
- /(?<![.\w$])export\s*[^"'()]*?from\s*["']([^"']+)["']/g,
2229
- /(?<![.\w$])import\s*["']([^"']+)["']/g
2230
- ];
2384
+ function importSpecifiers(code) {
2385
+ initSync();
2386
+ const [imports] = parse(code);
2387
+ return imports.flatMap((specifier) => specifier.d === -2 || specifier.n === void 0 ? [] : [specifier.n]);
2388
+ }
2231
2389
  /**
2232
2390
  * Module specifiers a worker cannot resolve: anything that is not relative,
2233
2391
  * root-relative, or an http(s)/data/blob URL. Used as a post-build guard so a
2234
2392
  * leftover bare (or `node:`) import fails the build with a name instead of
2235
2393
  * shipping a worker that dies on its first import statement.
2236
- *
2237
- * Expects minified (comment-free) output: a raw-text scan cannot tell a real
2238
- * import from a JSDoc code sample, and unminified kysely/viem are full of the
2239
- * latter. The build below always minifies for exactly this reason.
2240
2394
  */
2241
2395
  function findDisallowedSpecifiers(code) {
2242
2396
  const found = /* @__PURE__ */ new Set();
2243
- for (const pattern of SPECIFIER_PATTERNS) for (const match of code.matchAll(pattern)) {
2244
- const spec = match[1];
2245
- if (!spec.startsWith("./") && !spec.startsWith("../") && !spec.startsWith("/") && !/^(https?:|data:|blob:)/.test(spec)) found.add(spec);
2246
- }
2397
+ for (const spec of importSpecifiers(code)) if (!spec.startsWith("./") && !spec.startsWith("../") && !spec.startsWith("/") && !/^(https?:|data:|blob:)/.test(spec)) found.add(spec);
2247
2398
  return [...found].sort();
2248
2399
  }
2249
2400
  /**
@@ -2492,14 +2643,8 @@ function publishDirAtomic(tmpDir, outDir) {
2492
2643
  force: true
2493
2644
  });
2494
2645
  }
2495
- const RELATIVE_SPECIFIER_PATTERNS = SPECIFIER_PATTERNS;
2496
2646
  function findRelativeSpecifiers(code) {
2497
- const found = /* @__PURE__ */ new Set();
2498
- for (const pattern of RELATIVE_SPECIFIER_PATTERNS) for (const match of code.matchAll(pattern)) {
2499
- const spec = match[1];
2500
- if (spec.startsWith("./") || spec.startsWith("../")) found.add(spec);
2501
- }
2502
- return [...found];
2647
+ return [...new Set(importSpecifiers(code).filter((spec) => spec.startsWith("./") || spec.startsWith("../")))];
2503
2648
  }
2504
2649
  function normalizeBundlePath(fromFile, spec) {
2505
2650
  const segments = fromFile.split("/").slice(0, -1);
@@ -2588,7 +2733,13 @@ function workerSafeVendorImports(vendorDir, vendorImports) {
2588
2733
  for (const [spec, url] of Object.entries(vendorImports)) {
2589
2734
  const entryFile = url.slice(url.lastIndexOf("/") + 1);
2590
2735
  if (!existsSync(join(vendorDir, entryFile))) continue;
2591
- if (walkBundleGraph(vendorDir, entryFile, (_file, code) => findDisallowedSpecifiers(code).length === 0 && findWorkerUnsafeMarkers(code).length === 0)) safe[spec] = url;
2736
+ if (walkBundleGraph(vendorDir, entryFile, (_file, code) => {
2737
+ try {
2738
+ return findDisallowedSpecifiers(code).length === 0 && findWorkerUnsafeMarkers(code).length === 0;
2739
+ } catch {
2740
+ return false;
2741
+ }
2742
+ })) safe[spec] = url;
2592
2743
  }
2593
2744
  return safe;
2594
2745
  }
@@ -2941,6 +3092,25 @@ const runtimeConfigSchema = {
2941
3092
  connect: phConnectRuntimeConfigSchema
2942
3093
  }
2943
3094
  };
3095
+ //#endregion
3096
+ //#region connect-utils/dev-deps.ts
3097
+ /** Pre-bundled deps for Connect's dev server, scanning the project's routes. */
3098
+ function connectOptimizeDeps(projectRoot, routesDir, routeFileDeps) {
3099
+ const routes = routesDir && relative(projectRoot, routesDir).replaceAll("\\", "/");
3100
+ return {
3101
+ ...routes ? { entries: ["index.html", `${routes}/**/*.{js,jsx,ts,tsx}`] } : {},
3102
+ include: [
3103
+ "document-model",
3104
+ "zod",
3105
+ "@powerhousedao/design-system/connect",
3106
+ "@powerhousedao/reactor-browser",
3107
+ "@powerhousedao/document-engineering",
3108
+ ...routeFileDeps
3109
+ ],
3110
+ exclude: ["@electric-sql/pglite", "@electric-sql/pglite-tools"],
3111
+ rolldownOptions: { external: [ROUTE_TREE_SPECIFIER, CORE_ROUTE_TREE_SPECIFIER] }
3112
+ };
3113
+ }
2944
3114
  const RESOLVED_VIRTUAL_ID = "\0virtual:ph-bundled-packages-virtual";
2945
3115
  const BUNDLED_PACKAGES_DEV_URL = "@id/" + RESOLVED_VIRTUAL_ID.replace("\0", "__x00__");
2946
3116
  function readBundledPackageVersion(projectRoot, name) {
@@ -3005,7 +3175,13 @@ const REACT_DEPS = [
3005
3175
  "react-dom/client"
3006
3176
  ];
3007
3177
  const SHIM_PATH = "__ph/dev-react-shim/";
3008
- const VITE_DEPS_PATH = "node_modules/.vite/deps";
3178
+ const SHARED_SHIM = "ph-shared:";
3179
+ const SHARED_DEPS = EXTERNALIZABLE_SHARED_SPECIFIERS.filter((spec) => !REACT_DEPS.includes(spec));
3180
+ /** The page's import map entries for the shared deps: each root and its subpaths. */
3181
+ function sharedDepImports(base) {
3182
+ const url = (spec) => withBase$1(base, `@id/__x00__${SHARED_SHIM}${spec}`);
3183
+ return Object.fromEntries(SHARED_DEPS.flatMap((spec) => [[spec, url(spec)], [`${spec}/`, `${url(spec)}/`]]));
3184
+ }
3009
3185
  const VENDOR_MIME = {
3010
3186
  ".css": "text/css",
3011
3187
  ".map": "application/json",
@@ -3026,6 +3202,19 @@ const VENDOR_MODE = process.env.PH_CONNECT_EXTERNALIZE_VENDOR === "1";
3026
3202
  const VENDOR_EXTRA = (process.env.PH_CONNECT_VENDOR_EXTRA ?? "").split(",").map((s) => s.trim()).filter(Boolean);
3027
3203
  const HEAVY_LIBS = [...DEFAULT_VENDOR_INCLUDE, ...VENDOR_EXTRA];
3028
3204
  const heavyLibsFor = (routesDir) => routesDir ? HEAVY_LIBS.filter((lib) => lib !== "@powerhousedao/connect") : HEAVY_LIBS;
3205
+ /** The dev server's URL for a file: under the root, else through `/@fs/`. */
3206
+ function devUrlOf(root, file) {
3207
+ const relativePath = path.relative(root, file);
3208
+ return relativePath.startsWith("..") || path.isAbsolute(relativePath) ? `/@fs/${file.split(path.sep).join("/").replace(/^\/+/, "")}` : relativePath.split(path.sep).join("/");
3209
+ }
3210
+ /** A file of Connect's package, else the root: where Connect's own imports resolve from. */
3211
+ function connectImporter(root) {
3212
+ try {
3213
+ return createRequire(path.join(root, "package.json")).resolve("@powerhousedao/connect/package.json");
3214
+ } catch {
3215
+ return path.join(root, "index.html");
3216
+ }
3217
+ }
3029
3218
  function withBase$1(base, p) {
3030
3219
  return `${base}${p}`.replace(/\/{2,}/g, "/");
3031
3220
  }
@@ -3064,6 +3253,7 @@ function externalizePlugin(externals) {
3064
3253
  async function devReactImportmapPlugin(projectRoot = process.cwd(), routesDir = resolveConnectRoutesDir(projectRoot)) {
3065
3254
  let namedExports = /* @__PURE__ */ new Map();
3066
3255
  let base = "/";
3256
+ let root = projectRoot;
3067
3257
  let vendor = null;
3068
3258
  const heavyLibs = heavyLibsFor(routesDir);
3069
3259
  if (VENDOR_MODE) {
@@ -3084,6 +3274,16 @@ async function devReactImportmapPlugin(projectRoot = process.cwd(), routesDir =
3084
3274
  const main = {
3085
3275
  name: "ph-dev-react-importmap",
3086
3276
  apply: "serve",
3277
+ async resolveId(source, importer) {
3278
+ if (source.startsWith(SHARED_SHIM)) return `\0${source}`;
3279
+ if (source.startsWith(`\0${SHARED_SHIM}`)) return source;
3280
+ if (importer?.startsWith(`\0${SHARED_SHIM}`)) return this.resolve(source, connectImporter(root), { skipSelf: true });
3281
+ },
3282
+ load(id) {
3283
+ if (!id.startsWith(`\0${SHARED_SHIM}`)) return void 0;
3284
+ const spec = JSON.stringify(id.slice(11));
3285
+ return `export * from ${spec};\nimport * as M from ${spec};\nexport default M.default;\n`;
3286
+ },
3087
3287
  config(cfg) {
3088
3288
  cfg.optimizeDeps ??= {};
3089
3289
  const include = new Set(cfg.optimizeDeps.include ?? []);
@@ -3096,6 +3296,7 @@ async function devReactImportmapPlugin(projectRoot = process.cwd(), routesDir =
3096
3296
  },
3097
3297
  configResolved(config) {
3098
3298
  base = config.base;
3299
+ root = config.root;
3099
3300
  },
3100
3301
  configureServer(server) {
3101
3302
  const requireFromRoot = createRequire(path.join(server.config.root, "package.json"));
@@ -3145,7 +3346,7 @@ async function devReactImportmapPlugin(projectRoot = process.cwd(), routesDir =
3145
3346
  return;
3146
3347
  }
3147
3348
  const browserHash = info.browserHash ?? optimizer.metadata.browserHash;
3148
- const depUrl = `${withBase$1(base, VITE_DEPS_PATH)}/${path.basename(info.file)}?v=${browserHash}`;
3349
+ const depUrl = `${withBase$1(base, devUrlOf(root, info.file))}?v=${browserHash}`;
3149
3350
  const names = namedExports.get(id) ?? [];
3150
3351
  res.setHeader("Content-Type", "application/javascript");
3151
3352
  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` : ""));
@@ -3158,6 +3359,7 @@ async function devReactImportmapPlugin(projectRoot = process.cwd(), routesDir =
3158
3359
  if (!browserHash) return;
3159
3360
  const shimPrefix = withBase$1(base, SHIM_PATH);
3160
3361
  const imports = Object.fromEntries(REACT_DEPS.map((id) => [id, `${shimPrefix}${id}.js?v=${browserHash}`]));
3362
+ Object.assign(imports, sharedDepImports(base));
3161
3363
  let dynamicBaseScript = "";
3162
3364
  if (vendorActive) {
3163
3365
  for (const [spec, url] of Object.entries(vendor.imports)) imports[spec] = withBase$1(base, url);
@@ -3180,16 +3382,20 @@ const CONTENT_TYPE_BY_EXT = {
3180
3382
  /**
3181
3383
  * Vite plugin to serve the Connect favicon (icon.ico) from the connect package,
3182
3384
  * or from a caller-supplied file when `faviconPath` is set (e.g. `ph connect
3183
- * build --favicon`). The served/emitted name is always `icon.ico` so the static
3184
- * `<link rel="icon" href="%BASE_URL%icon.ico">` in index.html stays valid.
3385
+ * build --favicon`). An .svg or .png keeps its type as icon.svg or icon.png,
3386
+ * and index.html's `<link rel="icon">` is rewritten to it; browsers decode a
3387
+ * file named icon.ico as an ICO.
3185
3388
  */
3186
3389
  function connectFaviconPlugin(opts = {}) {
3187
3390
  const customPath = opts.faviconPath ? isAbsolute(opts.faviconPath) ? opts.faviconPath : resolve(process.cwd(), opts.faviconPath) : void 0;
3188
- const customContentType = customPath ? CONTENT_TYPE_BY_EXT[extname(customPath).toLowerCase()] ?? "image/x-icon" : "image/x-icon";
3391
+ const ext = customPath ? extname(customPath).toLowerCase() : ".ico";
3392
+ const customContentType = CONTENT_TYPE_BY_EXT[ext] ?? "image/x-icon";
3393
+ const fileName = ext === ".svg" || ext === ".png" ? `icon${ext}` : "icon.ico";
3189
3394
  return {
3190
3395
  name: "copy-connect-favicon",
3191
3396
  configureServer(server) {
3192
- const faviconRoute = `${server.config.base}icon.ico`.replace(/\/{2,}/g, "/");
3397
+ const base = server.config.base;
3398
+ const route = (name) => `${base}${name}`.replace(/\/{2,}/g, "/");
3193
3399
  const handler = (_req, res, next) => {
3194
3400
  if (customPath) {
3195
3401
  try {
@@ -3206,12 +3412,21 @@ function connectFaviconPlugin(opts = {}) {
3206
3412
  res.end(readFileSync(resolved.id));
3207
3413
  }).catch(() => next());
3208
3414
  };
3209
- const paths = /* @__PURE__ */ new Set([faviconRoute, "/icon.ico"]);
3415
+ const paths = /* @__PURE__ */ new Set([
3416
+ route(fileName),
3417
+ `/${fileName}`,
3418
+ route("icon.ico"),
3419
+ "/icon.ico"
3420
+ ]);
3210
3421
  for (const path of paths) server.middlewares.use(path, handler);
3211
3422
  },
3423
+ transformIndexHtml(html) {
3424
+ if (fileName === "icon.ico") return html;
3425
+ return html.replace(/<link rel="icon" href="([^"]*)icon\.ico"\s*\/?>/, `<link rel="icon" type="${customContentType}" href="$1${fileName}" />`);
3426
+ },
3212
3427
  async generateBundle(_options, bundle) {
3213
3428
  try {
3214
- if ("icon.ico" in bundle) return;
3429
+ if (fileName in bundle) return;
3215
3430
  let source;
3216
3431
  if (customPath) source = readFileSync(customPath);
3217
3432
  else {
@@ -3221,7 +3436,7 @@ function connectFaviconPlugin(opts = {}) {
3221
3436
  if (!source) return;
3222
3437
  this.emitFile({
3223
3438
  type: "asset",
3224
- fileName: "icon.ico",
3439
+ fileName,
3225
3440
  source
3226
3441
  });
3227
3442
  } catch {}
@@ -4333,9 +4548,14 @@ function getConnectBaseViteConfig(options) {
4333
4548
  return {
4334
4549
  configFile: false,
4335
4550
  mode,
4551
+ cacheDir: options.cacheDir,
4336
4552
  base: options.dynamicBase ? DYNAMIC_BASE_PLACEHOLDER : connectBasePath ? normalizeBasePath(connectBasePath) : void 0,
4337
4553
  server: {
4338
- watch: { ignored: ["**/backup-documents/**", "**/.ph/**"] },
4554
+ watch: { ignored: [
4555
+ "**/backup-documents/**",
4556
+ "**/coverage/**",
4557
+ ignoreDotPhButRouteTree(options.dirname, routesDir)
4558
+ ] },
4339
4559
  fs: { allow: [searchForWorkspaceRoot(options.dirname), ...linkedRoots] }
4340
4560
  },
4341
4561
  resolve: {
@@ -4355,17 +4575,7 @@ function getConnectBaseViteConfig(options) {
4355
4575
  },
4356
4576
  customLogger,
4357
4577
  envPrefix: ["PH_CONNECT_"],
4358
- optimizeDeps: {
4359
- include: [
4360
- "document-model",
4361
- "zod",
4362
- "@powerhousedao/design-system/connect",
4363
- "@powerhousedao/reactor-browser",
4364
- "@powerhousedao/document-engineering",
4365
- ...routes.include
4366
- ],
4367
- exclude: ["@electric-sql/pglite", "@electric-sql/pglite-tools"]
4368
- },
4578
+ optimizeDeps: connectOptimizeDeps(options.dirname, routesDir, routes.include),
4369
4579
  plugins: [
4370
4580
  configPlugin,
4371
4581
  hostStylesheetPlugin(options.dirname, hostStylesheet),
@@ -4417,6 +4627,6 @@ function getConnectBaseViteConfig(options) {
4417
4627
  };
4418
4628
  }
4419
4629
  //#endregion
4420
- 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, connectRouteFileDeps, connectRouterChunkGroups, connectRoutes, connectRoutesDirOf, connectRoutesGeneratorConfig, connectRoutesTreeOf, connectThemeBootPlugin, copyConnect, directoryContentDigest, distDirFingerprint, ensureNodeVersion, escapeForRegExp, findBundleSpecifierOffenders, findDisallowedSpecifiers, findPackageRoot, findWorkerUnsafeMarkers, generateConnectRoutes, getConnectBaseViteConfig, getConnectHtmlTags, hasProjectAppLayout, 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 };
4630
+ 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, CONNECT_ROUTE_FILE_DEPS, 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, connectRouteFileDeps, connectRouterChunkGroups, connectRoutes, connectRoutesDirOf, connectRoutesGeneratorConfig, connectRoutesTreeOf, connectThemeBootPlugin, copyConnect, directoryContentDigest, distDirFingerprint, ensureNodeVersion, escapeForRegExp, findBundleSpecifierOffenders, findDisallowedSpecifiers, findPackageRoot, findWorkerUnsafeMarkers, generateConnectRoutes, getConnectBaseViteConfig, getConnectHtmlTags, hasProjectAppLayout, hostStylesheetPath, hostStylesheetPlugin, ignoreDotPhButRouteTree, 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, withErrorOverlay, withHostStylesheet, withShellAppName, withSourceLocations, withVendorBase, workerSafeVendorImports };
4421
4631
 
4422
4632
  //# sourceMappingURL=index.mjs.map