@powerhousedao/connect 6.2.3-dev.71 → 6.2.3-dev.72
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/README.md +1 -1
- package/RUNTIME-CONFIG.md +2 -90
- package/dist/{ClearStorageModal-DxBXLSmH.js → ClearStorageModal-DQv3ZGOq.js} +4 -4
- package/dist/{ClearStorageModal-DxBXLSmH.js.map → ClearStorageModal-DQv3ZGOq.js.map} +1 -1
- package/dist/{CreateDocumentModal-B-cXzeOA.js → CreateDocumentModal-CiIW3pzx.js} +18 -9
- package/dist/CreateDocumentModal-CiIW3pzx.js.map +1 -0
- package/dist/{DebugSettingsModal-D1I-K2Gf.js → DebugSettingsModal-DjFwGop2.js} +6 -6
- package/dist/{DebugSettingsModal-D1I-K2Gf.js.map → DebugSettingsModal-DjFwGop2.js.map} +1 -1
- package/dist/{InspectorModal-D85U4oKJ.js → InspectorModal-C1ZVZpT5.js} +6 -6
- package/dist/{InspectorModal-D85U4oKJ.js.map → InspectorModal-C1ZVZpT5.js.map} +1 -1
- package/dist/app-loader-ClDJbH8j.js +4 -0
- package/dist/{app-loader-casiq2T2.js → app-loader-DxGySldw.js} +11 -11
- package/dist/{app-loader-casiq2T2.js.map → app-loader-DxGySldw.js.map} +1 -1
- package/dist/{boot-CFPdHSqB.js → boot-D2-yDYJi.js} +4 -4
- package/dist/{boot-CFPdHSqB.js.map → boot-D2-yDYJi.js.map} +1 -1
- package/dist/{build-info-Cn2f6llN.js → build-info-CZ8K52c5.js} +5 -5
- package/dist/{build-info-Cn2f6llN.js.map → build-info-CZ8K52c5.js.map} +1 -1
- package/dist/{components-C4K5xyad.js → components-B36iVkNp.js} +6 -6
- package/dist/{components-C4K5xyad.js.map → components-B36iVkNp.js.map} +1 -1
- package/dist/{connect.config-D1pGNmaF.js → connect.config-DL9nKtlW.js} +6 -5
- package/dist/connect.config-DL9nKtlW.js.map +1 -0
- package/dist/{connection-state-B6fleM37.js → connection-state-Bwm9Agwy.js} +4 -4
- package/dist/{connection-state-B6fleM37.js.map → connection-state-Bwm9Agwy.js.map} +1 -1
- package/dist/{cookie-banner-CAvd3PC3.js → cookie-banner-NclLYtB0.js} +4 -4
- package/dist/{cookie-banner-CAvd3PC3.js.map → cookie-banner-NclLYtB0.js.map} +1 -1
- package/dist/generic.d.ts +20 -2
- package/dist/generic.d.ts.map +1 -1
- package/dist/generic.js +2 -2
- package/dist/{load-DcDV9hi4.js → load-C2wlvi5d.js} +9 -9
- package/dist/{load-DcDV9hi4.js.map → load-C2wlvi5d.js.map} +1 -1
- package/dist/{load-runtime-config-Deq75NYr.js → load-runtime-config-BeZF5z7m.js} +4 -4
- package/dist/{load-runtime-config-Deq75NYr.js.map → load-runtime-config-BeZF5z7m.js.map} +1 -1
- package/dist/main.js +2 -2
- package/dist/{package-manager-CzBsaUUd.js → package-manager-dfP4R5L3.js} +11 -10
- package/dist/{package-manager-CzBsaUUd.js.map → package-manager-dfP4R5L3.js.map} +1 -1
- package/dist/{pglite-seed-eGzXMld2.js → pglite-seed-QPbGbLB_.js} +4 -4
- package/dist/{pglite-seed-eGzXMld2.js.map → pglite-seed-QPbGbLB_.js.map} +1 -1
- package/dist/{plugins-CegSox2x.js → plugins-DV3oFEmL.js} +4 -4
- package/dist/{plugins-CegSox2x.js.map → plugins-DV3oFEmL.js.map} +1 -1
- package/dist/{preferences-store-CSqauT9V.js → preferences-store-DxYAnGCc.js} +4 -4
- package/dist/{preferences-store-CSqauT9V.js.map → preferences-store-DxYAnGCc.js.map} +1 -1
- package/dist/prerender.d.ts.map +1 -1
- package/dist/prerender.js +12 -5
- package/dist/prerender.js.map +1 -1
- package/dist/{reactor-BGYR1N7Z.js → reactor-DT1kVwnf.js} +12 -7
- package/dist/{reactor-BGYR1N7Z.js.map → reactor-DT1kVwnf.js.map} +1 -1
- package/dist/{registerServiceWorker-APlHkrmH.js → registerServiceWorker-X6fT91iL.js} +4 -4
- package/dist/{registerServiceWorker-APlHkrmH.js.map → registerServiceWorker-X6fT91iL.js.map} +1 -1
- package/dist/route-tree.js +1 -1
- package/dist/{route-views-CDVZytw4.js → route-views-DmmQ1DzX.js} +4 -4
- package/dist/{route-views-CDVZytw4.js.map → route-views-DmmQ1DzX.js.map} +1 -1
- package/dist/route-views.js +3 -3
- package/dist/router-CBzb5FUq.js +4 -0
- package/dist/{router-Cu0PH6sh.js → router-DXpaaTeR.js} +13 -5
- package/dist/router-DXpaaTeR.js.map +1 -0
- package/dist/{settings-CFn4TA0g.js → settings-BwKo6EAU.js} +10 -9
- package/dist/{settings-CFn4TA0g.js.map → settings-BwKo6EAU.js.map} +1 -1
- package/dist/{settings-tabs-BC8gAacB.js → settings-tabs-BubPdsiT.js} +24 -17
- package/dist/settings-tabs-BubPdsiT.js.map +1 -0
- package/dist/shell-head.html +1 -1
- package/dist/shell.html +1 -1
- package/dist/start-connect.js +2 -2
- package/dist/style.css +82 -0
- package/dist/{ui-BOTsJPoc.js → ui-BVOQ9tj_.js} +8 -8
- package/dist/{ui-BOTsJPoc.js.map → ui-BVOQ9tj_.js.map} +1 -1
- package/docs/customizing/data-and-navigation.md +50 -0
- package/docs/customizing/drive-apps.md +42 -0
- package/docs/customizing/hosts-and-plugins.md +23 -0
- package/docs/customizing/layout.md +9 -2
- package/docs/customizing/modals.md +25 -4
- package/docs/customizing/overrides.md +59 -4
- package/docs/customizing/packages.md +2 -0
- package/docs/customizing/pages.md +10 -13
- package/docs/customizing/styles-and-branding.md +9 -2
- package/docs/customizing/types-and-troubleshooting.md +4 -2
- package/generic-routes.json +9 -0
- package/package.json +19 -18
- package/skills/customize-connect/SKILL.md +14 -11
- package/CUSTOMIZING.md +0 -80
- package/dist/CreateDocumentModal-B-cXzeOA.js.map +0 -1
- package/dist/app-loader-D5GEwpML.js +0 -4
- package/dist/connect.config-D1pGNmaF.js.map +0 -1
- package/dist/router-B0OQvO11.js +0 -4
- package/dist/router-Cu0PH6sh.js.map +0 -1
- package/dist/settings-tabs-BC8gAacB.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"package-manager-CzBsaUUd.js","sources":["../src/shared-deps.ts","../src/utils/pwa-idb.ts","../src/package-manager.ts"],"sourcesContent":["import { resolveDynamicBaseUrl } from \"@powerhousedao/shared/connect\";\n\n// Set by `ph connect build`: the content-hashed shared-deps module URL.\ndeclare const PH_CONNECT_SHARED_DEPS_URL: string | undefined;\n\nfunction builtSharedDepsUrl(): string | undefined {\n return typeof PH_CONNECT_SHARED_DEPS_URL !== \"undefined\"\n ? PH_CONNECT_SHARED_DEPS_URL\n : undefined;\n}\n\n/** The shared-deps module URL: this build's hashed copy, else the stable dev path. */\nexport function sharedDepsModuleUrl(\n runtimeBase: string,\n built: string | undefined = builtSharedDepsUrl(),\n): string {\n return built\n ? resolveDynamicBaseUrl(built, runtimeBase)\n : `${runtimeBase}__vendor__/shared-deps.js`;\n}\n\nexport type SharedDeps = {\n imports: Record<string, string>;\n versions: Record<string, string>;\n};\n\n/**\n * Resolve the vendor's import-map values to absolute URLs: the\n * dynamic-base placeholder (present in dynamic-base builds) is replaced\n * with the runtime base — which `import.meta.env.BASE_URL` already is,\n * since the dynamic-base plugin rewrites it to the resolved base — and\n * the result is made absolute against the page origin. Absolute URLs are\n * what the worker needs: its imports have no document context, so\n * relative or placeholder-based values would not resolve there.\n */\nexport function normalizeVendorImports(\n rawImports: Record<string, string>,\n runtimeBase: string,\n): Record<string, string> {\n // `location` is a browser global; the fallback keeps the helper usable\n // from node-based tests, where no origin exists.\n const origin =\n (globalThis as { location?: Location }).location?.origin ??\n \"http://localhost\";\n return Object.fromEntries(\n Object.entries(rawImports).map(([spec, value]) => [\n spec,\n new URL(resolveDynamicBaseUrl(value, runtimeBase), origin).href,\n ]),\n );\n}\n\nlet cached: Promise<SharedDeps | null> | null = null;\n\n/**\n * The production vendor's shared-deps table: import-map entries for the\n * shared dependency set plus the resolved version of every shared package\n * in this build. Fails soft (`null`) when the vendor is not present (dev,\n * or a `PH_CONNECT_VENDOR=0` build) — callers treat that as \"no sharing\".\n * The promise is cached: the vendor table is immutable per build.\n */\nexport function getSharedDeps(): Promise<SharedDeps | null> {\n cached ??= (async () => {\n try {\n const mod = (await import(\n /* @vite-ignore */ sharedDepsModuleUrl(import.meta.env.BASE_URL)\n )) as {\n imports: Record<string, string>;\n versions: Record<string, string>;\n };\n return {\n imports: normalizeVendorImports(mod.imports, import.meta.env.BASE_URL),\n versions: mod.versions,\n };\n } catch {\n return null;\n }\n })();\n return cached;\n}\n","import {\n PWA_IDB_KEY,\n PWA_IDB_NAME,\n PWA_IDB_STORE,\n PWA_IDB_VERSION,\n type PHConnectPwa,\n type PHConnectPwaIcon,\n} from \"@powerhousedao/shared/connect\";\n\n// The page-owned mirror of the effective PWA fragment contributed by the\n// currently-installed packages. The service worker reads this (read-only) to\n// serve a live web-app manifest — a SW cannot reach localStorage (where the\n// package list lives), so BrowserPackageManager writes the merged fragment\n// here on every package change. The db/store/key/version constants are the\n// SHARED source of truth in @powerhousedao/shared/connect, imported by both\n// this writer and the SW reader so the two cannot desync.\n\nexport type PwaFragmentRecord = {\n version: 1;\n fragment: PHConnectPwa;\n updatedAt: number;\n};\n\n// Self-contained IDB open (not reusing pglite-idb) so this module — and its\n// pure `resolveFragmentAssetUrls` — carries no dependency on connect.config,\n// keeping it importable in isolation.\nfunction openPwaIdb(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const req = indexedDB.open(PWA_IDB_NAME, PWA_IDB_VERSION);\n req.onupgradeneeded = () => {\n if (!req.result.objectStoreNames.contains(PWA_IDB_STORE)) {\n req.result.createObjectStore(PWA_IDB_STORE);\n }\n };\n req.onerror = () => reject(req.error ?? new Error(\"ph-pwa open failed\"));\n req.onblocked = () => reject(new Error(\"ph-pwa open blocked\"));\n req.onsuccess = () => resolve(req.result);\n });\n}\n\n/** Write (replace) the single merged fragment record. Best-effort: a failure to\n * mirror the manifest must never break package installation, so callers ignore\n * rejections. No-op when IndexedDB is unavailable (SSR/tests). */\nexport async function writeMergedPwaFragment(\n fragment: PHConnectPwa,\n): Promise<void> {\n if (typeof indexedDB === \"undefined\") return;\n const db = await openPwaIdb();\n try {\n await new Promise<void>((resolve, reject) => {\n const tx = db.transaction(PWA_IDB_STORE, \"readwrite\");\n tx.oncomplete = () => resolve();\n tx.onerror = () =>\n reject(tx.error ?? new Error(\"PWA fragment write failed\"));\n tx.objectStore(PWA_IDB_STORE).put(\n {\n version: 1,\n fragment,\n updatedAt: Date.now(),\n } satisfies PwaFragmentRecord,\n PWA_IDB_KEY,\n );\n });\n } finally {\n db.close();\n }\n}\n\n/** Resolve `src` against the package `baseUrl`, absolute srcs passing through.\n * `baseUrl` may itself be relative (e.g. a same-origin-proxied registry, or the\n * dev `/node_modules/…` path), so it is first made absolute against the app\n * origin — `new URL(src, relativeBase)` would otherwise throw and silently\n * leave the src unresolved. A malformed src is left untouched. */\nfunction toAbsoluteAssetUrl(src: string, baseUrl: string): string {\n try {\n const origin =\n typeof location !== \"undefined\" ? location.href : \"http://localhost/\";\n return new URL(src, new URL(baseUrl, origin)).toString();\n } catch {\n return src;\n }\n}\n\nfunction resolveIconSrc(\n icon: PHConnectPwaIcon,\n baseUrl: string,\n): PHConnectPwaIcon {\n return { ...icon, src: toAbsoluteAssetUrl(icon.src, baseUrl) };\n}\n\n/**\n * Rewrite a package fragment's relative asset srcs (manifest icons and\n * file-handler icons) to absolute URLs against the package's base — a runtime\n * package's assets live on the registry CDN, not the app origin, so the served\n * manifest must point there. `baseUrl` null (a local/bundled package whose\n * assets are app-origin-relative) leaves srcs untouched.\n */\nexport function resolveFragmentAssetUrls(\n config: PHConnectPwa,\n baseUrl: string | null,\n): PHConnectPwa {\n if (!baseUrl || !config.manifest) return config;\n const m = config.manifest;\n const resolveIcons = (icons?: PHConnectPwaIcon[]) =>\n icons?.map((icon) => resolveIconSrc(icon, baseUrl));\n return {\n ...config,\n manifest: {\n ...m,\n icons: resolveIcons(m.icons),\n file_handlers: m.file_handlers?.map((handler) => ({\n ...handler,\n icons: resolveIcons(handler.icons),\n })),\n },\n };\n}\n","import type { PackageRoute } from \"@powerhousedao/connect-core/router\";\nimport {\n holdConnectRoutes,\n registerPackageRoutes,\n} from \"@powerhousedao/connect-core/router\";\nimport * as common from \"@powerhousedao/powerhouse-vetra-packages\";\nimport type {\n IPackagesListener,\n PackageManagerInstallResult,\n} from \"@powerhousedao/reactor-browser\";\nimport {\n BrowserLocalStorage,\n type IPackageListerUnsubscribe,\n type IPackageManager,\n} from \"@powerhousedao/reactor-browser\";\nimport {\n checkSharedDeps,\n CONNECT_LAYER_ORDER,\n formatSharedDepWarnings,\n mergePwaConfig,\n type PHConnectPwa,\n type PwaContribution,\n withInferredCategory,\n} from \"@powerhousedao/shared/connect\";\nimport {\n type DocumentModelLib,\n type DocumentModelModule,\n PwaConfigSchema,\n} from \"@powerhousedao/shared/document-model\";\nimport { toCdnUrl } from \"@powerhousedao/shared/registry/urls\";\nimport { getSharedDeps } from \"./shared-deps.js\";\nimport {\n resolveFragmentAssetUrls,\n writeMergedPwaFragment,\n} from \"./utils/pwa-idb.js\";\nimport { refreshPwaManifestLink } from \"./utils/pwa-manifest-link.js\";\n\ntype PackageMeta = {\n name: string;\n importUrl: string | null;\n stylesheetUrl: string | null;\n version?: string;\n /**\n * Full spec the user asked for (e.g. `@scope/pkg@2.0.0-beta.2`). Kept so a\n * reload re-installs exactly the tag/version originally picked rather than\n * sliding to `latest`. Absent for legacy entries and local packages.\n */\n spec?: string;\n};\n\n/**\n * Strip any `@tag` / `@version` suffix from a package spec, returning the bare\n * package name. Mirrors `parsePackageSpec` on the UI side.\n */\nfunction parseBareName(spec: string): string {\n const trimmed = spec.trim();\n const at = trimmed.startsWith(\"@\")\n ? trimmed.lastIndexOf(\"@\")\n : trimmed.indexOf(\"@\");\n return at > 0 ? trimmed.slice(0, at) : trimmed;\n}\n\n/** Loads the routes a package offers (its `./connect-routes`). */\nexport type PackageRoutesLoader = () => Promise<{\n connectRoutes: readonly PackageRoute[];\n}>;\n\ntype PackageWithMeta = PackageMeta & {\n loadedPackage: DocumentModelLib<any>;\n spec?: string;\n loadRoutes?: PackageRoutesLoader;\n};\n\ntype FetchedPackageJson = {\n version?: string;\n dependencies?: Record<string, unknown>;\n peerDependencies?: Record<string, unknown>;\n};\n\nasync function fetchPackageJson(\n baseUrl: string,\n): Promise<FetchedPackageJson | null> {\n try {\n const res = await fetch(baseUrl);\n if (!res.ok) return null;\n const pkg = (await res.json()) as {\n version?: unknown;\n dependencies?: Record<string, unknown>;\n peerDependencies?: Record<string, unknown>;\n };\n return {\n version: typeof pkg.version === \"string\" ? pkg.version : undefined,\n dependencies: pkg.dependencies,\n peerDependencies: pkg.peerDependencies,\n };\n } catch {\n return null;\n }\n}\n\nasync function fetchPackageJsonVersion(\n baseUrl: string,\n): Promise<string | undefined> {\n return (await fetchPackageJson(baseUrl))?.version;\n}\n\n/**\n * Human-readable warnings for shared-dep mismatches between a package's npm\n * `package.json` (as served by the CDN) and the host's shared-deps version\n * table. Empty when either side is unavailable — a dev / vendor-off host has\n * no table to compare against, and a missing package.json means the check\n * can't run. Used by both the install flow and the package-manager UI.\n */\nexport function sharedDepMismatchWarnings(\n pkgJson: FetchedPackageJson | null,\n hostVersions: Record<string, string> | null | undefined,\n): string[] {\n if (!pkgJson || !hostVersions) return [];\n return formatSharedDepWarnings(checkSharedDeps(pkgJson, hostVersions));\n}\n\n// The bundled packages' versions, inlined by bundled-package-versions.ts.\ndeclare const PH_COMMON_PACKAGE_VERSION: string;\ndeclare const PH_VETRA_PACKAGE_VERSION: string;\ndeclare const PH_WORKFLOW_PACKAGE_VERSION: string;\n\nconst LOCAL_PACKAGE_NAME = \"Local\" as const;\n\n// Package CSS goes in external-packages: above Connect's reset so it can style\n// its editors, below Connect's utilities so it can't override them.\nexport const LAYER_ORDER = CONNECT_LAYER_ORDER;\nconst LAYER_ORDER_ATTR = \"data-ph-layer-order\";\n\n// Layer order is set by the first declaration in the document, and a project's\n// style.css declares Tailwind's layers first, so this goes first in <head>.\n\nexport function declareExternalPackagesLayer(): void {\n if (document.head.querySelector(`style[${LAYER_ORDER_ATTR}]`)) return;\n const order = document.createElement(\"style\");\n order.setAttribute(LAYER_ORDER_ATTR, \"\");\n order.textContent = LAYER_ORDER;\n document.head.prepend(order);\n}\n\nexport class BrowserPackageManager implements IPackageManager {\n registryUrl: string | null;\n #storage: BrowserLocalStorage<PackageMeta>;\n #packages: Map<string, DocumentModelLib<any>> = new Map();\n #subscribers = new Set<IPackagesListener>();\n #packagesMemo: DocumentModelLib<any>[] = [];\n #stylesheets: Map<string, HTMLStyleElement> = new Map();\n /** Takes each package's offered routes out of the router. */\n #routes: Map<string, () => void> = new Map();\n #localPackage: DocumentModelLib<any> | undefined;\n\n #cdnUrl: string | null;\n #localPackageVersion: string | undefined;\n #localPackageNames: Set<string> = new Set([LOCAL_PACKAGE_NAME]);\n #pwaSyncTimer: ReturnType<typeof setTimeout> | undefined;\n /** Serialized last-mirrored PWA fragment; lets a sync skip the IndexedDB\n * write + manifest re-attach when nothing PWA-relevant changed. */\n #lastSyncedFragmentJson: string | undefined;\n\n constructor(namespace: string, registryUrl: string | null) {\n this.#storage = new BrowserLocalStorage<PackageMeta>(\n namespace + \":PH_PACKAGES\",\n );\n this.registryUrl = registryUrl;\n this.#cdnUrl = registryUrl !== null ? toCdnUrl(registryUrl) : null;\n }\n\n async init(\n localPackage?: DocumentModelLib<any>,\n localPackageVersion?: string,\n studioMode?: boolean,\n workflowsEnabled?: boolean,\n genericChrome = true,\n ) {\n // Common's editors (drive explorer, document model editor) are the generic\n // chrome's; without it, core gets only common's document models.\n this.addLocalPackage(\n common.manifest.name,\n genericChrome ? common : { ...common, editors: [] },\n PH_COMMON_PACKAGE_VERSION,\n );\n // Vetra is builder-only and not CDN-loadable; lazy-load it (code-split\n // chunk, never fetched in production) only in studio mode.\n if (studioMode) {\n const vetra = await import(\"@powerhousedao/vetra\");\n this.addLocalPackage(\n vetra.manifest.name,\n vetra,\n PH_VETRA_PACKAGE_VERSION,\n );\n }\n // Same shape for the workflow package, behind its own independent flag.\n // Only the package root: `./pieces` and `./reactor` are node-only.\n if (workflowsEnabled) {\n const workflow = await import(\"@powerhousedao/workflow\");\n this.addLocalPackage(\n workflow.manifest.name,\n workflow,\n PH_WORKFLOW_PACKAGE_VERSION,\n );\n }\n if (localPackage) {\n this.updateLocalPackage(localPackage, localPackageVersion);\n }\n for (const packageName of this.#storage.keys()) {\n // Re-hydrate with the originally-requested spec so a tag/version pick\n // sticks across reloads. Fall back to the bare key for legacy entries\n // (pre-spec) and for entries that never had a tag.\n const existingMeta = this.#storage.get(packageName);\n const specForReload = existingMeta?.spec ?? packageName;\n console.debug(\n `[Connect][PackageManager] Rehydrating \"${packageName}\" via spec \"${specForReload}\"`,\n );\n const result = await this.addPackage(specForReload);\n // Previously-installed package that no longer resolves (version\n // withdrawn from npm, registry moved, etc.) would otherwise\n // 404-toast on every boot forever. Drop it from persistent storage\n // so the failure is one-shot instead of sticky.\n if (result.type === \"error\") {\n this.#storage.delete(packageName);\n }\n }\n }\n\n addLocalPackage(\n name: string,\n loadedPackage: DocumentModelLib<any>,\n version?: string,\n loadRoutes?: PackageRoutesLoader,\n ) {\n this.#localPackageNames.add(name);\n this.#registerPackage({\n name,\n importUrl: null,\n stylesheetUrl: null,\n loadedPackage,\n version,\n loadRoutes,\n });\n }\n\n updateLocalPackage(pkg: DocumentModelLib<any>, version?: string) {\n console.debug(\"Updating local package:\", pkg);\n this.#localPackage = pkg;\n this.#registerPackage({\n name: LOCAL_PACKAGE_NAME,\n stylesheetUrl: null,\n importUrl: null,\n loadedPackage: pkg,\n });\n if (version) {\n this.#localPackageVersion = version;\n this.#notifyPackagesChanged();\n return;\n }\n fetchPackageJsonVersion(\"/package.json\")\n .then((fetchedVersion) => {\n this.#localPackageVersion = fetchedVersion;\n if (fetchedVersion) this.#notifyPackagesChanged();\n })\n .catch(() => {});\n }\n\n get packages() {\n return this.#packagesMemo;\n }\n\n get localPackage(): DocumentModelLib<any> | undefined {\n return this.#localPackage;\n }\n\n get cdnUrl(): string | null {\n return this.#cdnUrl;\n }\n\n getPackageSource(packageName: string) {\n // check vs packages registered as local (Common, Vetra, bundled packages...)\n if (this.#localPackageNames.has(packageName)) {\n return \"common\";\n }\n // check if the package has the same name as the local project\n if (packageName === this.#localPackage?.manifest.name) return \"project\";\n const packageMeta = this.#storage.get(packageName);\n // if meta does not exist the package is not installed\n if (!packageMeta) return null;\n // if imported from node_modules then the package is installed locally\n if (packageMeta.importUrl === `/node_modules/${packageName}`)\n return \"local-install\";\n // all other import urls point to a registry\n return \"registry-install\";\n }\n\n /**\n * Return the registry-installed packages keyed by their storage name (which\n * is the registry spec, e.g. \"@powerhousedao/clint-common\"), with the\n * installed version when known. Excludes bundled (common) packages, the\n * local project package, and packages resolved out of `/node_modules/`.\n */\n getRegistryPackages(): { name: string; version: string | undefined }[] {\n const out: { name: string; version: string | undefined }[] = [];\n for (const [name, meta] of this.#storage) {\n if (this.#localPackageNames.has(name)) continue;\n if (name === LOCAL_PACKAGE_NAME) continue;\n if (meta.importUrl === `/node_modules/${name}`) continue;\n out.push({ name, version: meta.version });\n }\n return out;\n }\n\n getPackageVersion(packageName: string): string | undefined {\n if (packageName === this.#localPackage?.manifest.name) {\n return this.#localPackageVersion;\n }\n return this.#storage.get(packageName)?.version;\n }\n\n /**\n * The spec the user requested when this package was installed (e.g.\n * `name@dev` or `name@6.2.1`). Undefined for bare-name installs, legacy\n * entries, and local packages — the Package Manager treats that as the\n * `latest` stream when picking update targets.\n */\n getPackageSpec(packageName: string): string | undefined {\n return this.#storage.get(packageName)?.spec;\n }\n\n async addPackage(packageSpec: string): Promise<PackageManagerInstallResult> {\n // `packageSpec` may include a `@tag` / `@version` suffix (e.g. user picked\n // a specific version in the package manager UI, or re-hydrated on reload\n // from the persisted spec). We always register/look up by the bare name so\n // status tracking, version lookups, and uninstall all go through a single\n // canonical key. The spec itself is kept on the meta so reloads re-fetch\n // the same tag.\n const bareName = parseBareName(packageSpec);\n const hasTagOrVersion = bareName !== packageSpec;\n console.debug(\n `[Connect][PackageManager] addPackage spec=\"${packageSpec}\" bareName=\"${bareName}\"`,\n );\n\n const existingPackage = this.#packages.get(bareName);\n if (existingPackage) {\n const requestedVersion = hasTagOrVersion\n ? packageSpec.slice(bareName.length + 1)\n : undefined;\n const currentVersion = this.#storage.get(bareName)?.version;\n const isLocal = this.#localPackageNames.has(bareName);\n const sameVersion =\n !requestedVersion ||\n !currentVersion ||\n requestedVersion === currentVersion;\n if (isLocal || sameVersion) {\n console.debug(\n `[Connect][PackageManager] \"${bareName}\" already loaded; skipping re-fetch`,\n );\n return {\n type: \"success\",\n package: existingPackage,\n };\n }\n console.debug(\n `[Connect][PackageManager] \"${bareName}\" version bump ${currentVersion} → ${requestedVersion}; refetching`,\n );\n }\n try {\n const packageWithMeta = await this.#loadPackage(packageSpec);\n // `#loadPackage*` set `name` to whatever spec it built the URL from.\n // Canonicalize to the bare name for the map/storage keys, and stash the\n // original spec separately so reloads re-use it.\n packageWithMeta.name = bareName;\n if (hasTagOrVersion) {\n packageWithMeta.spec = packageSpec;\n }\n // Swap stylesheets only once the new package is in hand. If `#loadPackage`\n // throws above, the old stylesheet stays mounted and the UI keeps\n // rendering the previous version instead of unstyled markup.\n if (existingPackage) {\n this.#unmountStylesheet(bareName);\n }\n this.#registerPackage(packageWithMeta);\n\n return {\n type: \"success\",\n package: packageWithMeta.loadedPackage,\n };\n } catch (error) {\n const normalized =\n error instanceof Error ? error : new Error(String(error));\n console.error(\n `[Connect][PackageManager] Failed to install package \"${packageSpec}\": ${normalized.message}`,\n normalized,\n );\n return {\n type: \"error\",\n error: normalized,\n };\n }\n }\n\n async addPackages(packageNames: string[]) {\n const results: PackageManagerInstallResult[] = [];\n for (const packageName of packageNames) {\n const result = await this.addPackage(packageName);\n results.push(result);\n }\n return results;\n }\n\n removePackage(name: string) {\n this.#syncRoutes(name, undefined);\n this.#packages.delete(name);\n this.#storage.delete(name);\n this.#unmountStylesheet(name);\n this.#notifyPackagesChanged();\n }\n\n subscribe(handler: IPackagesListener): IPackageListerUnsubscribe {\n this.#subscribers.add(handler);\n return () => {\n this.#subscribers.delete(handler);\n };\n }\n\n load(documentType: string): Promise<DocumentModelModule<any>> {\n const documentModelModule = Array.from(\n this.#packages.values().flatMap((p) => p.documentModels),\n ).find((m) => m.documentModel.global.id === documentType);\n\n if (documentModelModule) return Promise.resolve(documentModelModule);\n return Promise.reject(new Error(\"Model not available\"));\n }\n\n async #loadPackageFromNodeModules(name: string): Promise<PackageWithMeta> {\n const importUrl = `/node_modules/${name}/browser/index.js`;\n const stylesheetUrl = `/node_modules/${name}/style.css`;\n\n const packageWithMeta = await this.#importPackage({\n name,\n importUrl,\n stylesheetUrl,\n });\n packageWithMeta.version = await fetchPackageJsonVersion(\n `/node_modules/${name}/package.json`,\n );\n\n return packageWithMeta;\n }\n\n async #loadPackageFromRegistry(name: string): Promise<PackageWithMeta> {\n const importUrl = `${this.#cdnUrl}/${name}/browser/index.js`;\n const stylesheetUrl = `${this.#cdnUrl}/${name}/style.css`;\n const packageWithMeta = await this.#importPackage({\n name,\n importUrl,\n stylesheetUrl,\n });\n const pkgJson = await fetchPackageJson(\n `${this.#cdnUrl}/${name}/package.json`,\n );\n packageWithMeta.version = pkgJson?.version;\n\n // Non-blocking warning: a package that pins a shared dep at a version\n // the host's vendor was built without still installs, but the host's\n // copy is what runs — surface the mismatch before it surprises the\n // user at runtime.\n const warnings = sharedDepMismatchWarnings(\n pkgJson,\n (await getSharedDeps())?.versions,\n );\n if (warnings.length > 0) {\n console.error(\n `[package-manager] shared-deps mismatch for ${name}:\\n` +\n warnings.join(\"\\n\"),\n );\n }\n\n return packageWithMeta;\n }\n\n async #importPackage(packageMeta: PackageMeta): Promise<PackageWithMeta> {\n const { name, importUrl, stylesheetUrl } = packageMeta;\n if (!importUrl) {\n throw new Error(`Import url not defined for package \"${name}\".`);\n }\n\n const loadedPackage = (await import(\n /* @vite-ignore */ importUrl\n )) as DocumentModelLib<any>;\n // Beside the package's entry: browser/connect-routes.js.\n const routesUrl = importUrl.replace(/index\\.js$/, \"connect-routes.js\");\n\n return {\n name,\n loadedPackage,\n importUrl,\n stylesheetUrl,\n loadRoutes: () => import(/* @vite-ignore */ routesUrl),\n };\n }\n\n async #loadPackage(packageName: string): Promise<PackageWithMeta> {\n if (this.#localPackageNames.has(packageName)) {\n throw new Error(\n `Package \"${packageName}\" is a local package and cannot be loaded dynamically.`,\n );\n }\n\n // only attemp to load from node_modules in dev mode\n if (!import.meta.env.PROD) {\n try {\n const packageWithMeta =\n await this.#loadPackageFromNodeModules(packageName);\n return packageWithMeta;\n } catch (error) {\n console.warn(\n `Failed to load package \"${packageName}\" from node_modules:`,\n error,\n );\n }\n }\n\n if (!this.registryUrl) {\n throw new Error(\"Registry url not defined.\");\n }\n\n return await this.#loadPackageFromRegistry(packageName);\n }\n\n /** Replaces `name`'s offered routes with `pkg`'s; the project's own package\n * is left out, as its host build already has its routes. */\n #syncRoutes(\n name: string,\n pkg: DocumentModelLib<any> | undefined,\n loadRoutes?: PackageRoutesLoader,\n ) {\n this.#routes.get(name)?.();\n this.#routes.delete(name);\n const offers = pkg?.manifest.connectRoutes && loadRoutes;\n if (!offers || name === LOCAL_PACKAGE_NAME) return;\n // A replacement before the routes load cancels them.\n let cancelled = false;\n this.#routes.set(name, () => {\n cancelled = true;\n });\n // Unknown paths wait for these routes before showing not found.\n const release = holdConnectRoutes();\n loadRoutes()\n .then(({ connectRoutes }) => {\n if (!cancelled) {\n this.#routes.set(name, registerPackageRoutes(connectRoutes));\n }\n })\n .catch((error: unknown) => {\n console.error(\n `[package-manager] ${name}'s routes failed to load:`,\n error,\n );\n })\n .finally(release);\n }\n\n #registerPackage(packageWithMeta: PackageWithMeta) {\n const { name, loadedPackage, importUrl, stylesheetUrl, version, spec } =\n packageWithMeta;\n\n if (stylesheetUrl !== null) {\n this.#mountStylesheet(name, stylesheetUrl);\n }\n this.#syncRoutes(name, loadedPackage, packageWithMeta.loadRoutes);\n this.#packages.set(name, loadedPackage);\n this.#storage.set(name, {\n name,\n importUrl,\n stylesheetUrl,\n version,\n ...(spec ? { spec } : {}),\n });\n console.debug(\n `[Connect][PackageManager] Registered \"${name}\" (version=${version ?? \"?\"}, spec=${spec ?? \"—\"})`,\n );\n\n this.#notifyPackagesChanged();\n }\n\n #mountStylesheet(name: string, href: string) {\n const existing = this.#stylesheets.get(name);\n if (existing) return existing;\n\n declareExternalPackagesLayer();\n const style = document.createElement(\"style\");\n style.textContent = `@import url(\"${href}\") layer(external-packages);`;\n document.head.appendChild(style);\n\n this.#stylesheets.set(name, style);\n }\n\n #unmountStylesheet(name: string): void {\n const style = this.#stylesheets.get(name);\n if (!style) return;\n\n style.remove();\n this.#stylesheets.delete(name);\n }\n\n #notifyPackagesChanged() {\n this.#packagesMemo = Array.from(this.#packages.values());\n const packages = this.packages;\n this.#subscribers.forEach((handler) => {\n handler({ packages });\n });\n this.#schedulePwaSync();\n }\n\n /**\n * Debounced mirror of every loaded package's PWA fragment into IndexedDB, so\n * the service worker can serve a web-app manifest that reflects packages\n * installed AT RUNTIME (a SW can't read localStorage, where the package list\n * lives). Debounced because `init()` rehydrates many packages in a burst;\n * coalescing collapses that into a single write.\n */\n #schedulePwaSync() {\n if (typeof indexedDB === \"undefined\") return;\n clearTimeout(this.#pwaSyncTimer);\n this.#pwaSyncTimer = setTimeout(() => {\n void this.#syncPwaFragments();\n }, 50);\n }\n\n async #syncPwaFragments() {\n const contributions: PwaContribution[] = [];\n for (const [name, loadedPackage] of this.#packages) {\n const manifest = loadedPackage.manifest;\n let config: PHConnectPwa = {};\n if (manifest.pwa) {\n // Third-party package code must not inject arbitrary manifest fields the\n // SW will serve — validate strictly and skip (with a warning) on failure.\n const parsed = PwaConfigSchema.safeParse(manifest.pwa);\n if (parsed.success) {\n // A package's assets live at its base (CDN for registry installs);\n // make relative icon srcs absolute so the served manifest resolves.\n const importUrl = this.#storage.get(name)?.importUrl ?? null;\n const baseUrl = importUrl\n ? importUrl.replace(/browser\\/index\\.js$/, \"\")\n : null;\n config = resolveFragmentAssetUrls(parsed.data, baseUrl);\n } else {\n console.warn(\n `[Connect][PWA] \"${name}\" ships an invalid pwa fragment; skipped.`,\n parsed.error,\n );\n }\n }\n // `categories` is derived from the manifest's `category` field (not\n // authored under `pwa`); it unions into the SW-served manifest so a\n // runtime-installed package's category shows up like a build-time one.\n config = withInferredCategory(config, manifest.category);\n if (Object.keys(config).length === 0) continue;\n contributions.push({ source: name, config });\n }\n // Fold in load order (base-first ordering is preserved so a package cannot\n // hijack the built-in .phd/.phdm handler at merge time either).\n const merged = mergePwaConfig(contributions);\n // Most package operations don't touch PWA config; skip the write + manifest\n // re-attach (which forces a redundant manifest re-fetch) when unchanged.\n const mergedJson = JSON.stringify(merged);\n if (mergedJson === this.#lastSyncedFragmentJson) return;\n try {\n await writeMergedPwaFragment(merged);\n } catch (error) {\n // Leave #lastSyncedFragmentJson unset so a later sync retries the write.\n console.debug(\n \"[Connect][PWA] fragment mirror to IndexedDB failed:\",\n error,\n );\n return;\n }\n this.#lastSyncedFragmentJson = mergedJson;\n // The SW serves the manifest fresh from IndexedDB, but the browser only\n // parsed <link rel=\"manifest\"> at page load — re-attach it so it\n // re-consumes the now-updated manifest without a manual reload. (Kept out\n // of the write's try/catch so a DOM error isn't mislabeled as an IDB\n // failure; refreshPwaManifestLink is itself non-throwing.)\n refreshPwaManifestLink();\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;AAKA,SAAS,qBAAyC;CAChD,OAAO,OAAO,+BAA+B,cACzC,6BACA,KAAA;AACN;;AAGA,SAAgB,oBACd,aACA,QAA4B,mBAAmB,GACvC;CACR,OAAO,QACH,sBAAsB,OAAO,WAAW,IACxC,GAAG,YAAY;AACrB;;;;;;;;;;AAgBA,SAAgB,uBACd,YACA,aACwB;CAGxB,MAAM,SACH,WAAuC,UAAU,UAClD;CACF,OAAO,OAAO,YACZ,OAAO,QAAQ,UAA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D,KAAK,iBAAiB;CACxB;;;;;;;;CASA,mBAAmB;EACjB,IAAI,OAAO,cAAc,aAAa;EACtC,aAAa,KAAK,aAAa;EAC/B,KAAK,gBAAgB,iBAAiB;GACpC,KAAU,kBAAkB;EAC9B,GAAG,EAAE;CACP;CAEA,MAAM,oBAAoB;EACxB,MAAM,gBAAmC,CAAC;EAC1C,KAAK,MAAM,CAAC,MAAM,kBAAkB,KAAK,WAAW;GAClD,MAAM,WAAW,cAAc;GAC/B,IAAI,SAAuB,CAAC;GAC5B,IAAI,SAAS,KAAK;IAGhB,MAAM,SAAS,gBAAgB,UAAU,SAAS,GAAG;IACrD,IAAI,OAAO,SAAS;KAGlB,MAAM,YAAY,KAAK,SAAS,IAAI,IAAI,CAAC,EAAE,aAAa;KACxD,MAAM,UAAU,YACZ,UAAU,QAAQ,uBAAuB,EAAE,IAC3C;KACJ,SAAS,yBAAyB,OAAO,MAAM,OAAO;IACxD,OACE,QAAQ,KACN,mBAAmB,KAAK,4CACxB,OAAO,KACT;GAEJ;GAIA,SAAS,qBAAqB,QAAQ,SAAS,QAAQ;GACvD,IAAI,OAAO,KAAK,MAAM,CAAC,CAAC,WAAW,GAAG;GACtC,cAAc,KAAK;IAAE,QAAQ;IAAM;GAAO,CAAC;EAC7C;EAGA,MAAM,SAAS,eAAe,aAAa;EAG3C,MAAM,aAAa,KAAK,UAAU,MAAM;EACxC,IAAI,eAAe,KAAK,yBAAyB;EACjD,IAAI;GACF,MAAM,uBAAuB,MAAM;EACrC,SAAS,OAAO;GAEd,QAAQ,MACN,uDACA,KACF;GACA;EACF;EACA,KAAK,0BAA0B;EAM/B,uBAAuB;CACzB;AACF","debug_id":"c0da8d5a-fcd4-523d-b4d6-7f40fbfd24b7"}
|
|
1
|
+
{"version":3,"file":"package-manager-dfP4R5L3.js","sources":["../src/shared-deps.ts","../src/utils/pwa-idb.ts","../src/package-manager.ts"],"sourcesContent":["import { resolveDynamicBaseUrl } from \"@powerhousedao/shared/connect\";\n\n// Set by `ph connect build`: the content-hashed shared-deps module URL.\ndeclare const PH_CONNECT_SHARED_DEPS_URL: string | undefined;\n\nfunction builtSharedDepsUrl(): string | undefined {\n return typeof PH_CONNECT_SHARED_DEPS_URL !== \"undefined\"\n ? PH_CONNECT_SHARED_DEPS_URL\n : undefined;\n}\n\n/** The shared-deps module URL: this build's hashed copy, else the stable dev path. */\nexport function sharedDepsModuleUrl(\n runtimeBase: string,\n built: string | undefined = builtSharedDepsUrl(),\n): string {\n return built\n ? resolveDynamicBaseUrl(built, runtimeBase)\n : `${runtimeBase}__vendor__/shared-deps.js`;\n}\n\nexport type SharedDeps = {\n imports: Record<string, string>;\n versions: Record<string, string>;\n};\n\n/**\n * Resolve the vendor's import-map values to absolute URLs: the\n * dynamic-base placeholder (present in dynamic-base builds) is replaced\n * with the runtime base — which `import.meta.env.BASE_URL` already is,\n * since the dynamic-base plugin rewrites it to the resolved base — and\n * the result is made absolute against the page origin. Absolute URLs are\n * what the worker needs: its imports have no document context, so\n * relative or placeholder-based values would not resolve there.\n */\nexport function normalizeVendorImports(\n rawImports: Record<string, string>,\n runtimeBase: string,\n): Record<string, string> {\n // `location` is a browser global; the fallback keeps the helper usable\n // from node-based tests, where no origin exists.\n const origin =\n (globalThis as { location?: Location }).location?.origin ??\n \"http://localhost\";\n return Object.fromEntries(\n Object.entries(rawImports).map(([spec, value]) => [\n spec,\n new URL(resolveDynamicBaseUrl(value, runtimeBase), origin).href,\n ]),\n );\n}\n\nlet cached: Promise<SharedDeps | null> | null = null;\n\n/**\n * The production vendor's shared-deps table: import-map entries for the\n * shared dependency set plus the resolved version of every shared package\n * in this build. Fails soft (`null`) when the vendor is not present (dev,\n * or a `PH_CONNECT_VENDOR=0` build) — callers treat that as \"no sharing\".\n * The promise is cached: the vendor table is immutable per build.\n */\nexport function getSharedDeps(): Promise<SharedDeps | null> {\n cached ??= (async () => {\n try {\n const mod = (await import(\n /* @vite-ignore */ sharedDepsModuleUrl(import.meta.env.BASE_URL)\n )) as {\n imports: Record<string, string>;\n versions: Record<string, string>;\n };\n return {\n imports: normalizeVendorImports(mod.imports, import.meta.env.BASE_URL),\n versions: mod.versions,\n };\n } catch {\n return null;\n }\n })();\n return cached;\n}\n","import {\n PWA_IDB_KEY,\n PWA_IDB_NAME,\n PWA_IDB_STORE,\n PWA_IDB_VERSION,\n type PHConnectPwa,\n type PHConnectPwaIcon,\n} from \"@powerhousedao/shared/connect\";\n\n// The page-owned mirror of the effective PWA fragment contributed by the\n// currently-installed packages. The service worker reads this (read-only) to\n// serve a live web-app manifest — a SW cannot reach localStorage (where the\n// package list lives), so BrowserPackageManager writes the merged fragment\n// here on every package change. The db/store/key/version constants are the\n// SHARED source of truth in @powerhousedao/shared/connect, imported by both\n// this writer and the SW reader so the two cannot desync.\n\nexport type PwaFragmentRecord = {\n version: 1;\n fragment: PHConnectPwa;\n updatedAt: number;\n};\n\n// Self-contained IDB open (not reusing pglite-idb) so this module — and its\n// pure `resolveFragmentAssetUrls` — carries no dependency on connect.config,\n// keeping it importable in isolation.\nfunction openPwaIdb(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const req = indexedDB.open(PWA_IDB_NAME, PWA_IDB_VERSION);\n req.onupgradeneeded = () => {\n if (!req.result.objectStoreNames.contains(PWA_IDB_STORE)) {\n req.result.createObjectStore(PWA_IDB_STORE);\n }\n };\n req.onerror = () => reject(req.error ?? new Error(\"ph-pwa open failed\"));\n req.onblocked = () => reject(new Error(\"ph-pwa open blocked\"));\n req.onsuccess = () => resolve(req.result);\n });\n}\n\n/** Write (replace) the single merged fragment record. Best-effort: a failure to\n * mirror the manifest must never break package installation, so callers ignore\n * rejections. No-op when IndexedDB is unavailable (SSR/tests). */\nexport async function writeMergedPwaFragment(\n fragment: PHConnectPwa,\n): Promise<void> {\n if (typeof indexedDB === \"undefined\") return;\n const db = await openPwaIdb();\n try {\n await new Promise<void>((resolve, reject) => {\n const tx = db.transaction(PWA_IDB_STORE, \"readwrite\");\n tx.oncomplete = () => resolve();\n tx.onerror = () =>\n reject(tx.error ?? new Error(\"PWA fragment write failed\"));\n tx.objectStore(PWA_IDB_STORE).put(\n {\n version: 1,\n fragment,\n updatedAt: Date.now(),\n } satisfies PwaFragmentRecord,\n PWA_IDB_KEY,\n );\n });\n } finally {\n db.close();\n }\n}\n\n/** Resolve `src` against the package `baseUrl`, absolute srcs passing through.\n * `baseUrl` may itself be relative (e.g. a same-origin-proxied registry, or the\n * dev `/node_modules/…` path), so it is first made absolute against the app\n * origin — `new URL(src, relativeBase)` would otherwise throw and silently\n * leave the src unresolved. A malformed src is left untouched. */\nfunction toAbsoluteAssetUrl(src: string, baseUrl: string): string {\n try {\n const origin =\n typeof location !== \"undefined\" ? location.href : \"http://localhost/\";\n return new URL(src, new URL(baseUrl, origin)).toString();\n } catch {\n return src;\n }\n}\n\nfunction resolveIconSrc(\n icon: PHConnectPwaIcon,\n baseUrl: string,\n): PHConnectPwaIcon {\n return { ...icon, src: toAbsoluteAssetUrl(icon.src, baseUrl) };\n}\n\n/**\n * Rewrite a package fragment's relative asset srcs (manifest icons and\n * file-handler icons) to absolute URLs against the package's base — a runtime\n * package's assets live on the registry CDN, not the app origin, so the served\n * manifest must point there. `baseUrl` null (a local/bundled package whose\n * assets are app-origin-relative) leaves srcs untouched.\n */\nexport function resolveFragmentAssetUrls(\n config: PHConnectPwa,\n baseUrl: string | null,\n): PHConnectPwa {\n if (!baseUrl || !config.manifest) return config;\n const m = config.manifest;\n const resolveIcons = (icons?: PHConnectPwaIcon[]) =>\n icons?.map((icon) => resolveIconSrc(icon, baseUrl));\n return {\n ...config,\n manifest: {\n ...m,\n icons: resolveIcons(m.icons),\n file_handlers: m.file_handlers?.map((handler) => ({\n ...handler,\n icons: resolveIcons(handler.icons),\n })),\n },\n };\n}\n","import type { PackageRoute } from \"@powerhousedao/connect-core/router\";\nimport {\n holdConnectRoutes,\n registerPackageRoutes,\n} from \"@powerhousedao/connect-core/router\";\nimport * as common from \"@powerhousedao/powerhouse-vetra-packages\";\nimport type {\n IPackagesListener,\n PackageManagerInstallResult,\n} from \"@powerhousedao/reactor-browser\";\nimport {\n BrowserLocalStorage,\n type IPackageListerUnsubscribe,\n type IPackageManager,\n} from \"@powerhousedao/reactor-browser\";\nimport {\n checkSharedDeps,\n CONNECT_LAYER_ORDER,\n formatSharedDepWarnings,\n mergePwaConfig,\n type PHConnectPwa,\n type PwaContribution,\n withInferredCategory,\n} from \"@powerhousedao/shared/connect\";\nimport {\n type DocumentModelLib,\n type DocumentModelModule,\n PwaConfigSchema,\n} from \"@powerhousedao/shared/document-model\";\nimport { toCdnUrl } from \"@powerhousedao/shared/registry/urls\";\nimport { getSharedDeps } from \"./shared-deps.js\";\nimport {\n resolveFragmentAssetUrls,\n writeMergedPwaFragment,\n} from \"./utils/pwa-idb.js\";\nimport { refreshPwaManifestLink } from \"./utils/pwa-manifest-link.js\";\n\ntype PackageMeta = {\n name: string;\n importUrl: string | null;\n stylesheetUrl: string | null;\n version?: string;\n /**\n * Full spec the user asked for (e.g. `@scope/pkg@2.0.0-beta.2`). Kept so a\n * reload re-installs exactly the tag/version originally picked rather than\n * sliding to `latest`. Absent for legacy entries and local packages.\n */\n spec?: string;\n};\n\n/**\n * Strip any `@tag` / `@version` suffix from a package spec, returning the bare\n * package name. Mirrors `parsePackageSpec` on the UI side.\n */\nfunction parseBareName(spec: string): string {\n const trimmed = spec.trim();\n const at = trimmed.startsWith(\"@\")\n ? trimmed.lastIndexOf(\"@\")\n : trimmed.indexOf(\"@\");\n return at > 0 ? trimmed.slice(0, at) : trimmed;\n}\n\n/** Loads the routes a package offers (its `./connect-routes`). */\nexport type PackageRoutesLoader = () => Promise<{\n connectRoutes: readonly PackageRoute[];\n}>;\n\ntype PackageWithMeta = PackageMeta & {\n loadedPackage: DocumentModelLib<any>;\n spec?: string;\n loadRoutes?: PackageRoutesLoader;\n};\n\ntype FetchedPackageJson = {\n version?: string;\n dependencies?: Record<string, unknown>;\n peerDependencies?: Record<string, unknown>;\n};\n\nasync function fetchPackageJson(\n baseUrl: string,\n): Promise<FetchedPackageJson | null> {\n try {\n const res = await fetch(baseUrl);\n if (!res.ok) return null;\n const pkg = (await res.json()) as {\n version?: unknown;\n dependencies?: Record<string, unknown>;\n peerDependencies?: Record<string, unknown>;\n };\n return {\n version: typeof pkg.version === \"string\" ? pkg.version : undefined,\n dependencies: pkg.dependencies,\n peerDependencies: pkg.peerDependencies,\n };\n } catch {\n return null;\n }\n}\n\nasync function fetchPackageJsonVersion(\n baseUrl: string,\n): Promise<string | undefined> {\n return (await fetchPackageJson(baseUrl))?.version;\n}\n\n/**\n * Human-readable warnings for shared-dep mismatches between a package's npm\n * `package.json` (as served by the CDN) and the host's shared-deps version\n * table. Empty when either side is unavailable — a dev / vendor-off host has\n * no table to compare against, and a missing package.json means the check\n * can't run. Used by both the install flow and the package-manager UI.\n */\nexport function sharedDepMismatchWarnings(\n pkgJson: FetchedPackageJson | null,\n hostVersions: Record<string, string> | null | undefined,\n): string[] {\n if (!pkgJson || !hostVersions) return [];\n return formatSharedDepWarnings(checkSharedDeps(pkgJson, hostVersions));\n}\n\n// The bundled packages' versions, inlined by bundled-package-versions.ts.\ndeclare const PH_COMMON_PACKAGE_VERSION: string;\ndeclare const PH_VETRA_PACKAGE_VERSION: string;\ndeclare const PH_WORKFLOW_PACKAGE_VERSION: string;\n\nconst LOCAL_PACKAGE_NAME = \"Local\" as const;\n\n// Package CSS goes in external-packages: above Connect's reset so it can style\n// its editors, below Connect's utilities so it can't override them.\nexport const LAYER_ORDER = CONNECT_LAYER_ORDER;\nconst LAYER_ORDER_ATTR = \"data-ph-layer-order\";\n\n// Layer order is set by the first declaration in the document, and a project's\n// style.css declares Tailwind's layers first, so this goes first in <head>.\n\nexport function declareExternalPackagesLayer(): void {\n if (document.head.querySelector(`style[${LAYER_ORDER_ATTR}]`)) return;\n const order = document.createElement(\"style\");\n order.setAttribute(LAYER_ORDER_ATTR, \"\");\n order.textContent = LAYER_ORDER;\n document.head.prepend(order);\n}\n\nexport class BrowserPackageManager implements IPackageManager {\n registryUrl: string | null;\n #storage: BrowserLocalStorage<PackageMeta>;\n #packages: Map<string, DocumentModelLib<any>> = new Map();\n #subscribers = new Set<IPackagesListener>();\n #packagesMemo: DocumentModelLib<any>[] = [];\n #stylesheets: Map<string, HTMLStyleElement> = new Map();\n /** Takes each package's offered routes out of the router. */\n #routes: Map<string, () => void> = new Map();\n #localPackage: DocumentModelLib<any> | undefined;\n\n #cdnUrl: string | null;\n #localPackageVersion: string | undefined;\n #localPackageNames: Set<string> = new Set([LOCAL_PACKAGE_NAME]);\n #pwaSyncTimer: ReturnType<typeof setTimeout> | undefined;\n /** Serialized last-mirrored PWA fragment; lets a sync skip the IndexedDB\n * write + manifest re-attach when nothing PWA-relevant changed. */\n #lastSyncedFragmentJson: string | undefined;\n\n constructor(namespace: string, registryUrl: string | null) {\n this.#storage = new BrowserLocalStorage<PackageMeta>(\n namespace + \":PH_PACKAGES\",\n );\n this.registryUrl = registryUrl;\n this.#cdnUrl = registryUrl !== null ? toCdnUrl(registryUrl) : null;\n }\n\n async init(\n localPackage?: DocumentModelLib<any>,\n localPackageVersion?: string,\n studioMode?: boolean,\n workflowsEnabled?: boolean,\n genericChrome = true,\n ) {\n // Common's editors (drive explorer, document model editor) are the generic\n // chrome's; without it, core gets only common's document models.\n this.addLocalPackage(\n common.manifest.name,\n genericChrome ? common : { ...common, editors: [] },\n PH_COMMON_PACKAGE_VERSION,\n );\n // Vetra is builder-only and not CDN-loadable; lazy-load it (code-split\n // chunk, never fetched in production) only in studio mode.\n if (studioMode) {\n const vetra = await import(\"@powerhousedao/vetra\");\n this.addLocalPackage(\n vetra.manifest.name,\n vetra,\n PH_VETRA_PACKAGE_VERSION,\n );\n }\n // Same shape for the workflow package, behind its own independent flag.\n // Only the package root: `./pieces` and `./reactor` are node-only.\n if (workflowsEnabled) {\n const workflow = await import(\"@powerhousedao/workflow\");\n this.addLocalPackage(\n workflow.manifest.name,\n workflow,\n PH_WORKFLOW_PACKAGE_VERSION,\n );\n }\n if (localPackage) {\n this.updateLocalPackage(localPackage, localPackageVersion);\n }\n for (const packageName of this.#storage.keys()) {\n // Re-hydrate with the originally-requested spec so a tag/version pick\n // sticks across reloads. Fall back to the bare key for legacy entries\n // (pre-spec) and for entries that never had a tag.\n const existingMeta = this.#storage.get(packageName);\n const specForReload = existingMeta?.spec ?? packageName;\n console.debug(\n `[Connect][PackageManager] Rehydrating \"${packageName}\" via spec \"${specForReload}\"`,\n );\n const result = await this.addPackage(specForReload);\n // Previously-installed package that no longer resolves (version\n // withdrawn from npm, registry moved, etc.) would otherwise\n // 404-toast on every boot forever. Drop it from persistent storage\n // so the failure is one-shot instead of sticky.\n if (result.type === \"error\") {\n this.#storage.delete(packageName);\n }\n }\n }\n\n addLocalPackage(\n name: string,\n loadedPackage: DocumentModelLib<any>,\n version?: string,\n loadRoutes?: PackageRoutesLoader,\n ) {\n this.#localPackageNames.add(name);\n this.#registerPackage({\n name,\n importUrl: null,\n stylesheetUrl: null,\n loadedPackage,\n version,\n loadRoutes,\n });\n }\n\n updateLocalPackage(pkg: DocumentModelLib<any>, version?: string) {\n console.debug(\"Updating local package:\", pkg);\n this.#localPackage = pkg;\n this.#registerPackage({\n name: LOCAL_PACKAGE_NAME,\n stylesheetUrl: null,\n importUrl: null,\n loadedPackage: pkg,\n });\n if (version) {\n this.#localPackageVersion = version;\n this.#notifyPackagesChanged();\n return;\n }\n fetchPackageJsonVersion(\"/package.json\")\n .then((fetchedVersion) => {\n this.#localPackageVersion = fetchedVersion;\n if (fetchedVersion) this.#notifyPackagesChanged();\n })\n .catch(() => {});\n }\n\n get packages() {\n return this.#packagesMemo;\n }\n\n get localPackage(): DocumentModelLib<any> | undefined {\n return this.#localPackage;\n }\n\n get cdnUrl(): string | null {\n return this.#cdnUrl;\n }\n\n getPackageSource(packageName: string) {\n // check vs packages registered as local (Common, Vetra, bundled packages...)\n if (this.#localPackageNames.has(packageName)) {\n return \"common\";\n }\n // check if the package has the same name as the local project\n if (packageName === this.#localPackage?.manifest.name) return \"project\";\n const packageMeta = this.#storage.get(packageName);\n // if meta does not exist the package is not installed\n if (!packageMeta) return null;\n // if imported from node_modules then the package is installed locally\n if (packageMeta.importUrl === `/node_modules/${packageName}`)\n return \"local-install\";\n // all other import urls point to a registry\n return \"registry-install\";\n }\n\n /**\n * Return the registry-installed packages keyed by their storage name (which\n * is the registry spec, e.g. \"@powerhousedao/clint-common\"), with the\n * installed version when known. Excludes bundled (common) packages, the\n * local project package, and packages resolved out of `/node_modules/`.\n */\n getRegistryPackages(): { name: string; version: string | undefined }[] {\n const out: { name: string; version: string | undefined }[] = [];\n for (const [name, meta] of this.#storage) {\n if (this.#localPackageNames.has(name)) continue;\n if (name === LOCAL_PACKAGE_NAME) continue;\n if (meta.importUrl === `/node_modules/${name}`) continue;\n out.push({ name, version: meta.version });\n }\n return out;\n }\n\n getPackageVersion(packageName: string): string | undefined {\n if (packageName === this.#localPackage?.manifest.name) {\n return this.#localPackageVersion;\n }\n return this.#storage.get(packageName)?.version;\n }\n\n /**\n * The spec the user requested when this package was installed (e.g.\n * `name@dev` or `name@6.2.1`). Undefined for bare-name installs, legacy\n * entries, and local packages — the Package Manager treats that as the\n * `latest` stream when picking update targets.\n */\n getPackageSpec(packageName: string): string | undefined {\n return this.#storage.get(packageName)?.spec;\n }\n\n async addPackage(packageSpec: string): Promise<PackageManagerInstallResult> {\n // `packageSpec` may include a `@tag` / `@version` suffix (e.g. user picked\n // a specific version in the package manager UI, or re-hydrated on reload\n // from the persisted spec). We always register/look up by the bare name so\n // status tracking, version lookups, and uninstall all go through a single\n // canonical key. The spec itself is kept on the meta so reloads re-fetch\n // the same tag.\n const bareName = parseBareName(packageSpec);\n const hasTagOrVersion = bareName !== packageSpec;\n console.debug(\n `[Connect][PackageManager] addPackage spec=\"${packageSpec}\" bareName=\"${bareName}\"`,\n );\n\n const existingPackage = this.#packages.get(bareName);\n if (existingPackage) {\n const requestedVersion = hasTagOrVersion\n ? packageSpec.slice(bareName.length + 1)\n : undefined;\n const currentVersion = this.#storage.get(bareName)?.version;\n const isLocal = this.#localPackageNames.has(bareName);\n const sameVersion =\n !requestedVersion ||\n !currentVersion ||\n requestedVersion === currentVersion;\n if (isLocal || sameVersion) {\n console.debug(\n `[Connect][PackageManager] \"${bareName}\" already loaded; skipping re-fetch`,\n );\n return {\n type: \"success\",\n package: existingPackage,\n };\n }\n console.debug(\n `[Connect][PackageManager] \"${bareName}\" version bump ${currentVersion} → ${requestedVersion}; refetching`,\n );\n }\n try {\n const packageWithMeta = await this.#loadPackage(packageSpec);\n // `#loadPackage*` set `name` to whatever spec it built the URL from.\n // Canonicalize to the bare name for the map/storage keys, and stash the\n // original spec separately so reloads re-use it.\n packageWithMeta.name = bareName;\n if (hasTagOrVersion) {\n packageWithMeta.spec = packageSpec;\n }\n // Swap stylesheets only once the new package is in hand. If `#loadPackage`\n // throws above, the old stylesheet stays mounted and the UI keeps\n // rendering the previous version instead of unstyled markup.\n if (existingPackage) {\n this.#unmountStylesheet(bareName);\n }\n this.#registerPackage(packageWithMeta);\n\n return {\n type: \"success\",\n package: packageWithMeta.loadedPackage,\n };\n } catch (error) {\n const normalized =\n error instanceof Error ? error : new Error(String(error));\n console.error(\n `[Connect][PackageManager] Failed to install package \"${packageSpec}\": ${normalized.message}`,\n normalized,\n );\n return {\n type: \"error\",\n error: normalized,\n };\n }\n }\n\n async addPackages(packageNames: string[]) {\n const results: PackageManagerInstallResult[] = [];\n for (const packageName of packageNames) {\n const result = await this.addPackage(packageName);\n results.push(result);\n }\n return results;\n }\n\n removePackage(name: string) {\n this.#syncRoutes(name, undefined);\n this.#packages.delete(name);\n this.#storage.delete(name);\n this.#unmountStylesheet(name);\n this.#notifyPackagesChanged();\n }\n\n subscribe(handler: IPackagesListener): IPackageListerUnsubscribe {\n this.#subscribers.add(handler);\n return () => {\n this.#subscribers.delete(handler);\n };\n }\n\n load(documentType: string): Promise<DocumentModelModule<any>> {\n const documentModelModule = Array.from(\n this.#packages.values().flatMap((p) => p.documentModels),\n ).find((m) => m.documentModel.global.id === documentType);\n\n if (documentModelModule) return Promise.resolve(documentModelModule);\n return Promise.reject(new Error(\"Model not available\"));\n }\n\n async #loadPackageFromNodeModules(name: string): Promise<PackageWithMeta> {\n // Installed under its bare name; the spec may carry a version or tag.\n const dir = `/node_modules/${parseBareName(name)}`;\n const importUrl = `${dir}/browser/index.js`;\n const stylesheetUrl = `${dir}/style.css`;\n\n const packageWithMeta = await this.#importPackage({\n name,\n importUrl,\n stylesheetUrl,\n });\n packageWithMeta.version = await fetchPackageJsonVersion(\n `${dir}/package.json`,\n );\n\n return packageWithMeta;\n }\n\n async #loadPackageFromRegistry(name: string): Promise<PackageWithMeta> {\n const importUrl = `${this.#cdnUrl}/${name}/browser/index.js`;\n const stylesheetUrl = `${this.#cdnUrl}/${name}/style.css`;\n const packageWithMeta = await this.#importPackage({\n name,\n importUrl,\n stylesheetUrl,\n });\n const pkgJson = await fetchPackageJson(\n `${this.#cdnUrl}/${name}/package.json`,\n );\n packageWithMeta.version = pkgJson?.version;\n\n // Non-blocking warning: a package that pins a shared dep at a version\n // the host's vendor was built without still installs, but the host's\n // copy is what runs — surface the mismatch before it surprises the\n // user at runtime.\n const warnings = sharedDepMismatchWarnings(\n pkgJson,\n (await getSharedDeps())?.versions,\n );\n if (warnings.length > 0) {\n console.error(\n `[package-manager] shared-deps mismatch for ${name}:\\n` +\n warnings.join(\"\\n\"),\n );\n }\n\n return packageWithMeta;\n }\n\n async #importPackage(packageMeta: PackageMeta): Promise<PackageWithMeta> {\n const { name, importUrl, stylesheetUrl } = packageMeta;\n if (!importUrl) {\n throw new Error(`Import url not defined for package \"${name}\".`);\n }\n\n const loadedPackage = (await import(\n /* @vite-ignore */ importUrl\n )) as DocumentModelLib<any>;\n // Beside the package's entry: browser/connect-routes.js.\n const routesUrl = importUrl.replace(/index\\.js$/, \"connect-routes.js\");\n\n return {\n name,\n loadedPackage,\n importUrl,\n stylesheetUrl,\n loadRoutes: () => import(/* @vite-ignore */ routesUrl),\n };\n }\n\n async #loadPackage(packageName: string): Promise<PackageWithMeta> {\n if (this.#localPackageNames.has(packageName)) {\n throw new Error(\n `Package \"${packageName}\" is a local package and cannot be loaded dynamically.`,\n );\n }\n\n // only attemp to load from node_modules in dev mode\n if (!import.meta.env.PROD) {\n try {\n const packageWithMeta =\n await this.#loadPackageFromNodeModules(packageName);\n return packageWithMeta;\n } catch (error) {\n // Expected for a package installed only in Connect, not the project.\n console.debug(\n `\"${packageName}\" isn't in node_modules; loading it from the registry.`,\n error,\n );\n }\n }\n\n if (!this.registryUrl) {\n throw new Error(\"Registry url not defined.\");\n }\n\n return await this.#loadPackageFromRegistry(packageName);\n }\n\n /** Replaces `name`'s offered routes with `pkg`'s; the project's own package\n * is left out, as its host build already has its routes. */\n #syncRoutes(\n name: string,\n pkg: DocumentModelLib<any> | undefined,\n loadRoutes?: PackageRoutesLoader,\n ) {\n this.#routes.get(name)?.();\n this.#routes.delete(name);\n const offers = pkg?.manifest.connectRoutes && loadRoutes;\n if (!offers || name === LOCAL_PACKAGE_NAME) return;\n // A replacement before the routes load cancels them.\n let cancelled = false;\n this.#routes.set(name, () => {\n cancelled = true;\n });\n // Unknown paths wait for these routes before showing not found.\n const release = holdConnectRoutes();\n loadRoutes()\n .then(({ connectRoutes }) => {\n if (!cancelled) {\n this.#routes.set(name, registerPackageRoutes(connectRoutes));\n }\n })\n .catch((error: unknown) => {\n console.error(\n `[package-manager] ${name}'s routes failed to load:`,\n error,\n );\n })\n .finally(release);\n }\n\n #registerPackage(packageWithMeta: PackageWithMeta) {\n const { name, loadedPackage, importUrl, stylesheetUrl, version, spec } =\n packageWithMeta;\n\n if (stylesheetUrl !== null) {\n this.#mountStylesheet(name, stylesheetUrl);\n }\n this.#syncRoutes(name, loadedPackage, packageWithMeta.loadRoutes);\n this.#packages.set(name, loadedPackage);\n this.#storage.set(name, {\n name,\n importUrl,\n stylesheetUrl,\n version,\n ...(spec ? { spec } : {}),\n });\n console.debug(\n `[Connect][PackageManager] Registered \"${name}\" (version=${version ?? \"?\"}, spec=${spec ?? \"—\"})`,\n );\n\n this.#notifyPackagesChanged();\n }\n\n #mountStylesheet(name: string, href: string) {\n const existing = this.#stylesheets.get(name);\n if (existing) return existing;\n\n declareExternalPackagesLayer();\n const style = document.createElement(\"style\");\n style.textContent = `@import url(\"${href}\") layer(external-packages);`;\n document.head.appendChild(style);\n\n this.#stylesheets.set(name, style);\n }\n\n #unmountStylesheet(name: string): void {\n const style = this.#stylesheets.get(name);\n if (!style) return;\n\n style.remove();\n this.#stylesheets.delete(name);\n }\n\n #notifyPackagesChanged() {\n this.#packagesMemo = Array.from(this.#packages.values());\n const packages = this.packages;\n this.#subscribers.forEach((handler) => {\n handler({ packages });\n });\n this.#schedulePwaSync();\n }\n\n /**\n * Debounced mirror of every loaded package's PWA fragment into IndexedDB, so\n * the service worker can serve a web-app manifest that reflects packages\n * installed AT RUNTIME (a SW can't read localStorage, where the package list\n * lives). Debounced because `init()` rehydrates many packages in a burst;\n * coalescing collapses that into a single write.\n */\n #schedulePwaSync() {\n if (typeof indexedDB === \"undefined\") return;\n clearTimeout(this.#pwaSyncTimer);\n this.#pwaSyncTimer = setTimeout(() => {\n void this.#syncPwaFragments();\n }, 50);\n }\n\n async #syncPwaFragments() {\n const contributions: PwaContribution[] = [];\n for (const [name, loadedPackage] of this.#packages) {\n const manifest = loadedPackage.manifest;\n let config: PHConnectPwa = {};\n if (manifest.pwa) {\n // Third-party package code must not inject arbitrary manifest fields the\n // SW will serve — validate strictly and skip (with a warning) on failure.\n const parsed = PwaConfigSchema.safeParse(manifest.pwa);\n if (parsed.success) {\n // A package's assets live at its base (CDN for registry installs);\n // make relative icon srcs absolute so the served manifest resolves.\n const importUrl = this.#storage.get(name)?.importUrl ?? null;\n const baseUrl = importUrl\n ? importUrl.replace(/browser\\/index\\.js$/, \"\")\n : null;\n config = resolveFragmentAssetUrls(parsed.data, baseUrl);\n } else {\n console.warn(\n `[Connect][PWA] \"${name}\" ships an invalid pwa fragment; skipped.`,\n parsed.error,\n );\n }\n }\n // `categories` is derived from the manifest's `category` field (not\n // authored under `pwa`); it unions into the SW-served manifest so a\n // runtime-installed package's category shows up like a build-time one.\n config = withInferredCategory(config, manifest.category);\n if (Object.keys(config).length === 0) continue;\n contributions.push({ source: name, config });\n }\n // Fold in load order (base-first ordering is preserved so a package cannot\n // hijack the built-in .phd/.phdm handler at merge time either).\n const merged = mergePwaConfig(contributions);\n // Most package operations don't touch PWA config; skip the write + manifest\n // re-attach (which forces a redundant manifest re-fetch) when unchanged.\n const mergedJson = JSON.stringify(merged);\n if (mergedJson === this.#lastSyncedFragmentJson) return;\n try {\n await writeMergedPwaFragment(merged);\n } catch (error) {\n // Leave #lastSyncedFragmentJson unset so a later sync retries the write.\n console.debug(\n \"[Connect][PWA] fragment mirror to IndexedDB failed:\",\n error,\n );\n return;\n }\n this.#lastSyncedFragmentJson = mergedJson;\n // The SW serves the manifest fresh from IndexedDB, but the browser only\n // parsed <link rel=\"manifest\"> at page load — re-attach it so it\n // re-consumes the now-updated manifest without a manual reload. (Kept out\n // of the write's try/catch so a DOM error isn't mislabeled as an IDB\n // failure; refreshPwaManifestLink is itself non-throwing.)\n refreshPwaManifestLink();\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;AAKA,SAAS,qBAAyC;CAChD,OAAO,OAAO,+BAA+B,cACzC,6BACA,KAAA;AACN;;AAGA,SAAgB,oBACd,aACA,QAA4B,mBAAmB,GACvC;CACR,OAAO,QACH,sBAAsB,OAAO,WAAW,IACxC,GAAG,YAAY;AACrB;;;;;;;;;;AAgBA,SAAgB,uBACd,YACA,aACwB;CAGxB,MAAM,SACH,WAAuC,UAAU,UAClD;CACF,OAAO,OAAO,YACZ,OAAO,QAAQ,UAAU,CAAC,CAAC,KAAK,CAAC,MAAM,WAAW,CAChD,MACA,IAAI,IAAI,sBAAsB,OAAO,WAAW,GAAG,MAAM,CAAC,CAAC,IAC7D,C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a,KAAK,aAAa;EAC/B,KAAK,gBAAgB,iBAAiB;GACpC,KAAU,kBAAkB;EAC9B,GAAG,EAAE;CACP;CAEA,MAAM,oBAAoB;EACxB,MAAM,gBAAmC,CAAC;EAC1C,KAAK,MAAM,CAAC,MAAM,kBAAkB,KAAK,WAAW;GAClD,MAAM,WAAW,cAAc;GAC/B,IAAI,SAAuB,CAAC;GAC5B,IAAI,SAAS,KAAK;IAGhB,MAAM,SAAS,gBAAgB,UAAU,SAAS,GAAG;IACrD,IAAI,OAAO,SAAS;KAGlB,MAAM,YAAY,KAAK,SAAS,IAAI,IAAI,CAAC,EAAE,aAAa;KACxD,MAAM,UAAU,YACZ,UAAU,QAAQ,uBAAuB,EAAE,IAC3C;KACJ,SAAS,yBAAyB,OAAO,MAAM,OAAO;IACxD,OACE,QAAQ,KACN,mBAAmB,KAAK,4CACxB,OAAO,KACT;GAEJ;GAIA,SAAS,qBAAqB,QAAQ,SAAS,QAAQ;GACvD,IAAI,OAAO,KAAK,MAAM,CAAC,CAAC,WAAW,GAAG;GACtC,cAAc,KAAK;IAAE,QAAQ;IAAM;GAAO,CAAC;EAC7C;EAGA,MAAM,SAAS,eAAe,aAAa;EAG3C,MAAM,aAAa,KAAK,UAAU,MAAM;EACxC,IAAI,eAAe,KAAK,yBAAyB;EACjD,IAAI;GACF,MAAM,uBAAuB,MAAM;EACrC,SAAS,OAAO;GAEd,QAAQ,MACN,uDACA,KACF;GACA;EACF;EACA,KAAK,0BAA0B;EAM/B,uBAAuB;CACzB;AACF","debug_id":"f4d144a4-4e49-5ec9-a19e-56fce38a29f8"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
3
|
-
import { h as REACTOR_PGLITE_NAME, u as invalidateReactorPgMajorCache } from "./connection-state-
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="852f8970-91f2-5f89-9c2b-e3a6a9074041")}catch(e){}}();
|
|
3
|
+
import { h as REACTOR_PGLITE_NAME, u as invalidateReactorPgMajorCache } from "./connection-state-Bwm9Agwy.js";
|
|
4
4
|
//#region src/utils/pglite-seed.ts
|
|
5
5
|
const PENDING_PG_SEED_KEY = "ph:pending-pg-seed";
|
|
6
6
|
/**
|
|
@@ -45,5 +45,5 @@ async function seedPendingPgVersion() {
|
|
|
45
45
|
//#endregion
|
|
46
46
|
export { seedPendingPgVersion as n, PENDING_PG_SEED_KEY as t };
|
|
47
47
|
|
|
48
|
-
//# sourceMappingURL=pglite-seed-
|
|
49
|
-
//# debugId=
|
|
48
|
+
//# sourceMappingURL=pglite-seed-QPbGbLB_.js.map
|
|
49
|
+
//# debugId=852f8970-91f2-5f89-9c2b-e3a6a9074041
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pglite-seed-
|
|
1
|
+
{"version":3,"file":"pglite-seed-QPbGbLB_.js","sources":["../src/utils/pglite-seed.ts"],"sourcesContent":["import { invalidateReactorPgMajorCache } from \"./pglite-runtime.js\";\nimport { REACTOR_PGLITE_NAME } from \"./storage-namespace.js\";\n\nexport const PENDING_PG_SEED_KEY = \"ph:pending-pg-seed\";\n\n/**\n * If the Debug Inspector requested a forced PG version reset, this runs\n * before the reactor is created on the subsequent page load: opens a fresh\n * PGlite of the requested major against the reactor data dir, lets `initdb`\n * populate `PG_VERSION`, then closes. The next step of app boot then\n * detects this fresh data dir and picks the matching runtime.\n */\nexport async function seedPendingPgVersion(): Promise<void> {\n const raw = localStorage.getItem(PENDING_PG_SEED_KEY);\n if (!raw) return;\n\n const major = parseInt(raw, 10);\n console.info(`[pglite-seed] Seeding fresh PG${major} data dir...`);\n\n try {\n if (major === 16) {\n const { PGlite } = await import(\"pglite-legacy-02\");\n const pg = new PGlite(`idb://${REACTOR_PGLITE_NAME}`);\n try {\n await pg.waitReady;\n } finally {\n await pg.close();\n }\n } else if (major === 17) {\n const { PGlite } = await import(\"@electric-sql/pglite\");\n const pg = new PGlite(`idb://${REACTOR_PGLITE_NAME}`);\n try {\n await pg.waitReady;\n } finally {\n await pg.close();\n }\n } else {\n console.warn(`[pglite-seed] Unsupported version ${raw}, skipping`);\n return;\n }\n console.info(`[pglite-seed] Seeded PG${major} data dir.`);\n } finally {\n localStorage.removeItem(PENDING_PG_SEED_KEY);\n invalidateReactorPgMajorCache();\n }\n}\n"],"names":[],"mappings":";;;;AAGA,MAAa,sBAAsB;;;;;;;;AASnC,eAAsB,uBAAsC;CAC1D,MAAM,MAAM,aAAa,QAAQ,mBAAmB;CACpD,IAAI,CAAC,KAAK;CAEV,MAAM,QAAQ,SAAS,KAAK,EAAE;CAC9B,QAAQ,KAAK,iCAAiC,MAAM,aAAa;CAEjE,IAAI;EACF,IAAI,UAAU,IAAI;GAChB,MAAM,EAAE,WAAW,MAAM,OAAO;GAChC,MAAM,KAAK,IAAI,OAAO,SAAS,qBAAqB;GACpD,IAAI;IACF,MAAM,GAAG;GACX,UAAU;IACR,MAAM,GAAG,MAAM;GACjB;EACF,OAAO,IAAI,UAAU,IAAI;GACvB,MAAM,EAAE,WAAW,MAAM,OAAO;GAChC,MAAM,KAAK,IAAI,OAAO,SAAS,qBAAqB;GACpD,IAAI;IACF,MAAM,GAAG;GACX,UAAU;IACR,MAAM,GAAG,MAAM;GACjB;EACF,OAAO;GACL,QAAQ,KAAK,qCAAqC,IAAI,WAAW;GACjE;EACF;EACA,QAAQ,KAAK,0BAA0B,MAAM,WAAW;CAC1D,UAAU;EACR,aAAa,WAAW,mBAAmB;EAC3C,8BAA8B;CAChC;AACF","debug_id":"852f8970-91f2-5f89-9c2b-e3a6a9074041"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="cc104551-d72f-51a7-8a6a-77c9eca12f77")}catch(e){}}();
|
|
3
3
|
import { a as genericConfigSchema, i as openPanelConfigSchema, n as vetraStudioConfigSchema, o as assistantConfigSchema, r as sentryConfigSchema, t as workflowsConnectConfigSchema } from "./workflows-C3qEvx1R.js";
|
|
4
4
|
import { DEFAULT_CONNECT_CONFIG } from "@powerhousedao/shared/connect";
|
|
5
5
|
import { z } from "zod";
|
|
@@ -182,7 +182,7 @@ const driveSectionOff = {
|
|
|
182
182
|
const connectPlugins = {
|
|
183
183
|
[GENERIC_PLUGIN]: {
|
|
184
184
|
create: createGenericPlugin,
|
|
185
|
-
ui: () => import("./ui-
|
|
185
|
+
ui: () => import("./ui-BVOQ9tj_.js").then((m) => m.default),
|
|
186
186
|
shell: "generic",
|
|
187
187
|
whenAbsent: (config) => ({
|
|
188
188
|
...config,
|
|
@@ -259,5 +259,5 @@ const connectPlugins = {
|
|
|
259
259
|
//#endregion
|
|
260
260
|
export { connectPlugins };
|
|
261
261
|
|
|
262
|
-
//# sourceMappingURL=plugins-
|
|
263
|
-
//# debugId=
|
|
262
|
+
//# sourceMappingURL=plugins-DV3oFEmL.js.map
|
|
263
|
+
//# debugId=cc104551-d72f-51a7-8a6a-77c9eca12f77
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugins-CegSox2x.js","sources":["../src/plugins/entry-config.ts","../src/plugins/assistant.ts","../src/plugins/generic.ts","../src/plugins/openpanel.ts","../src/plugins/sentry.ts","../src/plugins/ids.ts","../src/plugins/vetra-studio.ts","../src/plugins/workflows.ts","../src/plugins/index.ts"],"sourcesContent":["import { PluginError } from \"@powerhousedao/host-core/plugins\";\nimport { z } from \"zod\";\n\n/**\n * Validate a built-in plugin's entry config against its configSchema, the way\n * host-core's resolveHostPlugins does on the server: a failure names the\n * plugin and every offending key instead of surfacing a bare ZodError from\n * the runtime-config load.\n */\nexport function parseEntryConfig<S extends z.ZodType>(\n specifier: string,\n schema: S,\n rawConfig: unknown,\n): z.output<S> {\n const parsed = schema.safeParse(rawConfig);\n if (!parsed.success) {\n throw new PluginError(\n `config for Connect plugin \"${specifier}\" is invalid:\\n` +\n z.prettifyError(parsed.error),\n `Fix the entry's config in the host's runner.plugins.`,\n );\n }\n return parsed.data;\n}\n","import type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport type {\n ConnectPlugin,\n ConnectPluginFactory,\n} from \"@powerhousedao/connect-core/plugins\";\nimport { parseEntryConfig } from \"./entry-config.js\";\nimport {\n assistantConfigSchema,\n type AssistantConfigInput,\n} from \"../plugin-configs/assistant.js\";\n\n/**\n * The Connect AI assistant (`@powerhousedao/connect/plugins/assistant`).\n * Presence flips `ai.assistantEnabled` on; absence forces it off. The\n * assistant FAB in app.tsx already renders on `ai.assistantEnabled`, so this\n * plugin's config shuffle is immediately visible in the UI.\n *\n * It takes no entry config: `ai.assistantEnabled` is the only key of the\n * `connect.ai` slice, and presence is that switch. The endpoint and agent are\n * user settings in the browser, not host config.\n */\n\n// Schema and PHPluginConfigs augmentation: ../plugin-configs (zod-only).\nexport { assistantConfigSchema, type AssistantConfigInput };\n\nexport const createAssistantPlugin: ConnectPluginFactory = (rawConfig) => {\n parseEntryConfig(\n \"@powerhousedao/connect/plugins/assistant\",\n assistantConfigSchema,\n rawConfig,\n );\n const plugin: ConnectPlugin = {\n name: \"connect-assistant\",\n appliesTo: \"connect\",\n configSchema: assistantConfigSchema,\n hooks: {\n transformConnectConfig(served: PHConnectRuntimeConfig) {\n return {\n ...served,\n ai: { ...served.ai, assistantEnabled: true },\n };\n },\n },\n };\n return plugin;\n};\n\nexport default createAssistantPlugin;\n","import { DEFAULT_CONNECT_CONFIG } from \"@powerhousedao/shared/connect\";\nimport type {\n PHBackground,\n PHConnectExplorerIcons,\n PHConnectRuntimeConfig,\n} from \"@powerhousedao/shared/clis\";\nimport type {\n ConnectPlugin,\n ConnectPluginFactory,\n} from \"@powerhousedao/connect-core/plugins\";\nimport { parseEntryConfig } from \"./entry-config.js\";\nimport {\n genericConfigSchema,\n type GenericConfig,\n type GenericConfigInput,\n} from \"../plugin-configs/generic.js\";\n\n/**\n * The generic Connect shell plugin (`@powerhousedao/connect/plugins/generic`).\n *\n * It OWNS the drive-chrome UI toggles — `allowAddDrive` and the per-section\n * `sections.{remote,local}` switches (enabled / allowAdd / allowDelete) —\n * the explorer's `icons` (local/remote drive fallbacks, folder, document and\n * per-type document icons, which override the icons a package ships) and the\n * home screen's `homeBackground` (its layers over a page colour). These\n * describe nothing outside the generic chrome (connect.config.ts reads the\n * toggles to decide whether the add-drive affordance and the drive sections\n * render; the explorer components read the icons; the home screen is the\n * chrome's landing page), so under uniform runners they are configured HERE,\n * through this plugin's entry config, not as free-standing top-level\n * connect.drives / connect.home values:\n *\n * - present + entry provides a value -> that value\n * - present + entry omits it -> inherit DEFAULT_CONNECT_CONFIG\n * - absent from the composition -> zeroed off (see its whenAbsent\n * in ./index.ts — no chrome, no\n * toggles)\n *\n * The top-level served value is deliberately NOT a fallback: ownership means a\n * single source. `branding` is intentionally NOT handled here — it has reach\n * beyond the chrome (e.g. document.title), so it stays a Connect-level config\n * value that survives this plugin's absence.\n *\n * Icons and background images are image refs; a project path in host.js is\n * resolved to a data URI by the Connect build before the composition reaches\n * the browser, a URL or data URI passes through (the only forms for config\n * applied after the build). `null` keeps the built-in icon / gradient.\n */\n\n// Schema and PHPluginConfigs augmentation: ../plugin-configs (zod-only).\nexport { genericConfigSchema, type GenericConfig, type GenericConfigInput };\n\nconst DEFAULT_DRIVES = DEFAULT_CONNECT_CONFIG.drives;\nconst DEFAULT_HOME = DEFAULT_CONNECT_CONFIG.home;\n\nexport const createGenericPlugin: ConnectPluginFactory = (rawConfig) => {\n const config: GenericConfig = parseEntryConfig(\n \"@powerhousedao/connect/plugins/generic\",\n genericConfigSchema,\n rawConfig,\n );\n const plugin: ConnectPlugin = {\n name: \"connect-generic\",\n appliesTo: \"connect\",\n configSchema: genericConfigSchema,\n hooks: {\n transformConnectConfig(served: PHConnectRuntimeConfig) {\n const entrySections = config.sections ?? {};\n return {\n ...served,\n drives: {\n ...served.drives,\n // Owned: entry value, else the single-source default — never the\n // served top-level value.\n allowAddDrive:\n config.allowAddDrive ?? DEFAULT_DRIVES?.allowAddDrive,\n sections: {\n remote: {\n ...DEFAULT_DRIVES?.sections?.remote,\n ...entrySections.remote,\n },\n local: {\n ...DEFAULT_DRIVES?.sections?.local,\n ...entrySections.local,\n },\n },\n // Owned: the entry's icons (already resolved by the build), else\n // the default — the built-in icons.\n icons: (config.icons ?? null) as PHConnectExplorerIcons | null,\n } as never,\n home: {\n ...served.home,\n // Owned: the entry's background (images resolved by the build),\n // else the default — the bundled gradient.\n background: (config.homeBackground ??\n DEFAULT_HOME?.background ??\n null) as PHBackground | null,\n },\n };\n },\n },\n };\n return plugin;\n};\n\nexport default createGenericPlugin;\n","import type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport type {\n ConnectPlugin,\n ConnectPluginFactory,\n} from \"@powerhousedao/connect-core/plugins\";\nimport { parseEntryConfig } from \"./entry-config.js\";\nimport {\n openPanelConfigSchema,\n type OpenPanelConfigInput,\n} from \"../plugin-configs/openpanel.js\";\n\n/**\n * OpenPanel analytics (`@powerhousedao/connect/plugins/openpanel`). Presence\n * is activation: the entry config (clientId, trackUiEvents, trackOperations)\n * merges into the served `openPanel` block; absence clears the clientId and\n * turns tracking off. Config shuffle today; the Analytics/OpenPanel\n * components that consume it already live in the app tree.\n *\n * The entry config IS the `connect.openPanel` slice, so it is typed and\n * validated by that slice's single-source schema (a typo'd key fails).\n */\n\n// Schema and PHPluginConfigs augmentation: ../plugin-configs (zod-only).\nexport { openPanelConfigSchema, type OpenPanelConfigInput };\n\nexport const createOpenPanelPlugin: ConnectPluginFactory = (rawConfig) => {\n const config = parseEntryConfig(\n \"@powerhousedao/connect/plugins/openpanel\",\n openPanelConfigSchema,\n rawConfig,\n );\n const plugin: ConnectPlugin = {\n name: \"connect-openpanel\",\n appliesTo: \"connect\",\n configSchema: openPanelConfigSchema,\n hooks: {\n transformConnectConfig(served: PHConnectRuntimeConfig) {\n return {\n ...served,\n openPanel: { ...served.openPanel, ...config } as never,\n };\n },\n },\n };\n return plugin;\n};\n\nexport default createOpenPanelPlugin;\n","import type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport type {\n ConnectPlugin,\n ConnectPluginFactory,\n} from \"@powerhousedao/connect-core/plugins\";\nimport { parseEntryConfig } from \"./entry-config.js\";\nimport {\n sentryConfigSchema,\n type SentryConfigInput,\n} from \"../plugin-configs/sentry.js\";\n\n/**\n * Sentry error reporting (`@powerhousedao/connect/plugins/sentry`). Presence\n * is activation: listing it merges the entry config (dsn, env, tracing) into\n * the served `sentry` block; omitting it nulls the dsn (see the absence\n * zeroing in plugin-host). A thin config shuffle today — the SentryProvider\n * that reads this slice already exists in the app.\n *\n * The entry config IS the `connect.sentry` slice, so it is typed and\n * validated by that slice's single-source schema (a typo'd key fails).\n */\n\n// Schema and PHPluginConfigs augmentation: ../plugin-configs (zod-only).\nexport { sentryConfigSchema, type SentryConfigInput };\n\nexport const createSentryPlugin: ConnectPluginFactory = (rawConfig) => {\n const config = parseEntryConfig(\n \"@powerhousedao/connect/plugins/sentry\",\n sentryConfigSchema,\n rawConfig,\n );\n const plugin: ConnectPlugin = {\n name: \"connect-sentry\",\n appliesTo: \"connect\",\n configSchema: sentryConfigSchema,\n hooks: {\n transformConnectConfig(served: PHConnectRuntimeConfig) {\n return {\n ...served,\n sentry: { ...served.sentry, ...config } as never,\n };\n },\n },\n };\n return plugin;\n};\n\nexport default createSentryPlugin;\n","/** The generic shell: Connect's sidebar, home screen and settings tabs. */\nexport const GENERIC_PLUGIN = \"@powerhousedao/connect/plugins/generic\";\n","import type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport type {\n ConnectPlugin,\n ConnectPluginFactory,\n} from \"@powerhousedao/connect-core/plugins\";\nimport { parseEntryConfig } from \"./entry-config.js\";\nimport {\n vetraStudioConfigSchema,\n type VetraStudioConfigInput,\n} from \"../plugin-configs/vetra-studio.js\";\n\n/**\n * Vetra Studio, browser side (`@powerhousedao/vetra-studio/connect`). Its\n * presence turns Connect's studio mode on; the classic `app.studioMode`\n * consumer paths run unchanged, and absence forces studio off (the zeroing in\n * plugin-host). Lives here, in Connect's own source, because the studio-mode\n * behaviour is Connect browser behaviour — the published vetra-studio/connect\n * module is only the server-resolvable identity of the same plugin.\n *\n * It takes no entry config: presence is the switch, and the rest of the\n * `connect.app` slice is Connect-level config, not this plugin's.\n */\n\n// Schema and PHPluginConfigs augmentation: ../plugin-configs (zod-only).\nexport { vetraStudioConfigSchema, type VetraStudioConfigInput };\n\nexport const createVetraStudioPlugin: ConnectPluginFactory = (rawConfig) => {\n parseEntryConfig(\n \"@powerhousedao/vetra-studio/connect\",\n vetraStudioConfigSchema,\n rawConfig,\n );\n const plugin: ConnectPlugin = {\n name: \"vetra-studio-connect\",\n appliesTo: \"connect\",\n configSchema: vetraStudioConfigSchema,\n hooks: {\n transformConnectConfig(served: PHConnectRuntimeConfig) {\n return {\n ...served,\n app: { ...served.app, studioMode: true },\n };\n },\n },\n };\n return plugin;\n};\n\nexport default createVetraStudioPlugin;\n","import { findToken } from \"@powerhousedao/host-core/schema\";\nimport type {\n PHConnectDefaultDrive,\n PHConnectRuntimeConfig,\n} from \"@powerhousedao/shared/clis\";\nimport type {\n ConnectPlugin,\n ConnectPluginFactory,\n} from \"@powerhousedao/connect-core/plugins\";\nimport { parseEntryConfig } from \"./entry-config.js\";\nimport {\n workflowsConnectConfigSchema,\n type WorkflowsConnectConfig,\n type WorkflowsConnectConfigInput,\n} from \"../plugin-configs/workflows.js\";\n\n/**\n * The workflows plugin, browser side (`@powerhousedao/connect/plugins/\n * workflows`) — the Connect half of the link whose server half is\n * `@powerhousedao/switchboard/plugins/workflows` (workflow-plugins plan).\n *\n * Presence is activation: listed, Connect loads the workflow package (so\n * Workflow Studio, the drive app the Workflows drive names as its preferred\n * editor, exists) and attaches the configured drive as a remote default\n * drive. Absent from a declared composition, `app.workflowsEnabled` is zeroed\n * (its whenAbsent in ./index.ts) — the classic `workflows.enabled` /\n * `connect.app.workflowsEnabled` values stop being the switch.\n *\n * `drive` is the switchboard's drive URL (`http://host:port/d/<slug>`). The\n * drive has to be a REMOTE of the switchboard that runs the workflow runtime:\n * Workflow Studio reaches that runtime through the selected drive's\n * switchboard, so a local copy would render the studio against the wrong\n * endpoint. Host files write it as the output token\n * `switchboard.drives.workflows.url`; `ph run` resolves it (from the\n * compound's live member or the switchboard's run record) before this\n * config reaches the browser.\n */\n\n// Schema and PHPluginConfigs augmentation: ../plugin-configs (zod-only).\nexport {\n workflowsConnectConfigSchema,\n type WorkflowsConnectConfig,\n type WorkflowsConnectConfigInput,\n};\n\nconst LOG = \"[connect:plugins:workflows]\";\n\nfunction withDrive(\n drives: PHConnectDefaultDrive[] | undefined,\n url: string,\n name: string | undefined,\n): PHConnectDefaultDrive[] {\n const existing = drives ?? [];\n if (existing.some((drive) => \"url\" in drive && drive.url === url)) {\n return existing;\n }\n return [...existing, { url, name: name ?? null, icon: null }];\n}\n\nexport const createWorkflowsPlugin: ConnectPluginFactory = (rawConfig) => {\n const config: WorkflowsConnectConfig = parseEntryConfig(\n \"@powerhousedao/connect/plugins/workflows\",\n workflowsConnectConfigSchema,\n rawConfig,\n );\n const plugin: ConnectPlugin = {\n name: \"connect-workflows\",\n appliesTo: \"connect\",\n configSchema: workflowsConnectConfigSchema,\n hooks: {\n transformConnectConfig(served: PHConnectRuntimeConfig) {\n const out: PHConnectRuntimeConfig = {\n ...served,\n app: { ...served.app, workflowsEnabled: true } as never,\n };\n const drive = config.drive;\n if (typeof drive === \"string\") {\n out.drives = {\n ...served.drives,\n defaultDrives: withDrive(\n served.drives?.defaultDrives,\n drive,\n config.name,\n ),\n } as never;\n } else if (drive !== undefined) {\n console.warn(\n `${LOG} drive is an unresolved output token (${findToken(drive)?.key ?? \"unknown\"}); no Workflows drive attached.`,\n );\n }\n return out;\n },\n },\n };\n return plugin;\n};\n\nexport default createWorkflowsPlugin;\n","import type { ConnectPluginDefinition } from \"@powerhousedao/connect-core/plugins\";\nimport createAssistantPlugin from \"./assistant.js\";\nimport createGenericPlugin from \"./generic.js\";\nimport createOpenPanelPlugin from \"./openpanel.js\";\nimport createSentryPlugin from \"./sentry.js\";\nimport { GENERIC_PLUGIN } from \"./ids.js\";\nimport createVetraStudioPlugin from \"./vetra-studio.js\";\nimport createWorkflowsPlugin from \"./workflows.js\";\n\nexport { GENERIC_PLUGIN };\n\n// Sentry and OpenPanel start only once the viewer accepts analytics cookies.\nconst ANALYTICS_CONSENT = { consent: true };\n\n// Each built-in zeroes the config slice it owns when a composition leaves it out.\nconst driveSectionOff = { enabled: false, allowAdd: false, allowDelete: false };\n\n/** Connect's built-in plugins, by the specifier a composition names. */\nexport const connectPlugins: Record<string, ConnectPluginDefinition> = {\n [GENERIC_PLUGIN]: {\n create: createGenericPlugin,\n ui: () => import(\"../generic/ui.js\").then((m) => m.default),\n shell: \"generic\",\n // The drive-chrome toggles, explorer icons and home screen go: no\n // add-drive affordance, the sections off, built-in icons, no home\n // background. Branding is not zeroed: it is Connect-level and outlives\n // the plugin.\n whenAbsent: (config) => ({\n ...config,\n drives: {\n ...config.drives,\n allowAddDrive: false,\n sections: { remote: driveSectionOff, local: driveSectionOff },\n icons: null,\n } as never,\n home: { ...config.home, background: null } as never,\n }),\n },\n \"@powerhousedao/connect/plugins/sentry\": {\n create: createSentryPlugin,\n ui: () => Promise.resolve(ANALYTICS_CONSENT),\n whenAbsent: (config) => ({\n ...config,\n sentry: { ...config.sentry, dsn: null } as never,\n }),\n },\n \"@powerhousedao/connect/plugins/openpanel\": {\n create: createOpenPanelPlugin,\n ui: () => Promise.resolve(ANALYTICS_CONSENT),\n whenAbsent: (config) => ({\n ...config,\n openPanel: {\n ...config.openPanel,\n clientId: \"\",\n trackUiEvents: false,\n trackOperations: false,\n } as never,\n }),\n },\n \"@powerhousedao/connect/plugins/assistant\": {\n create: createAssistantPlugin,\n whenAbsent: (config) => ({\n ...config,\n ai: { ...config.ai, assistantEnabled: false } as never,\n }),\n },\n \"@powerhousedao/connect/plugins/workflows\": {\n create: createWorkflowsPlugin,\n // The workflow package (Workflow Studio) loads only when the plugin is\n // composed in; the classic workflows.enabled value is not the switch.\n whenAbsent: (config) => ({\n ...config,\n app: { ...config.app, workflowsEnabled: false } as never,\n }),\n },\n \"@powerhousedao/vetra-studio/connect\": {\n create: createVetraStudioPlugin,\n whenAbsent: (config) => ({\n ...config,\n app: { ...config.app, studioMode: false } as never,\n }),\n },\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;AASA,SAAgB,iBACd,WACA,QACA,WACa;CACb,MAAM,SAAS,OAAO,UAAU,SAAS;CACzC,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,YACR,8BAA8B,UAAU,mBACtC,EAAE,cAAc,OAAO,KAAK,GAC9B,sDACF;CAEF,OAAO,OAAO;AAChB;;;ACEA,MAAa,yBAA+C,cAAc;CACxE,iBACE,4CACA,uBACA,SACF;CAcA,OAAO;EAZL,MAAM;EACN,WAAW;EACX,cAAc;EACd,OAAO,EACL,uBAAuB,QAAgC;GACrD,OAAO;IACL,GAAG;IACH,IAAI;KAAE,GAAG,OAAO;KAAI,kBAAkB;IAAK;GAC7C;EACF,EACF;CAEU;AACd;;;ACOA,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GACA,MAAM;IAAE,GAAG,OAAO;IAAM,YAAY;GAAK;EAC3C;CACF;CACA,yCAAyC;EACvC,QAAQ;EACR,UAAU,QAAQ,QAAQ,iBAAiB;EAC3C,aAAa,YAAY;GACvB,GAAG;GACH,QAAQ;IAAE,GAAG,OAAO;IAAQ,KAAK;GAAK;EACxC;CACF;CACA,4CAA4C;EAC1C,QAAQ;EACR,UAAU,QAAQ,QAAQ,iBAAiB;EAC3C,aAAa,YAAY;GACvB,GAAG;GACH,WAAW;IACT,GAAG,OAAO;IACV,UAAU;IACV,eAAe;IACf,iBAAiB;GACnB;EACF;CACF;CACA,4CAA4C;EAC1C,QAAQ;EACR,aAAa,YAAY;GACvB,GAAG;GACH,IAAI;IAAE,GAAG,OAAO;IAAI,kBAAkB;GAAM;EAC9C;CACF;CACA,4CAA4C;EAC1C,QAAQ;EAGR,aAAa,YAAY;GACvB,GAAG;GACH,KAAK;IAAE,GAAG,OAAO;IAAK,kBAAkB;GAAM;EAChD;CACF;CACA,uCAAuC;EACrC,QAAQ;EACR,aAAa,YAAY;GACvB,GAAG;GACH,KAAK;IAAE,GAAG,OAAO;IAAK,YAAY;GAAM;EAC1C;CACF;AACF","debug_id":"5648c876-2263-515c-bec8-707bdf29a87a"}
|
|
1
|
+
{"version":3,"file":"plugins-DV3oFEmL.js","sources":["../src/plugins/entry-config.ts","../src/plugins/assistant.ts","../src/plugins/generic.ts","../src/plugins/openpanel.ts","../src/plugins/sentry.ts","../src/plugins/ids.ts","../src/plugins/vetra-studio.ts","../src/plugins/workflows.ts","../src/plugins/index.ts"],"sourcesContent":["import { PluginError } from \"@powerhousedao/host-core/plugins\";\nimport { z } from \"zod\";\n\n/**\n * Validate a built-in plugin's entry config against its configSchema, the way\n * host-core's resolveHostPlugins does on the server: a failure names the\n * plugin and every offending key instead of surfacing a bare ZodError from\n * the runtime-config load.\n */\nexport function parseEntryConfig<S extends z.ZodType>(\n specifier: string,\n schema: S,\n rawConfig: unknown,\n): z.output<S> {\n const parsed = schema.safeParse(rawConfig);\n if (!parsed.success) {\n throw new PluginError(\n `config for Connect plugin \"${specifier}\" is invalid:\\n` +\n z.prettifyError(parsed.error),\n `Fix the entry's config in the host's runner.plugins.`,\n );\n }\n return parsed.data;\n}\n","import type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport type {\n ConnectPlugin,\n ConnectPluginFactory,\n} from \"@powerhousedao/connect-core/plugins\";\nimport { parseEntryConfig } from \"./entry-config.js\";\nimport {\n assistantConfigSchema,\n type AssistantConfigInput,\n} from \"../plugin-configs/assistant.js\";\n\n/**\n * The Connect AI assistant (`@powerhousedao/connect/plugins/assistant`).\n * Presence flips `ai.assistantEnabled` on; absence forces it off. The\n * assistant FAB in app.tsx already renders on `ai.assistantEnabled`, so this\n * plugin's config shuffle is immediately visible in the UI.\n *\n * It takes no entry config: `ai.assistantEnabled` is the only key of the\n * `connect.ai` slice, and presence is that switch. The endpoint and agent are\n * user settings in the browser, not host config.\n */\n\n// Schema and PHPluginConfigs augmentation: ../plugin-configs (zod-only).\nexport { assistantConfigSchema, type AssistantConfigInput };\n\nexport const createAssistantPlugin: ConnectPluginFactory = (rawConfig) => {\n parseEntryConfig(\n \"@powerhousedao/connect/plugins/assistant\",\n assistantConfigSchema,\n rawConfig,\n );\n const plugin: ConnectPlugin = {\n name: \"connect-assistant\",\n appliesTo: \"connect\",\n configSchema: assistantConfigSchema,\n hooks: {\n transformConnectConfig(served: PHConnectRuntimeConfig) {\n return {\n ...served,\n ai: { ...served.ai, assistantEnabled: true },\n };\n },\n },\n };\n return plugin;\n};\n\nexport default createAssistantPlugin;\n","import { DEFAULT_CONNECT_CONFIG } from \"@powerhousedao/shared/connect\";\nimport type {\n PHBackground,\n PHConnectExplorerIcons,\n PHConnectRuntimeConfig,\n} from \"@powerhousedao/shared/clis\";\nimport type {\n ConnectPlugin,\n ConnectPluginFactory,\n} from \"@powerhousedao/connect-core/plugins\";\nimport { parseEntryConfig } from \"./entry-config.js\";\nimport {\n genericConfigSchema,\n type GenericConfig,\n type GenericConfigInput,\n} from \"../plugin-configs/generic.js\";\n\n/**\n * The generic Connect shell plugin (`@powerhousedao/connect/plugins/generic`).\n *\n * It OWNS the drive-chrome UI toggles — `allowAddDrive` and the per-section\n * `sections.{remote,local}` switches (enabled / allowAdd / allowDelete) —\n * the explorer's `icons` (local/remote drive fallbacks, folder, document and\n * per-type document icons, which override the icons a package ships) and the\n * home screen's `homeBackground` (its layers over a page colour). These\n * describe nothing outside the generic chrome (connect.config.ts reads the\n * toggles to decide whether the add-drive affordance and the drive sections\n * render; the explorer components read the icons; the home screen is the\n * chrome's landing page), so under uniform runners they are configured HERE,\n * through this plugin's entry config, not as free-standing top-level\n * connect.drives / connect.home values:\n *\n * - present + entry provides a value -> that value\n * - present + entry omits it -> inherit DEFAULT_CONNECT_CONFIG\n * - absent from the composition -> zeroed off (see its whenAbsent\n * in ./index.ts — no chrome, no\n * toggles)\n *\n * The top-level served value is deliberately NOT a fallback: ownership means a\n * single source. `branding` is intentionally NOT handled here — it has reach\n * beyond the chrome (e.g. document.title), so it stays a Connect-level config\n * value that survives this plugin's absence.\n *\n * Icons and background images are image refs; a project path in host.js is\n * resolved to a data URI by the Connect build before the composition reaches\n * the browser, a URL or data URI passes through (the only forms for config\n * applied after the build). `null` keeps the built-in icon / gradient.\n */\n\n// Schema and PHPluginConfigs augmentation: ../plugin-configs (zod-only).\nexport { genericConfigSchema, type GenericConfig, type GenericConfigInput };\n\nconst DEFAULT_DRIVES = DEFAULT_CONNECT_CONFIG.drives;\nconst DEFAULT_HOME = DEFAULT_CONNECT_CONFIG.home;\n\nexport const createGenericPlugin: ConnectPluginFactory = (rawConfig) => {\n const config: GenericConfig = parseEntryConfig(\n \"@powerhousedao/connect/plugins/generic\",\n genericConfigSchema,\n rawConfig,\n );\n const plugin: ConnectPlugin = {\n name: \"connect-generic\",\n appliesTo: \"connect\",\n configSchema: genericConfigSchema,\n hooks: {\n transformConnectConfig(served: PHConnectRuntimeConfig) {\n const entrySections = config.sections ?? {};\n return {\n ...served,\n drives: {\n ...served.drives,\n // Owned: entry value, else the single-source default — never the\n // served top-level value.\n allowAddDrive:\n config.allowAddDrive ?? DEFAULT_DRIVES?.allowAddDrive,\n sections: {\n remote: {\n ...DEFAULT_DRIVES?.sections?.remote,\n ...entrySections.remote,\n },\n local: {\n ...DEFAULT_DRIVES?.sections?.local,\n ...entrySections.local,\n },\n },\n // Owned: the entry's icons (already resolved by the build), else\n // the default — the built-in icons.\n icons: (config.icons ?? null) as PHConnectExplorerIcons | null,\n } as never,\n home: {\n ...served.home,\n // Owned: the entry's background (images resolved by the build),\n // else the default — the bundled gradient.\n background: (config.homeBackground ??\n DEFAULT_HOME?.background ??\n null) as PHBackground | null,\n },\n };\n },\n },\n };\n return plugin;\n};\n\nexport default createGenericPlugin;\n","import type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport type {\n ConnectPlugin,\n ConnectPluginFactory,\n} from \"@powerhousedao/connect-core/plugins\";\nimport { parseEntryConfig } from \"./entry-config.js\";\nimport {\n openPanelConfigSchema,\n type OpenPanelConfigInput,\n} from \"../plugin-configs/openpanel.js\";\n\n/**\n * OpenPanel analytics (`@powerhousedao/connect/plugins/openpanel`). Presence\n * is activation: the entry config (clientId, trackUiEvents, trackOperations)\n * merges into the served `openPanel` block; absence clears the clientId and\n * turns tracking off. Config shuffle today; the Analytics/OpenPanel\n * components that consume it already live in the app tree.\n *\n * The entry config IS the `connect.openPanel` slice, so it is typed and\n * validated by that slice's single-source schema (a typo'd key fails).\n */\n\n// Schema and PHPluginConfigs augmentation: ../plugin-configs (zod-only).\nexport { openPanelConfigSchema, type OpenPanelConfigInput };\n\nexport const createOpenPanelPlugin: ConnectPluginFactory = (rawConfig) => {\n const config = parseEntryConfig(\n \"@powerhousedao/connect/plugins/openpanel\",\n openPanelConfigSchema,\n rawConfig,\n );\n const plugin: ConnectPlugin = {\n name: \"connect-openpanel\",\n appliesTo: \"connect\",\n configSchema: openPanelConfigSchema,\n hooks: {\n transformConnectConfig(served: PHConnectRuntimeConfig) {\n return {\n ...served,\n openPanel: { ...served.openPanel, ...config } as never,\n };\n },\n },\n };\n return plugin;\n};\n\nexport default createOpenPanelPlugin;\n","import type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport type {\n ConnectPlugin,\n ConnectPluginFactory,\n} from \"@powerhousedao/connect-core/plugins\";\nimport { parseEntryConfig } from \"./entry-config.js\";\nimport {\n sentryConfigSchema,\n type SentryConfigInput,\n} from \"../plugin-configs/sentry.js\";\n\n/**\n * Sentry error reporting (`@powerhousedao/connect/plugins/sentry`). Presence\n * is activation: listing it merges the entry config (dsn, env, tracing) into\n * the served `sentry` block; omitting it nulls the dsn (see the absence\n * zeroing in plugin-host). A thin config shuffle today — the SentryProvider\n * that reads this slice already exists in the app.\n *\n * The entry config IS the `connect.sentry` slice, so it is typed and\n * validated by that slice's single-source schema (a typo'd key fails).\n */\n\n// Schema and PHPluginConfigs augmentation: ../plugin-configs (zod-only).\nexport { sentryConfigSchema, type SentryConfigInput };\n\nexport const createSentryPlugin: ConnectPluginFactory = (rawConfig) => {\n const config = parseEntryConfig(\n \"@powerhousedao/connect/plugins/sentry\",\n sentryConfigSchema,\n rawConfig,\n );\n const plugin: ConnectPlugin = {\n name: \"connect-sentry\",\n appliesTo: \"connect\",\n configSchema: sentryConfigSchema,\n hooks: {\n transformConnectConfig(served: PHConnectRuntimeConfig) {\n return {\n ...served,\n sentry: { ...served.sentry, ...config } as never,\n };\n },\n },\n };\n return plugin;\n};\n\nexport default createSentryPlugin;\n","/** The generic shell: Connect's sidebar, home screen and settings tabs. */\nexport const GENERIC_PLUGIN = \"@powerhousedao/connect/plugins/generic\";\n","import type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport type {\n ConnectPlugin,\n ConnectPluginFactory,\n} from \"@powerhousedao/connect-core/plugins\";\nimport { parseEntryConfig } from \"./entry-config.js\";\nimport {\n vetraStudioConfigSchema,\n type VetraStudioConfigInput,\n} from \"../plugin-configs/vetra-studio.js\";\n\n/**\n * Vetra Studio, browser side (`@powerhousedao/vetra-studio/connect`). Its\n * presence turns Connect's studio mode on; the classic `app.studioMode`\n * consumer paths run unchanged, and absence forces studio off (the zeroing in\n * plugin-host). Lives here, in Connect's own source, because the studio-mode\n * behaviour is Connect browser behaviour — the published vetra-studio/connect\n * module is only the server-resolvable identity of the same plugin.\n *\n * It takes no entry config: presence is the switch, and the rest of the\n * `connect.app` slice is Connect-level config, not this plugin's.\n */\n\n// Schema and PHPluginConfigs augmentation: ../plugin-configs (zod-only).\nexport { vetraStudioConfigSchema, type VetraStudioConfigInput };\n\nexport const createVetraStudioPlugin: ConnectPluginFactory = (rawConfig) => {\n parseEntryConfig(\n \"@powerhousedao/vetra-studio/connect\",\n vetraStudioConfigSchema,\n rawConfig,\n );\n const plugin: ConnectPlugin = {\n name: \"vetra-studio-connect\",\n appliesTo: \"connect\",\n configSchema: vetraStudioConfigSchema,\n hooks: {\n transformConnectConfig(served: PHConnectRuntimeConfig) {\n return {\n ...served,\n app: { ...served.app, studioMode: true },\n };\n },\n },\n };\n return plugin;\n};\n\nexport default createVetraStudioPlugin;\n","import { findToken } from \"@powerhousedao/host-core/schema\";\nimport type {\n PHConnectDefaultDrive,\n PHConnectRuntimeConfig,\n} from \"@powerhousedao/shared/clis\";\nimport type {\n ConnectPlugin,\n ConnectPluginFactory,\n} from \"@powerhousedao/connect-core/plugins\";\nimport { parseEntryConfig } from \"./entry-config.js\";\nimport {\n workflowsConnectConfigSchema,\n type WorkflowsConnectConfig,\n type WorkflowsConnectConfigInput,\n} from \"../plugin-configs/workflows.js\";\n\n/**\n * The workflows plugin, browser side (`@powerhousedao/connect/plugins/\n * workflows`) — the Connect half of the link whose server half is\n * `@powerhousedao/switchboard/plugins/workflows` (workflow-plugins plan).\n *\n * Presence is activation: listed, Connect loads the workflow package (so\n * Workflow Studio, the drive app the Workflows drive names as its preferred\n * editor, exists) and attaches the configured drive as a remote default\n * drive. Absent from a declared composition, `app.workflowsEnabled` is zeroed\n * (its whenAbsent in ./index.ts) — the classic `workflows.enabled` /\n * `connect.app.workflowsEnabled` values stop being the switch.\n *\n * `drive` is the switchboard's drive URL (`http://host:port/d/<slug>`). The\n * drive has to be a REMOTE of the switchboard that runs the workflow runtime:\n * Workflow Studio reaches that runtime through the selected drive's\n * switchboard, so a local copy would render the studio against the wrong\n * endpoint. Host files write it as the output token\n * `switchboard.drives.workflows.url`; `ph run` resolves it (from the\n * compound's live member or the switchboard's run record) before this\n * config reaches the browser.\n */\n\n// Schema and PHPluginConfigs augmentation: ../plugin-configs (zod-only).\nexport {\n workflowsConnectConfigSchema,\n type WorkflowsConnectConfig,\n type WorkflowsConnectConfigInput,\n};\n\nconst LOG = \"[connect:plugins:workflows]\";\n\nfunction withDrive(\n drives: PHConnectDefaultDrive[] | undefined,\n url: string,\n name: string | undefined,\n): PHConnectDefaultDrive[] {\n const existing = drives ?? [];\n if (existing.some((drive) => \"url\" in drive && drive.url === url)) {\n return existing;\n }\n return [...existing, { url, name: name ?? null, icon: null }];\n}\n\nexport const createWorkflowsPlugin: ConnectPluginFactory = (rawConfig) => {\n const config: WorkflowsConnectConfig = parseEntryConfig(\n \"@powerhousedao/connect/plugins/workflows\",\n workflowsConnectConfigSchema,\n rawConfig,\n );\n const plugin: ConnectPlugin = {\n name: \"connect-workflows\",\n appliesTo: \"connect\",\n configSchema: workflowsConnectConfigSchema,\n hooks: {\n transformConnectConfig(served: PHConnectRuntimeConfig) {\n const out: PHConnectRuntimeConfig = {\n ...served,\n app: { ...served.app, workflowsEnabled: true } as never,\n };\n const drive = config.drive;\n if (typeof drive === \"string\") {\n out.drives = {\n ...served.drives,\n defaultDrives: withDrive(\n served.drives?.defaultDrives,\n drive,\n config.name,\n ),\n } as never;\n } else if (drive !== undefined) {\n console.warn(\n `${LOG} drive is an unresolved output token (${findToken(drive)?.key ?? \"unknown\"}); no Workflows drive attached.`,\n );\n }\n return out;\n },\n },\n };\n return plugin;\n};\n\nexport default createWorkflowsPlugin;\n","import type { ConnectPluginDefinition } from \"@powerhousedao/connect-core/plugins\";\nimport createAssistantPlugin from \"./assistant.js\";\nimport createGenericPlugin from \"./generic.js\";\nimport createOpenPanelPlugin from \"./openpanel.js\";\nimport createSentryPlugin from \"./sentry.js\";\nimport { GENERIC_PLUGIN } from \"./ids.js\";\nimport createVetraStudioPlugin from \"./vetra-studio.js\";\nimport createWorkflowsPlugin from \"./workflows.js\";\n\nexport { GENERIC_PLUGIN };\n\n// Sentry and OpenPanel start only once the viewer accepts analytics cookies.\nconst ANALYTICS_CONSENT = { consent: true };\n\n// Each built-in zeroes the config slice it owns when a composition leaves it out.\nconst driveSectionOff = { enabled: false, allowAdd: false, allowDelete: false };\n\n/** Connect's built-in plugins, by the specifier a composition names. */\nexport const connectPlugins: Record<string, ConnectPluginDefinition> = {\n [GENERIC_PLUGIN]: {\n create: createGenericPlugin,\n ui: () => import(\"../generic/ui.js\").then((m) => m.default),\n shell: \"generic\",\n // The drive-chrome toggles, explorer icons and home screen go: no\n // add-drive affordance, the sections off, built-in icons, no home\n // background. Branding is not zeroed: it is Connect-level and outlives\n // the plugin.\n whenAbsent: (config) => ({\n ...config,\n drives: {\n ...config.drives,\n allowAddDrive: false,\n sections: { remote: driveSectionOff, local: driveSectionOff },\n icons: null,\n } as never,\n home: { ...config.home, background: null } as never,\n }),\n },\n \"@powerhousedao/connect/plugins/sentry\": {\n create: createSentryPlugin,\n ui: () => Promise.resolve(ANALYTICS_CONSENT),\n whenAbsent: (config) => ({\n ...config,\n sentry: { ...config.sentry, dsn: null } as never,\n }),\n },\n \"@powerhousedao/connect/plugins/openpanel\": {\n create: createOpenPanelPlugin,\n ui: () => Promise.resolve(ANALYTICS_CONSENT),\n whenAbsent: (config) => ({\n ...config,\n openPanel: {\n ...config.openPanel,\n clientId: \"\",\n trackUiEvents: false,\n trackOperations: false,\n } as never,\n }),\n },\n \"@powerhousedao/connect/plugins/assistant\": {\n create: createAssistantPlugin,\n whenAbsent: (config) => ({\n ...config,\n ai: { ...config.ai, assistantEnabled: false } as never,\n }),\n },\n \"@powerhousedao/connect/plugins/workflows\": {\n create: createWorkflowsPlugin,\n // The workflow package (Workflow Studio) loads only when the plugin is\n // composed in; the classic workflows.enabled value is not the switch.\n whenAbsent: (config) => ({\n ...config,\n app: { ...config.app, workflowsEnabled: false } as never,\n }),\n },\n \"@powerhousedao/vetra-studio/connect\": {\n create: createVetraStudioPlugin,\n whenAbsent: (config) => ({\n ...config,\n app: { ...config.app, studioMode: false } as never,\n }),\n },\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;AASA,SAAgB,iBACd,WACA,QACA,WACa;CACb,MAAM,SAAS,OAAO,UAAU,SAAS;CACzC,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,YACR,8BAA8B,UAAU,mBACtC,EAAE,cAAc,OAAO,KAAK,GAC9B,sDACF;CAEF,OAAO,OAAO;AAChB;;;ACEA,MAAa,yBAA+C,cAAc;CACxE,iBACE,4CACA,uBACA,SACF;CAcA,OAAO;EAZL,MAAM;EACN,WAAW;EACX,cAAc;EACd,OAAO,EACL,uBAAuB,QAAgC;GACrD,OAAO;IACL,GAAG;IACH,IAAI;KAAE,GAAG,OAAO;KAAI,kBAAkB;IAAK;GAC7C;EACF,EACF;CAEU;AACd;;;ACOA,MAAM,iBAAiB,uBAAuB;AAC9C,MAAM,eAAe,uBAAuB;AAE5C,MAAa,uBAA6C,cAAc;CACtE,MAAM,SAAwB,iBAC5B,0CACA,qBACA,SACF;CA0CA,OAAO;EAxCL,MAAM;EACN,WAAW;EACX,cAAc;EACd,OAAO,EACL,uBAAuB,QAAgC;GACrD,MAAM,gBAAgB,OAAO,YAAY,CAAC;GAC1C,OAAO;IACL,GAAG;IACH,QAAQ;KACN,GAAG,OAAO;KAGV,eACE,OAAO,iBAAiB,gBAAgB;KAC1C,UAAU;MACR,QAAQ;OACN,GAAG,gBAAgB,UAAU;OAC7B,GAAG,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4C;EAC1C,QAAQ;EACR,aAAa,YAAY;GACvB,GAAG;GACH,IAAI;IAAE,GAAG,OAAO;IAAI,kBAAkB;GAAM;EAC9C;CACF;CACA,4CAA4C;EAC1C,QAAQ;EAGR,aAAa,YAAY;GACvB,GAAG;GACH,KAAK;IAAE,GAAG,OAAO;IAAK,kBAAkB;GAAM;EAChD;CACF;CACA,uCAAuC;EACrC,QAAQ;EACR,aAAa,YAAY;GACvB,GAAG;GACH,KAAK;IAAE,GAAG,OAAO;IAAK,YAAY;GAAM;EAC1C;CACF;AACF","debug_id":"cc104551-d72f-51a7-8a6a-77c9eca12f77"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
3
|
-
import { r as connectConfig } from "./connect.config-
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="12ffe631-da25-51c9-9b9b-215cb5ec2a2e")}catch(e){}}();
|
|
3
|
+
import { r as connectConfig } from "./connect.config-DL9nKtlW.js";
|
|
4
4
|
import { useSyncExternalStore } from "react";
|
|
5
5
|
import { getIsEmbedded } from "@powerhousedao/connect-core/embedded";
|
|
6
6
|
//#region src/hooks/preferences-store.ts
|
|
@@ -81,5 +81,5 @@ const useCookieBanner = () => {
|
|
|
81
81
|
//#endregion
|
|
82
82
|
export { useAcceptedCookies as n, useCookieBanner as r, setBannerShown as t };
|
|
83
83
|
|
|
84
|
-
//# sourceMappingURL=preferences-store-
|
|
85
|
-
//# debugId=
|
|
84
|
+
//# sourceMappingURL=preferences-store-DxYAnGCc.js.map
|
|
85
|
+
//# debugId=12ffe631-da25-51c9-9b9b-215cb5ec2a2e
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"preferences-store-
|
|
1
|
+
{"version":3,"file":"preferences-store-DxYAnGCc.js","sources":["../src/hooks/preferences-store.ts"],"sourcesContent":["import { connectConfig } from \"@powerhousedao/connect/config\";\nimport { useSyncExternalStore } from \"react\";\n\nimport { getIsEmbedded } from \"@powerhousedao/connect-core/embedded\";\n\nconst namespace = connectConfig.routerBasename;\n\n/**\n * Block-proof home for Connect's consent and banner state.\n *\n * The file name deliberately avoids words that appear in ad-blocker\n * filter lists (cookie, banner, consent, analytics, ...). Modules in the\n * app's critical import chain import from here, never from files whose\n * URLs match those filters. If an ad blocker blocks the lazy-loaded\n * cookie-banner chunk instead, the app simply never shows the banner —\n * which leaves the flags at their rejected defaults (analytics off) —\n * and everything else keeps working.\n */\n\n// ---------------------------------------------------------------------------\n// Accepted cookies (analytics / marketing / functional)\n// ---------------------------------------------------------------------------\n\nexport const ACCEPTED_COOKIES_KEY_STORAGE = `${namespace}:acceptedCookies`;\n\nexport interface AcceptedCookies {\n analytics: boolean;\n marketing: boolean;\n functional: boolean;\n}\n\nconst REJECTED_COOKIES: AcceptedCookies = {\n analytics: false,\n marketing: false,\n functional: false,\n};\n\nconst cookieListeners = new Set<() => void>();\n\nlet acceptedCookies: AcceptedCookies = getInitialAcceptedCookies();\n\nfunction getInitialAcceptedCookies(): AcceptedCookies {\n try {\n const value = localStorage.getItem(ACCEPTED_COOKIES_KEY_STORAGE);\n return value ? (JSON.parse(value) as AcceptedCookies) : REJECTED_COOKIES;\n } catch {\n return REJECTED_COOKIES;\n }\n}\n\nfunction subscribeAcceptedCookies(fn: () => void) {\n cookieListeners.add(fn);\n return () => {\n cookieListeners.delete(fn);\n };\n}\n\nfunction getAcceptedCookies(): AcceptedCookies {\n return acceptedCookies;\n}\n\nexport function setAcceptedCookies(\n setter: (prev: AcceptedCookies) => AcceptedCookies,\n) {\n acceptedCookies = setter(acceptedCookies);\n localStorage.setItem(\n ACCEPTED_COOKIES_KEY_STORAGE,\n JSON.stringify(acceptedCookies),\n );\n cookieListeners.forEach((fn) => fn());\n}\n\nexport const useAcceptedCookies = () => {\n const cookies = useSyncExternalStore(\n subscribeAcceptedCookies,\n getAcceptedCookies,\n getAcceptedCookies,\n );\n return [cookies, setAcceptedCookies] as const;\n};\n\n// ---------------------------------------------------------------------------\n// Cookie banner visibility\n// ---------------------------------------------------------------------------\n\nexport const COOKIE_BANNER_KEY_STORAGE = `${namespace}:display-cookie-banner`;\n\nconst bannerListeners = new Set<() => void>();\n\nlet bannerShown = getInitialBannerShown();\n\nfunction getInitialBannerShown(): boolean {\n if (getIsEmbedded()) return false;\n try {\n const value = localStorage.getItem(COOKIE_BANNER_KEY_STORAGE);\n return value !== \"false\";\n } catch (error) {\n console.error(error);\n return true;\n }\n}\n\nfunction subscribeBannerShown(fn: () => void) {\n bannerListeners.add(fn);\n return () => {\n bannerListeners.delete(fn);\n };\n}\n\nfunction getBannerShown(): boolean {\n return bannerShown;\n}\n\nexport function setBannerShown(state: boolean) {\n bannerShown = state;\n localStorage.setItem(COOKIE_BANNER_KEY_STORAGE, JSON.stringify(state));\n bannerListeners.forEach((fn) => fn());\n}\n\nexport const useCookieBanner = () => {\n const shown = useSyncExternalStore(\n subscribeBannerShown,\n getBannerShown,\n getBannerShown,\n );\n return [shown, setBannerShown] as const;\n};\n"],"names":[],"mappings":";;;;;;AAKA,MAAM,YAAY,cAAc;;;;;;;;;;;;AAkBhC,MAAa,+BAA+B,GAAG,UAAU;AAQzD,MAAM,mBAAoC;CACxC,WAAW;CACX,WAAW;CACX,YAAY;AACd;AAEA,MAAM,kCAAkB,IAAI,IAAgB;AAE5C,IAAI,kBAAmC,0BAA0B;AAEjE,SAAS,4BAA6C;CACpD,IAAI;EACF,MAAM,QAAQ,aAAa,QAAQ,4BAA4B;EAC/D,OAAO,QAAS,KAAK,MAAM,KAAK,IAAwB;CAC1D,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,yBAAyB,IAAgB;CAChD,gBAAgB,IAAI,EAAE;CACtB,aAAa;EACX,gBAAgB,OAAO,EAAE;CAC3B;AACF;AAEA,SAAS,qBAAsC;CAC7C,OAAO;AACT;AAEA,SAAgB,mBACd,QACA;CACA,kBAAkB,OAAO,eAAe;CACxC,aAAa,QACX,8BACA,KAAK,UAAU,eAAe,CAChC;CACA,gBAAgB,SAAS,OAAO,GAAG,CAAC;AACtC;AAEA,MAAa,2BAA2B;CAMtC,OAAO,CALS,qBACd,0BACA,oBACA,kBAEY,GAAG,kBAAkB;AACrC;AAMA,MAAa,4BAA4B,GAAG,UAAU;AAEtD,MAAM,kCAAkB,IAAI,IAAgB;AAE5C,IAAI,cAAc,sBAAsB;AAExC,SAAS,wBAAiC;CACxC,IAAI,cAAc,GAAG,OAAO;CAC5B,IAAI;EAEF,OADc,aAAa,QAAQ,yBACxB,MAAM;CACnB,SAAS,OAAO;EACd,QAAQ,MAAM,KAAK;EACnB,OAAO;CACT;AACF;AAEA,SAAS,qBAAqB,IAAgB;CAC5C,gBAAgB,IAAI,EAAE;CACtB,aAAa;EACX,gBAAgB,OAAO,EAAE;CAC3B;AACF;AAEA,SAAS,iBAA0B;CACjC,OAAO;AACT;AAEA,SAAgB,eAAe,OAAgB;CAC7C,cAAc;CACd,aAAa,QAAQ,2BAA2B,KAAK,UAAU,KAAK,CAAC;CACrE,gBAAgB,SAAS,OAAO,GAAG,CAAC;AACtC;AAEA,MAAa,wBAAwB;CAMnC,OAAO,CALO,qBACZ,sBACA,gBACA,cAEU,GAAG,cAAc;AAC/B","debug_id":"12ffe631-da25-51c9-9b9b-215cb5ec2a2e"}
|
package/dist/prerender.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prerender.d.ts","names":[],"sources":["../src/prerender/app-shell.ts","../src/prerender/shell-css.ts","../src/prerender/shell.tsx"],"mappings":";;KAMY;;qBAGC;;;wBA8DG,YAAY;;;wBAYZ,SACd,MAAM,cACN,6BACA,gBACA;EAME;EAGA;;;;;;wBCnEkB,SACpB,eACA,gBACA,eAAiC;;;;wBCUb,gBAAgB,QACpC,QAAQ,OAAO;;YAUL;;;wBAMU,YACpB,UAAS,cACT,OAAM,eACL;;;
|
|
1
|
+
{"version":3,"file":"prerender.d.ts","names":[],"sources":["../src/prerender/app-shell.ts","../src/prerender/shell-css.ts","../src/prerender/shell.tsx"],"mappings":";;KAMY;;qBAGC;;;wBA8DG,YAAY;;;wBAYZ,SACd,MAAM,cACN,6BACA,gBACA;EAME;EAGA;;;;;;wBCnEkB,SACpB,eACA,gBACA,eAAiC;;;;wBCUb,gBAAgB,QACpC,QAAQ,OAAO;;YAUL;;;wBAMU,YACpB,UAAS,cACT,OAAM,eACL;;;wBAiEmB,oBAAoB,oBAAoB,eAAY,QAAA,QAAA,OAAA;EACrB;EAAc"}
|
package/dist/prerender.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="305fb767-6f6e-5988-a96a-bf319e034ac6")}catch(e){}}();
|
|
3
3
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
4
4
|
import { primeRuntimeConfig } from "@powerhousedao/connect-core/runtime-config";
|
|
5
5
|
import { PHStoreProvider, createPHStore } from "@powerhousedao/reactor-browser";
|
|
@@ -120,7 +120,7 @@ async function loadDefaultConfig(variant) {
|
|
|
120
120
|
const plugin = (await shellPlugins())[variant];
|
|
121
121
|
await loadConnectPluginUi(plugin ? [{ module: plugin }] : []);
|
|
122
122
|
}
|
|
123
|
-
const connectPlugins = () => import("./plugins-
|
|
123
|
+
const connectPlugins = () => import("./plugins-DV3oFEmL.js").then((m) => m.connectPlugins);
|
|
124
124
|
/** Each prerendered shell's plugin, whose presence in a composition picks it; core's has none. */
|
|
125
125
|
async function shellPlugins() {
|
|
126
126
|
return Object.fromEntries(Object.entries(await connectPlugins()).flatMap(([module, definition]) => definition.shell ? [[definition.shell, module]] : []));
|
|
@@ -151,17 +151,19 @@ async function renderShell(variant = "generic", kind = variant) {
|
|
|
151
151
|
const layoutPending = appRoute.options.pendingComponent;
|
|
152
152
|
const Loader = kind === "generic" ? ShellLoader : kind === "project" && layoutPending ? () => null : CoreShellLoader;
|
|
153
153
|
const errors = [];
|
|
154
|
+
const causes = [];
|
|
154
155
|
const { prelude } = await prerender(/* @__PURE__ */ jsxs(PHStoreProvider, {
|
|
155
156
|
store,
|
|
156
157
|
children: [/* @__PURE__ */ jsx(RouterProvider, { router: connectRouter.router }), /* @__PURE__ */ jsx(Loader, {})]
|
|
157
158
|
}), {
|
|
158
159
|
progressiveChunkSize: Number.POSITIVE_INFINITY,
|
|
159
|
-
onError: (error) => {
|
|
160
|
+
onError: (error, info) => {
|
|
160
161
|
errors.push(error);
|
|
162
|
+
causes.push(describeRenderError(error, info?.componentStack));
|
|
161
163
|
}
|
|
162
164
|
});
|
|
163
165
|
resetConnectPluginUi(routeTree);
|
|
164
|
-
if (errors.length) throw new AggregateError(errors,
|
|
166
|
+
if (errors.length) throw new AggregateError(errors, `The app shell failed to prerender:\n${causes.join("\n")}`);
|
|
165
167
|
return await new Response(prelude).text();
|
|
166
168
|
}
|
|
167
169
|
/** A project's shells, one per variant: its route tree rendered at `/`, with
|
|
@@ -174,8 +176,13 @@ async function renderProjectShells(stylesheet, css) {
|
|
|
174
176
|
}
|
|
175
177
|
return shells;
|
|
176
178
|
}
|
|
179
|
+
function describeRenderError(error, componentStack) {
|
|
180
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
181
|
+
const component = componentStack?.trim().split("\n")[0]?.trim();
|
|
182
|
+
return ` - ${message}${component ? ` (${component})` : ""}`;
|
|
183
|
+
}
|
|
177
184
|
//#endregion
|
|
178
185
|
export { APP_NAME_TOKEN, appShell, renderProjectShells, renderShell, shellCss, shellMarkup, shellPlugins };
|
|
179
186
|
|
|
180
187
|
//# sourceMappingURL=prerender.js.map
|
|
181
|
-
//# debugId=
|
|
188
|
+
//# debugId=305fb767-6f6e-5988-a96a-bf319e034ac6
|
package/dist/prerender.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prerender.js","sources":["../src/prerender/app-shell.ts","../src/prerender/shell-css.ts","../src/prerender/shell-loader.tsx","../src/prerender/shell.tsx"],"sourcesContent":["// Turns a rendered shell into what index.html carries: #root's markup and <head>'s CSS.\n\n/** The marker boot.tsx and the project build look for. */\nexport const SHELL_MARKER = \"data-ph-shell\";\n\n/** `generic`: Connect's chrome. `core`: core's views. `project`: a project's routes. */\nexport type AppShellKind = \"generic\" | \"core\" | \"project\";\n\n/** Rendered where the app's name goes. */\nexport const APP_NAME_TOKEN = \"__PH_SHELL_APP_NAME__\";\n\n// The app's name, delimited for the project build to fill in; the default is core's own.\n// Keep in sync with builder-tools' app-shell.ts.\nconst APP_NAME_REGION =\n \"<!--ph-shell:app-name-->Connect<!--/ph-shell:app-name-->\";\n\n// Before first paint: no sidebar in an embed, and the home view hidden off the home path.\nconst GUARD_SCRIPT =\n `(function(){try{var h=document.documentElement;` +\n `var e=new URLSearchParams(location.search).get('embed');` +\n `if(e!==null&&e!=='0'&&e!=='false')h.classList.add('ph-shell-embed');` +\n `var p=location.pathname;` +\n `if(!/\\\\/$/.test(p)||/\\\\/d\\\\//.test(p))h.classList.add('ph-shell-route')` +\n `}catch(x){}})();`;\n\n// The shell renders `/`: off it, its links mark no current page until the app routes.\nconst CURRENT_GUARD_SCRIPT =\n `(function(){if(!document.documentElement.classList.contains('ph-shell-route'))return;` +\n `document.querySelectorAll('[${SHELL_MARKER}] [aria-current]').forEach(function(e){` +\n `e.removeAttribute('aria-current');e.classList.remove('active')})})();`;\n\n// The loader fades in late so fast loads never show it; --ph-shell-t (set when\n// React re-renders the shell) keeps both animations on the navigation's clock.\nconst LOADER_CSS =\n `@keyframes ph-shell-loader-in{from{opacity:0}to{opacity:1}}` +\n `.ph-shell-loader{animation:ph-shell-loader-in .2s ease-in both;animation-delay:calc(.25s + var(--ph-shell-t,0ms))}` +\n `.ph-shell-loader>*{animation-delay:var(--ph-shell-t,0ms)}`;\n\n// The shell renders `/`: off the home path its content view hides until the app routes.\nconst ROUTE_GUARD = `.ph-shell-route [${SHELL_MARKER}] #content-view{visibility:hidden}`;\n\n// Core's header goes in an embed, and its static theme toggle shows the wrong glyph in one theme.\nconst GUARD_CSS: Record<AppShellKind, string> = {\n generic:\n `.ph-shell-embed [${SHELL_MARKER}] #sidebar{display:none}` +\n ROUTE_GUARD +\n LOADER_CSS,\n core:\n `.ph-shell-embed [${SHELL_MARKER}] header{display:none}` +\n `[${SHELL_MARKER}] header button{visibility:hidden}` +\n LOADER_CSS,\n project: ROUTE_GUARD + LOADER_CSS,\n};\n\n// Data-URI images (the login button's PNGs) weigh more than the rest of the\n// shell; a box of their size keeps the layout.\nfunction replaceInlineImages(html: string) {\n return html.replace(/<img\\b[^>]*\\bsrc=\"data:[^\"]*\"[^>]*>/g, (img) => {\n const attr = (name: string) =>\n new RegExp(`\\\\b${name}=\"([^\"]*)\"`).exec(img)?.[1];\n // A hidden variant (e.g. the hover image) needs no box.\n if (/(^| )hidden( |$)/.test(attr(\"class\") ?? \"\")) return \"\";\n const width = attr(\"width\");\n const height = attr(\"height\");\n const size = `${width ? `width:${width}px;` : \"\"}${height ? `height:${height}px;` : \"\"}`;\n return `<span style=\"display:inline-block;${size}\"></span>`;\n });\n}\n\n/** The rendered shell as #root's static markup: no scripts or title, images as\n * boxes, the app's name delimited. */\nexport function shellMarkup(rendered: string) {\n // The router's scroll restoration script is for hydration, and the page keeps\n // its own title until the app's routes set one.\n return replaceInlineImages(\n rendered\n .replace(/<script\\b[^>]*>[\\s\\S]*?<\\/script>/g, \"\")\n .replace(/<title\\b[^>]*>[\\s\\S]*?<\\/title>/g, \"\"),\n ).replaceAll(APP_NAME_TOKEN, APP_NAME_REGION);\n}\n\n/** #root's markup and <head>'s critical CSS (`css`, see shellCss) and guard.\n * `variant` names it for a server that swaps it. */\nexport function appShell(\n kind: AppShellKind,\n variant: \"generic\" | \"core\",\n markup: string,\n css: string,\n) {\n const guard = GUARD_CSS[kind];\n const marker = `${SHELL_MARKER}=\"${variant}\"`;\n return {\n // Inert: clicks and focus wait for the app; a static shell does nothing with them.\n body:\n `<div ${marker} inert style=\"display:contents\">${markup}</div>` +\n `<script ${marker}>${CURRENT_GUARD_SCRIPT}</script>`,\n head:\n `<style ${marker}>${css}${guard}</style>` +\n `<script ${marker}>${GUARD_SCRIPT}</script>`,\n };\n}\n","// The loading screen's CSS: Tailwind builds a stylesheet for just the classes its markup uses.\nimport { compile, optimize } from \"@tailwindcss/node\";\nimport { mkdtempSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nlet emptyFile: string | undefined;\nconst empty = () => {\n if (!emptyFile) {\n emptyFile = join(mkdtempSync(join(tmpdir(), \"ph-shell-\")), \"empty.css\");\n writeFileSync(emptyFile, \"\");\n }\n return emptyFile;\n};\n\n// Plain third-party CSS stays out: a vendor.css, or another package's stylesheet.\nconst isVendor = (id: string) =>\n id.endsWith(\"/vendor.css\") ||\n !(\n id.startsWith(\".\") ||\n id.startsWith(\"/\") ||\n id.startsWith(\"tailwindcss\") ||\n id.startsWith(\"@powerhousedao/\")\n );\n\nconst CLASS_ATTRIBUTE = /\\sclass=\"([^\"]*)\"/g;\n\n/** `entry`, a Tailwind stylesheet (its text `css` when given), built for the\n * classes in `markup` only: its tokens, reset and rules, without third-party CSS. */\nexport async function shellCss(\n entry: string,\n markup: string,\n css = readFileSync(entry, \"utf8\"),\n) {\n const compiler = await compile(css, {\n base: dirname(entry),\n from: entry,\n onDependency: () => {},\n customCssResolver: (id) =>\n Promise.resolve(isVendor(id) ? empty() : undefined),\n });\n const classes = new Set(\n [...markup.matchAll(CLASS_ATTRIBUTE)].flatMap((m) => m[1].split(/\\s+/)),\n );\n const built = compiler.build([...classes].filter(Boolean));\n return optimize(built, { file: entry, minify: true }).code;\n}\n","import { Icon } from \"@powerhousedao/design-system\";\n\n/** Class of the shell's loader; scripts/prerender-shell.ts fades it in. */\nexport const SHELL_LOADER_CLASS = \"ph-shell-loader\";\n\n// The static shell's \"starting\" state: a pulsing Powerhouse logo, CSS only.\nexport function ShellLoader() {\n return (\n <div\n role=\"status\"\n aria-label=\"Starting Connect\"\n className={`${SHELL_LOADER_CLASS} pointer-events-none fixed inset-0 z-10 flex items-center justify-center`}\n >\n {/* data-ph-loader-slot: a project build swaps this logo for its own\n loader (connect.branding.loader). */}\n <div\n data-ph-loader-slot=\"\"\n className=\"animate-pulse rounded-full bg-background p-4 text-foreground shadow-lg motion-reduce:animate-none\"\n >\n <Icon name=\"ConnectSmall\" size={40} />\n </div>\n </div>\n );\n}\n\n// Core's \"starting\" state: a small neutral spinner, no logo. The project's\n// loader (connect.branding.loader) is Connect-level branding, so a project\n// build swaps the spinner for it here too.\nexport function CoreShellLoader() {\n return (\n <div\n role=\"status\"\n aria-label=\"Starting\"\n className={`${SHELL_LOADER_CLASS} pointer-events-none fixed inset-0 z-10 flex items-center justify-center`}\n >\n <div\n data-ph-loader-slot=\"\"\n className=\"size-5 animate-spin rounded-full border-2 border-core-border border-t-core-muted motion-reduce:animate-none\"\n />\n </div>\n );\n}\n","// Renders the app shell at `/` before the reactor is up; `pnpm build` writes it to dist/shell.html.\nimport { createPHStore, PHStoreProvider } from \"@powerhousedao/reactor-browser\";\nimport type { AnyRoute } from \"@tanstack/react-router\";\nimport { createMemoryHistory, RouterProvider } from \"@tanstack/react-router\";\nimport { prerender } from \"react-dom/static\";\nimport {\n getConnectPluginUi,\n loadConnectPluginUi,\n registerConnectPlugins,\n resetConnectPluginUi,\n} from \"@powerhousedao/connect-core/plugins\";\nimport { primeRuntimeConfig } from \"@powerhousedao/connect-core/runtime-config\";\nimport type { RuntimePowerhouseConfig } from \"@powerhousedao/shared/connect\";\nimport { DEFAULT_CONNECT_CONFIG } from \"@powerhousedao/shared/connect\";\nimport type { AppShellKind } from \"./app-shell.js\";\nimport { APP_NAME_TOKEN, appShell, shellMarkup } from \"./app-shell.js\";\nimport { shellCss } from \"./shell-css.js\";\nimport { CoreShellLoader, ShellLoader } from \"./shell-loader.js\";\n\nexport { appShell, shellCss, shellMarkup };\nexport type { AppShellKind };\n\nasync function loadDefaultConfig(variant: ShellVariant) {\n // The config file is read at runtime; the shell renders Connect's defaults.\n // Not through the config loader: its cache is the realm's, so a dev server's\n // next render would read the variant primed last.\n primeRuntimeConfig({\n connect: {\n ...DEFAULT_CONNECT_CONFIG,\n // Core's shell is the one for a composition without a plugin that has a shell.\n composition: variant === \"core\" ? [] : undefined,\n },\n } as RuntimePowerhouseConfig);\n registerConnectPlugins(connectPlugins);\n const plugin = (await shellPlugins())[variant];\n await loadConnectPluginUi(plugin ? [{ module: plugin }] : []);\n}\n\nconst connectPlugins = () =>\n import(\"../plugins/index.js\").then((m) => m.connectPlugins);\n\n/** Each prerendered shell's plugin, whose presence in a composition picks it; core's has none. */\nexport async function shellPlugins(): Promise<\n Partial<Record<ShellVariant, string>>\n> {\n return Object.fromEntries(\n Object.entries(await connectPlugins()).flatMap(([module, definition]) =>\n definition.shell ? [[definition.shell, module]] : [],\n ),\n );\n}\n\n/** `generic`: Connect's chrome. `core`: core's views, for a composition without the generic plugin. */\nexport type ShellVariant = \"generic\" | \"core\";\n\nexport { APP_NAME_TOKEN };\n\n/** Renders the route tree at `/` before the reactor is up. `kind` picks the\n * loader: Connect's logo for its chrome, core's spinner otherwise. */\nexport async function renderShell(\n variant: ShellVariant = \"generic\",\n kind: AppShellKind = variant,\n): Promise<string> {\n await loadDefaultConfig(variant);\n // After the config: these modules read it as they evaluate.\n const [{ routeTree }, { RouterChrome }, routerModule] = await Promise.all([\n import(\"@powerhousedao/connect/route-tree\"),\n import(\"../components/route-views.js\"),\n import(\"@powerhousedao/connect-core/router\"),\n ]);\n // No reactor and no drives, as the app is until the reactor is up.\n const store = createPHStore();\n // A server router reuses the tree processed for the last variant; plugins' routes change it.\n delete (globalThis as { __TSR_CACHE__?: unknown }).__TSR_CACHE__;\n const connectRouter = routerModule.createConnectRouter({\n routeTree,\n store,\n history: createMemoryHistory({ initialEntries: [\"/\"] }),\n InnerWrap: RouterChrome,\n // The project's name is only known at its build; scripts/prerender-shell.ts marks this.\n appName: APP_NAME_TOKEN,\n // A project's layout shows its pendingComponent in place of the page.\n shell: kind === \"project\",\n pluginUi: getConnectPluginUi(),\n });\n routerModule.bindConnectRouter(connectRouter, store);\n await connectRouter.router.load();\n // A project layout's own pending view is its loader; core's spinner without one.\n const { appRoute } = routerModule.connectRoutes(routeTree as AnyRoute);\n const layoutPending = appRoute.options.pendingComponent;\n const Loader =\n kind === \"generic\"\n ? ShellLoader\n : kind === \"project\" && layoutPending\n ? () => null\n : CoreShellLoader;\n\n const errors: unknown[] = [];\n const { prelude } = await prerender(\n <PHStoreProvider store={store}>\n <RouterProvider router={connectRouter.router} />\n <Loader />\n </PHStoreProvider>,\n {\n // Inline every boundary; outlined ones need React's runtime to reveal.\n progressiveChunkSize: Number.POSITIVE_INFINITY,\n onError: (error) => {\n errors.push(error);\n },\n },\n );\n // The next variant renders the tree with its own plugins' UI.\n resetConnectPluginUi(routeTree as AnyRoute);\n // A boundary that errored renders its fallback, which is not the shell.\n if (errors.length) {\n throw new AggregateError(errors, \"The app shell failed to prerender\");\n }\n return await new Response(prelude).text();\n}\n\n/** A project's shells, one per variant: its route tree rendered at `/`, with\n * CSS that `stylesheet`, its Tailwind entry (text `css`), builds for the markup's classes. */\nexport async function renderProjectShells(stylesheet: string, css?: string) {\n const shells: Partial<Record<ShellVariant, { body: string; head: string }>> =\n {};\n for (const variant of [\"generic\", \"core\"] as const) {\n const markup = shellMarkup(await renderShell(variant, \"project\"));\n const shellStyles = await shellCss(stylesheet, markup, css);\n shells[variant] = appShell(\"project\", variant, markup, shellStyles);\n }\n return shells;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAGA,MAAa,eAAe;;AAM5B,MAAa,iBAAiB;AAI9B,MAAM,kBACJ;AAGF,MAAM,eACJ;AAQF,MAAM,uBACJ,oHAC+B,aAAa;AAK9C,MAAM,aACJ;AAKF,MAAM,cAAc,oBAAoB,aAAa;AAGrD,MAAM,YAA0C;CAC9C,SACE,oBAAoB,aAAa,4BACjC,cACA;CACF,MACE,oBAAoB,aAAa,yBAC7B,aAAa;CAEnB,SAAS,cAAc;AACzB;AAIA,SAAS,oBAAoB,MAAc;CACzC,OAAO,KAAK,QAAQ,yCAAyC,QAAQ;EACnE,MAAM,QAAQ,SACZ,IAAI,OAAO,MAAM,KAAK,WAAW,CAAC,CAAC,KAAK,GAAG,CAAC,GAAG;EAEjD,IAAI,mBAAmB,KAAK,KAAK,OAAO,KAAK,EAAE,GAAG,OAAO;EACzD,MAAM,QAAQ,KAAK,OAAO;EAC1B,MAAM,SAAS,KAAK,QAAQ;EAE5B,OAAO,qCAAqC,GAD5B,QAAQ,SAAS,MAAM,OAAO,KAAK,SAAS,UAAU,OAAO,OAAO,KACnC;CACnD,CAAC;AACH;;;AAIA,SAAgB,YAAY,UAAkB;CAG5C,OAAO,oBACL,SACG,QAAQ,sCAAsC,EAAE,CAAC,CACjD,QAAQ,oCAAoC,EAAE,CACnD,CAAC,CAAC,WAAW,gBAAgB,eAAe;AAC9C;;;AAIA,SAAgB,SACd,MACA,SACA,QACA,KACA;CACA,MAAM,QAAQ,UAAU;CACxB,MAAM,SAAS,GAAG,aAAa,IAAI,QAAQ;CAC3C,OAAO;EA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,EAAE,aAAa,aAAa,cAAc,SAAqB;CACrE,MAAM,gBAAgB,SAAS,QAAQ;CACvC,MAAM,SACJ,SAAS,YACL,cACA,SAAS,aAAa,sBACd,OACN;CAER,MAAM,SAAoB,CAAC;CAC3B,MAAM,EAAE,YAAY,MAAM,UACxB,qBAAC,iBAAD;EAAwB;EAAxB,UAAA,CACE,oBAAC,gBAAD,EAAgB,QAAQ,cAAc,OAAS,CAAA,GAC/C,oBAAC,QAAD,CAAS,CAAA,CACM;CACjB,CAAA,GAAA;EAEE,sBAAsB,OAAO;EAC7B,UAAU,UAAU;GAClB,OAAO,KAAK,KAAK;EACnB;CACF,CACF;CAEA,qBAAqB,SAAqB;CAE1C,IAAI,OAAO,QACT,MAAM,IAAI,eAAe,QAAQ,mCAAmC;CAEtE,OAAO,MAAM,IAAI,SAAS,OAAO,CAAC,CAAC,KAAK;AAC1C;;;AAIA,eAAsB,oBAAoB,YAAoB,KAAc;CAC1E,MAAM,SACJ,CAAC;CACH,KAAK,MAAM,WAAW,CAAC,WAAW,MAAM,GAAY;EAClD,MAAM,SAAS,YAAY,MAAM,YAAY,SAAS,SAAS,CAAC;EAEhE,OAAO,WAAW,SAAS,WAAW,SAAS,QAAQ,MAD7B,SAAS,YAAY,QAAQ,GAAG,CACQ;CACpE;CACA,OAAO;AACT","debug_id":"3b737e74-4acc-5d8c-af38-4a5b47101359"}
|
|
1
|
+
{"version":3,"file":"prerender.js","sources":["../src/prerender/app-shell.ts","../src/prerender/shell-css.ts","../src/prerender/shell-loader.tsx","../src/prerender/shell.tsx"],"sourcesContent":["// Turns a rendered shell into what index.html carries: #root's markup and <head>'s CSS.\n\n/** The marker boot.tsx and the project build look for. */\nexport const SHELL_MARKER = \"data-ph-shell\";\n\n/** `generic`: Connect's chrome. `core`: core's views. `project`: a project's routes. */\nexport type AppShellKind = \"generic\" | \"core\" | \"project\";\n\n/** Rendered where the app's name goes. */\nexport const APP_NAME_TOKEN = \"__PH_SHELL_APP_NAME__\";\n\n// The app's name, delimited for the project build to fill in; the default is core's own.\n// Keep in sync with builder-tools' app-shell.ts.\nconst APP_NAME_REGION =\n \"<!--ph-shell:app-name-->Connect<!--/ph-shell:app-name-->\";\n\n// Before first paint: no sidebar in an embed, and the home view hidden off the home path.\nconst GUARD_SCRIPT =\n `(function(){try{var h=document.documentElement;` +\n `var e=new URLSearchParams(location.search).get('embed');` +\n `if(e!==null&&e!=='0'&&e!=='false')h.classList.add('ph-shell-embed');` +\n `var p=location.pathname;` +\n `if(!/\\\\/$/.test(p)||/\\\\/d\\\\//.test(p))h.classList.add('ph-shell-route')` +\n `}catch(x){}})();`;\n\n// The shell renders `/`: off it, its links mark no current page until the app routes.\nconst CURRENT_GUARD_SCRIPT =\n `(function(){if(!document.documentElement.classList.contains('ph-shell-route'))return;` +\n `document.querySelectorAll('[${SHELL_MARKER}] [aria-current]').forEach(function(e){` +\n `e.removeAttribute('aria-current');e.classList.remove('active')})})();`;\n\n// The loader fades in late so fast loads never show it; --ph-shell-t (set when\n// React re-renders the shell) keeps both animations on the navigation's clock.\nconst LOADER_CSS =\n `@keyframes ph-shell-loader-in{from{opacity:0}to{opacity:1}}` +\n `.ph-shell-loader{animation:ph-shell-loader-in .2s ease-in both;animation-delay:calc(.25s + var(--ph-shell-t,0ms))}` +\n `.ph-shell-loader>*{animation-delay:var(--ph-shell-t,0ms)}`;\n\n// The shell renders `/`: off the home path its content view hides until the app routes.\nconst ROUTE_GUARD = `.ph-shell-route [${SHELL_MARKER}] #content-view{visibility:hidden}`;\n\n// Core's header goes in an embed, and its static theme toggle shows the wrong glyph in one theme.\nconst GUARD_CSS: Record<AppShellKind, string> = {\n generic:\n `.ph-shell-embed [${SHELL_MARKER}] #sidebar{display:none}` +\n ROUTE_GUARD +\n LOADER_CSS,\n core:\n `.ph-shell-embed [${SHELL_MARKER}] header{display:none}` +\n `[${SHELL_MARKER}] header button{visibility:hidden}` +\n LOADER_CSS,\n project: ROUTE_GUARD + LOADER_CSS,\n};\n\n// Data-URI images (the login button's PNGs) weigh more than the rest of the\n// shell; a box of their size keeps the layout.\nfunction replaceInlineImages(html: string) {\n return html.replace(/<img\\b[^>]*\\bsrc=\"data:[^\"]*\"[^>]*>/g, (img) => {\n const attr = (name: string) =>\n new RegExp(`\\\\b${name}=\"([^\"]*)\"`).exec(img)?.[1];\n // A hidden variant (e.g. the hover image) needs no box.\n if (/(^| )hidden( |$)/.test(attr(\"class\") ?? \"\")) return \"\";\n const width = attr(\"width\");\n const height = attr(\"height\");\n const size = `${width ? `width:${width}px;` : \"\"}${height ? `height:${height}px;` : \"\"}`;\n return `<span style=\"display:inline-block;${size}\"></span>`;\n });\n}\n\n/** The rendered shell as #root's static markup: no scripts or title, images as\n * boxes, the app's name delimited. */\nexport function shellMarkup(rendered: string) {\n // The router's scroll restoration script is for hydration, and the page keeps\n // its own title until the app's routes set one.\n return replaceInlineImages(\n rendered\n .replace(/<script\\b[^>]*>[\\s\\S]*?<\\/script>/g, \"\")\n .replace(/<title\\b[^>]*>[\\s\\S]*?<\\/title>/g, \"\"),\n ).replaceAll(APP_NAME_TOKEN, APP_NAME_REGION);\n}\n\n/** #root's markup and <head>'s critical CSS (`css`, see shellCss) and guard.\n * `variant` names it for a server that swaps it. */\nexport function appShell(\n kind: AppShellKind,\n variant: \"generic\" | \"core\",\n markup: string,\n css: string,\n) {\n const guard = GUARD_CSS[kind];\n const marker = `${SHELL_MARKER}=\"${variant}\"`;\n return {\n // Inert: clicks and focus wait for the app; a static shell does nothing with them.\n body:\n `<div ${marker} inert style=\"display:contents\">${markup}</div>` +\n `<script ${marker}>${CURRENT_GUARD_SCRIPT}</script>`,\n head:\n `<style ${marker}>${css}${guard}</style>` +\n `<script ${marker}>${GUARD_SCRIPT}</script>`,\n };\n}\n","// The loading screen's CSS: Tailwind builds a stylesheet for just the classes its markup uses.\nimport { compile, optimize } from \"@tailwindcss/node\";\nimport { mkdtempSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nlet emptyFile: string | undefined;\nconst empty = () => {\n if (!emptyFile) {\n emptyFile = join(mkdtempSync(join(tmpdir(), \"ph-shell-\")), \"empty.css\");\n writeFileSync(emptyFile, \"\");\n }\n return emptyFile;\n};\n\n// Plain third-party CSS stays out: a vendor.css, or another package's stylesheet.\nconst isVendor = (id: string) =>\n id.endsWith(\"/vendor.css\") ||\n !(\n id.startsWith(\".\") ||\n id.startsWith(\"/\") ||\n id.startsWith(\"tailwindcss\") ||\n id.startsWith(\"@powerhousedao/\")\n );\n\nconst CLASS_ATTRIBUTE = /\\sclass=\"([^\"]*)\"/g;\n\n/** `entry`, a Tailwind stylesheet (its text `css` when given), built for the\n * classes in `markup` only: its tokens, reset and rules, without third-party CSS. */\nexport async function shellCss(\n entry: string,\n markup: string,\n css = readFileSync(entry, \"utf8\"),\n) {\n const compiler = await compile(css, {\n base: dirname(entry),\n from: entry,\n onDependency: () => {},\n customCssResolver: (id) =>\n Promise.resolve(isVendor(id) ? empty() : undefined),\n });\n const classes = new Set(\n [...markup.matchAll(CLASS_ATTRIBUTE)].flatMap((m) => m[1].split(/\\s+/)),\n );\n const built = compiler.build([...classes].filter(Boolean));\n return optimize(built, { file: entry, minify: true }).code;\n}\n","import { Icon } from \"@powerhousedao/design-system\";\n\n/** Class of the shell's loader; scripts/prerender-shell.ts fades it in. */\nexport const SHELL_LOADER_CLASS = \"ph-shell-loader\";\n\n// The static shell's \"starting\" state: a pulsing Powerhouse logo, CSS only.\nexport function ShellLoader() {\n return (\n <div\n role=\"status\"\n aria-label=\"Starting Connect\"\n className={`${SHELL_LOADER_CLASS} pointer-events-none fixed inset-0 z-10 flex items-center justify-center`}\n >\n {/* data-ph-loader-slot: a project build swaps this logo for its own\n loader (connect.branding.loader). */}\n <div\n data-ph-loader-slot=\"\"\n className=\"animate-pulse rounded-full bg-background p-4 text-foreground shadow-lg motion-reduce:animate-none\"\n >\n <Icon name=\"ConnectSmall\" size={40} />\n </div>\n </div>\n );\n}\n\n// Core's \"starting\" state: a small neutral spinner, no logo. The project's\n// loader (connect.branding.loader) is Connect-level branding, so a project\n// build swaps the spinner for it here too.\nexport function CoreShellLoader() {\n return (\n <div\n role=\"status\"\n aria-label=\"Starting\"\n className={`${SHELL_LOADER_CLASS} pointer-events-none fixed inset-0 z-10 flex items-center justify-center`}\n >\n <div\n data-ph-loader-slot=\"\"\n className=\"size-5 animate-spin rounded-full border-2 border-core-border border-t-core-muted motion-reduce:animate-none\"\n />\n </div>\n );\n}\n","// Renders the app shell at `/` before the reactor is up; `pnpm build` writes it to dist/shell.html.\nimport { createPHStore, PHStoreProvider } from \"@powerhousedao/reactor-browser\";\nimport type { AnyRoute } from \"@tanstack/react-router\";\nimport { createMemoryHistory, RouterProvider } from \"@tanstack/react-router\";\nimport { prerender } from \"react-dom/static\";\nimport {\n getConnectPluginUi,\n loadConnectPluginUi,\n registerConnectPlugins,\n resetConnectPluginUi,\n} from \"@powerhousedao/connect-core/plugins\";\nimport { primeRuntimeConfig } from \"@powerhousedao/connect-core/runtime-config\";\nimport type { RuntimePowerhouseConfig } from \"@powerhousedao/shared/connect\";\nimport { DEFAULT_CONNECT_CONFIG } from \"@powerhousedao/shared/connect\";\nimport type { AppShellKind } from \"./app-shell.js\";\nimport { APP_NAME_TOKEN, appShell, shellMarkup } from \"./app-shell.js\";\nimport { shellCss } from \"./shell-css.js\";\nimport { CoreShellLoader, ShellLoader } from \"./shell-loader.js\";\n\nexport { appShell, shellCss, shellMarkup };\nexport type { AppShellKind };\n\nasync function loadDefaultConfig(variant: ShellVariant) {\n // The config file is read at runtime; the shell renders Connect's defaults.\n // Not through the config loader: its cache is the realm's, so a dev server's\n // next render would read the variant primed last.\n primeRuntimeConfig({\n connect: {\n ...DEFAULT_CONNECT_CONFIG,\n // Core's shell is the one for a composition without a plugin that has a shell.\n composition: variant === \"core\" ? [] : undefined,\n },\n } as RuntimePowerhouseConfig);\n registerConnectPlugins(connectPlugins);\n const plugin = (await shellPlugins())[variant];\n await loadConnectPluginUi(plugin ? [{ module: plugin }] : []);\n}\n\nconst connectPlugins = () =>\n import(\"../plugins/index.js\").then((m) => m.connectPlugins);\n\n/** Each prerendered shell's plugin, whose presence in a composition picks it; core's has none. */\nexport async function shellPlugins(): Promise<\n Partial<Record<ShellVariant, string>>\n> {\n return Object.fromEntries(\n Object.entries(await connectPlugins()).flatMap(([module, definition]) =>\n definition.shell ? [[definition.shell, module]] : [],\n ),\n );\n}\n\n/** `generic`: Connect's chrome. `core`: core's views, for a composition without the generic plugin. */\nexport type ShellVariant = \"generic\" | \"core\";\n\nexport { APP_NAME_TOKEN };\n\n/** Renders the route tree at `/` before the reactor is up. `kind` picks the\n * loader: Connect's logo for its chrome, core's spinner otherwise. */\nexport async function renderShell(\n variant: ShellVariant = \"generic\",\n kind: AppShellKind = variant,\n): Promise<string> {\n await loadDefaultConfig(variant);\n // After the config: these modules read it as they evaluate.\n const [{ routeTree }, { RouterChrome }, routerModule] = await Promise.all([\n import(\"@powerhousedao/connect/route-tree\"),\n import(\"../components/route-views.js\"),\n import(\"@powerhousedao/connect-core/router\"),\n ]);\n // No reactor and no drives, as the app is until the reactor is up.\n const store = createPHStore();\n // A server router reuses the tree processed for the last variant; plugins' routes change it.\n delete (globalThis as { __TSR_CACHE__?: unknown }).__TSR_CACHE__;\n const connectRouter = routerModule.createConnectRouter({\n routeTree,\n store,\n history: createMemoryHistory({ initialEntries: [\"/\"] }),\n InnerWrap: RouterChrome,\n // The project's name is only known at its build; scripts/prerender-shell.ts marks this.\n appName: APP_NAME_TOKEN,\n // A project's layout shows its pendingComponent in place of the page.\n shell: kind === \"project\",\n pluginUi: getConnectPluginUi(),\n });\n routerModule.bindConnectRouter(connectRouter, store);\n await connectRouter.router.load();\n // A project layout's own pending view is its loader; core's spinner without one.\n const { appRoute } = routerModule.connectRoutes(routeTree as AnyRoute);\n const layoutPending = appRoute.options.pendingComponent;\n const Loader =\n kind === \"generic\"\n ? ShellLoader\n : kind === \"project\" && layoutPending\n ? () => null\n : CoreShellLoader;\n\n const errors: unknown[] = [];\n const causes: string[] = [];\n const { prelude } = await prerender(\n <PHStoreProvider store={store}>\n <RouterProvider router={connectRouter.router} />\n <Loader />\n </PHStoreProvider>,\n {\n // Inline every boundary; outlined ones need React's runtime to reveal.\n progressiveChunkSize: Number.POSITIVE_INFINITY,\n onError: (error, info) => {\n errors.push(error);\n causes.push(describeRenderError(error, info?.componentStack));\n },\n },\n );\n // The next variant renders the tree with its own plugins' UI.\n resetConnectPluginUi(routeTree as AnyRoute);\n // A boundary that errored renders its fallback, which is not the shell.\n if (errors.length) {\n throw new AggregateError(\n errors,\n `The app shell failed to prerender:\\n${causes.join(\"\\n\")}`,\n );\n }\n return await new Response(prelude).text();\n}\n\n/** A project's shells, one per variant: its route tree rendered at `/`, with\n * CSS that `stylesheet`, its Tailwind entry (text `css`), builds for the markup's classes. */\nexport async function renderProjectShells(stylesheet: string, css?: string) {\n const shells: Partial<Record<ShellVariant, { body: string; head: string }>> =\n {};\n for (const variant of [\"generic\", \"core\"] as const) {\n const markup = shellMarkup(await renderShell(variant, \"project\"));\n const shellStyles = await shellCss(stylesheet, markup, css);\n shells[variant] = appShell(\"project\", variant, markup, shellStyles);\n }\n return shells;\n}\n\n// The message and the component it came from: the stack is Connect's own code.\nfunction describeRenderError(error: unknown, componentStack?: string | null) {\n const message = error instanceof Error ? error.message : String(error);\n const component = componentStack?.trim().split(\"\\n\")[0]?.trim();\n return ` - ${message}${component ? ` (${component})` : \"\"}`;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAGA,MAAa,eAAe;;AAM5B,MAAa,iBAAiB;AAI9B,MAAM,kBACJ;AAGF,MAAM,eACJ;AAQF,MAAM,uBACJ,oHAC+B,aAAa;AAK9C,MAAM,aACJ;AAKF,MAAM,cAAc,oBAAoB,aAAa;AAGrD,MAAM,YAA0C;CAC9C,SACE,oBAAoB,aAAa,4BACjC,cACA;CACF,MACE,oBAAoB,aAAa,yBAC7B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