@powerhousedao/ph-cli 6.2.2-dev.10 → 6.2.2-dev.11

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.
@@ -0,0 +1,4 @@
1
+ import { n as runBuild } from "./build-uQXq6_HU.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]="07cbb8f4-54b7-5333-be22-8ce017cd9e53")}catch(e){}}();
4
+ //# debugId=07cbb8f4-54b7-5333-be22-8ce017cd9e53
@@ -1,13 +1,35 @@
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]="53802aa9-82a4-5f73-8876-9bf4310ea58e")}catch(e){}}();
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]="a81d56d6-7b6c-5288-ac91-899d56570def")}catch(e){}}();
3
3
  import { execSync } from "node:child_process";
4
4
  import { browserBuildConfig, nodeBuildConfig } from "@powerhousedao/shared/build-config";
5
+ import { existsSync, readFileSync } from "node:fs";
5
6
  import { join } from "node:path";
6
7
  import { detect, resolveCommand } from "package-manager-detector";
8
+ import { readPackage } from "read-pkg";
7
9
  import { build } from "tsdown";
8
10
  //#region src/services/build.ts
11
+ /**
12
+ * A Powerhouse package's `powerhouse.manifest.json` "name" must match its
13
+ * `package.json` "name" — Connect and the registry resolve installed versions
14
+ * by treating the manifest name as the npm package name, so a mismatch silently
15
+ * breaks resolution. Fail the build early if they diverge. No-op when the
16
+ * project has no manifest (nothing to compare).
17
+ */
18
+ async function assertManifestNameMatchesPackage(projectPath) {
19
+ const manifestPath = join(projectPath, "powerhouse.manifest.json");
20
+ if (!existsSync(manifestPath)) return;
21
+ const { name: packageName } = await readPackage({ cwd: projectPath });
22
+ let manifestName;
23
+ try {
24
+ manifestName = JSON.parse(readFileSync(manifestPath, "utf-8")).name;
25
+ } catch {
26
+ throw new Error(`Failed to parse "powerhouse.manifest.json" at ${manifestPath}. Make sure it is valid JSON.`);
27
+ }
28
+ if (manifestName !== packageName) throw new Error(`Package name mismatch — "package.json" and "powerhouse.manifest.json" must have the same "name":\n package.json "name": ${JSON.stringify(packageName)}\n powerhouse.manifest.json "name": ${JSON.stringify(manifestName)}\n\nUpdate one so they match, then run the build again.`);
29
+ }
9
30
  async function runBuild(args) {
10
31
  const { outDir } = args;
32
+ await assertManifestNameMatchesPackage(process.cwd());
11
33
  await build({
12
34
  ...browserBuildConfig,
13
35
  outDir: join(outDir, "browser")
@@ -43,7 +65,7 @@ async function runBuild(args) {
43
65
  execSync(`${executeLocalCommand.command} ${executeLocalCommand.args.join(" ")}`);
44
66
  }
45
67
  //#endregion
46
- export { runBuild as t };
68
+ export { runBuild as n, assertManifestNameMatchesPackage as t };
47
69
 
48
- //# sourceMappingURL=build-B5LEeRPm.mjs.map
49
- //# debugId=53802aa9-82a4-5f73-8876-9bf4310ea58e
70
+ //# sourceMappingURL=build-uQXq6_HU.mjs.map
71
+ //# debugId=a81d56d6-7b6c-5288-ac91-899d56570def
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build-uQXq6_HU.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 { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { detect, resolveCommand } from \"package-manager-detector\";\nimport { readPackage } from \"read-pkg\";\nimport { build as tsdownBuild } from \"tsdown\";\nimport type { BuildArgs } from \"../types.js\";\n\n/**\n * A Powerhouse package's `powerhouse.manifest.json` \"name\" must match its\n * `package.json` \"name\" — Connect and the registry resolve installed versions\n * by treating the manifest name as the npm package name, so a mismatch silently\n * breaks resolution. Fail the build early if they diverge. No-op when the\n * project has no manifest (nothing to compare).\n */\nexport async function assertManifestNameMatchesPackage(projectPath: string) {\n const manifestPath = join(projectPath, \"powerhouse.manifest.json\");\n if (!existsSync(manifestPath)) return;\n\n const { name: packageName } = await readPackage({ cwd: projectPath });\n\n let manifestName: unknown;\n try {\n manifestName = (\n JSON.parse(readFileSync(manifestPath, \"utf-8\")) as { name?: unknown }\n ).name;\n } catch {\n throw new Error(\n `Failed to parse \"powerhouse.manifest.json\" at ${manifestPath}. Make sure it is valid JSON.`,\n );\n }\n\n if (manifestName !== packageName) {\n throw new Error(\n `Package name mismatch — \"package.json\" and \"powerhouse.manifest.json\" must have the same \"name\":\\n` +\n ` package.json \"name\": ${JSON.stringify(packageName)}\\n` +\n ` powerhouse.manifest.json \"name\": ${JSON.stringify(manifestName)}\\n\\n` +\n `Update one so they match, then run the build again.`,\n );\n }\n}\n\nexport async function runBuild(args: BuildArgs) {\n const { outDir } = args;\n\n // Fail fast if the manifest name and package.json name have drifted apart.\n await assertManifestNameMatchesPackage(process.cwd());\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":";;;;;;;;;;;;;;;;;AAmBA,eAAsB,iCAAiC,aAAqB;CAC1E,MAAM,eAAe,KAAK,aAAa,2BAA2B;AAClE,KAAI,CAAC,WAAW,aAAa,CAAE;CAE/B,MAAM,EAAE,MAAM,gBAAgB,MAAM,YAAY,EAAE,KAAK,aAAa,CAAC;CAErE,IAAI;AACJ,KAAI;AACF,iBACE,KAAK,MAAM,aAAa,cAAc,QAAQ,CAAC,CAC/C;SACI;AACN,QAAM,IAAI,MACR,iDAAiD,aAAa,+BAC/D;;AAGH,KAAI,iBAAiB,YACnB,OAAM,IAAI,MACR,wIACwC,KAAK,UAAU,YAAY,CAAC,uCAC5B,KAAK,UAAU,aAAa,CAAC,yDAEtE;;AAIL,eAAsB,SAAS,MAAiB;CAC9C,MAAM,EAAE,WAAW;AAGnB,OAAM,iCAAiC,QAAQ,KAAK,CAAC;AAErD,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":"a81d56d6-7b6c-5288-ac91-899d56570def"}
package/dist/cli.mjs CHANGED
@@ -15,7 +15,7 @@ import { createInterface } from "node:readline/promises";
15
15
  import { bold, yellow } from "colorette";
16
16
  //#region src/get-version.ts
17
17
  function getVersion() {
18
- return "6.2.2-dev.10";
18
+ return "6.2.2-dev.11";
19
19
  }
20
20
  //#endregion
21
21
  //#region src/utils/constants.ts
@@ -105,7 +105,7 @@ const build$1 = command({
105
105
  handler: async (args) => {
106
106
  if (args.debug) console.log(args);
107
107
  try {
108
- const { runBuild } = await import("./build-CMgv-erS.mjs");
108
+ const { runBuild } = await import("./build-C-A5-ipO.mjs");
109
109
  await runBuild(args);
110
110
  } catch (error) {
111
111
  console.error(error);
@@ -152,7 +152,7 @@ Build has no read mode; passing only <key> without <value> errors out (use \`ph
152
152
  args: connectBuildArgs,
153
153
  handler: async (args) => {
154
154
  if (args.debug) console.log(args);
155
- const { runConnectBuild } = await import("./connect-build-BtaMnrYu.mjs");
155
+ const { runConnectBuild } = await import("./connect-build-CjAEjO8Q.mjs");
156
156
  await runConnectBuild(args);
157
157
  process.exit(0);
158
158
  }
@@ -187,7 +187,7 @@ Writes go to:
187
187
  `,
188
188
  args: connectConfigArgs,
189
189
  handler: async (args) => {
190
- const { runConnectConfig } = await import("./connect-config-O3qXExg9.mjs");
190
+ const { runConnectConfig } = await import("./connect-config-Bwv3d3uD.mjs");
191
191
  await runConnectConfig(args);
192
192
  }
193
193
  })
@@ -528,7 +528,7 @@ This command:
528
528
  args: inspectArgs,
529
529
  handler: async (args) => {
530
530
  if (args.debug) console.log(args);
531
- const { startInspect } = await import("./inspect-CKdafPbC.mjs");
531
+ const { startInspect } = await import("./inspect-DXjbQEV_.mjs");
532
532
  startInspect(args);
533
533
  process.exit(0);
534
534
  }
@@ -607,7 +607,7 @@ Resolution order for the registry URL:
607
607
  throw error;
608
608
  }
609
609
  }
610
- const { updateConfigFile, updateStylesFile } = await import("./utils-DPGwKNam.mjs");
610
+ const { updateConfigFile, updateStylesFile } = await import("./utils-BzwczAW-.mjs");
611
611
  try {
612
612
  console.log("⚙️ Updating powerhouse config file...");
613
613
  updateConfigFile(dependenciesWithVersions, projectPath, "install", args.local ? "local" : "registry", registryUrl, args.registry !== void 0);
@@ -785,7 +785,7 @@ const migrate = command({
785
785
  description: "Run migrations",
786
786
  handler: async (args) => {
787
787
  if (args.debug) console.log(args);
788
- const { startMigrate } = await import("./migrate-BJQvY88v.mjs");
788
+ const { startMigrate } = await import("./migrate-jGKfE02L.mjs");
789
789
  await startMigrate(args);
790
790
  process.exit(0);
791
791
  }
@@ -1021,7 +1021,7 @@ This command:
1021
1021
  console.error("❌ Failed to uninstall dependencies");
1022
1022
  throw error;
1023
1023
  }
1024
- const { removeStylesImports, updateConfigFile } = await import("./utils-DPGwKNam.mjs");
1024
+ const { removeStylesImports, updateConfigFile } = await import("./utils-BzwczAW-.mjs");
1025
1025
  try {
1026
1026
  console.log("⚙️ Updating powerhouse config file...");
1027
1027
  updateConfigFile(dependenciesWithVersions, projectPath, "uninstall");
@@ -1152,7 +1152,7 @@ This command:
1152
1152
  args: vetraArgs,
1153
1153
  handler: async (args) => {
1154
1154
  if (args.debug) console.log(args);
1155
- const { startVetra } = await import("./vetra-D9MTB556.mjs");
1155
+ const { startVetra } = await import("./vetra-Chnn6I6A.mjs");
1156
1156
  await startVetra(args);
1157
1157
  }
1158
1158
  }),
@@ -1,11 +1,11 @@
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]="dc494274-1708-5d29-a306-0842e1d42768")}catch(e){}}();
3
- import { t as runBuild } from "./build-B5LEeRPm.mjs";
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]="03f33837-8290-5947-ac4f-1b9873fd7618")}catch(e){}}();
3
+ import { n as runBuild } from "./build-uQXq6_HU.mjs";
4
4
  import { t as buildCliConnectOverride } from "./cli-connect-override-CFsTgKB6.mjs";
5
+ import { existsSync } from "node:fs";
5
6
  import { join } from "node:path";
6
7
  import { getConnectBaseViteConfig } from "@powerhousedao/builder-tools";
7
8
  import { getConfig } from "@powerhousedao/shared/clis";
8
- import { existsSync } from "node:fs";
9
9
  import { build, mergeConfig } from "vite";
10
10
  //#region src/services/connect-build.ts
11
11
  async function runConnectBuild(args) {
@@ -39,5 +39,5 @@ function assertLocalPackagesInstalled(projectPath) {
39
39
  //#endregion
40
40
  export { runConnectBuild };
41
41
 
42
- //# sourceMappingURL=connect-build-BtaMnrYu.mjs.map
43
- //# debugId=dc494274-1708-5d29-a306-0842e1d42768
42
+ //# sourceMappingURL=connect-build-CjAEjO8Q.mjs.map
43
+ //# debugId=03f33837-8290-5947-ac4f-1b9873fd7618
@@ -1 +1 @@
1
- {"version":3,"file":"connect-build-BtaMnrYu.mjs","sources":["../src/services/connect-build.ts"],"sourcesContent":["import { getConnectBaseViteConfig } from \"@powerhousedao/builder-tools\";\nimport { getConfig } from \"@powerhousedao/shared/clis\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { InlineConfig } from \"vite\";\nimport { build, mergeConfig } from \"vite\";\nimport type { ConnectBuildArgs } from \"../types.js\";\nimport { buildCliConnectOverride } from \"../utils/cli-connect-override.js\";\nimport { runBuild } from \"./build.js\";\n\nexport async function runConnectBuild(args: ConnectBuildArgs) {\n const { outDir, debug, dynamicBase, favicon } = args;\n\n const mode = \"production\";\n const dirname = process.cwd();\n\n // Build has no read mode; a bare positional `<key>` is a user error. The\n // 2-positional `<key> <value>` form is handled inside buildCliConnectOverride\n // so it layers on top of --json + flags like any other override input.\n if (args.keyPositional !== undefined && args.valuePositional === undefined) {\n throw new Error(\n \"ph connect build: positional override requires both <key> and <value> (e.g. `ph connect build connect.renown.url https://renown.staging`). To read a value, use `ph connect config <key>`.\",\n );\n }\n\n // Fail fast if any package marked as provider: \"local\" is missing from\n // node_modules — the Vite plugin that bundles them needs them on disk.\n assertLocalPackagesInstalled(dirname);\n\n // Build the CLI override layers (--json + individual flags + positional)\n // once here so a bad payload fails before we waste a build.\n // `--packages-registry` lands at the top-level `packageRegistryUrl`\n // (mirrors source-config shape); every other flag feeds the connect-block\n // precedence ladder.\n const { connectOverride, packageRegistryUrl } = buildCliConnectOverride(args);\n\n await runBuild({\n outDir: \"dist\",\n debug,\n });\n\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride: connectOverride,\n cliPackageRegistryUrl: packageRegistryUrl,\n dynamicBase,\n favicon,\n });\n\n const buildConfig: InlineConfig = {\n build: {\n outDir,\n },\n };\n\n const config = mergeConfig(baseConfig, buildConfig);\n\n await build(config);\n}\n\nfunction assertLocalPackagesInstalled(projectPath: string) {\n const config = getConfig(join(projectPath, \"powerhouse.config.json\"));\n const localPackages = (config.packages ?? []).filter(\n (p) => p.provider === \"local\",\n );\n if (localPackages.length === 0) return;\n\n const missing = localPackages.filter(\n (p) =>\n !existsSync(\n join(projectPath, \"node_modules\", p.packageName, \"package.json\"),\n ),\n );\n if (missing.length === 0) return;\n\n const names = missing.map((p) => p.packageName);\n throw new Error(\n `ph connect build requires these packages to be installed in node_modules (they are declared with provider: \"local\" in powerhouse.config.json):\\n` +\n names.map((n) => ` - ${n}`).join(\"\\n\") +\n `\\n\\nInstall them with:\\n ph install --local ${names.join(\" \")}`,\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;AAUA,eAAsB,gBAAgB,MAAwB;CAC5D,MAAM,EAAE,QAAQ,OAAO,aAAa,YAAY;CAEhD,MAAM,OAAO;CACb,MAAM,UAAU,QAAQ,KAAK;AAK7B,KAAI,KAAK,kBAAkB,KAAA,KAAa,KAAK,oBAAoB,KAAA,EAC/D,OAAM,IAAI,MACR,6LACD;AAKH,8BAA6B,QAAQ;CAOrC,MAAM,EAAE,iBAAiB,uBAAuB,wBAAwB,KAAK;AAE7E,OAAM,SAAS;EACb,QAAQ;EACR;EACD,CAAC;AAmBF,OAAM,MAFS,YAfI,yBAAyB;EAC1C;EACA;EACA,oBAAoB;EACpB,uBAAuB;EACvB;EACA;EACD,CAAC,EAEgC,EAChC,OAAO,EACL,QACD,EACF,CAEkD,CAEhC;;AAGrB,SAAS,6BAA6B,aAAqB;CAEzD,MAAM,iBADS,UAAU,KAAK,aAAa,yBAAyB,CAAC,CACvC,YAAY,EAAE,EAAE,QAC3C,MAAM,EAAE,aAAa,QACvB;AACD,KAAI,cAAc,WAAW,EAAG;CAEhC,MAAM,UAAU,cAAc,QAC3B,MACC,CAAC,WACC,KAAK,aAAa,gBAAgB,EAAE,aAAa,eAAe,CACjE,CACJ;AACD,KAAI,QAAQ,WAAW,EAAG;CAE1B,MAAM,QAAQ,QAAQ,KAAK,MAAM,EAAE,YAAY;AAC/C,OAAM,IAAI,MACR,qJACE,MAAM,KAAK,MAAM,OAAO,IAAI,CAAC,KAAK,KAAK,GACvC,gDAAgD,MAAM,KAAK,IAAI,GAClE","debug_id":"dc494274-1708-5d29-a306-0842e1d42768"}
1
+ {"version":3,"file":"connect-build-CjAEjO8Q.mjs","sources":["../src/services/connect-build.ts"],"sourcesContent":["import { getConnectBaseViteConfig } from \"@powerhousedao/builder-tools\";\nimport { getConfig } from \"@powerhousedao/shared/clis\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { InlineConfig } from \"vite\";\nimport { build, mergeConfig } from \"vite\";\nimport type { ConnectBuildArgs } from \"../types.js\";\nimport { buildCliConnectOverride } from \"../utils/cli-connect-override.js\";\nimport { runBuild } from \"./build.js\";\n\nexport async function runConnectBuild(args: ConnectBuildArgs) {\n const { outDir, debug, dynamicBase, favicon } = args;\n\n const mode = \"production\";\n const dirname = process.cwd();\n\n // Build has no read mode; a bare positional `<key>` is a user error. The\n // 2-positional `<key> <value>` form is handled inside buildCliConnectOverride\n // so it layers on top of --json + flags like any other override input.\n if (args.keyPositional !== undefined && args.valuePositional === undefined) {\n throw new Error(\n \"ph connect build: positional override requires both <key> and <value> (e.g. `ph connect build connect.renown.url https://renown.staging`). To read a value, use `ph connect config <key>`.\",\n );\n }\n\n // Fail fast if any package marked as provider: \"local\" is missing from\n // node_modules — the Vite plugin that bundles them needs them on disk.\n assertLocalPackagesInstalled(dirname);\n\n // Build the CLI override layers (--json + individual flags + positional)\n // once here so a bad payload fails before we waste a build.\n // `--packages-registry` lands at the top-level `packageRegistryUrl`\n // (mirrors source-config shape); every other flag feeds the connect-block\n // precedence ladder.\n const { connectOverride, packageRegistryUrl } = buildCliConnectOverride(args);\n\n await runBuild({\n outDir: \"dist\",\n debug,\n });\n\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride: connectOverride,\n cliPackageRegistryUrl: packageRegistryUrl,\n dynamicBase,\n favicon,\n });\n\n const buildConfig: InlineConfig = {\n build: {\n outDir,\n },\n };\n\n const config = mergeConfig(baseConfig, buildConfig);\n\n await build(config);\n}\n\nfunction assertLocalPackagesInstalled(projectPath: string) {\n const config = getConfig(join(projectPath, \"powerhouse.config.json\"));\n const localPackages = (config.packages ?? []).filter(\n (p) => p.provider === \"local\",\n );\n if (localPackages.length === 0) return;\n\n const missing = localPackages.filter(\n (p) =>\n !existsSync(\n join(projectPath, \"node_modules\", p.packageName, \"package.json\"),\n ),\n );\n if (missing.length === 0) return;\n\n const names = missing.map((p) => p.packageName);\n throw new Error(\n `ph connect build requires these packages to be installed in node_modules (they are declared with provider: \"local\" in powerhouse.config.json):\\n` +\n names.map((n) => ` - ${n}`).join(\"\\n\") +\n `\\n\\nInstall them with:\\n ph install --local ${names.join(\" \")}`,\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;AAUA,eAAsB,gBAAgB,MAAwB;CAC5D,MAAM,EAAE,QAAQ,OAAO,aAAa,YAAY;CAEhD,MAAM,OAAO;CACb,MAAM,UAAU,QAAQ,KAAK;AAK7B,KAAI,KAAK,kBAAkB,KAAA,KAAa,KAAK,oBAAoB,KAAA,EAC/D,OAAM,IAAI,MACR,6LACD;AAKH,8BAA6B,QAAQ;CAOrC,MAAM,EAAE,iBAAiB,uBAAuB,wBAAwB,KAAK;AAE7E,OAAM,SAAS;EACb,QAAQ;EACR;EACD,CAAC;AAmBF,OAAM,MAFS,YAfI,yBAAyB;EAC1C;EACA;EACA,oBAAoB;EACpB,uBAAuB;EACvB;EACA;EACD,CAAC,EAEgC,EAChC,OAAO,EACL,QACD,EACF,CAEkD,CAEhC;;AAGrB,SAAS,6BAA6B,aAAqB;CAEzD,MAAM,iBADS,UAAU,KAAK,aAAa,yBAAyB,CAAC,CACvC,YAAY,EAAE,EAAE,QAC3C,MAAM,EAAE,aAAa,QACvB;AACD,KAAI,cAAc,WAAW,EAAG;CAEhC,MAAM,UAAU,cAAc,QAC3B,MACC,CAAC,WACC,KAAK,aAAa,gBAAgB,EAAE,aAAa,eAAe,CACjE,CACJ;AACD,KAAI,QAAQ,WAAW,EAAG;CAE1B,MAAM,QAAQ,QAAQ,KAAK,MAAM,EAAE,YAAY;AAC/C,OAAM,IAAI,MACR,qJACE,MAAM,KAAK,MAAM,OAAO,IAAI,CAAC,KAAK,KAAK,GACvC,gDAAgD,MAAM,KAAK,IAAI,GAClE","debug_id":"03f33837-8290-5947-ac4f-1b9873fd7618"}
@@ -1,8 +1,8 @@
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]="bdeba91a-33bc-543e-87f8-cc51074d0b17")}catch(e){}}();
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]="a1f9834f-cd0a-506d-9d79-62579f3ee62e")}catch(e){}}();
3
3
  import { c as validateConnectKeyValue, i as wasFlagExplicitlyPassed, l as validateConnectPatch, n as buildConnectFlagPatch, o as normalizeKey, s as parseCliValue } from "./cli-connect-override-CFsTgKB6.mjs";
4
- import { isAbsolute, join, resolve } from "node:path";
5
4
  import { existsSync } from "node:fs";
5
+ import { isAbsolute, join, resolve } from "node:path";
6
6
  import { ConfigLoader, DEFAULT_CONNECT_CONFIG, JsonConfigAdapter, deepMerge } from "@powerhousedao/shared/connect";
7
7
  import { stringToPath } from "remeda";
8
8
  //#region src/utils/get-at-path.ts
@@ -183,5 +183,5 @@ async function runConnectConfig(args) {
183
183
  //#endregion
184
184
  export { runConnectConfig };
185
185
 
186
- //# sourceMappingURL=connect-config-O3qXExg9.mjs.map
187
- //# debugId=bdeba91a-33bc-543e-87f8-cc51074d0b17
186
+ //# sourceMappingURL=connect-config-Bwv3d3uD.mjs.map
187
+ //# debugId=a1f9834f-cd0a-506d-9d79-62579f3ee62e
@@ -1 +1 @@
1
- {"version":3,"file":"connect-config-O3qXExg9.mjs","sources":["../src/utils/get-at-path.ts","../src/services/connect-config.ts"],"sourcesContent":["/**\n * Walk a parsed path (e.g. from remeda's `stringToPath`) through a runtime-\n * typed object, returning the value or `undefined` if any segment is\n * missing.\n *\n * Remeda's `prop` is overload-typed for compile-time literal paths and\n * doesn't accept a runtime path array via spread, so we walk inline for\n * the dynamic-path case used by `ph connect config --get`.\n */\nexport function getAtPath(\n obj: unknown,\n parts: ReadonlyArray<string | number>,\n): unknown {\n let cur: unknown = obj;\n for (const key of parts) {\n if (cur === null || typeof cur !== \"object\") return undefined;\n cur = (cur as Record<string, unknown>)[String(key)];\n }\n return cur;\n}\n","// `ph connect config` — read or update Connect's runtime configuration.\n//\n// Mode dispatch (exactly one mode per invocation; mutex enforced below):\n//\n// ph connect config → list mode (print effective merged config)\n// ph connect config <key> → get mode (positional)\n// ph connect config --get <dotted.path> → get mode (flag form, equivalent)\n// ph connect config <key> <value> → set mode (positional, dual-write source + dist)\n// ph connect config --<field> <value> → set mode (flag form)\n// ph connect config --json '{...}' → bulk-set mode (dual-write)\n//\n// Dual-write semantics for set / bulk-set:\n// - Source `powerhouse.config.json` (project root) gets the connect.* patch\n// deep-merged into `connect.*`. `--packages-registry` lands at the\n// top-level `packageRegistryUrl` field (project-wide setting, also read\n// by `ph install` / `ph publish` / Switchboard).\n// - Dist `powerhouse.config.json` (default `.ph/connect-build/dist/`) gets\n// the same connect.* patch deep-merged in, and the same top-level\n// `packageRegistryUrl` if set. The runtime schema mirrors the source\n// schema, so the field lives at the same path in both files.\n//\n// The dist write is skipped silently if the dist file doesn't exist — that's\n// the \"config-only-before-first-build\" workflow, not an error.\n//\n// Field flags + the 4 commonArgs flags (base, log-level, default-drives-url,\n// drive-preserve-strategy) come from the same source as `ph connect build`'s\n// flags, so the two commands share identical CLI surfaces. The 4 commonArgs\n// flags carry cmd-ts defaults; we gate them through `wasFlagExplicitlyPassed`\n// for the same reason `buildCliConnectOverride` does — to avoid leaking\n// default values into a write the user didn't request.\n\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport {\n ConfigLoader,\n DEFAULT_CONNECT_CONFIG,\n JsonConfigAdapter,\n deepMerge,\n} from \"@powerhousedao/shared/connect\";\nimport { existsSync } from \"node:fs\";\nimport { isAbsolute, join, resolve } from \"node:path\";\nimport { stringToPath } from \"remeda\";\nimport type { ConnectConfigArgs } from \"../types.js\";\nimport {\n buildConnectFlagPatch,\n wasFlagExplicitlyPassed,\n type ConnectFlagInput,\n} from \"../utils/cli-connect-override.js\";\nimport {\n normalizeKey,\n parseCliValue,\n validateConnectKeyValue,\n validateConnectPatch,\n} from \"../utils/connect-config-validation.js\";\nimport { getAtPath } from \"../utils/get-at-path.js\";\n\ntype ConnectPartial = Partial<PHConnectRuntimeConfig>;\n\nconst SOURCE_FILE = \"powerhouse.config.json\";\nconst DEFAULT_DIST_SUBPATH = \".ph/connect-build/dist\";\n\nfunction resolveSourcePath(cwd: string): string {\n return join(cwd, SOURCE_FILE);\n}\n\nfunction resolveDistPath(cwd: string, distDirArg: string | undefined): string {\n const fromArg = distDirArg;\n const fromEnv = process.env.PH_CONNECT_OUTDIR;\n const dir = fromArg ?? fromEnv ?? DEFAULT_DIST_SUBPATH;\n const abs = isAbsolute(dir) ? dir : resolve(cwd, dir);\n return join(abs, SOURCE_FILE);\n}\n\n/**\n * Read the source file's raw bytes (no merge with defaults). Returns an empty\n * object stub when the file doesn't exist — the operator can config their way\n * to a complete file before ever running `ph connect build`.\n */\nasync function readSourceRaw(path: string): Promise<Record<string, unknown>> {\n if (!existsSync(path)) return {};\n const adapter = new JsonConfigAdapter({ path });\n const raw = await adapter.read();\n return raw && typeof raw === \"object\" && !Array.isArray(raw)\n ? (raw as Record<string, unknown>)\n : {};\n}\n\nasync function writeSourceRaw(\n path: string,\n next: Record<string, unknown>,\n): Promise<void> {\n const adapter = new JsonConfigAdapter({ path });\n // ConfigShape requires a `connect` key; ensure it's present.\n const shape = {\n ...next,\n connect: (next.connect as PHConnectRuntimeConfig | undefined) ?? {},\n };\n await adapter.write(shape);\n}\n\n/**\n * Build the merged \"effective\" connect block for list/get mode: defaults <\n * source.connect. Doesn't go through env or dist — list mode shows what the\n * source declares + defaults, which is what the next build will produce as a\n * baseline (before env seeds + CLI overrides).\n */\nfunction effectiveConnect(\n source: Record<string, unknown>,\n): PHConnectRuntimeConfig {\n const sourceConnect =\n source.connect &&\n typeof source.connect === \"object\" &&\n !Array.isArray(source.connect)\n ? (source.connect as ConnectPartial)\n : {};\n return deepMerge(DEFAULT_CONNECT_CONFIG, sourceConnect);\n}\n\nfunction printJson(value: unknown): void {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\n/**\n * Translate the parsed `ph connect config` args into the structural\n * `ConnectFlagInput` consumed by `buildConnectFlagPatch`. Common-args flags\n * with cmd-ts defaults are gated through `wasFlagExplicitlyPassed` so the\n * defaults don't leak into a write the user didn't request. `--base` is\n * not translated here — it's rejected up front by `runConnectConfig`.\n */\nfunction argsToFlagInput(args: ConnectConfigArgs): ConnectFlagInput {\n return {\n renownUrl: args.renownUrl,\n renownNetworkId: args.renownNetworkId,\n renownChainId: args.renownChainId,\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 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\n/**\n * Whether any field flag (any of the 19) was passed. Distinguishes the\n * single-field-set mode from list mode when neither `--get` nor `--json` is\n * present.\n */\nfunction hasAnyFieldFlag(input: ConnectFlagInput): boolean {\n // Object.values doesn't include json (which isn't in ConnectFlagInput here).\n // Cast to a generic record so the `!== undefined` predicate is type-aware:\n // ConnectFlagInput's optional properties narrow `v` in a way TS thinks\n // excludes `undefined`, even though at runtime any of them can be unset.\n return Object.values(input as Record<string, unknown>).some(\n (v) => v !== undefined,\n );\n}\n\nexport async function runConnectConfig(args: ConnectConfigArgs): Promise<void> {\n // `--base` is a build-time field (baked into the Vite bundle's asset URLs\n // and the nginx config template), so writing it post-build leaves the\n // layers disagreeing and the SPA's assets 404. The flag stays declared so\n // cmd-ts parses it; we reject explicit use here with an actionable error.\n if (wasFlagExplicitlyPassed(\"base\")) {\n throw new Error(\n \"ph connect config: --base is a build-time field; run `ph connect build --base <value>` and redeploy the container (or restart with PH_CONNECT_BASE_PATH=<value> set in the environment).\",\n );\n }\n\n const cwd = process.cwd();\n const sourcePath = resolveSourcePath(cwd);\n const distPath = resolveDistPath(cwd, args.distDir);\n\n const flagInput = argsToFlagInput(args);\n const hasGet = args.get !== undefined;\n const hasJson = args.json !== undefined;\n const hasFieldFlag = hasAnyFieldFlag(flagInput);\n // `--packages-registry` is a top-level field, not part of the connect-flag\n // patch. Track it separately so the set-mode write puts it in the right\n // place and the mutex counts it as a \"field flag\".\n const explicitRegistry = args.packagesRegistry;\n const hasExplicitRegistry = explicitRegistry !== undefined;\n // Positional pair: 1 positional = get, 2 = set. cmd-ts assigns the first\n // positional to `keyPositional` and the second to `valuePositional`, so a\n // standalone <value> isn't representable here.\n const hasPositionalKey = args.keyPositional !== undefined;\n const hasPositionalValue = args.valuePositional !== undefined;\n const hasPositional = hasPositionalKey;\n\n // Mutex: positional / --get / --json / (any field flag OR\n // --packages-registry) are mutually exclusive. Exactly one mode (or none →\n // list) per call. Counting positional as a single mode regardless of arity:\n // a `<key>` alone is a get, `<key> <value>` is a set, both occupy the same\n // \"positional mode\" slot vs. the other forms.\n const modeCount = [\n hasPositional,\n hasGet,\n hasJson,\n hasFieldFlag || hasExplicitRegistry,\n ].filter(Boolean).length;\n if (modeCount > 1) {\n throw new Error(\n \"ph connect config: positional <key>/<value>, --get, --json, and individual field flags are mutually exclusive. Use one mode per invocation.\",\n );\n }\n\n const source = await readSourceRaw(sourcePath);\n\n // List mode.\n if (modeCount === 0) {\n printJson(effectiveConnect(source));\n return;\n }\n\n // Get mode (either positional `<key>` alone or `--get <key>`).\n if (hasGet || (hasPositional && !hasPositionalValue)) {\n const rawKey = hasGet ? args.get! : args.keyPositional!;\n const sourceLabel = hasGet ? \"--get\" : \"<key>\";\n const normalized = normalizeKey(rawKey);\n if (!normalized) {\n throw new Error(\n `ph connect config ${sourceLabel}: key cannot be empty. Pass a dotted path inside connect.* (e.g. connect.renown.url).`,\n );\n }\n // `packageRegistryUrl` is a top-level field — look it up on the raw\n // source object, not inside `effectiveConnect`.\n if (normalized === \"packageRegistryUrl\") {\n const value = source.packageRegistryUrl;\n if (value === undefined) {\n throw new Error(\n `ph connect config ${sourceLabel}: no value at key \"${normalized}\". Run \\`ph connect config\\` (no args) to see the available paths.`,\n );\n }\n printJson(value);\n return;\n }\n const value = getAtPath(effectiveConnect(source), stringToPath(normalized));\n if (value === undefined) {\n throw new Error(\n `ph connect config ${sourceLabel}: no value at key \"${normalized}\". Run \\`ph connect config\\` (no args) to see the available paths.`,\n );\n }\n printJson(value);\n return;\n }\n\n // Set / bulk-set mode. Build the connect-side patch from positional\n // `<key> <value>` (Ajv-validated against the schema at that path), --json\n // (Ajv-validated as a partial connect.* blob), or individual field flags\n // (shape guaranteed by cmd-ts type coercion). `--packages-registry` is a\n // top-level field; if positional `<key>` is `packageRegistryUrl` or --json\n // carries it, route that to the top-level write.\n let topLevelRegistry: string | undefined = explicitRegistry;\n let patch: ConnectPartial;\n if (hasPositional && hasPositionalValue) {\n const normalized = normalizeKey(args.keyPositional!);\n if (!normalized) {\n throw new Error(\n \"ph connect config <key>: key cannot be empty. Pass a dotted path inside connect.* (e.g. connect.renown.url).\",\n );\n }\n // Top-level: positional `packageRegistryUrl <value>` writes the top-level\n // field instead of a connect.* path.\n if (normalized === \"packageRegistryUrl\") {\n const parsed = parseCliValue(args.valuePositional!);\n if (typeof parsed !== \"string\") {\n throw new Error(\n `ph connect config: packageRegistryUrl must be a string (got ${typeof parsed}).`,\n );\n }\n topLevelRegistry = parsed;\n patch = {};\n } else {\n patch = validateConnectKeyValue(\n normalized,\n args.valuePositional!,\n ) as ConnectPartial;\n }\n } else if (hasJson) {\n const validated = validateConnectPatch(args.json!) as Record<\n string,\n unknown\n >;\n if (typeof validated.packageRegistryUrl === \"string\") {\n topLevelRegistry = topLevelRegistry ?? validated.packageRegistryUrl;\n }\n const connectOnly = { ...validated };\n delete connectOnly.packageRegistryUrl;\n patch = connectOnly as ConnectPartial;\n } else {\n patch = buildConnectFlagPatch(flagInput) as ConnectPartial;\n }\n\n if (Object.keys(patch).length === 0 && topLevelRegistry === undefined) {\n throw new Error(\n \"ph connect config: nothing to set. Pass at least one field flag (e.g. --renown-url <url>) or --json with a non-empty payload.\",\n );\n }\n\n // Build the next source: top-level packageRegistryUrl (if set) +\n // connect.* deep-merge.\n const currentConnect =\n source.connect &&\n typeof source.connect === \"object\" &&\n !Array.isArray(source.connect)\n ? (source.connect as PHConnectRuntimeConfig)\n : ({} as PHConnectRuntimeConfig);\n const nextConnect = deepMerge(\n currentConnect,\n patch as PHConnectRuntimeConfig,\n );\n const nextSource: Record<string, unknown> = {\n ...source,\n connect: nextConnect,\n };\n if (topLevelRegistry !== undefined) {\n nextSource.packageRegistryUrl = topLevelRegistry;\n }\n\n await writeSourceRaw(sourcePath, nextSource);\n\n // Dual-write to dist if it exists. Same shape as source: connect.* block\n // is deep-merged; top-level `packageRegistryUrl` is set in place.\n if (existsSync(distPath)) {\n const distLoader = new ConfigLoader(\n new JsonConfigAdapter({ path: distPath }),\n );\n const distPatch: Record<string, unknown> = { connect: patch };\n if (topLevelRegistry !== undefined) {\n distPatch.packageRegistryUrl = topLevelRegistry;\n }\n await distLoader.write(distPatch);\n }\n\n process.stdout.write(\n `ph connect config: wrote ${sourcePath}${existsSync(distPath) ? ` and ${distPath}` : \"\"}\\n`,\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AASA,SAAgB,UACd,KACA,OACS;CACT,IAAI,MAAe;AACnB,MAAK,MAAM,OAAO,OAAO;AACvB,MAAI,QAAQ,QAAQ,OAAO,QAAQ,SAAU,QAAO,KAAA;AACpD,QAAO,IAAgC,OAAO,IAAI;;AAEpD,QAAO;;;;ACuCT,MAAM,cAAc;AACpB,MAAM,uBAAuB;AAE7B,SAAS,kBAAkB,KAAqB;AAC9C,QAAO,KAAK,KAAK,YAAY;;AAG/B,SAAS,gBAAgB,KAAa,YAAwC;CAC5E,MAAM,UAAU;CAChB,MAAM,UAAU,QAAQ,IAAI;CAC5B,MAAM,MAAM,WAAW,WAAW;AAElC,QAAO,KADK,WAAW,IAAI,GAAG,MAAM,QAAQ,KAAK,IAAI,EACpC,YAAY;;;;;;;AAQ/B,eAAe,cAAc,MAAgD;AAC3E,KAAI,CAAC,WAAW,KAAK,CAAE,QAAO,EAAE;CAEhC,MAAM,MAAM,MADI,IAAI,kBAAkB,EAAE,MAAM,CAAC,CACrB,MAAM;AAChC,QAAO,OAAO,OAAO,QAAQ,YAAY,CAAC,MAAM,QAAQ,IAAI,GACvD,MACD,EAAE;;AAGR,eAAe,eACb,MACA,MACe;CACf,MAAM,UAAU,IAAI,kBAAkB,EAAE,MAAM,CAAC;CAE/C,MAAM,QAAQ;EACZ,GAAG;EACH,SAAU,KAAK,WAAkD,EAAE;EACpE;AACD,OAAM,QAAQ,MAAM,MAAM;;;;;;;;AAS5B,SAAS,iBACP,QACwB;AAOxB,QAAO,UAAU,wBALf,OAAO,WACP,OAAO,OAAO,YAAY,YAC1B,CAAC,M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M;AAIlD,MAAI,OAAO,UAAU,uBAAuB,SAC1C,oBAAmB,oBAAoB,UAAU;EAEnD,MAAM,cAAc,EAAE,GAAG,WAAW;AACpC,SAAO,YAAY;AACnB,UAAQ;OAER,SAAQ,sBAAsB,UAAU;AAG1C,KAAI,OAAO,KAAK,MAAM,CAAC,WAAW,KAAK,qBAAqB,KAAA,EAC1D,OAAM,IAAI,MACR,gIACD;CAWH,MAAM,cAAc,UALlB,OAAO,WACP,OAAO,OAAO,YAAY,YAC1B,CAAC,MAAM,QAAQ,OAAO,QAAQ,GACzB,OAAO,UACP,EAAE,EAGP,MACD;CACD,MAAM,aAAsC;EAC1C,GAAG;EACH,SAAS;EACV;AACD,KAAI,qBAAqB,KAAA,EACvB,YAAW,qBAAqB;AAGlC,OAAM,eAAe,YAAY,WAAW;AAI5C,KAAI,WAAW,SAAS,EAAE;EACxB,MAAM,aAAa,IAAI,aACrB,IAAI,kBAAkB,EAAE,MAAM,UAAU,CAAC,CAC1C;EACD,MAAM,YAAqC,EAAE,SAAS,OAAO;AAC7D,MAAI,qBAAqB,KAAA,EACvB,WAAU,qBAAqB;AAEjC,QAAM,WAAW,MAAM,UAAU;;AAGnC,SAAQ,OAAO,MACb,4BAA4B,aAAa,WAAW,SAAS,GAAG,QAAQ,aAAa,GAAG,IACzF","debug_id":"bdeba91a-33bc-543e-87f8-cc51074d0b17"}
1
+ {"version":3,"file":"connect-config-Bwv3d3uD.mjs","sources":["../src/utils/get-at-path.ts","../src/services/connect-config.ts"],"sourcesContent":["/**\n * Walk a parsed path (e.g. from remeda's `stringToPath`) through a runtime-\n * typed object, returning the value or `undefined` if any segment is\n * missing.\n *\n * Remeda's `prop` is overload-typed for compile-time literal paths and\n * doesn't accept a runtime path array via spread, so we walk inline for\n * the dynamic-path case used by `ph connect config --get`.\n */\nexport function getAtPath(\n obj: unknown,\n parts: ReadonlyArray<string | number>,\n): unknown {\n let cur: unknown = obj;\n for (const key of parts) {\n if (cur === null || typeof cur !== \"object\") return undefined;\n cur = (cur as Record<string, unknown>)[String(key)];\n }\n return cur;\n}\n","// `ph connect config` — read or update Connect's runtime configuration.\n//\n// Mode dispatch (exactly one mode per invocation; mutex enforced below):\n//\n// ph connect config → list mode (print effective merged config)\n// ph connect config <key> → get mode (positional)\n// ph connect config --get <dotted.path> → get mode (flag form, equivalent)\n// ph connect config <key> <value> → set mode (positional, dual-write source + dist)\n// ph connect config --<field> <value> → set mode (flag form)\n// ph connect config --json '{...}' → bulk-set mode (dual-write)\n//\n// Dual-write semantics for set / bulk-set:\n// - Source `powerhouse.config.json` (project root) gets the connect.* patch\n// deep-merged into `connect.*`. `--packages-registry` lands at the\n// top-level `packageRegistryUrl` field (project-wide setting, also read\n// by `ph install` / `ph publish` / Switchboard).\n// - Dist `powerhouse.config.json` (default `.ph/connect-build/dist/`) gets\n// the same connect.* patch deep-merged in, and the same top-level\n// `packageRegistryUrl` if set. The runtime schema mirrors the source\n// schema, so the field lives at the same path in both files.\n//\n// The dist write is skipped silently if the dist file doesn't exist — that's\n// the \"config-only-before-first-build\" workflow, not an error.\n//\n// Field flags + the 4 commonArgs flags (base, log-level, default-drives-url,\n// drive-preserve-strategy) come from the same source as `ph connect build`'s\n// flags, so the two commands share identical CLI surfaces. The 4 commonArgs\n// flags carry cmd-ts defaults; we gate them through `wasFlagExplicitlyPassed`\n// for the same reason `buildCliConnectOverride` does — to avoid leaking\n// default values into a write the user didn't request.\n\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport {\n ConfigLoader,\n DEFAULT_CONNECT_CONFIG,\n JsonConfigAdapter,\n deepMerge,\n} from \"@powerhousedao/shared/connect\";\nimport { existsSync } from \"node:fs\";\nimport { isAbsolute, join, resolve } from \"node:path\";\nimport { stringToPath } from \"remeda\";\nimport type { ConnectConfigArgs } from \"../types.js\";\nimport {\n buildConnectFlagPatch,\n wasFlagExplicitlyPassed,\n type ConnectFlagInput,\n} from \"../utils/cli-connect-override.js\";\nimport {\n normalizeKey,\n parseCliValue,\n validateConnectKeyValue,\n validateConnectPatch,\n} from \"../utils/connect-config-validation.js\";\nimport { getAtPath } from \"../utils/get-at-path.js\";\n\ntype ConnectPartial = Partial<PHConnectRuntimeConfig>;\n\nconst SOURCE_FILE = \"powerhouse.config.json\";\nconst DEFAULT_DIST_SUBPATH = \".ph/connect-build/dist\";\n\nfunction resolveSourcePath(cwd: string): string {\n return join(cwd, SOURCE_FILE);\n}\n\nfunction resolveDistPath(cwd: string, distDirArg: string | undefined): string {\n const fromArg = distDirArg;\n const fromEnv = process.env.PH_CONNECT_OUTDIR;\n const dir = fromArg ?? fromEnv ?? DEFAULT_DIST_SUBPATH;\n const abs = isAbsolute(dir) ? dir : resolve(cwd, dir);\n return join(abs, SOURCE_FILE);\n}\n\n/**\n * Read the source file's raw bytes (no merge with defaults). Returns an empty\n * object stub when the file doesn't exist — the operator can config their way\n * to a complete file before ever running `ph connect build`.\n */\nasync function readSourceRaw(path: string): Promise<Record<string, unknown>> {\n if (!existsSync(path)) return {};\n const adapter = new JsonConfigAdapter({ path });\n const raw = await adapter.read();\n return raw && typeof raw === \"object\" && !Array.isArray(raw)\n ? (raw as Record<string, unknown>)\n : {};\n}\n\nasync function writeSourceRaw(\n path: string,\n next: Record<string, unknown>,\n): Promise<void> {\n const adapter = new JsonConfigAdapter({ path });\n // ConfigShape requires a `connect` key; ensure it's present.\n const shape = {\n ...next,\n connect: (next.connect as PHConnectRuntimeConfig | undefined) ?? {},\n };\n await adapter.write(shape);\n}\n\n/**\n * Build the merged \"effective\" connect block for list/get mode: defaults <\n * source.connect. Doesn't go through env or dist — list mode shows what the\n * source declares + defaults, which is what the next build will produce as a\n * baseline (before env seeds + CLI overrides).\n */\nfunction effectiveConnect(\n source: Record<string, unknown>,\n): PHConnectRuntimeConfig {\n const sourceConnect =\n source.connect &&\n typeof source.connect === \"object\" &&\n !Array.isArray(source.connect)\n ? (source.connect as ConnectPartial)\n : {};\n return deepMerge(DEFAULT_CONNECT_CONFIG, sourceConnect);\n}\n\nfunction printJson(value: unknown): void {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\n/**\n * Translate the parsed `ph connect config` args into the structural\n * `ConnectFlagInput` consumed by `buildConnectFlagPatch`. Common-args flags\n * with cmd-ts defaults are gated through `wasFlagExplicitlyPassed` so the\n * defaults don't leak into a write the user didn't request. `--base` is\n * not translated here — it's rejected up front by `runConnectConfig`.\n */\nfunction argsToFlagInput(args: ConnectConfigArgs): ConnectFlagInput {\n return {\n renownUrl: args.renownUrl,\n renownNetworkId: args.renownNetworkId,\n renownChainId: args.renownChainId,\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 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\n/**\n * Whether any field flag (any of the 19) was passed. Distinguishes the\n * single-field-set mode from list mode when neither `--get` nor `--json` is\n * present.\n */\nfunction hasAnyFieldFlag(input: ConnectFlagInput): boolean {\n // Object.values doesn't include json (which isn't in ConnectFlagInput here).\n // Cast to a generic record so the `!== undefined` predicate is type-aware:\n // ConnectFlagInput's optional properties narrow `v` in a way TS thinks\n // excludes `undefined`, even though at runtime any of them can be unset.\n return Object.values(input as Record<string, unknown>).some(\n (v) => v !== undefined,\n );\n}\n\nexport async function runConnectConfig(args: ConnectConfigArgs): Promise<void> {\n // `--base` is a build-time field (baked into the Vite bundle's asset URLs\n // and the nginx config template), so writing it post-build leaves the\n // layers disagreeing and the SPA's assets 404. The flag stays declared so\n // cmd-ts parses it; we reject explicit use here with an actionable error.\n if (wasFlagExplicitlyPassed(\"base\")) {\n throw new Error(\n \"ph connect config: --base is a build-time field; run `ph connect build --base <value>` and redeploy the container (or restart with PH_CONNECT_BASE_PATH=<value> set in the environment).\",\n );\n }\n\n const cwd = process.cwd();\n const sourcePath = resolveSourcePath(cwd);\n const distPath = resolveDistPath(cwd, args.distDir);\n\n const flagInput = argsToFlagInput(args);\n const hasGet = args.get !== undefined;\n const hasJson = args.json !== undefined;\n const hasFieldFlag = hasAnyFieldFlag(flagInput);\n // `--packages-registry` is a top-level field, not part of the connect-flag\n // patch. Track it separately so the set-mode write puts it in the right\n // place and the mutex counts it as a \"field flag\".\n const explicitRegistry = args.packagesRegistry;\n const hasExplicitRegistry = explicitRegistry !== undefined;\n // Positional pair: 1 positional = get, 2 = set. cmd-ts assigns the first\n // positional to `keyPositional` and the second to `valuePositional`, so a\n // standalone <value> isn't representable here.\n const hasPositionalKey = args.keyPositional !== undefined;\n const hasPositionalValue = args.valuePositional !== undefined;\n const hasPositional = hasPositionalKey;\n\n // Mutex: positional / --get / --json / (any field flag OR\n // --packages-registry) are mutually exclusive. Exactly one mode (or none →\n // list) per call. Counting positional as a single mode regardless of arity:\n // a `<key>` alone is a get, `<key> <value>` is a set, both occupy the same\n // \"positional mode\" slot vs. the other forms.\n const modeCount = [\n hasPositional,\n hasGet,\n hasJson,\n hasFieldFlag || hasExplicitRegistry,\n ].filter(Boolean).length;\n if (modeCount > 1) {\n throw new Error(\n \"ph connect config: positional <key>/<value>, --get, --json, and individual field flags are mutually exclusive. Use one mode per invocation.\",\n );\n }\n\n const source = await readSourceRaw(sourcePath);\n\n // List mode.\n if (modeCount === 0) {\n printJson(effectiveConnect(source));\n return;\n }\n\n // Get mode (either positional `<key>` alone or `--get <key>`).\n if (hasGet || (hasPositional && !hasPositionalValue)) {\n const rawKey = hasGet ? args.get! : args.keyPositional!;\n const sourceLabel = hasGet ? \"--get\" : \"<key>\";\n const normalized = normalizeKey(rawKey);\n if (!normalized) {\n throw new Error(\n `ph connect config ${sourceLabel}: key cannot be empty. Pass a dotted path inside connect.* (e.g. connect.renown.url).`,\n );\n }\n // `packageRegistryUrl` is a top-level field — look it up on the raw\n // source object, not inside `effectiveConnect`.\n if (normalized === \"packageRegistryUrl\") {\n const value = source.packageRegistryUrl;\n if (value === undefined) {\n throw new Error(\n `ph connect config ${sourceLabel}: no value at key \"${normalized}\". Run \\`ph connect config\\` (no args) to see the available paths.`,\n );\n }\n printJson(value);\n return;\n }\n const value = getAtPath(effectiveConnect(source), stringToPath(normalized));\n if (value === undefined) {\n throw new Error(\n `ph connect config ${sourceLabel}: no value at key \"${normalized}\". Run \\`ph connect config\\` (no args) to see the available paths.`,\n );\n }\n printJson(value);\n return;\n }\n\n // Set / bulk-set mode. Build the connect-side patch from positional\n // `<key> <value>` (Ajv-validated against the schema at that path), --json\n // (Ajv-validated as a partial connect.* blob), or individual field flags\n // (shape guaranteed by cmd-ts type coercion). `--packages-registry` is a\n // top-level field; if positional `<key>` is `packageRegistryUrl` or --json\n // carries it, route that to the top-level write.\n let topLevelRegistry: string | undefined = explicitRegistry;\n let patch: ConnectPartial;\n if (hasPositional && hasPositionalValue) {\n const normalized = normalizeKey(args.keyPositional!);\n if (!normalized) {\n throw new Error(\n \"ph connect config <key>: key cannot be empty. Pass a dotted path inside connect.* (e.g. connect.renown.url).\",\n );\n }\n // Top-level: positional `packageRegistryUrl <value>` writes the top-level\n // field instead of a connect.* path.\n if (normalized === \"packageRegistryUrl\") {\n const parsed = parseCliValue(args.valuePositional!);\n if (typeof parsed !== \"string\") {\n throw new Error(\n `ph connect config: packageRegistryUrl must be a string (got ${typeof parsed}).`,\n );\n }\n topLevelRegistry = parsed;\n patch = {};\n } else {\n patch = validateConnectKeyValue(\n normalized,\n args.valuePositional!,\n ) as ConnectPartial;\n }\n } else if (hasJson) {\n const validated = validateConnectPatch(args.json!) as Record<\n string,\n unknown\n >;\n if (typeof validated.packageRegistryUrl === \"string\") {\n topLevelRegistry = topLevelRegistry ?? validated.packageRegistryUrl;\n }\n const connectOnly = { ...validated };\n delete connectOnly.packageRegistryUrl;\n patch = connectOnly as ConnectPartial;\n } else {\n patch = buildConnectFlagPatch(flagInput) as ConnectPartial;\n }\n\n if (Object.keys(patch).length === 0 && topLevelRegistry === undefined) {\n throw new Error(\n \"ph connect config: nothing to set. Pass at least one field flag (e.g. --renown-url <url>) or --json with a non-empty payload.\",\n );\n }\n\n // Build the next source: top-level packageRegistryUrl (if set) +\n // connect.* deep-merge.\n const currentConnect =\n source.connect &&\n typeof source.connect === \"object\" &&\n !Array.isArray(source.connect)\n ? (source.connect as PHConnectRuntimeConfig)\n : ({} as PHConnectRuntimeConfig);\n const nextConnect = deepMerge(\n currentConnect,\n patch as PHConnectRuntimeConfig,\n );\n const nextSource: Record<string, unknown> = {\n ...source,\n connect: nextConnect,\n };\n if (topLevelRegistry !== undefined) {\n nextSource.packageRegistryUrl = topLevelRegistry;\n }\n\n await writeSourceRaw(sourcePath, nextSource);\n\n // Dual-write to dist if it exists. Same shape as source: connect.* block\n // is deep-merged; top-level `packageRegistryUrl` is set in place.\n if (existsSync(distPath)) {\n const distLoader = new ConfigLoader(\n new JsonConfigAdapter({ path: distPath }),\n );\n const distPatch: Record<string, unknown> = { connect: patch };\n if (topLevelRegistry !== undefined) {\n distPatch.packageRegistryUrl = topLevelRegistry;\n }\n await distLoader.write(distPatch);\n }\n\n process.stdout.write(\n `ph connect config: wrote ${sourcePath}${existsSync(distPath) ? ` and ${distPath}` : \"\"}\\n`,\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AASA,SAAgB,UACd,KACA,OACS;CACT,IAAI,MAAe;AACnB,MAAK,M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YAC1B,CAAC,MAAM,QAAQ,OAAO,QAAQ,GACzB,OAAO,UACP,EAAE,EAGP,MACD;CACD,MAAM,aAAsC;EAC1C,GAAG;EACH,SAAS;EACV;AACD,KAAI,qBAAqB,KAAA,EACvB,YAAW,qBAAqB;AAGlC,OAAM,eAAe,YAAY,WAAW;AAI5C,KAAI,WAAW,SAAS,EAAE;EACxB,MAAM,aAAa,IAAI,aACrB,IAAI,kBAAkB,EAAE,MAAM,UAAU,CAAC,CAC1C;EACD,MAAM,YAAqC,EAAE,SAAS,OAAO;AAC7D,MAAI,qBAAqB,KAAA,EACvB,WAAU,qBAAqB;AAEjC,QAAM,WAAW,MAAM,UAAU;;AAGnC,SAAQ,OAAO,MACb,4BAA4B,aAAa,WAAW,SAAS,GAAG,QAAQ,aAAa,GAAG,IACzF","debug_id":"a1f9834f-cd0a-506d-9d79-62579f3ee62e"}
@@ -1,6 +1,6 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b2a9ca8c-b055-504d-90d5-d0bbacda0201")}catch(e){}}();
3
- import { s as getProjectInfo } from "./utils-BaTZlyL3.mjs";
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]="e71cc752-7835-5af2-bae0-1a7629056456")}catch(e){}}();
3
+ import { s as getProjectInfo } from "./utils-C4isxXSO.mjs";
4
4
  import fs from "node:fs";
5
5
  //#region src/services/inspect.ts
6
6
  function startInspect(args) {
@@ -44,5 +44,5 @@ function startInspect(args) {
44
44
  //#endregion
45
45
  export { startInspect };
46
46
 
47
- //# sourceMappingURL=inspect-CKdafPbC.mjs.map
48
- //# debugId=b2a9ca8c-b055-504d-90d5-d0bbacda0201
47
+ //# sourceMappingURL=inspect-DXjbQEV_.mjs.map
48
+ //# debugId=e71cc752-7835-5af2-bae0-1a7629056456
@@ -1 +1 @@
1
- {"version":3,"file":"inspect-CKdafPbC.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(\"No manifest found in the package\");\n }\n }\n}\n"],"names":[],"mappings":";;;;;AAIA,SAAgB,aAAa,MAAmB;AAC9C,KAAI,KAAK,MACP,SAAQ,IAAI,yBAAyB,KAAK;CAG5C,MAAM,cAAc,eAAe,KAAK,MAAM;CAC9C,MAAM,EAAE,gBAAgB;AAExB,KAAI,KAAK,MACP,SAAQ,IAAI,qBAAqB,YAAY;AAG/C,KAAI;EACF,MAAM,gBAAgB,SACpB,KAAK,MAAM,GAAG,aAAa,MAAM,QAAQ,CAAC;EAC5C,MAAM,WAAW,aACf,GAAG,QAAQ,KAAK,CAAC,gBAAgB,YAAY,gCAC9C;AAED,UAAQ,IAAI,SAAS,KAAK;AAC1B,MAAI,SAAS,gBAAgB;AAC3B,WAAQ,IAAI,qBAAqB;AACjC,YAAS,eAAe,SAAS,UAAU;AACzC,YAAQ,IAAI,KAAK,MAAM,KAAK,IAAI,MAAM,GAAG,GAAG;KAC5C;;AAGJ,MAAI,SAAS,SAAS;AACpB,WAAQ,IAAI,aAAa;AACzB,YAAS,QAAQ,SAAS,WAAW;AACnC,YAAQ,IAAI,KAAK,OAAO,KAAK,IAAI,OAAO,GAAG,GAAG;KAC9C;;AAGJ,MAAI,SAAS,YAAY;AACvB,WAAQ,IAAI,gBAAgB;AAC5B,YAAS,WAAW,SAAS,cAAc;AACzC,YAAQ,IAAI,KAAK,UAAU,KAAK,IAAI,UAAU,GAAG,GAAG;KACpD;;AAGJ,MAAI,SAAS,WAAW;AACtB,WAAQ,IAAI,eAAe;AAC3B,YAAS,UAAU,SAAS,aAAa;AACvC,YAAQ,IAAI,KAAK,SAAS,KAAK,IAAI,SAAS,GAAG,GAAG;KAClD;;UAEG,GAAG;AACV,MAAI,KAAK,MACP,SAAQ,MAAM,EAAE;MAEhB,SAAQ,IAAI,mCAAmC","debug_id":"b2a9ca8c-b055-504d-90d5-d0bbacda0201"}
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(\"No manifest found in the package\");\n }\n }\n}\n"],"names":[],"mappings":";;;;;AAIA,SAAgB,aAAa,MAAmB;AAC9C,KAAI,KAAK,MACP,SAAQ,IAAI,yBAAyB,KAAK;CAG5C,MAAM,cAAc,eAAe,KAAK,MAAM;CAC9C,MAAM,EAAE,gBAAgB;AAExB,KAAI,KAAK,MACP,SAAQ,IAAI,qBAAqB,YAAY;AAG/C,KAAI;EACF,MAAM,gBAAgB,SACpB,KAAK,MAAM,GAAG,aAAa,MAAM,QAAQ,CAAC;EAC5C,MAAM,WAAW,aACf,GAAG,QAAQ,KAAK,CAAC,gBAAgB,YAAY,gCAC9C;AAED,UAAQ,IAAI,SAAS,KAAK;AAC1B,MAAI,SAAS,gBAAgB;AAC3B,WAAQ,IAAI,qBAAqB;AACjC,YAAS,eAAe,SAAS,UAAU;AACzC,YAAQ,IAAI,KAAK,MAAM,KAAK,IAAI,MAAM,GAAG,GAAG;KAC5C;;AAGJ,MAAI,SAAS,SAAS;AACpB,WAAQ,IAAI,aAAa;AACzB,YAAS,QAAQ,SAAS,WAAW;AACnC,YAAQ,IAAI,KAAK,OAAO,KAAK,IAAI,OAAO,GAAG,GAAG;KAC9C;;AAGJ,MAAI,SAAS,YAAY;AACvB,WAAQ,IAAI,gBAAgB;AAC5B,YAAS,WAAW,SAAS,cAAc;AACzC,YAAQ,IAAI,KAAK,UAAU,KAAK,IAAI,UAAU,GAAG,GAAG;KACpD;;AAGJ,MAAI,SAAS,WAAW;AACtB,WAAQ,IAAI,eAAe;AAC3B,YAAS,UAAU,SAAS,aAAa;AACvC,YAAQ,IAAI,KAAK,SAAS,KAAK,IAAI,SAAS,GAAG,GAAG;KAClD;;UAEG,GAAG;AACV,MAAI,KAAK,MACP,SAAQ,MAAM,EAAE;MAEhB,SAAQ,IAAI,mCAAmC","debug_id":"e71cc752-7835-5af2-bae0-1a7629056456"}
@@ -1,10 +1,10 @@
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]="5cc924ff-7015-5b6b-ac8d-a2c87fcac122")}catch(e){}}();
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-BJQvY88v.mjs.map
83
- //# debugId=5cc924ff-7015-5b6b-ac8d-a2c87fcac122
82
+ //# sourceMappingURL=migrate-jGKfE02L.mjs.map
83
+ //# debugId=5917a8da-bcbd-52a8-af0d-9c6d60ae5475
@@ -1 +1 @@
1
- {"version":3,"file":"migrate-BJQvY88v.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,YAAY;EAChC,MAAM,IAAK,QAA0B;AACrC,MAAI,OAAO,MAAM,SAAU,QAAO;;;AAKtC,SAAgB,4BAA4B,MAInC;CACP,MAAM,EAAE,gBAAgB,gBAAgB,UAAU;AAClD,KAAI,MAAO;AACX,KAAI,CAAC,eACH,OAAM,IAAI,MACR,sJAED;AAEH,KAAI,kBAAkB,mBAAmB,eACvC,OAAM,IAAI,MACR,0BAA0B,eAAe,yBAAyB,eAAe,wDAElF;;AAIL,eAAsB,aAAa,EACjC,mBACA,SACA,OACA,SACc;CACd,MAAM,YAAY,qBAAqB;AACvC,KAAI,MAAO,SAAQ,IAAI,gCAAgC,YAAY;CAEnE,IAAI;AACJ,KAAI;AACF,kBAAgB,MAAM,mCACpB,yBAAyB,YAC1B;UACM,OAAO;EACd,MAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AACrE,MAAI,CAAC,MACH,OAAM,IAAI,MACR,sBAAsB,UAAU,2BAA2B,OAAO,gEAClE,EAAE,OAAO,OAAO,CACjB;AAEH,MAAI,MACF,SAAQ,IACN,gGAAgG,SACjG;;CAIL,MAAM,iBAAiB,wBAAwB;AAC/C,KAAI,OAAO;AACT,UAAQ,IACN,sCAAsC,iBAAiB,cACxD;AACD,UAAQ,IACN,qCAAqC,kBAAkB,cACxD;;AAGH,KAAI,CAAC,iBAAiB,SAAS,kBAAkB,gBAAgB;AAC/D,MAAI,MAAO,SAAQ,IAAI,iDAAiD;EACxE,MAAM,aAAa,MAAM,OAAO;EAChC,MAAM,iBAAiB,sBACrB,WACD;AACD,8BAA4B;GAC1B;GACA;GACA,OAAO,QAAQ,MAAM;GACtB,CAAC;AACF,UAAQ,IACN,+CAA+C,kBAAkB,YAClE;AACD,QAAM,WAAW,QAAQ,iBAAiB,UAAU;AACpD;;CAGF,MAAM,SAAS,MAAM,QAAQ,GAAG,SAAS;CACzC,MAAM,WAAW,eAAe,OAAO,WAAW;EAChD,yBAAyB;EACzB;EACA;EACA;EACA,GAAI,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":"5cc924ff-7015-5b6b-ac8d-a2c87fcac122"}
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,YAAY;EAChC,MAAM,IAAK,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AG,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-BaTZlyL3.mjs";
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]="08292df2-191b-515a-94a1-4ba124a2296c")}catch(e){}}();
4
- //# debugId=08292df2-191b-515a-94a1-4ba124a2296c
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]="78c06d69-a52c-5bea-96c7-df0b42c3115e")}catch(e){}}();
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-BaTZlyL3.mjs.map
165
- //# debugId=78c06d69-a52c-5bea-96c7-df0b42c3115e
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,KAAK;AAEjC,KAAI,MACF,SAAQ,IAAI,mBAAmB,YAAY;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,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;AAGhE,MAAa,kBAAkB;CAC7B,KAAK;EACH,kBAAkB;EAClB,gBAA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c,KAAK,KAAK;;AAK5C,KAAI,kBAAkB,cACpB,IAAG,cAAc,YAAY,cAAc","debug_id":"73159d3c-22a7-5dc6-8bd4-7b15f3b94c79"}
@@ -1,8 +1,8 @@
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]="9bbf7fa0-0432-5c47-b876-f2b249aa5528")}catch(e){}}();
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]="c64a42be-598a-5c20-9536-7fac4a326cd8")}catch(e){}}();
3
3
  import { a as parseDefaultDrivesUrl } from "./cli-connect-override-CFsTgKB6.mjs";
4
4
  import { t as runConnectStudio } from "./connect-studio-sRLuTabi.mjs";
5
- import { a as generateProjectDriveId } from "./utils-BaTZlyL3.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";
@@ -440,5 +440,5 @@ async function startVetra(args) {
440
440
  //#endregion
441
441
  export { startVetra };
442
442
 
443
- //# sourceMappingURL=vetra-D9MTB556.mjs.map
444
- //# debugId=9bbf7fa0-0432-5c47-b876-f2b249aa5528
443
+ //# sourceMappingURL=vetra-Chnn6I6A.mjs.map
444
+ //# debugId=c64a42be-598a-5c20-9536-7fac4a326cd8
@@ -1 +1 @@
1
- {"version":3,"file":"vetra-D9MTB556.mjs","sources":["../src/utils/configure-vetra-github-url.ts","../src/utils/resolve-switchboard-port.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 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 { 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 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 // 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":";;;;;;;;;;;;;;;;;;;;AAaA,SAAS,kBAAiC;AACxC,KAAI;AAKF,SAJY,SAAS,6BAA6B;GAChD,UAAU;GACV,OAAO;IAAC;IAAQ;IAAQ;IAAO;GAChC,CAAC,CAAC,MAAM,IACK;SACR;AACN,SAAO;;;;;;AAOX,eAAe,qBAA6C;AAC1D,QAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,KAAK,gB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utils/configure-vetra-github-url.ts","../src/utils/resolve-switchboard-port.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 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 { 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 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 // 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":";;;;;;;;;;;;;;;;;;;;AAaA,SAAS,kBAAiC;AACxC,KAAI;AAKF,SAJY,SAAS,6BAA6B;GAChD,UAAU;GACV,OAAO;IAAC;IAAQ;IAAQ;IAAO;GAChC,CAAC,CAAC,MAA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,MAAM,MAAM","debug_id":"c64a42be-598a-5c20-9536-7fac4a326cd8"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerhousedao/ph-cli",
3
- "version": "6.2.2-dev.10",
3
+ "version": "6.2.2-dev.11",
4
4
  "description": "",
5
5
  "license": "AGPL-3.0-only",
6
6
  "type": "module",
@@ -40,16 +40,16 @@
40
40
  "semver": "7.7.4",
41
41
  "tsdown": "0.21.1",
42
42
  "vite": "8.0.10",
43
- "@powerhousedao/builder-tools": "6.2.2-dev.10",
44
- "@powerhousedao/codegen": "6.2.2-dev.10",
45
- "@powerhousedao/common": "6.2.2-dev.10",
46
- "@powerhousedao/config": "6.2.2-dev.10",
47
- "@powerhousedao/reactor": "6.2.2-dev.10",
48
- "@powerhousedao/shared": "6.2.2-dev.10",
49
- "@powerhousedao/switchboard": "6.2.2-dev.10",
50
- "@powerhousedao/vetra": "6.2.2-dev.10",
51
- "@renown/sdk": "6.2.2-dev.10",
52
- "document-model": "6.2.2-dev.10"
43
+ "@powerhousedao/builder-tools": "6.2.2-dev.11",
44
+ "@powerhousedao/codegen": "6.2.2-dev.11",
45
+ "@powerhousedao/common": "6.2.2-dev.11",
46
+ "@powerhousedao/config": "6.2.2-dev.11",
47
+ "@powerhousedao/reactor": "6.2.2-dev.11",
48
+ "@powerhousedao/shared": "6.2.2-dev.11",
49
+ "@powerhousedao/vetra": "6.2.2-dev.11",
50
+ "@powerhousedao/switchboard": "6.2.2-dev.11",
51
+ "@renown/sdk": "6.2.2-dev.11",
52
+ "document-model": "6.2.2-dev.11"
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"}
@@ -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