@powerhousedao/ph-cli 6.2.2-dev.8 → 6.2.2-dev.80
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/build-C-A5-ipO.mjs +4 -0
- package/dist/{build-B5LEeRPm.mjs → build-uQXq6_HU.mjs} +26 -4
- package/dist/build-uQXq6_HU.mjs.map +1 -0
- package/dist/{cli-connect-override-CFsTgKB6.mjs → cli-connect-override-D3hh4aH_.mjs} +5 -3
- package/dist/cli-connect-override-D3hh4aH_.mjs.map +1 -0
- package/dist/cli.mjs +29 -19
- package/dist/cli.mjs.map +1 -1
- package/dist/{connect-build-BtaMnrYu.mjs → connect-build-WL4axo4z.mjs} +6 -6
- package/dist/{connect-build-BtaMnrYu.mjs.map → connect-build-WL4axo4z.mjs.map} +1 -1
- package/dist/{connect-config-O3qXExg9.mjs → connect-config-BWGiW3IB.mjs} +7 -5
- package/dist/connect-config-BWGiW3IB.mjs.map +1 -0
- package/dist/connect-studio-BIQzyq5B.mjs +5 -0
- package/dist/{connect-studio-sRLuTabi.mjs → connect-studio-D6rfWCNB.mjs} +4 -4
- package/dist/{connect-studio-sRLuTabi.mjs.map → connect-studio-D6rfWCNB.mjs.map} +1 -1
- package/dist/{inspect-CKdafPbC.mjs → inspect-DXjbQEV_.mjs} +4 -4
- package/dist/{inspect-CKdafPbC.mjs.map → inspect-DXjbQEV_.mjs.map} +1 -1
- package/dist/{migrate-BJQvY88v.mjs → migrate-jGKfE02L.mjs} +4 -4
- package/dist/{migrate-BJQvY88v.mjs.map → migrate-jGKfE02L.mjs.map} +1 -1
- package/dist/{utils-DPGwKNam.mjs → utils-BzwczAW-.mjs} +3 -3
- package/dist/{utils-BaTZlyL3.mjs → utils-C4isxXSO.mjs} +4 -4
- package/dist/{utils-BaTZlyL3.mjs.map → utils-C4isxXSO.mjs.map} +1 -1
- package/dist/{vetra-D9MTB556.mjs → vetra-DkF6EJMY.mjs} +141 -6
- package/dist/vetra-DkF6EJMY.mjs.map +1 -0
- package/package.json +12 -12
- package/dist/build-B5LEeRPm.mjs.map +0 -1
- package/dist/build-CMgv-erS.mjs +0 -4
- package/dist/cli-connect-override-CFsTgKB6.mjs.map +0 -1
- package/dist/connect-config-O3qXExg9.mjs.map +0 -1
- package/dist/connect-studio-DQ6dRWlL.mjs +0 -5
- package/dist/vetra-D9MTB556.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inspect-
|
|
1
|
+
{"version":3,"file":"inspect-DXjbQEV_.mjs","sources":["../src/services/inspect.ts"],"sourcesContent":["import type { Manifest } from \"@powerhousedao/shared/document-model\";\nimport fs from \"node:fs\";\nimport type { InspectArgs } from \"../types.js\";\nimport { getProjectInfo } from \"../utils.js\";\nexport function startInspect(args: InspectArgs) {\n if (args.debug) {\n console.log(\">>> command arguments\", args);\n }\n\n const projectInfo = getProjectInfo(args.debug);\n const { packageName } = args;\n\n if (args.debug) {\n console.log(\"\\n>>> projectInfo\", projectInfo);\n }\n\n try {\n const loadManifest = (path: string) =>\n JSON.parse(fs.readFileSync(path, \"utf-8\")) as Manifest;\n const manifest = loadManifest(\n `${process.cwd()}/node_modules/${packageName}/dist/powerhouse.manifest.json`,\n );\n\n console.log(manifest.name);\n if (manifest.documentModels) {\n console.log(\"\\nDocument Models:\");\n manifest.documentModels.forEach((model) => {\n console.log(`- ${model.name} (${model.id})`);\n });\n }\n\n if (manifest.editors) {\n console.log(\"\\nEditors:\");\n manifest.editors.forEach((editor) => {\n console.log(`- ${editor.name} (${editor.id})`);\n });\n }\n\n if (manifest.processors) {\n console.log(\"\\nProcessors:\");\n manifest.processors.forEach((processor) => {\n console.log(`- ${processor.name} (${processor.id})`);\n });\n }\n\n if (manifest.subgraphs) {\n console.log(\"\\nSubgraphs:\");\n manifest.subgraphs.forEach((subgraph) => {\n console.log(`- ${subgraph.name} (${subgraph.id})`);\n });\n }\n } catch (e) {\n if (args.debug) {\n console.error(e);\n } else {\n console.log(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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]="5917a8da-bcbd-52a8-af0d-9c6d60ae5475")}catch(e){}}();
|
|
3
3
|
import { execSync } from "node:child_process";
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
4
5
|
import { dirname, join } from "node:path";
|
|
5
6
|
import { detect, resolveCommand } from "package-manager-detector";
|
|
6
7
|
import { fetchPackageVersionFromNpmRegistry, injectPnpmAllowBuilds } from "@powerhousedao/shared/clis";
|
|
7
|
-
import { readFileSync } from "node:fs";
|
|
8
8
|
import { fileURLToPath } from "node:url";
|
|
9
9
|
//#region src/services/migrate.ts
|
|
10
10
|
function getBundledPhCliVersion() {
|
|
@@ -79,5 +79,5 @@ async function startMigrate({ versionPositional, version, force, debug }) {
|
|
|
79
79
|
//#endregion
|
|
80
80
|
export { startMigrate };
|
|
81
81
|
|
|
82
|
-
//# sourceMappingURL=migrate-
|
|
83
|
-
//# debugId=
|
|
82
|
+
//# sourceMappingURL=migrate-jGKfE02L.mjs.map
|
|
83
|
+
//# debugId=5917a8da-bcbd-52a8-af0d-9c6d60ae5475
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrate-
|
|
1
|
+
{"version":3,"file":"migrate-jGKfE02L.mjs","sources":["../src/services/migrate.ts"],"sourcesContent":["import {\n fetchPackageVersionFromNpmRegistry,\n injectPnpmAllowBuilds,\n} from \"@powerhousedao/shared/clis\";\nimport { execSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { detect, resolveCommand } from \"package-manager-detector\";\nimport type { MigrateArgs } from \"../types.js\";\n\nfunction getBundledPhCliVersion(): string | undefined {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let i = 0; i < 5; i++) {\n try {\n const pkg = JSON.parse(\n readFileSync(join(dir, \"package.json\"), \"utf8\"),\n ) as { name?: string; version?: string };\n if (pkg.name === \"@powerhousedao/ph-cli\") return pkg.version;\n } catch {\n // keep walking\n }\n dir = dirname(dir);\n }\n}\n\nexport function resolveCodegenVersion(\n codegenMod: Record<string, unknown>,\n): string | undefined {\n const getter = codegenMod.getCodegenVersion;\n if (typeof getter === \"function\") {\n const v = (getter as () => unknown)();\n if (typeof v === \"string\") return v;\n }\n return undefined;\n}\n\nexport function assertCodegenMatchesBundled(args: {\n codegenVersion: string | undefined;\n bundledVersion: string | undefined;\n force: boolean;\n}): void {\n const { codegenVersion, bundledVersion, force } = args;\n if (force) return;\n if (!codegenVersion) {\n throw new Error(\n `@powerhousedao/codegen is older than this ph-cli expects (no version export). ` +\n `Reinstall ph-cli to bring a matching codegen, or re-run with --force.`,\n );\n }\n if (bundledVersion && codegenVersion !== bundledVersion) {\n throw new Error(\n `@powerhousedao/codegen@${codegenVersion} does not match ph-cli@${bundledVersion}. ` +\n `Reinstall to align versions, or re-run with --force.`,\n );\n }\n}\n\nexport async function startMigrate({\n versionPositional,\n version,\n force,\n debug,\n}: MigrateArgs) {\n const requested = versionPositional ?? version;\n if (debug) console.log(`[migrate] requested version: ${requested}`);\n\n let targetVersion: string | undefined;\n try {\n targetVersion = await fetchPackageVersionFromNpmRegistry(\n `@powerhousedao/ph-cli@${requested}`,\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n if (!force) {\n throw new Error(\n `Failed to resolve \"${requested}\" from the npm registry: ${reason}\\nRe-run with --force to migrate using the installed version.`,\n { cause: error },\n );\n }\n if (debug) {\n console.log(\n `[migrate] failed to resolve target version, --force is set, falling back to bundled codegen: ${reason}`,\n );\n }\n }\n\n const bundledVersion = getBundledPhCliVersion();\n if (debug) {\n console.log(\n `[migrate] resolved target version: ${targetVersion ?? \"(unknown)\"}`,\n );\n console.log(\n `[migrate] current ph-cli version: ${bundledVersion ?? \"(unknown)\"}`,\n );\n }\n\n if (!targetVersion || force || targetVersion === bundledVersion) {\n if (debug) console.log(`[migrate] running migrate from bundled codegen`);\n const codegenMod = await import(\"@powerhousedao/codegen\");\n const codegenVersion = resolveCodegenVersion(\n codegenMod as unknown as Record<string, unknown>,\n );\n assertCodegenMatchesBundled({\n codegenVersion,\n bundledVersion,\n force: Boolean(force),\n });\n console.log(\n `Running migrate with @powerhousedao/codegen@${codegenVersion ?? \"unknown\"}`,\n );\n await codegenMod.migrate(targetVersion ?? requested);\n return;\n }\n\n const agent = (await detect())?.agent ?? \"npm\";\n const resolved = resolveCommand(agent, \"execute\", [\n `@powerhousedao/ph-cli@${targetVersion}`,\n \"migrate\",\n \"--version\",\n targetVersion,\n ...(debug ? [\"--debug\"] : []),\n ]);\n if (!resolved) {\n throw new Error(\n `Failed to resolve execute command for package manager \"${agent}\".`,\n );\n }\n\n injectPnpmAllowBuilds(agent, resolved);\n\n const command = `${resolved.command} ${resolved.args.join(\" \")}`;\n if (debug) {\n console.log(`[migrate] detected package manager: ${agent}`);\n console.log(`[migrate] re-executing: ${command}`);\n }\n execSync(command, { stdio: \"inherit\" });\n}\n"],"names":[],"mappings":";;;;;;;;;AAWA,SAAS,yBAA6C;CACpD,IAAI,MAAM,QAAQ,cAAc,OAAO,KAAK,IAAI,CAAC;AACjD,MAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,MAAI;GACF,MAAM,MAAM,KAAK,MACf,aAAa,KAAK,KAAK,eAAe,EAAE,OAAO,CAChD;AACD,OAAI,IAAI,SAAS,wBAAyB,QAAO,IAAI;UAC/C;AAGR,QAAM,QAAQ,IAAI;;;AAItB,SAAgB,sBACd,YACoB;CACpB,MAAM,SAAS,WAAW;AAC1B,KAAI,OAAO,WAAW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AI,QAAQ,CAAC,UAAU,GAAG,EAAE;EAC7B,CAAC;AACF,KAAI,CAAC,SACH,OAAM,IAAI,MACR,0DAA0D,MAAM,IACjE;AAGH,uBAAsB,OAAO,SAAS;CAEtC,MAAM,UAAU,GAAG,SAAS,QAAQ,GAAG,SAAS,KAAK,KAAK,IAAI;AAC9D,KAAI,OAAO;AACT,UAAQ,IAAI,uCAAuC,QAAQ;AAC3D,UAAQ,IAAI,2BAA2B,UAAU;;AAEnD,UAAS,SAAS,EAAE,OAAO,WAAW,CAAC","debug_id":"5917a8da-bcbd-52a8-af0d-9c6d60ae5475"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { d as updateConfigFile, p as updateStylesFile, u as removeStylesImports } from "./utils-
|
|
1
|
+
import { d as updateConfigFile, p as updateStylesFile, u as removeStylesImports } from "./utils-C4isxXSO.mjs";
|
|
2
2
|
export { removeStylesImports, updateConfigFile, updateStylesFile };
|
|
3
|
-
!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]="
|
|
4
|
-
//# debugId=
|
|
3
|
+
!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]="33804f1d-c6ad-5650-aedb-dd51a31d17aa")}catch(e){}}();
|
|
4
|
+
//# debugId=33804f1d-c6ad-5650-aedb-dd51a31d17aa
|
|
@@ -1,7 +1,7 @@
|
|
|
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 path, { dirname } from "node:path";
|
|
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]="73159d3c-22a7-5dc6-8bd4-7b15f3b94c79")}catch(e){}}();
|
|
4
3
|
import fs from "node:fs";
|
|
4
|
+
import path, { dirname } from "node:path";
|
|
5
5
|
import crypto from "node:crypto";
|
|
6
6
|
import { homedir } from "node:os";
|
|
7
7
|
//#region src/utils.ts
|
|
@@ -161,5 +161,5 @@ function removeStylesImports(dependencies, projectPath) {
|
|
|
161
161
|
//#endregion
|
|
162
162
|
export { generateProjectDriveId as a, isPowerhouseProject as c, updateConfigFile as d, updatePackagesArray as f, findNodeProjectRoot as i, packageManagers as l, POWERHOUSE_GLOBAL_DIR as n, getPackageManagerFromLockfile as o, updateStylesFile as p, defaultPathValidation as r, getProjectInfo as s, POWERHOUSE_CONFIG_FILE as t, removeStylesImports as u };
|
|
163
163
|
|
|
164
|
-
//# sourceMappingURL=utils-
|
|
165
|
-
//# debugId=
|
|
164
|
+
//# sourceMappingURL=utils-C4isxXSO.mjs.map
|
|
165
|
+
//# debugId=73159d3c-22a7-5dc6-8bd4-7b15f3b94c79
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils-BaTZlyL3.mjs","sources":["../src/utils.ts"],"sourcesContent":["import type { PowerhouseConfig } from \"@powerhousedao/config\";\nimport crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport path, { dirname } from \"node:path\";\nexport const POWERHOUSE_CONFIG_FILE = \"powerhouse.config.json\";\nexport const POWERHOUSE_GLOBAL_DIR = path.join(homedir(), \".ph\");\nexport const SUPPORTED_PACKAGE_MANAGERS = [\"npm\", \"yarn\", \"pnpm\", \"bun\"];\n\nexport const packageManagers = {\n bun: {\n globalPathRegexp: /[\\\\/].bun[\\\\/]/,\n installCommand: \"bun add {{dependency}}\",\n uninstallCommand: \"bun remove {{dependency}}\",\n workspaceOption: \"\",\n lockfile: \"bun.lock\",\n updateCommand: \"bun update {{dependency}}\",\n buildAffected: \"bun run build:affected\",\n },\n pnpm: {\n globalPathRegexp: /[\\\\/]pnpm[\\\\/]/,\n installCommand: \"pnpm add {{dependency}}\",\n uninstallCommand: \"pnpm remove {{dependency}}\",\n workspaceOption: \"--workspace-root\",\n lockfile: \"pnpm-lock.yaml\",\n updateCommand: \"pnpm update {{dependency}}\",\n buildAffected: \"pnpm run build:affected\",\n },\n yarn: {\n globalPathRegexp: /[\\\\/]yarn[\\\\/]/,\n installCommand: \"yarn add {{dependency}}\",\n uninstallCommand: \"yarn remove {{dependency}}\",\n workspaceOption: \"-W\",\n lockfile: \"yarn.lock\",\n updateCommand: \"yarn upgrade {{dependency}}\",\n buildAffected: \"yarn run build:affected\",\n },\n npm: {\n installCommand: \"npm install {{dependency}}\",\n uninstallCommand: \"npm uninstall {{dependency}}\",\n workspaceOption: \"\",\n lockfile: \"package-lock.json\",\n updateCommand: \"npm update {{dependency}} --save\",\n buildAffected: \"npm run build:affected\",\n },\n};\n\ntype PathValidation = (dir: string) => boolean;\n\nexport type PackageManager = \"npm\" | \"yarn\" | \"pnpm\" | \"bun\";\n\nexport type ProjectInfo = {\n isGlobal: boolean;\n path: string;\n packageManager: PackageManager;\n};\n\nexport function defaultPathValidation() {\n return true;\n}\n\nexport function isPowerhouseProject(dir: string) {\n const powerhouseConfigPath = path.join(dir, POWERHOUSE_CONFIG_FILE);\n\n return fs.existsSync(powerhouseConfigPath);\n}\n\nexport function findNodeProjectRoot(\n dir: string,\n pathValidation: PathValidation = defaultPathValidation,\n) {\n const packageJsonPath = path.join(dir, \"package.json\");\n\n if (fs.existsSync(packageJsonPath) && pathValidation(dir)) {\n return dir;\n }\n\n const parentDir = dirname(dir);\n\n if (parentDir === dir) {\n return null;\n }\n\n return findNodeProjectRoot(parentDir, pathValidation);\n}\n\nexport function getProjectInfo(debug?: boolean): ProjectInfo {\n const currentPath = process.cwd();\n\n if (debug) {\n console.log(\">>> currentPath\", currentPath);\n }\n\n const projectPath = findNodeProjectRoot(currentPath, isPowerhouseProject);\n\n if (!projectPath) {\n return {\n isGlobal: true,\n path: POWERHOUSE_GLOBAL_DIR,\n packageManager: getPackageManagerFromLockfile(POWERHOUSE_GLOBAL_DIR),\n };\n }\n\n return {\n isGlobal: false,\n path: projectPath,\n packageManager: getPackageManagerFromLockfile(projectPath),\n };\n}\n\n/**\n * Generates a unique drive ID based on the project path.\n * The same project path will always generate the same ID.\n * @param name - The name prefix for the drive ID (e.g., \"vetra\", \"powerhouse\")\n * @returns A unique drive ID in the format \"{name}-{hash}\"\n */\nexport function generateProjectDriveId(name: string): string {\n const projectInfo = getProjectInfo();\n const hash = crypto\n .createHash(\"sha256\")\n .update(projectInfo.path)\n .digest(\"hex\");\n const shortHash = hash.substring(0, 8);\n return `${name}-${shortHash}`;\n}\n\nexport function getPackageManagerFromLockfile(dir: string): PackageManager {\n if (fs.existsSync(path.join(dir, packageManagers.pnpm.lockfile))) {\n return \"pnpm\";\n } else if (fs.existsSync(path.join(dir, packageManagers.yarn.lockfile))) {\n return \"yarn\";\n } else if (fs.existsSync(path.join(dir, packageManagers.bun.lockfile))) {\n return \"bun\";\n }\n\n return \"npm\";\n}\n\nexport function updatePackagesArray(\n currentPackages: PowerhouseConfig[\"packages\"] = [],\n dependencies: { name: string; version: string | undefined }[],\n task: \"install\" | \"uninstall\" = \"install\",\n provider: \"registry\" | \"local\" = \"registry\",\n): PowerhouseConfig[\"packages\"] {\n const isInstall = task === \"install\";\n const mappedPackages = dependencies.map((dep) => ({\n packageName: dep.name,\n version: dep.version,\n provider,\n }));\n\n if (isInstall) {\n // Overwrite existing package if version is different\n const filteredPackages = currentPackages.filter(\n (pkg) => !dependencies.find((dep) => dep.name === pkg.packageName),\n );\n return [...filteredPackages, ...mappedPackages];\n }\n\n return currentPackages.filter(\n (pkg) => !dependencies.map((dep) => dep.name).includes(pkg.packageName),\n );\n}\n\n// Modify updateConfigFile to use the new function\nexport function updateConfigFile(\n dependencies: { name: string; version: string | undefined }[],\n projectPath: string,\n task: \"install\" | \"uninstall\" = \"install\",\n provider: \"registry\" | \"local\" = \"registry\",\n registryUrl?: string,\n registryUrlExplicit = false,\n) {\n const configPath = path.join(projectPath, POWERHOUSE_CONFIG_FILE);\n\n if (!fs.existsSync(configPath)) {\n throw new Error(\n `powerhouse.config.json file not found. projectPath: ${projectPath}`,\n );\n }\n\n const config = JSON.parse(\n fs.readFileSync(configPath, \"utf-8\"),\n ) as PowerhouseConfig;\n\n const updatedConfig: PowerhouseConfig = {\n ...config,\n packages: updatePackagesArray(\n config.packages,\n dependencies,\n task,\n provider,\n ),\n };\n\n if (\n task === \"install\" &&\n registryUrl &&\n (registryUrlExplicit || !config.packageRegistryUrl) &&\n dependencies.length > 0\n ) {\n updatedConfig.packageRegistryUrl = registryUrl;\n }\n\n fs.writeFileSync(configPath, JSON.stringify(updatedConfig, null, 2));\n}\n\n/**\n * Recursively searches for a specific file by traversing up the directory tree.\n * Starting from the given path, it checks each parent directory until it finds\n * the target file or reaches the root directory.\n *\n * @param startPath - The absolute path of the directory to start searching from\n * @param targetFile - The name of the file to search for (e.g., 'package.json', 'pnpm-workspace.yaml')\n * @returns The absolute path of the directory containing the target file, or null if not found\n *\n * @example\n * // Find the workspace root directory\n * const workspaceRoot = findContainerDirectory('/path/to/project/src', 'pnpm-workspace.yaml');\n *\n * // Find the nearest package.json\n * const packageDir = findContainerDirectory('/path/to/project/src/components', 'package.json');\n */\nexport const findContainerDirectory = (\n startPath: string,\n targetFile: string,\n): string | null => {\n const filePath = path.join(startPath, targetFile);\n\n if (fs.existsSync(filePath)) {\n return startPath;\n }\n\n const parentDir = path.dirname(startPath);\n\n //reached the root directory and haven't found the file\n if (parentDir === startPath) {\n return null;\n }\n\n return findContainerDirectory(parentDir, targetFile);\n};\n\n/**\n * Updates the styles.css file to include imports for newly installed packages\n * @param dependencies - Array of dependencies that were installed\n * @param projectPath - Path to the project root\n */\nexport function updateStylesFile(\n dependencies: { name: string; version: string | undefined }[],\n projectPath: string,\n) {\n const stylesPath = path.join(projectPath, \"style.css\");\n\n // Check if styles.css exists\n if (!fs.existsSync(stylesPath)) {\n console.warn(\"⚠️ Warning: style.css file not found in project root\");\n return;\n }\n\n const currentStyles = fs.readFileSync(stylesPath, \"utf-8\");\n let updatedStyles = currentStyles;\n\n for (const dep of dependencies) {\n const cssPath = `./node_modules/${dep.name}/dist/style.css`;\n const fullCssPath = path.join(projectPath, cssPath);\n const importStatement = `@import '${cssPath}';`;\n\n // Check if the CSS file exists\n if (!fs.existsSync(fullCssPath)) {\n console.warn(`⚠️ Warning: CSS file not found at ${cssPath}`);\n continue;\n }\n\n // Check if import already exists\n if (currentStyles.includes(importStatement)) {\n continue;\n }\n\n // Find the last @import statement\n const importLines = currentStyles\n .split(\"\\n\")\n .filter((line) => line.trim().startsWith(\"@import\"));\n const lastImport = importLines[importLines.length - 1];\n\n if (lastImport) {\n // Insert new import after the last existing import\n updatedStyles = currentStyles.replace(\n lastImport,\n `${lastImport}\\n${importStatement}`,\n );\n } else {\n // If no imports exist, add at the top of the file\n updatedStyles = `${importStatement}\\n${currentStyles}`;\n }\n }\n\n // Only write if changes were made\n if (updatedStyles !== currentStyles) {\n fs.writeFileSync(stylesPath, updatedStyles);\n }\n}\n\n/**\n * Removes CSS imports for uninstalled packages from styles.css\n */\nexport function removeStylesImports(\n dependencies: { name: string; version: string | undefined }[],\n projectPath: string,\n) {\n const stylesPath = path.join(projectPath, \"style.css\");\n\n // Check if styles.css exists\n if (!fs.existsSync(stylesPath)) {\n console.warn(\"⚠️ Warning: style.css file not found in project root\");\n return;\n }\n\n const currentStyles = fs.readFileSync(stylesPath, \"utf-8\");\n let updatedStyles = currentStyles;\n\n for (const dep of dependencies) {\n const cssPath = `./node_modules/${dep.name}/dist/style.css`;\n const importStatement = `@import '${cssPath}';`;\n\n // Remove the import line if it exists\n const lines = updatedStyles.split(\"\\n\");\n const filteredLines = lines.filter(\n (line) => !line.trim().includes(importStatement),\n );\n\n if (filteredLines.length !== lines.length) {\n updatedStyles = filteredLines.join(\"\\n\");\n }\n }\n\n // Only write if changes were made\n if (updatedStyles !== currentStyles) {\n fs.writeFileSync(stylesPath, updatedStyles);\n }\n}\n"],"names":[],"mappings":";;;;;;;AAKA,MAAa,yBAAyB;AACtC,MAAa,wBAAwB,KAAK,KAAK,SAAS,EAAE,MAAM;AAGhE,MAAa,kBAAkB;CAC7B,KAAK;EACH,kBAAkB;EAClB,gBAAgB;EAChB,kBAAkB;EAClB,iBAAiB;EACjB,UAAU;EACV,eAAe;EACf,eAAe;EAChB;CACD,MAAM;EACJ,kBAAkB;EAClB,gBAAgB;EAChB,kBAAkB;EAClB,iBAAiB;EACjB,UAAU;EACV,eAAe;EACf,eAAe;EAChB;CACD,MAAM;EACJ,kBAAkB;EAClB,gBAAgB;EAChB,kBAAkB;EAClB,iBAAiB;EACjB,UAAU;EACV,eAAe;EACf,eAAe;EAChB;CACD,KAAK;EACH,gBAAgB;EAChB,kBAAkB;EAClB,iBAAiB;EACjB,UAAU;EACV,eAAe;EACf,eAAe;EAChB;CACF;AAYD,SAAgB,wBAAwB;AACtC,QAAO;;AAGT,SAAgB,oBAAoB,KAAa;CAC/C,MAAM,uBAAuB,KAAK,KAAK,KAAK,uBAAuB;AAEnE,QAAO,GAAG,WAAW,qBAAqB;;AAG5C,SAAgB,oBACd,KACA,iBAAiC,uBACjC;CACA,MAAM,kBAAkB,KAAK,KAAK,KAAK,eAAe;AAEtD,KAAI,GAAG,WAAW,gBAAgB,IAAI,eAAe,IAAI,CACvD,QAAO;CAGT,MAAM,YAAY,QAAQ,IAAI;AAE9B,KAAI,cAAc,IAChB,QAAO;AAGT,QAAO,oBAAoB,WAAW,eAAe;;AAGvD,SAAgB,eAAe,OAA8B;CAC3D,MAAM,cAAc,QAAQ,KA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AAGtD,KAAI,CAAC,GAAG,WAAW,WAAW,EAAE;AAC9B,UAAQ,KAAK,uDAAuD;AACpE;;CAGF,MAAM,gBAAgB,GAAG,aAAa,YAAY,QAAQ;CAC1D,IAAI,gBAAgB;AAEpB,MAAK,MAAM,OAAO,cAAc;EAE9B,MAAM,kBAAkB,YADR,kBAAkB,IAAI,KAAK,iBACC;EAG5C,MAAM,QAAQ,cAAc,MAAM,KAAK;EACvC,MAAM,gBAAgB,MAAM,QACzB,SAAS,CAAC,KAAK,MAAM,CAAC,SAAS,gBAAgB,CACjD;AAED,MAAI,cAAc,WAAW,MAAM,OACjC,iBAAgB,cAAc,KAAK,KAAK;;AAK5C,KAAI,kBAAkB,cACpB,IAAG,cAAc,YAAY,cAAc","debug_id":"78c06d69-a52c-5bea-96c7-df0b42c3115e"}
|
|
1
|
+
{"version":3,"file":"utils-C4isxXSO.mjs","sources":["../src/utils.ts"],"sourcesContent":["import type { PowerhouseConfig } from \"@powerhousedao/config\";\nimport crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport path, { dirname } from \"node:path\";\nexport const POWERHOUSE_CONFIG_FILE = \"powerhouse.config.json\";\nexport const POWERHOUSE_GLOBAL_DIR = path.join(homedir(), \".ph\");\nexport const SUPPORTED_PACKAGE_MANAGERS = [\"npm\", \"yarn\", \"pnpm\", \"bun\"];\n\nexport const packageManagers = {\n bun: {\n globalPathRegexp: /[\\\\/].bun[\\\\/]/,\n installCommand: \"bun add {{dependency}}\",\n uninstallCommand: \"bun remove {{dependency}}\",\n workspaceOption: \"\",\n lockfile: \"bun.lock\",\n updateCommand: \"bun update {{dependency}}\",\n buildAffected: \"bun run build:affected\",\n },\n pnpm: {\n globalPathRegexp: /[\\\\/]pnpm[\\\\/]/,\n installCommand: \"pnpm add {{dependency}}\",\n uninstallCommand: \"pnpm remove {{dependency}}\",\n workspaceOption: \"--workspace-root\",\n lockfile: \"pnpm-lock.yaml\",\n updateCommand: \"pnpm update {{dependency}}\",\n buildAffected: \"pnpm run build:affected\",\n },\n yarn: {\n globalPathRegexp: /[\\\\/]yarn[\\\\/]/,\n installCommand: \"yarn add {{dependency}}\",\n uninstallCommand: \"yarn remove {{dependency}}\",\n workspaceOption: \"-W\",\n lockfile: \"yarn.lock\",\n updateCommand: \"yarn upgrade {{dependency}}\",\n buildAffected: \"yarn run build:affected\",\n },\n npm: {\n installCommand: \"npm install {{dependency}}\",\n uninstallCommand: \"npm uninstall {{dependency}}\",\n workspaceOption: \"\",\n lockfile: \"package-lock.json\",\n updateCommand: \"npm update {{dependency}} --save\",\n buildAffected: \"npm run build:affected\",\n },\n};\n\ntype PathValidation = (dir: string) => boolean;\n\nexport type PackageManager = \"npm\" | \"yarn\" | \"pnpm\" | \"bun\";\n\nexport type ProjectInfo = {\n isGlobal: boolean;\n path: string;\n packageManager: PackageManager;\n};\n\nexport function defaultPathValidation() {\n return true;\n}\n\nexport function isPowerhouseProject(dir: string) {\n const powerhouseConfigPath = path.join(dir, POWERHOUSE_CONFIG_FILE);\n\n return fs.existsSync(powerhouseConfigPath);\n}\n\nexport function findNodeProjectRoot(\n dir: string,\n pathValidation: PathValidation = defaultPathValidation,\n) {\n const packageJsonPath = path.join(dir, \"package.json\");\n\n if (fs.existsSync(packageJsonPath) && pathValidation(dir)) {\n return dir;\n }\n\n const parentDir = dirname(dir);\n\n if (parentDir === dir) {\n return null;\n }\n\n return findNodeProjectRoot(parentDir, pathValidation);\n}\n\nexport function getProjectInfo(debug?: boolean): ProjectInfo {\n const currentPath = process.cwd();\n\n if (debug) {\n console.log(\">>> currentPath\", currentPath);\n }\n\n const projectPath = findNodeProjectRoot(currentPath, isPowerhouseProject);\n\n if (!projectPath) {\n return {\n isGlobal: true,\n path: POWERHOUSE_GLOBAL_DIR,\n packageManager: getPackageManagerFromLockfile(POWERHOUSE_GLOBAL_DIR),\n };\n }\n\n return {\n isGlobal: false,\n path: projectPath,\n packageManager: getPackageManagerFromLockfile(projectPath),\n };\n}\n\n/**\n * Generates a unique drive ID based on the project path.\n * The same project path will always generate the same ID.\n * @param name - The name prefix for the drive ID (e.g., \"vetra\", \"powerhouse\")\n * @returns A unique drive ID in the format \"{name}-{hash}\"\n */\nexport function generateProjectDriveId(name: string): string {\n const projectInfo = getProjectInfo();\n const hash = crypto\n .createHash(\"sha256\")\n .update(projectInfo.path)\n .digest(\"hex\");\n const shortHash = hash.substring(0, 8);\n return `${name}-${shortHash}`;\n}\n\nexport function getPackageManagerFromLockfile(dir: string): PackageManager {\n if (fs.existsSync(path.join(dir, packageManagers.pnpm.lockfile))) {\n return \"pnpm\";\n } else if (fs.existsSync(path.join(dir, packageManagers.yarn.lockfile))) {\n return \"yarn\";\n } else if (fs.existsSync(path.join(dir, packageManagers.bun.lockfile))) {\n return \"bun\";\n }\n\n return \"npm\";\n}\n\nexport function updatePackagesArray(\n currentPackages: PowerhouseConfig[\"packages\"] = [],\n dependencies: { name: string; version: string | undefined }[],\n task: \"install\" | \"uninstall\" = \"install\",\n provider: \"registry\" | \"local\" = \"registry\",\n): PowerhouseConfig[\"packages\"] {\n const isInstall = task === \"install\";\n const mappedPackages = dependencies.map((dep) => ({\n packageName: dep.name,\n version: dep.version,\n provider,\n }));\n\n if (isInstall) {\n // Overwrite existing package if version is different\n const filteredPackages = currentPackages.filter(\n (pkg) => !dependencies.find((dep) => dep.name === pkg.packageName),\n );\n return [...filteredPackages, ...mappedPackages];\n }\n\n return currentPackages.filter(\n (pkg) => !dependencies.map((dep) => dep.name).includes(pkg.packageName),\n );\n}\n\n// Modify updateConfigFile to use the new function\nexport function updateConfigFile(\n dependencies: { name: string; version: string | undefined }[],\n projectPath: string,\n task: \"install\" | \"uninstall\" = \"install\",\n provider: \"registry\" | \"local\" = \"registry\",\n registryUrl?: string,\n registryUrlExplicit = false,\n) {\n const configPath = path.join(projectPath, POWERHOUSE_CONFIG_FILE);\n\n if (!fs.existsSync(configPath)) {\n throw new Error(\n `powerhouse.config.json file not found. projectPath: ${projectPath}`,\n );\n }\n\n const config = JSON.parse(\n fs.readFileSync(configPath, \"utf-8\"),\n ) as PowerhouseConfig;\n\n const updatedConfig: PowerhouseConfig = {\n ...config,\n packages: updatePackagesArray(\n config.packages,\n dependencies,\n task,\n provider,\n ),\n };\n\n if (\n task === \"install\" &&\n registryUrl &&\n (registryUrlExplicit || !config.packageRegistryUrl) &&\n dependencies.length > 0\n ) {\n updatedConfig.packageRegistryUrl = registryUrl;\n }\n\n fs.writeFileSync(configPath, JSON.stringify(updatedConfig, null, 2));\n}\n\n/**\n * Recursively searches for a specific file by traversing up the directory tree.\n * Starting from the given path, it checks each parent directory until it finds\n * the target file or reaches the root directory.\n *\n * @param startPath - The absolute path of the directory to start searching from\n * @param targetFile - The name of the file to search for (e.g., 'package.json', 'pnpm-workspace.yaml')\n * @returns The absolute path of the directory containing the target file, or null if not found\n *\n * @example\n * // Find the workspace root directory\n * const workspaceRoot = findContainerDirectory('/path/to/project/src', 'pnpm-workspace.yaml');\n *\n * // Find the nearest package.json\n * const packageDir = findContainerDirectory('/path/to/project/src/components', 'package.json');\n */\nexport const findContainerDirectory = (\n startPath: string,\n targetFile: string,\n): string | null => {\n const filePath = path.join(startPath, targetFile);\n\n if (fs.existsSync(filePath)) {\n return startPath;\n }\n\n const parentDir = path.dirname(startPath);\n\n //reached the root directory and haven't found the file\n if (parentDir === startPath) {\n return null;\n }\n\n return findContainerDirectory(parentDir, targetFile);\n};\n\n/**\n * Updates the styles.css file to include imports for newly installed packages\n * @param dependencies - Array of dependencies that were installed\n * @param projectPath - Path to the project root\n */\nexport function updateStylesFile(\n dependencies: { name: string; version: string | undefined }[],\n projectPath: string,\n) {\n const stylesPath = path.join(projectPath, \"style.css\");\n\n // Check if styles.css exists\n if (!fs.existsSync(stylesPath)) {\n console.warn(\"⚠️ Warning: style.css file not found in project root\");\n return;\n }\n\n const currentStyles = fs.readFileSync(stylesPath, \"utf-8\");\n let updatedStyles = currentStyles;\n\n for (const dep of dependencies) {\n const cssPath = `./node_modules/${dep.name}/dist/style.css`;\n const fullCssPath = path.join(projectPath, cssPath);\n const importStatement = `@import '${cssPath}';`;\n\n // Check if the CSS file exists\n if (!fs.existsSync(fullCssPath)) {\n console.warn(`⚠️ Warning: CSS file not found at ${cssPath}`);\n continue;\n }\n\n // Check if import already exists\n if (currentStyles.includes(importStatement)) {\n continue;\n }\n\n // Find the last @import statement\n const importLines = currentStyles\n .split(\"\\n\")\n .filter((line) => line.trim().startsWith(\"@import\"));\n const lastImport = importLines[importLines.length - 1];\n\n if (lastImport) {\n // Insert new import after the last existing import\n updatedStyles = currentStyles.replace(\n lastImport,\n `${lastImport}\\n${importStatement}`,\n );\n } else {\n // If no imports exist, add at the top of the file\n updatedStyles = `${importStatement}\\n${currentStyles}`;\n }\n }\n\n // Only write if changes were made\n if (updatedStyles !== currentStyles) {\n fs.writeFileSync(stylesPath, updatedStyles);\n }\n}\n\n/**\n * Removes CSS imports for uninstalled packages from styles.css\n */\nexport function removeStylesImports(\n dependencies: { name: string; version: string | undefined }[],\n projectPath: string,\n) {\n const stylesPath = path.join(projectPath, \"style.css\");\n\n // Check if styles.css exists\n if (!fs.existsSync(stylesPath)) {\n console.warn(\"⚠️ Warning: style.css file not found in project root\");\n return;\n }\n\n const currentStyles = fs.readFileSync(stylesPath, \"utf-8\");\n let updatedStyles = currentStyles;\n\n for (const dep of dependencies) {\n const cssPath = `./node_modules/${dep.name}/dist/style.css`;\n const importStatement = `@import '${cssPath}';`;\n\n // Remove the import line if it exists\n const lines = updatedStyles.split(\"\\n\");\n const filteredLines = lines.filter(\n (line) => !line.trim().includes(importStatement),\n );\n\n if (filteredLines.length !== lines.length) {\n updatedStyles = filteredLines.join(\"\\n\");\n }\n }\n\n // Only write if changes were made\n if (updatedStyles !== currentStyles) {\n fs.writeFileSync(stylesPath, updatedStyles);\n }\n}\n"],"names":[],"mappings":";;;;;;;AAKA,MAAa,yBAAyB;AACtC,MAAa,wBAAwB,KAAK,KAAK,SAAS,EAAE,MAAM;AA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gB,CACjD;AAED,MAAI,cAAc,WAAW,MAAM,OACjC,iBAAgB,cAAc,KAAK,KAAK;;AAK5C,KAAI,kBAAkB,cACpB,IAAG,cAAc,YAAY,cAAc","debug_id":"73159d3c-22a7-5dc6-8bd4-7b15f3b94c79"}
|
|
@@ -1,11 +1,13 @@
|
|
|
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 { a as parseDefaultDrivesUrl } from "./cli-connect-override-
|
|
4
|
-
import { t as runConnectStudio } from "./connect-studio-
|
|
5
|
-
import { a as generateProjectDriveId } from "./utils-
|
|
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]="0be7e354-5024-5332-aa33-5bc37e651ed4")}catch(e){}}();
|
|
3
|
+
import { a as parseDefaultDrivesUrl } from "./cli-connect-override-D3hh4aH_.mjs";
|
|
4
|
+
import { t as runConnectStudio } from "./connect-studio-D6rfWCNB.mjs";
|
|
5
|
+
import { a as generateProjectDriveId } from "./utils-C4isxXSO.mjs";
|
|
6
6
|
import { n as startSwitchboard$1 } from "./switchboard-CJMoMzWx.mjs";
|
|
7
7
|
import { execSync } from "node:child_process";
|
|
8
8
|
import { blue, green, red, yellow } from "colorette";
|
|
9
|
+
import fs from "node:fs";
|
|
10
|
+
import path from "node:path";
|
|
9
11
|
import { createLogger } from "vite";
|
|
10
12
|
import { createVetraDocument, getVetraDocuments, setPackageGithubUrl } from "@powerhousedao/common/utils";
|
|
11
13
|
import { isPortAvailable } from "@powerhousedao/switchboard/server";
|
|
@@ -252,6 +254,103 @@ async function resolveSwitchboardPort(requested) {
|
|
|
252
254
|
return candidate;
|
|
253
255
|
}
|
|
254
256
|
//#endregion
|
|
257
|
+
//#region src/utils/vetra-runtime.ts
|
|
258
|
+
const RECORD_REL = path.join(".ph", "vetra-runtime.json");
|
|
259
|
+
const READY_TIMEOUT_MS = 2e3;
|
|
260
|
+
const recordPath = (projectDir) => path.join(projectDir, RECORD_REL);
|
|
261
|
+
function readVetraRuntime(projectDir) {
|
|
262
|
+
try {
|
|
263
|
+
return JSON.parse(fs.readFileSync(recordPath(projectDir), "utf8"));
|
|
264
|
+
} catch {
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
function writeVetraRuntime(projectDir, record) {
|
|
269
|
+
const target = recordPath(projectDir);
|
|
270
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
271
|
+
fs.writeFileSync(target, `${JSON.stringify(record, null, 2)}\n`);
|
|
272
|
+
}
|
|
273
|
+
function clearVetraRuntime(projectDir) {
|
|
274
|
+
try {
|
|
275
|
+
fs.rmSync(recordPath(projectDir));
|
|
276
|
+
} catch {}
|
|
277
|
+
}
|
|
278
|
+
function isPidAlive(pid) {
|
|
279
|
+
try {
|
|
280
|
+
process.kill(pid, 0);
|
|
281
|
+
return true;
|
|
282
|
+
} catch (error) {
|
|
283
|
+
return error.code === "EPERM";
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
async function isReady(port) {
|
|
287
|
+
try {
|
|
288
|
+
return (await fetch(`http://localhost:${port}/ready`, { signal: AbortSignal.timeout(READY_TIMEOUT_MS) })).ok;
|
|
289
|
+
} catch {
|
|
290
|
+
return false;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Decide whether the recorded instance is actually serving this project.
|
|
295
|
+
*
|
|
296
|
+
* All three checks are load-bearing. A pid can be reused by an unrelated
|
|
297
|
+
* process, so a live pid proves nothing on its own. Another project's
|
|
298
|
+
* switchboard would answer `/ready` on its own port, so a healthy `/ready`
|
|
299
|
+
* proves nothing either. And the recorded `projectName` is what separates
|
|
300
|
+
* "my instance" from "someone else's instance that happens to hold this
|
|
301
|
+
* port" — which is precisely the confusion that let an agent write document
|
|
302
|
+
* models into a different project's drive.
|
|
303
|
+
*
|
|
304
|
+
* A stale record is deleted so the next start is unblocked. A foreign one is
|
|
305
|
+
* left alone: it describes something that is alive.
|
|
306
|
+
*/
|
|
307
|
+
async function probeVetraRuntime(projectDir, projectName) {
|
|
308
|
+
const record = readVetraRuntime(projectDir);
|
|
309
|
+
if (!record) return { status: "none" };
|
|
310
|
+
if (!isPidAlive(record.pid) || !await isReady(record.switchboardPort)) {
|
|
311
|
+
clearVetraRuntime(projectDir);
|
|
312
|
+
return { status: "stale" };
|
|
313
|
+
}
|
|
314
|
+
if (record.projectName !== projectName) return {
|
|
315
|
+
status: "foreign",
|
|
316
|
+
record
|
|
317
|
+
};
|
|
318
|
+
return {
|
|
319
|
+
status: "live",
|
|
320
|
+
record
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
const MCP_FILES = [".mcp.json", path.join(".cursor", "mcp.json")];
|
|
324
|
+
/**
|
|
325
|
+
* Point every generated MCP config at `port`, returning the files changed.
|
|
326
|
+
*
|
|
327
|
+
* An MCP client resolves these files at session start and cannot read the
|
|
328
|
+
* project config or `.env`, so when an override moves the port the literal
|
|
329
|
+
* has to be corrected on disk. Rewrites in place rather than regenerating,
|
|
330
|
+
* so any other servers or hand-added keys survive.
|
|
331
|
+
*/
|
|
332
|
+
function syncMcpPort(projectDir, port) {
|
|
333
|
+
const changed = [];
|
|
334
|
+
for (const rel of MCP_FILES) {
|
|
335
|
+
const target = path.join(projectDir, rel);
|
|
336
|
+
if (!fs.existsSync(target)) continue;
|
|
337
|
+
let parsed;
|
|
338
|
+
try {
|
|
339
|
+
parsed = JSON.parse(fs.readFileSync(target, "utf8"));
|
|
340
|
+
} catch {
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
const server = parsed.mcpServers?.["reactor-mcp"];
|
|
344
|
+
if (!server?.url) continue;
|
|
345
|
+
const wanted = `http://localhost:${port}/mcp`;
|
|
346
|
+
if (server.url === wanted) continue;
|
|
347
|
+
server.url = wanted;
|
|
348
|
+
fs.writeFileSync(target, `${JSON.stringify(parsed, null, 2)}\n`);
|
|
349
|
+
changed.push(rel);
|
|
350
|
+
}
|
|
351
|
+
return changed;
|
|
352
|
+
}
|
|
353
|
+
//#endregion
|
|
255
354
|
//#region src/services/vetra.ts
|
|
256
355
|
const VETRA_DRIVE_NAME = "vetra";
|
|
257
356
|
const getDefaultVetraUrl = (port) => `http://localhost:${port}/d/${generateProjectDriveId(VETRA_DRIVE_NAME)}`;
|
|
@@ -377,6 +476,22 @@ async function startLocalVetraSwitchboard(args, logger) {
|
|
|
377
476
|
async function startVetra(args) {
|
|
378
477
|
const { connectPort, verbose, remoteDrive, disableConnect, debug, httpsCertFile, httpsKeyFile, disableLocalPackages, host, open, cors, strictPort, printUrls, bindCLIShortcuts, watchTimeout } = args;
|
|
379
478
|
const switchboardLogger = childLogger(["vetra", "switchboard"]);
|
|
479
|
+
const projectDir = process.cwd();
|
|
480
|
+
const { readPackageSync } = await import("read-pkg");
|
|
481
|
+
const projectName = readPackageSync({ cwd: projectDir }).name;
|
|
482
|
+
const probe = await probeVetraRuntime(projectDir, projectName);
|
|
483
|
+
if (probe.status === "live") {
|
|
484
|
+
console.log();
|
|
485
|
+
console.log(green("Vetra is already running for this project."));
|
|
486
|
+
console.log(green(` ➜ Connect: http://localhost:${probe.record.connectPort}`));
|
|
487
|
+
console.log(green(` ➜ Switchboard: http://localhost:${probe.record.switchboardPort}/graphql`));
|
|
488
|
+
console.log(`Stop that instance (pid ${probe.record.pid}) if you need to restart it.`);
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
if (probe.status === "foreign") {
|
|
492
|
+
console.error(red(`.ph/vetra-runtime.json describes a live Vetra for "${probe.record.projectName}", but this project is "${projectName}". Refusing to start a second instance. Delete .ph/vetra-runtime.json if that record is wrong.`));
|
|
493
|
+
process.exit(1);
|
|
494
|
+
}
|
|
380
495
|
try {
|
|
381
496
|
if (!process.env.LOG_LEVEL) setLogLevel("info");
|
|
382
497
|
if (verbose) {
|
|
@@ -397,6 +512,26 @@ async function startVetra(args) {
|
|
|
397
512
|
const driveUrl = switchboardResult.driveUrl || remoteDrive || "";
|
|
398
513
|
const previewDriveUrl = switchboardResult.previewDriveUrl;
|
|
399
514
|
const actualSwitchboardPort = switchboardResult.switchboardPort;
|
|
515
|
+
writeVetraRuntime(projectDir, {
|
|
516
|
+
pid: process.pid,
|
|
517
|
+
projectName,
|
|
518
|
+
switchboardPort: actualSwitchboardPort,
|
|
519
|
+
connectPort,
|
|
520
|
+
mcpUrl: `http://localhost:${actualSwitchboardPort}/mcp`,
|
|
521
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
522
|
+
});
|
|
523
|
+
const releaseRuntimeRecord = () => clearVetraRuntime(projectDir);
|
|
524
|
+
process.on("exit", releaseRuntimeRecord);
|
|
525
|
+
process.on("SIGINT", () => {
|
|
526
|
+
releaseRuntimeRecord();
|
|
527
|
+
process.exit(130);
|
|
528
|
+
});
|
|
529
|
+
process.on("SIGTERM", () => {
|
|
530
|
+
releaseRuntimeRecord();
|
|
531
|
+
process.exit(143);
|
|
532
|
+
});
|
|
533
|
+
const driftedMcpFiles = syncMcpPort(projectDir, actualSwitchboardPort);
|
|
534
|
+
if (driftedMcpFiles.length > 0) console.log(yellow(`Updated ${driftedMcpFiles.join(" and ")} to port ${actualSwitchboardPort}. Reconnect your MCP client (/mcp) to pick it up. This edit is local — do not commit it.`));
|
|
400
535
|
if (remoteDrive) {
|
|
401
536
|
await sleep(3e3);
|
|
402
537
|
await configureVetraGithubUrl(actualSwitchboardPort, remoteDrive, verbose);
|
|
@@ -440,5 +575,5 @@ async function startVetra(args) {
|
|
|
440
575
|
//#endregion
|
|
441
576
|
export { startVetra };
|
|
442
577
|
|
|
443
|
-
//# sourceMappingURL=vetra-
|
|
444
|
-
//# debugId=
|
|
578
|
+
//# sourceMappingURL=vetra-DkF6EJMY.mjs.map
|
|
579
|
+
//# debugId=0be7e354-5024-5332-aa33-5bc37e651ed4
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vetra-DkF6EJMY.mjs","sources":["../src/utils/configure-vetra-github-url.ts","../src/utils/resolve-switchboard-port.ts","../src/utils/vetra-runtime.ts","../src/services/vetra.ts"],"sourcesContent":["import {\n createVetraDocument,\n getVetraDocuments,\n setPackageGithubUrl,\n} from \"@powerhousedao/common/utils\";\nimport { red } from \"colorette\";\nimport { execSync } from \"node:child_process\";\nimport { createInterface } from \"node:readline\";\n\n/**\n * Get git remote URL (origin)\n * @returns Git remote URL or null if not configured\n */\nfunction getGitRemoteUrl(): string | null {\n try {\n const url = execSync(\"git remote get-url origin\", {\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n }).trim();\n return url || null;\n } catch {\n return null;\n }\n}\n\n/**\n * Prompt user to enter a custom GitHub URL\n */\nasync function promptForCustomUrl(): Promise<string | null> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n process.stdout.write(\"\\nEnter GitHub URL (or press Enter to skip): \");\n\n rl.on(\"line\", (answer: string) => {\n rl.close();\n const url = answer.trim();\n resolve(url || null);\n });\n });\n}\n\n/**\n * Prompt yes/no question\n */\nasync function promptYesNo(question: string): Promise<boolean> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n process.stdout.write(`\\n${question} (y/n): `);\n\n rl.on(\"line\", (answer: string) => {\n rl.close();\n const response = answer.trim().toLowerCase();\n resolve(response === \"y\" || response === \"yes\");\n });\n });\n}\n\n/**\n * Prompt user to select or enter GitHub URL\n * @param gitRemoteUrl - Git remote URL if available\n * @returns Selected URL or null if skipped\n */\nasync function promptForGithubUrl(\n gitRemoteUrl: string | null,\n): Promise<string | null> {\n return new Promise((resolve) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n console.log(\"\\n\" + \"=\".repeat(50));\n console.log(\"🔍 Vetra Package Configuration\");\n console.log(\"=\".repeat(50));\n console.log(\n \"\\nWe detected a Vetra package document in your remote drive without a GitHub URL configured.\",\n );\n console.log(\"\\nWould you like to configure the GitHub URL now?\");\n\n if (gitRemoteUrl) {\n console.log(`\\nGit remote URL detected: ${gitRemoteUrl}`);\n console.log(\"\\nOptions:\");\n console.log(\"1. Use detected URL\");\n console.log(\"2. Enter a different URL\");\n console.log(\"3. Skip configuration\");\n\n process.stdout.write(\"\\nSelect an option (1-3): \");\n\n const handleAnswer = (answer: string) => {\n const choice = answer.trim();\n\n if (choice === \"1\") {\n rl.close();\n resolve(gitRemoteUrl);\n } else if (choice === \"2\") {\n rl.close();\n promptForCustomUrl()\n .then(resolve)\n .catch(() => resolve(null));\n } else if (choice === \"3\") {\n rl.close();\n resolve(null);\n } else {\n process.stdout.write(\"Invalid choice. Select an option (1-3): \");\n }\n };\n\n rl.on(\"line\", handleAnswer);\n } else {\n console.log(\"\\nNo git remote URL detected.\");\n console.log(\"\\nOptions:\");\n console.log(\"1. Enter GitHub URL manually\");\n console.log(\"2. Skip configuration\");\n\n process.stdout.write(\"\\nSelect an option (1-2): \");\n\n const handleAnswer = (answer: string) => {\n const choice = answer.trim();\n\n if (choice === \"1\") {\n rl.close();\n promptForCustomUrl()\n .then(resolve)\n .catch(() => resolve(null));\n } else if (choice === \"2\") {\n rl.close();\n resolve(null);\n } else {\n process.stdout.write(\"Invalid choice. Select an option (1-2): \");\n }\n };\n\n rl.on(\"line\", handleAnswer);\n }\n });\n}\n\n/**\n * Set git remote URL (origin)\n */\nfunction setGitRemoteUrl(url: string): void {\n try {\n execSync(`git remote add origin ${url}`, {\n stdio: \"inherit\",\n });\n console.log(`✅ Git remote origin set to: ${url}`);\n } catch {\n try {\n execSync(`git remote set-url origin ${url}`, {\n stdio: \"inherit\",\n });\n console.log(`✅ Git remote origin updated to: ${url}`);\n } catch {\n console.error(red(`❌ Failed to set git remote URL`));\n }\n }\n}\n\n/**\n * Validates documents and returns the target document to use\n * Warns if multiple documents found\n */\nfunction validateAndSelectDocument<T>(documents: T[]): T | null {\n if (documents.length === 0) {\n return null;\n }\n\n if (documents.length > 1) {\n console.warn(\n `⚠️ Warning: Multiple Vetra documents found (${documents.length}). Using first document.`,\n );\n }\n\n return documents[0];\n}\n\nasync function applyGithubUrlConfiguration(\n graphqlEndpoint: string,\n vetraDriveId: string,\n documentId: string,\n selectedUrl: string,\n shouldSetRemote: boolean,\n): Promise<void> {\n // Set package GitHub URL\n await setPackageGithubUrl(\n graphqlEndpoint,\n vetraDriveId,\n documentId,\n selectedUrl,\n );\n\n console.log(`✅ GitHub URL configured: ${selectedUrl}`);\n\n // Set git remote URL if requested\n if (shouldSetRemote) {\n setGitRemoteUrl(selectedUrl);\n }\n}\n\nfunction logVerbose(message: string, verbose?: boolean): void {\n if (verbose) {\n console.log(message);\n }\n}\n\n/**\n * Sleep for a specified number of milliseconds\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Configure GitHub URL for Vetra documents\n * @param switchboardPort - Port where switchboard is running\n * @param vetraDriveUrl - Remote drive URL\n * @param verbose - Enable verbose logging\n */\nexport async function configureVetraGithubUrl(\n switchboardPort: number,\n vetraDriveUrl: string,\n verbose?: boolean,\n): Promise<void> {\n logVerbose(\"Checking GitHub URL configuration...\", verbose);\n\n try {\n const graphqlEndpoint = `http://localhost:${switchboardPort}/graphql`;\n const vetraDriveId = vetraDriveUrl.split(\"/\").pop();\n if (!vetraDriveId) {\n throw new Error(\"Invalid vetraDriveUrl: unable to extract drive ID\");\n }\n\n const documents = await getVetraDocuments(graphqlEndpoint, vetraDriveId);\n\n // Skip if already configured\n if (documents.some((doc) => doc.githubUrl)) {\n logVerbose(\"GitHub URL already configured, skipping setup\", verbose);\n return;\n }\n\n // Get or create target document\n let targetDocumentId: string;\n const targetDocument = validateAndSelectDocument(documents);\n\n // Collect user input\n const gitRemoteUrl = getGitRemoteUrl();\n const selectedUrl = await promptForGithubUrl(gitRemoteUrl);\n\n if (!selectedUrl) {\n logVerbose(\"GitHub URL configuration skipped\", verbose);\n return;\n }\n\n let shouldSetRemote = false;\n if (selectedUrl !== gitRemoteUrl && !gitRemoteUrl) {\n shouldSetRemote = await promptYesNo(\"Set this as your git remote URL?\");\n }\n\n if (!targetDocument) {\n logVerbose(\"No Vetra documents found, creating new document...\", verbose);\n\n targetDocumentId = await createVetraDocument(\n graphqlEndpoint,\n vetraDriveId,\n \"vetra-package\",\n );\n\n logVerbose(`Created new document: ${targetDocumentId}`, verbose);\n } else {\n targetDocumentId = targetDocument.id;\n }\n\n await applyGithubUrlConfiguration(\n graphqlEndpoint,\n vetraDriveId,\n targetDocumentId,\n selectedUrl,\n shouldSetRemote,\n );\n } catch (error) {\n console.error(\n red(\n `⚠️ GitHub URL configuration failed: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n logVerbose(String(error), verbose);\n }\n}\n","import { isPortAvailable } from \"@powerhousedao/switchboard/server\";\nimport { yellow } from \"colorette\";\n\nconst MAX_FALLBACK_ATTEMPTS = 20;\n\nfunction isInteractive(): boolean {\n return Boolean(process.stdin.isTTY) && !process.env.CI;\n}\n\nasync function findFreePort(start: number): Promise<number | null> {\n for (let i = 0; i < MAX_FALLBACK_ATTEMPTS; i++) {\n const candidate = start + i;\n if (await isPortAvailable(candidate)) return candidate;\n }\n return null;\n}\n\n/**\n * Resolve the port switchboard should bind to. If the requested port is free,\n * returns it unchanged. If it's in use, walks forward for the next free port\n * and — in an interactive terminal — asks the user to confirm the fallback.\n * In CI / piped contexts the fallback is applied automatically so scripts\n * don't hang on an unanswered prompt.\n *\n * Throws a process.exit(1) when the user declines the prompt or when no free\n * port is available in the search window.\n */\nexport async function resolveSwitchboardPort(\n requested: number,\n): Promise<number> {\n if (await isPortAvailable(requested)) return requested;\n\n const candidate = await findFreePort(requested + 1);\n if (candidate === null) {\n console.error(\n `Port ${requested} is in use and no free port was found in the range ${requested}-${requested + MAX_FALLBACK_ATTEMPTS - 1}.`,\n );\n process.exit(1);\n }\n\n if (!isInteractive()) {\n console.log(\n yellow(\n `Port ${requested} is in use. Falling back to port ${candidate} (non-interactive; skipping confirmation).`,\n ),\n );\n return candidate;\n }\n\n const enquirer = await import(\"enquirer\");\n\n let confirmed: boolean;\n try {\n const answer = await enquirer.default.prompt<{ confirmed: boolean }>({\n type: \"confirm\",\n name: \"confirmed\",\n message: `Port ${requested} is in use. Use port ${candidate} instead?`,\n initial: true,\n });\n confirmed = answer.confirmed;\n } catch {\n // user aborted the prompt (Ctrl-C); treat as decline\n confirmed = false;\n }\n\n if (!confirmed) {\n console.error(\n `Aborted. Free port ${requested} or pass --switchboard-port <port> to choose a different port.`,\n );\n process.exit(1);\n }\n\n return candidate;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport type VetraRuntimeRecord = {\n pid: number;\n projectName: string;\n switchboardPort: number;\n connectPort: number;\n mcpUrl: string;\n startedAt: string;\n};\n\nexport type VetraProbe =\n | { status: \"none\" }\n | { status: \"stale\" }\n | { status: \"live\"; record: VetraRuntimeRecord }\n | { status: \"foreign\"; record: VetraRuntimeRecord };\n\nconst RECORD_REL = path.join(\".ph\", \"vetra-runtime.json\");\nconst READY_TIMEOUT_MS = 2000;\n\nconst recordPath = (projectDir: string) => path.join(projectDir, RECORD_REL);\n\nexport function readVetraRuntime(\n projectDir: string,\n): VetraRuntimeRecord | undefined {\n try {\n return JSON.parse(\n fs.readFileSync(recordPath(projectDir), \"utf8\"),\n ) as VetraRuntimeRecord;\n } catch {\n // Missing or corrupt: either way there is no usable record.\n return undefined;\n }\n}\n\nexport function writeVetraRuntime(\n projectDir: string,\n record: VetraRuntimeRecord,\n): void {\n const target = recordPath(projectDir);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, `${JSON.stringify(record, null, 2)}\\n`);\n}\n\nexport function clearVetraRuntime(projectDir: string): void {\n try {\n fs.rmSync(recordPath(projectDir));\n } catch {\n // Already gone.\n }\n}\n\nfunction isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM means the process exists but belongs to another user.\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\nasync function isReady(port: number): Promise<boolean> {\n try {\n const response = await fetch(`http://localhost:${port}/ready`, {\n signal: AbortSignal.timeout(READY_TIMEOUT_MS),\n });\n return response.ok;\n } catch {\n return false;\n }\n}\n\n/**\n * Decide whether the recorded instance is actually serving this project.\n *\n * All three checks are load-bearing. A pid can be reused by an unrelated\n * process, so a live pid proves nothing on its own. Another project's\n * switchboard would answer `/ready` on its own port, so a healthy `/ready`\n * proves nothing either. And the recorded `projectName` is what separates\n * \"my instance\" from \"someone else's instance that happens to hold this\n * port\" — which is precisely the confusion that let an agent write document\n * models into a different project's drive.\n *\n * A stale record is deleted so the next start is unblocked. A foreign one is\n * left alone: it describes something that is alive.\n */\nexport async function probeVetraRuntime(\n projectDir: string,\n projectName: string,\n): Promise<VetraProbe> {\n const record = readVetraRuntime(projectDir);\n if (!record) return { status: \"none\" };\n\n if (!isPidAlive(record.pid) || !(await isReady(record.switchboardPort))) {\n clearVetraRuntime(projectDir);\n return { status: \"stale\" };\n }\n\n if (record.projectName !== projectName) {\n return { status: \"foreign\", record };\n }\n return { status: \"live\", record };\n}\n\nconst MCP_FILES = [\".mcp.json\", path.join(\".cursor\", \"mcp.json\")];\n\n/**\n * Point every generated MCP config at `port`, returning the files changed.\n *\n * An MCP client resolves these files at session start and cannot read the\n * project config or `.env`, so when an override moves the port the literal\n * has to be corrected on disk. Rewrites in place rather than regenerating,\n * so any other servers or hand-added keys survive.\n */\nexport function syncMcpPort(projectDir: string, port: number): string[] {\n const changed: string[] = [];\n for (const rel of MCP_FILES) {\n const target = path.join(projectDir, rel);\n if (!fs.existsSync(target)) continue;\n\n let parsed: { mcpServers?: Record<string, { url?: string }> };\n try {\n parsed = JSON.parse(fs.readFileSync(target, \"utf8\")) as typeof parsed;\n } catch {\n // Hand-broken JSON is the author's to fix; don't clobber it.\n continue;\n }\n\n const server = parsed.mcpServers?.[\"reactor-mcp\"];\n if (!server?.url) continue;\n\n const wanted = `http://localhost:${port}/mcp`;\n if (server.url === wanted) continue;\n\n server.url = wanted;\n fs.writeFileSync(target, `${JSON.stringify(parsed, null, 2)}\\n`);\n changed.push(rel);\n }\n return changed;\n}\n","import type { VetraProcessorConfigType } from \"@powerhousedao/config\";\nimport { VETRA_PROCESSOR_CONFIG_KEY } from \"@powerhousedao/config\";\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { addDefaultDrive } from \"@powerhousedao/switchboard/utils\";\nimport { blue, green, red, yellow, type Color } from \"colorette\";\nimport type { ILogger } from \"document-model\";\nimport { childLogger, setLogLevel } from \"document-model\";\nimport { createLogger } from \"vite\";\nimport type { VetraArgs } from \"../types.js\";\nimport { generateProjectDriveId } from \"../utils.js\";\nimport {\n configureVetraGithubUrl,\n sleep,\n} from \"../utils/configure-vetra-github-url.js\";\nimport { parseDefaultDrivesUrl } from \"../utils/parse-default-drives.js\";\nimport { resolveSwitchboardPort } from \"../utils/resolve-switchboard-port.js\";\nimport {\n clearVetraRuntime,\n probeVetraRuntime,\n syncMcpPort,\n writeVetraRuntime,\n} from \"../utils/vetra-runtime.js\";\nimport { runConnectStudio } from \"./connect-studio.js\";\nimport { startSwitchboard } from \"./switchboard.js\";\n\nconst VETRA_DRIVE_NAME = \"vetra\";\n\nconst getDefaultVetraUrl = (port: number) =>\n `http://localhost:${port}/d/${generateProjectDriveId(VETRA_DRIVE_NAME)}`;\n\nconst getDriveId = (driveUrl: string | undefined): string =>\n driveUrl?.split(\"/\").pop() ?? generateProjectDriveId(VETRA_DRIVE_NAME);\n\n// Rebase a local drive URL onto --drives-public-base: keeps the /d/<slug>\n// path, swaps the loopback origin for the public base. Browser clients\n// behind a reverse proxy can't reach http://localhost:<port>. Non-loopback\n// URLs (e.g. a remote drive) are already public and pass through unchanged.\nconst rebaseDriveUrl = (driveUrl: string, publicBase: string): string => {\n // Unparseable URLs pass through unchanged, like non-loopback ones.\n let url: URL;\n try {\n url = new URL(driveUrl);\n } catch {\n return driveUrl;\n }\n if (![\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname)) {\n return driveUrl;\n }\n return `${publicBase.replace(/\\/+$/, \"\")}${url.pathname}`;\n};\n\nfunction createViteLogger(color: Color) {\n const customLogger = createLogger(\"info\");\n const loggerInfo = customLogger.info.bind(customLogger);\n customLogger.info = (msg, options) => {\n loggerInfo(color(msg), options);\n };\n const loggerWarn = customLogger.warn.bind(customLogger);\n customLogger.warn = (msg, options) => {\n loggerWarn(yellow(msg), options);\n };\n const loggerError = customLogger.error.bind(customLogger);\n customLogger.error = (msg, options) => {\n loggerError(red(msg), options);\n };\n\n const loggerWarnOnce = customLogger.warnOnce.bind(customLogger);\n customLogger.warnOnce = (msg, options) => {\n loggerWarnOnce(yellow(msg), options);\n };\n return customLogger;\n}\n\nasync function startVetraPreviewDrive(\n reactor: IReactorClient,\n port: number,\n verbose?: boolean,\n): Promise<string> {\n const previewDriveId = generateProjectDriveId(\"preview\");\n\n const previewDrive = {\n id: previewDriveId,\n slug: previewDriveId,\n global: {\n name: \"Vetra Preview\",\n icon: \"https://azure-elderly-tortoise-212.mypinata.cloud/ipfs/bafkreifddkbopiyvcirf7vaqar74th424r5phlxkdxniirdyg3qgu2ajha\",\n nodes: [],\n },\n local: {\n availableOffline: true,\n listeners: [],\n sharingType: \"public\" as const,\n triggers: [],\n },\n };\n\n const driveUrl = await addDefaultDrive(reactor, previewDrive, port);\n\n if (verbose) {\n console.log(blue(`Vetra Switchboard: Preview drive: ${driveUrl}`));\n }\n return driveUrl;\n}\nasync function startLocalVetraSwitchboard(args: VetraArgs, logger?: ILogger) {\n const {\n connectPort,\n switchboardPort,\n dev,\n packages,\n disableLocalPackages,\n debug,\n httpsKeyFile,\n httpsCertFile,\n remoteDrive,\n interactive,\n watch,\n verbose,\n } = args;\n\n // Convert single remote drive to array if provided\n const remoteDrives = remoteDrive ? [remoteDrive] : [];\n\n const vetraProcessorConfig: VetraProcessorConfigType = {\n interactive,\n driveUrl: remoteDrive ?? getDefaultVetraUrl(connectPort),\n driveId: getDriveId(remoteDrive),\n };\n\n const processorConfig = new Map<string, unknown>();\n processorConfig.set(VETRA_PROCESSOR_CONFIG_KEY, vetraProcessorConfig);\n\n const vetraDriveId = generateProjectDriveId(VETRA_DRIVE_NAME);\n\n // When the user didn't opt into strict-port semantics, check for a port\n // conflict up front and ask for confirmation before binding a fallback.\n // Doing this in the CLI layer keeps the interactive prompt out of the\n // switchboard server package and aligns with the existing prerelease-tag\n // confirmation flow in `ph publish`.\n const resolvedSwitchboardPort = args.strictPort\n ? switchboardPort\n : await resolveSwitchboardPort(switchboardPort);\n\n try {\n const switchboard = await startSwitchboard(\n {\n ...args,\n useVetraDrive: true, // Use Vetra drive instead of Powerhouse drive\n mcp: true,\n port: resolvedSwitchboardPort,\n // We've already probed and (when interactive) confirmed the port with\n // the user, so keep the server from running its own fallback on top.\n strictPort: true,\n dev,\n packages,\n remoteDrives,\n vetraDriveId,\n disableLocalPackages,\n debug,\n httpsKeyFile,\n httpsCertFile,\n processorConfig,\n basePath: undefined,\n keypairPath: undefined,\n dbPath: args.dbPath,\n useIdentity: undefined,\n migrate: undefined,\n migrateStatus: undefined,\n reset: undefined,\n yes: undefined,\n requireIdentity: undefined,\n },\n logger,\n );\n\n const actualSwitchboardPort = switchboard.port;\n\n // Add preview drive (only in watch mode)\n let previewDriveUrl: string | null = null;\n if (watch) {\n try {\n previewDriveUrl = await startVetraPreviewDrive(\n switchboard.reactor,\n actualSwitchboardPort,\n verbose,\n );\n } catch (error) {\n console.error(error);\n }\n }\n\n if (verbose) {\n console.log(blue(`Vetra Switchboard: Started successfully`));\n if (remoteDrive) {\n console.log(\n blue(`Vetra Switchboard: Syncing with remote drive: ${remoteDrive}`),\n );\n }\n } else {\n console.log();\n console.log(\n blue(\n `Vetra Switchboard: http://localhost:${actualSwitchboardPort}/graphql`,\n ),\n );\n console.log(blue(` ➜ Drive URL: ${switchboard.defaultDriveUrl}`));\n if (previewDriveUrl) {\n console.log(blue(` ➜ Preview Drive URL: ${previewDriveUrl}`));\n }\n }\n return {\n driveUrl: switchboard.defaultDriveUrl || \"\",\n previewDriveUrl: previewDriveUrl,\n switchboardPort: actualSwitchboardPort,\n };\n } catch (error) {\n console.error(\n red(\n `Vetra Switchboard: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n throw error instanceof Error ? error : new Error(String(error));\n }\n}\n\nexport async function startVetra(args: VetraArgs) {\n const {\n connectPort,\n verbose,\n remoteDrive,\n disableConnect,\n debug,\n httpsCertFile,\n httpsKeyFile,\n disableLocalPackages,\n host,\n open,\n cors,\n strictPort,\n printUrls,\n bindCLIShortcuts,\n watchTimeout,\n } = args;\n\n const switchboardLogger = childLogger([\"vetra\", \"switchboard\"]);\n\n // One Vetra per project. Two instances over one working tree would contend\n // for the same `.ph/read-model.db` and `.ph/reactor-storage`, and leave the\n // project with two drives that diverge.\n const projectDir = process.cwd();\n const { readPackageSync } = await import(\"read-pkg\");\n const projectName = readPackageSync({ cwd: projectDir }).name;\n const probe = await probeVetraRuntime(projectDir, projectName);\n\n if (probe.status === \"live\") {\n console.log();\n console.log(green(\"Vetra is already running for this project.\"));\n console.log(\n green(` ➜ Connect: http://localhost:${probe.record.connectPort}`),\n );\n console.log(\n green(\n ` ➜ Switchboard: http://localhost:${probe.record.switchboardPort}/graphql`,\n ),\n );\n console.log(\n `Stop that instance (pid ${probe.record.pid}) if you need to restart it.`,\n );\n return;\n }\n\n if (probe.status === \"foreign\") {\n console.error(\n red(\n `.ph/vetra-runtime.json describes a live Vetra for \"${probe.record.projectName}\", ` +\n `but this project is \"${projectName}\". Refusing to start a second instance. ` +\n `Delete .ph/vetra-runtime.json if that record is wrong.`,\n ),\n );\n process.exit(1);\n }\n\n try {\n // Set default log level to info if not already specified\n if (!process.env.LOG_LEVEL) {\n setLogLevel(\"info\");\n }\n\n if (verbose) {\n switchboardLogger.info(\"Starting Vetra Switchboard...\");\n if (remoteDrive) {\n const source = remoteDrive\n ? \"command line argument\"\n : \"powerhouse.config.json\";\n switchboardLogger.info(`Using vetraUrl from ${source}: ${remoteDrive}`);\n }\n }\n const switchboardResult = await startLocalVetraSwitchboard(\n {\n ...args,\n dev: true, // Vetra always runs in dev mode to load local packages\n httpsKeyFile,\n httpsCertFile,\n disableLocalPackages,\n debug,\n },\n switchboardLogger,\n );\n const driveUrl: string = switchboardResult.driveUrl || remoteDrive || \"\";\n const previewDriveUrl = switchboardResult.previewDriveUrl;\n const actualSwitchboardPort = switchboardResult.switchboardPort;\n\n // Record what we actually bound, so a second `ph vetra` can tell a live\n // instance from a stale file, and so an agent can see the real ports.\n writeVetraRuntime(projectDir, {\n pid: process.pid,\n projectName,\n switchboardPort: actualSwitchboardPort,\n connectPort,\n mcpUrl: `http://localhost:${actualSwitchboardPort}/mcp`,\n startedAt: new Date().toISOString(),\n });\n const releaseRuntimeRecord = () => clearVetraRuntime(projectDir);\n process.on(\"exit\", releaseRuntimeRecord);\n process.on(\"SIGINT\", () => {\n releaseRuntimeRecord();\n process.exit(130);\n });\n process.on(\"SIGTERM\", () => {\n releaseRuntimeRecord();\n process.exit(143);\n });\n\n // An MCP client resolved `.mcp.json` before this process started and\n // cannot re-read it, so a drifted literal means the agent is pointed at\n // the wrong port — possibly another project's reactor. Correct the file\n // and say so plainly; we cannot fix the already-open client ourselves.\n const driftedMcpFiles = syncMcpPort(projectDir, actualSwitchboardPort);\n if (driftedMcpFiles.length > 0) {\n console.log(\n yellow(\n `Updated ${driftedMcpFiles.join(\" and \")} to port ${actualSwitchboardPort}. ` +\n `Reconnect your MCP client (/mcp) to pick it up. ` +\n `This edit is local — do not commit it.`,\n ),\n );\n }\n\n // Configure GitHub URL if remote drive is set\n if (remoteDrive) {\n // give some time for the drive to process initial strands\n await sleep(3000);\n\n await configureVetraGithubUrl(\n actualSwitchboardPort,\n remoteDrive,\n verbose,\n );\n\n // give some time for the user to read log messages\n await sleep(2000);\n }\n\n if (verbose) {\n console.log(\"Starting Codegen Reactor...\");\n }\n\n // Start Connect pointing to the drive (unless disabled)\n if (!disableConnect) {\n if (verbose) {\n console.log(\"Starting Connect...\");\n const drives = previewDriveUrl\n ? `${driveUrl}, ${previewDriveUrl}`\n : driveUrl;\n console.log(` ➜ Connect will use drives: ${drives}`);\n }\n console.log();\n console.log(green(`Vetra Connect: http://localhost:${connectPort}`));\n\n const customViteLogger = createViteLogger(green);\n\n // Programmatic override forwarded to the Connect runtime config —\n // vetra always sets these regardless of what the user typed on the\n // command line. We pass it as the explicit third arg to\n // runConnectStudio so it survives the `wasFlagExplicitlyPassed`\n // gating (the user didn't pass --default-drives-url; vetra is setting\n // it itself).\n // --drives-public-base: advertise proxy-reachable drive URLs to the\n // browser instead of the switchboard's localhost origin.\n const publicBase = args.drivesPublicBase;\n const browserDriveUrl = publicBase\n ? rebaseDriveUrl(driveUrl, publicBase)\n : driveUrl;\n const browserPreviewDriveUrl =\n previewDriveUrl && publicBase\n ? rebaseDriveUrl(previewDriveUrl, publicBase)\n : previewDriveUrl;\n const vetraDrivesOverride = {\n drives: {\n defaultDrives: parseDefaultDrivesUrl(\n browserPreviewDriveUrl\n ? [browserDriveUrl, browserPreviewDriveUrl].join(\",\")\n : browserDriveUrl,\n ),\n preserveStrategy: \"preserve-all\" as const,\n },\n };\n\n await runConnectStudio(\n {\n ...args,\n port: connectPort,\n disableLocalPackages,\n debug,\n host: host,\n open: open,\n cors: cors,\n strictPort: strictPort,\n printUrls: printUrls,\n bindCLIShortcuts: bindCLIShortcuts,\n watchTimeout: watchTimeout,\n },\n customViteLogger,\n vetraDrivesOverride,\n );\n }\n } catch (error) {\n console.error(error);\n }\n}\n"],"names":["startSwitchboard"],"mappings":";;;;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SAAS,IAAI,oBAChB;AACJ,YAAQ,IAAI,iCAAiC,SAAS;;AAExD,WAAQ,KAAK;AACb,WAAQ,IAAI,MAAM,mCAAmC,cAAc,CAAC;GAEpE,MAAM,mBAAmB,iBAAiB,MAAM;GAUhD,MAAM,aAAa,KAAK;GACxB,MAAM,kBAAkB,aACpB,eAAe,UAAU,WAAW,GACpC;GACJ,MAAM,yBACJ,mBAAmB,aACf,eAAe,iBAAiB,WAAW,GAC3C;GACN,MAAM,sBAAsB,EAC1B,QAAQ;IACN,eAAe,sBACb,yBACI,CAAC,iBAAiB,uBAAuB,CAAC,KAAK,IAAI,GACnD,gBACL;IACD,kBAAkB;IACnB,EACF;AAED,SAAM,iBACJ;IACE,GAAG;IACH,MAAM;IACN;IACA;IACM;IACA;IACA;IACM;IACD;IACO;IACJ;IACf,EACD,kBACA,oBACD;;UAEI,OAAO;AACd,UAAQ,MAAM,MAAM","debug_id":"0be7e354-5024-5332-aa33-5bc37e651ed4"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@powerhousedao/ph-cli",
|
|
3
|
-
"version": "6.2.2-dev.
|
|
3
|
+
"version": "6.2.2-dev.80",
|
|
4
4
|
"description": "",
|
|
5
5
|
"license": "AGPL-3.0-only",
|
|
6
6
|
"type": "module",
|
|
@@ -23,6 +23,15 @@
|
|
|
23
23
|
"keywords": [],
|
|
24
24
|
"author": "",
|
|
25
25
|
"dependencies": {
|
|
26
|
+
"@powerhousedao/builder-tools": "6.2.2-dev.80",
|
|
27
|
+
"@powerhousedao/codegen": "6.2.2-dev.80",
|
|
28
|
+
"@powerhousedao/common": "6.2.2-dev.80",
|
|
29
|
+
"@powerhousedao/config": "6.2.2-dev.80",
|
|
30
|
+
"@powerhousedao/reactor": "6.2.2-dev.80",
|
|
31
|
+
"@powerhousedao/shared": "6.2.2-dev.80",
|
|
32
|
+
"@powerhousedao/switchboard": "6.2.2-dev.80",
|
|
33
|
+
"@powerhousedao/vetra": "6.2.2-dev.80",
|
|
34
|
+
"@renown/sdk": "6.2.2-dev.80",
|
|
26
35
|
"@sentry/node-core": "^10.52.0",
|
|
27
36
|
"@tsdown/css": "0.21.1",
|
|
28
37
|
"ajv": "^8.18.0",
|
|
@@ -30,6 +39,7 @@
|
|
|
30
39
|
"change-case": "5.4.4",
|
|
31
40
|
"cmd-ts": "0.15.0",
|
|
32
41
|
"colorette": "2.0.20",
|
|
42
|
+
"document-model": "6.2.2-dev.80",
|
|
33
43
|
"enquirer": "2.4.1",
|
|
34
44
|
"kysely": "0.28.16",
|
|
35
45
|
"package-manager-detector": "1.6.0",
|
|
@@ -39,17 +49,7 @@
|
|
|
39
49
|
"rolldown": "1.0.0-rc.8",
|
|
40
50
|
"semver": "7.7.4",
|
|
41
51
|
"tsdown": "0.21.1",
|
|
42
|
-
"vite": "8.0.10"
|
|
43
|
-
"@powerhousedao/codegen": "6.2.2-dev.8",
|
|
44
|
-
"@powerhousedao/common": "6.2.2-dev.8",
|
|
45
|
-
"@powerhousedao/config": "6.2.2-dev.8",
|
|
46
|
-
"@powerhousedao/builder-tools": "6.2.2-dev.8",
|
|
47
|
-
"@powerhousedao/reactor": "6.2.2-dev.8",
|
|
48
|
-
"@powerhousedao/switchboard": "6.2.2-dev.8",
|
|
49
|
-
"@renown/sdk": "6.2.2-dev.8",
|
|
50
|
-
"@powerhousedao/vetra": "6.2.2-dev.8",
|
|
51
|
-
"document-model": "6.2.2-dev.8",
|
|
52
|
-
"@powerhousedao/shared": "6.2.2-dev.8"
|
|
52
|
+
"vite": "8.0.10"
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
55
|
"@types/node": "25.2.3",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"build-B5LEeRPm.mjs","sources":["../src/services/build.ts"],"sourcesContent":["import {\n browserBuildConfig,\n nodeBuildConfig,\n} from \"@powerhousedao/shared/build-config\";\nimport { execSync } from \"node:child_process\";\nimport { join } from \"node:path\";\nimport { detect, resolveCommand } from \"package-manager-detector\";\nimport { build as tsdownBuild } from \"tsdown\";\nimport type { BuildArgs } from \"../types.js\";\n\nexport async function runBuild(args: BuildArgs) {\n const { outDir } = args;\n\n await tsdownBuild({\n ...browserBuildConfig,\n outDir: join(outDir, \"browser\"),\n });\n\n await tsdownBuild({\n ...nodeBuildConfig,\n outDir: join(outDir, \"node\"),\n });\n\n const detectResult = await detect();\n const agent = detectResult?.agent ?? \"npm\";\n\n // Emit types with tsc\n const tscCommand = resolveCommand(agent, \"execute-local\", [\"tsc\", \"--build\"]);\n if (tscCommand === null) {\n console.error(\n \"You need to have typescript installed to use the `build` command.\",\n );\n process.exit(1);\n }\n console.log(\"\\n▶ Emitting types via tsc...\");\n try {\n execSync(`${tscCommand.command} ${tscCommand.args.join(\" \")}`, {\n stdio: \"inherit\",\n });\n console.log(\"✔ Types emitted to\", join(outDir, \"types\"));\n } catch {\n console.warn(\n \"✘ tsc reported errors above; declarations were still written. Fix the errors to keep types accurate.\",\n );\n }\n\n const executeLocalCommand = resolveCommand(agent, \"execute-local\", [\n \"tailwindcss\",\n \"-i\",\n \"./style.css\",\n \"-o\",\n \"./dist/style.css\",\n ]);\n if (executeLocalCommand === null) {\n console.error(\n \"You need to have tailwindcss installed to use the `build` command.\",\n );\n process.exit(1);\n }\n execSync(\n `${executeLocalCommand.command} ${executeLocalCommand.args.join(\" \")}`,\n );\n}\n"],"names":["tsdownBuild"],"mappings":";;;;;;;;AAUA,eAAsB,SAAS,MAAiB;CAC9C,MAAM,EAAE,WAAW;AAEnB,OAAMA,MAAY;EAChB,GAAG;EACH,QAAQ,KAAK,QAAQ,UAAU;EAChC,CAAC;AAEF,OAAMA,MAAY;EAChB,GAAG;EACH,QAAQ,KAAK,QAAQ,OAAO;EAC7B,CAAC;CAGF,MAAM,SADe,MAAM,QAAQ,GACP,SAAS;CAGrC,MAAM,aAAa,eAAe,OAAO,iBAAiB,CAAC,OAAO,UAAU,CAAC;AAC7E,KAAI,eAAe,MAAM;AACvB,UAAQ,MACN,oEACD;AACD,UAAQ,KAAK,EAAE;;AAEjB,SAAQ,IAAI,gCAAgC;AAC5C,KAAI;AACF,WAAS,GAAG,WAAW,QAAQ,GAAG,WAAW,KAAK,KAAK,IAAI,IAAI,EAC7D,OAAO,WACR,CAAC;AACF,UAAQ,IAAI,sBAAsB,KAAK,QAAQ,QAAQ,CAAC;SAClD;AACN,UAAQ,KACN,uGACD;;CAGH,MAAM,sBAAsB,eAAe,OAAO,iBAAiB;EACjE;EACA;EACA;EACA;EACA;EACD,CAAC;AACF,KAAI,wBAAwB,MAAM;AAChC,UAAQ,MACN,qEACD;AACD,UAAQ,KAAK,EAAE;;AAEjB,UACE,GAAG,oBAAoB,QAAQ,GAAG,oBAAoB,KAAK,KAAK,IAAI,GACrE","debug_id":"53802aa9-82a4-5f73-8876-9bf4310ea58e"}
|
package/dist/build-CMgv-erS.mjs
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { t as runBuild } from "./build-B5LEeRPm.mjs";
|
|
2
|
-
export { runBuild };
|
|
3
|
-
!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]="03c7575f-6904-5af5-be74-46221d2b3a6f")}catch(e){}}();
|
|
4
|
-
//# debugId=03c7575f-6904-5af5-be74-46221d2b3a6f
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cli-connect-override-CFsTgKB6.mjs","sources":["../src/utils/connect-config-validation.ts","../src/utils/parse-default-drives.ts","../src/utils/cli-connect-override.ts"],"sourcesContent":["// Ajv-backed validation for `ph connect config` writes.\n//\n// Two entry points:\n//\n// - validateConnectKeyValue(key, value)\n// For the `<key> <value>` form. Sets the value at the dotted path inside a\n// stub connect block, then validates the result against the runtime schema.\n// Catches both invalid paths (key doesn't map to a real field) and invalid\n// types (e.g. `connect.renown.chainId \"abc\"` — schema says number).\n//\n// - validateConnectPatch(patch)\n// For the `--json` form. Validates the whole patch as a partial connect.*\n// blob. Same schema, but we only check the keys actually present in the\n// patch (additional keys still fail per `additionalProperties: false`).\n//\n// Both return a typed `connect.*` partial on success or throw with a multi-\n// line, actionable message on failure.\n\nimport { phConnectRuntimeConfigSchema } from \"@powerhousedao/shared/connect\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport AjvNs from \"ajv\";\nimport { isPlainObject, stringToPath } from \"remeda\";\n\ntype PlainObject = Record<string, unknown>;\ntype ConnectPartial = Partial<PHConnectRuntimeConfig>;\n\n// Ajv ships as CJS — under NodeNext ESM the default lands on `.default` while\n// types still point at the class on the namespace. Normalize the constructor.\ntype AjvCtor = new (opts?: Record<string, unknown>) => {\n compile: (schema: unknown) => AjvValidate;\n};\ntype AjvError = { instancePath?: string; message?: string };\ntype AjvValidate = ((data: unknown) => boolean) & {\n errors?: AjvError[] | null;\n};\n\nconst Ajv = ((AjvNs as unknown as { default?: AjvCtor }).default ??\n (AjvNs as unknown as AjvCtor)) as AjvCtor;\n\nconst ajv = new Ajv({ allErrors: true, strict: false });\nconst validateConnect: AjvValidate = ajv.compile(phConnectRuntimeConfigSchema);\n\n/**\n * Parse the CLI-supplied value. Tries JSON first so `true`, `42`, `\"a\"`,\n * `null`, `[1,2]` coerce; falls back to the raw string for unquoted text.\n *\n * Examples:\n * \"true\" -> true (boolean)\n * \"42\" -> 42 (number)\n * '\"x\"' -> \"x\" (string, quoted)\n * \"x\" -> \"x\" (string, bare)\n * \"[1,2]\" -> [1, 2] (array)\n */\nexport function parseCliValue(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n}\n\n/**\n * Strip the optional leading \"connect.\" prefix so callers can pass either\n * \"connect.renown.url\" or \"renown.url\" interchangeably.\n */\nexport function normalizeKey(key: string): string {\n return key.startsWith(\"connect.\") ? key.slice(\"connect.\".length) : key;\n}\n\nfunction formatErrors(errors: AjvError[] | null | undefined): string {\n if (!errors || errors.length === 0) return \"unknown validation error\";\n return errors\n .map((e) => {\n const path = e.instancePath || \"(root)\";\n return ` ${path} ${e.message ?? \"\"}`.trim();\n })\n .join(\"\\n\");\n}\n\n/**\n * Validate a single `<key> <value>` pair. Returns the parsed connect-partial\n * that, when deep-merged into the existing config, applies the change.\n *\n * Throws on:\n * - Empty key\n * - Path that doesn't exist in the schema\n * - Value whose type doesn't match the schema at the leaf path\n */\nexport function validateConnectKeyValue(\n key: string,\n rawValue: string,\n): ConnectPartial {\n const normalized = normalizeKey(key);\n if (!normalized) {\n throw new Error(\n \"ph connect config: key cannot be empty. Pass a dotted path inside connect.* (e.g. connect.renown.url).\",\n );\n }\n const parsed = parseCliValue(rawValue);\n // Build a nested-stub object from the dotted path so Ajv can validate\n // the value's shape against the schema (e.g. \"renown.url\" + parsed →\n // { renown: { url: parsed } }). Remeda's `setPath` requires the path\n // to exist; this is the sparse-creation case, so we fold the parts.\n const stub = stringToPath(normalized).reduceRight<unknown>(\n (acc, key) => ({ [String(key)]: acc }),\n parsed,\n ) as PlainObject;\n if (!validateConnect(stub)) {\n throw new Error(\n `ph connect config: validation failed for key=\"${normalized}\" value=${JSON.stringify(parsed)} (parsed as ${typeof parsed}):\\n${formatErrors(validateConnect.errors)}`,\n );\n }\n return stub;\n}\n\n/**\n * Validate a `--json` bulk override. Returns the parsed partial.\n *\n * `packageRegistryUrl` is a top-level runtime field (not part of the\n * `connect.*` schema). If present in the payload, it is extracted before\n * validation so the connect-only blob can be checked against the schema,\n * then re-attached on the returned object so the caller can route it.\n */\nexport function validateConnectPatch(raw: string): ConnectPartial & {\n packageRegistryUrl?: unknown;\n} {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n throw new Error(\n `ph connect config --json: invalid JSON (${msg}). Expected a partial connect.* blob, e.g. --json '{\"renown\":{\"url\":\"...\"}}'.`,\n { cause: e },\n );\n }\n if (!isPlainObject(parsed)) {\n throw new Error(\n `ph connect config --json: payload must be a JSON object, got ${typeof parsed}.`,\n );\n }\n // Extract `packageRegistryUrl` (top-level field, not in the connect schema)\n // before validating, so a payload like `{\"packageRegistryUrl\":\"…\"}` doesn't\n // fail the `additionalProperties: false` check on the connect schema.\n const top = parsed as PlainObject;\n const hasPackageRegistryUrl = Object.prototype.hasOwnProperty.call(\n top,\n \"packageRegistryUrl\",\n );\n const packageRegistryUrl = top.packageRegistryUrl;\n const connectOnly: PlainObject = { ...top };\n delete connectOnly.packageRegistryUrl;\n if (!validateConnect(connectOnly)) {\n throw new Error(\n `ph connect config --json: validation failed:\\n${formatErrors(validateConnect.errors)}`,\n );\n }\n return hasPackageRegistryUrl\n ? ({ ...connectOnly, packageRegistryUrl } as ConnectPartial & {\n packageRegistryUrl?: unknown;\n })\n : (connectOnly as ConnectPartial);\n}\n","/**\n * Comma-separated URL string → array of `{url, name: null, icon: null}`\n * entries suitable for `connect.drives.defaultDrives`. Used by ph-cli's\n * CLI-override builders and by `ph vetra` when forwarding the local\n * switchboard's drive URLs into the runtime config.\n */\nexport const parseDefaultDrivesUrl = (\n v: string,\n): Array<{ url: string; name: null; icon: null }> =>\n v\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n .map((url) => ({ url, name: null, icon: null }));\n","// Builds a `connectOverride` partial from CLI flags. Shared by:\n//\n// - `ph connect build` — uses `buildCliConnectOverride` to produce the\n// `cliConnectOverride` patch the Vite plugin applies at the top of the\n// precedence ladder:\n//\n// DEFAULT_CONNECT_CONFIG < env-var seeds < source connect.* < --json < individual --flag\n//\n// - `ph connect config` — uses `buildConnectFlagPatch` (the per-field\n// partial builder) to translate flag-set values into the patch that\n// gets dual-written to source + dist `powerhouse.config.json`.\n//\n// `--json` parses as a partial `connect.*` blob and merges in first; then any\n// individual --flag values merge on top, so a flag beats a conflicting --json\n// value.\n\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport { deepMerge } from \"@powerhousedao/shared/connect\";\nimport type { ConnectBuildArgs, ConnectStudioArgs } from \"../types.js\";\nimport {\n normalizeKey,\n parseCliValue,\n validateConnectKeyValue,\n} from \"./connect-config-validation.js\";\nimport { parseDefaultDrivesUrl } from \"./parse-default-drives.js\";\n\ntype PlainObject = Record<string, unknown>;\n\n/**\n * Structural input shape consumed by `buildConnectFlagPatch`. Every property\n * is strict-optional — `undefined` means \"user did not pass this flag\" and\n * the path is excluded from the patch.\n *\n * Callers with cmd-ts-typed args where some flags have built-in defaults\n * (e.g. the 4 commonArgs flags `--base` / `--log-level` /\n * `--default-drives-url` / `--drive-preserve-strategy`) must filter through\n * `wasFlagExplicitlyPassed` BEFORE building this input — otherwise default\n * values like `\"info\"` will silently clobber source `powerhouse.config.json`\n * values.\n */\nexport type ConnectFlagInput = {\n // Strict-optional flags from connectRuntimeOverrideArgs (excluding\n // `packagesRegistry`, which is a top-level runtime field — see\n // `buildCliConnectOverride`).\n json?: string | undefined;\n renownUrl?: string | undefined;\n renownNetworkId?: string | undefined;\n renownChainId?: number | undefined;\n renownNamespace?: string | undefined;\n allowAddDrive?: boolean | undefined;\n externalPackages?: boolean | undefined;\n remoteDrivesEnabled?: boolean | undefined;\n remoteDrivesAllowAdd?: boolean | undefined;\n remoteDrivesAllowDelete?: boolean | undefined;\n localDrivesEnabled?: boolean | undefined;\n localDrivesAllowAdd?: boolean | undefined;\n localDrivesAllowDelete?: boolean | undefined;\n appName?: string | undefined;\n homeBackground?: string | undefined;\n sentryDsn?: string | undefined;\n sentryEnv?: string | undefined;\n sentryTracingEnabled?: boolean | undefined;\n // commonArgs flags. Callers must apply `wasFlagExplicitlyPassed`\n // filtering (see above).\n basePath?: string | undefined;\n logLevel?: string | undefined;\n defaultDrivesUrl?: string | undefined;\n drivesPreserveStrategy?: string | undefined;\n};\n\n/**\n * Parse the `--json` payload (if any). Throws on malformed JSON or on a\n * non-object root with a clear, command-line-visible error.\n */\nfunction parseJsonOverride(raw: string | undefined): PlainObject {\n if (raw === undefined || raw === \"\") return {};\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n throw new Error(\n `--json: invalid JSON (${msg}). Expected a partial 'connect.*' blob, e.g. --json '{\"renown\":{\"url\":\"...\"}}'.`,\n { cause: e },\n );\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\n `--json: payload must be a JSON object, got ${typeof parsed}.`,\n );\n }\n return parsed as PlainObject;\n}\n\n/**\n * Re-exported for `runConnectConfig` so the same JSON validation runs for\n * both `build --json` and `config --json`.\n */\nexport function parseConnectJsonArg(raw: string | undefined): PlainObject {\n return parseJsonOverride(raw);\n}\n\nfunction setIfDefined<V>(\n target: PlainObject,\n key: string,\n value: V | undefined,\n): void {\n if (value !== undefined) target[key] = value;\n}\n\n/**\n * Detect whether the user literally typed `--<longName>` on the command\n * line. Used to gate the 4 commonArgs flags through `cliConnectOverride` —\n * those flags have cmd-ts defaults, so their parsed value is always\n * defined, and a naive merge would silently clobber source values with the\n * default on every build.\n *\n * Handles both `--flag value` and `--flag=value` forms.\n */\nexport function wasFlagExplicitlyPassed(longName: string): boolean {\n const dashed = `--${longName}`;\n return process.argv.some(\n (arg) => arg === dashed || arg.startsWith(`${dashed}=`),\n );\n}\n\n/**\n * Build a `connect.*` partial from the 19 field flags. Only includes paths\n * the user explicitly set (undefined values are excluded).\n *\n * Single source of truth for the flag → JSON-path mapping; consumed by both\n * `ph connect build` and `ph connect config`.\n */\nexport function buildConnectFlagPatch(args: ConnectFlagInput): PlainObject {\n const out: PlainObject = {};\n\n const app: PlainObject = {};\n setIfDefined(app, \"basePath\", args.basePath);\n setIfDefined(app, \"logLevel\", args.logLevel);\n if (Object.keys(app).length > 0) out.app = app;\n\n const renown: PlainObject = {};\n setIfDefined(renown, \"url\", args.renownUrl);\n setIfDefined(renown, \"networkId\", args.renownNetworkId);\n setIfDefined(renown, \"chainId\", args.renownChainId);\n setIfDefined(renown, \"namespace\", args.renownNamespace);\n if (Object.keys(renown).length > 0) out.renown = renown;\n\n const packages: PlainObject = {};\n setIfDefined(packages, \"externalEnabled\", args.externalPackages);\n if (Object.keys(packages).length > 0) out.packages = packages;\n\n // --home-background: empty string is the explicit \"set null\" form\n // (cmd-ts can't pass `null` directly through a string option).\n const branding: PlainObject = {};\n setIfDefined(branding, \"appName\", args.appName);\n if (args.homeBackground !== undefined) {\n branding.homeBackground =\n args.homeBackground === \"\" ? null : args.homeBackground;\n }\n if (Object.keys(branding).length > 0) out.branding = branding;\n\n // --sentry-dsn: empty string is the explicit \"set null\" form (disables\n // Sentry). Same pattern as --home-background.\n const sentry: PlainObject = {};\n if (args.sentryDsn !== undefined) {\n sentry.dsn = args.sentryDsn === \"\" ? null : args.sentryDsn;\n }\n setIfDefined(sentry, \"env\", args.sentryEnv);\n setIfDefined(sentry, \"tracing\", args.sentryTracingEnabled);\n if (Object.keys(sentry).length > 0) out.sentry = sentry;\n\n const drives: PlainObject = {};\n setIfDefined(drives, \"allowAddDrive\", args.allowAddDrive);\n setIfDefined(drives, \"preserveStrategy\", args.drivesPreserveStrategy);\n if (args.defaultDrivesUrl !== undefined && args.defaultDrivesUrl !== \"\") {\n drives.defaultDrives = parseDefaultDrivesUrl(args.defaultDrivesUrl);\n }\n\n const remote: PlainObject = {};\n setIfDefined(remote, \"enabled\", args.remoteDrivesEnabled);\n setIfDefined(remote, \"allowAdd\", args.remoteDrivesAllowAdd);\n setIfDefined(remote, \"allowDelete\", args.remoteDrivesAllowDelete);\n\n const local: PlainObject = {};\n setIfDefined(local, \"enabled\", args.localDrivesEnabled);\n setIfDefined(local, \"allowAdd\", args.localDrivesAllowAdd);\n setIfDefined(local, \"allowDelete\", args.localDrivesAllowDelete);\n\n const sections: PlainObject = {};\n if (Object.keys(remote).length > 0) sections.remote = remote;\n if (Object.keys(local).length > 0) sections.local = local;\n if (Object.keys(sections).length > 0) drives.sections = sections;\n if (Object.keys(drives).length > 0) out.drives = drives;\n\n return out;\n}\n\n/**\n * Combine `--json` and the individual flag values into the two override\n * inputs `ph connect build` forwards to the Vite plugin:\n *\n * - `connectOverride`: a partial `connect.*` patch (deep-merged at the top\n * of the runtime-config precedence ladder).\n * - `packageRegistryUrl`: a separate top-level override; mirrors the\n * source-config top-level field (the SPA reads it directly).\n *\n * `--packages-registry` and `--json` containing a top-level\n * `packageRegistryUrl` both flow into `packageRegistryUrl`; the flag wins on\n * collision. Returns `undefined` for whichever override was not supplied.\n *\n * The 4 commonArgs flags (`--base`, `--log-level`, `--default-drives-url`,\n * `--drive-preserve-strategy`) are gated through `wasFlagExplicitlyPassed`\n * because they carry cmd-ts defaults that would otherwise leak into the\n * override on every build.\n */\nexport function buildCliConnectOverride(args: ConnectBuildArgs): {\n connectOverride: PHConnectRuntimeConfig | undefined;\n packageRegistryUrl: string | undefined;\n} {\n const fromJson = parseJsonOverride(args.json);\n\n const input: ConnectFlagInput = {\n renownUrl: args.renownUrl,\n renownNetworkId: args.renownNetworkId,\n renownChainId: args.renownChainId,\n renownNamespace: args.renownNamespace,\n allowAddDrive: args.allowAddDrive,\n externalPackages: args.externalPackages,\n remoteDrivesEnabled: args.remoteDrivesEnabled,\n remoteDrivesAllowAdd: args.remoteDrivesAllowAdd,\n remoteDrivesAllowDelete: args.remoteDrivesAllowDelete,\n localDrivesEnabled: args.localDrivesEnabled,\n localDrivesAllowAdd: args.localDrivesAllowAdd,\n localDrivesAllowDelete: args.localDrivesAllowDelete,\n appName: args.appName,\n homeBackground: args.homeBackground,\n sentryDsn: args.sentryDsn,\n sentryEnv: args.sentryEnv,\n sentryTracingEnabled: args.sentryTracingEnabled,\n // commonArgs flags — only forward when the user explicitly passed them.\n basePath: wasFlagExplicitlyPassed(\"base\")\n ? args.connectBasePath\n : undefined,\n logLevel: wasFlagExplicitlyPassed(\"log-level\") ? args.logLevel : undefined,\n defaultDrivesUrl: wasFlagExplicitlyPassed(\"default-drives-url\")\n ? args.defaultDrivesUrl\n : undefined,\n drivesPreserveStrategy: wasFlagExplicitlyPassed(\"drive-preserve-strategy\")\n ? args.drivesPreserveStrategy\n : undefined,\n };\n\n const fromFlags = buildConnectFlagPatch(input);\n\n // Positional `<key> <value>` override (only set when both are present;\n // `runConnectBuild` rejects the 1-positional case up front because build\n // has no read mode). Layered on top of --json + flags so a positional\n // override wins on collision — matches the user's literal command line.\n let positionalRegistry: string | undefined;\n let fromPositional: PlainObject = {};\n if (args.keyPositional !== undefined && args.valuePositional !== undefined) {\n const normalized = normalizeKey(args.keyPositional);\n if (!normalized) {\n throw new Error(\n \"ph connect build: positional <key> cannot be empty. Pass a dotted path inside connect.* (e.g. connect.renown.url).\",\n );\n }\n if (normalized === \"packageRegistryUrl\") {\n const parsed = parseCliValue(args.valuePositional);\n if (typeof parsed !== \"string\") {\n throw new Error(\n `ph connect build: positional packageRegistryUrl must be a string (got ${typeof parsed}).`,\n );\n }\n positionalRegistry = parsed;\n } else {\n fromPositional = validateConnectKeyValue(\n normalized,\n args.valuePositional,\n );\n }\n }\n\n // Top-level `packageRegistryUrl` can come from --json (top-level),\n // --packages-registry flag, or positional `packageRegistryUrl <value>`.\n // Precedence (highest → lowest): positional > flag > --json.\n const jsonRegistry =\n typeof fromJson.packageRegistryUrl === \"string\"\n ? (fromJson.packageRegistryUrl as string)\n : undefined;\n const packageRegistryUrl =\n positionalRegistry ?? args.packagesRegistry ?? jsonRegistry;\n // Strip the top-level field from the JSON patch before deep-merging into\n // the connect partial — it isn't a `connect.*` field.\n const jsonConnect = { ...fromJson };\n delete jsonConnect.packageRegistryUrl;\n\n const hasJsonConnect = Object.keys(jsonConnect).length > 0;\n const hasFlags = Object.keys(fromFlags).length > 0;\n const hasPositional = Object.keys(fromPositional).length > 0;\n const connectOverride =\n !hasJsonConnect && !hasFlags && !hasPositional\n ? undefined\n : deepMerge(\n deepMerge(\n jsonConnect as PHConnectRuntimeConfig,\n fromFlags as PHConnectRuntimeConfig,\n ),\n fromPositional as PHConnectRuntimeConfig,\n );\n\n return { connectOverride, packageRegistryUrl };\n}\n\n/**\n * Parallel of `buildCliConnectOverride` for `ph connect studio` / `ph vetra`.\n * Studio only exposes the 4 commonArgs flags (`--base`, `--log-level`,\n * `--default-drives-url`, `--drive-preserve-strategy`); each is gated through\n * `wasFlagExplicitlyPassed` so cmd-ts defaults don't leak into the override.\n *\n * `callerOverride` is supplied by wrappers around studio (notably `ph vetra`,\n * which sets default drives + preserveStrategy directly). The flag override\n * deep-merges on top of it: caller choices apply for every flag the user\n * didn't type, but an explicitly passed flag (e.g. `--default-drives-url`)\n * always wins.\n */\nexport function buildStudioConnectOverride(\n args: ConnectStudioArgs,\n callerOverride: PHConnectRuntimeConfig | undefined,\n): PHConnectRuntimeConfig | undefined {\n const flagOverride = buildConnectFlagPatch({\n basePath: wasFlagExplicitlyPassed(\"base\")\n ? args.connectBasePath\n : undefined,\n logLevel: wasFlagExplicitlyPassed(\"log-level\") ? args.logLevel : undefined,\n defaultDrivesUrl: wasFlagExplicitlyPassed(\"default-drives-url\")\n ? args.defaultDrivesUrl\n : undefined,\n drivesPreserveStrategy: wasFlagExplicitlyPassed(\"drive-preserve-strategy\")\n ? args.drivesPreserveStrategy\n : undefined,\n renownNamespace: args.renownNamespace,\n }) as PHConnectRuntimeConfig;\n\n // Studio commands (`ph connect studio`, `ph vetra`) always run in studio\n // mode: Connect loads the vetra package and offers builder document types.\n const studioOverride: PHConnectRuntimeConfig = { app: { studioMode: true } };\n return [callerOverride, flagOverride, studioOverride]\n .filter(\n (o): o is PHConnectRuntimeConfig =>\n o !== undefined && Object.keys(o).length > 0,\n )\n .reduce((acc, o) => deepMerge(acc, o), {} as PHConnectRuntimeConfig);\n}\n"],"names":[],"mappings":";;;;;;AAwCA,MAAM,kBADM,KAHE,MAA2C,WACtD,OAEiB;CAAE,WAAW;CAAM,QAAQ;CAAO,CAAC,CACd,QAAQ,6BAA6B;;;;;;;;;;;;AAa9E,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