@powerhousedao/builder-tools 6.2.2-dev.3 → 6.2.2-dev.31
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 +301 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +342 -102
- package/dist/index.mjs.map +1 -1
- package/dist/service-worker/service-worker.ts +352 -0
- package/dist/service-worker/virtual-sw-config.d.ts +22 -0
- package/package.json +10 -4
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["importTarget","pathDirname","dirname","dirname","pathDirname"],"sources":["../connect-utils/constants.ts","../connect-utils/vite-plugins/dynamic-base.ts","../connect-utils/externalize-vendor.ts","../connect-utils/helpers.ts","../connect-utils/runtime-config-schema.ts","../connect-utils/vite-plugins/ph-bundled-packages.ts","../connect-utils/vite-plugins/dev-external-react.ts","../connect-utils/vite-plugins/favicon.ts","../connect-utils/vite-plugins/ph-config.ts","../connect-utils/vite-plugins/pwa-icons.ts","../connect-utils/vite-plugins/pwa.ts","../connect-utils/vite-plugins/react-self-host.ts","../connect-utils/vite-plugins/theme-boot.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 MagicString from \"magic-string\";\nimport type { Plugin } from \"vite\";\n\n/**\n * Placeholder base used when Connect is built in dynamic-base mode. The Vite\n * `base` option is set to this token; this plugin rewrites it in the emitted\n * output so the effective base is resolved at serve time from a global instead\n * of being baked at build time.\n *\n * Trailing slash matches `normalizeBasePath` output, so the token sits in the\n * same syntactic position as a concrete base would.\n */\nexport const DYNAMIC_BASE_PLACEHOLDER = \"/__PH_DYNAMIC_BASE__/\";\n\n/**\n * Global the runtime (ph-clint proxy) must set before the entry bundle loads.\n * Value is the normalized deploy base, e.g. \"/myagent/\" or \"/\". The JS rewrite\n * below resolves all asset / lazy-chunk / BASE_URL references against it.\n */\nconst RUNTIME_GLOBAL = \"globalThis.__PH_DYNAMIC_BASE__\";\n\n// `(globalThis.__PH_DYNAMIC_BASE__||\"/\")` — used everywhere the placeholder\n// base prefix appears in emitted JS.\nconst BASE_EXPR = `(${RUNTIME_GLOBAL}||\"/\")`;\n\n// Worker prelude: derive the deploy base in worker scope from the worker's own\n// URL (proxy sets the global on the main thread only).\nfunction workerPrelude(stripPrefix: string): string {\n // `stripPrefix` is the segment between the deploy base and `assets/` (default\n // \"\" → strip `assets/<file>`; vendor passes \"__vendor__/\").\n const prefix = escapeForRegExp(stripPrefix).replace(/\\//g, \"\\\\/\");\n return `${RUNTIME_GLOBAL}=self.location.pathname.replace(/${prefix}assets\\\\/[^/]*$/,\"\");\\n`;\n}\n\n// Match a string literal whose content STARTS with the placeholder, in any of\n// the three JS quote styles Rolldown emits (double, single, backtick). Group 1\n// captures the opening quote; the closing quote must be the same character\n// (backreference), so a double-quoted literal may contain ' or ` and vice\n// versa. Group 2 captures the literal text after the placeholder up to the\n// closing quote. Rolldown emits the base both as a bare literal (the inlined\n// BASE_URL) and as a `<base>`+suffix (preload/asset URL prefix); both start at\n// the placeholder. The content stops at `$`, so a template literal that\n// interpolates after the token (`` `<token>...${expr}` ``) is NOT rewritten —\n// the residual-token assertion in `generateBundle` fails the build instead of\n// shipping the raw placeholder.\nconst PLACEHOLDER_LITERAL = new RegExp(\n `([\"'\\`])${escapeForRegExp(DYNAMIC_BASE_PLACEHOLDER)}((?:(?!\\\\1)[^$])*)\\\\1`,\n \"g\",\n);\n\n/**\n * Rewrites the placeholder base in emitted JS chunks to a runtime expression so\n * one built `dist/connect` serves under any subpath. Rolldown-native: per-match\n * MagicString edits in `renderChunk`, no AST splicing (the SWC byte-offset\n * splicing in vite-plugin-dynamic-base corrupts Rolldown chunks). Each edited\n * chunk returns a hires sourcemap that the bundler composes into the chunk's\n * map chain, so the emitted `.map` files track the rewrite (and the worker\n * prelude's line shift).\n *\n * What gets rewritten in JS, all of which emit the base as a quoted string\n * literal beginning with the placeholder:\n * - asset URLs (`new URL(\"/__PH_DYNAMIC_BASE__/assets/x.png\", ...)`)\n * - dynamic-import / lazy-chunk preload URLs\n * - the inlined `import.meta.env.BASE_URL` (drives Connect's router basename\n * and BASE_URL-relative fetches such as `${BASE_URL}ph-packages.json`)\n *\n * A literal `\"/__PH_DYNAMIC_BASE__/foo\"` becomes `((globalThis.__PH_DYNAMIC_BASE__||\"/\")+\"foo\")`;\n * a bare `\"/__PH_DYNAMIC_BASE__/\"` (the BASE_URL value) becomes `(globalThis.__PH_DYNAMIC_BASE__||\"/\")`.\n *\n * HTML is left untouched: the entry `<script>`/`<link>` tags keep the literal\n * placeholder so the proxy substitutes it with the concrete base at serve time\n * (the same proxy also sets the runtime global for the JS rewrite). See the\n * plugin's module doc / report for the exact serve-time contract.\n *\n * CSS `url(...)` references resolve relative to the stylesheet's own URL, so\n * they need no rewrite once the stylesheet itself is loaded from the right\n * prefix (which the HTML substitution handles).\n */\nexport function connectDynamicBasePlugin(\n options: { forWorker?: boolean; workerStripPrefix?: string } = {},\n): Plugin {\n return {\n name: \"ph-connect-dynamic-base\",\n enforce: \"post\",\n renderChunk(code, chunk) {\n if (!code.includes(DYNAMIC_BASE_PLACEHOLDER)) return null;\n\n const s = new MagicString(code);\n for (const match of code.matchAll(PLACEHOLDER_LITERAL)) {\n const rest = match[2];\n s.overwrite(\n match.index,\n match.index + match[0].length,\n rest.length === 0\n ? BASE_EXPR\n : `(${BASE_EXPR}+${JSON.stringify(rest)})`,\n );\n }\n\n // Worker chunks run in their own global scope where the proxy never\n // sets the runtime global; derive it from the worker's script URL so\n // the rewritten references above resolve against the deploy base.\n if (options.forWorker) {\n s.prepend(workerPrelude(options.workerStripPrefix ?? \"\"));\n this.info(\n `dynamic-base: worker prelude prepended to ${chunk.fileName}`,\n );\n }\n\n if (!s.hasChanged()) return null;\n return { code: s.toString(), map: s.generateMap({ hires: true }) };\n },\n generateBundle(_options, bundle) {\n // A residual token in JS (a literal the regex couldn't rewrite, e.g. a\n // template interpolating after the token) or CSS (url() must stay\n // stylesheet-relative; the placeholder would ship verbatim and 404)\n // would fail silently at runtime — fail the build instead. HTML keeps\n // the token by design: the proxy substitutes it at serve time.\n for (const file of Object.values(bundle)) {\n const content =\n file.type === \"chunk\"\n ? file.code\n : file.fileName.endsWith(\".css\") && typeof file.source === \"string\"\n ? file.source\n : undefined;\n if (content?.includes(DYNAMIC_BASE_PLACEHOLDER)) {\n this.error(\n `dynamic-base: unrewritten placeholder ${DYNAMIC_BASE_PLACEHOLDER} remains in ${file.fileName}`,\n );\n }\n }\n },\n };\n}\n\nfunction escapeForRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","/**\n * Prebuild the heavy, stable Connect dependencies into a static ESM \"vendor\"\n * bundle so the dev server never runs (or holds) the dependency optimizer /\n * module graph for them.\n *\n * The reactor-project preview dev-optimizes a large UI graph (Connect itself,\n * design-system, document-engineering, reactor-browser, …) every session —\n * ~1–2 GB resident — even though those libs don't change; only the project's\n * editors do. This module builds them ONCE with `vite build` (in a throwaway\n * subprocess that exits, freeing the build's peak memory): `vite build` handles\n * CSS/asset imports, web workers, and WASM (Connect's in-browser PGlite ships\n * all three), and a multi-entry build with `preserveEntrySignatures: 'strict'`\n * dedupes shared code into shared chunks. Entries for CJS deps re-export the\n * module's named API explicitly (so `import { createRoot }` works); ESM deps\n * use `export *`. The build runs under a dynamic-base placeholder + vendor\n * segment (`connectDynamicBasePlugin`), so emitted asset/chunk URLs\n * (`new URL(…, import.meta.url)` for .wasm/.data/workers) carry the placeholder\n * and resolve at serve time to `<deploy-base>__vendor__/`, while the vendored\n * Connect's `import.meta.env.BASE_URL` resolves to the deploy base.\n *\n * The React family stays EXTERNAL (see `VENDOR_EXTERNAL`); `esmExternalRequirePlugin`\n * owns that externalization and rewrites CJS `require(\"react\")` → import. Vendor\n * chunks keep bare React imports, which the dev import map resolves to Vite's\n * pre-bundled React (`devReactImportmapPlugin`) — one React instance across the\n * vendor, the project's editors, and CDN-loaded editors.\n *\n * `devReactImportmapPlugin` consumes the result: it externalizes these\n * specifiers in the long-lived dev server, points the page import map at the\n * vendor URLs, and serves the bundle. With Connect vendored, the dev server only\n * processes the project's own `main` + local package; HMR for them is unaffected.\n */\nimport { spawn } from \"node:child_process\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n existsSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n realpathSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname as pathDirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { DYNAMIC_BASE_PLACEHOLDER } from \"./vite-plugins/dynamic-base.js\";\n\nexport interface VendorPrebuildOptions {\n /** Project root (the reactor-project dir). */\n dirname: string;\n /** Bare specifiers to bundle into the vendor (defaults to the heavy libs). */\n include?: string[];\n /** Specifiers left external to the build (defaults to the React family). */\n external?: string[];\n /** Directory to hold the static vendor bundle + import map. */\n vendorDir?: string;\n /** Filled with the failure cause when the prebuild returns null. */\n errorRef?: { message?: string };\n}\n\n/**\n * The stable Connect libraries worth prebuilding. The React family is NOT here —\n * it's externalized from the build (see `VENDOR_EXTERNAL`) so the vendor shares\n * the dev server's single React instance via the import map.\n */\nexport const DEFAULT_VENDOR_INCLUDE = [\n \"@powerhousedao/connect\",\n \"document-model\",\n \"zod\",\n \"@powerhousedao/design-system/connect\",\n \"@powerhousedao/reactor-browser\",\n \"@powerhousedao/document-engineering\",\n];\n\n/**\n * React-family specifiers kept external to the vendor build. The vendor's chunks\n * emit bare imports for these; `devReactImportmapPlugin`'s import map resolves\n * them to Vite's pre-bundled React, so there is exactly one React instance.\n */\nexport const VENDOR_EXTERNAL = [\n \"react\",\n \"react-dom\",\n \"react-dom/client\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n // Dev-server virtual module (bundled local packages). Connect imports it in a\n // try/catch; left external so the build doesn't try to resolve it and the dev\n // server / import map resolves it at runtime.\n \"ph-bundled-packages-virtual\",\n];\n\nexport interface PrebuiltVendor {\n vendorDir: string;\n /** import map: bare specifier -> \"/__vendor__/<entry>.js\". */\n imports: Record<string, string>;\n}\n\n/** URL prefix the vendor bundle is served under by the dev middleware. */\nexport const VENDOR_URL_PREFIX = \"/__vendor__/\";\n\n// Vite `base` for the vendor build: dynamic-base placeholder + vendor segment.\n// connectDynamicBasePlugin rewrites it so chunk/asset URLs resolve at serve time.\nconst VENDOR_DYNAMIC_BASE = `${DYNAMIC_BASE_PLACEHOLDER}${VENDOR_URL_PREFIX.replace(/^\\/+/, \"\")}`;\n\n/**\n * Build the prebuilt vendor (once, in a throwaway subprocess) and return its dir\n * + import map. Idempotent: reuses a cached vendor built for the same dep set.\n * Returns null on any failure (caller falls back to a normal dev server).\n */\nexport async function prebuildConnectVendor(\n options: VendorPrebuildOptions,\n): Promise<PrebuiltVendor | null> {\n const include = expandIncludeSubpaths(\n options.dirname,\n options.include ?? DEFAULT_VENDOR_INCLUDE,\n );\n const external = options.external ?? VENDOR_EXTERNAL;\n const vendorDir =\n options.vendorDir ?? join(options.dirname, \"node_modules/.ph-vendor\");\n const importMapPath = join(vendorDir, \"import-map.json\");\n // A version change of any vendored dep must invalidate the cache, so the\n // resolved versions are part of the key (not just the specifier lists).\n const versionDigest = resolveVersionDigest(options.dirname, [\n ...include,\n ...external,\n ]);\n\n try {\n const hit = readCacheHit(importMapPath, include, external, versionDigest);\n if (hit) return { vendorDir, imports: hit };\n\n // Serialize concurrent builders on a lock dir; a loser waits for the\n // winner's result instead of clobbering the shared output.\n const lockDir = `${vendorDir}.lock`;\n const lock = acquireLock(lockDir);\n if (!lock) {\n const imports = await waitForCacheHit(\n importMapPath,\n include,\n external,\n versionDigest,\n lockDir,\n );\n return imports ? { vendorDir, imports } : null;\n }\n\n try {\n // Recheck under the lock: another builder may have finished while we\n // were acquiring it.\n const raced = readCacheHit(\n importMapPath,\n include,\n external,\n versionDigest,\n );\n if (raced) return { vendorDir, imports: raced };\n\n const imports = await buildVendorAtomic(\n options.dirname,\n vendorDir,\n include,\n external,\n versionDigest,\n );\n return imports ? { vendorDir, imports } : null;\n } finally {\n releaseLock(lock);\n }\n } catch (err) {\n if (options.errorRef)\n options.errorRef.message =\n err instanceof Error ? err.message : String(err);\n return null;\n }\n}\n\ninterface VendorCacheMeta {\n include?: string[];\n external?: string[];\n versionDigest?: string;\n imports: Record<string, string>;\n}\n\n// Return the cached import map iff the specifier sets AND the resolved-version\n// digest all match; otherwise null (forces a rebuild).\nfunction readCacheHit(\n importMapPath: string,\n include: string[],\n external: string[],\n versionDigest: string,\n): Record<string, string> | null {\n if (!existsSync(importMapPath)) return null;\n try {\n const cached = JSON.parse(\n readFileSync(importMapPath, \"utf8\"),\n ) as VendorCacheMeta;\n if (\n sameSet(cached.include, include) &&\n sameSet(cached.external, external) &&\n cached.versionDigest === versionDigest\n ) {\n return cached.imports;\n }\n } catch {\n // partial/corrupt import-map.json → treat as miss\n }\n return null;\n}\n\n// Hash the resolved version of each spec's owning package (from its installed\n// package.json). A bump or branch checkout that changes any version yields a\n// different digest, invalidating the cache. Unresolvable specs contribute a\n// sentinel so they don't silently collide.\nfunction resolveVersionDigest(dirname: string, specs: string[]): string {\n const seen = new Map<string, string>();\n for (const spec of specs) {\n const { pkg } = parsePkg(spec);\n if (seen.has(pkg)) continue;\n let version = \"missing\";\n try {\n const pkgRoot = realpathSync(join(dirname, \"node_modules\", pkg));\n const meta = JSON.parse(\n readFileSync(join(pkgRoot, \"package.json\"), \"utf8\"),\n ) as { version?: string };\n version = String(meta.version ?? \"unknown\");\n } catch {\n // leave sentinel\n }\n seen.set(pkg, version);\n }\n const h = createHash(\"sha256\");\n // Fold in the build worker so a logic/build-option change busts stale bundles,\n // not just a dep version bump.\n const workerHash = createHash(\"sha256\")\n .update(VENDOR_BUILD_WORKER)\n .digest(\"hex\");\n h.update(`worker:${workerHash}\\n`);\n for (const pkg of [...seen.keys()].sort()) {\n h.update(`${pkg}@${seen.get(pkg)}\\n`);\n }\n return h.digest(\"hex\").slice(0, 16);\n}\n\nfunction sameSet(a: string[] | undefined, b: string[]): boolean {\n if (!a || a.length !== b.length) return false;\n const s = new Set(a);\n return b.every((x) => s.has(x));\n}\n\n// Exclusive lock via mkdir (atomic on POSIX). The holder heartbeats an owner\n// file so a live (slow) build keeps it fresh; a crashed builder lets it go stale.\nconst LOCK_STALE_MS = 5 * 60_000;\nconst LOCK_HEARTBEAT_MS = 60_000;\n\ninterface VendorLock {\n dir: string;\n token: string;\n timer: ReturnType<typeof setInterval>;\n}\n\nconst ownerFile = (lockDir: string): string => join(lockDir, \"owner\");\n\n// Stale iff the owner file hasn't been heartbeated within LOCK_STALE_MS. A\n// missing owner file means a builder mid-acquire — treat as fresh, don't steal.\nfunction lockIsStale(lockDir: string): boolean {\n try {\n return Date.now() - statSync(ownerFile(lockDir)).mtimeMs > LOCK_STALE_MS;\n } catch {\n return false;\n }\n}\n\nfunction acquireLock(lockDir: string): VendorLock | null {\n let made = false;\n try {\n mkdirSync(lockDir);\n made = true;\n } catch {\n if (lockIsStale(lockDir)) {\n try {\n rmSync(lockDir, { recursive: true, force: true });\n mkdirSync(lockDir);\n made = true;\n } catch {\n // lost the reclaim race to another builder\n }\n }\n }\n if (!made) return null;\n const token = `${process.pid}-${randomUUID()}`;\n writeFileSync(ownerFile(lockDir), token);\n // Refresh mtime while we still own it; stop if a stale-reclaim handed it off.\n const timer = setInterval(() => {\n try {\n if (readFileSync(ownerFile(lockDir), \"utf8\") === token) {\n writeFileSync(ownerFile(lockDir), token);\n } else {\n clearInterval(timer);\n }\n } catch {\n clearInterval(timer);\n }\n }, LOCK_HEARTBEAT_MS);\n timer.unref();\n return { dir: lockDir, token, timer };\n}\n\n// Remove only if we still own it — a stale-reclaim may have handed the lock to\n// another builder, whose dir we must not delete.\nfunction releaseLock(lock: VendorLock): void {\n clearInterval(lock.timer);\n try {\n if (readFileSync(ownerFile(lock.dir), \"utf8\") === lock.token) {\n rmSync(lock.dir, { recursive: true, force: true });\n }\n } catch {\n // owner file gone/unreadable — leave it for the stale path\n }\n}\n\n// Loser path: poll for the winner to publish a matching import-map.json, until\n// the lock is released or a timeout elapses.\nasync function waitForCacheHit(\n importMapPath: string,\n include: string[],\n external: string[],\n versionDigest: string,\n lockDir: string,\n): Promise<Record<string, string> | null> {\n const deadline = Date.now() + LOCK_STALE_MS;\n while (Date.now() < deadline) {\n const hit = readCacheHit(importMapPath, include, external, versionDigest);\n if (hit) return hit;\n if (!existsSync(lockDir)) {\n // winner finished (or gave up); one last read\n return readCacheHit(importMapPath, include, external, versionDigest);\n }\n await new Promise((r) => setTimeout(r, 250));\n }\n return null;\n}\n\n// Resolve an exports entry to the file it loads under browser/import\n// conditions, or null if none (e.g. document-model's node-only `./node`). Used\n// to skip node-only and CSS/JSON subpaths the browser-targeted build can't take.\nfunction importTarget(value: unknown): string | null {\n if (typeof value === \"string\") return value;\n if (!value || typeof value !== \"object\") return null;\n const o = value as Record<string, unknown>;\n for (const c of [\"browser\", \"import\", \"module\", \"default\"]) {\n if (c in o) {\n const t = importTarget(o[c]);\n if (t) return t;\n }\n }\n return null;\n}\n\nfunction parsePkg(spec: string): { pkg: string; sub: string } {\n if (spec.startsWith(\"@\")) {\n const parts = spec.split(\"/\");\n return { pkg: parts.slice(0, 2).join(\"/\"), sub: parts.slice(2).join(\"/\") };\n }\n const i = spec.indexOf(\"/\");\n return i === -1\n ? { pkg: spec, sub: \"\" }\n : { pkg: spec.slice(0, i), sub: spec.slice(i + 1) };\n}\n\n/**\n * Connect imports the heavy libs by subpath too (e.g.\n * `@powerhousedao/design-system/connect/toast`, `zod/v4/core`). Those bare\n * imports need their own import-map entry, so expand each listed spec to its\n * package's concrete (non-wildcard, JS) subpath exports that share the spec's\n * prefix. Unresolvable / CSS / JSON targets are skipped. Failures leave the\n * original spec untouched.\n */\nfunction expandIncludeSubpaths(dirname: string, include: string[]): string[] {\n const out = new Set<string>(include);\n for (const spec of include) {\n const { pkg, sub } = parsePkg(spec);\n let exp: unknown;\n let pkgRoot: string;\n try {\n pkgRoot = realpathSync(join(dirname, \"node_modules\", pkg));\n const pkgJson = JSON.parse(\n readFileSync(join(pkgRoot, \"package.json\"), \"utf8\"),\n ) as { exports?: unknown };\n exp = pkgJson.exports;\n } catch {\n continue;\n }\n if (!exp || typeof exp !== \"object\") continue;\n const expMap = exp as Record<string, unknown>;\n const prefixKey = sub ? `./${sub}` : \".\";\n for (const key of Object.keys(expMap)) {\n if (key.includes(\"*\") || key === \"./package.json\") continue;\n if (/\\.(css|json|scss)$/.test(key)) continue;\n const matches =\n prefixKey === \".\"\n ? key === \".\" || key.startsWith(\"./\")\n : key === prefixKey || key.startsWith(`${prefixKey}/`);\n if (!matches) continue;\n const target = importTarget(expMap[key]);\n if (!target || /\\.(css|json|scss)$/.test(target)) continue;\n // Skip subpaths whose target file isn't shipped (e.g. a `./test` export\n // pointing at unbuilt dist) — they'd fail the build.\n if (!existsSync(join(pkgRoot, target))) continue;\n out.add(key === \".\" ? pkg : pkg + key.slice(1));\n }\n }\n return [...out];\n}\n\n/**\n * Build the vendor into a unique temp dir, then atomically swap it into place,\n * so a concurrent reader never sees a partial bundle or import-map.json. Runs\n * the build in a throwaway subprocess (its peak memory is reclaimed on exit);\n * the parent augments the import map with the version digest and does the swap.\n * Returns the published import map, or null on failure.\n */\nasync function buildVendorAtomic(\n dirname: string,\n vendorDir: string,\n include: string[],\n external: string[],\n versionDigest: string,\n): Promise<Record<string, string> | null> {\n const parent = pathDirname(vendorDir);\n mkdirSync(parent, { recursive: true });\n const tmpDir = mkdtempSync(join(parent, \".ph-vendor.tmp-\"));\n try {\n const { ok, stderr } = await runBuildWorker(\n dirname,\n tmpDir,\n include,\n external,\n );\n const tmpMap = join(tmpDir, \"import-map.json\");\n if (!ok || !existsSync(tmpMap)) {\n const detail = stderr.trim();\n throw new Error(\n `vendor build failed${detail ? `:\\n${detail}` : \" (no output captured)\"}`,\n );\n }\n // Stamp the version digest into the published metadata so the cache check\n // can detect a dep bump.\n const meta = JSON.parse(readFileSync(tmpMap, \"utf8\")) as VendorCacheMeta;\n meta.versionDigest = versionDigest;\n writeFileSync(tmpMap, JSON.stringify(meta, null, 2));\n\n // Swap: move any existing dir aside, rename temp into place, drop the old.\n const oldDir = `${vendorDir}.old-${process.pid}-${Date.now()}`;\n if (existsSync(vendorDir)) renameSync(vendorDir, oldDir);\n renameSync(tmpDir, vendorDir);\n rmSync(oldDir, { recursive: true, force: true });\n return meta.imports;\n } catch (err) {\n rmSync(tmpDir, { recursive: true, force: true });\n throw err;\n }\n}\n\n/**\n * Spawn a throwaway worker that generates one entry per specifier (CJS deps get\n * explicit named re-exports, ESM deps `export *`), `vite build`s them into the\n * given out dir, and writes the import map. Captures stdout/stderr so a failure\n * is debuggable; the normal path stays quiet.\n */\nfunction runBuildWorker(\n dirname: string,\n outDir: string,\n include: string[],\n external: string[],\n): Promise<{ ok: boolean; stderr: string }> {\n const workerPath = join(outDir, \"build-worker.mjs\");\n writeFileSync(workerPath, VENDOR_BUILD_WORKER);\n // Absolute path to this (built) module so the worker can import the\n // dynamic-base plugin from builder-tools' own bundle.\n const selfModulePath = fileURLToPath(import.meta.url);\n return new Promise((resolve) => {\n const child = spawn(\n process.execPath,\n [\n workerPath,\n dirname,\n outDir,\n JSON.stringify(include),\n VENDOR_URL_PREFIX,\n JSON.stringify(external),\n VENDOR_DYNAMIC_BASE,\n selfModulePath,\n ],\n { cwd: dirname, stdio: [\"ignore\", \"pipe\", \"pipe\"] },\n );\n let stderr = \"\";\n child.stdout.on(\"data\", (d) => {\n stderr += String(d);\n });\n child.stderr.on(\"data\", (d) => {\n stderr += String(d);\n });\n child.on(\"exit\", (code) => resolve({ ok: code === 0, stderr }));\n child.on(\"error\", (e) => resolve({ ok: false, stderr: String(e) }));\n });\n}\n\n/**\n * The vendor build worker, written to disk and run as a subprocess. Loads\n * `vite` from the project and `connectDynamicBasePlugin` from builder-tools' own\n * built bundle (selfModulePath). argv: dirname, vendorDir, includeJSON,\n * urlPrefix, externalJSON, dynamicBase, selfModulePath.\n */\nconst VENDOR_BUILD_WORKER = `\nimport { createRequire } from 'node:module';\nimport { mkdirSync, writeFileSync, rmSync } from 'node:fs';\nimport { join, isAbsolute } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nconst [dirname, vendorDir, includeJSON, urlPrefix, externalJSON, dynamicBase, selfModulePath] = process.argv.slice(2);\nconst include = JSON.parse(includeJSON);\nconst external = JSON.parse(externalJSON ?? '[]');\nconst externalSet = new Set(external);\nconst reqProj = createRequire(join(dirname, 'noop.js'));\nconst { build, esmExternalRequirePlugin } = await import(reqProj.resolve('vite'));\n// Load the dynamic-base plugin from builder-tools' own built bundle (passed as\n// an absolute path) — it isn't resolvable as a bare specifier from the worker.\nconst { connectDynamicBasePlugin, DYNAMIC_BASE_PLACEHOLDER } = await import(pathToFileURL(selfModulePath));\nconst srcDir = join(vendorDir, '.entries');\nmkdirSync(srcDir, { recursive: true });\nconst entryName = (spec) => spec.replace(/[^\\\\w]+/g, '_');\nconst RESERVED = new Set('enum void null function in instanceof typeof new delete do if else return switch case break continue for while this true false class const let var default export import extends super with yield debugger finally throw try catch await implements interface package private protected public static eval arguments'.split(' '));\nconst input = {};\nfor (const spec of include) {\n const name = entryName(spec);\n let src;\n try {\n // Import the bare spec (not reqProj.resolve(spec)) so Node picks the same\n // import/browser-condition module the build resolves — resolving first can\n // pick a CJS sibling whose default-export shape differs from the ESM build.\n const ns = await import(spec);\n // Only fall back to re-exporting from default when the module exposes NO\n // top-level named exports (a true CJS-interop module). If it does (e.g. zod\n // exposes \\`z\\`), \\`export *\\` captures them; destructuring default would miss\n // top-level names that aren't keys of the default object.\n const named = Object.keys(ns).filter((k) => k !== 'default');\n const cjs = named.length === 0 && ns.default && typeof ns.default === 'object';\n if (cjs) {\n const names = Object.keys(ns.default).filter((k) => k !== 'default' && k !== '__esModule' && /^[A-Za-z_$][\\\\w$]*$/.test(k));\n const plain = names.filter((n) => !RESERVED.has(n));\n const reserved = names.filter((n) => RESERVED.has(n));\n src = 'import d from ' + JSON.stringify(spec) + ';\\\\nexport default d;\\\\n'\n + (plain.length ? 'export const { ' + plain.join(', ') + ' } = d;\\\\n' : '');\n // reserved words are invalid as const-binding names but valid as export\n // aliases (export { x as enum }).\n reserved.forEach((n, i) => {\n src += 'const __r' + i + ' = d[' + JSON.stringify(n) + '];\\\\nexport { __r' + i + ' as ' + n + ' };\\\\n';\n });\n } else {\n src = 'export * from ' + JSON.stringify(spec) + ';\\\\n'\n + (('default' in ns) ? 'export { default } from ' + JSON.stringify(spec) + ';\\\\n' : '');\n }\n } catch {\n src = 'export * from ' + JSON.stringify(spec) + ';\\\\n';\n }\n const file = join(srcDir, name + '.js');\n writeFileSync(file, src);\n input[name] = file;\n}\n// Prefer the bundler's browser-condition-aware resolution; fall back to resolving\n// from the worker (real install path) only for Rolldown's realpath-anchoring bug.\nconst phResolveCache = new Map();\nconst phVendorResolve = {\n name: 'ph-vendor-resolve', enforce: 'pre',\n async resolveId(source, importer, options) {\n if (externalSet.has(source)) return null;\n if (source[0] === '\\\\0' || source[0] === '.' || isAbsolute(source)) return null;\n if (source.startsWith('node:') || source.startsWith('data:')) return null;\n let viaBundler = null;\n try { viaBundler = await this.resolve(source, importer, { ...options, skipSelf: true }); } catch {}\n if (viaBundler) return viaBundler;\n if (phResolveCache.has(source)) return phResolveCache.get(source);\n let resolved = null;\n try { resolved = fileURLToPath(import.meta.resolve(source)); } catch {}\n phResolveCache.set(source, resolved);\n return resolved;\n },\n};\nawait build({\n root: dirname, configFile: false, logLevel: 'error',\n // Dynamic-base placeholder + vendor segment: connectDynamicBasePlugin rewrites\n // emitted chunk/asset URLs to resolve against the deploy base at serve time.\n base: dynamicBase,\n define: {\n 'process.env.NODE_ENV': '\"development\"',\n // BASE_URL resolves to the deploy base (not the vendor prefix) so vendored\n // Connect's router basename + BASE_URL-relative fetches use the right path.\n 'import.meta.env.BASE_URL': JSON.stringify(DYNAMIC_BASE_PLACEHOLDER),\n },\n // phVendorResolve (pre) resolves bares from the worker; esmExternalRequirePlugin owns\n // react/virtual externalization; connectDynamicBasePlugin (post) rewrites the placeholder base.\n plugins: [phVendorResolve, esmExternalRequirePlugin({ external }), connectDynamicBasePlugin()],\n // pglite ships web workers as ES-module chunks. workerStripPrefix is the vendor\n // segment so the worker recovers the deploy base, not the vendor prefix.\n worker: { format: 'es', plugins: () => [connectDynamicBasePlugin({ forWorker: true, workerStripPrefix: urlPrefix.replace(/^\\\\/+/, '') })] },\n build: {\n outDir: vendorDir, emptyOutDir: false, minify: false, target: 'esnext', cssCodeSplit: true,\n rollupOptions: {\n input, preserveEntrySignatures: 'strict',\n output: { format: 'es', entryFileNames: '[name].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]' },\n },\n },\n});\nrmSync(srcDir, { recursive: true, force: true });\nconst imports = {};\nfor (const spec of include) imports[spec] = urlPrefix + entryName(spec) + '.js';\nwriteFileSync(join(vendorDir, 'import-map.json'), JSON.stringify({ include, external, imports }, null, 2));\n`;\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 type { ConnectCommonOptions } from \"./types.js\";\n\nexport const DEFAULT_CONNECT_OUTDIR = \".ph/connect-build/dist/\" as const;\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","// JSON Schema (draft-07) for dist/powerhouse.config.json — the runtime\n// artifact emitted into the build output and fetched by the Connect SPA at\n// boot.\n//\n// A strict SUBSET of the source PowerhouseConfig schema plus two runtime-only\n// fields (schemaVersion, localPackage). Field shapes shared with the source\n// schema (PowerhousePackage, PHConnectRuntimeConfig) are imported from the\n// shared fragments module so the two schemas stay in sync by construction.\n\nimport {\n phConnectRuntimeConfigSchema,\n powerhousePackageSchema,\n} from \"@powerhousedao/shared/connect\";\n\nexport const RUNTIME_CONFIG_SCHEMA_ID =\n \"https://powerhouse.inc/schemas/powerhouse.config.json\";\n\n// GitHub-hosted schema URL. Points at the JSON artifact committed alongside\n// this TS module. Currently tracks the `main` branch — schema edits go live\n// for editors as soon as they merge. Migrate to a `schema-v<N>` tag pinned\n// to schemaVersion if/when stability across edits becomes a concern.\nexport const RUNTIME_CONFIG_SCHEMA_URL =\n \"https://raw.githubusercontent.com/powerhouse-inc/powerhouse/main/packages/builder-tools/connect-utils/runtime-config.schema.json\";\n\nexport const runtimeConfigSchema = {\n $schema: \"http://json-schema.org/draft-07/schema#\",\n $id: RUNTIME_CONFIG_SCHEMA_ID,\n title: \"Powerhouse Connect runtime configuration\",\n description:\n \"Runtime configuration loaded by Connect at boot from /powerhouse.config.json.\",\n type: \"object\",\n additionalProperties: false,\n required: [\"schemaVersion\", \"packages\", \"localPackage\"],\n properties: {\n $schema: {\n type: \"string\",\n description:\n \"Optional JSON Schema reference for editor autocomplete. Set to the GitHub-hosted schema URL.\",\n },\n schemaVersion: {\n const: 2,\n description:\n \"Schema version. Must match the SPA bundle that ships with this dist. The SPA throws on mismatch to prevent SPA/config skew.\",\n },\n packages: {\n type: \"array\",\n description:\n \"Powerhouse packages this Connect instance loads at runtime.\",\n items: powerhousePackageSchema,\n },\n packageRegistryUrl: {\n type: \"string\",\n description:\n \"Project-wide package registry endpoint. Copied verbatim from the source `powerhouse.config.json` top-level field — the SPA's Package Manager UI reads this directly.\",\n },\n localPackage: {\n description:\n \"Identity of the consumer project itself, captured at build time. null for Docker images and other generic deploys with no host project.\",\n oneOf: [\n { type: \"null\" },\n {\n type: \"object\",\n additionalProperties: false,\n required: [\"name\", \"version\"],\n properties: {\n name: { type: \"string\" },\n version: { type: \"string\" },\n },\n },\n ],\n },\n connect: phConnectRuntimeConfigSchema,\n },\n} as const;\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { Plugin } from \"vite\";\n\nexport type PhBundledPackagesPluginOptions = {\n /**\n * Package names (with `provider: \"local\"` in powerhouse.config.json)\n * that should be bundled into Connect at build time. Each must be\n * resolvable from node_modules.\n */\n packages: string[];\n /** Project root used to read each bundled package's package.json version. */\n projectRoot?: string;\n};\n\nexport const VIRTUAL_ID = \"ph-bundled-packages-virtual\";\nexport const RESOLVED_VIRTUAL_ID = \"\\0virtual:\" + VIRTUAL_ID;\n// Vite serves a resolved id at /@id/<id with \\0 → __x00__>.\nexport const BUNDLED_PACKAGES_DEV_URL =\n \"@id/\" + RESOLVED_VIRTUAL_ID.replace(\"\\0\", \"__x00__\");\n\nfunction readBundledPackageVersion(\n projectRoot: string,\n name: string,\n): string | undefined {\n try {\n const raw = fs.readFileSync(\n path.join(projectRoot, \"node_modules\", name, \"package.json\"),\n \"utf-8\",\n );\n const pkg = JSON.parse(raw) as { version?: unknown };\n return typeof pkg.version === \"string\" ? pkg.version : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction makeRegisterModule(packages: string[], projectRoot: string): string {\n if (packages.length === 0) {\n return \"export default () => {};\\n\";\n }\n const imports: string[] = [];\n const calls: string[] = [];\n\n packages.forEach((name, i) => {\n const moduleName = `pkg${i}`;\n const version = readBundledPackageVersion(projectRoot, name);\n imports.push(`import * as ${moduleName} from ${JSON.stringify(name)};`);\n imports.push(`import ${JSON.stringify(`${name}/style.css`)};`);\n calls.push(\n ` pm.addLocalPackage(${JSON.stringify(name)}, ${moduleName}, ${JSON.stringify(version)});`,\n );\n });\n\n return `${imports.join(\"\\n\")}\\n\\nexport default function register(pm) {\\n${calls.join(\"\\n\")}\\n};\\n`;\n}\n\n/**\n * Emits a virtual module `ph-bundled-packages-virtual` whose default export\n * is a `register(packageManager)` function. When called at runtime (from\n * Connect's bootstrap), it registers each bundled package with the package\n * manager the same way Common/Vetra are registered — meaning they work\n * offline without the registry being reachable.\n *\n * When the list is empty, the module exports a no-op function so Connect's\n * bootstrap code can always import it unconditionally.\n */\nexport function phBundledPackagesPlugin(\n options: PhBundledPackagesPluginOptions,\n): Plugin {\n const projectRoot = options.projectRoot ?? process.cwd();\n const moduleSource = makeRegisterModule(options.packages, projectRoot);\n\n return {\n name: \"vite-plugin-ph-bundled-packages\",\n enforce: \"pre\",\n resolveId(id) {\n if (id === VIRTUAL_ID) return RESOLVED_VIRTUAL_ID;\n },\n load(id) {\n if (id === RESOLVED_VIRTUAL_ID) return moduleSource;\n },\n };\n}\n","import { createRequire } from \"node:module\";\nimport { createReadStream } from \"node:fs\";\nimport path from \"node:path\";\nimport type { Plugin } from \"vite\";\nimport {\n DEFAULT_VENDOR_INCLUDE,\n VENDOR_URL_PREFIX,\n prebuildConnectVendor,\n type PrebuiltVendor,\n} from \"../externalize-vendor.js\";\nimport { BUNDLED_PACKAGES_DEV_URL } from \"./ph-bundled-packages.js\";\n\nconst REACT_DEPS = [\n \"react\",\n \"react-dom\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n \"react-dom/client\",\n];\n\nconst SHIM_PATH = \"__ph/dev-react-shim/\";\nconst VITE_DEPS_PATH = \"node_modules/.vite/deps\";\n\n// Content-Type for the asset extensions the vendor build emits; JS is the default.\nconst VENDOR_MIME: Record<string, string> = {\n \".css\": \"text/css\",\n \".map\": \"application/json\",\n \".json\": \"application/json\",\n \".wasm\": \"application/wasm\",\n \".data\": \"application/octet-stream\",\n \".woff2\": \"font/woff2\",\n \".woff\": \"font/woff\",\n \".ttf\": \"font/ttf\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n};\n\n// Opt-in: also serve the heavy stable Connect libs from a prebuilt vendor\n// bundle, so the long-lived dev server never dep-optimizes them (~1–2 GB\n// resident). Set PH_CONNECT_EXTERNALIZE_VENDOR=1 to enable.\nconst VENDOR_MODE = process.env.PH_CONNECT_EXTERNALIZE_VENDOR === \"1\";\n// Extra specifiers to vendor on top of the defaults, comma-separated. Lets a\n// project add its own stable heavy deps without code changes.\nconst VENDOR_EXTRA = (process.env.PH_CONNECT_VENDOR_EXTRA ?? \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\nconst HEAVY_LIBS = [...DEFAULT_VENDOR_INCLUDE, ...VENDOR_EXTRA];\n\n// Vite serves dev module URLs under the resolved `base`. Join base + path\n// while collapsing the double slash so `base: \"/\"` stays byte-identical.\nfunction withBase(base: string, p: string): string {\n return `${base}${p}`.replace(/\\/{2,}/g, \"/\");\n}\n\n// Keep the matched specifiers bare in dev (Vite otherwise rewrites externals to\n// \"/@id/<spec>\") so the import map resolves them; predicate matching supported.\ntype Externals = Array<string | ((id: string) => boolean)>;\nfunction externalizePlugin(externals: Externals): Plugin | undefined {\n try {\n const require = createRequire(import.meta.url);\n const mod = require(\"vite-plugin-externalize-dependencies\") as {\n default?: (o: { externals: Externals }) => Plugin;\n } & ((o: { externals: Externals }) => Plugin);\n const factory = mod.default ?? mod;\n return factory({ externals });\n } catch {\n return undefined;\n }\n}\n\n/**\n * Dev-only sibling of `esmExternalRequirePlugin`. The build path externalizes\n * React via Rolldown so an importmap hands the same React instance to both\n * Connect and CDN-served editor packages. Rolldown plugins don't run in\n * `vite createServer`, and Vite's pre-bundled CJS deps only expose a `default`\n * export — so a CDN editor that does `import { lazy } from \"react\"` would\n * fail with \"no named export 'lazy'\".\n *\n * This plugin owns the page import map. It always:\n * 1. Forces React into `optimizeDeps.include` so the optimizer always knows\n * about it.\n * 2. Serves a shim per React module at a stable URL. Each shim imports\n * from Vite's live pre-bundled URL (sharing Connect's React instance)\n * and re-exports React's named members so editors importing\n * `{ lazy }`, `{ jsx }`, etc. work.\n * 3. Rewrites the page importmap to point at those shim URLs.\n *\n * When PH_CONNECT_EXTERNALIZE_VENDOR=1 it additionally prebuilds the heavy\n * stable libs (design-system, reactor-browser, …) into a static vendor bundle,\n * externalizes them from the dev server, serves the bundle, and adds them to\n * the SAME import map. The vendor's React imports stay bare → resolve through\n * the React shims above → one React instance across Connect, the vendor, and\n * CDN editors.\n */\n// Async factory: in VENDOR_MODE it runs the vendor prebuild up front (Vite\n// awaits a Promise<PluginOption>), so `vendor` is known before any plugin hook\n// fires. The heavy libs are excluded from the optimizer — and the externalize\n// plugin is added — ONLY when a valid bundle will be served. On prebuild\n// failure they stay dev-optimized (no broken bare imports) and neither the\n// import map nor the externalizer touch them.\nexport async function devReactImportmapPlugin(\n projectRoot: string = process.cwd(),\n): Promise<Plugin | Plugin[]> {\n let namedExports = new Map<string, string[]>();\n let base = \"/\";\n let vendor: PrebuiltVendor | null = null;\n\n if (VENDOR_MODE) {\n const errorRef: { message?: string } = {};\n vendor = await prebuildConnectVendor({\n dirname: projectRoot,\n include: HEAVY_LIBS,\n errorRef,\n });\n if (!vendor) {\n const detail = errorRef.message ? `: ${errorRef.message}` : \"\";\n console.warn(\n `[connect] PH_CONNECT_EXTERNALIZE_VENDOR set but vendor prebuild failed; falling back to dep-optimizing the heavy libs${detail}`,\n );\n }\n }\n\n // Externalize exactly the specifiers in the vendor import map (not broad\n // prefixes) so an undiscovered subpath stays resolvable instead of 404ing.\n const ext = vendor\n ? externalizePlugin([(id) => id in vendor!.imports])\n : undefined;\n if (vendor && !ext) {\n console.warn(\n \"[connect] PH_CONNECT_EXTERNALIZE_VENDOR set and vendor prebuilt, but vite-plugin-externalize-dependencies is not installed; falling back to dep-optimizing the heavy libs (install it to enable the vendor)\",\n );\n }\n const vendorActive = !!(vendor && ext);\n\n const main: Plugin = {\n name: \"ph-dev-react-importmap\",\n apply: \"serve\",\n config(cfg) {\n cfg.optimizeDeps ??= {};\n const include = new Set(cfg.optimizeDeps.include ?? []);\n REACT_DEPS.forEach((d) => include.add(d));\n if (vendorActive) {\n // The heavy libs are served from the prebuilt vendor; force-including\n // them would pre-bundle them anyway (and leave their excluded deps —\n // e.g. zod subpaths — as unmapped bare imports). Drop them from include\n // and exclude them so the optimizer never touches them.\n HEAVY_LIBS.forEach((d) => include.delete(d));\n cfg.optimizeDeps.exclude = [\n ...new Set([...(cfg.optimizeDeps.exclude ?? []), ...HEAVY_LIBS]),\n ];\n }\n cfg.optimizeDeps.include = [...include];\n },\n configResolved(config) {\n base = config.base;\n },\n configureServer(server) {\n // Resolve React's named exports from the consumer project so we don't\n // hardcode lists that drift across React versions.\n const requireFromRoot = createRequire(\n path.join(server.config.root, \"package.json\"),\n );\n namedExports = new Map(\n REACT_DEPS.map((id) => {\n try {\n const mod = requireFromRoot(id) as Record<string, unknown>;\n return [id, Object.keys(mod).filter((k) => k !== \"default\")];\n } catch {\n return [id, []];\n }\n }),\n );\n\n // Serve the prebuilt vendor bundle. Match the base-prefixed URL (chunk/asset\n // URLs carry the deploy base) and the bare prefix; strip whichever matched.\n if (vendorActive) {\n const vendorDir = vendor!.vendorDir;\n const vendorPrefixes = [\n withBase(base, VENDOR_URL_PREFIX),\n VENDOR_URL_PREFIX,\n ];\n server.middlewares.use((req, res, next) => {\n const url = (req.url ?? \"\").split(\"?\")[0];\n const prefix = vendorPrefixes.find((p) => url.startsWith(p));\n if (!prefix) return next();\n const name = url.slice(prefix.length).replace(/^\\/+/, \"\");\n const file = path.join(vendorDir, name);\n // Path-segment containment (not a string prefix): reject anything that\n // escapes vendorDir, incl. siblings like `.ph-vendor.lock`.\n const rel = path.relative(vendorDir, file);\n if (!name || rel.startsWith(\"..\") || path.isAbsolute(rel)) {\n return next();\n }\n // Stream (don't buffer multi-MB wasm/.data); a missing file → next().\n const stream = createReadStream(file);\n stream.on(\"error\", () => {\n if (!res.headersSent) next();\n });\n stream.once(\"open\", () => {\n const ext = file.slice(file.lastIndexOf(\".\"));\n res.setHeader(\n \"Content-Type\",\n VENDOR_MIME[ext] ?? \"text/javascript\",\n );\n // Content-hashed chunks/assets are immutable; entries + map can change.\n const hashed =\n name.startsWith(\"chunks/\") || name.startsWith(\"assets/\");\n res.setHeader(\n \"Cache-Control\",\n hashed ? \"public, max-age=31536000, immutable\" : \"no-cache\",\n );\n stream.pipe(res);\n });\n });\n }\n\n // Match the base-prefixed shim URL, and the bare path for robustness.\n const shimPrefixes = [withBase(base, SHIM_PATH), `/${SHIM_PATH}`];\n server.middlewares.use((req, res, next) => {\n const prefix = shimPrefixes.find((p) => req.url?.startsWith(p));\n if (!prefix) return next();\n const id = req.url!.slice(prefix.length).replace(/\\.js(\\?.*)?$/, \"\");\n if (!REACT_DEPS.includes(id)) return next();\n\n const optimizer = server.environments.client.depsOptimizer;\n const info =\n optimizer?.metadata.optimized[id] ??\n optimizer?.metadata.discovered[id];\n if (!optimizer || !info) {\n res.statusCode = 404;\n res.end();\n return;\n }\n\n const browserHash = info.browserHash ?? optimizer.metadata.browserHash;\n const depUrl = `${withBase(base, VITE_DEPS_PATH)}/${path.basename(info.file)}?v=${browserHash}`;\n const names = namedExports.get(id) ?? [];\n\n res.setHeader(\"Content-Type\", \"application/javascript\");\n res.end(\n `import * as M from ${JSON.stringify(depUrl)};\\n` +\n `const ns = M.default ?? M;\\n` +\n `export default ns;\\n` +\n (names.length\n ? `export const { ${names.join(\", \")} } = ns;\\n`\n : \"\"),\n );\n });\n },\n transformIndexHtml: {\n order: \"post\",\n handler(html, ctx) {\n const browserHash =\n ctx.server?.environments.client.depsOptimizer?.metadata.browserHash;\n if (!browserHash) return;\n const shimPrefix = withBase(base, SHIM_PATH);\n const imports: Record<string, string> = Object.fromEntries(\n REACT_DEPS.map((id) => [\n id,\n `${shimPrefix}${id}.js?v=${browserHash}`,\n ]),\n );\n // Heavy libs resolve to the prebuilt vendor (base-prefixed); their bare\n // React imports fall through to the React shim entries above.\n let dynamicBaseScript = \"\";\n if (vendorActive) {\n for (const [spec, url] of Object.entries(vendor!.imports)) {\n imports[spec] = withBase(base, url);\n }\n // Connect vendored isn't dev-processed, so its dynamic\n // `import(\"ph-bundled-packages-virtual\")` points at the virtual URL.\n if (vendor!.imports[\"@powerhousedao/connect\"]) {\n imports[\"ph-bundled-packages-virtual\"] = withBase(\n base,\n BUNDLED_PACKAGES_DEV_URL,\n );\n }\n // Set the runtime base global so the vendor's rewritten URL exprs\n // resolve to the dev/deploy base (mirrors the proxy at serve time).\n dynamicBaseScript = `<script>globalThis.__PH_DYNAMIC_BASE__=${JSON.stringify(base)};</script>\\n`;\n }\n return html.replace(\n /<script type=\"importmap\">[\\s\\S]*?<\\/script>/,\n `${dynamicBaseScript}<script type=\"importmap\">${JSON.stringify({ imports }, null, 2)}</script>`,\n );\n },\n },\n };\n\n // The externalizer runs alongside `main` so Connect's source leaves the heavy\n // libs bare (→ import map → vendor); React stays optimized via the shims.\n return vendorActive ? [ext!, main] : main;\n}\n","import { readFileSync } from \"node:fs\";\nimport { extname, isAbsolute, resolve } from \"node:path\";\nimport type { Connect, Plugin } from \"vite\";\n\nconst CONTENT_TYPE_BY_EXT: Record<string, string> = {\n \".ico\": \"image/x-icon\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n};\n\n/**\n * Vite plugin to serve the Connect favicon (icon.ico) from the connect package,\n * or from a caller-supplied file when `faviconPath` is set (e.g. `ph connect\n * build --favicon`). The served/emitted name is always `icon.ico` so the static\n * `<link rel=\"icon\" href=\"%BASE_URL%icon.ico\">` in index.html stays valid.\n */\nexport function connectFaviconPlugin(\n opts: { faviconPath?: string } = {},\n): Plugin {\n // Build input, not runtime config: a non-absolute path resolves against the\n // build cwd (= the project dir during `ph connect build`).\n const customPath = opts.faviconPath\n ? isAbsolute(opts.faviconPath)\n ? opts.faviconPath\n : resolve(process.cwd(), opts.faviconPath)\n : undefined;\n const customContentType = customPath\n ? (CONTENT_TYPE_BY_EXT[extname(customPath).toLowerCase()] ?? \"image/x-icon\")\n : \"image/x-icon\";\n\n return {\n name: \"copy-connect-favicon\",\n configureServer(server) {\n // Vite rewrites the favicon link against `base`, so serve the\n // base-prefixed path. Keep the bare path for robustness.\n const base = server.config.base;\n const faviconRoute = `${base}icon.ico`.replace(/\\/{2,}/g, \"/\");\n const handler: Connect.NextHandleFunction = (_req, res, next) => {\n if (customPath) {\n try {\n res.setHeader(\"Content-Type\", customContentType);\n res.end(readFileSync(customPath));\n } catch {\n next();\n }\n return;\n }\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 // Mount on the exact route(s) so the handler only runs for icon.ico.\n // Connect strips the mount prefix before matching, so mounting on\n // \"/icon.ico\" matches that path exactly.\n const paths = new Set([faviconRoute, \"/icon.ico\"]);\n for (const path of paths) {\n server.middlewares.use(path, handler);\n }\n },\n async generateBundle(_options, bundle) {\n try {\n if (\"icon.ico\" in bundle) return;\n let source: Uint8Array | undefined;\n if (customPath) {\n source = readFileSync(customPath);\n } else {\n const resolved = await this.resolve(\n \"@powerhousedao/connect/assets/icon.ico\",\n );\n if (resolved) source = readFileSync(resolved.id);\n }\n if (!source) return;\n this.emitFile({\n type: \"asset\",\n fileName: \"icon.ico\",\n source,\n });\n } catch {\n // favicon source not found, skip\n }\n },\n };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { Plugin } from \"vite\";\nimport type { PowerhousePackage } from \"@powerhousedao/config\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport {\n buildRuntimeConfig,\n DEFAULT_CONNECT_CONFIG,\n deepMerge,\n} from \"@powerhousedao/shared/connect\";\nimport { RUNTIME_CONFIG_SCHEMA_URL } from \"../runtime-config-schema.js\";\n\nexport type PhConfigPluginOptions = {\n packages: PowerhousePackage[];\n projectRoot?: string;\n connect?: PHConnectRuntimeConfig;\n /**\n * Project-wide package registry URL — the effective value (CLI override\n * `??` source) the caller has already resolved. Copied verbatim into the\n * emitted runtime config (no namespace change); the SPA reads\n * `runtimeConfig.packageRegistryUrl` directly.\n */\n packageRegistryUrl?: string;\n /**\n * CLI-supplied connect override (final merge layer, beats source).\n * Forwarded from `ph connect build`'s `--json` + individual `--flag` parsing.\n * See clis/ph-cli/src/utils/cli-connect-override.ts.\n */\n cliConnectOverride?: PHConnectRuntimeConfig;\n};\n\nfunction readProjectPackageInfo(\n projectRoot: string | undefined,\n): { name: string; version: string } | null {\n if (!projectRoot) return null;\n try {\n const raw = fs.readFileSync(\n path.join(projectRoot, \"package.json\"),\n \"utf-8\",\n );\n const pkg = JSON.parse(raw) as { name?: unknown; version?: unknown };\n if (typeof pkg.name !== \"string\" || typeof pkg.version !== \"string\") {\n return null;\n }\n return { name: pkg.name, version: pkg.version };\n } catch {\n return null;\n }\n}\n\nexport function phConfigPlugin(options: PhConfigPluginOptions): Plugin {\n const projectRoot = options.projectRoot ?? process.cwd();\n const localPackage = readProjectPackageInfo(projectRoot);\n\n // Precedence ladder (lowest → highest) for the emitted connect.* block:\n // DEFAULT_CONNECT_CONFIG (base — fills in any field nothing else supplied)\n // < source.connect (user's hand-edited powerhouse.config.json)\n // < cliConnectOverride (`ph connect build --json` + individual flags)\n //\n // Env vars are NOT a layer in this ladder. The Connect SPA's runtime\n // configuration is exclusively set via `powerhouse.config.json` or CLI\n // overrides (`ph connect build --<field>` / `ph connect config --<field>`).\n const sourceConnect = options.connect ?? {};\n const withDefaults = deepMerge(DEFAULT_CONNECT_CONFIG, sourceConnect);\n const mergedConnect = options.cliConnectOverride\n ? deepMerge(withDefaults, options.cliConnectOverride)\n : withDefaults;\n const source = {\n packages: options.packages,\n packageRegistryUrl: options.packageRegistryUrl,\n connect: mergedConnect,\n };\n\n const runtimeConfig = buildRuntimeConfig(source, localPackage);\n const content = JSON.stringify(\n { $schema: RUNTIME_CONFIG_SCHEMA_URL, ...runtimeConfig },\n null,\n 2,\n );\n\n return {\n name: \"vite-plugin-ph-config\",\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n if (req.url?.endsWith(\"/powerhouse.config.json\")) {\n res.setHeader(\"Content-Type\", \"application/json\");\n res.setHeader(\"Cache-Control\", \"no-cache\");\n res.end(content);\n return;\n }\n next();\n });\n },\n hotUpdate: {\n order: \"pre\",\n handler(ctx) {\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: \"powerhouse.config.json\",\n source: content,\n });\n },\n };\n}\n","import { readFileSync } from \"node:fs\";\nimport type { Plugin } from \"vite\";\n\n// PWA manifest icons emitted into the build from the @powerhousedao/connect\n// package assets. The `ph connect build` Vite root is a scaffolded project that\n// has no PWA icons of its own, so — like connectFaviconPlugin does for the\n// favicon — we resolve them out of the installed connect package and emit them\n// as build assets. vite-plugin-pwa references these filenames in the generated\n// manifest and precaches them via its png glob.\nconst PWA_ICONS = [\"pwa-192x192.png\", \"pwa-512x512.png\"] as const;\n\nexport function connectPwaIconsPlugin(): Plugin {\n return {\n name: \"copy-connect-pwa-icons\",\n async generateBundle(_options, bundle) {\n for (const icon of PWA_ICONS) {\n try {\n if (icon in bundle) continue;\n const resolved = await this.resolve(\n `@powerhousedao/connect/assets/${icon}`,\n );\n if (!resolved) continue;\n this.emitFile({\n type: \"asset\",\n fileName: icon,\n source: readFileSync(resolved.id),\n });\n } catch {\n // connect package or icon not found — skip; the manifest still\n // generates, the icon URL just 404s (non-fatal for offline caching).\n }\n }\n },\n };\n}\n","import type { PluginOption } from \"vite\";\nimport { VitePWA } from \"vite-plugin-pwa\";\nimport { connectPwaIconsPlugin } from \"./pwa-icons.js\";\n\n/**\n * Service-worker / PWA support for Connect, gated by `connect.app.offline`.\n *\n * When enabled (the default), Workbox `generateSW` precaches the built app\n * shell so Connect loads with no network, and runtime-caches the Google-hosted\n * Inter font + the runtime config. Registration is left to the Connect SPA\n * (`serviceWorkerManager`, `injectRegister: null`) rather than the plugin's\n * `virtual:pwa-register` module, so the published `@powerhousedao/connect`\n * tsdown build never has to resolve that virtual import.\n *\n * When disabled, a self-destroying worker is emitted at the same URL so any\n * worker a previous offline-enabled build installed unregisters itself and\n * clears its caches on the browser's next service-worker update check.\n */\nexport function connectPwaPlugins(options: {\n offlineEnabled: boolean;\n}): PluginOption[] {\n const { offlineEnabled } = options;\n\n if (!offlineEnabled) {\n return [\n VitePWA({\n selfDestroying: true,\n strategies: \"generateSW\",\n injectRegister: null,\n filename: \"service-worker.js\",\n devOptions: { enabled: false },\n }),\n ];\n }\n\n return [\n connectPwaIconsPlugin(),\n VitePWA({\n strategies: \"generateSW\",\n // prompt → Workbox leaves the new worker waiting and emits a SKIP_WAITING\n // message listener; the SPA surfaces a refresh prompt and posts that\n // message when the user accepts (see serviceWorkerManager).\n registerType: \"prompt\",\n injectRegister: null,\n // Matches nginx's dedicated no-cache location and the SPA's existing\n // registration path.\n filename: \"service-worker.js\",\n // ph connect dev keeps running without a service worker.\n devOptions: { enabled: false },\n // Icons are emitted by connectPwaIconsPlugin and precached via the png\n // glob, so the plugin must not also try to resolve them from /public.\n includeManifestIcons: false,\n manifest: {\n name: \"Powerhouse Connect\",\n short_name: \"Connect\",\n description:\n \"A navigation, collaboration and reporting tool for decentralised and open organisations.\",\n theme_color: \"#ffffff\",\n background_color: \"#ffffff\",\n display: \"standalone\",\n start_url: \".\",\n scope: \".\",\n icons: [\n { src: \"pwa-192x192.png\", sizes: \"192x192\", type: \"image/png\" },\n { src: \"pwa-512x512.png\", sizes: \"512x512\", type: \"image/png\" },\n {\n src: \"pwa-512x512.png\",\n sizes: \"512x512\",\n type: \"image/png\",\n purpose: \"maskable\",\n },\n ],\n },\n workbox: {\n clientsClaim: true,\n skipWaiting: false, // wait for the user to accept the refresh prompt\n cleanupOutdatedCaches: true,\n // PGlite's wasm + fs bundles are several MB each; Workbox's 2 MiB\n // default would silently skip them and the in-browser Postgres would\n // fail to initialise offline. Raise the ceiling so they precache.\n maximumFileSizeToCacheInBytes: 16 * 1024 * 1024,\n // Precache the app shell AND the PGlite assets. The default glob omits\n // `.wasm`/`.data`, but PGlite's Postgres-in-wasm needs both its `.wasm`\n // and its `.data` filesystem bundles, or the in-browser DB fails to\n // initialise offline (\"Failed to fetch\").\n globPatterns: [\n \"**/*.{js,css,html,wasm,data,ico,png,svg,webp,woff,woff2}\",\n ],\n // powerhouse.config.json is operator-editable and served no-cache, so\n // precaching it would freeze runtime config; source maps don't belong\n // in the precache either.\n globIgnores: [\"**/powerhouse.config.json\", \"**/*.map\"],\n navigateFallback: \"index.html\",\n navigateFallbackDenylist: [\n /\\/powerhouse\\.config\\.json$/,\n /^\\/health$/,\n /\\/__/,\n ],\n runtimeCaching: [\n // Inter font stays on Google's CDN (edge perf, no self-hosting); we\n // just cache it after the first online load so it renders offline.\n {\n urlPattern: ({ url }) =>\n url.origin === \"https://fonts.googleapis.com\",\n handler: \"StaleWhileRevalidate\",\n options: { cacheName: \"google-fonts-stylesheets\" },\n },\n {\n urlPattern: ({ url }) => url.origin === \"https://fonts.gstatic.com\",\n handler: \"CacheFirst\",\n options: {\n cacheName: \"google-fonts-webfonts\",\n expiration: {\n maxEntries: 30,\n maxAgeSeconds: 60 * 60 * 24 * 365,\n },\n // statuses [0, 200]: 0 permits opaque cross-origin font responses.\n cacheableResponse: { statuses: [0, 200] },\n },\n },\n // Document-model editors/packages loaded at runtime from the registry\n // CDN. The registry ORIGIN is a runtime value (packageRegistryUrl), so\n // match the stable \"/-/cdn/\" path instead. Two rules (order matters —\n // Workbox is first-match-wins): the unversioned ENTRY points first,\n // then a catch-all for the content-hashed assets.\n //\n // statuses: [0, 200] on BOTH — the editor's JS is a CORS module import\n // (200), but its stylesheet is mounted via cross-origin `@import`\n // (no-cors → opaque/0) and its CSS-referenced images/fonts ≥14 KB are\n // also no-cors (0). [200] alone silently dropped those, so styles and\n // icons broke offline. Opaque responses are still applied/displayed by\n // the browser when served from cache.\n //\n // Entry points (browser/index.js, style.css, package.json) are\n // unversioned/mutable → SWR so installing a newer editor refreshes\n // online; offline serves the cached copy.\n {\n urlPattern: ({ url }) =>\n url.pathname.includes(\"/-/cdn/\") &&\n (url.pathname.endsWith(\"/browser/index.js\") ||\n url.pathname.endsWith(\"/style.css\") ||\n url.pathname.endsWith(\"/package.json\")),\n handler: \"StaleWhileRevalidate\",\n options: {\n cacheName: \"ph-package-cdn-entry\",\n expiration: { maxEntries: 60, maxAgeSeconds: 60 * 60 * 24 * 30 },\n cacheableResponse: { statuses: [0, 200] },\n },\n },\n // Everything else under /-/cdn/ is content-hashed → immutable.\n // CacheFirst: no revalidation (clean offline network tab), never stale\n // (the hash changes when content changes). Caches opaque (no-cors)\n // images/fonts referenced by the editor CSS.\n {\n urlPattern: ({ url }) => url.pathname.includes(\"/-/cdn/\"),\n handler: \"CacheFirst\",\n options: {\n cacheName: \"ph-package-cdn\",\n expiration: { maxEntries: 200, maxAgeSeconds: 60 * 60 * 24 * 30 },\n cacheableResponse: { statuses: [0, 200] },\n },\n },\n // Runtime config: NetworkFirst so a fresh value wins when online, but\n // the last-known config is still served offline (it is precache-\n // ignored above).\n {\n urlPattern: ({ url }) =>\n url.pathname.endsWith(\"/powerhouse.config.json\"),\n handler: \"NetworkFirst\",\n options: { cacheName: \"ph-runtime-config\" },\n },\n ],\n },\n }),\n ];\n}\n","// Self-host React: emit the React family into the Connect dist and point the\n// page import map at it, instead of resolving react/react-dom from esm.sh.\nimport { spawn } from \"node:child_process\";\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname as pathDirname, join, resolve } from \"node:path\";\nimport type { Plugin } from \"vite\";\n\n// URL path (under base) the React bundle is emitted/served at.\nconst REACT_URL_DIR = \"__react__\";\n\n// Packages whose every browser-importable subpath is self-hosted.\nconst REACT_PACKAGES = [\"react\", \"react-dom\"];\n\n// Resolve an exports value to its browser-preferred target, or null.\nfunction importTarget(value: unknown): string | null {\n if (typeof value === \"string\") return value;\n if (!value || typeof value !== \"object\") return null;\n const o = value as Record<string, unknown>;\n for (const c of [\"browser\", \"import\", \"module\", \"default\"]) {\n if (c in o) {\n const t = importTarget(o[c]);\n if (t) return t;\n }\n }\n return null;\n}\n\n// All browser-usable subpaths of react/react-dom, mapped to the absolute file\n// their browser condition resolves to. Node/bun-only targets are skipped.\nfunction resolveReactEntries(dirname: string): Record<string, string> {\n const require = createRequire(join(dirname, \"noop.js\"));\n const out: Record<string, string> = {};\n for (const pkg of REACT_PACKAGES) {\n let pkgRoot: string;\n let exp: unknown;\n try {\n const pkgJsonPath = require.resolve(`${pkg}/package.json`);\n pkgRoot = pathDirname(pkgJsonPath);\n exp = (\n JSON.parse(readFileSync(pkgJsonPath, \"utf8\")) as { exports?: unknown }\n ).exports;\n } catch {\n continue;\n }\n if (!exp || typeof exp !== \"object\") continue;\n for (const key of Object.keys(exp as Record<string, unknown>)) {\n if (key === \"./package.json\" || key.includes(\"*\")) continue;\n const target = importTarget((exp as Record<string, unknown>)[key]);\n // Skip non-JS and runtime-only (node/bun) targets — unusable in a browser.\n if (!target || /\\.(json|css)$/.test(target)) continue;\n if (/\\.(node|bun)\\.js$/.test(target)) continue;\n const file = join(pkgRoot, target);\n if (!existsSync(file)) continue;\n out[key === \".\" ? pkg : `${pkg}${key.slice(1)}`] = file;\n }\n }\n return out;\n}\n\nexport interface ReactSelfHostOptions {\n // Project root used to resolve react/react-dom and run the sub-build.\n dirname: string;\n // Emit the development React build (warnings/act) instead of production.\n dev?: boolean;\n}\n\n// Emits one React variant (dev or prod, per options.dev) into the dist and\n// injects a static import map pointing every react/react-dom subpath at it.\nexport function reactSelfHostPlugin(options: ReactSelfHostOptions): Plugin {\n const entries = resolveReactEntries(options.dirname);\n let absOutDir = resolve(options.dirname, \"dist\");\n let importMap: Record<string, string> = {};\n return {\n name: \"ph-react-self-host\",\n apply: \"build\",\n configResolved(config) {\n absOutDir = resolve(config.root, config.build.outDir);\n // Entry URLs mirror the specifier (react-dom/client -> __react__/react-dom/client.js)\n // so the trailing-slash catch-alls below resolve any subpath to the same file.\n importMap = Object.fromEntries(\n Object.keys(entries).map((spec) => [\n spec,\n `${config.base}${REACT_URL_DIR}/${spec}.js`,\n ]),\n );\n // Catch-all per package: an unenumerated react/* import resolves to the single\n // self-hosted instance (same-origin) instead of failing import-map resolution.\n for (const pkg of REACT_PACKAGES) {\n importMap[`${pkg}/`] = `${config.base}${REACT_URL_DIR}/${pkg}/`;\n }\n },\n transformIndexHtml() {\n if (!Object.keys(importMap).length) return;\n return [\n {\n tag: \"script\",\n attrs: { type: \"importmap\" },\n children: JSON.stringify({ imports: importMap }),\n injectTo: \"head-prepend\",\n },\n ];\n },\n async closeBundle() {\n if (!Object.keys(entries).length) return;\n const { ok, stderr } = await runReactBuild(\n options.dirname,\n join(absOutDir, REACT_URL_DIR),\n entries,\n options.dev ? \"development\" : \"production\",\n );\n if (!ok) {\n this.error(\n `react self-host build failed${stderr.trim() ? `:\\n${stderr.trim()}` : \"\"}`,\n );\n }\n },\n };\n}\n\n// Spawn a throwaway worker that builds the React family; peak build memory is\n// reclaimed when the subprocess exits.\nfunction runReactBuild(\n dirname: string,\n outDir: string,\n entries: Record<string, string>,\n nodeEnv: \"development\" | \"production\",\n): Promise<{ ok: boolean; stderr: string }> {\n mkdirSync(outDir, { recursive: true });\n const workerPath = join(outDir, \"build-worker.mjs\");\n writeFileSync(workerPath, REACT_BUILD_WORKER);\n return new Promise((resolvePromise) => {\n const child = spawn(\n process.execPath,\n [workerPath, dirname, outDir, JSON.stringify(entries), nodeEnv],\n { cwd: dirname, stdio: [\"ignore\", \"pipe\", \"pipe\"] },\n );\n let out = \"\";\n child.stdout.on(\"data\", (d) => (out += String(d)));\n child.stderr.on(\"data\", (d) => (out += String(d)));\n const done = (r: { ok: boolean; stderr: string }) => {\n rmSync(workerPath, { force: true });\n resolvePromise(r);\n };\n child.on(\"exit\", (code) => done({ ok: code === 0, stderr: out }));\n child.on(\"error\", (e) => done({ ok: false, stderr: String(e) }));\n });\n}\n\n// Worker: one ESM entry per subpath with explicit named re-exports. Names come\n// from the browser-resolved file (node names differ for server/static).\nconst REACT_BUILD_WORKER = `\nimport { createRequire } from 'node:module';\nimport { mkdirSync, writeFileSync, rmSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nconst [dirname, outDir, entriesJSON, nodeEnv] = process.argv.slice(2);\nconst entries = JSON.parse(entriesJSON);\nconst reqProj = createRequire(join(dirname, 'noop.js'));\nconst { build } = await import(reqProj.resolve('vite'));\nconst srcDir = join(outDir, '.entries');\nmkdirSync(srcDir, { recursive: true });\nconst entryName = (spec) => spec.replace(/[^\\\\w]+/g, '_');\nconst RESERVED = new Set('enum void null function in instanceof typeof new delete do if else return switch case break continue for while this true false class const let var default export import extends super with yield debugger finally throw try catch await implements interface package private protected public static eval arguments'.split(' '));\nconst input = {};\nfor (const [spec, file] of Object.entries(entries)) {\n const name = entryName(spec);\n let names = [];\n try {\n const ns = await import(pathToFileURL(file).href);\n const obj = (ns.default && typeof ns.default === 'object') ? ns.default : ns;\n names = Object.keys(obj).filter((k) => k !== 'default' && k !== '__esModule' && /^[A-Za-z_$][\\\\w$]*$/.test(k));\n } catch {}\n const plain = names.filter((n) => !RESERVED.has(n));\n const reserved = names.filter((n) => RESERVED.has(n));\n let src = 'import __m from ' + JSON.stringify(spec) + ';\\\\nexport default __m;\\\\n';\n if (plain.length) src += 'export const { ' + plain.join(', ') + ' } = __m;\\\\n';\n reserved.forEach((n, i) => {\n src += 'const __r' + i + ' = __m[' + JSON.stringify(n) + '];\\\\nexport { __r' + i + ' as ' + n + ' };\\\\n';\n });\n const entryFile = join(srcDir, name + '.js');\n writeFileSync(entryFile, src);\n // Key by the full spec so the output path mirrors the subpath\n // (react-dom/client -> react-dom/client.js), matching the catch-all import map.\n input[spec] = entryFile;\n}\ntry {\n await build({\n root: dirname, configFile: false, logLevel: 'error',\n base: './', publicDir: false,\n define: { 'process.env.NODE_ENV': JSON.stringify(nodeEnv) },\n resolve: { conditions: ['browser', 'import', 'module', 'default'] },\n build: {\n outDir, emptyOutDir: false, minify: nodeEnv === 'production', target: 'esnext',\n rollupOptions: {\n input, preserveEntrySignatures: 'strict',\n output: { format: 'es', entryFileNames: '[name].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]' },\n },\n },\n });\n rmSync(srcDir, { recursive: true, force: true });\n // Force exit: rolldown can leave native worker threads alive that keep the\n // event loop open, hanging the parent's spawn() promise indefinitely.\n process.exit(0);\n} catch (err) {\n console.error(err instanceof Error ? (err.stack ?? err.message) : String(err));\n process.exit(1);\n}\n`;\n","import type { Plugin } from \"vite\";\n\n/**\n * Marker attribute on the injected script. Serve-time injectors (e.g. the\n * ph-clint connect proxy) and this plugin both check it, so the script is\n * applied exactly once no matter which layer runs first.\n */\nexport const THEME_BOOT_MARKER = \"data-ph-theme-boot\";\n\n/**\n * Pre-paint theme boot: `?theme=dark|light` persists to `ph:theme`, then the\n * stored choice (or system preference) decides the `.dark` root class before\n * hydration. Fail-silent — storage access can throw in embed/privacy contexts.\n * Keep semantically identical to the runtime store in\n * `@powerhousedao/reactor-browser` (hooks/theme.ts).\n */\nconst THEME_BOOT_SCRIPT =\n `(function(){try{` +\n `var p=new URLSearchParams(location.search).get('theme');` +\n `if(p==='dark'||p==='light')localStorage.setItem('ph:theme',p);` +\n `var s=localStorage.getItem('ph:theme');` +\n `var d=s==='dark'||((!s||s==='system')&&matchMedia('(prefers-color-scheme: dark)').matches);` +\n `document.documentElement.classList.toggle('dark',d);` +\n `}catch(e){}})();`;\n\n/**\n * Injects the theme boot script at the top of `<head>` of every emitted\n * index.html, so built Connect apps render the stored theme from first paint\n * without depending on a serve-time injector.\n */\nexport function connectThemeBootPlugin(): Plugin {\n return {\n name: \"ph-connect-theme-boot\",\n transformIndexHtml(html) {\n if (html.includes(THEME_BOOT_MARKER)) return;\n return {\n html,\n tags: [\n {\n tag: \"script\",\n attrs: { [THEME_BOOT_MARKER]: \"\" },\n children: THEME_BOOT_SCRIPT,\n injectTo: \"head-prepend\",\n },\n ],\n };\n },\n };\n}\n","import type { PowerhouseConfig } from \"@powerhousedao/config\";\nimport { getConfig } from \"@powerhousedao/config/node\";\nimport {\n loadConnectEnv,\n normalizeBasePath,\n setConnectEnv,\n} from \"@powerhousedao/shared/connect\";\nimport tailwind from \"@tailwindcss/vite\";\nimport react from \"@vitejs/plugin-react\";\nimport { realpathSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n createLogger,\n esmExternalRequirePlugin,\n loadEnv,\n searchForWorkspaceRoot,\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 { devReactImportmapPlugin } from \"./vite-plugins/dev-external-react.js\";\nimport {\n DYNAMIC_BASE_PLACEHOLDER,\n connectDynamicBasePlugin,\n} from \"./vite-plugins/dynamic-base.js\";\nimport { connectFaviconPlugin } from \"./vite-plugins/favicon.js\";\nimport { phBundledPackagesPlugin } from \"./vite-plugins/ph-bundled-packages.js\";\nimport { phConfigPlugin } from \"./vite-plugins/ph-config.js\";\nimport { connectPwaPlugins } from \"./vite-plugins/pwa.js\";\nimport { reactSelfHostPlugin } from \"./vite-plugins/react-self-host.js\";\nimport { connectThemeBootPlugin } from \"./vite-plugins/theme-boot.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'${registryUrl ? \" \" + registryUrl : \"\"}; worker-src 'self' blob:; 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 parsePackagesEnvOverride(phPackagesStr: string) {\n return phPackagesStr\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n .map((entry) => {\n const lastAt = entry.lastIndexOf(\"@\");\n if (lastAt > 0) {\n return {\n packageName: entry.slice(0, lastAt),\n version: entry.slice(lastAt + 1),\n provider: \"registry\" as const,\n };\n }\n return { packageName: entry, provider: \"registry\" as const };\n });\n}\n\nfunction getLocalPackageNamesFromPowerhouseConfig({\n packages,\n}: PowerhouseConfig) {\n if (!packages) return [];\n return packages\n .filter((p) => p.provider === \"local\")\n .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 > 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 // Source config is always the project-root powerhouse.config.json.\n const phConfigPath = join(options.dirname, \"powerhouse.config.json\");\n\n const phConfig = options.powerhouseConfig ?? getConfig(phConfigPath);\n\n const packagesFromConfig = phConfig.packages ?? [];\n const localPackagesFromConfig =\n getLocalPackageNamesFromPowerhouseConfig(phConfig);\n const phPackagesStr = env.PH_PACKAGES;\n const envPhPackages = phPackagesStr\n ? parsePackagesEnvOverride(phPackagesStr)\n : undefined;\n\n const phPackages = envPhPackages ?? packagesFromConfig;\n\n // Precedence (highest → lowest): `ph connect build --packages-registry`\n // CLI override > source-config `packageRegistryUrl`. The resolved value\n // flows both into the CSP header (script-src allowance for the registry\n // CDN) and into the emitted runtime config so the SPA reads the same\n // value.\n const phPackageRegistryUrl =\n options.cliPackageRegistryUrl ?? phConfig.packageRegistryUrl ?? null;\n\n // Base path is a runtime-config field (connect.app.basePath), not an env\n // var. Resolve it with the same precedence as the rest of the connect\n // config: CLI override > source powerhouse.config.json.\n const connectBasePath =\n options.cliConnectOverride?.app?.basePath ??\n phConfig.connect?.app?.basePath;\n\n const offlineEnabled =\n options.cliConnectOverride?.app?.offline ??\n phConfig.connect?.app?.offline ??\n true;\n\n const authToken = env.PH_SENTRY_AUTH_TOKEN;\n const org = env.PH_SENTRY_ORG;\n const project = env.PH_SENTRY_PROJECT;\n // Release tag derived from the workspace version so it matches the\n // sourcemap upload tag CI uses.\n const release =\n process.env.WORKSPACE_VERSION ??\n process.env.npm_package_version ??\n env.PH_CONNECT_VERSION;\n const uploadSentrySourcemaps = authToken && org && project;\n\n const connectHtmlTags = getConnectHtmlTags({\n registryUrl: phPackageRegistryUrl,\n });\n\n // Dev needs a placeholder importmap for devReactImportmapPlugin to rewrite;\n // builds get their map from reactSelfHostPlugin's boot script instead.\n const devImportmapTag =\n mode === \"development\"\n ? [\n {\n tag: \"script\",\n attrs: { type: \"importmap\" },\n children: JSON.stringify({ imports: {} }),\n injectTo: \"head-prepend\" as const,\n },\n ]\n : [];\n\n const plugins: PluginOption[] = [\n tailwind(),\n react(),\n createHtmlPlugin({\n minify: false,\n inject: {\n tags: [...connectHtmlTags, ...devImportmapTag],\n },\n }),\n ] as const;\n\n if (uploadSentrySourcemaps) {\n plugins.push(\n import(\"@sentry/vite-plugin\").then(({ sentryVitePlugin }) =>\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 }),\n ) as PluginOption,\n );\n }\n\n // hide warnings unless LOG_LEVEL is set to debug, or the source config\n // declares connect.app.logLevel = \"debug\"\n const isDebug =\n process.env.LOG_LEVEL === \"debug\" ||\n phConfig.connect?.app?.logLevel === \"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 // pnpm `link:` deps (e.g. a downstream project linking @powerhousedao/*\n // packages from a sibling monorepo checkout) live outside Vite's\n // auto-detected workspace root. Their `node_modules/.pnpm/...` assets\n // then 403 through `/@fs/`, returning a 760-byte HTML body where the\n // binary should be — which breaks PGlite at startup with \"Invalid FS\n // bundle size: 760 !== 4939170\". Resolve key linked packages back to\n // their real workspace roots and allow Vite to serve from there.\n const linkedRoots = [\n \"@powerhousedao/reactor-browser\",\n \"@powerhousedao/connect\",\n \"@electric-sql/pglite\",\n ]\n .map((pkg) => {\n try {\n return searchForWorkspaceRoot(\n realpathSync(join(options.dirname, \"node_modules\", pkg)),\n );\n } catch {\n return null;\n }\n })\n .filter((p): p is string => p !== null);\n\n const config: InlineConfig = {\n configFile: false,\n mode,\n // Prefix served/built asset URLs so Connect can run under a path prefix\n // (reverse proxy). Mirrors the client router basename; normalize so a bare\n // `app` or `/app` becomes `/app/` and matches the router.\n //\n // Dynamic-base mode: set a placeholder token instead of a concrete base.\n // connectDynamicBasePlugin (below) rewrites it in the emitted JS to a\n // runtime expression so one bundle serves under any subpath; the proxy\n // substitutes it in the HTML and sets the runtime global at serve time.\n base: options.dynamicBase\n ? DYNAMIC_BASE_PLACEHOLDER\n : connectBasePath\n ? normalizeBasePath(connectBasePath)\n : undefined,\n server: {\n watch: {\n ignored: [\"**/backup-documents/**\", \"**/.ph/**\"],\n },\n fs: {\n allow: [searchForWorkspaceRoot(options.dirname), ...linkedRoots],\n },\n },\n resolve: {\n dedupe: [\"react\", \"react-dom\"],\n tsconfigPaths: true,\n },\n define: {\n PH_CONNECT_SENTRY_RELEASE: JSON.stringify(release || \"unknown\"),\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 // phConfigPlugin 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 phConfigPlugin({\n packages: phPackages,\n projectRoot: options.dirname,\n connect: phConfig.connect,\n packageRegistryUrl: phPackageRegistryUrl ?? undefined,\n cliConnectOverride: options.cliConnectOverride,\n }),\n phBundledPackagesPlugin({\n packages: localPackagesFromConfig,\n projectRoot: options.dirname,\n }),\n // Dev-only: rewrite the importmap to Vite's pre-bundled React so Connect\n // and CDN editors share one instance (build uses reactSelfHostPlugin).\n devReactImportmapPlugin(options.dirname),\n ...plugins,\n // Externalize React so Connect + CDN editors share one instance via the\n // import map (reactSelfHostPlugin URLs); also rewrites external require().\n esmExternalRequirePlugin({ external: reactExternal }),\n // Build-only: emit the React family into the dist + static import map, so\n // React is self-hosted (not esm.sh). Dev React for non-prod/debug builds.\n reactSelfHostPlugin({\n dirname: options.dirname,\n dev: mode !== \"production\" || isDebug,\n }),\n connectFaviconPlugin({ faviconPath: options.favicon }),\n // Pre-paint theme boot in every emitted index.html (marker-idempotent\n // with the serve-time injection in the ph-clint connect proxy).\n connectThemeBootPlugin(),\n // enforce: \"post\" — rewrites the placeholder base after all other\n // transforms have emitted their asset/chunk URLs.\n ...(options.dynamicBase ? [connectDynamicBasePlugin()] : []),\n // PWA / service worker last, so its precache manifest sees every emitted\n // asset (including the icons connectPwaIconsPlugin emits).\n ...connectPwaPlugins({ offlineEnabled }),\n ],\n worker: {\n format: \"es\",\n // Worker chunks are emitted by a separate Rolldown build, so the main\n // bundle's generateBundle never sees them. The worker instance both\n // rewrites the placeholder and prepends a prelude that resolves the base\n // in worker scope (forWorker) — the proxy only sets the global on the\n // main thread.\n ...(options.dynamicBase\n ? { plugins: () => [connectDynamicBasePlugin({ forWorker: true })] }\n : {}),\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,2BAA2B;;;;;;AAOxC,MAAM,iBAAiB;AAIvB,MAAM,YAAY,IAAI,eAAe;AAIrC,SAAS,cAAc,aAA6B;AAIlD,QAAO,GAAG,eAAe,mCADV,gBAAgB,YAAY,CAAC,QAAQ,OAAO,MAAM,CACE;;AAcrE,MAAM,sBAAsB,IAAI,OAC9B,WAAW,gBAAgB,yBAAyB,CAAC,wBACrD,IACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BD,SAAgB,yBACd,UAA+D,EAAE,EACzD;AACR,QAAO;EACL,MAAM;EACN,SAAS;EACT,YAAY,MAAM,OAAO;AACvB,OAAI,CAAC,KAAK,SAAA,wBAAkC,CAAE,QAAO;GAErD,MAAM,IAAI,IAAI,YAAY,KAAK;AAC/B,QAAK,MAAM,SA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ACD,QAAQ,EACN,2BAA2B,KAAK,UAAU,WAAW,UAAU,EAChE;EACD;EACA,WAAW,CAAC,cAAc;EAC1B,cAAc;GACZ,SAAS;IACP;IACA;IACA;IACA;IACA;IACD;GACD,SAAS,CAAC,wBAAwB,6BAA6B;GAChE;EACD,SAAS;GAIP,eAAe;IACb,UAAU;IACV,aAAa,QAAQ;IACrB,SAAS,SAAS;IAClB,oBAAoB,wBAAwB,KAAA;IAC5C,oBAAoB,QAAQ;IAC7B,CAAC;GACF,wBAAwB;IACtB,UAAU;IACV,aAAa,QAAQ;IACtB,CAAC;GAGF,wBAAwB,QAAQ,QAAQ;GACxC,GAAG;GAGH,yBAAyB,EAAE,UAAU,eAAe,CAAC;GAGrD,oBAAoB;IAClB,SAAS,QAAQ;IACjB,KAAK,SAAS,gBAAgB;IAC/B,CAAC;GACF,qBAAqB,EAAE,aAAa,QAAQ,SAAS,CAAC;GAGtD,wBAAwB;GAGxB,GAAI,QAAQ,cAAc,CAAC,0BAA0B,CAAC,GAAG,EAAE;GAG3D,GAAG,kBAAkB,EAAE,gBAAgB,CAAC;GACzC;EACD,QAAQ;GACN,QAAQ;GAMR,GAAI,QAAQ,cACR,EAAE,eAAe,CAAC,yBAAyB,EAAE,WAAW,MAAM,CAAC,CAAC,EAAE,GAClE,EAAE;GACP;EACD,OAAO,EACL,WAAW,MACZ;EACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["importTarget","pathDirname","dirname","FILE_HANDLER_ACTION","dirname","pathDirname"],"sources":["../connect-utils/constants.ts","../connect-utils/vite-plugins/dynamic-base.ts","../connect-utils/externalize-vendor.ts","../connect-utils/helpers.ts","../connect-utils/runtime-config-schema.ts","../connect-utils/vite-plugins/ph-bundled-packages.ts","../connect-utils/vite-plugins/dev-external-react.ts","../connect-utils/vite-plugins/favicon.ts","../connect-utils/vite-plugins/ph-config.ts","../connect-utils/vite-plugins/pwa-packages.ts","../connect-utils/vite-plugins/pwa-icons.ts","../connect-utils/vite-plugins/pwa-overrides.ts","../connect-utils/vite-plugins/pwa.ts","../connect-utils/vite-plugins/react-self-host.ts","../connect-utils/vite-plugins/theme-boot.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 MagicString from \"magic-string\";\nimport type { Plugin } from \"vite\";\n\n/**\n * Placeholder base used when Connect is built in dynamic-base mode. The Vite\n * `base` option is set to this token; this plugin rewrites it in the emitted\n * output so the effective base is resolved at serve time from a global instead\n * of being baked at build time.\n *\n * Trailing slash matches `normalizeBasePath` output, so the token sits in the\n * same syntactic position as a concrete base would.\n */\nexport const DYNAMIC_BASE_PLACEHOLDER = \"/__PH_DYNAMIC_BASE__/\";\n\n/**\n * Global the runtime (ph-clint proxy) must set before the entry bundle loads.\n * Value is the normalized deploy base, e.g. \"/myagent/\" or \"/\". The JS rewrite\n * below resolves all asset / lazy-chunk / BASE_URL references against it.\n */\nconst RUNTIME_GLOBAL = \"globalThis.__PH_DYNAMIC_BASE__\";\n\n// `(globalThis.__PH_DYNAMIC_BASE__||\"/\")` — used everywhere the placeholder\n// base prefix appears in emitted JS.\nconst BASE_EXPR = `(${RUNTIME_GLOBAL}||\"/\")`;\n\n// Worker prelude: derive the deploy base in worker scope from the worker's own\n// URL (proxy sets the global on the main thread only).\nfunction workerPrelude(stripPrefix: string): string {\n // `stripPrefix` is the segment between the deploy base and `assets/` (default\n // \"\" → strip `assets/<file>`; vendor passes \"__vendor__/\").\n const prefix = escapeForRegExp(stripPrefix).replace(/\\//g, \"\\\\/\");\n return `${RUNTIME_GLOBAL}=self.location.pathname.replace(/${prefix}assets\\\\/[^/]*$/,\"\");\\n`;\n}\n\n// Match a string literal whose content STARTS with the placeholder, in any of\n// the three JS quote styles Rolldown emits (double, single, backtick). Group 1\n// captures the opening quote; the closing quote must be the same character\n// (backreference), so a double-quoted literal may contain ' or ` and vice\n// versa. Group 2 captures the literal text after the placeholder up to the\n// closing quote. Rolldown emits the base both as a bare literal (the inlined\n// BASE_URL) and as a `<base>`+suffix (preload/asset URL prefix); both start at\n// the placeholder. The content stops at `$`, so a template literal that\n// interpolates after the token (`` `<token>...${expr}` ``) is NOT rewritten —\n// the residual-token assertion in `generateBundle` fails the build instead of\n// shipping the raw placeholder.\nconst PLACEHOLDER_LITERAL = new RegExp(\n `([\"'\\`])${escapeForRegExp(DYNAMIC_BASE_PLACEHOLDER)}((?:(?!\\\\1)[^$])*)\\\\1`,\n \"g\",\n);\n\n/**\n * Rewrites the placeholder base in emitted JS chunks to a runtime expression so\n * one built `dist/connect` serves under any subpath. Rolldown-native: per-match\n * MagicString edits in `renderChunk`, no AST splicing (the SWC byte-offset\n * splicing in vite-plugin-dynamic-base corrupts Rolldown chunks). Each edited\n * chunk returns a hires sourcemap that the bundler composes into the chunk's\n * map chain, so the emitted `.map` files track the rewrite (and the worker\n * prelude's line shift).\n *\n * What gets rewritten in JS, all of which emit the base as a quoted string\n * literal beginning with the placeholder:\n * - asset URLs (`new URL(\"/__PH_DYNAMIC_BASE__/assets/x.png\", ...)`)\n * - dynamic-import / lazy-chunk preload URLs\n * - the inlined `import.meta.env.BASE_URL` (drives Connect's router basename\n * and BASE_URL-relative fetches such as `${BASE_URL}ph-packages.json`)\n *\n * A literal `\"/__PH_DYNAMIC_BASE__/foo\"` becomes `((globalThis.__PH_DYNAMIC_BASE__||\"/\")+\"foo\")`;\n * a bare `\"/__PH_DYNAMIC_BASE__/\"` (the BASE_URL value) becomes `(globalThis.__PH_DYNAMIC_BASE__||\"/\")`.\n *\n * HTML is left untouched: the entry `<script>`/`<link>` tags keep the literal\n * placeholder so the proxy substitutes it with the concrete base at serve time\n * (the same proxy also sets the runtime global for the JS rewrite). See the\n * plugin's module doc / report for the exact serve-time contract.\n *\n * CSS `url(...)` references resolve relative to the stylesheet's own URL, so\n * they need no rewrite once the stylesheet itself is loaded from the right\n * prefix (which the HTML substitution handles).\n */\nexport function connectDynamicBasePlugin(\n options: { forWorker?: boolean; workerStripPrefix?: string } = {},\n): Plugin {\n return {\n name: \"ph-connect-dynamic-base\",\n enforce: \"post\",\n renderChunk(code, chunk) {\n if (!code.includes(DYNAMIC_BASE_PLACEHOLDER)) return null;\n\n const s = new MagicString(code);\n for (const match of code.matchAll(PLACEHOLDER_LITERAL)) {\n const rest = match[2];\n s.overwrite(\n match.index,\n match.index + match[0].length,\n rest.length === 0\n ? BASE_EXPR\n : `(${BASE_EXPR}+${JSON.stringify(rest)})`,\n );\n }\n\n // Worker chunks run in their own global scope where the proxy never\n // sets the runtime global; derive it from the worker's script URL so\n // the rewritten references above resolve against the deploy base.\n if (options.forWorker) {\n s.prepend(workerPrelude(options.workerStripPrefix ?? \"\"));\n this.info(\n `dynamic-base: worker prelude prepended to ${chunk.fileName}`,\n );\n }\n\n if (!s.hasChanged()) return null;\n return { code: s.toString(), map: s.generateMap({ hires: true }) };\n },\n generateBundle(_options, bundle) {\n // A residual token in JS (a literal the regex couldn't rewrite, e.g. a\n // template interpolating after the token) or CSS (url() must stay\n // stylesheet-relative; the placeholder would ship verbatim and 404)\n // would fail silently at runtime — fail the build instead. HTML keeps\n // the token by design: the proxy substitutes it at serve time.\n for (const file of Object.values(bundle)) {\n const content =\n file.type === \"chunk\"\n ? file.code\n : file.fileName.endsWith(\".css\") && typeof file.source === \"string\"\n ? file.source\n : undefined;\n if (content?.includes(DYNAMIC_BASE_PLACEHOLDER)) {\n this.error(\n `dynamic-base: unrewritten placeholder ${DYNAMIC_BASE_PLACEHOLDER} remains in ${file.fileName}`,\n );\n }\n }\n },\n };\n}\n\nexport function escapeForRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","/**\n * Prebuild the heavy, stable Connect dependencies into a static ESM \"vendor\"\n * bundle so the dev server never runs (or holds) the dependency optimizer /\n * module graph for them.\n *\n * The reactor-project preview dev-optimizes a large UI graph (Connect itself,\n * design-system, document-engineering, reactor-browser, …) every session —\n * ~1–2 GB resident — even though those libs don't change; only the project's\n * editors do. This module builds them ONCE with `vite build` (in a throwaway\n * subprocess that exits, freeing the build's peak memory): `vite build` handles\n * CSS/asset imports, web workers, and WASM (Connect's in-browser PGlite ships\n * all three), and a multi-entry build with `preserveEntrySignatures: 'strict'`\n * dedupes shared code into shared chunks. Entries for CJS deps re-export the\n * module's named API explicitly (so `import { createRoot }` works); ESM deps\n * use `export *`. The build runs under a dynamic-base placeholder + vendor\n * segment (`connectDynamicBasePlugin`), so emitted asset/chunk URLs\n * (`new URL(…, import.meta.url)` for .wasm/.data/workers) carry the placeholder\n * and resolve at serve time to `<deploy-base>__vendor__/`, while the vendored\n * Connect's `import.meta.env.BASE_URL` resolves to the deploy base.\n *\n * The React family stays EXTERNAL (see `VENDOR_EXTERNAL`); `esmExternalRequirePlugin`\n * owns that externalization and rewrites CJS `require(\"react\")` → import. Vendor\n * chunks keep bare React imports, which the dev import map resolves to Vite's\n * pre-bundled React (`devReactImportmapPlugin`) — one React instance across the\n * vendor, the project's editors, and CDN-loaded editors.\n *\n * `devReactImportmapPlugin` consumes the result: it externalizes these\n * specifiers in the long-lived dev server, points the page import map at the\n * vendor URLs, and serves the bundle. With Connect vendored, the dev server only\n * processes the project's own `main` + local package; HMR for them is unaffected.\n */\nimport { spawn } from \"node:child_process\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n existsSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n realpathSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname as pathDirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { DYNAMIC_BASE_PLACEHOLDER } from \"./vite-plugins/dynamic-base.js\";\n\nexport interface VendorPrebuildOptions {\n /** Project root (the reactor-project dir). */\n dirname: string;\n /** Bare specifiers to bundle into the vendor (defaults to the heavy libs). */\n include?: string[];\n /** Specifiers left external to the build (defaults to the React family). */\n external?: string[];\n /** Directory to hold the static vendor bundle + import map. */\n vendorDir?: string;\n /** Filled with the failure cause when the prebuild returns null. */\n errorRef?: { message?: string };\n}\n\n/**\n * The stable Connect libraries worth prebuilding. The React family is NOT here —\n * it's externalized from the build (see `VENDOR_EXTERNAL`) so the vendor shares\n * the dev server's single React instance via the import map.\n */\nexport const DEFAULT_VENDOR_INCLUDE = [\n \"@powerhousedao/connect\",\n \"document-model\",\n \"zod\",\n \"@powerhousedao/design-system/connect\",\n \"@powerhousedao/reactor-browser\",\n \"@powerhousedao/document-engineering\",\n];\n\n/**\n * React-family specifiers kept external to the vendor build. The vendor's chunks\n * emit bare imports for these; `devReactImportmapPlugin`'s import map resolves\n * them to Vite's pre-bundled React, so there is exactly one React instance.\n */\nexport const VENDOR_EXTERNAL = [\n \"react\",\n \"react-dom\",\n \"react-dom/client\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n // Dev-server virtual module (bundled local packages). Connect imports it in a\n // try/catch; left external so the build doesn't try to resolve it and the dev\n // server / import map resolves it at runtime.\n \"ph-bundled-packages-virtual\",\n];\n\nexport interface PrebuiltVendor {\n vendorDir: string;\n /** import map: bare specifier -> \"/__vendor__/<entry>.js\". */\n imports: Record<string, string>;\n}\n\n/** URL prefix the vendor bundle is served under by the dev middleware. */\nexport const VENDOR_URL_PREFIX = \"/__vendor__/\";\n\n// Vite `base` for the vendor build: dynamic-base placeholder + vendor segment.\n// connectDynamicBasePlugin rewrites it so chunk/asset URLs resolve at serve time.\nconst VENDOR_DYNAMIC_BASE = `${DYNAMIC_BASE_PLACEHOLDER}${VENDOR_URL_PREFIX.replace(/^\\/+/, \"\")}`;\n\n/**\n * Build the prebuilt vendor (once, in a throwaway subprocess) and return its dir\n * + import map. Idempotent: reuses a cached vendor built for the same dep set.\n * Returns null on any failure (caller falls back to a normal dev server).\n */\nexport async function prebuildConnectVendor(\n options: VendorPrebuildOptions,\n): Promise<PrebuiltVendor | null> {\n const include = expandIncludeSubpaths(\n options.dirname,\n options.include ?? DEFAULT_VENDOR_INCLUDE,\n );\n const external = options.external ?? VENDOR_EXTERNAL;\n const vendorDir =\n options.vendorDir ?? join(options.dirname, \"node_modules/.ph-vendor\");\n const importMapPath = join(vendorDir, \"import-map.json\");\n // A version change of any vendored dep must invalidate the cache, so the\n // resolved versions are part of the key (not just the specifier lists).\n const versionDigest = resolveVersionDigest(options.dirname, [\n ...include,\n ...external,\n ]);\n\n try {\n const hit = readCacheHit(importMapPath, include, external, versionDigest);\n if (hit) return { vendorDir, imports: hit };\n\n // Serialize concurrent builders on a lock dir; a loser waits for the\n // winner's result instead of clobbering the shared output.\n const lockDir = `${vendorDir}.lock`;\n const lock = acquireLock(lockDir);\n if (!lock) {\n const imports = await waitForCacheHit(\n importMapPath,\n include,\n external,\n versionDigest,\n lockDir,\n );\n return imports ? { vendorDir, imports } : null;\n }\n\n try {\n // Recheck under the lock: another builder may have finished while we\n // were acquiring it.\n const raced = readCacheHit(\n importMapPath,\n include,\n external,\n versionDigest,\n );\n if (raced) return { vendorDir, imports: raced };\n\n const imports = await buildVendorAtomic(\n options.dirname,\n vendorDir,\n include,\n external,\n versionDigest,\n );\n return imports ? { vendorDir, imports } : null;\n } finally {\n releaseLock(lock);\n }\n } catch (err) {\n if (options.errorRef)\n options.errorRef.message =\n err instanceof Error ? err.message : String(err);\n return null;\n }\n}\n\ninterface VendorCacheMeta {\n include?: string[];\n external?: string[];\n versionDigest?: string;\n imports: Record<string, string>;\n}\n\n// Return the cached import map iff the specifier sets AND the resolved-version\n// digest all match; otherwise null (forces a rebuild).\nfunction readCacheHit(\n importMapPath: string,\n include: string[],\n external: string[],\n versionDigest: string,\n): Record<string, string> | null {\n if (!existsSync(importMapPath)) return null;\n try {\n const cached = JSON.parse(\n readFileSync(importMapPath, \"utf8\"),\n ) as VendorCacheMeta;\n if (\n sameSet(cached.include, include) &&\n sameSet(cached.external, external) &&\n cached.versionDigest === versionDigest\n ) {\n return cached.imports;\n }\n } catch {\n // partial/corrupt import-map.json → treat as miss\n }\n return null;\n}\n\n// Hash the resolved version of each spec's owning package (from its installed\n// package.json). A bump or branch checkout that changes any version yields a\n// different digest, invalidating the cache. Unresolvable specs contribute a\n// sentinel so they don't silently collide.\nfunction resolveVersionDigest(dirname: string, specs: string[]): string {\n const seen = new Map<string, string>();\n for (const spec of specs) {\n const { pkg } = parsePkg(spec);\n if (seen.has(pkg)) continue;\n let version = \"missing\";\n try {\n const pkgRoot = realpathSync(join(dirname, \"node_modules\", pkg));\n const meta = JSON.parse(\n readFileSync(join(pkgRoot, \"package.json\"), \"utf8\"),\n ) as { version?: string };\n version = String(meta.version ?? \"unknown\");\n } catch {\n // leave sentinel\n }\n seen.set(pkg, version);\n }\n const h = createHash(\"sha256\");\n // Fold in the build worker so a logic/build-option change busts stale bundles,\n // not just a dep version bump.\n const workerHash = createHash(\"sha256\")\n .update(VENDOR_BUILD_WORKER)\n .digest(\"hex\");\n h.update(`worker:${workerHash}\\n`);\n for (const pkg of [...seen.keys()].sort()) {\n h.update(`${pkg}@${seen.get(pkg)}\\n`);\n }\n return h.digest(\"hex\").slice(0, 16);\n}\n\nfunction sameSet(a: string[] | undefined, b: string[]): boolean {\n if (!a || a.length !== b.length) return false;\n const s = new Set(a);\n return b.every((x) => s.has(x));\n}\n\n// Exclusive lock via mkdir (atomic on POSIX). The holder heartbeats an owner\n// file so a live (slow) build keeps it fresh; a crashed builder lets it go stale.\nconst LOCK_STALE_MS = 5 * 60_000;\nconst LOCK_HEARTBEAT_MS = 60_000;\n\ninterface VendorLock {\n dir: string;\n token: string;\n timer: ReturnType<typeof setInterval>;\n}\n\nconst ownerFile = (lockDir: string): string => join(lockDir, \"owner\");\n\n// Stale iff the owner file hasn't been heartbeated within LOCK_STALE_MS. A\n// missing owner file means a builder mid-acquire — treat as fresh, don't steal.\nfunction lockIsStale(lockDir: string): boolean {\n try {\n return Date.now() - statSync(ownerFile(lockDir)).mtimeMs > LOCK_STALE_MS;\n } catch {\n return false;\n }\n}\n\nfunction acquireLock(lockDir: string): VendorLock | null {\n let made = false;\n try {\n mkdirSync(lockDir);\n made = true;\n } catch {\n if (lockIsStale(lockDir)) {\n try {\n rmSync(lockDir, { recursive: true, force: true });\n mkdirSync(lockDir);\n made = true;\n } catch {\n // lost the reclaim race to another builder\n }\n }\n }\n if (!made) return null;\n const token = `${process.pid}-${randomUUID()}`;\n writeFileSync(ownerFile(lockDir), token);\n // Refresh mtime while we still own it; stop if a stale-reclaim handed it off.\n const timer = setInterval(() => {\n try {\n if (readFileSync(ownerFile(lockDir), \"utf8\") === token) {\n writeFileSync(ownerFile(lockDir), token);\n } else {\n clearInterval(timer);\n }\n } catch {\n clearInterval(timer);\n }\n }, LOCK_HEARTBEAT_MS);\n timer.unref();\n return { dir: lockDir, token, timer };\n}\n\n// Remove only if we still own it — a stale-reclaim may have handed the lock to\n// another builder, whose dir we must not delete.\nfunction releaseLock(lock: VendorLock): void {\n clearInterval(lock.timer);\n try {\n if (readFileSync(ownerFile(lock.dir), \"utf8\") === lock.token) {\n rmSync(lock.dir, { recursive: true, force: true });\n }\n } catch {\n // owner file gone/unreadable — leave it for the stale path\n }\n}\n\n// Loser path: poll for the winner to publish a matching import-map.json, until\n// the lock is released or a timeout elapses.\nasync function waitForCacheHit(\n importMapPath: string,\n include: string[],\n external: string[],\n versionDigest: string,\n lockDir: string,\n): Promise<Record<string, string> | null> {\n const deadline = Date.now() + LOCK_STALE_MS;\n while (Date.now() < deadline) {\n const hit = readCacheHit(importMapPath, include, external, versionDigest);\n if (hit) return hit;\n if (!existsSync(lockDir)) {\n // winner finished (or gave up); one last read\n return readCacheHit(importMapPath, include, external, versionDigest);\n }\n await new Promise((r) => setTimeout(r, 250));\n }\n return null;\n}\n\n// Resolve an exports entry to the file it loads under browser/import\n// conditions, or null if none (e.g. document-model's node-only `./node`). Used\n// to skip node-only and CSS/JSON subpaths the browser-targeted build can't take.\nfunction importTarget(value: unknown): string | null {\n if (typeof value === \"string\") return value;\n if (!value || typeof value !== \"object\") return null;\n const o = value as Record<string, unknown>;\n for (const c of [\"browser\", \"import\", \"module\", \"default\"]) {\n if (c in o) {\n const t = importTarget(o[c]);\n if (t) return t;\n }\n }\n return null;\n}\n\nfunction parsePkg(spec: string): { pkg: string; sub: string } {\n if (spec.startsWith(\"@\")) {\n const parts = spec.split(\"/\");\n return { pkg: parts.slice(0, 2).join(\"/\"), sub: parts.slice(2).join(\"/\") };\n }\n const i = spec.indexOf(\"/\");\n return i === -1\n ? { pkg: spec, sub: \"\" }\n : { pkg: spec.slice(0, i), sub: spec.slice(i + 1) };\n}\n\n/**\n * Connect imports the heavy libs by subpath too (e.g.\n * `@powerhousedao/design-system/connect/toast`, `zod/v4/core`). Those bare\n * imports need their own import-map entry, so expand each listed spec to its\n * package's concrete (non-wildcard, JS) subpath exports that share the spec's\n * prefix. Unresolvable / CSS / JSON targets are skipped. Failures leave the\n * original spec untouched.\n */\nfunction expandIncludeSubpaths(dirname: string, include: string[]): string[] {\n const out = new Set<string>(include);\n for (const spec of include) {\n const { pkg, sub } = parsePkg(spec);\n let exp: unknown;\n let pkgRoot: string;\n try {\n pkgRoot = realpathSync(join(dirname, \"node_modules\", pkg));\n const pkgJson = JSON.parse(\n readFileSync(join(pkgRoot, \"package.json\"), \"utf8\"),\n ) as { exports?: unknown };\n exp = pkgJson.exports;\n } catch {\n continue;\n }\n if (!exp || typeof exp !== \"object\") continue;\n const expMap = exp as Record<string, unknown>;\n const prefixKey = sub ? `./${sub}` : \".\";\n for (const key of Object.keys(expMap)) {\n if (key.includes(\"*\") || key === \"./package.json\") continue;\n if (/\\.(css|json|scss)$/.test(key)) continue;\n const matches =\n prefixKey === \".\"\n ? key === \".\" || key.startsWith(\"./\")\n : key === prefixKey || key.startsWith(`${prefixKey}/`);\n if (!matches) continue;\n const target = importTarget(expMap[key]);\n if (!target || /\\.(css|json|scss)$/.test(target)) continue;\n // Skip subpaths whose target file isn't shipped (e.g. a `./test` export\n // pointing at unbuilt dist) — they'd fail the build.\n if (!existsSync(join(pkgRoot, target))) continue;\n out.add(key === \".\" ? pkg : pkg + key.slice(1));\n }\n }\n return [...out];\n}\n\n/**\n * Build the vendor into a unique temp dir, then atomically swap it into place,\n * so a concurrent reader never sees a partial bundle or import-map.json. Runs\n * the build in a throwaway subprocess (its peak memory is reclaimed on exit);\n * the parent augments the import map with the version digest and does the swap.\n * Returns the published import map, or null on failure.\n */\nasync function buildVendorAtomic(\n dirname: string,\n vendorDir: string,\n include: string[],\n external: string[],\n versionDigest: string,\n): Promise<Record<string, string> | null> {\n const parent = pathDirname(vendorDir);\n mkdirSync(parent, { recursive: true });\n const tmpDir = mkdtempSync(join(parent, \".ph-vendor.tmp-\"));\n try {\n const { ok, stderr } = await runBuildWorker(\n dirname,\n tmpDir,\n include,\n external,\n );\n const tmpMap = join(tmpDir, \"import-map.json\");\n if (!ok || !existsSync(tmpMap)) {\n const detail = stderr.trim();\n throw new Error(\n `vendor build failed${detail ? `:\\n${detail}` : \" (no output captured)\"}`,\n );\n }\n // Stamp the version digest into the published metadata so the cache check\n // can detect a dep bump.\n const meta = JSON.parse(readFileSync(tmpMap, \"utf8\")) as VendorCacheMeta;\n meta.versionDigest = versionDigest;\n writeFileSync(tmpMap, JSON.stringify(meta, null, 2));\n\n // Swap: move any existing dir aside, rename temp into place, drop the old.\n const oldDir = `${vendorDir}.old-${process.pid}-${Date.now()}`;\n if (existsSync(vendorDir)) renameSync(vendorDir, oldDir);\n renameSync(tmpDir, vendorDir);\n rmSync(oldDir, { recursive: true, force: true });\n return meta.imports;\n } catch (err) {\n rmSync(tmpDir, { recursive: true, force: true });\n throw err;\n }\n}\n\n/**\n * Spawn a throwaway worker that generates one entry per specifier (CJS deps get\n * explicit named re-exports, ESM deps `export *`), `vite build`s them into the\n * given out dir, and writes the import map. Captures stdout/stderr so a failure\n * is debuggable; the normal path stays quiet.\n */\nfunction runBuildWorker(\n dirname: string,\n outDir: string,\n include: string[],\n external: string[],\n): Promise<{ ok: boolean; stderr: string }> {\n const workerPath = join(outDir, \"build-worker.mjs\");\n writeFileSync(workerPath, VENDOR_BUILD_WORKER);\n // Absolute path to this (built) module so the worker can import the\n // dynamic-base plugin from builder-tools' own bundle.\n const selfModulePath = fileURLToPath(import.meta.url);\n return new Promise((resolve) => {\n const child = spawn(\n process.execPath,\n [\n workerPath,\n dirname,\n outDir,\n JSON.stringify(include),\n VENDOR_URL_PREFIX,\n JSON.stringify(external),\n VENDOR_DYNAMIC_BASE,\n selfModulePath,\n ],\n { cwd: dirname, stdio: [\"ignore\", \"pipe\", \"pipe\"] },\n );\n let stderr = \"\";\n child.stdout.on(\"data\", (d) => {\n stderr += String(d);\n });\n child.stderr.on(\"data\", (d) => {\n stderr += String(d);\n });\n child.on(\"exit\", (code) => resolve({ ok: code === 0, stderr }));\n child.on(\"error\", (e) => resolve({ ok: false, stderr: String(e) }));\n });\n}\n\n/**\n * The vendor build worker, written to disk and run as a subprocess. Loads\n * `vite` from the project and `connectDynamicBasePlugin` from builder-tools' own\n * built bundle (selfModulePath). argv: dirname, vendorDir, includeJSON,\n * urlPrefix, externalJSON, dynamicBase, selfModulePath.\n */\nconst VENDOR_BUILD_WORKER = `\nimport { createRequire } from 'node:module';\nimport { mkdirSync, writeFileSync, rmSync } from 'node:fs';\nimport { join, isAbsolute } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nconst [dirname, vendorDir, includeJSON, urlPrefix, externalJSON, dynamicBase, selfModulePath] = process.argv.slice(2);\nconst include = JSON.parse(includeJSON);\nconst external = JSON.parse(externalJSON ?? '[]');\nconst externalSet = new Set(external);\nconst reqProj = createRequire(join(dirname, 'noop.js'));\nconst { build, esmExternalRequirePlugin } = await import(reqProj.resolve('vite'));\n// Load the dynamic-base plugin from builder-tools' own built bundle (passed as\n// an absolute path) — it isn't resolvable as a bare specifier from the worker.\nconst { connectDynamicBasePlugin, DYNAMIC_BASE_PLACEHOLDER } = await import(pathToFileURL(selfModulePath));\nconst srcDir = join(vendorDir, '.entries');\nmkdirSync(srcDir, { recursive: true });\nconst entryName = (spec) => spec.replace(/[^\\\\w]+/g, '_');\nconst RESERVED = new Set('enum void null function in instanceof typeof new delete do if else return switch case break continue for while this true false class const let var default export import extends super with yield debugger finally throw try catch await implements interface package private protected public static eval arguments'.split(' '));\nconst input = {};\nfor (const spec of include) {\n const name = entryName(spec);\n let src;\n try {\n // Import the bare spec (not reqProj.resolve(spec)) so Node picks the same\n // import/browser-condition module the build resolves — resolving first can\n // pick a CJS sibling whose default-export shape differs from the ESM build.\n const ns = await import(spec);\n // Only fall back to re-exporting from default when the module exposes NO\n // top-level named exports (a true CJS-interop module). If it does (e.g. zod\n // exposes \\`z\\`), \\`export *\\` captures them; destructuring default would miss\n // top-level names that aren't keys of the default object.\n const named = Object.keys(ns).filter((k) => k !== 'default');\n const cjs = named.length === 0 && ns.default && typeof ns.default === 'object';\n if (cjs) {\n const names = Object.keys(ns.default).filter((k) => k !== 'default' && k !== '__esModule' && /^[A-Za-z_$][\\\\w$]*$/.test(k));\n const plain = names.filter((n) => !RESERVED.has(n));\n const reserved = names.filter((n) => RESERVED.has(n));\n src = 'import d from ' + JSON.stringify(spec) + ';\\\\nexport default d;\\\\n'\n + (plain.length ? 'export const { ' + plain.join(', ') + ' } = d;\\\\n' : '');\n // reserved words are invalid as const-binding names but valid as export\n // aliases (export { x as enum }).\n reserved.forEach((n, i) => {\n src += 'const __r' + i + ' = d[' + JSON.stringify(n) + '];\\\\nexport { __r' + i + ' as ' + n + ' };\\\\n';\n });\n } else {\n src = 'export * from ' + JSON.stringify(spec) + ';\\\\n'\n + (('default' in ns) ? 'export { default } from ' + JSON.stringify(spec) + ';\\\\n' : '');\n }\n } catch {\n src = 'export * from ' + JSON.stringify(spec) + ';\\\\n';\n }\n const file = join(srcDir, name + '.js');\n writeFileSync(file, src);\n input[name] = file;\n}\n// Prefer the bundler's browser-condition-aware resolution; fall back to resolving\n// from the worker (real install path) only for Rolldown's realpath-anchoring bug.\nconst phResolveCache = new Map();\nconst phVendorResolve = {\n name: 'ph-vendor-resolve', enforce: 'pre',\n async resolveId(source, importer, options) {\n if (externalSet.has(source)) return null;\n if (source[0] === '\\\\0' || source[0] === '.' || isAbsolute(source)) return null;\n if (source.startsWith('node:') || source.startsWith('data:')) return null;\n let viaBundler = null;\n try { viaBundler = await this.resolve(source, importer, { ...options, skipSelf: true }); } catch {}\n if (viaBundler) return viaBundler;\n if (phResolveCache.has(source)) return phResolveCache.get(source);\n let resolved = null;\n try { resolved = fileURLToPath(import.meta.resolve(source)); } catch {}\n phResolveCache.set(source, resolved);\n return resolved;\n },\n};\nawait build({\n root: dirname, configFile: false, logLevel: 'error',\n // Dynamic-base placeholder + vendor segment: connectDynamicBasePlugin rewrites\n // emitted chunk/asset URLs to resolve against the deploy base at serve time.\n base: dynamicBase,\n define: {\n 'process.env.NODE_ENV': '\"development\"',\n // BASE_URL resolves to the deploy base (not the vendor prefix) so vendored\n // Connect's router basename + BASE_URL-relative fetches use the right path.\n 'import.meta.env.BASE_URL': JSON.stringify(DYNAMIC_BASE_PLACEHOLDER),\n },\n // phVendorResolve (pre) resolves bares from the worker; esmExternalRequirePlugin owns\n // react/virtual externalization; connectDynamicBasePlugin (post) rewrites the placeholder base.\n plugins: [phVendorResolve, esmExternalRequirePlugin({ external }), connectDynamicBasePlugin()],\n // pglite ships web workers as ES-module chunks. workerStripPrefix is the vendor\n // segment so the worker recovers the deploy base, not the vendor prefix.\n worker: { format: 'es', plugins: () => [connectDynamicBasePlugin({ forWorker: true, workerStripPrefix: urlPrefix.replace(/^\\\\/+/, '') })] },\n build: {\n outDir: vendorDir, emptyOutDir: false, minify: false, target: 'esnext', cssCodeSplit: true,\n rollupOptions: {\n input, preserveEntrySignatures: 'strict',\n output: { format: 'es', entryFileNames: '[name].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]' },\n },\n },\n});\nrmSync(srcDir, { recursive: true, force: true });\nconst imports = {};\nfor (const spec of include) imports[spec] = urlPrefix + entryName(spec) + '.js';\nwriteFileSync(join(vendorDir, 'import-map.json'), JSON.stringify({ include, external, imports }, null, 2));\n`;\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 type { ConnectCommonOptions } from \"./types.js\";\n\nexport const DEFAULT_CONNECT_OUTDIR = \".ph/connect-build/dist/\" as const;\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","// JSON Schema (draft-07) for dist/powerhouse.config.json — the runtime\n// artifact emitted into the build output and fetched by the Connect SPA at\n// boot.\n//\n// A strict SUBSET of the source PowerhouseConfig schema plus two runtime-only\n// fields (schemaVersion, localPackage). Field shapes shared with the source\n// schema (PowerhousePackage, PHConnectRuntimeConfig) are imported from the\n// shared fragments module so the two schemas stay in sync by construction.\n\nimport {\n phConnectRuntimeConfigSchema,\n powerhousePackageSchema,\n} from \"@powerhousedao/shared/connect\";\n\nexport const RUNTIME_CONFIG_SCHEMA_ID =\n \"https://powerhouse.inc/schemas/powerhouse.config.json\";\n\n// GitHub-hosted schema URL. Points at the JSON artifact committed alongside\n// this TS module. Currently tracks the `main` branch — schema edits go live\n// for editors as soon as they merge. Migrate to a `schema-v<N>` tag pinned\n// to schemaVersion if/when stability across edits becomes a concern.\nexport const RUNTIME_CONFIG_SCHEMA_URL =\n \"https://raw.githubusercontent.com/powerhouse-inc/powerhouse/main/packages/builder-tools/connect-utils/runtime-config.schema.json\";\n\nexport const runtimeConfigSchema = {\n $schema: \"http://json-schema.org/draft-07/schema#\",\n $id: RUNTIME_CONFIG_SCHEMA_ID,\n title: \"Powerhouse Connect runtime configuration\",\n description:\n \"Runtime configuration loaded by Connect at boot from /powerhouse.config.json.\",\n type: \"object\",\n additionalProperties: false,\n required: [\"schemaVersion\", \"packages\", \"localPackage\"],\n properties: {\n $schema: {\n type: \"string\",\n description:\n \"Optional JSON Schema reference for editor autocomplete. Set to the GitHub-hosted schema URL.\",\n },\n schemaVersion: {\n const: 2,\n description:\n \"Schema version. Must match the SPA bundle that ships with this dist. The SPA throws on mismatch to prevent SPA/config skew.\",\n },\n packages: {\n type: \"array\",\n description:\n \"Powerhouse packages this Connect instance loads at runtime.\",\n items: powerhousePackageSchema,\n },\n packageRegistryUrl: {\n type: \"string\",\n description:\n \"Project-wide package registry endpoint. Copied verbatim from the source `powerhouse.config.json` top-level field — the SPA's Package Manager UI reads this directly.\",\n },\n localPackage: {\n description:\n \"Identity of the consumer project itself, captured at build time. null for Docker images and other generic deploys with no host project.\",\n oneOf: [\n { type: \"null\" },\n {\n type: \"object\",\n additionalProperties: false,\n required: [\"name\", \"version\"],\n properties: {\n name: { type: \"string\" },\n version: { type: \"string\" },\n },\n },\n ],\n },\n connect: phConnectRuntimeConfigSchema,\n },\n} as const;\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { Plugin } from \"vite\";\n\nexport type PhBundledPackagesPluginOptions = {\n /**\n * Package names (with `provider: \"local\"` in powerhouse.config.json)\n * that should be bundled into Connect at build time. Each must be\n * resolvable from node_modules.\n */\n packages: string[];\n /** Project root used to read each bundled package's package.json version. */\n projectRoot?: string;\n};\n\nexport const VIRTUAL_ID = \"ph-bundled-packages-virtual\";\nexport const RESOLVED_VIRTUAL_ID = \"\\0virtual:\" + VIRTUAL_ID;\n// Vite serves a resolved id at /@id/<id with \\0 → __x00__>.\nexport const BUNDLED_PACKAGES_DEV_URL =\n \"@id/\" + RESOLVED_VIRTUAL_ID.replace(\"\\0\", \"__x00__\");\n\nfunction readBundledPackageVersion(\n projectRoot: string,\n name: string,\n): string | undefined {\n try {\n const raw = fs.readFileSync(\n path.join(projectRoot, \"node_modules\", name, \"package.json\"),\n \"utf-8\",\n );\n const pkg = JSON.parse(raw) as { version?: unknown };\n return typeof pkg.version === \"string\" ? pkg.version : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction makeRegisterModule(packages: string[], projectRoot: string): string {\n if (packages.length === 0) {\n return \"export default () => {};\\n\";\n }\n const imports: string[] = [];\n const calls: string[] = [];\n\n packages.forEach((name, i) => {\n const moduleName = `pkg${i}`;\n const version = readBundledPackageVersion(projectRoot, name);\n imports.push(`import * as ${moduleName} from ${JSON.stringify(name)};`);\n imports.push(`import ${JSON.stringify(`${name}/style.css`)};`);\n calls.push(\n ` pm.addLocalPackage(${JSON.stringify(name)}, ${moduleName}, ${JSON.stringify(version)});`,\n );\n });\n\n return `${imports.join(\"\\n\")}\\n\\nexport default function register(pm) {\\n${calls.join(\"\\n\")}\\n};\\n`;\n}\n\n/**\n * Emits a virtual module `ph-bundled-packages-virtual` whose default export\n * is a `register(packageManager)` function. When called at runtime (from\n * Connect's bootstrap), it registers each bundled package with the package\n * manager the same way Common/Vetra are registered — meaning they work\n * offline without the registry being reachable.\n *\n * When the list is empty, the module exports a no-op function so Connect's\n * bootstrap code can always import it unconditionally.\n */\nexport function phBundledPackagesPlugin(\n options: PhBundledPackagesPluginOptions,\n): Plugin {\n const projectRoot = options.projectRoot ?? process.cwd();\n const moduleSource = makeRegisterModule(options.packages, projectRoot);\n\n return {\n name: \"vite-plugin-ph-bundled-packages\",\n enforce: \"pre\",\n resolveId(id) {\n if (id === VIRTUAL_ID) return RESOLVED_VIRTUAL_ID;\n },\n load(id) {\n if (id === RESOLVED_VIRTUAL_ID) return moduleSource;\n },\n };\n}\n","import { createRequire } from \"node:module\";\nimport { createReadStream } from \"node:fs\";\nimport path from \"node:path\";\nimport type { Plugin } from \"vite\";\nimport {\n DEFAULT_VENDOR_INCLUDE,\n VENDOR_URL_PREFIX,\n prebuildConnectVendor,\n type PrebuiltVendor,\n} from \"../externalize-vendor.js\";\nimport { BUNDLED_PACKAGES_DEV_URL } from \"./ph-bundled-packages.js\";\n\nconst REACT_DEPS = [\n \"react\",\n \"react-dom\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n \"react-dom/client\",\n];\n\nconst SHIM_PATH = \"__ph/dev-react-shim/\";\nconst VITE_DEPS_PATH = \"node_modules/.vite/deps\";\n\n// Content-Type for the asset extensions the vendor build emits; JS is the default.\nconst VENDOR_MIME: Record<string, string> = {\n \".css\": \"text/css\",\n \".map\": \"application/json\",\n \".json\": \"application/json\",\n \".wasm\": \"application/wasm\",\n \".data\": \"application/octet-stream\",\n \".woff2\": \"font/woff2\",\n \".woff\": \"font/woff\",\n \".ttf\": \"font/ttf\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n};\n\n// Opt-in: also serve the heavy stable Connect libs from a prebuilt vendor\n// bundle, so the long-lived dev server never dep-optimizes them (~1–2 GB\n// resident). Set PH_CONNECT_EXTERNALIZE_VENDOR=1 to enable.\nconst VENDOR_MODE = process.env.PH_CONNECT_EXTERNALIZE_VENDOR === \"1\";\n// Extra specifiers to vendor on top of the defaults, comma-separated. Lets a\n// project add its own stable heavy deps without code changes.\nconst VENDOR_EXTRA = (process.env.PH_CONNECT_VENDOR_EXTRA ?? \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\nconst HEAVY_LIBS = [...DEFAULT_VENDOR_INCLUDE, ...VENDOR_EXTRA];\n\n// Vite serves dev module URLs under the resolved `base`. Join base + path\n// while collapsing the double slash so `base: \"/\"` stays byte-identical.\nfunction withBase(base: string, p: string): string {\n return `${base}${p}`.replace(/\\/{2,}/g, \"/\");\n}\n\n// Keep the matched specifiers bare in dev (Vite otherwise rewrites externals to\n// \"/@id/<spec>\") so the import map resolves them; predicate matching supported.\ntype Externals = Array<string | ((id: string) => boolean)>;\nfunction externalizePlugin(externals: Externals): Plugin | undefined {\n try {\n const require = createRequire(import.meta.url);\n const mod = require(\"vite-plugin-externalize-dependencies\") as {\n default?: (o: { externals: Externals }) => Plugin;\n } & ((o: { externals: Externals }) => Plugin);\n const factory = mod.default ?? mod;\n return factory({ externals });\n } catch {\n return undefined;\n }\n}\n\n/**\n * Dev-only sibling of `esmExternalRequirePlugin`. The build path externalizes\n * React via Rolldown so an importmap hands the same React instance to both\n * Connect and CDN-served editor packages. Rolldown plugins don't run in\n * `vite createServer`, and Vite's pre-bundled CJS deps only expose a `default`\n * export — so a CDN editor that does `import { lazy } from \"react\"` would\n * fail with \"no named export 'lazy'\".\n *\n * This plugin owns the page import map. It always:\n * 1. Forces React into `optimizeDeps.include` so the optimizer always knows\n * about it.\n * 2. Serves a shim per React module at a stable URL. Each shim imports\n * from Vite's live pre-bundled URL (sharing Connect's React instance)\n * and re-exports React's named members so editors importing\n * `{ lazy }`, `{ jsx }`, etc. work.\n * 3. Rewrites the page importmap to point at those shim URLs.\n *\n * When PH_CONNECT_EXTERNALIZE_VENDOR=1 it additionally prebuilds the heavy\n * stable libs (design-system, reactor-browser, …) into a static vendor bundle,\n * externalizes them from the dev server, serves the bundle, and adds them to\n * the SAME import map. The vendor's React imports stay bare → resolve through\n * the React shims above → one React instance across Connect, the vendor, and\n * CDN editors.\n */\n// Async factory: in VENDOR_MODE it runs the vendor prebuild up front (Vite\n// awaits a Promise<PluginOption>), so `vendor` is known before any plugin hook\n// fires. The heavy libs are excluded from the optimizer — and the externalize\n// plugin is added — ONLY when a valid bundle will be served. On prebuild\n// failure they stay dev-optimized (no broken bare imports) and neither the\n// import map nor the externalizer touch them.\nexport async function devReactImportmapPlugin(\n projectRoot: string = process.cwd(),\n): Promise<Plugin | Plugin[]> {\n let namedExports = new Map<string, string[]>();\n let base = \"/\";\n let vendor: PrebuiltVendor | null = null;\n\n if (VENDOR_MODE) {\n const errorRef: { message?: string } = {};\n vendor = await prebuildConnectVendor({\n dirname: projectRoot,\n include: HEAVY_LIBS,\n errorRef,\n });\n if (!vendor) {\n const detail = errorRef.message ? `: ${errorRef.message}` : \"\";\n console.warn(\n `[connect] PH_CONNECT_EXTERNALIZE_VENDOR set but vendor prebuild failed; falling back to dep-optimizing the heavy libs${detail}`,\n );\n }\n }\n\n // Externalize exactly the specifiers in the vendor import map (not broad\n // prefixes) so an undiscovered subpath stays resolvable instead of 404ing.\n const ext = vendor\n ? externalizePlugin([(id) => id in vendor!.imports])\n : undefined;\n if (vendor && !ext) {\n console.warn(\n \"[connect] PH_CONNECT_EXTERNALIZE_VENDOR set and vendor prebuilt, but vite-plugin-externalize-dependencies is not installed; falling back to dep-optimizing the heavy libs (install it to enable the vendor)\",\n );\n }\n const vendorActive = !!(vendor && ext);\n\n const main: Plugin = {\n name: \"ph-dev-react-importmap\",\n apply: \"serve\",\n config(cfg) {\n cfg.optimizeDeps ??= {};\n const include = new Set(cfg.optimizeDeps.include ?? []);\n REACT_DEPS.forEach((d) => include.add(d));\n if (vendorActive) {\n // The heavy libs are served from the prebuilt vendor; force-including\n // them would pre-bundle them anyway (and leave their excluded deps —\n // e.g. zod subpaths — as unmapped bare imports). Drop them from include\n // and exclude them so the optimizer never touches them.\n HEAVY_LIBS.forEach((d) => include.delete(d));\n cfg.optimizeDeps.exclude = [\n ...new Set([...(cfg.optimizeDeps.exclude ?? []), ...HEAVY_LIBS]),\n ];\n }\n cfg.optimizeDeps.include = [...include];\n },\n configResolved(config) {\n base = config.base;\n },\n configureServer(server) {\n // Resolve React's named exports from the consumer project so we don't\n // hardcode lists that drift across React versions.\n const requireFromRoot = createRequire(\n path.join(server.config.root, \"package.json\"),\n );\n namedExports = new Map(\n REACT_DEPS.map((id) => {\n try {\n const mod = requireFromRoot(id) as Record<string, unknown>;\n return [id, Object.keys(mod).filter((k) => k !== \"default\")];\n } catch {\n return [id, []];\n }\n }),\n );\n\n // Serve the prebuilt vendor bundle. Match the base-prefixed URL (chunk/asset\n // URLs carry the deploy base) and the bare prefix; strip whichever matched.\n if (vendorActive) {\n const vendorDir = vendor!.vendorDir;\n const vendorPrefixes = [\n withBase(base, VENDOR_URL_PREFIX),\n VENDOR_URL_PREFIX,\n ];\n server.middlewares.use((req, res, next) => {\n const url = (req.url ?? \"\").split(\"?\")[0];\n const prefix = vendorPrefixes.find((p) => url.startsWith(p));\n if (!prefix) return next();\n const name = url.slice(prefix.length).replace(/^\\/+/, \"\");\n const file = path.join(vendorDir, name);\n // Path-segment containment (not a string prefix): reject anything that\n // escapes vendorDir, incl. siblings like `.ph-vendor.lock`.\n const rel = path.relative(vendorDir, file);\n if (!name || rel.startsWith(\"..\") || path.isAbsolute(rel)) {\n return next();\n }\n // Stream (don't buffer multi-MB wasm/.data); a missing file → next().\n const stream = createReadStream(file);\n stream.on(\"error\", () => {\n if (!res.headersSent) next();\n });\n stream.once(\"open\", () => {\n const ext = file.slice(file.lastIndexOf(\".\"));\n res.setHeader(\n \"Content-Type\",\n VENDOR_MIME[ext] ?? \"text/javascript\",\n );\n // Content-hashed chunks/assets are immutable; entries + map can change.\n const hashed =\n name.startsWith(\"chunks/\") || name.startsWith(\"assets/\");\n res.setHeader(\n \"Cache-Control\",\n hashed ? \"public, max-age=31536000, immutable\" : \"no-cache\",\n );\n stream.pipe(res);\n });\n });\n }\n\n // Match the base-prefixed shim URL, and the bare path for robustness.\n const shimPrefixes = [withBase(base, SHIM_PATH), `/${SHIM_PATH}`];\n server.middlewares.use((req, res, next) => {\n const prefix = shimPrefixes.find((p) => req.url?.startsWith(p));\n if (!prefix) return next();\n const id = req.url!.slice(prefix.length).replace(/\\.js(\\?.*)?$/, \"\");\n if (!REACT_DEPS.includes(id)) return next();\n\n const optimizer = server.environments.client.depsOptimizer;\n const info =\n optimizer?.metadata.optimized[id] ??\n optimizer?.metadata.discovered[id];\n if (!optimizer || !info) {\n res.statusCode = 404;\n res.end();\n return;\n }\n\n const browserHash = info.browserHash ?? optimizer.metadata.browserHash;\n const depUrl = `${withBase(base, VITE_DEPS_PATH)}/${path.basename(info.file)}?v=${browserHash}`;\n const names = namedExports.get(id) ?? [];\n\n res.setHeader(\"Content-Type\", \"application/javascript\");\n res.end(\n `import * as M from ${JSON.stringify(depUrl)};\\n` +\n `const ns = M.default ?? M;\\n` +\n `export default ns;\\n` +\n (names.length\n ? `export const { ${names.join(\", \")} } = ns;\\n`\n : \"\"),\n );\n });\n },\n transformIndexHtml: {\n order: \"post\",\n handler(html, ctx) {\n const browserHash =\n ctx.server?.environments.client.depsOptimizer?.metadata.browserHash;\n if (!browserHash) return;\n const shimPrefix = withBase(base, SHIM_PATH);\n const imports: Record<string, string> = Object.fromEntries(\n REACT_DEPS.map((id) => [\n id,\n `${shimPrefix}${id}.js?v=${browserHash}`,\n ]),\n );\n // Heavy libs resolve to the prebuilt vendor (base-prefixed); their bare\n // React imports fall through to the React shim entries above.\n let dynamicBaseScript = \"\";\n if (vendorActive) {\n for (const [spec, url] of Object.entries(vendor!.imports)) {\n imports[spec] = withBase(base, url);\n }\n // Connect vendored isn't dev-processed, so its dynamic\n // `import(\"ph-bundled-packages-virtual\")` points at the virtual URL.\n if (vendor!.imports[\"@powerhousedao/connect\"]) {\n imports[\"ph-bundled-packages-virtual\"] = withBase(\n base,\n BUNDLED_PACKAGES_DEV_URL,\n );\n }\n // Set the runtime base global so the vendor's rewritten URL exprs\n // resolve to the dev/deploy base (mirrors the proxy at serve time).\n dynamicBaseScript = `<script>globalThis.__PH_DYNAMIC_BASE__=${JSON.stringify(base)};</script>\\n`;\n }\n return html.replace(\n /<script type=\"importmap\">[\\s\\S]*?<\\/script>/,\n `${dynamicBaseScript}<script type=\"importmap\">${JSON.stringify({ imports }, null, 2)}</script>`,\n );\n },\n },\n };\n\n // The externalizer runs alongside `main` so Connect's source leaves the heavy\n // libs bare (→ import map → vendor); React stays optimized via the shims.\n return vendorActive ? [ext!, main] : main;\n}\n","import { readFileSync } from \"node:fs\";\nimport { extname, isAbsolute, resolve } from \"node:path\";\nimport type { Connect, Plugin } from \"vite\";\n\nconst CONTENT_TYPE_BY_EXT: Record<string, string> = {\n \".ico\": \"image/x-icon\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n};\n\n/**\n * Vite plugin to serve the Connect favicon (icon.ico) from the connect package,\n * or from a caller-supplied file when `faviconPath` is set (e.g. `ph connect\n * build --favicon`). The served/emitted name is always `icon.ico` so the static\n * `<link rel=\"icon\" href=\"%BASE_URL%icon.ico\">` in index.html stays valid.\n */\nexport function connectFaviconPlugin(\n opts: { faviconPath?: string } = {},\n): Plugin {\n // Build input, not runtime config: a non-absolute path resolves against the\n // build cwd (= the project dir during `ph connect build`).\n const customPath = opts.faviconPath\n ? isAbsolute(opts.faviconPath)\n ? opts.faviconPath\n : resolve(process.cwd(), opts.faviconPath)\n : undefined;\n const customContentType = customPath\n ? (CONTENT_TYPE_BY_EXT[extname(customPath).toLowerCase()] ?? \"image/x-icon\")\n : \"image/x-icon\";\n\n return {\n name: \"copy-connect-favicon\",\n configureServer(server) {\n // Vite rewrites the favicon link against `base`, so serve the\n // base-prefixed path. Keep the bare path for robustness.\n const base = server.config.base;\n const faviconRoute = `${base}icon.ico`.replace(/\\/{2,}/g, \"/\");\n const handler: Connect.NextHandleFunction = (_req, res, next) => {\n if (customPath) {\n try {\n res.setHeader(\"Content-Type\", customContentType);\n res.end(readFileSync(customPath));\n } catch {\n next();\n }\n return;\n }\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 // Mount on the exact route(s) so the handler only runs for icon.ico.\n // Connect strips the mount prefix before matching, so mounting on\n // \"/icon.ico\" matches that path exactly.\n const paths = new Set([faviconRoute, \"/icon.ico\"]);\n for (const path of paths) {\n server.middlewares.use(path, handler);\n }\n },\n async generateBundle(_options, bundle) {\n try {\n if (\"icon.ico\" in bundle) return;\n let source: Uint8Array | undefined;\n if (customPath) {\n source = readFileSync(customPath);\n } else {\n const resolved = await this.resolve(\n \"@powerhousedao/connect/assets/icon.ico\",\n );\n if (resolved) source = readFileSync(resolved.id);\n }\n if (!source) return;\n this.emitFile({\n type: \"asset\",\n fileName: \"icon.ico\",\n source,\n });\n } catch {\n // favicon source not found, skip\n }\n },\n };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { Plugin } from \"vite\";\nimport type { PowerhousePackage } from \"@powerhousedao/config\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport {\n buildRuntimeConfig,\n DEFAULT_CONNECT_CONFIG,\n deepMerge,\n} from \"@powerhousedao/shared/connect\";\nimport { RUNTIME_CONFIG_SCHEMA_URL } from \"../runtime-config-schema.js\";\n\nexport type PhConfigPluginOptions = {\n packages: PowerhousePackage[];\n projectRoot?: string;\n connect?: PHConnectRuntimeConfig;\n /**\n * Project-wide package registry URL — the effective value (CLI override\n * `??` source) the caller has already resolved. Copied verbatim into the\n * emitted runtime config (no namespace change); the SPA reads\n * `runtimeConfig.packageRegistryUrl` directly.\n */\n packageRegistryUrl?: string;\n /**\n * CLI-supplied connect override (final merge layer, beats source).\n * Forwarded from `ph connect build`'s `--json` + individual `--flag` parsing.\n * See clis/ph-cli/src/utils/cli-connect-override.ts.\n */\n cliConnectOverride?: PHConnectRuntimeConfig;\n};\n\nfunction readProjectPackageInfo(\n projectRoot: string | undefined,\n): { name: string; version: string } | null {\n if (!projectRoot) return null;\n try {\n const raw = fs.readFileSync(\n path.join(projectRoot, \"package.json\"),\n \"utf-8\",\n );\n const pkg = JSON.parse(raw) as { name?: unknown; version?: unknown };\n if (typeof pkg.name !== \"string\" || typeof pkg.version !== \"string\") {\n return null;\n }\n return { name: pkg.name, version: pkg.version };\n } catch {\n return null;\n }\n}\n\nexport function phConfigPlugin(options: PhConfigPluginOptions): Plugin {\n const projectRoot = options.projectRoot ?? process.cwd();\n const localPackage = readProjectPackageInfo(projectRoot);\n\n // Precedence ladder (lowest → highest) for the emitted connect.* block:\n // DEFAULT_CONNECT_CONFIG (base — fills in any field nothing else supplied)\n // < source.connect (user's hand-edited powerhouse.config.json)\n // < cliConnectOverride (`ph connect build --json` + individual flags)\n //\n // Env vars are NOT a layer in this ladder. The Connect SPA's runtime\n // configuration is exclusively set via `powerhouse.config.json` or CLI\n // overrides (`ph connect build --<field>` / `ph connect config --<field>`).\n const sourceConnect = options.connect ?? {};\n const withDefaults = deepMerge(DEFAULT_CONNECT_CONFIG, sourceConnect);\n const mergedConnect = options.cliConnectOverride\n ? deepMerge(withDefaults, options.cliConnectOverride)\n : withDefaults;\n const source = {\n packages: options.packages,\n packageRegistryUrl: options.packageRegistryUrl,\n connect: mergedConnect,\n };\n\n const runtimeConfig = buildRuntimeConfig(source, localPackage);\n const content = JSON.stringify(\n { $schema: RUNTIME_CONFIG_SCHEMA_URL, ...runtimeConfig },\n null,\n 2,\n );\n\n return {\n name: \"vite-plugin-ph-config\",\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n if (req.url?.endsWith(\"/powerhouse.config.json\")) {\n res.setHeader(\"Content-Type\", \"application/json\");\n res.setHeader(\"Cache-Control\", \"no-cache\");\n res.end(content);\n return;\n }\n next();\n });\n },\n hotUpdate: {\n order: \"pre\",\n handler(ctx) {\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: \"powerhouse.config.json\",\n source: content,\n });\n },\n };\n}\n","import type { PowerhousePackage } from \"@powerhousedao/config\";\nimport type {\n PHConnectPwa,\n PwaContribution,\n} from \"@powerhousedao/shared/connect\";\nimport { withInferredCategory } from \"@powerhousedao/shared/connect\";\nimport { PwaConfigSchema } from \"@powerhousedao/shared/document-model\";\nimport { toCdnUrl } from \"@powerhousedao/shared/registry/urls\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { ZodError } from \"zod\";\n\n// Collects the serialisable `pwa` fragments that build-time-known packages ship\n// in their `powerhouse.manifest.json`, from three sources:\n// - the project's own manifest (`collectProjectPwaContribution`);\n// - `provider: \"local\"` packages, read from node_modules (a package's\n// manifest is emitted to `dist/powerhouse.manifest.json` and exposed via\n// its `./manifest` export, so the Connect build can read it as JSON — no\n// need to execute package code, whose main entry pulls browser-only\n// modules that would crash in Node);\n// - `provider: \"registry\"` packages, fetched from the registry CDN (they are\n// not installed in node_modules; production Connect loads them from the\n// CDN at runtime, so the CDN copy is the build-time source of truth).\n// Fragments are validated with `PwaConfigSchema`; anything unreadable,\n// unreachable or malformed is warned about and skipped, never fatal to the\n// build. Only the project's `connect.pwa` block is strict — see\n// `validateProjectPwaConfig`.\n\nconst REGISTRY_FETCH_TIMEOUT_MS = 10_000;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction formatZodIssues(error: ZodError): string {\n return error.issues\n .map((issue) => `${issue.path.join(\".\") || \"(root)\"}: ${issue.message}`)\n .join(\"; \");\n}\n\n/** Turn a parsed manifest JSON into a contribution: its `pwa` fragment (a\n * malformed one → warn + skip that fragment, not the whole contribution) plus a\n * `categories` entry derived from the manifest's `category` field. Returns null\n * only when the manifest yields neither — no `pwa` and no `category`. */\nfunction toPwaContribution(\n manifest: unknown,\n fallbackLabel: string,\n onWarn: (message: string) => void,\n): PwaContribution | null {\n if (!isPlainObject(manifest)) return null;\n const label =\n typeof manifest.name === \"string\" && manifest.name\n ? manifest.name\n : fallbackLabel;\n\n let config: PHConnectPwa = {};\n if (manifest.pwa !== undefined) {\n if (!isPlainObject(manifest.pwa)) {\n onWarn(\n `PWA config: ${label} declares a non-object 'pwa' field in its manifest; ignored.`,\n );\n } else {\n const parsed = PwaConfigSchema.safeParse(manifest.pwa);\n if (!parsed.success) {\n onWarn(\n `PWA config: ${label}'s pwa fragment is invalid; ignored. ${formatZodIssues(parsed.error)}`,\n );\n } else {\n config = parsed.data;\n }\n }\n }\n\n config = withInferredCategory(config, manifest.category);\n if (Object.keys(config).length === 0) return null;\n return { source: label, config };\n}\n\n/** Read the first parseable manifest among `candidates` (relative to `dir`)\n * and extract its pwa contribution. Candidates that resolve outside `dir`\n * (a hostile `./manifest` export) are warned about and skipped. */\nfunction readPwaFragmentFromDir(\n dir: string,\n candidates: string[],\n fallbackLabel: string,\n onWarn: (message: string) => void,\n): PwaContribution | null {\n for (const rel of candidates) {\n const manifestPath = path.resolve(dir, rel);\n if (path.relative(dir, manifestPath).startsWith(\"..\")) {\n onWarn(\n `PWA config: ${fallbackLabel} declares a manifest path outside its package directory (${rel}); ignored.`,\n );\n continue;\n }\n if (!fs.existsSync(manifestPath)) continue;\n try {\n const manifest: unknown = JSON.parse(\n fs.readFileSync(manifestPath, \"utf-8\"),\n );\n return toPwaContribution(manifest, fallbackLabel, onWarn);\n } catch {\n onWarn(\n `PWA config: could not parse ${fallbackLabel}'s manifest at ${rel}; ignored.`,\n );\n return null;\n }\n }\n return null;\n}\n\nfunction readLocalPackagePwaFragment(\n projectRoot: string,\n name: string,\n onWarn: (message: string) => void,\n): PwaContribution | null {\n const pkgDir = path.join(projectRoot, \"node_modules\", name);\n let manifestRel: string | undefined;\n try {\n const pkgJson = JSON.parse(\n fs.readFileSync(path.join(pkgDir, \"package.json\"), \"utf-8\"),\n ) as { exports?: Record<string, unknown> };\n const exported = pkgJson.exports?.[\"./manifest\"];\n if (typeof exported === \"string\") manifestRel = exported;\n } catch {\n // No package.json / unreadable — fall back to the conventional paths.\n }\n\n // The package's declared `./manifest` export first, then the conventional\n // build output and source locations.\n const candidates = [\n manifestRel,\n \"dist/powerhouse.manifest.json\",\n \"powerhouse.manifest.json\",\n ].filter((rel): rel is string => typeof rel === \"string\");\n\n return readPwaFragmentFromDir(pkgDir, candidates, name, onWarn);\n}\n\nasync function fetchRegistryPwaFragment(\n cdnUrl: string,\n pkg: PowerhousePackage,\n onWarn: (message: string) => void,\n fetchImpl: typeof fetch,\n): Promise<PwaContribution | null> {\n // Same version-pinned spec production Connect uses to load the package, so\n // the fragment matches the code that will actually run.\n const spec = pkg.version\n ? `${pkg.packageName}@${pkg.version}`\n : pkg.packageName;\n const url = `${cdnUrl}/${spec}/powerhouse.manifest.json`;\n try {\n const response = await fetchImpl(url, {\n signal: AbortSignal.timeout(REGISTRY_FETCH_TIMEOUT_MS),\n });\n // 404 = the package ships no manifest on the CDN — silent, like a local\n // package without a manifest file.\n if (response.status === 404) return null;\n if (!response.ok) {\n onWarn(\n `PWA config: registry returned ${response.status} for ${spec}'s manifest; its pwa fragment (if any) is skipped.`,\n );\n return null;\n }\n const manifest: unknown = await response.json();\n return toPwaContribution(manifest, pkg.packageName, onWarn);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n onWarn(\n `PWA config: could not fetch ${spec}'s manifest from the registry (${message}); its pwa fragment (if any) is skipped.`,\n );\n return null;\n }\n}\n\n/**\n * Read the `pwa` fragment of each package in `packages`, in the given order\n * (which becomes their merge precedence — later packages win scalar\n * conflicts). `provider: \"local\"` packages are read from node_modules;\n * everything else is fetched from the registry CDN (skipped with a warning\n * when `registryUrl` is missing or the registry is unreachable). Packages\n * with no `pwa` fragment are simply absent from the result.\n */\nexport async function collectPackagePwaContributions(options: {\n packages: PowerhousePackage[];\n projectRoot?: string;\n registryUrl?: string | null;\n onWarn?: (message: string) => void;\n /** Injectable for tests. */\n fetchImpl?: typeof fetch;\n}): Promise<PwaContribution[]> {\n const projectRoot = options.projectRoot ?? process.cwd();\n const onWarn = options.onWarn ?? (() => {});\n const fetchImpl = options.fetchImpl ?? fetch;\n const cdnUrl = options.registryUrl ? toCdnUrl(options.registryUrl) : null;\n\n const results = await Promise.all(\n options.packages.map(async (pkg) => {\n if (pkg.provider === \"local\") {\n return readLocalPackagePwaFragment(\n projectRoot,\n pkg.packageName,\n onWarn,\n );\n }\n if (!cdnUrl) {\n onWarn(\n `PWA config: no packageRegistryUrl configured; cannot read ${pkg.packageName}'s pwa fragment (if any) from the registry.`,\n );\n return null;\n }\n return fetchRegistryPwaFragment(cdnUrl, pkg, onWarn, fetchImpl);\n }),\n );\n return results.filter(\n (contribution): contribution is PwaContribution => contribution !== null,\n );\n}\n\n/**\n * Read the pwa fragment from the project's OWN manifest\n * (`powerhouse.manifest.json` under the project root, falling back to the\n * `dist/` copy the project build emits). The root file comes first — it is\n * the source the dist copy is made from, and a stale dist left by an older\n * build must not shadow it. Returns null silently when no manifest exists —\n * not every project ships one — or when it carries neither a `pwa` block nor a\n * `category` to derive `categories` from.\n *\n * The `pwa` block is parsed STRICTLY, like `connect.pwa` and unlike third-party\n * package fragments: the project's own manifest is the developer's config, so\n * an invalid `pwa` block (a typo, or a removed/unknown field such as\n * `protocol_handlers`) FAILS the build instead of being silently skipped — a\n * silently-dropped field would be far harder to notice.\n */\nexport function collectProjectPwaContribution(options: {\n projectRoot?: string;\n}): PwaContribution | null {\n const projectRoot = options.projectRoot ?? process.cwd();\n for (const rel of [\n \"powerhouse.manifest.json\",\n \"dist/powerhouse.manifest.json\",\n ]) {\n const manifestPath = path.resolve(projectRoot, rel);\n if (!fs.existsSync(manifestPath)) continue;\n let manifest: unknown;\n try {\n manifest = JSON.parse(fs.readFileSync(manifestPath, \"utf-8\"));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Could not parse ${manifestPath}: ${message}`);\n }\n if (!isPlainObject(manifest)) return null;\n const label =\n typeof manifest.name === \"string\" && manifest.name\n ? manifest.name\n : \"project manifest\";\n const config =\n manifest.pwa === undefined\n ? {}\n : parsePwaConfigStrict(manifest.pwa, `pwa in ${manifestPath}`);\n const withCategory = withInferredCategory(config, manifest.category);\n if (Object.keys(withCategory).length === 0) return null;\n return { source: label, config: withCategory };\n }\n return null;\n}\n\n/** Strictly parse a PWA config block, throwing a build-failing error (naming\n * the offending field) when it is invalid. Used for the developer's own config\n * (`connect.pwa` and the project manifest's `pwa`), where a silent drop would\n * be a footgun — unlike third-party package fragments, which warn + skip. */\nfunction parsePwaConfigStrict(\n config: unknown,\n description: string,\n): PHConnectPwa {\n const parsed = PwaConfigSchema.safeParse(config);\n if (!parsed.success) {\n throw new Error(\n `Invalid ${description}: ${formatZodIssues(parsed.error)}. Fix it or remove the field.`,\n );\n }\n return parsed.data;\n}\n\n/**\n * Validate the project's `connect.pwa` block. Unlike package fragments\n * (third-party, warn + skip), the user's own config fails the build: a typo\n * that silently dropped offline coverage would be far harder to notice.\n */\nexport function validateProjectPwaConfig(\n config: unknown,\n configPath: string,\n): PHConnectPwa {\n return parsePwaConfigStrict(config, `connect.pwa in ${configPath}`);\n}\n","import { readFileSync } from \"node:fs\";\nimport type { Plugin } from \"vite\";\n\n// PWA manifest icons emitted into the build from the @powerhousedao/connect\n// package assets. The `ph connect build` Vite root is a scaffolded project that\n// has no PWA icons of its own, so — like connectFaviconPlugin does for the\n// favicon — we resolve them out of the installed connect package and emit them\n// as build assets. vite-plugin-pwa references these filenames in the generated\n// manifest and precaches them via its png glob. The document icons are the\n// OS-level file-type icons referenced by the .phd/.phdm file_handlers.\nconst PWA_ICONS = [\n \"pwa-192x192.png\",\n \"pwa-512x512.png\",\n \"pwa-512x512-maskable.png\",\n \"document-icon-192x192.png\",\n \"document-icon-512x512.png\",\n] as const;\n\nexport function connectPwaIconsPlugin(): Plugin {\n return {\n name: \"copy-connect-pwa-icons\",\n async generateBundle(_options, bundle) {\n for (const icon of PWA_ICONS) {\n try {\n if (icon in bundle) continue;\n const resolved = await this.resolve(\n `@powerhousedao/connect/assets/${icon}`,\n );\n if (!resolved) continue;\n this.emitFile({\n type: \"asset\",\n fileName: icon,\n source: readFileSync(resolved.id),\n });\n } catch {\n // connect package or icon not found — skip; the manifest still\n // generates, the icon URL just 404s (non-fatal for offline caching).\n }\n }\n },\n };\n}\n","import {\n mergeManifest,\n PWA_FILE_HANDLER_ACTION,\n unionStrings,\n type PHConnectPwa,\n type PwaWebManifest,\n} from \"@powerhousedao/shared/connect\";\nimport type { ManifestOptions } from \"vite-plugin-pwa\";\n\n// Applies the effective (already merged, see mergePwaConfig) serialisable PWA\n// fragment onto Connect's hardcoded base. The manifest merge is delegated to\n// the browser-safe `mergeManifest` in @powerhousedao/shared/connect so the\n// exact same code shapes the manifest here (build time) and inside the service\n// worker (runtime, for dynamically-installed packages). This module only adds\n// the vite-plugin-pwa manifest TYPES and the precache-glob merge; the Workbox\n// runtime-caching / navigation behaviour now lives in the hand-written service\n// worker (see connect-utils/service-worker/service-worker.ts), because\n// `injectManifest` has no declarative runtimeCaching option.\n\n// Re-exported so existing importers (pwa.ts, the e2e test) keep a stable name\n// while the constant's source of truth moves to @powerhousedao/shared/connect.\nexport { PWA_FILE_HANDLER_ACTION as FILE_HANDLER_ACTION };\n\n/** A manifest file-handler entry. vite-plugin-pwa's own type stops at\n * `{ action; accept }`; the spec'd `icons`/`launch_type` members are added\n * here — the manifest is emitted as verbatim JSON, so they ship through. */\nexport type ConnectPwaFileHandler = NonNullable<\n ManifestOptions[\"file_handlers\"]\n>[number] & {\n icons?: ManifestOptions[\"icons\"];\n launch_type?: \"single-client\" | \"multiple-clients\";\n};\n\n/** The web-app manifest exactly as VitePWA accepts it, with the file-handler\n * entries widened to their full spec'd shape. */\nexport type ConnectPwaManifest = Omit<\n Partial<ManifestOptions>,\n \"file_handlers\"\n> & {\n file_handlers?: ConnectPwaFileHandler[];\n};\n\n/** The precache-driving subset of the old Workbox config. Under injectManifest\n * these are the `injectManifest` options; `self.__WB_MANIFEST` is generated\n * from them. Everything else (runtimeCaching, navigation, clientsClaim, …) is\n * imperative code in the service worker. */\nexport type ConnectPrecacheOptions = {\n globPatterns: string[];\n globIgnores: string[];\n maximumFileSizeToCacheInBytes: number;\n};\n\n/**\n * Lay an effective PWA fragment over the plugin's hardcoded manifest + precache\n * base. The manifest is merged by the shared `mergeManifest` with\n * `fragment-wins` scalars (the build-time effective config is the authority);\n * icons and file handlers concatenate after the base set (contributed handlers\n * get Connect's fixed action injected — the open route is not configurable);\n * globs union; the size ceiling takes the max.\n *\n * The serialisable `runtimeCaching` / `navigateFallbackDenylist` overrides are\n * NOT handled here — they are passed straight to the service worker (which\n * registers them after its built-in rules), because injectManifest has no\n * declarative runtimeCaching and Workbox is first-match-wins, so an override\n * can only be appended after the built-ins (intentional for v1).\n */\nexport function applyPwaOverrides(\n base: { manifest: ConnectPwaManifest; precache: ConnectPrecacheOptions },\n override: PHConnectPwa,\n): { manifest: ConnectPwaManifest; precache: ConnectPrecacheOptions } {\n const manifest = mergeManifest(\n base.manifest as PwaWebManifest,\n override.manifest,\n { scalarPolicy: \"fragment-wins\" },\n ) as ConnectPwaManifest;\n\n const precache: ConnectPrecacheOptions = {\n globPatterns: override.globPatterns?.length\n ? unionStrings(base.precache.globPatterns, override.globPatterns)\n : base.precache.globPatterns,\n globIgnores: override.globIgnores?.length\n ? unionStrings(base.precache.globIgnores, override.globIgnores)\n : base.precache.globIgnores,\n maximumFileSizeToCacheInBytes:\n typeof override.maximumFileSizeToCacheInBytes === \"number\"\n ? Math.max(\n base.precache.maximumFileSizeToCacheInBytes,\n override.maximumFileSizeToCacheInBytes,\n )\n : base.precache.maximumFileSizeToCacheInBytes,\n };\n\n return { manifest, precache };\n}\n","import { type PHConnectPwa } from \"@powerhousedao/shared/connect\";\nimport { existsSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Plugin, PluginOption } from \"vite\";\nimport { VitePWA } from \"vite-plugin-pwa\";\nimport { connectPwaIconsPlugin } from \"./pwa-icons.js\";\nimport {\n applyPwaOverrides,\n FILE_HANDLER_ACTION,\n type ConnectPrecacheOptions,\n type ConnectPwaManifest,\n} from \"./pwa-overrides.js\";\n\n/**\n * Connect's hardcoded PWA manifest. The base layer of the override ladder —\n * package `pwa` fragments and the project's `connect.pwa` block are laid on\n * top of this by `applyPwaOverrides`.\n */\nconst BASE_MANIFEST: ConnectPwaManifest = {\n name: \"Powerhouse Connect\",\n short_name: \"Connect\",\n description:\n \"A navigation, collaboration and reporting tool for decentralised and open organisations.\",\n theme_color: \"#ffffff\",\n background_color: \"#ffffff\",\n display: \"standalone\",\n start_url: \".\",\n scope: \".\",\n icons: [\n { src: \"pwa-192x192.png\", sizes: \"192x192\", type: \"image/png\" },\n { src: \"pwa-512x512.png\", sizes: \"512x512\", type: \"image/png\" },\n {\n // Full-bleed variant: maskable icons get cropped to the platform shape,\n // so the logo sits inside the safe zone instead of reusing the rounded\n // \"any\" icon (whose transparent corners would show through the mask).\n src: \"pwa-512x512-maskable.png\",\n sizes: \"512x512\",\n type: \"image/png\",\n purpose: \"maskable\",\n },\n ],\n // OS-level file associations for the installed PWA (File Handling API,\n // Chromium desktop). Powerhouse documents are zip archives, but keying on\n // application/zip would make Connect a candidate handler for EVERY zip on\n // MIME-keyed platforms — hence the vendor types with the RFC 6839 +zip\n // suffix. Config-contributed handlers are appended after this entry, and\n // Chromium is first-registered-wins per extension, so .phd/.phdm cannot be\n // hijacked by a package. Consuming the launched files happens in the\n // Connect SPA (launchQueue consumer).\n file_handlers: [\n {\n action: FILE_HANDLER_ACTION,\n accept: {\n \"application/vnd.powerhouse.document+zip\": [\".phd\"],\n \"application/vnd.powerhouse.document-model+zip\": [\".phdm\"],\n },\n // OS file-type icons: the same Powerhouse document icon the in-app\n // import list shows. Declared per spec, but note Chromium doesn't\n // consume them on desktop yet — macOS synthesizes document icons from\n // the app icon (no CFBundleTypeIconFile is written), and Windows\n // support is unimplemented (FileHandlingIconsSupportedByOs() is false,\n // crbug.com/40185571). Shipping them is forward-compatible and costs\n // nothing. Assets emitted by connectPwaIconsPlugin, precached via the\n // png glob.\n icons: [\n {\n src: \"document-icon-192x192.png\",\n sizes: \"192x192\",\n type: \"image/png\",\n },\n {\n src: \"document-icon-512x512.png\",\n sizes: \"512x512\",\n type: \"image/png\",\n },\n ],\n },\n ],\n // Opening a handled file focuses the running Connect window (launchQueue\n // delivers the file there) instead of spawning a new window per file.\n launch_handler: { client_mode: \"focus-existing\" },\n};\n\n/**\n * Connect's hardcoded precache config — the base layer for the `injectManifest`\n * precache. Overridable additively (extra globs) or by raising the size ceiling\n * via package/project `pwa` config. The rest of the old Workbox config\n * (runtime-caching rules with their function urlPatterns, the navigation\n * fallback, clientsClaim/skipWaiting/cleanupOutdatedCaches) now lives as\n * imperative code in the hand-written service worker\n * (../service-worker/service-worker.ts), because `injectManifest` has no\n * declarative runtimeCaching option.\n */\nconst BASE_PRECACHE: ConnectPrecacheOptions = {\n // PGlite's wasm + fs bundles are several MB each; Workbox's 2 MiB\n // default would silently skip them and the in-browser Postgres would\n // fail to initialise offline. Raise the ceiling so they precache.\n maximumFileSizeToCacheInBytes: 16 * 1024 * 1024,\n // Precache the app shell AND the PGlite assets. The default glob omits\n // `.wasm`/`.data`, but PGlite's Postgres-in-wasm needs both its `.wasm`\n // and its `.data` filesystem bundles, or the in-browser DB fails to\n // initialise offline (\"Failed to fetch\").\n globPatterns: [\"**/*.{js,css,html,wasm,data,ico,png,svg,webp,woff,woff2}\"],\n // powerhouse.config.json is operator-editable and served no-cache, so\n // precaching it would freeze runtime config; source maps don't belong\n // in the precache either. manifest.webmanifest is added at wiring time so\n // the SW's dynamic manifest route is the sole producer at that URL.\n globIgnores: [\"**/powerhouse.config.json\", \"**/*.map\"],\n};\n\nconst SW_FILENAME = \"service-worker.ts\";\n\n/**\n * Absolute directory holding the hand-written service-worker source. Resolved\n * relative to THIS module so it works from source\n * (connect-utils/vite-plugins → ../service-worker) and from the bundled dist\n * (dist/index.mjs → ./service-worker, where tsdown copies it). vite-plugin-pwa\n * resolves `swSrc = path.resolve(root, srcDir, filename)`, and `path.resolve`\n * ignores `root` when `srcDir` is absolute — so the SW ships with\n * builder-tools instead of every project needing its own copy.\n */\nfunction resolveServiceWorkerDir(): string {\n const here = dirname(fileURLToPath(import.meta.url));\n const candidates = [\n resolve(here, \"../service-worker\"), // source layout\n resolve(here, \"service-worker\"), // bundled dist layout\n ];\n return (\n candidates.find((dir) => existsSync(join(dir, SW_FILENAME))) ??\n candidates[0]\n );\n}\n\n/**\n * Virtual module that feeds the hand-written SW its build-time data. Passed\n * into vite-plugin-pwa's SEPARATE injectManifest build via\n * `injectManifest.buildPlugins.vite`: that build runs with `configFile: false`,\n * so the app's own plugins aren't present, but buildPlugins (and `define`) are.\n */\nfunction phSwConfigPlugin(data: Record<string, unknown>): Plugin {\n const virtualId = \"virtual:ph-sw-config\";\n const resolvedId = `\\0${virtualId}`;\n return {\n name: \"ph-sw-config\",\n resolveId(id) {\n if (id === virtualId) return resolvedId;\n },\n load(id) {\n if (id !== resolvedId) return;\n return Object.entries(data)\n .map(\n ([key, value]) => `export const ${key} = ${JSON.stringify(value)};`,\n )\n .join(\"\\n\");\n },\n };\n}\n\n/**\n * Service-worker / PWA support for Connect, gated by `connect.app.offline`.\n *\n * When enabled (the default), Workbox `injectManifest` bundles Connect's\n * hand-written service worker (../service-worker/service-worker.ts), which\n * precaches the built app shell so Connect loads with no network, runtime-\n * caches the Google-hosted Inter font + the registry CDN + the runtime config,\n * AND serves a dynamic web-app manifest so packages installed AT RUNTIME can\n * extend it (their fragments are mirrored into IndexedDB by the SPA; the base\n * the SW merges onto is embedded here at build time). The manifest and precache\n * config start from the BASE_* defaults above and are extended by `pwa` — the\n * effective, already-merged overrides from build-time packages and the\n * project's `connect.pwa` block (see mergePwaConfig). Registration is left to\n * the Connect SPA (`serviceWorkerManager`, `injectRegister: null`).\n *\n * When disabled, a self-destroying worker is emitted at the same URL so any\n * worker a previous offline-enabled build installed unregisters itself and\n * clears its caches on the browser's next service-worker update check.\n */\nexport function connectPwaPlugins(options: {\n offlineEnabled: boolean;\n /** Effective PWA overrides (packages + project), already merged. */\n pwa?: PHConnectPwa;\n}): PluginOption[] {\n const { offlineEnabled, pwa } = options;\n\n if (!offlineEnabled) {\n return [\n VitePWA({\n selfDestroying: true,\n strategies: \"generateSW\",\n injectRegister: null,\n filename: \"service-worker.js\",\n devOptions: { enabled: false },\n }),\n ];\n }\n\n const { manifest, precache } = applyPwaOverrides(\n { manifest: BASE_MANIFEST, precache: BASE_PRECACHE },\n pwa ?? {},\n );\n\n // Build-time data handed to the SW via the virtual module. EMBEDDED_BASE_\n // MANIFEST is the base the runtime manifest route merges dynamically-\n // installed package fragments onto; the two EXTRA_* arrays are the\n // serialisable build-time contributions the SW registers after its built-ins.\n const swConfig = {\n EMBEDDED_BASE_MANIFEST: manifest,\n EXTRA_RUNTIME_CACHING: pwa?.runtimeCaching ?? [],\n NAVIGATE_FALLBACK_DENYLIST_EXTRA: pwa?.navigateFallbackDenylist ?? [],\n };\n\n return [\n connectPwaIconsPlugin(),\n VitePWA({\n strategies: \"injectManifest\",\n // Absolute srcDir → swSrc is builder-tools' own SW source; the emitted\n // file is service-worker.js (vite-plugin-pwa maps the .ts source).\n srcDir: resolveServiceWorkerDir(),\n filename: SW_FILENAME,\n // prompt → the new worker waits; the SPA surfaces a refresh prompt and\n // posts SKIP_WAITING when the user accepts (see serviceWorkerManager).\n registerType: \"prompt\",\n injectRegister: null,\n // ph connect studio keeps running without a service worker.\n devOptions: { enabled: false },\n // Icons are emitted by connectPwaIconsPlugin and precached via the png\n // glob, so the plugin must not also try to resolve them from /public.\n includeManifestIcons: false,\n // Still emitted as the static base/offline fallback + the <link>.\n manifest,\n injectManifest: {\n globPatterns: precache.globPatterns,\n // Exclude the webmanifest from precache so the SW's dynamic route is\n // the sole producer at that URL.\n globIgnores: [...precache.globIgnores, \"**/manifest.webmanifest\"],\n maximumFileSizeToCacheInBytes: precache.maximumFileSizeToCacheInBytes,\n buildPlugins: { vite: [phSwConfigPlugin(swConfig)] },\n },\n }),\n ];\n}\n","// Self-host React: emit the React family into the Connect dist and point the\n// page import map at it, instead of resolving react/react-dom from esm.sh.\nimport { spawn } from \"node:child_process\";\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname as pathDirname, join, resolve } from \"node:path\";\nimport type { Plugin } from \"vite\";\n\n// URL path (under base) the React bundle is emitted/served at.\nconst REACT_URL_DIR = \"__react__\";\n\n// Packages whose every browser-importable subpath is self-hosted.\nconst REACT_PACKAGES = [\"react\", \"react-dom\"];\n\n// Resolve an exports value to its browser-preferred target, or null.\nfunction importTarget(value: unknown): string | null {\n if (typeof value === \"string\") return value;\n if (!value || typeof value !== \"object\") return null;\n const o = value as Record<string, unknown>;\n for (const c of [\"browser\", \"import\", \"module\", \"default\"]) {\n if (c in o) {\n const t = importTarget(o[c]);\n if (t) return t;\n }\n }\n return null;\n}\n\n// All browser-usable subpaths of react/react-dom, mapped to the absolute file\n// their browser condition resolves to. Node/bun-only targets are skipped.\nfunction resolveReactEntries(dirname: string): Record<string, string> {\n const require = createRequire(join(dirname, \"noop.js\"));\n const out: Record<string, string> = {};\n for (const pkg of REACT_PACKAGES) {\n let pkgRoot: string;\n let exp: unknown;\n try {\n const pkgJsonPath = require.resolve(`${pkg}/package.json`);\n pkgRoot = pathDirname(pkgJsonPath);\n exp = (\n JSON.parse(readFileSync(pkgJsonPath, \"utf8\")) as { exports?: unknown }\n ).exports;\n } catch {\n continue;\n }\n if (!exp || typeof exp !== \"object\") continue;\n for (const key of Object.keys(exp as Record<string, unknown>)) {\n if (key === \"./package.json\" || key.includes(\"*\")) continue;\n const target = importTarget((exp as Record<string, unknown>)[key]);\n // Skip non-JS and runtime-only (node/bun) targets — unusable in a browser.\n if (!target || /\\.(json|css)$/.test(target)) continue;\n if (/\\.(node|bun)\\.js$/.test(target)) continue;\n const file = join(pkgRoot, target);\n if (!existsSync(file)) continue;\n out[key === \".\" ? pkg : `${pkg}${key.slice(1)}`] = file;\n }\n }\n return out;\n}\n\nexport interface ReactSelfHostOptions {\n // Project root used to resolve react/react-dom and run the sub-build.\n dirname: string;\n // Emit the development React build (warnings/act) instead of production.\n dev?: boolean;\n}\n\n// Emits one React variant (dev or prod, per options.dev) into the dist and\n// injects a static import map pointing every react/react-dom subpath at it.\nexport function reactSelfHostPlugin(options: ReactSelfHostOptions): Plugin {\n const entries = resolveReactEntries(options.dirname);\n let absOutDir = resolve(options.dirname, \"dist\");\n let importMap: Record<string, string> = {};\n return {\n name: \"ph-react-self-host\",\n apply: \"build\",\n configResolved(config) {\n absOutDir = resolve(config.root, config.build.outDir);\n // Entry URLs mirror the specifier (react-dom/client -> __react__/react-dom/client.js)\n // so the trailing-slash catch-alls below resolve any subpath to the same file.\n importMap = Object.fromEntries(\n Object.keys(entries).map((spec) => [\n spec,\n `${config.base}${REACT_URL_DIR}/${spec}.js`,\n ]),\n );\n // Catch-all per package: an unenumerated react/* import resolves to the single\n // self-hosted instance (same-origin) instead of failing import-map resolution.\n for (const pkg of REACT_PACKAGES) {\n importMap[`${pkg}/`] = `${config.base}${REACT_URL_DIR}/${pkg}/`;\n }\n },\n transformIndexHtml() {\n if (!Object.keys(importMap).length) return;\n return [\n {\n tag: \"script\",\n attrs: { type: \"importmap\" },\n children: JSON.stringify({ imports: importMap }),\n injectTo: \"head-prepend\",\n },\n ];\n },\n async closeBundle() {\n if (!Object.keys(entries).length) return;\n const { ok, stderr } = await runReactBuild(\n options.dirname,\n join(absOutDir, REACT_URL_DIR),\n entries,\n options.dev ? \"development\" : \"production\",\n );\n if (!ok) {\n this.error(\n `react self-host build failed${stderr.trim() ? `:\\n${stderr.trim()}` : \"\"}`,\n );\n }\n },\n };\n}\n\n// Spawn a throwaway worker that builds the React family; peak build memory is\n// reclaimed when the subprocess exits.\nfunction runReactBuild(\n dirname: string,\n outDir: string,\n entries: Record<string, string>,\n nodeEnv: \"development\" | \"production\",\n): Promise<{ ok: boolean; stderr: string }> {\n mkdirSync(outDir, { recursive: true });\n const workerPath = join(outDir, \"build-worker.mjs\");\n writeFileSync(workerPath, REACT_BUILD_WORKER);\n return new Promise((resolvePromise) => {\n const child = spawn(\n process.execPath,\n [workerPath, dirname, outDir, JSON.stringify(entries), nodeEnv],\n { cwd: dirname, stdio: [\"ignore\", \"pipe\", \"pipe\"] },\n );\n let out = \"\";\n child.stdout.on(\"data\", (d) => (out += String(d)));\n child.stderr.on(\"data\", (d) => (out += String(d)));\n const done = (r: { ok: boolean; stderr: string }) => {\n rmSync(workerPath, { force: true });\n resolvePromise(r);\n };\n child.on(\"exit\", (code) => done({ ok: code === 0, stderr: out }));\n child.on(\"error\", (e) => done({ ok: false, stderr: String(e) }));\n });\n}\n\n// Worker: one ESM entry per subpath with explicit named re-exports. Names come\n// from the browser-resolved file (node names differ for server/static).\nconst REACT_BUILD_WORKER = `\nimport { createRequire } from 'node:module';\nimport { mkdirSync, writeFileSync, rmSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nconst [dirname, outDir, entriesJSON, nodeEnv] = process.argv.slice(2);\nconst entries = JSON.parse(entriesJSON);\nconst reqProj = createRequire(join(dirname, 'noop.js'));\nconst { build } = await import(reqProj.resolve('vite'));\nconst srcDir = join(outDir, '.entries');\nmkdirSync(srcDir, { recursive: true });\nconst entryName = (spec) => spec.replace(/[^\\\\w]+/g, '_');\nconst RESERVED = new Set('enum void null function in instanceof typeof new delete do if else return switch case break continue for while this true false class const let var default export import extends super with yield debugger finally throw try catch await implements interface package private protected public static eval arguments'.split(' '));\nconst input = {};\nfor (const [spec, file] of Object.entries(entries)) {\n const name = entryName(spec);\n let names = [];\n try {\n const ns = await import(pathToFileURL(file).href);\n const obj = (ns.default && typeof ns.default === 'object') ? ns.default : ns;\n names = Object.keys(obj).filter((k) => k !== 'default' && k !== '__esModule' && /^[A-Za-z_$][\\\\w$]*$/.test(k));\n } catch {}\n const plain = names.filter((n) => !RESERVED.has(n));\n const reserved = names.filter((n) => RESERVED.has(n));\n let src = 'import __m from ' + JSON.stringify(spec) + ';\\\\nexport default __m;\\\\n';\n if (plain.length) src += 'export const { ' + plain.join(', ') + ' } = __m;\\\\n';\n reserved.forEach((n, i) => {\n src += 'const __r' + i + ' = __m[' + JSON.stringify(n) + '];\\\\nexport { __r' + i + ' as ' + n + ' };\\\\n';\n });\n const entryFile = join(srcDir, name + '.js');\n writeFileSync(entryFile, src);\n // Key by the full spec so the output path mirrors the subpath\n // (react-dom/client -> react-dom/client.js), matching the catch-all import map.\n input[spec] = entryFile;\n}\ntry {\n await build({\n root: dirname, configFile: false, logLevel: 'error',\n base: './', publicDir: false,\n define: { 'process.env.NODE_ENV': JSON.stringify(nodeEnv) },\n resolve: { conditions: ['browser', 'import', 'module', 'default'] },\n build: {\n outDir, emptyOutDir: false, minify: nodeEnv === 'production', target: 'esnext',\n rollupOptions: {\n input, preserveEntrySignatures: 'strict',\n output: { format: 'es', entryFileNames: '[name].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]' },\n },\n },\n });\n rmSync(srcDir, { recursive: true, force: true });\n // Force exit: rolldown can leave native worker threads alive that keep the\n // event loop open, hanging the parent's spawn() promise indefinitely.\n process.exit(0);\n} catch (err) {\n console.error(err instanceof Error ? (err.stack ?? err.message) : String(err));\n process.exit(1);\n}\n`;\n","import type { Plugin } from \"vite\";\n\n/**\n * Marker attribute on the injected script. Serve-time injectors (e.g. the\n * ph-clint connect proxy) and this plugin both check it, so the script is\n * applied exactly once no matter which layer runs first.\n */\nexport const THEME_BOOT_MARKER = \"data-ph-theme-boot\";\n\n/**\n * Pre-paint theme boot: `?theme=dark|light` persists to `ph:theme`, then the\n * stored choice (or system preference) decides the `.dark` root class before\n * hydration. Fail-silent — storage access can throw in embed/privacy contexts.\n * Keep semantically identical to the runtime store in\n * `@powerhousedao/reactor-browser` (hooks/theme.ts).\n */\nconst THEME_BOOT_SCRIPT =\n `(function(){try{` +\n `var p=new URLSearchParams(location.search).get('theme');` +\n `if(p==='dark'||p==='light')localStorage.setItem('ph:theme',p);` +\n `var s=localStorage.getItem('ph:theme');` +\n `var d=s==='dark'||((!s||s==='system')&&matchMedia('(prefers-color-scheme: dark)').matches);` +\n `document.documentElement.classList.toggle('dark',d);` +\n `}catch(e){}})();`;\n\n/**\n * Injects the theme boot script at the top of `<head>` of every emitted\n * index.html, so built Connect apps render the stored theme from first paint\n * without depending on a serve-time injector.\n */\nexport function connectThemeBootPlugin(): Plugin {\n return {\n name: \"ph-connect-theme-boot\",\n transformIndexHtml(html) {\n if (html.includes(THEME_BOOT_MARKER)) return;\n return {\n html,\n tags: [\n {\n tag: \"script\",\n attrs: { [THEME_BOOT_MARKER]: \"\" },\n children: THEME_BOOT_SCRIPT,\n injectTo: \"head-prepend\",\n },\n ],\n };\n },\n };\n}\n","import type { PowerhouseConfig } from \"@powerhousedao/config\";\nimport { getConfig } from \"@powerhousedao/config/node\";\nimport {\n deepMerge,\n loadConnectEnv,\n mergePwaConfig,\n normalizeBasePath,\n setConnectEnv,\n} from \"@powerhousedao/shared/connect\";\nimport tailwind from \"@tailwindcss/vite\";\nimport react from \"@vitejs/plugin-react\";\nimport { realpathSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n createLogger,\n esmExternalRequirePlugin,\n loadEnv,\n searchForWorkspaceRoot,\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 { devReactImportmapPlugin } from \"./vite-plugins/dev-external-react.js\";\nimport {\n DYNAMIC_BASE_PLACEHOLDER,\n connectDynamicBasePlugin,\n} from \"./vite-plugins/dynamic-base.js\";\nimport { connectFaviconPlugin } from \"./vite-plugins/favicon.js\";\nimport { phBundledPackagesPlugin } from \"./vite-plugins/ph-bundled-packages.js\";\nimport { phConfigPlugin } from \"./vite-plugins/ph-config.js\";\nimport {\n collectPackagePwaContributions,\n collectProjectPwaContribution,\n validateProjectPwaConfig,\n} from \"./vite-plugins/pwa-packages.js\";\nimport { connectPwaPlugins } from \"./vite-plugins/pwa.js\";\nimport { reactSelfHostPlugin } from \"./vite-plugins/react-self-host.js\";\nimport { connectThemeBootPlugin } from \"./vite-plugins/theme-boot.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'${registryUrl ? \" \" + registryUrl : \"\"}; worker-src 'self' blob:; 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 parsePackagesEnvOverride(phPackagesStr: string) {\n return phPackagesStr\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n .map((entry) => {\n const lastAt = entry.lastIndexOf(\"@\");\n if (lastAt > 0) {\n return {\n packageName: entry.slice(0, lastAt),\n version: entry.slice(lastAt + 1),\n provider: \"registry\" as const,\n };\n }\n return { packageName: entry, provider: \"registry\" as const };\n });\n}\n\nfunction getLocalPackageNamesFromPowerhouseConfig({\n packages,\n}: PowerhouseConfig) {\n if (!packages) return [];\n return packages\n .filter((p) => p.provider === \"local\")\n .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 > 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 // Source config is always the project-root powerhouse.config.json.\n const phConfigPath = join(options.dirname, \"powerhouse.config.json\");\n\n const phConfig = options.powerhouseConfig ?? getConfig(phConfigPath);\n\n const packagesFromConfig = phConfig.packages ?? [];\n const localPackagesFromConfig =\n getLocalPackageNamesFromPowerhouseConfig(phConfig);\n const phPackagesStr = env.PH_PACKAGES;\n const envPhPackages = phPackagesStr\n ? parsePackagesEnvOverride(phPackagesStr)\n : undefined;\n\n const phPackages = envPhPackages ?? packagesFromConfig;\n\n // Precedence (highest → lowest): `ph connect build --packages-registry`\n // CLI override > source-config `packageRegistryUrl`. The resolved value\n // flows both into the CSP header (script-src allowance for the registry\n // CDN) and into the emitted runtime config so the SPA reads the same\n // value.\n const phPackageRegistryUrl =\n options.cliPackageRegistryUrl ?? phConfig.packageRegistryUrl ?? null;\n\n // Base path is a runtime-config field (connect.app.basePath), not an env\n // var. Resolve it with the same precedence as the rest of the connect\n // config: CLI override > source powerhouse.config.json.\n const connectBasePath =\n options.cliConnectOverride?.app?.basePath ??\n phConfig.connect?.app?.basePath;\n\n const offlineEnabled =\n options.cliConnectOverride?.app?.offline ??\n phConfig.connect?.app?.offline ??\n true;\n\n const authToken = env.PH_SENTRY_AUTH_TOKEN;\n const org = env.PH_SENTRY_ORG;\n const project = env.PH_SENTRY_PROJECT;\n // Release tag derived from the workspace version so it matches the\n // sourcemap upload tag CI uses.\n const release =\n process.env.WORKSPACE_VERSION ??\n process.env.npm_package_version ??\n env.PH_CONNECT_VERSION;\n const uploadSentrySourcemaps = authToken && org && project;\n\n const connectHtmlTags = getConnectHtmlTags({\n registryUrl: phPackageRegistryUrl,\n });\n\n // Dev needs a placeholder importmap for devReactImportmapPlugin to rewrite;\n // builds get their map from reactSelfHostPlugin's boot script instead.\n const devImportmapTag =\n mode === \"development\"\n ? [\n {\n tag: \"script\",\n attrs: { type: \"importmap\" },\n children: JSON.stringify({ imports: {} }),\n injectTo: \"head-prepend\" as const,\n },\n ]\n : [];\n\n const plugins: PluginOption[] = [\n tailwind(),\n react(),\n createHtmlPlugin({\n minify: false,\n inject: {\n tags: [...connectHtmlTags, ...devImportmapTag],\n },\n }),\n ] as const;\n\n if (uploadSentrySourcemaps) {\n plugins.push(\n import(\"@sentry/vite-plugin\").then(({ sentryVitePlugin }) =>\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 }),\n ) as PluginOption,\n );\n }\n\n // hide warnings unless LOG_LEVEL is set to debug, or the source config\n // declares connect.app.logLevel = \"debug\"\n const isDebug =\n process.env.LOG_LEVEL === \"debug\" ||\n phConfig.connect?.app?.logLevel === \"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 // PWA overrides ladder: build-time-known package `pwa` fragments merge UNDER\n // the project's `connect.pwa` block (source deep-merged with the CLI/operator\n // override, CLI wins). Scalars are project-wins; arrays (icons, globs,\n // runtime-caching rules, denylist) are additive; the size ceiling takes the\n // max. Fragments come from the configured packages (local from node_modules,\n // registry from the CDN) and, last among packages, the project's own\n // manifest. The user's own connect.pwa is validated strictly (fails the\n // build); package fragments warn + skip inside the collectors.\n const projectPwa = validateProjectPwaConfig(\n deepMerge(\n phConfig.connect?.pwa ?? {},\n options.cliConnectOverride?.pwa ?? {},\n ),\n phConfigPath,\n );\n const pwaWarn = (msg: string) => (customLogger ?? console).warn(msg);\n // Registry fragments need the network, so only production builds fetch them\n // (dev/studio runs without a service worker and must not depend on the\n // registry being reachable). Async: Vite resolves promised plugins, same\n // pattern as the sentry plugin below.\n const pwaPackagesForFragments =\n mode === \"production\"\n ? phPackages\n : phPackages.filter((p) => p.provider === \"local\");\n const pwaPlugins: PluginOption = (async () => {\n if (!offlineEnabled) return connectPwaPlugins({ offlineEnabled });\n const contributions = await collectPackagePwaContributions({\n packages: pwaPackagesForFragments,\n projectRoot: options.dirname,\n registryUrl: phPackageRegistryUrl,\n onWarn: pwaWarn,\n });\n const projectContribution = collectProjectPwaContribution({\n projectRoot: options.dirname,\n });\n if (projectContribution) contributions.push(projectContribution);\n const mergedPwa = mergePwaConfig(contributions, projectPwa, pwaWarn);\n return connectPwaPlugins({ offlineEnabled, pwa: mergedPwa });\n })();\n\n const reactExternal = [\n \"react\",\n \"react-dom\",\n \"react/jsx-runtime\",\n \"react-dom/client\",\n ];\n\n // pnpm `link:` deps (e.g. a downstream project linking @powerhousedao/*\n // packages from a sibling monorepo checkout) live outside Vite's\n // auto-detected workspace root. Their `node_modules/.pnpm/...` assets\n // then 403 through `/@fs/`, returning a 760-byte HTML body where the\n // binary should be — which breaks PGlite at startup with \"Invalid FS\n // bundle size: 760 !== 4939170\". Resolve key linked packages back to\n // their real workspace roots and allow Vite to serve from there.\n const linkedRoots = [\n \"@powerhousedao/reactor-browser\",\n \"@powerhousedao/connect\",\n \"@electric-sql/pglite\",\n ]\n .map((pkg) => {\n try {\n return searchForWorkspaceRoot(\n realpathSync(join(options.dirname, \"node_modules\", pkg)),\n );\n } catch {\n return null;\n }\n })\n .filter((p): p is string => p !== null);\n\n const config: InlineConfig = {\n configFile: false,\n mode,\n // Prefix served/built asset URLs so Connect can run under a path prefix\n // (reverse proxy). Mirrors the client router basename; normalize so a bare\n // `app` or `/app` becomes `/app/` and matches the router.\n //\n // Dynamic-base mode: set a placeholder token instead of a concrete base.\n // connectDynamicBasePlugin (below) rewrites it in the emitted JS to a\n // runtime expression so one bundle serves under any subpath; the proxy\n // substitutes it in the HTML and sets the runtime global at serve time.\n base: options.dynamicBase\n ? DYNAMIC_BASE_PLACEHOLDER\n : connectBasePath\n ? normalizeBasePath(connectBasePath)\n : undefined,\n server: {\n watch: {\n ignored: [\"**/backup-documents/**\", \"**/.ph/**\"],\n },\n fs: {\n allow: [searchForWorkspaceRoot(options.dirname), ...linkedRoots],\n },\n },\n resolve: {\n dedupe: [\"react\", \"react-dom\"],\n tsconfigPaths: true,\n },\n define: {\n PH_CONNECT_SENTRY_RELEASE: JSON.stringify(release || \"unknown\"),\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 // phConfigPlugin 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 phConfigPlugin({\n packages: phPackages,\n projectRoot: options.dirname,\n connect: phConfig.connect,\n packageRegistryUrl: phPackageRegistryUrl ?? undefined,\n cliConnectOverride: options.cliConnectOverride,\n }),\n phBundledPackagesPlugin({\n packages: localPackagesFromConfig,\n projectRoot: options.dirname,\n }),\n // Dev-only: rewrite the importmap to Vite's pre-bundled React so Connect\n // and CDN editors share one instance (build uses reactSelfHostPlugin).\n devReactImportmapPlugin(options.dirname),\n ...plugins,\n // Externalize React so Connect + CDN editors share one instance via the\n // import map (reactSelfHostPlugin URLs); also rewrites external require().\n esmExternalRequirePlugin({ external: reactExternal }),\n // Build-only: emit the React family into the dist + static import map, so\n // React is self-hosted (not esm.sh). Dev React for non-prod/debug builds.\n reactSelfHostPlugin({\n dirname: options.dirname,\n dev: mode !== \"production\" || isDebug,\n }),\n connectFaviconPlugin({ faviconPath: options.favicon }),\n // Pre-paint theme boot in every emitted index.html (marker-idempotent\n // with the serve-time injection in the ph-clint connect proxy).\n connectThemeBootPlugin(),\n // enforce: \"post\" — rewrites the placeholder base after all other\n // transforms have emitted their asset/chunk URLs.\n ...(options.dynamicBase ? [connectDynamicBasePlugin()] : []),\n // PWA / service worker last, so its precache manifest sees every emitted\n // asset (including the icons connectPwaIconsPlugin emits).\n pwaPlugins,\n ],\n worker: {\n format: \"es\",\n // Worker chunks are emitted by a separate Rolldown build, so the main\n // bundle's generateBundle never sees them. The worker instance both\n // rewrites the placeholder and prepends a prelude that resolves the base\n // in worker scope (forWorker) — the proxy only sets the global on the\n // main thread.\n ...(options.dynamicBase\n ? { plugins: () => [connectDynamicBasePlugin({ forWorker: true })] }\n : {}),\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,2BAA2B;;;;;;AAOxC,MAAM,iBAAiB;AAIvB,MAAM,YAAY,IAAI,eAAe;AAIrC,SAAS,cAAc,aAA6B;AAIlD,QAAO,GAAG,eAAe,mCADV,gBAAgB,YAAY,CAAC,QAAQ,OAAO,MAAM,CACE;;AAcrE,MAAM,sBAAsB,IAAI,OAC9B,WAAW,gBAAgB,yBAAyB,CAAC,wBACrD,IACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BD,SAAgB,yBACd,UAA+D,EAAE,EACzD;AACR,QAAO;EACL,MAAM;EACN,SAAS;EACT,YAAY,MAAM,OAAO;AACvB,OAAI,CAAC,KAAK,SAAA,wBAAkC,CAAE,QAAO;GAErD,MAAM,IAAI,IAAI,YAAY,KAAK;AAC/B,QAAK,MAAM,SAAS,KAAK,SAAS,oBAAoB,EAAE;IACtD,MAAM,OAAO,MAAM;AACnB,MAAE,UACA,MAAM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