@powerhousedao/builder-tools 6.0.0-dev.111 → 6.0.0-dev.113

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,9 +9,8 @@ import { getConfig } from "@powerhousedao/config/node";
9
9
  import { sentryVitePlugin } from "@sentry/vite-plugin";
10
10
  import tailwind from "@tailwindcss/vite";
11
11
  import react from "@vitejs/plugin-react";
12
- import { createLogger, loadEnv } from "vite";
12
+ import { createLogger, esmExternalRequirePlugin, loadEnv } from "vite";
13
13
  import { createHtmlPlugin } from "vite-plugin-html";
14
- import tsconfigPaths from "vite-tsconfig-paths";
15
14
  import fs$2 from "fs/promises";
16
15
  import MagicString from "magic-string";
17
16
  import { build } from "esbuild";
@@ -323,7 +322,6 @@ function getConnectBaseViteConfig(options) {
323
322
  const release = env.PH_CONNECT_SENTRY_RELEASE || env.PH_CONNECT_VERSION;
324
323
  const uploadSentrySourcemaps = authToken && org && project;
325
324
  const plugins = [
326
- tsconfigPaths(),
327
325
  tailwind(),
328
326
  react(),
329
327
  createHtmlPlugin({
@@ -359,9 +357,16 @@ function getConnectBaseViteConfig(options) {
359
357
  warnings: ["@import must precede all other statements (besides @charset or empty @layer)"],
360
358
  errors: ["Unterminated string literal"]
361
359
  } });
360
+ const reactExternal = [
361
+ "react",
362
+ "react-dom",
363
+ "react/jsx-runtime",
364
+ "react-dom/client"
365
+ ];
362
366
  return {
363
367
  configFile: false,
364
368
  mode,
369
+ resolve: { tsconfigPaths: true },
365
370
  define: {
366
371
  PH_PACKAGES: phPackages,
367
372
  PH_PACKAGE_REGISTRY_URL: `"${phPackageRegistryUrl}"`
@@ -369,13 +374,7 @@ function getConnectBaseViteConfig(options) {
369
374
  customLogger,
370
375
  envPrefix: ["PH_CONNECT_"],
371
376
  optimizeDeps: { exclude: ["@electric-sql/pglite", "@electric-sql/pglite-tools"] },
372
- build: { rollupOptions: { external: [
373
- "react",
374
- "react-dom",
375
- "react/jsx-runtime",
376
- "react-dom/client"
377
- ] } },
378
- plugins,
377
+ plugins: [...plugins, esmExternalRequirePlugin({ external: reactExternal })],
379
378
  worker: { format: "es" }
380
379
  };
381
380
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["fs","fs"],"sources":["../connect-utils/constants.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/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 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 loadEnv,\n type HtmlTagDescriptor,\n type InlineConfig,\n type PluginOption,\n} from \"vite\";\nimport { createHtmlPlugin } from \"vite-plugin-html\";\nimport tsconfigPaths from \"vite-tsconfig-paths\";\nimport type { IConnectOptions } from \"./types.js\";\n\nconst isLocalDev = true;\nconst esmShUrl = isLocalDev ? \"http://localhost:8080\" : \"https://esm.sh\";\n\nexport const connectClientConfig = {\n meta: [\n {\n tag: \"meta\",\n attrs: {\n \"http-equiv\": \"Content-Security-Policy\",\n content:\n \"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://esm.sh http://localhost:8080; object-src 'none'; base-uri 'self';\",\n },\n },\n {\n tag: \"meta\",\n attrs: {\n property: \"og:title\",\n content: \"Connect\",\n },\n },\n {\n tag: \"meta\",\n attrs: {\n property: \"og:type\",\n content: \"website\",\n },\n },\n {\n tag: \"meta\",\n attrs: {\n property: \"og:url\",\n content: \"https://apps.powerhouse.io/powerhouse/connect/\",\n },\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 },\n {\n tag: \"meta\",\n attrs: {\n property: \"og:image\",\n content:\n \"https://cf-ipfs.com/ipfs/bafkreigrmclndf2jpbolaq22535q2sw5t44uad3az3dpvkzrnt4lpjt63e\",\n },\n },\n {\n tag: \"meta\",\n attrs: {\n name: \"twitter:card\",\n content: \"summary_large_image\",\n },\n },\n {\n tag: \"meta\",\n attrs: {\n name: \"twitter:image\",\n content:\n \"https://cf-ipfs.com/ipfs/bafkreigrmclndf2jpbolaq22535q2sw5t44uad3az3dpvkzrnt4lpjt63e\",\n },\n },\n {\n tag: \"meta\",\n attrs: {\n name: \"twitter:title\",\n content: \"Connect\",\n },\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 },\n ],\n} as const;\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 plugins: PluginOption[] = [\n tsconfigPaths(),\n tailwind(),\n react(),\n createHtmlPlugin({\n minify: false,\n inject: {\n tags: [\n ...(connectClientConfig.meta.map((meta) => ({\n ...meta,\n injectTo: \"head\",\n })) as HtmlTagDescriptor[]),\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 config: InlineConfig = {\n configFile: false,\n mode,\n define: {\n PH_PACKAGES: phPackages,\n PH_PACKAGE_REGISTRY_URL: `\"${phPackageRegistryUrl}\"`,\n },\n customLogger,\n envPrefix: [\"PH_CONNECT_\"],\n optimizeDeps: {\n exclude: [\"@electric-sql/pglite\", \"@electric-sql/pglite-tools\"],\n },\n build: {\n rollupOptions: {\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 external: [\n \"react\",\n \"react-dom\",\n \"react/jsx-runtime\",\n \"react-dom/client\",\n ],\n },\n },\n plugins,\n worker: {\n format: \"es\",\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,mBAA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ect-utils/constants.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/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 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\";\n\nconst isLocalDev = true;\nconst esmShUrl = isLocalDev ? \"http://localhost:8080\" : \"https://esm.sh\";\n\nexport const connectClientConfig = {\n meta: [\n {\n tag: \"meta\",\n attrs: {\n \"http-equiv\": \"Content-Security-Policy\",\n content:\n \"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://esm.sh http://localhost:8080; object-src 'none'; base-uri 'self';\",\n },\n },\n {\n tag: \"meta\",\n attrs: {\n property: \"og:title\",\n content: \"Connect\",\n },\n },\n {\n tag: \"meta\",\n attrs: {\n property: \"og:type\",\n content: \"website\",\n },\n },\n {\n tag: \"meta\",\n attrs: {\n property: \"og:url\",\n content: \"https://apps.powerhouse.io/powerhouse/connect/\",\n },\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 },\n {\n tag: \"meta\",\n attrs: {\n property: \"og:image\",\n content:\n \"https://cf-ipfs.com/ipfs/bafkreigrmclndf2jpbolaq22535q2sw5t44uad3az3dpvkzrnt4lpjt63e\",\n },\n },\n {\n tag: \"meta\",\n attrs: {\n name: \"twitter:card\",\n content: \"summary_large_image\",\n },\n },\n {\n tag: \"meta\",\n attrs: {\n name: \"twitter:image\",\n content:\n \"https://cf-ipfs.com/ipfs/bafkreigrmclndf2jpbolaq22535q2sw5t44uad3az3dpvkzrnt4lpjt63e\",\n },\n },\n {\n tag: \"meta\",\n attrs: {\n name: \"twitter:title\",\n content: \"Connect\",\n },\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 },\n ],\n} as const;\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 plugins: PluginOption[] = [\n tailwind(),\n react(),\n createHtmlPlugin({\n minify: false,\n inject: {\n tags: [\n ...(connectClientConfig.meta.map((meta) => ({\n ...meta,\n injectTo: \"head\",\n })) as HtmlTagDescriptor[]),\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 resolve: {\n tsconfigPaths: true,\n },\n define: {\n PH_PACKAGES: phPackages,\n PH_PACKAGE_REGISTRY_URL: `\"${phPackageRegistryUrl}\"`,\n },\n customLogger,\n envPrefix: [\"PH_CONNECT_\"],\n optimizeDeps: {\n exclude: [\"@electric-sql/pglite\", \"@electric-sql/pglite-tools\"],\n },\n plugins: [\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 ],\n worker: {\n format: \"es\",\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;AACh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ACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerhousedao/builder-tools",
3
- "version": "6.0.0-dev.111",
3
+ "version": "6.0.0-dev.113",
4
4
  "type": "module",
5
5
  "license": "AGPL-3.0-only",
6
6
  "publishConfig": {
@@ -22,9 +22,9 @@
22
22
  "sideEffects": false,
23
23
  "dependencies": {
24
24
  "@sentry/vite-plugin": "^4.3.0",
25
- "@tailwindcss/vite": "4.1.18",
26
- "@vitejs/plugin-basic-ssl": "2.1.4",
27
- "@vitejs/plugin-react": "5.1.4",
25
+ "@tailwindcss/vite": "4.2.2",
26
+ "@vitejs/plugin-basic-ssl": "2.3.0",
27
+ "@vitejs/plugin-react": "6.0.1",
28
28
  "esbuild": "^0.25.5",
29
29
  "esbuild-plugins-node-modules-polyfill": "1.8.1",
30
30
  "fast-glob": "^3.3.3",
@@ -32,16 +32,16 @@
32
32
  "magic-string": "^0.30.17",
33
33
  "read-pkg": "10.1.0",
34
34
  "resolve.exports": "^2.0.3",
35
- "vite": "7.3.1",
35
+ "vite": "8.0.2",
36
36
  "vite-envs": "4.6.2",
37
37
  "vite-plugin-html": "3.2.2",
38
38
  "vite-plugin-node-polyfills": "0.25.0",
39
39
  "vite-plugin-svgr": "4.5.0",
40
40
  "vite-tsconfig-paths": "6.1.1",
41
41
  "zod": "4.3.6",
42
- "@powerhousedao/config": "6.0.0-dev.111",
43
- "@powerhousedao/shared": "6.0.0-dev.111",
44
- "document-model": "6.0.0-dev.111"
42
+ "@powerhousedao/config": "6.0.0-dev.113",
43
+ "@powerhousedao/shared": "6.0.0-dev.113",
44
+ "document-model": "6.0.0-dev.113"
45
45
  },
46
46
  "devDependencies": {
47
47
  "tsdown": "0.21.0",