@powerhousedao/builder-tools 6.0.0-dev.169 → 6.0.0-dev.170

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 CHANGED
@@ -1,5 +1,4 @@
1
- import { CommonServerOptions, HtmlTagDescriptor, InlineConfig, Plugin, PluginOption } from "vite";
2
- import { Package } from "resolve.exports";
1
+ import { CommonServerOptions, HtmlTagDescriptor, InlineConfig, Plugin } from "vite";
3
2
  import { PowerhouseConfig } from "@powerhousedao/config";
4
3
 
5
4
  //#region connect-utils/constants.d.ts
@@ -165,46 +164,11 @@ declare function getConnectHtmlTags(options?: {
165
164
  }];
166
165
  declare function getConnectBaseViteConfig(options: IConnectOptions): InlineConfig;
167
166
  //#endregion
168
- //#region connect-utils/vite-plugins/base.d.ts
169
- declare const externalIds: RegExp[];
170
- declare function viteIgnoreStaticImport(_importKeys: (string | RegExp | false | undefined)[]): Plugin;
171
- declare function viteReplaceImports(imports: Record<string, string>): PluginOption;
172
- declare function findPackageJson(packageName: string): Promise<{
173
- packageJson: Package;
174
- path: string;
175
- }>;
176
- //#endregion
177
- //#region connect-utils/vite-plugins/importmap.d.ts
178
- type Provider = "node_modules" | "esm.sh";
179
- type Dependency = {
180
- name: string;
181
- version?: string;
182
- provider: Provider;
183
- dependencies?: string[];
184
- };
185
- /**
186
- * Vite plugin to bundle or copy dependencies and inject an import map into `index.html`.
187
- *
188
- * @param {string} outputDir - The directory where the modules should be placed.
189
- * @param {(string | { name: string; provider: string })[]} dependencies -
190
- * List of dependencies to process. Can be:
191
- * - A string (dependency is copied as is).
192
- * - An object `{ name, provide }` where:
193
- * - `name` (string): The module name.
194
- * - `provider` (string): Where to retrieve the module bundle. Defaults to node_modules.
195
- *
196
- * @returns {Plugin} A Vite plugin that processes dependencies and injects an import map.
197
- */
198
- declare function generateImportMapPlugin(outputDir: string, dependencies: (string | Dependency)[]): PluginOption[];
199
- //#endregion
200
167
  //#region connect-utils/vite-plugins/ph-packages.d.ts
201
168
  type PhPackagesPluginOptions = {
202
169
  packages: string[];
203
170
  };
204
171
  declare function phPackagesPlugin(options: PhPackagesPluginOptions): Plugin;
205
172
  //#endregion
206
- //#region connect-utils/vite-plugins/studio.d.ts
207
- declare function viteConnectDevStudioPlugin(enabled: boolean | undefined, connectPath: string, env?: Record<string, string>): PluginOption[];
208
- //#endregion
209
- export { ConnectBuildOptions, ConnectCommonOptions, ConnectPreviewOptions, ConnectStudioOptions, DEFAULT_CONNECT_OUTDIR, Dependency, EXTERNAL_PACKAGES_IMPORT, IConnectOptions, IMPORT_SCRIPT_FILE, LOCAL_PACKAGE_ID, PH_DIR_NAME, PhPackagesPluginOptions, Provider, ViteDevOptions, appendToHtmlHead, backupIndexHtml, commonConnectOptionsToEnv, copyConnect, ensureNodeVersion, externalIds, findPackageJson, generateImportMapPlugin, getConnectBaseViteConfig, getConnectHtmlTags, makeImportScriptFromPackages, phPackagesPlugin, prependToHtmlHead, readJsonFile, removeBase64EnvValues, resolveConnectBundle, resolveConnectPackageJson, resolveConnectPublicDir, resolvePackage, resolveViteConfigPath, runShellScriptPlugin, runTsc, stripVersionFromPackage, viteConnectDevStudioPlugin, viteIgnoreStaticImport, viteReplaceImports };
173
+ export { ConnectBuildOptions, ConnectCommonOptions, ConnectPreviewOptions, ConnectStudioOptions, DEFAULT_CONNECT_OUTDIR, EXTERNAL_PACKAGES_IMPORT, IConnectOptions, IMPORT_SCRIPT_FILE, LOCAL_PACKAGE_ID, PH_DIR_NAME, PhPackagesPluginOptions, ViteDevOptions, appendToHtmlHead, backupIndexHtml, commonConnectOptionsToEnv, copyConnect, ensureNodeVersion, getConnectBaseViteConfig, getConnectHtmlTags, makeImportScriptFromPackages, phPackagesPlugin, prependToHtmlHead, readJsonFile, removeBase64EnvValues, resolveConnectBundle, resolveConnectPackageJson, resolveConnectPublicDir, resolvePackage, resolveViteConfigPath, runShellScriptPlugin, runTsc, stripVersionFromPackage };
210
174
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../connect-utils/constants.ts","../connect-utils/types.ts","../connect-utils/helpers.ts","../connect-utils/vite-config.ts","../connect-utils/vite-plugins/base.ts","../connect-utils/vite-plugins/importmap.ts","../connect-utils/vite-plugins/ph-packages.ts","../connect-utils/vite-plugins/studio.ts"],"mappings":";;;;;cAAa,wBAAA;AAAA,cACA,kBAAA;AAAA,cACA,gBAAA;AAAA,cACA,WAAA;;;KCAD,eAAA;EACV,IAAA;EACA,OAAA;EACA,MAAA;EACA,gBAAA,GAAmB,gBAAA;EACnB,YAAA;AAAA;AAAA,KAGU,oBAAA;EAEV,IAAA;EAEA,IAAA;EAEA,UAAA;EAEA,WAAA;EAEA,cAAA;EAEA,mBAAA;EAEA,gBAAA;EAEA,sBAAA;AAAA;AAAA,KAGU,cAAA,GAAiB,IAAA,CAC3B,mBAAA;EAEI,KAAA;AAAA;AAAA,KAEM,oBAAA,GAAuB,oBAAA;EACjC,gBAAA,GAAmB,cAAA;EACnB,SAAA;EACA,gBAAA;AAAA;AAAA,KAGU,mBAAA,GAAsB,oBAAA;EAEhC,MAAA;AAAA;AAAA,KAGU,qBAAA,GAAwB,oBAAA,GAClC,IAAA,CAAK,cAAA;EAEH,MAAA;EACA,SAAA;EACA,gBAAA;AAAA;;;cCvCS,sBAAA;AAAA,iBAEG,yBAAA,CAA0B,OAAA,EAAS,oBAAA;AAAA,iBAqCnC,qBAAA,CACd,OAAA,EAAS,IAAA,CAAK,oBAAA;AAAA,iBAMA,cAAA,CAAe,WAAA,UAAqB,IAAA;AAAA,iBAMpC,yBAAA,CAA0B,IAAA,YAAoB,IAAA;;;AF/D9D;iBEgFgB,oBAAA,CAAqB,IAAA;AAAA,iBASrB,uBAAA,CAAwB,IAAA;;;AFxFxC;iBEmGgB,WAAA,CAAY,UAAA,UAAoB,UAAA;;;;AFlGhD;;iBEmHgB,eAAA,CAAgB,OAAA,UAAiB,OAAA;AAAA,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{"version":3,"file":"index.d.mts","names":[],"sources":["../connect-utils/constants.ts","../connect-utils/types.ts","../connect-utils/helpers.ts","../connect-utils/vite-config.ts","../connect-utils/vite-plugins/ph-packages.ts"],"mappings":";;;;cAAa,wBAAA;AAAA,cACA,kBAAA;AAAA,cACA,gBAAA;AAAA,cACA,WAAA;;;KCAD,eAAA;EACV,IAAA;EACA,OAAA;EACA,MAAA;EACA,gBAAA,GAAmB,gBAAA;EACnB,YAAA;AAAA;AAAA,KAGU,oBAAA;EAEV,IAAA;EAEA,IAAA;EAEA,UAAA;EAEA,WAAA;EAEA,cAAA;EAEA,mBAAA;EAEA,gBAAA;EAEA,sBAAA;AAAA;AAAA,KAGU,cAAA,GAAiB,IAAA,CAC3B,mBAAA;EAEI,KAAA;AAAA;AAAA,KAEM,oBAAA,GAAuB,oBAAA;EACjC,gBAAA,GAAmB,cAAA;EACnB,SAAA;EACA,gBAAA;AAAA;AAAA,KAGU,mBAAA,GAAsB,oBAAA;EAEhC,MAAA;AAAA;AAAA,KAGU,qBAAA,GAAwB,oBAAA,GAClC,IAAA,CAAK,cAAA;EAEH,MAAA;EACA,SAAA;EACA,gBAAA;AAAA;;;cCvCS,sBAAA;AAAA,iBAEG,yBAAA,CAA0B,OAAA,EAAS,oBAAA;AAAA,iBAqCnC,qBAAA,CACd,OAAA,EAAS,IAAA,CAAK,oBAAA;AAAA,iBAMA,cAAA,CAAe,WAAA,UAAqB,IAAA;AAAA,iBAMpC,yBAAA,CAA0B,IAAA,YAAoB,IAAA;;AF/D9D;;iBEgFgB,oBAAA,CAAqB,IAAA;AAAA,iBASrB,uBAAA,CAAwB,IAAA;;AFxFxC;;iBEmGgB,WAAA,CAAY,UAAA,UAAoB,UAAA;;;AFlGhD;;;iBEmHgB,eAAA,CAAgB,OAAA,UAAiB,OAAA;AAAA,iBAWjC,qBAAA,CAAsB,OAAA;AAAA,iBAmCtB,YAAA,CAAa,QAAA,WAAmB,gBAAA;;;ADjKhD;iBC+KgB,4BAAA,CAA6B,IAAA;EAC3C,QAAA;EACA,YAAA;EACA,WAAA;EACA,YAAA;AAAA;AAAA,iBAsDc,iBAAA,CAAkB,UAAA;AAAA,iBAclB,oBAAA,CACd,UAAA,UACA,WAAA,WACC,MAAA;;;;iBAwCmB,gBAAA,CAAiB,UAAA,UAAoB,QAAA,WAAgB,OAAA;;;;iBAYrD,iBAAA,CAAkB,UAAA,UAAoB,QAAA,WAAgB,OAAA;AAAA,iBAS5D,MAAA,CAAO,MAAA;AAAA,iBAMP,uBAAA,CAAwB,WAAA;;;iBC5SxB,kBAAA,CACd,OAAA;EACE,WAAA;EACA,QAAA,GAAW,iBAAA;AAAA;EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA2HC,wBAAA,CAAyB,OAAA,EAAS,eAAA,GAAe,YAAA;;;KChJrD,uBAAA;EACV,QAAA;AAAA;AAAA,iBAGc,gBAAA,CAAiB,OAAA,EAAS,uBAAA,GAA0B,MAAA"}
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
- import { builtinModules, createRequire } from "node:module";
1
+ import { createRequire } from "node:module";
2
2
  import { exec, execSync } from "node:child_process";
3
3
  import fs, { existsSync, readFileSync } from "node:fs";
4
- import fs$1, { readFile, writeFile } from "node:fs/promises";
5
- import path, { basename, dirname, join, resolve } from "node:path";
4
+ import { readFile, writeFile } from "node:fs/promises";
5
+ import path, { join, resolve } from "node:path";
6
6
  import { cwd } from "node:process";
7
7
  import { loadConnectEnv, setConnectEnv } from "@powerhousedao/shared/connect";
8
8
  import { getConfig } from "@powerhousedao/config/node";
@@ -11,11 +11,6 @@ import tailwind from "@tailwindcss/vite";
11
11
  import react from "@vitejs/plugin-react";
12
12
  import { createLogger, esmExternalRequirePlugin, loadEnv } from "vite";
13
13
  import { createHtmlPlugin } from "vite-plugin-html";
14
- import fs$2 from "fs/promises";
15
- import MagicString from "magic-string";
16
- import { build } from "esbuild";
17
- import fg from "fast-glob";
18
- import { exports } from "resolve.exports";
19
14
  //#region connect-utils/constants.ts
20
15
  const EXTERNAL_PACKAGES_IMPORT = "PH:EXTERNAL_PACKAGES";
21
16
  const IMPORT_SCRIPT_FILE = "external-packages.js";
@@ -444,7 +439,10 @@ function getConnectBaseViteConfig(options) {
444
439
  configFile: false,
445
440
  mode,
446
441
  server: { watch: { ignored: ["**/backup-documents/**", "**/.ph/**"] } },
447
- resolve: { tsconfigPaths: true },
442
+ resolve: {
443
+ dedupe: ["react", "react-dom"],
444
+ tsconfigPaths: true
445
+ },
448
446
  define: { PH_PACKAGE_REGISTRY_URL: `"${phPackageRegistryUrl}"` },
449
447
  customLogger,
450
448
  envPrefix: ["PH_CONNECT_"],
@@ -469,317 +467,6 @@ function getConnectBaseViteConfig(options) {
469
467
  };
470
468
  }
471
469
  //#endregion
472
- //#region connect-utils/vite-plugins/base.ts
473
- const externalIds = [/^react(-dom)?(\/.*)?$/, /^node:.*$/];
474
- function viteIgnoreStaticImport(_importKeys) {
475
- const importKeys = _importKeys.filter((key) => typeof key === "string" || key instanceof RegExp);
476
- return {
477
- name: "vite-plugin-ignore-static-import",
478
- enforce: "pre",
479
- configResolved(resolvedConfig) {
480
- const values = importKeys.map((key) => typeof key === "string" ? key : key.source);
481
- const reg = new RegExp(`("|')\\/@id\\/(${values.join("|")})(\\/[^"'\\\\]*)?\\1`, "g");
482
- resolvedConfig.plugins.push({
483
- name: "vite-plugin-ignore-static-import-replace-idprefix",
484
- transform: (code) => {
485
- const s = new MagicString(code);
486
- const matches = code.matchAll(reg);
487
- let modified = false;
488
- for (const match of matches) {
489
- s.overwrite(match.index, match.index + match[0].length, match[0].replace("/@id/", ""));
490
- modified = true;
491
- }
492
- if (!modified) return null;
493
- return {
494
- code: s.toString(),
495
- map: s.generateMap({ hires: true })
496
- };
497
- }
498
- });
499
- },
500
- resolveId: (id) => {
501
- if (importKeys.some((key) => typeof key === "string" ? key === id : key.test(id))) return {
502
- id,
503
- external: true
504
- };
505
- },
506
- load(id) {
507
- if (importKeys.some((key) => typeof key === "string" ? key === id : key.test(id))) return "";
508
- }
509
- };
510
- }
511
- function viteReplaceImports(imports) {
512
- const importKeys = Object.keys(imports);
513
- return {
514
- name: "vite-plugin-connect-replace-imports",
515
- enforce: "pre",
516
- config(config) {
517
- const resolve = config.resolve ?? {};
518
- const alias = resolve.alias;
519
- let resolvedAlias;
520
- if (Array.isArray(alias)) {
521
- const arrayAlias = [...alias];
522
- arrayAlias.push(...Object.entries(imports).map(([find, replacement]) => ({
523
- find,
524
- replacement
525
- })));
526
- resolvedAlias = arrayAlias;
527
- } else if (typeof alias === "object") resolvedAlias = {
528
- ...alias,
529
- ...imports
530
- };
531
- else if (typeof alias === "undefined") resolvedAlias = { ...imports };
532
- else console.error("resolve.alias was not recognized");
533
- if (resolvedAlias) {
534
- resolve.alias = resolvedAlias;
535
- config.resolve = resolve;
536
- }
537
- },
538
- resolveId: (id) => {
539
- if (importKeys.includes(id)) return {
540
- id,
541
- external: true
542
- };
543
- }
544
- };
545
- }
546
- async function findPackageJson(packageName) {
547
- let packagePath;
548
- try {
549
- packagePath = createRequire(process.cwd()).resolve(packageName, { paths: [process.cwd()] });
550
- } catch (err) {
551
- throw new Error(`Failed to resolve package: ${packageName}`, { cause: err });
552
- }
553
- let dir = dirname(packagePath);
554
- while (dir !== "/" && dir !== "." && dir !== "node_modules") {
555
- if (basename(dir) === "dist") dir = dirname(dir);
556
- const pkgJsonPath = `${dir}/package.json`;
557
- try {
558
- await fs$2.access(pkgJsonPath);
559
- const file = await fs$2.readFile(pkgJsonPath, "utf-8");
560
- return {
561
- packageJson: JSON.parse(file),
562
- path: dir
563
- };
564
- } catch {
565
- dir = dirname(dir);
566
- }
567
- }
568
- throw new Error(`package.json not found for ${packageName}`);
569
- }
570
- //#endregion
571
- //#region connect-utils/vite-plugins/importmap.ts
572
- const nodeModules = builtinModules.concat(builtinModules.map((m) => `node:${m}`));
573
- /**
574
- * Resolves glob exports like `"./*": "./dist/*.js"` and `"./utils/*": "./dist/utils/*.js"`
575
- * into actual file mappings.
576
- *
577
- * @param {string} exportName - The export pattern (e.g., `"./*"` or `"./utils/*"`).
578
- * @param {string} exportPath - The actual path pattern (e.g., `"./dist/*.js"`).
579
- * @param {string} srcPath - The package root directory where the exports are located.
580
- * @returns {Promise<Record<string, string>>} - A mapping of export names to resolved paths.
581
- */
582
- async function resolveGlobExport(exportName, exportPath, srcPath) {
583
- const resolvedExports = /* @__PURE__ */ new Map();
584
- const hasGloblExport = exportName.endsWith("/*");
585
- const globPath = hasGloblExport ? exportPath.replace("*", "**/*") : exportPath;
586
- const distPath = exportPath.substring(0, exportPath.lastIndexOf("/*"));
587
- const resolvedSrcPath = hasGloblExport ? path.join(srcPath.replace("*", ""), distPath) : srcPath;
588
- const files = await fg(path.join(srcPath, globPath));
589
- for (const file of files) {
590
- const relativeSrcFilePath = path.relative(resolvedSrcPath, file);
591
- const exportFilePath = path.relative(srcPath, file);
592
- const exportKey = relativeSrcFilePath.replace(path.extname(file), "");
593
- const mappedExport = exportName.replace("*", exportKey);
594
- resolvedExports.set(mappedExport, {
595
- export: `./${relativeSrcFilePath}`,
596
- file: exportFilePath
597
- });
598
- }
599
- return resolvedExports;
600
- }
601
- async function addExportToMap(exportName, exportPath, srcPath, map) {
602
- if (exportName.includes("*")) (await resolveGlobExport(exportName, exportPath, srcPath)).forEach((value, key) => map.set(key, value));
603
- else map.set(exportName, {
604
- export: exportPath,
605
- file: exportPath
606
- });
607
- }
608
- async function getPackageExports(name, packageJson, srcPath) {
609
- const entries = /* @__PURE__ */ new Map();
610
- const mainExport = exports(packageJson, ".", { browser: true });
611
- if (mainExport) for (const entry of mainExport) await addExportToMap(".", entry, srcPath, entries);
612
- if (!packageJson.exports) return entries;
613
- if (typeof packageJson.exports === "string") {
614
- await addExportToMap(name, packageJson.exports, srcPath, entries);
615
- return entries;
616
- }
617
- for (const [key, entry] of Object.entries(packageJson.exports)) if (typeof entry === "string") await addExportToMap(key, entry, srcPath, entries);
618
- else {
619
- const exportResult = exports(packageJson, key, { browser: true })?.at(0);
620
- if (exportResult) await addExportToMap(key, exportResult, srcPath, entries);
621
- else console.warn(`No browser exports found for ${name}/${key}`);
622
- }
623
- const main = entries.get(".");
624
- const resolvedExport = (main ? Array.from(entries.entries()).find(([key, entry]) => key != "." && [entry.file, `./${entry.file}`].includes(main.file)) : void 0)?.at(1);
625
- if (resolvedExport) entries.set(".", {
626
- export: resolvedExport.export,
627
- file: resolvedExport.file
628
- });
629
- return entries;
630
- }
631
- function importFromEsmSh(name, version, dependencies) {
632
- const lib = `${name}${version ? `@${version}` : ""}`;
633
- const query = dependencies?.length ? `&deps=${dependencies.join(",")}` : "";
634
- return {
635
- [name]: `https://esm.sh/${lib}${query}`,
636
- [`${name}/`]: `https://esm.sh/${lib}${query}/`
637
- };
638
- }
639
- async function importFromNodeModules(name, modulesDir, importMapDeps, baseUrl) {
640
- const importMap = {};
641
- const { packageJson, path: srcPath } = await findPackageJson(name);
642
- const entries = await getPackageExports(name, packageJson, srcPath);
643
- if (!entries.size) throw new Error(`No browser exports found for ${name}`);
644
- const indexFile = entries.get("")?.export || "index";
645
- const fileName = path.basename(entries.get("")?.export || "index", path.extname(indexFile));
646
- const outputPath = path.join(modulesDir, name);
647
- const buildModule = () => {
648
- console.log(`Bundling dependency: ${name}`);
649
- return build({
650
- entryPoints: Array.from(entries.values()).map((value) => path.join(srcPath, value.file)),
651
- outdir: outputPath,
652
- bundle: true,
653
- format: "esm",
654
- platform: "browser",
655
- target: "esnext",
656
- splitting: true,
657
- external: nodeModules.concat(Array.from(importMapDeps)),
658
- sourcemap: true,
659
- minify: false
660
- });
661
- };
662
- importMap[name] = `./modules/${name}/${fileName}.js`;
663
- entries.forEach((entry, key) => {
664
- importMap[path.join(name, key)] = path.join(baseUrl, `./modules/${path.join(name, entry.export)}`);
665
- });
666
- return {
667
- importMap,
668
- buildModule
669
- };
670
- }
671
- async function generateImportMap(outputDir, dependencies, baseUrl) {
672
- const modulesDir = path.join(outputDir, "/modules");
673
- await fs$1.mkdir(modulesDir, { recursive: true });
674
- const importMapDeps = new Set(dependencies.map((dep) => typeof dep === "string" ? dep : dep.name));
675
- let importMap = {};
676
- const buildModules = [];
677
- for (const dependency of dependencies) {
678
- const isString = typeof dependency === "string";
679
- const name = isString ? dependency : dependency.name;
680
- const version = isString ? void 0 : dependency.version;
681
- const provider = isString ? "node_modules" : dependency.provider;
682
- const subDependencies = isString ? void 0 : dependency.dependencies;
683
- if (provider === "esm.sh") {
684
- const imports = importFromEsmSh(name, version, subDependencies);
685
- importMap = {
686
- ...importMap,
687
- ...imports
688
- };
689
- } else if (provider.toString() === "node_modules") {
690
- const { importMap: imports, buildModule } = await importFromNodeModules(name, modulesDir, importMapDeps, baseUrl);
691
- importMap = {
692
- ...importMap,
693
- ...imports
694
- };
695
- buildModules.push(buildModule);
696
- } else throw new Error(`Unsupported provider: ${provider}`);
697
- }
698
- return {
699
- importMap,
700
- buildModules: async () => {
701
- await Promise.all(buildModules.map((build) => build()));
702
- }
703
- };
704
- }
705
- function addImportMapToHTML(importMap, html) {
706
- let newHtml = "";
707
- const importMapRegex = /<script type="importmap">(.*?)<\/script>/s;
708
- const match = importMapRegex.exec(html);
709
- if (match) try {
710
- const existingImportMap = JSON.parse(match[1]);
711
- existingImportMap.imports = {
712
- ...existingImportMap.imports,
713
- ...importMap
714
- };
715
- const mergedImportMapString = JSON.stringify(existingImportMap, null, 2);
716
- newHtml = html.replace(importMapRegex, `<script type="importmap">${mergedImportMapString}<\/script>`);
717
- } catch (error) {
718
- console.error("⚠️ Error parsing existing import map:", error);
719
- }
720
- else {
721
- const importMapScript = `<script type="importmap">${JSON.stringify({ imports: importMap }, null, 2)}<\/script>`;
722
- newHtml = html.replace("</head>", `${importMapScript}\n</head>`);
723
- }
724
- return newHtml;
725
- }
726
- /**
727
- * Vite plugin to bundle or copy dependencies and inject an import map into `index.html`.
728
- *
729
- * @param {string} outputDir - The directory where the modules should be placed.
730
- * @param {(string | { name: string; provider: string })[]} dependencies -
731
- * List of dependencies to process. Can be:
732
- * - A string (dependency is copied as is).
733
- * - An object `{ name, provide }` where:
734
- * - `name` (string): The module name.
735
- * - `provider` (string): Where to retrieve the module bundle. Defaults to node_modules.
736
- *
737
- * @returns {Plugin} A Vite plugin that processes dependencies and injects an import map.
738
- */
739
- function generateImportMapPlugin(outputDir, dependencies) {
740
- let buildModules = void 0;
741
- let importMap = {};
742
- return [{
743
- name: "vite-plugin-importmap",
744
- enforce: "post",
745
- async configResolved(config) {
746
- const result = await generateImportMap(outputDir, dependencies, config.base);
747
- importMap = result.importMap;
748
- buildModules = result.buildModules;
749
- },
750
- closeBundle() {
751
- return buildModules?.();
752
- },
753
- configureServer() {
754
- return buildModules?.();
755
- },
756
- transformIndexHtml(html) {
757
- return addImportMapToHTML(importMap, html) || html;
758
- }
759
- }];
760
- }
761
- //#endregion
762
- //#region connect-utils/vite-plugins/studio.ts
763
- function viteConnectDevStudioPlugin(enabled = false, connectPath, env) {
764
- return [enabled && viteIgnoreStaticImport([
765
- "react",
766
- "react-dom",
767
- ...externalIds
768
- ]), {
769
- name: "vite-plugin-connect-dev-studio",
770
- enforce: "pre",
771
- config(config) {
772
- if (!config.build) config.build = {};
773
- if (!config.build.rollupOptions) config.build.rollupOptions = {};
774
- if (!Array.isArray(config.build.rollupOptions.external)) config.build.rollupOptions.external = [];
775
- if (enabled) config.build.rollupOptions.external.push(...externalIds);
776
- },
777
- closeBundle() {
778
- if (!enabled) fs.copyFileSync(join(connectPath, "../.env"), join(connectPath, ".env"));
779
- }
780
- }];
781
- }
782
- //#endregion
783
- export { DEFAULT_CONNECT_OUTDIR, EXTERNAL_PACKAGES_IMPORT, IMPORT_SCRIPT_FILE, LOCAL_PACKAGE_ID, PH_DIR_NAME, appendToHtmlHead, backupIndexHtml, commonConnectOptionsToEnv, copyConnect, ensureNodeVersion, externalIds, findPackageJson, generateImportMapPlugin, getConnectBaseViteConfig, getConnectHtmlTags, makeImportScriptFromPackages, phPackagesPlugin, prependToHtmlHead, readJsonFile, removeBase64EnvValues, resolveConnectBundle, resolveConnectPackageJson, resolveConnectPublicDir, resolvePackage, resolveViteConfigPath, runShellScriptPlugin, runTsc, stripVersionFromPackage, viteConnectDevStudioPlugin, viteIgnoreStaticImport, viteReplaceImports };
470
+ export { DEFAULT_CONNECT_OUTDIR, EXTERNAL_PACKAGES_IMPORT, IMPORT_SCRIPT_FILE, LOCAL_PACKAGE_ID, PH_DIR_NAME, appendToHtmlHead, backupIndexHtml, commonConnectOptionsToEnv, copyConnect, ensureNodeVersion, getConnectBaseViteConfig, getConnectHtmlTags, makeImportScriptFromPackages, phPackagesPlugin, prependToHtmlHead, readJsonFile, removeBase64EnvValues, resolveConnectBundle, resolveConnectPackageJson, resolveConnectPublicDir, resolvePackage, resolveViteConfigPath, runShellScriptPlugin, runTsc, stripVersionFromPackage };
784
471
 
785
472
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["fs","fs"],"sources":["../connect-utils/constants.ts","../connect-utils/helpers.ts","../connect-utils/vite-plugins/favicon.ts","../connect-utils/vite-plugins/ph-packages.ts","../connect-utils/vite-config.ts","../connect-utils/vite-plugins/base.ts","../connect-utils/vite-plugins/importmap.ts","../connect-utils/vite-plugins/studio.ts"],"sourcesContent":["export const EXTERNAL_PACKAGES_IMPORT = \"PH:EXTERNAL_PACKAGES\";\nexport const IMPORT_SCRIPT_FILE = \"external-packages.js\";\nexport const LOCAL_PACKAGE_ID = \"ph:local-package\";\nexport const PH_DIR_NAME = \".ph\";\n","import type { PowerhouseConfig } from \"@powerhousedao/config\";\nimport { exec, execSync } from \"node:child_process\";\nimport fs, { existsSync } from \"node:fs\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport path, { join, resolve } from \"node:path\";\nimport { cwd } from \"node:process\";\nimport type { Plugin } from \"vite\";\nimport { LOCAL_PACKAGE_ID } from \"./constants.js\";\nimport { setConnectEnv } from \"@powerhousedao/shared/connect\";\nimport type { ConnectCommonOptions } from \"./types.js\";\n\nexport const DEFAULT_CONNECT_OUTDIR = \".ph/connect-build/dist/\" as const;\n\nexport function commonConnectOptionsToEnv(options: ConnectCommonOptions) {\n const {\n base,\n configFile,\n defaultDrivesUrl,\n drivesPreserveStrategy,\n disableLocalPackage,\n } = options;\n\n if (base) {\n setConnectEnv({\n PH_CONNECT_BASE_PATH: base,\n });\n }\n\n if (configFile) {\n setConnectEnv({\n PH_CONFIG_PATH: configFile,\n });\n }\n if (defaultDrivesUrl) {\n setConnectEnv({\n PH_CONNECT_DEFAULT_DRIVES_URL: defaultDrivesUrl.join(\",\"),\n });\n }\n if (drivesPreserveStrategy) {\n setConnectEnv({\n PH_CONNECT_DRIVES_PRESERVE_STRATEGY: drivesPreserveStrategy,\n });\n }\n if (disableLocalPackage) {\n setConnectEnv({\n PH_DISABLE_LOCAL_PACKAGE: true,\n });\n }\n}\n\nexport function resolveViteConfigPath(\n options: Pick<ConnectCommonOptions, \"projectRoot\" | \"viteConfigFile\">,\n) {\n const { projectRoot = cwd(), viteConfigFile } = options;\n return viteConfigFile || join(projectRoot, \"vite.config.ts\");\n}\n\nexport function resolvePackage(packageName: string, root = process.cwd()) {\n // find connect installation\n const require = createRequire(root);\n return require.resolve(packageName, { paths: [root] });\n}\n\nexport function resolveConnectPackageJson(root = process.cwd()) {\n try {\n const connectPackageJsonPath = resolvePackage(\n \"@powerhousedao/connect/package.json\",\n root,\n );\n const fileContents = fs.readFileSync(connectPackageJsonPath, \"utf-8\");\n return JSON.parse(fileContents) as JSON;\n } catch (error) {\n console.error(`Error reading Connect package.json:`, error);\n return null;\n }\n}\n\n/**\n * Finds the dist dir of Connect on the local machine\n */\nexport function resolveConnectBundle(root = process.cwd()) {\n const connectIndexPath = resolvePackage(\"@powerhousedao/connect\", root);\n const connectRootPath = connectIndexPath.substring(\n 0,\n connectIndexPath.indexOf(\"connect\") + \"connect\".length,\n );\n return join(connectRootPath, \"dist/\");\n}\n\nexport function resolveConnectPublicDir(root = process.cwd()) {\n const connectIconPath = resolvePackage(\n \"@powerhousedao/connect/public/icon.ico\",\n root,\n );\n return path.join(connectIconPath, \"../\");\n}\n\n/**\n * Copies the Connect dist dir to the target path\n */\nexport function copyConnect(sourcePath: string, targetPath: string) {\n try {\n // Ensure targetPath is removed before copying\n fs.rmSync(targetPath, { recursive: true, force: true });\n\n // Copy everything from sourcePath to targetPath\n fs.cpSync(sourcePath, targetPath, { recursive: true });\n } catch (error) {\n console.error(`❌ Error copying ${sourcePath} to ${targetPath}:`, error);\n }\n}\n\n/**\n * Backs up the index.html file\n *\n * Needed when running the Connect Studio dev server on Windows\n */\nexport function backupIndexHtml(appPath: string, restore = false) {\n const filePath = join(appPath, \"index.html\");\n const backupPath = join(appPath, \"index.html.bak\");\n\n const paths = restore ? [backupPath, filePath] : [filePath, backupPath];\n\n if (fs.existsSync(paths[0])) {\n fs.copyFileSync(paths[0], paths[1]);\n }\n}\n\nexport function removeBase64EnvValues(appPath: string) {\n backupIndexHtml(appPath);\n\n const filePath = join(appPath, \"index.html\");\n\n // Read the HTML file\n fs.readFile(filePath, \"utf-8\", (err, data) => {\n if (err) {\n console.error(\"Error reading file:\", err);\n return;\n }\n\n // Use regex to replace the dynamic Base64 values with empty strings\n // TODO is this needed?\n const modifiedData = data\n .replace(\n /\"LOCAL_DOCUMENT_MODELS\":\\s*\".*?\",/,\n `\"LOCAL_DOCUMENT_MODELS\": \"\",`,\n )\n .replace(\n /\"LOCAL_DOCUMENT_EDITORS\":\\s*\".*?\"/,\n `\"LOCAL_DOCUMENT_EDITORS\": \"\"`,\n );\n\n console.log(\"Modified data:\", modifiedData);\n // Write the modified content back to the file\n fs.writeFile(filePath, modifiedData, \"utf-8\", (err) => {\n if (err) {\n console.error(\"Error writing file:\", err);\n return;\n }\n });\n });\n}\n\nexport function readJsonFile(filePath: string): PowerhouseConfig | null {\n try {\n const absolutePath = resolve(filePath);\n const fileContents = fs.readFileSync(absolutePath, \"utf-8\");\n return JSON.parse(fileContents) as PowerhouseConfig;\n } catch (error) {\n console.error(`Error reading file: ${filePath}`);\n return null;\n }\n}\n\n/**\n * 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.\n */\nexport function makeImportScriptFromPackages(args: {\n packages: string[];\n importStyles?: boolean;\n localJsPath?: string;\n localCssPath?: string;\n}) {\n const { packages, localJsPath, localCssPath, importStyles = true } = args;\n const imports: string[] = [];\n const moduleNames: string[] = [];\n let counter = 0;\n\n for (const packageName of packages) {\n const moduleName = `module${counter}`;\n moduleNames.push(moduleName);\n imports.push(`import * as ${moduleName} from '${packageName}';`);\n if (importStyles) {\n imports.push(`import '${packageName}/style.css';`);\n }\n counter++;\n }\n\n const exports = moduleNames.map(\n (name, index) => `{\n id: \"${packages[index]}\",\n ...${name},\n }`,\n );\n\n const hasModule = localJsPath !== undefined;\n const hasStyles = importStyles && localCssPath !== undefined;\n const hasLocalPackage = hasModule || hasStyles;\n\n if (hasLocalPackage) {\n if (hasStyles) {\n imports.push(`import '${localCssPath}';`);\n }\n if (hasModule) {\n const moduleName = `module${counter}`;\n imports.push(`import * as ${moduleName} from '${localJsPath}';`);\n exports.push(`{\n id: \"${LOCAL_PACKAGE_ID}\",\n ...${moduleName},\n }`);\n }\n }\n const exportsString = exports.length\n ? `\n ${exports.join(\",\\n\")}\n `\n : \"\";\n\n const exportStatement = `export default [${exportsString}];`;\n\n const fileContent = `${imports.join(\"\\n\")}\\n\\n${exportStatement}`;\n\n return fileContent;\n}\n\nexport function ensureNodeVersion(minVersion = \"24\") {\n const version = process.versions.node;\n if (!version) {\n return;\n }\n\n if (version < minVersion) {\n console.error(\n `Node version ${minVersion} or higher is required. Current version: ${version}`,\n );\n process.exit(1);\n }\n}\n\nexport function runShellScriptPlugin(\n scriptName: string,\n connectPath: string,\n): Plugin {\n return {\n name: \"vite-plugin-run-shell-script\",\n buildStart() {\n const scriptPath = join(connectPath, scriptName);\n if (fs.existsSync(scriptPath)) {\n exec(`sh ${scriptPath}`, (error, stdout, stderr) => {\n if (error) {\n console.error(`Error executing the script: ${error.message}`);\n removeBase64EnvValues(connectPath);\n return;\n }\n if (stderr) {\n console.error(stderr);\n }\n });\n }\n },\n };\n}\n\n/**\n * Shared helper to modify the <head> tag of an HTML file by transforming its contents.\n */\nasync function modifyHtmlHead(\n pathToHtml: string,\n contents: string,\n transform: (html: string, contents: string) => string,\n) {\n if (!existsSync(pathToHtml)) {\n throw new Error(`File ${pathToHtml} does not exist.`);\n }\n let html = await readFile(pathToHtml, \"utf8\");\n html = transform(html, contents);\n await writeFile(pathToHtml, html, \"utf8\");\n}\n\n/**\n * Appends the contents to the <head> tag of the index.html file\n */\nexport async function appendToHtmlHead(pathToHtml: string, contents: string) {\n return modifyHtmlHead(pathToHtml, contents, (html, contents) => {\n if (!html.includes(\"</head>\")) {\n throw new Error(\"No </head> tag found in the HTML file.\");\n }\n return html.replace(\"</head>\", `\\n${contents}\\n</head>`);\n });\n}\n\n/**\n * Prepends the contents to the <head> tag of the index.html file\n */\nexport async function prependToHtmlHead(pathToHtml: string, contents: string) {\n return modifyHtmlHead(pathToHtml, contents, (html, contents) => {\n if (!html.includes(\"</head>\")) {\n throw new Error(\"No </head> tag found in the HTML file.\");\n }\n return html.replace(\"<head>\", `<head>\\n${contents}\\n`);\n });\n}\n\nexport function runTsc(outDir: string) {\n execSync(`npx tsc --outDir ${outDir}`, { stdio: \"inherit\" });\n}\n\n// Helper function to remove version suffix from package name\n// Handles formats like: @scope/package@version -> @scope/package\nexport function stripVersionFromPackage(packageName: string): string {\n const trimmed = packageName.trim();\n if (!trimmed) return \"\";\n const lastAtIndex = trimmed.lastIndexOf(\"@\");\n if (lastAtIndex > 0) {\n return trimmed.substring(0, lastAtIndex);\n }\n\n return trimmed;\n}\n","import { readFileSync } from \"node:fs\";\nimport type { Plugin } from \"vite\";\n\n/**\n * Vite plugin to serve the Connect favicon (icon.ico) from the connect package.\n * This ensures the favicon is available in development and included in the production build.\n */\nexport function connectFaviconPlugin(): Plugin {\n return {\n name: \"copy-connect-favicon\",\n configureServer(server) {\n // Serve icon.ico before Vite's static middleware so it acts as a fallback\n server.middlewares.use(\"/icon.ico\", (_req, res, next) => {\n server.pluginContainer\n .resolveId(\"@powerhousedao/connect/assets/icon.ico\")\n .then((resolved) => {\n if (!resolved) return next();\n res.setHeader(\"Content-Type\", \"image/x-icon\");\n res.end(readFileSync(resolved.id));\n })\n .catch(() => next());\n });\n },\n async generateBundle(_options, bundle) {\n try {\n if (\"icon.ico\" in bundle) return;\n const resolved = await this.resolve(\n \"@powerhousedao/connect/assets/icon.ico\",\n );\n if (!resolved) return;\n this.emitFile({\n type: \"asset\",\n fileName: \"icon.ico\",\n source: readFileSync(resolved.id),\n });\n } catch {\n // connect package not found, skip favicon\n }\n },\n };\n}\n","import type { Plugin } from \"vite\";\n\nexport type PhPackagesPluginOptions = {\n packages: string[];\n};\n\nexport function phPackagesPlugin(options: PhPackagesPluginOptions): Plugin {\n const content = JSON.stringify(\n {\n packages: options.packages,\n },\n null,\n 2,\n );\n\n return {\n name: \"vite-plugin-ph-packages\",\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n if (req.url?.endsWith(\"/ph-packages.json\")) {\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(content);\n return;\n }\n next();\n });\n },\n hotUpdate: {\n order: \"pre\",\n handler(ctx) {\n // filter out modules only imported by \"style.css\"\n // to avoid page reloads triggered by tailwind\n return ctx.modules.filter((mod) => {\n if (mod.importers.size > 1) {\n return true;\n }\n const importer = mod.importers.values().next();\n return !importer.value?.file?.endsWith(\".css\");\n });\n },\n },\n generateBundle() {\n this.emitFile({\n type: \"asset\",\n fileName: \"ph-packages.json\",\n source: content,\n });\n },\n };\n}\n","import type { PowerhouseConfig } from \"@powerhousedao/config\";\nimport { getConfig } from \"@powerhousedao/config/node\";\nimport { loadConnectEnv, setConnectEnv } from \"@powerhousedao/shared/connect\";\nimport { sentryVitePlugin } from \"@sentry/vite-plugin\";\nimport tailwind from \"@tailwindcss/vite\";\nimport react from \"@vitejs/plugin-react\";\nimport { join } from \"node:path\";\nimport {\n createLogger,\n esmExternalRequirePlugin,\n loadEnv,\n type HtmlTagDescriptor,\n type InlineConfig,\n type PluginOption,\n} from \"vite\";\nimport { createHtmlPlugin } from \"vite-plugin-html\";\nimport type { IConnectOptions } from \"./types.js\";\nimport { connectFaviconPlugin } from \"./vite-plugins/favicon.js\";\nimport { phPackagesPlugin } from \"./vite-plugins/ph-packages.js\";\n\nexport function getConnectHtmlTags(\n options: {\n registryUrl?: string | null;\n injectTo?: HtmlTagDescriptor[\"injectTo\"];\n } = {},\n) {\n const { registryUrl, injectTo = \"head\" } = options;\n return [\n {\n tag: \"meta\",\n attrs: {\n \"http-equiv\": \"Content-Security-Policy\",\n content: `script-src 'self' 'unsafe-inline' 'unsafe-eval' https://esm.sh${registryUrl ? \" \" + registryUrl : \"\"}; object-src 'none'; base-uri 'self';`,\n },\n injectTo,\n },\n {\n tag: \"meta\",\n attrs: {\n property: \"og:title\",\n content: \"Connect\",\n },\n injectTo,\n },\n {\n tag: \"meta\",\n attrs: {\n property: \"og:type\",\n content: \"website\",\n },\n injectTo,\n },\n {\n tag: \"meta\",\n attrs: {\n property: \"og:url\",\n content: \"https://apps.powerhouse.io/powerhouse/connect/\",\n },\n injectTo,\n },\n {\n tag: \"meta\",\n attrs: {\n property: \"og:description\",\n content:\n \"Navigate your organisation’s toughest operational challenges and steer your contributors to success with Connect. A navigation, collaboration and reporting tool for decentralised and open organisation.\",\n },\n injectTo,\n },\n {\n tag: \"meta\",\n attrs: {\n property: \"og:image\",\n content:\n \"https://cf-ipfs.com/ipfs/bafkreigrmclndf2jpbolaq22535q2sw5t44uad3az3dpvkzrnt4lpjt63e\",\n },\n injectTo,\n },\n {\n tag: \"meta\",\n attrs: {\n name: \"twitter:card\",\n content: \"summary_large_image\",\n },\n injectTo,\n },\n {\n tag: \"meta\",\n attrs: {\n name: \"twitter:image\",\n content:\n \"https://cf-ipfs.com/ipfs/bafkreigrmclndf2jpbolaq22535q2sw5t44uad3az3dpvkzrnt4lpjt63e\",\n },\n injectTo,\n },\n {\n tag: \"meta\",\n attrs: {\n name: \"twitter:title\",\n content: \"Connect\",\n },\n injectTo,\n },\n {\n tag: \"meta\",\n attrs: {\n name: \"twitter:description\",\n content:\n \"Navigate your organisation’s toughest operational challenges and steer your contributors to success with Connect. A navigation, collaboration and reporting tool for decentralised and open organisation.\",\n },\n injectTo,\n },\n ] as const satisfies HtmlTagDescriptor[];\n}\n\nfunction viteLogger({\n silence,\n}: {\n silence?: { warnings?: string[]; errors?: string[] };\n}) {\n const logger = createLogger();\n const loggerWarn = logger.warn.bind(logger);\n const loggerError = logger.error.bind(logger);\n\n logger.warn = (msg, options) => {\n if (silence?.warnings?.some((warning) => msg.includes(warning))) {\n return;\n }\n loggerWarn(msg, options);\n };\n\n logger.error = (msg, options) => {\n if (silence?.errors?.some((error) => msg.includes(error))) {\n return;\n }\n loggerError(msg, options);\n };\n\n return logger;\n}\n\nfunction getPackageNamesFromPowerhouseConfig({ packages }: PowerhouseConfig) {\n if (!packages) return [];\n return packages.map((p) => p.packageName);\n}\n\nexport function getConnectBaseViteConfig(options: IConnectOptions) {\n const mode = options.mode;\n const envDir = options.envDir ?? options.dirname;\n const fileEnv = loadEnv(mode, envDir, \"PH_\");\n\n // Load and validate environment with priority: process.env > options > fileEnv > defaults\n const env = loadConnectEnv({\n processEnv: process.env,\n fileEnv,\n });\n\n // set the resolved env to process.env so it's loaded by vite\n setConnectEnv(env);\n\n // load powerhouse config\n const phConfigPath =\n env.PH_CONFIG_PATH ?? join(options.dirname, \"powerhouse.config.json\");\n\n const phConfig = options.powerhouseConfig ?? getConfig(phConfigPath);\n\n const packagesFromConfig = getPackageNamesFromPowerhouseConfig(phConfig);\n const phPackagesStr = env.PH_PACKAGES;\n const envPhPackages = phPackagesStr?.split(\",\");\n\n const phPackages = envPhPackages ?? packagesFromConfig;\n\n const phPackageRegistryUrl =\n env.PH_CONNECT_PACKAGES_REGISTRY ?? phConfig.packageRegistryUrl ?? null;\n\n const authToken = env.PH_SENTRY_AUTH_TOKEN;\n const org = env.PH_SENTRY_ORG;\n const project = env.PH_SENTRY_PROJECT;\n const release = env.PH_CONNECT_SENTRY_RELEASE || env.PH_CONNECT_VERSION;\n const uploadSentrySourcemaps = authToken && org && project;\n\n const connectHtmlTags = getConnectHtmlTags({\n registryUrl: phPackageRegistryUrl,\n });\n\n const plugins: PluginOption[] = [\n tailwind(),\n react(),\n createHtmlPlugin({\n minify: false,\n inject: {\n tags: [\n ...connectHtmlTags,\n {\n tag: \"script\",\n attrs: { type: \"importmap\" },\n children: JSON.stringify(\n {\n imports: {\n react: \"https://esm.sh/react@19.2.0\",\n \"react/\": \"https://esm.sh/react@19.2.0/\",\n \"react-dom\": \"https://esm.sh/react-dom@19.2.0\",\n \"react-dom/\": \"https://esm.sh/react-dom@19.2.0/\",\n },\n },\n null,\n 2,\n ),\n injectTo: \"head-prepend\",\n },\n ],\n },\n }),\n ] as const;\n\n if (uploadSentrySourcemaps) {\n plugins.push(\n sentryVitePlugin({\n release: {\n name: release ?? \"unknown\",\n inject: false, // prevent it from injecting the release id in the service worker code, this is done in 'src/app/sentry.ts' instead\n },\n authToken,\n org,\n project,\n bundleSizeOptimizations: {\n excludeDebugStatements: true,\n },\n reactComponentAnnotation: {\n enabled: true,\n },\n }) as PluginOption,\n );\n }\n\n // hide warnings unless LOG_LEVEL is set to debug\n const isDebug =\n process.env.LOG_LEVEL === \"debug\" || env.PH_CONNECT_LOG_LEVEL === \"debug\";\n const customLogger = isDebug\n ? undefined\n : viteLogger({\n silence: {\n warnings: [\n \"@import must precede all other statements (besides @charset or empty @layer)\", // tailwindcss error when importing font file\n ],\n errors: [\"Unterminated string literal\"],\n },\n });\n\n const reactExternal = [\n \"react\",\n \"react-dom\",\n \"react/jsx-runtime\",\n \"react-dom/client\",\n ];\n\n const config: InlineConfig = {\n configFile: false,\n mode,\n server: {\n watch: {\n ignored: [\"**/backup-documents/**\", \"**/.ph/**\"],\n },\n },\n resolve: {\n tsconfigPaths: true,\n },\n define: {\n PH_PACKAGE_REGISTRY_URL: `\"${phPackageRegistryUrl}\"`,\n },\n customLogger,\n envPrefix: [\"PH_CONNECT_\"],\n optimizeDeps: {\n include: [\n \"document-model\",\n \"zod\",\n \"@powerhousedao/design-system/connect\",\n \"@powerhousedao/reactor-browser\",\n \"@powerhousedao/document-engineering\",\n ],\n exclude: [\"@electric-sql/pglite\", \"@electric-sql/pglite-tools\"],\n },\n plugins: [\n // phPackagesPlugin must be registered before tailwind so its hotUpdate\n // hook runs first and can suppress HMR updates for codegen-generated\n // files, preventing tailwind from triggering full page reloads.\n phPackagesPlugin({\n packages: phPackages,\n }),\n ...plugins,\n // Externalize React so both Connect and dynamically loaded registry\n // packages share the same React instance via the import map in index.html.\n // Without this, Vite bundles React into Connect's chunks while registry\n // packages resolve React from the import map (esm.sh), creating two\n // separate React instances that don't share context/state.\n //\n // In Vite 8 (Rolldown), require() calls for external modules are preserved\n // as-is, which fails in browsers. esmExternalRequirePlugin handles both\n // externalization AND converting require() to import statements.\n // NOTE: Do NOT also list these in build.rolldownOptions.external — overlapping\n // entries prevent the plugin from transforming require() calls.\n esmExternalRequirePlugin({ external: reactExternal }),\n connectFaviconPlugin(),\n ],\n worker: {\n format: \"es\",\n },\n build: {\n sourcemap: true,\n },\n };\n return config;\n}\n","import fs from \"fs/promises\";\nimport MagicString from \"magic-string\";\nimport { createRequire } from \"node:module\";\nimport { basename, dirname } from \"node:path\";\nimport type { Package } from \"resolve.exports\";\nimport type { Alias, AliasOptions, Plugin, PluginOption } from \"vite\";\n\n// matches @powerhousedao/connect, react, react-dom and all their sub-imports like react-dom/client\nexport const externalIds = [/^react(-dom)?(\\/.*)?$/, /^node:.*$/];\n\n// https://github.com/vitejs/vite/issues/6393#issuecomment-1006819717\n// vite dev server doesn't support setting dependencies as external\n// as when building the app.\nexport function viteIgnoreStaticImport(\n _importKeys: (string | RegExp | false | undefined)[],\n): Plugin {\n const importKeys = _importKeys.filter(\n (key) => typeof key === \"string\" || key instanceof RegExp,\n );\n return {\n name: \"vite-plugin-ignore-static-import\",\n enforce: \"pre\",\n // vite will still append /@id/ to an external import\n // so this will rewrite the 'vite:import-analysis' prefix\n configResolved(resolvedConfig) {\n const values = importKeys.map((key) =>\n typeof key === \"string\" ? key : key.source,\n );\n const reg = new RegExp(\n `(\"|')\\\\/@id\\\\/(${values.join(\"|\")})(\\\\/[^\"'\\\\\\\\]*)?\\\\1`,\n \"g\",\n );\n\n (resolvedConfig.plugins as Plugin[]).push({\n name: \"vite-plugin-ignore-static-import-replace-idprefix\",\n transform: (code) => {\n const s = new MagicString(code);\n const matches = code.matchAll(reg);\n let modified = false;\n\n for (const match of matches) {\n s.overwrite(\n match.index,\n match.index + match[0].length,\n match[0].replace(\"/@id/\", \"\"),\n );\n modified = true;\n }\n\n if (!modified) return null;\n\n return {\n code: s.toString(),\n map: s.generateMap({ hires: true }), // Generate an accurate source map\n };\n },\n });\n },\n // prevents the external import from being transformed to 'node_modules/...'\n resolveId: (id) => {\n if (\n importKeys.some((key) =>\n typeof key === \"string\" ? key === id : key.test(id),\n )\n ) {\n return { id, external: true };\n }\n },\n // returns empty string to prevent \"Pre-transform error: Failed to load url\"\n load(id) {\n if (\n importKeys.some((key) =>\n typeof key === \"string\" ? key === id : key.test(id),\n )\n ) {\n return \"\";\n }\n },\n };\n}\n\nexport function viteReplaceImports(\n imports: Record<string, string>,\n): PluginOption {\n const importKeys = Object.keys(imports);\n return {\n name: \"vite-plugin-connect-replace-imports\",\n enforce: \"pre\",\n config(config) {\n // adds the provided paths to be resolved by vite\n const resolve = config.resolve ?? {};\n const alias = resolve.alias;\n let resolvedAlias: AliasOptions | undefined;\n if (Array.isArray(alias)) {\n const arrayAlias = [...(alias as Alias[])];\n\n arrayAlias.push(\n ...Object.entries(imports).map(([find, replacement]) => ({\n find,\n replacement,\n })),\n );\n\n resolvedAlias = arrayAlias;\n } else if (typeof alias === \"object\") {\n resolvedAlias = {\n ...(alias as Record<string, string>),\n ...imports,\n };\n } else if (typeof alias === \"undefined\") {\n resolvedAlias = { ...imports };\n } else {\n console.error(\"resolve.alias was not recognized\");\n }\n\n if (resolvedAlias) {\n resolve.alias = resolvedAlias;\n config.resolve = resolve;\n }\n },\n resolveId: (id) => {\n // if the path was not provided then declares the local\n // imports as external so that vite ignores them\n if (importKeys.includes(id)) {\n return {\n id,\n external: true,\n };\n }\n },\n };\n}\n\nexport async function findPackageJson(packageName: string) {\n let packagePath;\n try {\n // Locate the package entry point\n const require = createRequire(process.cwd());\n packagePath = require.resolve(packageName, { paths: [process.cwd()] });\n } catch (err) {\n throw new Error(`Failed to resolve package: ${packageName}`, {\n cause: err,\n });\n }\n\n // Walk up the directory tree to find package.json\n let dir = dirname(packagePath);\n while (dir !== \"/\" && dir !== \".\" && dir !== \"node_modules\") {\n if (basename(dir) === \"dist\") {\n dir = dirname(dir);\n }\n const pkgJsonPath = `${dir}/package.json`;\n try {\n await fs.access(pkgJsonPath);\n const file = await fs.readFile(pkgJsonPath, \"utf-8\");\n return { packageJson: JSON.parse(file) as Package, path: dir };\n } catch {\n dir = dirname(dir); // Move up one level\n }\n }\n\n throw new Error(`package.json not found for ${packageName}`);\n}\n","import type { BuildResult } from \"esbuild\";\nimport { build } from \"esbuild\";\nimport fg from \"fast-glob\";\nimport fs from \"node:fs/promises\";\nimport { builtinModules } from \"node:module\";\nimport path from \"node:path\";\nimport type { Package } from \"resolve.exports\";\nimport { exports } from \"resolve.exports\";\nimport type { PluginOption } from \"vite\";\nimport { findPackageJson } from \"./base.js\";\n\nexport type Provider = \"node_modules\" | \"esm.sh\";\n\nexport type Dependency = {\n name: string;\n version?: string;\n provider: Provider;\n dependencies?: string[];\n};\n\nconst nodeModules = builtinModules.concat(\n builtinModules.map((m) => `node:${m}`),\n);\n\n/**\n * Resolves glob exports like `\"./*\": \"./dist/*.js\"` and `\"./utils/*\": \"./dist/utils/*.js\"`\n * into actual file mappings.\n *\n * @param {string} exportName - The export pattern (e.g., `\"./*\"` or `\"./utils/*\"`).\n * @param {string} exportPath - The actual path pattern (e.g., `\"./dist/*.js\"`).\n * @param {string} srcPath - The package root directory where the exports are located.\n * @returns {Promise<Record<string, string>>} - A mapping of export names to resolved paths.\n */\nasync function resolveGlobExport(\n exportName: string,\n exportPath: string,\n srcPath: string,\n) {\n const resolvedExports = new Map<string, { export: string; file: string }>();\n\n const hasGloblExport = exportName.endsWith(\"/*\");\n const globPath = hasGloblExport\n ? exportPath.replace(\"*\", \"**/*\")\n : exportPath;\n\n const distPath = exportPath.substring(0, exportPath.lastIndexOf(\"/*\"));\n const resolvedSrcPath = hasGloblExport\n ? path.join(srcPath.replace(\"*\", \"\"), distPath)\n : srcPath;\n\n const files = await fg(path.join(srcPath, globPath));\n\n for (const file of files) {\n const relativeSrcFilePath = path.relative(resolvedSrcPath, file); // Relative to the dist folder\n const exportFilePath = path.relative(srcPath, file); // Relative to package root\n const exportKey = relativeSrcFilePath.replace(path.extname(file), \"\"); // Remove .js extension\n const mappedExport = exportName.replace(\"*\", exportKey); // Replace glob `*` with actual name\n resolvedExports.set(mappedExport, {\n export: `./${relativeSrcFilePath}`,\n file: exportFilePath,\n }); // Final mapped entry\n }\n return resolvedExports;\n}\n\nasync function addExportToMap(\n exportName: string,\n exportPath: string,\n srcPath: string,\n map: Map<string, { export: string; file: string }>,\n) {\n if (exportName.includes(\"*\")) {\n const exports = await resolveGlobExport(exportName, exportPath, srcPath);\n exports.forEach((value, key) => map.set(key, value));\n } else {\n map.set(exportName, { export: exportPath, file: exportPath });\n }\n}\n\nasync function getPackageExports(\n name: string,\n packageJson: Package,\n srcPath: string,\n) {\n const entries = new Map<string, { export: string; file: string }>();\n const mainExport = exports(packageJson, \".\", {\n browser: true,\n });\n if (mainExport) {\n for (const entry of mainExport) {\n await addExportToMap(\".\", entry, srcPath, entries);\n }\n }\n\n if (!packageJson.exports) {\n return entries;\n }\n if (typeof packageJson.exports === \"string\") {\n await addExportToMap(name, packageJson.exports, srcPath, entries);\n return entries;\n }\n\n for (const [key, entry] of Object.entries(packageJson.exports)) {\n if (typeof entry === \"string\") {\n await addExportToMap(key, entry, srcPath, entries);\n } else {\n const exportEntry = exports(packageJson, key, {\n browser: true,\n });\n\n const exportResult = exportEntry?.at(0);\n if (exportResult) {\n await addExportToMap(key, exportResult, srcPath, entries);\n } else {\n console.warn(`No browser exports found for ${name}/${key}`);\n }\n }\n }\n\n // if the main entry file was resolved to a shorter path then updates it\n const main = entries.get(\".\");\n const resolvedEntry = main\n ? Array.from(entries.entries()).find(\n ([key, entry]) =>\n key != \".\" && [entry.file, `./${entry.file}`].includes(main.file),\n )\n : undefined;\n const resolvedExport = resolvedEntry?.at(1) as\n | {\n export: string;\n file: string;\n }\n | undefined;\n if (resolvedExport) {\n entries.set(\".\", {\n export: resolvedExport.export,\n file: resolvedExport.file,\n });\n }\n\n return entries;\n}\n\nfunction importFromEsmSh(\n name: string,\n version?: string,\n dependencies?: string[],\n) {\n const lib = `${name}${version ? `@${version}` : \"\"}`;\n const query = dependencies?.length ? `&deps=${dependencies.join(\",\")}` : \"\";\n return {\n [name]: `https://esm.sh/${lib}${query}`,\n [`${name}/`]: `https://esm.sh/${lib}${query}/`,\n };\n}\n\ntype BuildModule = () => Promise<BuildResult>;\n\nasync function importFromNodeModules(\n name: string,\n modulesDir: string,\n importMapDeps: Set<string>,\n baseUrl: string,\n): Promise<{ importMap: Record<string, string>; buildModule: BuildModule }> {\n const importMap: Record<string, string> = {};\n\n const { packageJson, path: srcPath } = await findPackageJson(name);\n const entries = await getPackageExports(name, packageJson, srcPath);\n\n if (!entries.size) {\n throw new Error(`No browser exports found for ${name}`);\n }\n\n const indexFile = entries.get(\"\")?.export || \"index\";\n const fileName = path.basename(\n entries.get(\"\")?.export || \"index\",\n path.extname(indexFile),\n );\n const outputPath = path.join(modulesDir, name);\n\n // Bundle and tree-shake only dependencies (exclude the actual library code)\n const buildModule = () => {\n console.log(`Bundling dependency: ${name}`);\n return build({\n entryPoints: Array.from(entries.values()).map((value) =>\n path.join(srcPath, value.file),\n ),\n outdir: outputPath,\n bundle: true,\n format: \"esm\",\n platform: \"browser\",\n target: \"esnext\",\n splitting: true,\n external: nodeModules.concat(Array.from(importMapDeps)), // Exclude dependencies already in import map\n sourcemap: true,\n minify: false,\n });\n };\n\n // Add entry to import map\n importMap[name] = `./modules/${name}/${fileName}.js`;\n\n entries.forEach((entry, key) => {\n importMap[path.join(name, key)] = path.join(\n baseUrl,\n `./modules/${path.join(name, entry.export)}`,\n );\n });\n\n return { importMap, buildModule };\n}\n\nasync function generateImportMap(\n outputDir: string,\n dependencies: (string | Dependency)[],\n baseUrl: string,\n): Promise<{\n importMap: Record<string, string>;\n buildModules: undefined | (() => Promise<void>);\n}> {\n const modulesDir = path.join(outputDir, \"/modules\");\n await fs.mkdir(modulesDir, { recursive: true });\n const importMapDeps = new Set(\n dependencies.map((dep) => (typeof dep === \"string\" ? dep : dep.name)),\n );\n\n let importMap: Record<string, string> = {};\n\n const buildModules: BuildModule[] = [];\n\n for (const dependency of dependencies) {\n const isString = typeof dependency === \"string\";\n const name = isString ? dependency : dependency.name;\n const version = isString ? undefined : dependency.version;\n const provider = isString ? \"node_modules\" : dependency.provider;\n const subDependencies = isString ? undefined : dependency.dependencies;\n\n if (provider === \"esm.sh\") {\n const imports = importFromEsmSh(name, version, subDependencies);\n importMap = { ...importMap, ...imports };\n // TODO: this does not make sense.\n // We need to give this the actual correct type, or if we really don't know what it is, then make it `unknown`\n } else if (provider.toString() === \"node_modules\") {\n const { importMap: imports, buildModule } = await importFromNodeModules(\n name,\n modulesDir,\n importMapDeps,\n baseUrl,\n );\n importMap = { ...importMap, ...imports };\n buildModules.push(buildModule);\n } else {\n throw new Error(`Unsupported provider: ${provider as string}`);\n }\n }\n\n return {\n importMap,\n buildModules: async () => {\n await Promise.all(buildModules.map((build) => build()));\n },\n };\n}\n\nfunction addImportMapToHTML(importMap: Record<string, string>, html: string) {\n let newHtml = \"\";\n\n // Regex to find existing import map\n const importMapRegex = /<script type=\"importmap\">(.*?)<\\/script>/s;\n const match = importMapRegex.exec(html);\n\n // If an import map exists, merge the imports\n if (match) {\n try {\n const existingImportMap = JSON.parse(match[1]) as {\n imports: Record<string, string>;\n };\n existingImportMap.imports = {\n ...existingImportMap.imports,\n ...importMap,\n };\n\n const mergedImportMapString = JSON.stringify(existingImportMap, null, 2);\n\n newHtml = html.replace(\n importMapRegex,\n `<script type=\"importmap\">${mergedImportMapString}</script>`,\n );\n } catch (error) {\n console.error(\"⚠️ Error parsing existing import map:\", error);\n }\n } else {\n const importMapString = JSON.stringify({ imports: importMap }, null, 2);\n const importMapScript = `<script type=\"importmap\">${importMapString}</script>`;\n newHtml = html.replace(\"</head>\", `${importMapScript}\\n</head>`);\n }\n return newHtml;\n}\n\n/**\n * Vite plugin to bundle or copy dependencies and inject an import map into `index.html`.\n *\n * @param {string} outputDir - The directory where the modules should be placed.\n * @param {(string | { name: string; provider: string })[]} dependencies -\n * List of dependencies to process. Can be:\n * - A string (dependency is copied as is).\n * - An object `{ name, provide }` where:\n * - `name` (string): The module name.\n * - `provider` (string): Where to retrieve the module bundle. Defaults to node_modules.\n *\n * @returns {Plugin} A Vite plugin that processes dependencies and injects an import map.\n */\nexport function generateImportMapPlugin(\n outputDir: string,\n dependencies: (string | Dependency)[],\n): PluginOption[] {\n let buildModules: (() => Promise<void>) | undefined = undefined;\n let importMap: Record<string, string> = {};\n return [\n {\n name: \"vite-plugin-importmap\",\n enforce: \"post\",\n // generates import map according to the base url\n // and collects build method for each dependency\n async configResolved(config) {\n const result = await generateImportMap(\n outputDir,\n dependencies,\n config.base,\n );\n importMap = result.importMap;\n buildModules = result.buildModules;\n },\n // builds modules when building the bundle\n closeBundle() {\n return buildModules?.();\n },\n // builds modules when starting the dev server\n configureServer() {\n return buildModules?.();\n },\n // adds importmap to the html\n transformIndexHtml(html) {\n const newHtml = addImportMapToHTML(importMap, html);\n return newHtml || html;\n },\n },\n ];\n}\n","import fs from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { PluginOption } from \"vite\";\nimport { externalIds, viteIgnoreStaticImport } from \"./base.js\";\n\nexport function viteConnectDevStudioPlugin(\n enabled = false,\n connectPath: string,\n env?: Record<string, string>,\n): PluginOption[] {\n return [\n enabled && viteIgnoreStaticImport([\"react\", \"react-dom\", ...externalIds]),\n {\n name: \"vite-plugin-connect-dev-studio\",\n enforce: \"pre\",\n config(config) {\n if (!config.build) {\n config.build = {};\n }\n if (!config.build.rollupOptions) {\n config.build.rollupOptions = {};\n }\n if (!Array.isArray(config.build.rollupOptions.external)) {\n config.build.rollupOptions.external = [];\n }\n\n if (enabled) {\n config.build.rollupOptions.external.push(...externalIds);\n }\n },\n closeBundle() {\n if (!enabled) {\n // Copy the .env file to the dist folder\n fs.copyFileSync(\n join(connectPath, \"../.env\"),\n join(connectPath, \".env\"),\n );\n }\n },\n },\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,MAAa,2BAA2B;AACxC,MAAa,qBAAqB;AAClC,MAAa,mBAAmB;AAChC,MAAa,cAAc;;;ACS3B,MAAa,yBAAyB;AAEtC,SAAgB,0BAA0B,SAA+B;CACvE,MAAM,EACJ,MACA,YACA,kBACA,wBACA,wBACE;AAEJ,KAAI,KACF,eAAc,EACZ,sBAAsB,MACvB,CAAC;AAGJ,KAAI,WACF,eAAc,EACZ,gBAAgB,YACjB,CAAC;AAEJ,KAAI,iBACF,eAAc,EACZ,+BAA+B,iBAAiB,KAAK,IAAI,EAC1D,CAAC;AAEJ,KAAI,uBACF,eAAc,EACZ,qCAAqC,wBACtC,CAAC;AAEJ,KAAI,oBACF,eAAc,EACZ,0BAA0B,MAC3B,CAAC;;AAIN,SAAgB,sBACd,SACA;CACA,MAAM,EAAE,cAAc,KAAK,EAAE,mBAAmB;AAChD,QAAO,kBAAkB,K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AM,cAAc,SAAS,CACrD,QAAO,MAAM,cAAc,WAAW,EAAE;AAG1C,OAAI,QACF,QAAO,MAAM,cAAc,SAAS,KAAK,GAAG,YAAY;;EAG5D,cAAc;AACZ,OAAI,CAAC,QAEH,IAAG,aACD,KAAK,aAAa,UAAU,EAC5B,KAAK,aAAa,OAAO,CAC1B;;EAGN,CACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../connect-utils/constants.ts","../connect-utils/helpers.ts","../connect-utils/vite-plugins/favicon.ts","../connect-utils/vite-plugins/ph-packages.ts","../connect-utils/vite-config.ts"],"sourcesContent":["export const EXTERNAL_PACKAGES_IMPORT = \"PH:EXTERNAL_PACKAGES\";\nexport const IMPORT_SCRIPT_FILE = \"external-packages.js\";\nexport const LOCAL_PACKAGE_ID = \"ph:local-package\";\nexport const PH_DIR_NAME = \".ph\";\n","import type { PowerhouseConfig } from \"@powerhousedao/config\";\nimport { exec, execSync } from \"node:child_process\";\nimport fs, { existsSync } from \"node:fs\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport path, { join, resolve } from \"node:path\";\nimport { cwd } from \"node:process\";\nimport type { Plugin } from \"vite\";\nimport { LOCAL_PACKAGE_ID } from \"./constants.js\";\nimport { setConnectEnv } from \"@powerhousedao/shared/connect\";\nimport type { ConnectCommonOptions } from \"./types.js\";\n\nexport const DEFAULT_CONNECT_OUTDIR = \".ph/connect-build/dist/\" as const;\n\nexport function commonConnectOptionsToEnv(options: ConnectCommonOptions) {\n const {\n base,\n configFile,\n defaultDrivesUrl,\n drivesPreserveStrategy,\n disableLocalPackage,\n } = options;\n\n if (base) {\n setConnectEnv({\n PH_CONNECT_BASE_PATH: base,\n });\n }\n\n if (configFile) {\n setConnectEnv({\n PH_CONFIG_PATH: configFile,\n });\n }\n if (defaultDrivesUrl) {\n setConnectEnv({\n PH_CONNECT_DEFAULT_DRIVES_URL: defaultDrivesUrl.join(\",\"),\n });\n }\n if (drivesPreserveStrategy) {\n setConnectEnv({\n PH_CONNECT_DRIVES_PRESERVE_STRATEGY: drivesPreserveStrategy,\n });\n }\n if (disableLocalPackage) {\n setConnectEnv({\n PH_DISABLE_LOCAL_PACKAGE: true,\n });\n }\n}\n\nexport function resolveViteConfigPath(\n options: Pick<ConnectCommonOptions, \"projectRoot\" | \"viteConfigFile\">,\n) {\n const { projectRoot = cwd(), viteConfigFile } = options;\n return viteConfigFile || join(projectRoot, \"vite.config.ts\");\n}\n\nexport function resolvePackage(packageName: string, root = process.cwd()) {\n // find connect installation\n const require = createRequire(root);\n return require.resolve(packageName, { paths: [root] });\n}\n\nexport function resolveConnectPackageJson(root = process.cwd()) {\n try {\n const connectPackageJsonPath = resolvePackage(\n \"@powerhousedao/connect/package.json\",\n root,\n );\n const fileContents = fs.readFileSync(connectPackageJsonPath, \"utf-8\");\n return JSON.parse(fileContents) as JSON;\n } catch (error) {\n console.error(`Error reading Connect package.json:`, error);\n return null;\n }\n}\n\n/**\n * Finds the dist dir of Connect on the local machine\n */\nexport function resolveConnectBundle(root = process.cwd()) {\n const connectIndexPath = resolvePackage(\"@powerhousedao/connect\", root);\n const connectRootPath = connectIndexPath.substring(\n 0,\n connectIndexPath.indexOf(\"connect\") + \"connect\".length,\n );\n return join(connectRootPath, \"dist/\");\n}\n\nexport function resolveConnectPublicDir(root = process.cwd()) {\n const connectIconPath = resolvePackage(\n \"@powerhousedao/connect/public/icon.ico\",\n root,\n );\n return path.join(connectIconPath, \"../\");\n}\n\n/**\n * Copies the Connect dist dir to the target path\n */\nexport function copyConnect(sourcePath: string, targetPath: string) {\n try {\n // Ensure targetPath is removed before copying\n fs.rmSync(targetPath, { recursive: true, force: true });\n\n // Copy everything from sourcePath to targetPath\n fs.cpSync(sourcePath, targetPath, { recursive: true });\n } catch (error) {\n console.error(`❌ Error copying ${sourcePath} to ${targetPath}:`, error);\n }\n}\n\n/**\n * Backs up the index.html file\n *\n * Needed when running the Connect Studio dev server on Windows\n */\nexport function backupIndexHtml(appPath: string, restore = false) {\n const filePath = join(appPath, \"index.html\");\n const backupPath = join(appPath, \"index.html.bak\");\n\n const paths = restore ? [backupPath, filePath] : [filePath, backupPath];\n\n if (fs.existsSync(paths[0])) {\n fs.copyFileSync(paths[0], paths[1]);\n }\n}\n\nexport function removeBase64EnvValues(appPath: string) {\n backupIndexHtml(appPath);\n\n const filePath = join(appPath, \"index.html\");\n\n // Read the HTML file\n fs.readFile(filePath, \"utf-8\", (err, data) => {\n if (err) {\n console.error(\"Error reading file:\", err);\n return;\n }\n\n // Use regex to replace the dynamic Base64 values with empty strings\n // TODO is this needed?\n const modifiedData = data\n .replace(\n /\"LOCAL_DOCUMENT_MODELS\":\\s*\".*?\",/,\n `\"LOCAL_DOCUMENT_MODELS\": \"\",`,\n )\n .replace(\n /\"LOCAL_DOCUMENT_EDITORS\":\\s*\".*?\"/,\n `\"LOCAL_DOCUMENT_EDITORS\": \"\"`,\n );\n\n console.log(\"Modified data:\", modifiedData);\n // Write the modified content back to the file\n fs.writeFile(filePath, modifiedData, \"utf-8\", (err) => {\n if (err) {\n console.error(\"Error writing file:\", err);\n return;\n }\n });\n });\n}\n\nexport function readJsonFile(filePath: string): PowerhouseConfig | null {\n try {\n const absolutePath = resolve(filePath);\n const fileContents = fs.readFileSync(absolutePath, \"utf-8\");\n return JSON.parse(fileContents) as PowerhouseConfig;\n } catch (error) {\n console.error(`Error reading file: ${filePath}`);\n return null;\n }\n}\n\n/**\n * 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.\n */\nexport function makeImportScriptFromPackages(args: {\n packages: string[];\n importStyles?: boolean;\n localJsPath?: string;\n localCssPath?: string;\n}) {\n const { packages, localJsPath, localCssPath, importStyles = true } = args;\n const imports: string[] = [];\n const moduleNames: string[] = [];\n let counter = 0;\n\n for (const packageName of packages) {\n const moduleName = `module${counter}`;\n moduleNames.push(moduleName);\n imports.push(`import * as ${moduleName} from '${packageName}';`);\n if (importStyles) {\n imports.push(`import '${packageName}/style.css';`);\n }\n counter++;\n }\n\n const exports = moduleNames.map(\n (name, index) => `{\n id: \"${packages[index]}\",\n ...${name},\n }`,\n );\n\n const hasModule = localJsPath !== undefined;\n const hasStyles = importStyles && localCssPath !== undefined;\n const hasLocalPackage = hasModule || hasStyles;\n\n if (hasLocalPackage) {\n if (hasStyles) {\n imports.push(`import '${localCssPath}';`);\n }\n if (hasModule) {\n const moduleName = `module${counter}`;\n imports.push(`import * as ${moduleName} from '${localJsPath}';`);\n exports.push(`{\n id: \"${LOCAL_PACKAGE_ID}\",\n ...${moduleName},\n }`);\n }\n }\n const exportsString = exports.length\n ? `\n ${exports.join(\",\\n\")}\n `\n : \"\";\n\n const exportStatement = `export default [${exportsString}];`;\n\n const fileContent = `${imports.join(\"\\n\")}\\n\\n${exportStatement}`;\n\n return fileContent;\n}\n\nexport function ensureNodeVersion(minVersion = \"24\") {\n const version = process.versions.node;\n if (!version) {\n return;\n }\n\n if (version < minVersion) {\n console.error(\n `Node version ${minVersion} or higher is required. Current version: ${version}`,\n );\n process.exit(1);\n }\n}\n\nexport function runShellScriptPlugin(\n scriptName: string,\n connectPath: string,\n): Plugin {\n return {\n name: \"vite-plugin-run-shell-script\",\n buildStart() {\n const scriptPath = join(connectPath, scriptName);\n if (fs.existsSync(scriptPath)) {\n exec(`sh ${scriptPath}`, (error, stdout, stderr) => {\n if (error) {\n console.error(`Error executing the script: ${error.message}`);\n removeBase64EnvValues(connectPath);\n return;\n }\n if (stderr) {\n console.error(stderr);\n }\n });\n }\n },\n };\n}\n\n/**\n * Shared helper to modify the <head> tag of an HTML file by transforming its contents.\n */\nasync function modifyHtmlHead(\n pathToHtml: string,\n contents: string,\n transform: (html: string, contents: string) => string,\n) {\n if (!existsSync(pathToHtml)) {\n throw new Error(`File ${pathToHtml} does not exist.`);\n }\n let html = await readFile(pathToHtml, \"utf8\");\n html = transform(html, contents);\n await writeFile(pathToHtml, html, \"utf8\");\n}\n\n/**\n * Appends the contents to the <head> tag of the index.html file\n */\nexport async function appendToHtmlHead(pathToHtml: string, contents: string) {\n return modifyHtmlHead(pathToHtml, contents, (html, contents) => {\n if (!html.includes(\"</head>\")) {\n throw new Error(\"No </head> tag found in the HTML file.\");\n }\n return html.replace(\"</head>\", `\\n${contents}\\n</head>`);\n });\n}\n\n/**\n * Prepends the contents to the <head> tag of the index.html file\n */\nexport async function prependToHtmlHead(pathToHtml: string, contents: string) {\n return modifyHtmlHead(pathToHtml, contents, (html, contents) => {\n if (!html.includes(\"</head>\")) {\n throw new Error(\"No </head> tag found in the HTML file.\");\n }\n return html.replace(\"<head>\", `<head>\\n${contents}\\n`);\n });\n}\n\nexport function runTsc(outDir: string) {\n execSync(`npx tsc --outDir ${outDir}`, { stdio: \"inherit\" });\n}\n\n// Helper function to remove version suffix from package name\n// Handles formats like: @scope/package@version -> @scope/package\nexport function stripVersionFromPackage(packageName: string): string {\n const trimmed = packageName.trim();\n if (!trimmed) return \"\";\n const lastAtIndex = trimmed.lastIndexOf(\"@\");\n if (lastAtIndex > 0) {\n return trimmed.substring(0, lastAtIndex);\n }\n\n return trimmed;\n}\n","import { readFileSync } from \"node:fs\";\nimport type { Plugin } from \"vite\";\n\n/**\n * Vite plugin to serve the Connect favicon (icon.ico) from the connect package.\n * This ensures the favicon is available in development and included in the production build.\n */\nexport function connectFaviconPlugin(): Plugin {\n return {\n name: \"copy-connect-favicon\",\n configureServer(server) {\n // Serve icon.ico before Vite's static middleware so it acts as a fallback\n server.middlewares.use(\"/icon.ico\", (_req, res, next) => {\n server.pluginContainer\n .resolveId(\"@powerhousedao/connect/assets/icon.ico\")\n .then((resolved) => {\n if (!resolved) return next();\n res.setHeader(\"Content-Type\", \"image/x-icon\");\n res.end(readFileSync(resolved.id));\n })\n .catch(() => next());\n });\n },\n async generateBundle(_options, bundle) {\n try {\n if (\"icon.ico\" in bundle) return;\n const resolved = await this.resolve(\n \"@powerhousedao/connect/assets/icon.ico\",\n );\n if (!resolved) return;\n this.emitFile({\n type: \"asset\",\n fileName: \"icon.ico\",\n source: readFileSync(resolved.id),\n });\n } catch {\n // connect package not found, skip favicon\n }\n },\n };\n}\n","import type { Plugin } from \"vite\";\n\nexport type PhPackagesPluginOptions = {\n packages: string[];\n};\n\nexport function phPackagesPlugin(options: PhPackagesPluginOptions): Plugin {\n const content = JSON.stringify(\n {\n packages: options.packages,\n },\n null,\n 2,\n );\n\n return {\n name: \"vite-plugin-ph-packages\",\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n if (req.url?.endsWith(\"/ph-packages.json\")) {\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(content);\n return;\n }\n next();\n });\n },\n hotUpdate: {\n order: \"pre\",\n handler(ctx) {\n // filter out modules only imported by \"style.css\"\n // to avoid page reloads triggered by tailwind\n return ctx.modules.filter((mod) => {\n if (mod.importers.size > 1) {\n return true;\n }\n const importer = mod.importers.values().next();\n return !importer.value?.file?.endsWith(\".css\");\n });\n },\n },\n generateBundle() {\n this.emitFile({\n type: \"asset\",\n fileName: \"ph-packages.json\",\n source: content,\n });\n },\n };\n}\n","import type { PowerhouseConfig } from \"@powerhousedao/config\";\nimport { getConfig } from \"@powerhousedao/config/node\";\nimport { loadConnectEnv, setConnectEnv } from \"@powerhousedao/shared/connect\";\nimport { sentryVitePlugin } from \"@sentry/vite-plugin\";\nimport tailwind from \"@tailwindcss/vite\";\nimport react from \"@vitejs/plugin-react\";\nimport { join } from \"node:path\";\nimport {\n createLogger,\n esmExternalRequirePlugin,\n loadEnv,\n type HtmlTagDescriptor,\n type InlineConfig,\n type PluginOption,\n} from \"vite\";\nimport { createHtmlPlugin } from \"vite-plugin-html\";\nimport type { IConnectOptions } from \"./types.js\";\nimport { connectFaviconPlugin } from \"./vite-plugins/favicon.js\";\nimport { phPackagesPlugin } from \"./vite-plugins/ph-packages.js\";\n\nexport function getConnectHtmlTags(\n options: {\n registryUrl?: string | null;\n injectTo?: HtmlTagDescriptor[\"injectTo\"];\n } = {},\n) {\n const { registryUrl, injectTo = \"head\" } = options;\n return [\n {\n tag: \"meta\",\n attrs: {\n \"http-equiv\": \"Content-Security-Policy\",\n content: `script-src 'self' 'unsafe-inline' 'unsafe-eval' https://esm.sh${registryUrl ? \" \" + registryUrl : \"\"}; object-src 'none'; base-uri 'self';`,\n },\n injectTo,\n },\n {\n tag: \"meta\",\n attrs: {\n property: \"og:title\",\n content: \"Connect\",\n },\n injectTo,\n },\n {\n tag: \"meta\",\n attrs: {\n property: \"og:type\",\n content: \"website\",\n },\n injectTo,\n },\n {\n tag: \"meta\",\n attrs: {\n property: \"og:url\",\n content: \"https://apps.powerhouse.io/powerhouse/connect/\",\n },\n injectTo,\n },\n {\n tag: \"meta\",\n attrs: {\n property: \"og:description\",\n content:\n \"Navigate your organisation’s toughest operational challenges and steer your contributors to success with Connect. A navigation, collaboration and reporting tool for decentralised and open organisation.\",\n },\n injectTo,\n },\n {\n tag: \"meta\",\n attrs: {\n property: \"og:image\",\n content:\n \"https://cf-ipfs.com/ipfs/bafkreigrmclndf2jpbolaq22535q2sw5t44uad3az3dpvkzrnt4lpjt63e\",\n },\n injectTo,\n },\n {\n tag: \"meta\",\n attrs: {\n name: \"twitter:card\",\n content: \"summary_large_image\",\n },\n injectTo,\n },\n {\n tag: \"meta\",\n attrs: {\n name: \"twitter:image\",\n content:\n \"https://cf-ipfs.com/ipfs/bafkreigrmclndf2jpbolaq22535q2sw5t44uad3az3dpvkzrnt4lpjt63e\",\n },\n injectTo,\n },\n {\n tag: \"meta\",\n attrs: {\n name: \"twitter:title\",\n content: \"Connect\",\n },\n injectTo,\n },\n {\n tag: \"meta\",\n attrs: {\n name: \"twitter:description\",\n content:\n \"Navigate your organisation’s toughest operational challenges and steer your contributors to success with Connect. A navigation, collaboration and reporting tool for decentralised and open organisation.\",\n },\n injectTo,\n },\n ] as const satisfies HtmlTagDescriptor[];\n}\n\nfunction viteLogger({\n silence,\n}: {\n silence?: { warnings?: string[]; errors?: string[] };\n}) {\n const logger = createLogger();\n const loggerWarn = logger.warn.bind(logger);\n const loggerError = logger.error.bind(logger);\n\n logger.warn = (msg, options) => {\n if (silence?.warnings?.some((warning) => msg.includes(warning))) {\n return;\n }\n loggerWarn(msg, options);\n };\n\n logger.error = (msg, options) => {\n if (silence?.errors?.some((error) => msg.includes(error))) {\n return;\n }\n loggerError(msg, options);\n };\n\n return logger;\n}\n\nfunction getPackageNamesFromPowerhouseConfig({ packages }: PowerhouseConfig) {\n if (!packages) return [];\n return packages.map((p) => p.packageName);\n}\n\nexport function getConnectBaseViteConfig(options: IConnectOptions) {\n const mode = options.mode;\n const envDir = options.envDir ?? options.dirname;\n const fileEnv = loadEnv(mode, envDir, \"PH_\");\n\n // Load and validate environment with priority: process.env > options > fileEnv > defaults\n const env = loadConnectEnv({\n processEnv: process.env,\n fileEnv,\n });\n\n // set the resolved env to process.env so it's loaded by vite\n setConnectEnv(env);\n\n // load powerhouse config\n const phConfigPath =\n env.PH_CONFIG_PATH ?? join(options.dirname, \"powerhouse.config.json\");\n\n const phConfig = options.powerhouseConfig ?? getConfig(phConfigPath);\n\n const packagesFromConfig = getPackageNamesFromPowerhouseConfig(phConfig);\n const phPackagesStr = env.PH_PACKAGES;\n const envPhPackages = phPackagesStr?.split(\",\");\n\n const phPackages = envPhPackages ?? packagesFromConfig;\n\n const phPackageRegistryUrl =\n env.PH_CONNECT_PACKAGES_REGISTRY ?? phConfig.packageRegistryUrl ?? null;\n\n const authToken = env.PH_SENTRY_AUTH_TOKEN;\n const org = env.PH_SENTRY_ORG;\n const project = env.PH_SENTRY_PROJECT;\n const release = env.PH_CONNECT_SENTRY_RELEASE || env.PH_CONNECT_VERSION;\n const uploadSentrySourcemaps = authToken && org && project;\n\n const connectHtmlTags = getConnectHtmlTags({\n registryUrl: phPackageRegistryUrl,\n });\n\n const plugins: PluginOption[] = [\n tailwind(),\n react(),\n createHtmlPlugin({\n minify: false,\n inject: {\n tags: [\n ...connectHtmlTags,\n {\n tag: \"script\",\n attrs: { type: \"importmap\" },\n children: JSON.stringify(\n {\n imports: {\n react: \"https://esm.sh/react@19.2.0\",\n \"react/\": \"https://esm.sh/react@19.2.0/\",\n \"react-dom\": \"https://esm.sh/react-dom@19.2.0\",\n \"react-dom/\": \"https://esm.sh/react-dom@19.2.0/\",\n },\n },\n null,\n 2,\n ),\n injectTo: \"head-prepend\",\n },\n ],\n },\n }),\n ] as const;\n\n if (uploadSentrySourcemaps) {\n plugins.push(\n sentryVitePlugin({\n release: {\n name: release ?? \"unknown\",\n inject: false, // prevent it from injecting the release id in the service worker code, this is done in 'src/app/sentry.ts' instead\n },\n authToken,\n org,\n project,\n bundleSizeOptimizations: {\n excludeDebugStatements: true,\n },\n reactComponentAnnotation: {\n enabled: true,\n },\n }) as PluginOption,\n );\n }\n\n // hide warnings unless LOG_LEVEL is set to debug\n const isDebug =\n process.env.LOG_LEVEL === \"debug\" || env.PH_CONNECT_LOG_LEVEL === \"debug\";\n const customLogger = isDebug\n ? undefined\n : viteLogger({\n silence: {\n warnings: [\n \"@import must precede all other statements (besides @charset or empty @layer)\", // tailwindcss error when importing font file\n ],\n errors: [\"Unterminated string literal\"],\n },\n });\n\n const reactExternal = [\n \"react\",\n \"react-dom\",\n \"react/jsx-runtime\",\n \"react-dom/client\",\n ];\n\n const config: InlineConfig = {\n configFile: false,\n mode,\n server: {\n watch: {\n ignored: [\"**/backup-documents/**\", \"**/.ph/**\"],\n },\n },\n resolve: {\n dedupe: [\"react\", \"react-dom\"],\n tsconfigPaths: true,\n },\n define: {\n PH_PACKAGE_REGISTRY_URL: `\"${phPackageRegistryUrl}\"`,\n },\n customLogger,\n envPrefix: [\"PH_CONNECT_\"],\n optimizeDeps: {\n include: [\n \"document-model\",\n \"zod\",\n \"@powerhousedao/design-system/connect\",\n \"@powerhousedao/reactor-browser\",\n \"@powerhousedao/document-engineering\",\n ],\n exclude: [\"@electric-sql/pglite\", \"@electric-sql/pglite-tools\"],\n },\n plugins: [\n // phPackagesPlugin must be registered before tailwind so its hotUpdate\n // hook runs first and can suppress HMR updates for codegen-generated\n // files, preventing tailwind from triggering full page reloads.\n phPackagesPlugin({\n packages: phPackages,\n }),\n ...plugins,\n // Externalize React so both Connect and dynamically loaded registry\n // packages share the same React instance via the import map in index.html.\n // Without this, Vite bundles React into Connect's chunks while registry\n // packages resolve React from the import map (esm.sh), creating two\n // separate React instances that don't share context/state.\n //\n // In Vite 8 (Rolldown), require() calls for external modules are preserved\n // as-is, which fails in browsers. esmExternalRequirePlugin handles both\n // externalization AND converting require() to import statements.\n // NOTE: Do NOT also list these in build.rolldownOptions.external — overlapping\n // entries prevent the plugin from transforming require() calls.\n esmExternalRequirePlugin({ external: reactExternal }),\n connectFaviconPlugin(),\n ],\n worker: {\n format: \"es\",\n },\n build: {\n sourcemap: true,\n },\n };\n return config;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,MAAa,2BAA2B;AACxC,MAAa,qBAAqB;AAClC,MAAa,mBAAmB;AAChC,MAAa,cAAc;;;ACS3B,MAAa,yBAAyB;AAEtC,SAAgB,0BAA0B,SAA+B;CACvE,MAAM,EACJ,MACA,YACA,kBACA,wBACA,wBACE;AAEJ,KAAI,KACF,eAAc,EACZ,sBAAsB,MACvB,CAAC;AAGJ,KAAI,WACF,eAAc,EACZ,gBAAgB,YACjB,CAAC;AAEJ,KAAI,iBACF,eAAc,EACZ,+BAA+B,iBAAiB,KAAK,IAAI,EAC1D,CAAC;AAEJ,KAAI,uBACF,eAAc,EACZ,qCAAqC,wBACtC,CAAC;AAEJ,KAAI,oBACF,eAAc,EACZ,0BAA0B,MAC3B,CAAC;;AAIN,SAAgB,sBACd,SACA;CACA,MAAM,EAAE,cAAc,KAAK,EAAE,mBAAmB;AAChD,QAAO,kBAAkB,KAAK,aAAa,iBAAiB;;AAG9D,SAAgB,eAAe,aAAqB,OAAO,QAAQ,KAAK,EAAE;AAGxE,QADgB,cAAc,KAAK,CACpB,QAAQ,aAAa,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC;;AAGxD,SAA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ACvB,wBAAwB,MACzB;EACD,0BAA0B,EACxB,SAAS,MACV;EACF,CAAC,CACH;CAMH,MAAM,eADJ,QAAQ,IAAI,cAAc,WAAW,IAAI,yBAAyB,UAEhE,KAAA,IACA,WAAW,EACT,SAAS;EACP,UAAU,CACR,+EACD;EACD,QAAQ,CAAC,8BAA8B;EACxC,EACF,CAAC;CAEN,MAAM,gBAAgB;EACpB;EACA;EACA;EACA;EACD;AA0DD,QAxD6B;EAC3B,YAAY;EACZ;EACA,QAAQ,EACN,OAAO,EACL,SAAS,CAAC,0BAA0B,YAAY,EACjD,EACF;EACD,SAAS;GACP,QAAQ,CAAC,SAAS,YAAY;GAC9B,eAAe;GAChB;EACD,QAAQ,EACN,yBAAyB,IAAI,qBAAqB,IACnD;EACD;EACA,WAAW,CAAC,cAAc;EAC1B,cAAc;GACZ,SAAS;IACP;IACA;IACA;IACA;IACA;IACD;GACD,SAAS,CAAC,wBAAwB,6BAA6B;GAChE;EACD,SAAS;GAIP,iBAAiB,EACf,UAAU,YACX,CAAC;GACF,GAAG;GAYH,yBAAyB,EAAE,UAAU,eAAe,CAAC;GACrD,sBAAsB;GACvB;EACD,QAAQ,EACN,QAAQ,MACT;EACD,OAAO,EACL,WAAW,MACZ;EACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerhousedao/builder-tools",
3
- "version": "6.0.0-dev.169",
3
+ "version": "6.0.0-dev.170",
4
4
  "type": "module",
5
5
  "license": "AGPL-3.0-only",
6
6
  "publishConfig": {
@@ -23,23 +23,13 @@
23
23
  "dependencies": {
24
24
  "@sentry/vite-plugin": "^4.3.0",
25
25
  "@tailwindcss/vite": "4.2.2",
26
- "@vitejs/plugin-basic-ssl": "2.3.0",
27
26
  "@vitejs/plugin-react": "6.0.1",
28
- "esbuild": "^0.25.5",
29
- "esbuild-plugins-node-modules-polyfill": "1.8.1",
30
- "fast-glob": "^3.3.3",
31
- "identify-monorepo-root": "^1.0.9",
32
- "magic-string": "^0.30.17",
33
- "read-pkg": "10.1.0",
34
- "resolve.exports": "^2.0.3",
35
27
  "vite": "8.0.2",
36
28
  "vite-plugin-html": "3.2.2",
37
- "vite-plugin-svgr": "4.5.0",
38
- "vite-tsconfig-paths": "6.1.1",
39
29
  "zod": "4.3.6",
40
- "@powerhousedao/config": "6.0.0-dev.169",
41
- "document-model": "6.0.0-dev.169",
42
- "@powerhousedao/shared": "6.0.0-dev.169"
30
+ "@powerhousedao/config": "6.0.0-dev.170",
31
+ "@powerhousedao/shared": "6.0.0-dev.170",
32
+ "document-model": "6.0.0-dev.170"
43
33
  },
44
34
  "devDependencies": {
45
35
  "tsdown": "0.21.0",