@powerhousedao/ph-cli 6.3.0-dev.5 → 6.3.0-dev.7

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.
Files changed (32) hide show
  1. package/dist/build-DFEAUrqt.mjs +4 -0
  2. package/dist/{build-Cs3xAL0T.mjs → build-pt5j4Jkr.mjs} +4 -4
  3. package/dist/{build-Cs3xAL0T.mjs.map → build-pt5j4Jkr.mjs.map} +1 -1
  4. package/dist/{check-3glk3pLB.mjs → check-BP1eEHG4.mjs} +3 -3
  5. package/dist/{check-Bg06Tzgm.mjs → check-BhYboAXc.mjs} +4 -4
  6. package/dist/{check-Bg06Tzgm.mjs.map → check-BhYboAXc.mjs.map} +1 -1
  7. package/dist/cli.mjs +3 -3
  8. package/dist/{connect-build-DXpZXOJw.mjs → connect-build-DWMIQHA3.mjs} +4 -4
  9. package/dist/{connect-build-DXpZXOJw.mjs.map → connect-build-DWMIQHA3.mjs.map} +1 -1
  10. package/dist/definitions-worker.mjs +1 -1
  11. package/dist/{get-version-C3ozwlOI.mjs → get-version-COv7hnzB.mjs} +4 -4
  12. package/dist/{get-version-C3ozwlOI.mjs.map → get-version-COv7hnzB.mjs.map} +1 -1
  13. package/dist/{mcp-4VkYD_JF.mjs → mcp-CLxrbUT1.mjs} +4 -4
  14. package/dist/{mcp-4VkYD_JF.mjs.map → mcp-CLxrbUT1.mjs.map} +1 -1
  15. package/dist/{migrate-HIHQdxMV.mjs → migrate-DufFMK7_.mjs} +4 -4
  16. package/dist/{migrate-HIHQdxMV.mjs.map → migrate-DufFMK7_.mjs.map} +1 -1
  17. package/dist/{migrate-document-models-3ioRcLNQ.mjs → migrate-document-models-09A1X_-c.mjs} +4 -4
  18. package/dist/{migrate-document-models-3ioRcLNQ.mjs.map → migrate-document-models-09A1X_-c.mjs.map} +1 -1
  19. package/dist/{migrate-subgraphs-DWnMMl4X.mjs → migrate-subgraphs-B38Bh800.mjs} +5 -5
  20. package/dist/{migrate-subgraphs-DWnMMl4X.mjs.map → migrate-subgraphs-B38Bh800.mjs.map} +1 -1
  21. package/dist/migrate-subgraphs-B5A-eQZP.mjs +4 -0
  22. package/dist/{ph-cli-commands-B39ZOxXF.mjs → ph-cli-commands-CM9JBqeZ.mjs} +11 -11
  23. package/dist/{ph-cli-commands-B39ZOxXF.mjs.map → ph-cli-commands-CM9JBqeZ.mjs.map} +1 -1
  24. package/dist/ph-cli-commands-CpbYNixr.mjs +4 -0
  25. package/dist/runners/connect.mjs +1 -1
  26. package/dist/runners/switchboard.mjs +1 -1
  27. package/dist/{verify-CanemraA.mjs → verify-Dv9s1Ikh.mjs} +4 -4
  28. package/dist/{verify-CanemraA.mjs.map → verify-Dv9s1Ikh.mjs.map} +1 -1
  29. package/package.json +16 -16
  30. package/dist/build-DJgPFSFp.mjs +0 -4
  31. package/dist/migrate-subgraphs-DPUi-4RF.mjs +0 -4
  32. package/dist/ph-cli-commands-DppvECPl.mjs +0 -4
@@ -1,4 +1,4 @@
1
- import { n as runModelCheck, t as definitionChecks } from "./check-Bg06Tzgm.mjs";
1
+ import { n as runModelCheck, t as definitionChecks } from "./check-BhYboAXc.mjs";
2
2
  export { definitionChecks, runModelCheck };
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]="f80806f2-1cc8-520f-80fc-5343ab3c724d")}catch(e){}}();
4
- //# debugId=f80806f2-1cc8-520f-80fc-5343ab3c724d
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]="a89f1579-f517-5d01-be70-25472d9e007c")}catch(e){}}();
4
+ //# debugId=a89f1579-f517-5d01-be70-25472d9e007c
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="533a33cf-0f5f-569f-b825-56382274a91e")}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]="6c9ac309-c6d6-59a0-a411-0e6ee0e4cebb")}catch(e){}}();
3
3
  import { t as readProjectSubgraphs } from "./subgraphs-7OYWwP-C.mjs";
4
4
  import { n as processStreams, r as runModelCommand } from "./run--de_-WAz.mjs";
5
5
  import { t as renderCheckReport } from "./render-SVfj3m8A.mjs";
@@ -59,7 +59,7 @@ async function runModelCheck(args, options = {}) {
59
59
  */
60
60
  async function runPrepackCheck(json, options) {
61
61
  const streams = options.streams ?? processStreams;
62
- const { renderReleaseDecision, verifyRelease } = await import("./verify-CanemraA.mjs");
62
+ const { renderReleaseDecision, verifyRelease } = await import("./verify-Dv9s1Ikh.mjs");
63
63
  let decision;
64
64
  try {
65
65
  decision = verifyRelease(options.projectRoot ?? process.cwd());
@@ -77,5 +77,5 @@ async function runPrepackCheck(json, options) {
77
77
  //#endregion
78
78
  export { runModelCheck as n, definitionChecks as t };
79
79
 
80
- //# sourceMappingURL=check-Bg06Tzgm.mjs.map
81
- //# debugId=533a33cf-0f5f-569f-b825-56382274a91e
80
+ //# sourceMappingURL=check-BhYboAXc.mjs.map
81
+ //# debugId=6c9ac309-c6d6-59a0-a411-0e6ee0e4cebb
@@ -1 +1 @@
1
- {"version":3,"file":"check-Bg06Tzgm.mjs","sources":["../src/services/model/check.ts"],"sourcesContent":["import type { DefinitionCheckReport } from \"@powerhousedao/shared/document-model\";\nimport {\n checkProjectDefinitions,\n documentModelChecks,\n type ProjectDefinitions,\n subgraphChecks,\n} from \"document-model/tooling\";\nimport type { ReleaseDecision } from \"../release/approval.js\";\nimport type { ReleaseCheck } from \"../release/evidence.js\";\nimport type { ProjectModules } from \"./project.js\";\nimport { readProjectSubgraphs } from \"./subgraphs.js\";\nimport {\n type ModelRunOptions,\n processStreams,\n runModelCommand,\n} from \"./run.js\";\nimport { renderCheckReport } from \"./render.js\";\n\nasync function subgraphContributions(\n project: ProjectDefinitions,\n modules: ProjectModules,\n) {\n const subgraphs = await readProjectSubgraphs(project, modules);\n if (subgraphs === undefined) return undefined;\n return {\n checks: subgraphChecks,\n input: { subgraphs: subgraphs.input },\n inventory: subgraphs.inventory,\n };\n}\n\n/**\n * The edit and the release profile of the definition check, as `ph model\n * check` runs them and the definitions worker runs them for `ph build`.\n */\nexport const definitionChecks = {\n edit: async (\n project: ProjectDefinitions,\n modules: ProjectModules,\n ): Promise<DefinitionCheckReport> => {\n const contributions = await subgraphContributions(project, modules);\n if (contributions === undefined) return checkProjectDefinitions(project);\n return checkProjectDefinitions(\n { ...project, ...contributions.input },\n {\n checks: [...documentModelChecks, ...contributions.checks],\n definitions: contributions.inventory,\n },\n );\n },\n release: async (\n project: ProjectDefinitions,\n modules: ProjectModules,\n ): Promise<ReleaseCheck> => {\n const contributions = await subgraphContributions(project, modules);\n const { checkForRelease } = await import(\"../release/evidence.js\");\n return await checkForRelease(\n project,\n modules,\n contributions === undefined ? {} : { contributions },\n );\n },\n};\n\n/** `ph model check`. Returns the exit code. */\nexport async function runModelCheck(\n args: {\n readonly json: boolean;\n readonly release?: boolean;\n readonly prepack?: boolean;\n },\n options: ModelRunOptions = {},\n): Promise<number> {\n if (args.prepack) {\n if (args.release) {\n (options.streams ?? processStreams).err(\n \"ph model check could not run: --prepack and --release cannot be combined.\\n\",\n );\n return 2;\n }\n return await runPrepackCheck(args.json, options);\n }\n return await runModelCommand(\n {\n name: \"ph model check\",\n json: args.json,\n read: async (project, modules) =>\n args.release\n ? (await definitionChecks.release(project, modules)).report\n : await definitionChecks.edit(project, modules),\n render: renderCheckReport,\n },\n options,\n );\n}\n\n/**\n * `ph model check --prepack`: 0 when the release approval matches the\n * package, 1 when it does not, 2 when it cannot be checked. Loads none of\n * the package's modules.\n */\nasync function runPrepackCheck(\n json: boolean,\n options: ModelRunOptions,\n): Promise<number> {\n const streams = options.streams ?? processStreams;\n const { renderReleaseDecision, verifyRelease } =\n await import(\"../release/verify.js\");\n let decision: ReleaseDecision;\n try {\n decision = verifyRelease(options.projectRoot ?? process.cwd());\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n streams.err(`ph model check --prepack could not run: ${message}\\n`);\n return 2;\n }\n streams.out(\n `${json ? JSON.stringify({ decision: decision.decision, reasons: decision.reasons }) : renderReleaseDecision(decision)}\\n`,\n );\n return decision.decision === \"approved\" ? 0 : 1;\n}\n"],"names":[],"mappings":";;;;;;;AAkBA,eAAe,sBACb,SACA,SACA;CACA,MAAM,YAAY,MAAM,qBAAqB,SAAS,OAAO;CAC7D,IAAI,cAAc,KAAA,GAAW,OAAO,KAAA;CACpC,OAAO;EACL,QAAQ;EACR,OAAO,EAAE,WAAW,UAAU,MAAM;EACpC,WAAW,UAAU;CACvB;AACF;;;;;AAMA,MAAa,mBAAmB;CAC9B,MAAM,OACJ,SACA,YACmC;EACnC,MAAM,gBAAgB,MAAM,sBAAsB,SAAS,OAAO;EAClE,IAAI,kBAAkB,KAAA,GAAW,OAAO,wBAAwB,OAAO;EACvE,OAAO,wBACL;GAAE,GAAG;GAAS,GAAG,cAAc;EAAM,GACrC;GACE,QAAQ,CAAC,GAAG,qBAAqB,GAAG,cAAc,MAAM;GACxD,aAAa,cAAc;EAC7B,CACF;CACF;CACA,SAAS,OACP,SACA,YAC0B;EAC1B,MAAM,gBAAgB,MAAM,sBAAsB,SAAS,OAAO;EAClE,MAAM,EAAE,oBAAoB,MAAM,OAAO;EACzC,OAAO,MAAM,gBACX,SACA,SACA,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc,CACrD;CACF;AACF;;AAGA,eAAsB,cACpB,MAKA,UAA2B,CAAC,GACX;CACjB,IAAI,KAAK,SAAS;EAChB,IAAI,KAAK,SAAS;GAChB,CAAC,QAAQ,WAAW,eAAA,CAAgB,IAClC,6EACF;GACA,OAAO;EACT;EACA,OAAO,MAAM,gBAAgB,KAAK,MAAM,OAAO;CACjD;CACA,OAAO,MAAM,gBACX;EACE,MAAM;EACN,MAAM,KAAK;EACX,MAAM,OAAO,SAAS,YACpB,KAAK,WACA,MAAM,iBAAiB,QAAQ,SAAS,OAAO,EAAA,CAAG,SACnD,MAAM,iBAAiB,KAAK,SAAS,OAAO;EAClD,QAAQ;CACV,GACA,OACF;AACF;;;;;;AAOA,eAAe,gBACb,MACA,SACiB;CACjB,MAAM,UAAU,QAAQ,WAAW;CACnC,MAAM,EAAE,uBAAuB,kBAC7B,MAAM,OAAO;CACf,IAAI;CACJ,IAAI;EACF,WAAW,cAAc,QAAQ,eAAe,QAAQ,IAAI,CAAC;CAC/D,SAAS,OAAO;EACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EACrE,QAAQ,IAAI,2CAA2C,QAAQ,GAAG;EAClE,OAAO;CACT;CACA,QAAQ,IACN,GAAG,OAAO,KAAK,UAAU;EAAE,UAAU,SAAS;EAAU,SAAS,SAAS;CAAQ,CAAC,IAAI,sBAAsB,QAAQ,EAAE,GACzH;CACA,OAAO,SAAS,aAAa,aAAa,IAAI;AAChD","debug_id":"533a33cf-0f5f-569f-b825-56382274a91e"}
1
+ {"version":3,"file":"check-BhYboAXc.mjs","sources":["../src/services/model/check.ts"],"sourcesContent":["import type { DefinitionCheckReport } from \"@powerhousedao/shared/document-model\";\nimport {\n checkProjectDefinitions,\n documentModelChecks,\n type ProjectDefinitions,\n subgraphChecks,\n} from \"document-model/tooling\";\nimport type { ReleaseDecision } from \"../release/approval.js\";\nimport type { ReleaseCheck } from \"../release/evidence.js\";\nimport type { ProjectModules } from \"./project.js\";\nimport { readProjectSubgraphs } from \"./subgraphs.js\";\nimport {\n type ModelRunOptions,\n processStreams,\n runModelCommand,\n} from \"./run.js\";\nimport { renderCheckReport } from \"./render.js\";\n\nasync function subgraphContributions(\n project: ProjectDefinitions,\n modules: ProjectModules,\n) {\n const subgraphs = await readProjectSubgraphs(project, modules);\n if (subgraphs === undefined) return undefined;\n return {\n checks: subgraphChecks,\n input: { subgraphs: subgraphs.input },\n inventory: subgraphs.inventory,\n };\n}\n\n/**\n * The edit and the release profile of the definition check, as `ph model\n * check` runs them and the definitions worker runs them for `ph build`.\n */\nexport const definitionChecks = {\n edit: async (\n project: ProjectDefinitions,\n modules: ProjectModules,\n ): Promise<DefinitionCheckReport> => {\n const contributions = await subgraphContributions(project, modules);\n if (contributions === undefined) return checkProjectDefinitions(project);\n return checkProjectDefinitions(\n { ...project, ...contributions.input },\n {\n checks: [...documentModelChecks, ...contributions.checks],\n definitions: contributions.inventory,\n },\n );\n },\n release: async (\n project: ProjectDefinitions,\n modules: ProjectModules,\n ): Promise<ReleaseCheck> => {\n const contributions = await subgraphContributions(project, modules);\n const { checkForRelease } = await import(\"../release/evidence.js\");\n return await checkForRelease(\n project,\n modules,\n contributions === undefined ? {} : { contributions },\n );\n },\n};\n\n/** `ph model check`. Returns the exit code. */\nexport async function runModelCheck(\n args: {\n readonly json: boolean;\n readonly release?: boolean;\n readonly prepack?: boolean;\n },\n options: ModelRunOptions = {},\n): Promise<number> {\n if (args.prepack) {\n if (args.release) {\n (options.streams ?? processStreams).err(\n \"ph model check could not run: --prepack and --release cannot be combined.\\n\",\n );\n return 2;\n }\n return await runPrepackCheck(args.json, options);\n }\n return await runModelCommand(\n {\n name: \"ph model check\",\n json: args.json,\n read: async (project, modules) =>\n args.release\n ? (await definitionChecks.release(project, modules)).report\n : await definitionChecks.edit(project, modules),\n render: renderCheckReport,\n },\n options,\n );\n}\n\n/**\n * `ph model check --prepack`: 0 when the release approval matches the\n * package, 1 when it does not, 2 when it cannot be checked. Loads none of\n * the package's modules.\n */\nasync function runPrepackCheck(\n json: boolean,\n options: ModelRunOptions,\n): Promise<number> {\n const streams = options.streams ?? processStreams;\n const { renderReleaseDecision, verifyRelease } =\n await import(\"../release/verify.js\");\n let decision: ReleaseDecision;\n try {\n decision = verifyRelease(options.projectRoot ?? process.cwd());\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n streams.err(`ph model check --prepack could not run: ${message}\\n`);\n return 2;\n }\n streams.out(\n `${json ? JSON.stringify({ decision: decision.decision, reasons: decision.reasons }) : renderReleaseDecision(decision)}\\n`,\n );\n return decision.decision === \"approved\" ? 0 : 1;\n}\n"],"names":[],"mappings":";;;;;;;AAkBA,eAAe,sBACb,SACA,SACA;CACA,MAAM,YAAY,MAAM,qBAAqB,SAAS,OAAO;CAC7D,IAAI,cAAc,KAAA,GAAW,OAAO,KAAA;CACpC,OAAO;EACL,QAAQ;EACR,OAAO,EAAE,WAAW,UAAU,MAAM;EACpC,WAAW,UAAU;CACvB;AACF;;;;;AAMA,MAAa,mBAAmB;CAC9B,MAAM,OACJ,SACA,YACmC;EACnC,MAAM,gBAAgB,MAAM,sBAAsB,SAAS,OAAO;EAClE,IAAI,kBAAkB,KAAA,GAAW,OAAO,wBAAwB,OAAO;EACvE,OAAO,wBACL;GAAE,GAAG;GAAS,GAAG,cAAc;EAAM,GACrC;GACE,QAAQ,CAAC,GAAG,qBAAqB,GAAG,cAAc,MAAM;GACxD,aAAa,cAAc;EAC7B,CACF;CACF;CACA,SAAS,OACP,SACA,YAC0B;EAC1B,MAAM,gBAAgB,MAAM,sBAAsB,SAAS,OAAO;EAClE,MAAM,EAAE,oBAAoB,MAAM,OAAO;EACzC,OAAO,MAAM,gBACX,SACA,SACA,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc,CACrD;CACF;AACF;;AAGA,eAAsB,cACpB,MAKA,UAA2B,CAAC,GACX;CACjB,IAAI,KAAK,SAAS;EAChB,IAAI,KAAK,SAAS;GAChB,CAAC,QAAQ,WAAW,eAAA,CAAgB,IAClC,6EACF;GACA,OAAO;EACT;EACA,OAAO,MAAM,gBAAgB,KAAK,MAAM,OAAO;CACjD;CACA,OAAO,MAAM,gBACX;EACE,MAAM;EACN,MAAM,KAAK;EACX,MAAM,OAAO,SAAS,YACpB,KAAK,WACA,MAAM,iBAAiB,QAAQ,SAAS,OAAO,EAAA,CAAG,SACnD,MAAM,iBAAiB,KAAK,SAAS,OAAO;EAClD,QAAQ;CACV,GACA,OACF;AACF;;;;;;AAOA,eAAe,gBACb,MACA,SACiB;CACjB,MAAM,UAAU,QAAQ,WAAW;CACnC,MAAM,EAAE,uBAAuB,kBAC7B,MAAM,OAAO;CACf,IAAI;CACJ,IAAI;EACF,WAAW,cAAc,QAAQ,eAAe,QAAQ,IAAI,CAAC;CAC/D,SAAS,OAAO;EACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EACrE,QAAQ,IAAI,2CAA2C,QAAQ,GAAG;EAClE,OAAO;CACT;CACA,QAAQ,IACN,GAAG,OAAO,KAAK,UAAU;EAAE,UAAU,SAAS;EAAU,SAAS,SAAS;CAAQ,CAAC,IAAI,sBAAsB,QAAQ,EAAE,GACzH;CACA,OAAO,SAAS,aAAa,aAAa,IAAI;AAChD","debug_id":"6c9ac309-c6d6-59a0-a411-0e6ee0e4cebb"}
package/dist/cli.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
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]="aa38e5db-5dbe-5933-859e-76cf696ddca8")}catch(e){}}();
4
- import { t as getVersion } from "./get-version-C3ozwlOI.mjs";
5
- import { t as phCliCommands } from "./ph-cli-commands-B39ZOxXF.mjs";
4
+ import { t as getVersion } from "./get-version-COv7hnzB.mjs";
5
+ import { t as phCliCommands } from "./ph-cli-commands-CM9JBqeZ.mjs";
6
6
  import { initCliTelemetry } from "@powerhousedao/shared/clis/telemetry";
7
7
  import { assertNodeVersion } from "@powerhousedao/shared/clis/utils";
8
8
  import { run, runSafely, subcommands } from "cmd-ts";
@@ -114,7 +114,7 @@ async function main() {
114
114
  });
115
115
  let args = process.argv.slice(2);
116
116
  const { applyRunSugar, forwardRunnerArgv } = await import("./run-sugar-DpznOP1e.mjs");
117
- const { phCliCommands } = await import("./ph-cli-commands-DppvECPl.mjs");
117
+ const { phCliCommands } = await import("./ph-cli-commands-CpbYNixr.mjs");
118
118
  const sugar = applyRunSugar(args, new Set(Object.keys(phCliCommands)), process.cwd());
119
119
  if (sugar.warning) console.warn(sugar.warning);
120
120
  args = forwardRunnerArgv(sugar.args);
@@ -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]="a4b4fd30-695f-5f66-b18c-056f86903346")}catch(e){}}();
3
- import { t as runBuild } from "./build-Cs3xAL0T.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]="c09ed773-3f07-5190-b874-8bf442e45854")}catch(e){}}();
3
+ import { t as runBuild } from "./build-pt5j4Jkr.mjs";
4
4
  import { t as buildCliConnectOverride } from "./cli-connect-override-D22yFWlC.mjs";
5
5
  import { existsSync, mkdirSync, readdirSync, rmSync } from "node:fs";
6
6
  import { join, resolve } from "node:path";
@@ -318,5 +318,5 @@ function assertLocalPackagesInstalled(projectPath) {
318
318
  //#endregion
319
319
  export { runConnectBuild };
320
320
 
321
- //# sourceMappingURL=connect-build-DXpZXOJw.mjs.map
322
- //# debugId=a4b4fd30-695f-5f66-b18c-056f86903346
321
+ //# sourceMappingURL=connect-build-DWMIQHA3.mjs.map
322
+ //# debugId=c09ed773-3f07-5190-b874-8bf442e45854
@@ -1 +1 @@
1
- {"version":3,"file":"connect-build-DXpZXOJw.mjs","sources":["../src/utils/precompress.ts","../src/services/connect-build.ts"],"sourcesContent":["import { PRECOMPRESS_EXTENSIONS } from \"@powerhousedao/ph-run/connect-serve\";\nimport { createHash } from \"node:crypto\";\nimport { readdir, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { gzip } from \"node:zlib\";\n\nconst gzipAsync = promisify(gzip);\n\nexport { PRECOMPRESS_EXTENSIONS };\n\n/** A sibling is written only when it is at most this fraction of the source. */\nconst MAX_RATIO = 0.9;\n\nexport type PrecompressResult = {\n files: number;\n written: number;\n skipped: number;\n inputBytes: number;\n outputBytes: number;\n ms: number;\n};\n\nasync function findTargets(dir: string): Promise<string[]> {\n const entries = await readdir(dir, { recursive: true, withFileTypes: true });\n return entries\n .filter(\n (e) =>\n e.isFile() &&\n PRECOMPRESS_EXTENSIONS.some((ext) => e.name.endsWith(ext)),\n )\n .map((e) => join(e.parentPath, e.name));\n}\n\nasync function isFresh(source: string, sibling: string): Promise<boolean> {\n try {\n const [s, c] = await Promise.all([stat(source), stat(sibling)]);\n return c.mtimeMs >= s.mtimeMs;\n } catch {\n return false;\n }\n}\n\n/** Write gzip siblings for every `.wasm`/`.data` under `dir`. */\nexport async function precompressAssets(\n dir: string,\n): Promise<PrecompressResult> {\n const start = performance.now();\n const targets = await findTargets(dir);\n const result: PrecompressResult = {\n files: targets.length,\n written: 0,\n skipped: 0,\n inputBytes: 0,\n outputBytes: 0,\n ms: 0,\n };\n // Vendor and worker copies share content: compress each distinct file once.\n const byHash = new Map<string, Promise<Buffer | null>>();\n\n await Promise.all(\n targets.map(async (file) => {\n const sibling = file + \".gz\";\n if (await isFresh(file, sibling)) {\n result.skipped += 1;\n return;\n }\n const source = await readFile(file);\n result.inputBytes += source.length;\n const hash = createHash(\"sha256\").update(source).digest(\"hex\");\n let compressed = byHash.get(hash);\n if (!compressed) {\n compressed = gzipAsync(source, { level: 9 }).then((out) =>\n out.length <= source.length * MAX_RATIO ? out : null,\n );\n byHash.set(hash, compressed);\n }\n const out = await compressed;\n if (!out) {\n await rm(sibling, { force: true });\n result.skipped += 1;\n return;\n }\n await writeFile(sibling, out);\n result.written += 1;\n result.outputBytes += out.length;\n }),\n );\n\n result.ms = Math.round(performance.now() - start);\n return result;\n}\n\n/** On by default; PH_CONNECT_PRECOMPRESS=0|false disables it. */\nexport function isPrecompressEnabled(\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n const raw = env.PH_CONNECT_PRECOMPRESS ?? \"1\";\n return raw !== \"0\" && raw !== \"false\";\n}\n","import {\n DEFAULT_VENDOR_INCLUDE,\n DYNAMIC_BASE_PLACEHOLDER,\n directoryContentDigest,\n findPackageRoot,\n getConnectBaseViteConfig,\n missingVendorEntries,\n prebuildConnectVendor,\n ownProjectPackage,\n prebuildReactorWorker,\n prebuildWorkerPackages,\n resolveReactorWorkerSource,\n type PrebuiltReactorWorker,\n type PrebuiltVendor,\n} from \"@powerhousedao/builder-tools\";\nimport { getConfig } from \"@powerhousedao/shared/clis\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport {\n deepMerge,\n normalizeBasePath,\n SHARED_DEP_SPECIFIERS,\n SHARED_SUBPATHS,\n} from \"@powerhousedao/shared/connect\";\nimport { existsSync, mkdirSync, readdirSync, rmSync } from \"node:fs\";\nimport { join, resolve } 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 {\n isPrecompressEnabled,\n precompressAssets,\n} from \"../utils/precompress.js\";\nimport { runBuild } from \"./build.js\";\n\nexport async function runConnectBuild(\n args: ConnectBuildArgs,\n callerOverride?: PHConnectRuntimeConfig,\n { routes }: { routes?: string | false } = {},\n) {\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 cli = buildCliConnectOverride(args);\n const { packageRegistryUrl } = cli;\n // A runner's host config sits under the CLI's flags.\n const connectOverride = callerOverride\n ? deepMerge(callerOverride, cli.connectOverride ?? {})\n : cli.connectOverride;\n\n await runBuild({\n outDir: \"dist\",\n debug,\n // Local packages built for Connect share deps with the app vendor, same\n // as a plain `ph build`.\n noSharedDeps: false,\n ignoreTypeErrors: false,\n release: false,\n });\n\n // Production shared-dependency vendor: prebuilt into <outDir>/__vendor__\n // before the app build. On by default; PH_CONNECT_VENDOR=0|false disables\n // it. A failed prebuild fails the build — production must not ship import\n // map entries pointing at a vendor that was never built (the dev server\n // keeps its own soft fallback in the dev plugin).\n const outDirAbs = resolve(dirname, outDir);\n let vendor: PrebuiltVendor | null = null;\n // The deploy base the vendor's import-map addresses are written against.\n // Only meaningful when the vendor is built; \"/\" is the inert default.\n let appBase = \"/\";\n // The prebuild out dirs' parent must exist before the prebuilds: their\n // build locks are siblings of the out dirs, and the package build\n // (runBuild) writes to a different out dir, so nothing else creates it yet.\n mkdirSync(outDirAbs, { recursive: true });\n if (isVendorEnabled()) {\n const errorRef: { message?: string } = {};\n // The same base string the app build uses below: the dynamic-base\n // placeholder, or the normalized deploy base (CLI override wins over the\n // source config). The vendor worker appends its own segment.\n const phConfig = getConfig(join(dirname, \"powerhouse.config.json\"));\n const connectBasePath =\n connectOverride?.app?.basePath ?? phConfig.connect?.app?.basePath;\n appBase = dynamicBase\n ? DYNAMIC_BASE_PLACEHOLDER\n : connectBasePath\n ? normalizeBasePath(connectBasePath)\n : \"/\";\n vendor = await prebuildConnectVendor({\n dirname,\n include: productionVendorInclude(),\n vendorDir: join(outDirAbs, \"__vendor__\"),\n base: appBase,\n nodeEnv: \"production\",\n errorRef,\n ...connectOwnVendorDeps(dirname),\n });\n if (!vendor) {\n console.error(\n `ph connect build: the shared-dependency vendor failed to build${\n errorRef.message ? `:\\n${errorRef.message}` : \"\"\n }`,\n );\n throw new Error(\"shared-dependency vendor prebuild failed\");\n }\n }\n\n // Reactor SharedWorker bundle: the dist worker is a library artifact whose\n // bare imports no worker can resolve (import maps do not apply to workers),\n // so the deployable form is prebuilt here. With a vendor, its shared deps\n // are externalized onto ../__vendor__/ so page and worker share one cache\n // entry per dep; without one it is fully self-contained.\n const reactorWorker = await prebuildReactorWorkerBundle(\n dirname,\n outDirAbs,\n vendor,\n connectOverride,\n );\n\n // Local project models the worker cannot get from the registry, built into\n // the worker bundle's own directory so they share its vendor.\n if (reactorWorker) {\n await prebuildLocalWorkerPackages(\n dirname,\n outDirAbs,\n vendor,\n reactorWorker.vendorImports,\n );\n }\n\n const keepDirs = [\n ...(vendor ? [\"__vendor__\"] : []),\n ...(reactorWorker ? [\"__reactor_worker__\"] : []),\n ];\n // Stale top-level output goes, the prebuilt dirs stay: the app build below\n // runs with emptyOutDir: false and must not wipe them.\n if (keepDirs.length > 0) {\n cleanDistExcept(outDirAbs, keepDirs);\n }\n\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride: connectOverride,\n cliPackageRegistryUrl: packageRegistryUrl,\n dynamicBase,\n favicon,\n routes,\n // Vendor import-map entries are relative (leading slash stripped) so\n // they resolve against the page URL under any deploy base — root or\n // subpath, dynamic or concrete.\n vendor: vendor\n ? {\n imports: vendorImportMapEntries(vendor.imports, appBase),\n versions: vendor.versions,\n sharedDeps: vendorImportMapEntries(\n { sharedDeps: vendor.sharedDeps },\n appBase,\n ).sharedDeps,\n }\n : undefined,\n reactorWorkerVersion: reactorWorker\n ? directoryContentDigest(join(outDirAbs, \"__reactor_worker__\"))\n : undefined,\n });\n\n const buildConfig: InlineConfig = {\n build: {\n outDir,\n // The vendor / worker dirs were prebuilt into the out dir above; the\n // build must not empty them.\n ...(keepDirs.length > 0 ? { emptyOutDir: false } : {}),\n },\n };\n\n const config = mergeConfig(baseConfig, buildConfig);\n\n await build(config);\n\n // Last word on the shipped artifact: every specifier the page's import map\n // publishes must have a file next to it. The prebuild verifies its own\n // output, but it can return a cache hit it never rebuilt, and both the\n // stale-output clean and the app build run afterwards. An entry with no\n // file behind it ships as a URL that 404s, and a SPA answers that with\n // index.html — so the browser reports only an opaque MIME-type error with\n // no filename. Fail here instead, naming the entries.\n if (vendor) {\n const unbacked = missingVendorEntries(\n join(outDirAbs, \"__vendor__\"),\n vendor.imports,\n );\n if (unbacked.length > 0) {\n throw new Error(\n `ph connect build: the shared-dependency vendor is missing ` +\n `${unbacked.length} of the ${Object.keys(vendor.imports).length} ` +\n `entries its import map publishes:\\n` +\n unbacked.map((e) => ` ${e.spec} -> ${e.url}`).join(\"\\n\"),\n );\n }\n }\n\n // Runs after the PWA plugin, so the siblings never enter the precache list.\n if (isPrecompressEnabled()) {\n const r = await precompressAssets(outDirAbs);\n console.log(\n `ph connect build: precompressed ${r.files} wasm/data files ` +\n `(${r.written} .gz written, ${(r.outputBytes / 1e6).toFixed(1)} MB) in ${(r.ms / 1000).toFixed(1)}s`,\n );\n }\n}\n\n/**\n * The specifier set the production vendor bundles: the dev-proven heavy set\n * ∪ the package-shared set — everything the app and loaded packages\n * externalize onto the vendor.\n *\n * Two specifiers are deliberately dropped:\n *\n * - `@powerhousedao/connect`. It is in DEFAULT_VENDOR_INCLUDE because the dev\n * server vendors the app to keep rebuilds cheap, but in a production build\n * the app *is* Connect: `SHARED_DEP_SPECIFIERS` omits it, so the app build\n * never externalizes it and nothing would ever resolve its import-map\n * entry. Vendoring it is not merely dead weight — bundling Connect's dist\n * for the browser pulls in its node-only `@powerhousedao/config/node`\n * import, and so `read-pkg` -> `unicorn-magic`, whose browser entry has no\n * `toPath`. That fails the vendor build, and a failed prebuild fails\n * `ph connect build`.\n * - the bare `@powerhousedao/shared` root, whose barrel likewise reaches\n * node-only modules. Its browser-safe subpaths (SHARED_SUBPATHS) are\n * listed instead; a package importing the bare root bundles its own copy.\n */\nexport function productionVendorInclude(): string[] {\n return [\n ...new Set([\n ...DEFAULT_VENDOR_INCLUDE.filter((s) => s !== \"@powerhousedao/connect\"),\n ...SHARED_DEP_SPECIFIERS.filter((s) => s !== \"@powerhousedao/shared\"),\n ...SHARED_SUBPATHS.map((s) => `@powerhousedao/shared/${s}`),\n // Connect imports these roots too; unvendored, the app re-bundles their shared chunks.\n \"@powerhousedao/design-system\",\n \"@powerhousedao/reactor\",\n ]),\n ];\n}\n\n/** Connect's own deps that vendored packages also bundle; projects don't install them. */\nexport const CONNECT_OWN_VENDOR_DEPS = [\n \"kysely\",\n \"tailwind-merge\",\n \"@renown/sdk\",\n \"@renown/sdk/crypto\",\n \"@renown/sdk/trust\",\n \"@powerhousedao/reactor-attachments/client\",\n // One core and router for Connect and packages; the route tree, config and\n // embedded subpaths stay with the app.\n \"@powerhousedao/connect-core\",\n \"@powerhousedao/connect-core/router\",\n \"@powerhousedao/connect-core/plugins\",\n \"@powerhousedao/connect-core/runtime\",\n \"@powerhousedao/connect-core/views\",\n \"@tanstack/react-router\",\n];\n\nexport function connectOwnVendorDeps(dirname: string): {\n ownDeps?: { specs: string[]; from: string };\n} {\n const from = findPackageRoot(dirname, \"@powerhousedao/connect\");\n return from ? { ownDeps: { specs: CONNECT_OWN_VENDOR_DEPS, from } } : {};\n}\n\n/**\n * Turn the vendor's base-less URLs (`/__vendor__/x.js`) into the addresses\n * the page's import map ships, by prefixing the deploy base.\n *\n * An import map *address* must be a URL or begin with `/`, `./` or `../`;\n * anything else is a bare specifier, which the browser rejects — it drops the\n * entry, resolves the specifier to null, and every shared import then fails\n * with \"blocked by a null value\". So the base is applied rather than the\n * leading slash stripped: a root-relative address is both valid and correct\n * under a subpath deploy, and a dynamic-base build keeps its placeholder for\n * the serving proxy to substitute (the dynamic-base plugin leaves HTML\n * tokens alone by design).\n */\nexport function vendorImportMapEntries(\n imports: Record<string, string>,\n appBase: string,\n): Record<string, string> {\n return Object.fromEntries(\n Object.entries(imports).map(([spec, url]) => [\n spec,\n `${appBase}/${url}`.replace(/\\/{2,}/g, \"/\"),\n ]),\n );\n}\n\n/**\n * The production vendor prebuild runs on every `ph connect build` unless\n * disabled with PH_CONNECT_VENDOR=0 or false.\n */\nexport function isVendorEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n const raw = env.PH_CONNECT_VENDOR ?? \"1\";\n return raw !== \"0\" && raw !== \"false\";\n}\n\n/**\n * The reactor worker bundle prebuild runs on every `ph connect build` unless\n * disabled with PH_CONNECT_REACTOR_WORKER=0 or false. It is built even when\n * `connect.instance.reactorWorker` is off, because the `?reactorWorker=true`\n * runtime override can enable the feature on a flag-off deployment.\n */\nexport function isReactorWorkerBundleEnabled(\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n const raw = env.PH_CONNECT_REACTOR_WORKER ?? \"1\";\n return raw !== \"0\" && raw !== \"false\";\n}\n\n/**\n * Prebuild the reactor SharedWorker bundle into `<dist>/__reactor_worker__`.\n * Returns null when the prebuild is disabled, the installed Connect ships no\n * worker entry, or the build fails. A failure only fails `ph connect build`\n * when the project explicitly enables `connect.instance.reactorWorker` —\n * otherwise the feature degrades to unavailable and the build goes on.\n */\nasync function prebuildReactorWorkerBundle(\n dirname: string,\n outDirAbs: string,\n vendor: PrebuiltVendor | null,\n connectOverride: PHConnectRuntimeConfig | undefined,\n): Promise<PrebuiltReactorWorker | null> {\n if (!isReactorWorkerBundleEnabled()) return null;\n if (!resolveReactorWorkerSource(dirname)) return null;\n\n const errorRef: { message?: string } = {};\n const bundle = await prebuildReactorWorker({\n dirname,\n outDir: join(outDirAbs, \"__reactor_worker__\"),\n vendor: vendor\n ? { imports: vendor.imports, dir: join(outDirAbs, \"__vendor__\") }\n : undefined,\n nodeEnv: \"production\",\n errorRef,\n });\n if (bundle) return bundle;\n\n const message = `ph connect build: the reactor worker bundle failed to build${\n errorRef.message ? `:\\n${errorRef.message}` : \"\"\n }`;\n const phConfig = getConfig(join(dirname, \"powerhouse.config.json\"));\n const required =\n connectOverride?.instance?.reactorWorker ??\n phConfig.connect?.instance?.reactorWorker ??\n false;\n if (required) {\n throw new Error(message);\n }\n console.warn(\n `${message}\\nThe reactorWorker feature will be unavailable in this build.`,\n );\n return null;\n}\n\n/**\n * Build the project's `provider: \"local\"` packages into worker-loadable model\n * bundles beside the worker. A failure is a warning, not a build failure: the\n * worker still runs, and documents of registry types still work - only the\n * project's own types would be unavailable in worker mode.\n */\nasync function prebuildLocalWorkerPackages(\n dirname: string,\n outDirAbs: string,\n vendor: PrebuiltVendor | null,\n safeVendorImports: Record<string, string>,\n): Promise<void> {\n const config = getConfig(join(dirname, \"powerhouse.config.json\"));\n const configured = (config.packages ?? [])\n .filter((p) => p.provider === \"local\")\n .map((p) => p.packageName);\n // The project itself is a local package in all but name: a vetra project\n // declares no entry for itself, and its models are the ones the worker\n // cannot otherwise get.\n const own = ownProjectPackage(dirname);\n const localPackages = [...new Set([...configured, ...(own ? [own] : [])])];\n\n const errorRef: { message?: string } = {};\n const built = await prebuildWorkerPackages({\n dirname,\n packages: localPackages,\n outDir: join(outDirAbs, \"__reactor_worker__\", \"packages\"),\n vendor: vendor\n ? { imports: vendor.imports, dir: join(outDirAbs, \"__vendor__\") }\n : undefined,\n safeVendorImports,\n nodeEnv: \"production\",\n errorRef,\n });\n if (!built) {\n console.warn(\n `ph connect build: the reactor worker's local package bundles failed to build${\n errorRef.message ? `:\\n${errorRef.message}` : \"\"\n }\\nDocuments of this project's own types will not load in worker mode.`,\n );\n }\n}\n\n/**\n * Remove every top-level entry of `dist` except the kept names. Used between\n * the vendor prebuild and the app build so stale app output goes but the\n * just-built vendor stays (the build then runs with emptyOutDir: false).\n * Returns the number of entries removed.\n */\nexport function cleanDistExcept(dist: string, keep: string[] = []): number {\n if (!existsSync(dist)) return 0;\n let removed = 0;\n for (const entry of readdirSync(dist)) {\n if (keep.includes(entry)) continue;\n rmSync(join(dist, entry), { recursive: true, force: true });\n removed += 1;\n }\n return removed;\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":";;;;;;;;;;;;;;;;AAOA,MAAM,YAAY,UAAU,IAAI;;AAKhC,MAAM,YAAY;AAWlB,eAAe,YAAY,KAAgC;CAEzD,QAAO,MADe,QAAQ,KAAK;EAAE,WAAW;EAAM,eAAe;CAAK,CAAC,EAAA,CAExE,QACE,MACC,EAAE,OAAO,KACT,uBAAuB,MAAM,QAAQ,EAAE,KAAK,SAAS,GAAG,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,GAAG;EACrC,IAAI,KAAK,SAAS,KAAK,GAAG;EAC1B,OAAO,KAAK,MAAM,KAAK,GAAG;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;EAC1D,WAAW;CACb;CACA,OAAO;AACT;AAEA,SAAS,6BAA6B,aAAqB;CAEzD,MAAM,iBADS,UAAU,KAAK,aAAa,wBAAwB,CACvC,CAAC,CAAC,YAAY,CAAC,EAAA,CAAG,QAC3C,MAAM,EAAE,aAAa,OACxB;CACA,IAAI,cAAc,WAAW,GAAG;CAEhC,MAAM,UAAU,cAAc,QAC3B,MACC,CAAC,WACC,KAAK,aAAa,gBAAgB,EAAE,aAAa,cAAc,CACjE,CACJ;CACA,IAAI,QAAQ,WAAW,GAAG;CAE1B,MAAM,QAAQ,QAAQ,KAAK,MAAM,EAAE,WAAW;CAC9C,MAAM,IAAI,MACR,qJACE,MAAM,KAAK,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,IAAI,IACtC,gDAAgD,MAAM,KAAK,GAAG,GAClE;AACF","debug_id":"a4b4fd30-695f-5f66-b18c-056f86903346"}
1
+ {"version":3,"file":"connect-build-DWMIQHA3.mjs","sources":["../src/utils/precompress.ts","../src/services/connect-build.ts"],"sourcesContent":["import { PRECOMPRESS_EXTENSIONS } from \"@powerhousedao/ph-run/connect-serve\";\nimport { createHash } from \"node:crypto\";\nimport { readdir, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { gzip } from \"node:zlib\";\n\nconst gzipAsync = promisify(gzip);\n\nexport { PRECOMPRESS_EXTENSIONS };\n\n/** A sibling is written only when it is at most this fraction of the source. */\nconst MAX_RATIO = 0.9;\n\nexport type PrecompressResult = {\n files: number;\n written: number;\n skipped: number;\n inputBytes: number;\n outputBytes: number;\n ms: number;\n};\n\nasync function findTargets(dir: string): Promise<string[]> {\n const entries = await readdir(dir, { recursive: true, withFileTypes: true });\n return entries\n .filter(\n (e) =>\n e.isFile() &&\n PRECOMPRESS_EXTENSIONS.some((ext) => e.name.endsWith(ext)),\n )\n .map((e) => join(e.parentPath, e.name));\n}\n\nasync function isFresh(source: string, sibling: string): Promise<boolean> {\n try {\n const [s, c] = await Promise.all([stat(source), stat(sibling)]);\n return c.mtimeMs >= s.mtimeMs;\n } catch {\n return false;\n }\n}\n\n/** Write gzip siblings for every `.wasm`/`.data` under `dir`. */\nexport async function precompressAssets(\n dir: string,\n): Promise<PrecompressResult> {\n const start = performance.now();\n const targets = await findTargets(dir);\n const result: PrecompressResult = {\n files: targets.length,\n written: 0,\n skipped: 0,\n inputBytes: 0,\n outputBytes: 0,\n ms: 0,\n };\n // Vendor and worker copies share content: compress each distinct file once.\n const byHash = new Map<string, Promise<Buffer | null>>();\n\n await Promise.all(\n targets.map(async (file) => {\n const sibling = file + \".gz\";\n if (await isFresh(file, sibling)) {\n result.skipped += 1;\n return;\n }\n const source = await readFile(file);\n result.inputBytes += source.length;\n const hash = createHash(\"sha256\").update(source).digest(\"hex\");\n let compressed = byHash.get(hash);\n if (!compressed) {\n compressed = gzipAsync(source, { level: 9 }).then((out) =>\n out.length <= source.length * MAX_RATIO ? out : null,\n );\n byHash.set(hash, compressed);\n }\n const out = await compressed;\n if (!out) {\n await rm(sibling, { force: true });\n result.skipped += 1;\n return;\n }\n await writeFile(sibling, out);\n result.written += 1;\n result.outputBytes += out.length;\n }),\n );\n\n result.ms = Math.round(performance.now() - start);\n return result;\n}\n\n/** On by default; PH_CONNECT_PRECOMPRESS=0|false disables it. */\nexport function isPrecompressEnabled(\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n const raw = env.PH_CONNECT_PRECOMPRESS ?? \"1\";\n return raw !== \"0\" && raw !== \"false\";\n}\n","import {\n DEFAULT_VENDOR_INCLUDE,\n DYNAMIC_BASE_PLACEHOLDER,\n directoryContentDigest,\n findPackageRoot,\n getConnectBaseViteConfig,\n missingVendorEntries,\n prebuildConnectVendor,\n ownProjectPackage,\n prebuildReactorWorker,\n prebuildWorkerPackages,\n resolveReactorWorkerSource,\n type PrebuiltReactorWorker,\n type PrebuiltVendor,\n} from \"@powerhousedao/builder-tools\";\nimport { getConfig } from \"@powerhousedao/shared/clis\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport {\n deepMerge,\n normalizeBasePath,\n SHARED_DEP_SPECIFIERS,\n SHARED_SUBPATHS,\n} from \"@powerhousedao/shared/connect\";\nimport { existsSync, mkdirSync, readdirSync, rmSync } from \"node:fs\";\nimport { join, resolve } 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 {\n isPrecompressEnabled,\n precompressAssets,\n} from \"../utils/precompress.js\";\nimport { runBuild } from \"./build.js\";\n\nexport async function runConnectBuild(\n args: ConnectBuildArgs,\n callerOverride?: PHConnectRuntimeConfig,\n { routes }: { routes?: string | false } = {},\n) {\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 cli = buildCliConnectOverride(args);\n const { packageRegistryUrl } = cli;\n // A runner's host config sits under the CLI's flags.\n const connectOverride = callerOverride\n ? deepMerge(callerOverride, cli.connectOverride ?? {})\n : cli.connectOverride;\n\n await runBuild({\n outDir: \"dist\",\n debug,\n // Local packages built for Connect share deps with the app vendor, same\n // as a plain `ph build`.\n noSharedDeps: false,\n ignoreTypeErrors: false,\n release: false,\n });\n\n // Production shared-dependency vendor: prebuilt into <outDir>/__vendor__\n // before the app build. On by default; PH_CONNECT_VENDOR=0|false disables\n // it. A failed prebuild fails the build — production must not ship import\n // map entries pointing at a vendor that was never built (the dev server\n // keeps its own soft fallback in the dev plugin).\n const outDirAbs = resolve(dirname, outDir);\n let vendor: PrebuiltVendor | null = null;\n // The deploy base the vendor's import-map addresses are written against.\n // Only meaningful when the vendor is built; \"/\" is the inert default.\n let appBase = \"/\";\n // The prebuild out dirs' parent must exist before the prebuilds: their\n // build locks are siblings of the out dirs, and the package build\n // (runBuild) writes to a different out dir, so nothing else creates it yet.\n mkdirSync(outDirAbs, { recursive: true });\n if (isVendorEnabled()) {\n const errorRef: { message?: string } = {};\n // The same base string the app build uses below: the dynamic-base\n // placeholder, or the normalized deploy base (CLI override wins over the\n // source config). The vendor worker appends its own segment.\n const phConfig = getConfig(join(dirname, \"powerhouse.config.json\"));\n const connectBasePath =\n connectOverride?.app?.basePath ?? phConfig.connect?.app?.basePath;\n appBase = dynamicBase\n ? DYNAMIC_BASE_PLACEHOLDER\n : connectBasePath\n ? normalizeBasePath(connectBasePath)\n : \"/\";\n vendor = await prebuildConnectVendor({\n dirname,\n include: productionVendorInclude(),\n vendorDir: join(outDirAbs, \"__vendor__\"),\n base: appBase,\n nodeEnv: \"production\",\n errorRef,\n ...connectOwnVendorDeps(dirname),\n });\n if (!vendor) {\n console.error(\n `ph connect build: the shared-dependency vendor failed to build${\n errorRef.message ? `:\\n${errorRef.message}` : \"\"\n }`,\n );\n throw new Error(\"shared-dependency vendor prebuild failed\");\n }\n }\n\n // Reactor SharedWorker bundle: the dist worker is a library artifact whose\n // bare imports no worker can resolve (import maps do not apply to workers),\n // so the deployable form is prebuilt here. With a vendor, its shared deps\n // are externalized onto ../__vendor__/ so page and worker share one cache\n // entry per dep; without one it is fully self-contained.\n const reactorWorker = await prebuildReactorWorkerBundle(\n dirname,\n outDirAbs,\n vendor,\n connectOverride,\n );\n\n // Local project models the worker cannot get from the registry, built into\n // the worker bundle's own directory so they share its vendor.\n if (reactorWorker) {\n await prebuildLocalWorkerPackages(\n dirname,\n outDirAbs,\n vendor,\n reactorWorker.vendorImports,\n );\n }\n\n const keepDirs = [\n ...(vendor ? [\"__vendor__\"] : []),\n ...(reactorWorker ? [\"__reactor_worker__\"] : []),\n ];\n // Stale top-level output goes, the prebuilt dirs stay: the app build below\n // runs with emptyOutDir: false and must not wipe them.\n if (keepDirs.length > 0) {\n cleanDistExcept(outDirAbs, keepDirs);\n }\n\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride: connectOverride,\n cliPackageRegistryUrl: packageRegistryUrl,\n dynamicBase,\n favicon,\n routes,\n // Vendor import-map entries are relative (leading slash stripped) so\n // they resolve against the page URL under any deploy base — root or\n // subpath, dynamic or concrete.\n vendor: vendor\n ? {\n imports: vendorImportMapEntries(vendor.imports, appBase),\n versions: vendor.versions,\n sharedDeps: vendorImportMapEntries(\n { sharedDeps: vendor.sharedDeps },\n appBase,\n ).sharedDeps,\n }\n : undefined,\n reactorWorkerVersion: reactorWorker\n ? directoryContentDigest(join(outDirAbs, \"__reactor_worker__\"))\n : undefined,\n });\n\n const buildConfig: InlineConfig = {\n build: {\n outDir,\n // The vendor / worker dirs were prebuilt into the out dir above; the\n // build must not empty them.\n ...(keepDirs.length > 0 ? { emptyOutDir: false } : {}),\n },\n };\n\n const config = mergeConfig(baseConfig, buildConfig);\n\n await build(config);\n\n // Last word on the shipped artifact: every specifier the page's import map\n // publishes must have a file next to it. The prebuild verifies its own\n // output, but it can return a cache hit it never rebuilt, and both the\n // stale-output clean and the app build run afterwards. An entry with no\n // file behind it ships as a URL that 404s, and a SPA answers that with\n // index.html — so the browser reports only an opaque MIME-type error with\n // no filename. Fail here instead, naming the entries.\n if (vendor) {\n const unbacked = missingVendorEntries(\n join(outDirAbs, \"__vendor__\"),\n vendor.imports,\n );\n if (unbacked.length > 0) {\n throw new Error(\n `ph connect build: the shared-dependency vendor is missing ` +\n `${unbacked.length} of the ${Object.keys(vendor.imports).length} ` +\n `entries its import map publishes:\\n` +\n unbacked.map((e) => ` ${e.spec} -> ${e.url}`).join(\"\\n\"),\n );\n }\n }\n\n // Runs after the PWA plugin, so the siblings never enter the precache list.\n if (isPrecompressEnabled()) {\n const r = await precompressAssets(outDirAbs);\n console.log(\n `ph connect build: precompressed ${r.files} wasm/data files ` +\n `(${r.written} .gz written, ${(r.outputBytes / 1e6).toFixed(1)} MB) in ${(r.ms / 1000).toFixed(1)}s`,\n );\n }\n}\n\n/**\n * The specifier set the production vendor bundles: the dev-proven heavy set\n * ∪ the package-shared set — everything the app and loaded packages\n * externalize onto the vendor.\n *\n * Two specifiers are deliberately dropped:\n *\n * - `@powerhousedao/connect`. It is in DEFAULT_VENDOR_INCLUDE because the dev\n * server vendors the app to keep rebuilds cheap, but in a production build\n * the app *is* Connect: `SHARED_DEP_SPECIFIERS` omits it, so the app build\n * never externalizes it and nothing would ever resolve its import-map\n * entry. Vendoring it is not merely dead weight — bundling Connect's dist\n * for the browser pulls in its node-only `@powerhousedao/config/node`\n * import, and so `read-pkg` -> `unicorn-magic`, whose browser entry has no\n * `toPath`. That fails the vendor build, and a failed prebuild fails\n * `ph connect build`.\n * - the bare `@powerhousedao/shared` root, whose barrel likewise reaches\n * node-only modules. Its browser-safe subpaths (SHARED_SUBPATHS) are\n * listed instead; a package importing the bare root bundles its own copy.\n */\nexport function productionVendorInclude(): string[] {\n return [\n ...new Set([\n ...DEFAULT_VENDOR_INCLUDE.filter((s) => s !== \"@powerhousedao/connect\"),\n ...SHARED_DEP_SPECIFIERS.filter((s) => s !== \"@powerhousedao/shared\"),\n ...SHARED_SUBPATHS.map((s) => `@powerhousedao/shared/${s}`),\n // Connect imports these roots too; unvendored, the app re-bundles their shared chunks.\n \"@powerhousedao/design-system\",\n \"@powerhousedao/reactor\",\n ]),\n ];\n}\n\n/** Connect's own deps that vendored packages also bundle; projects don't install them. */\nexport const CONNECT_OWN_VENDOR_DEPS = [\n \"kysely\",\n \"tailwind-merge\",\n \"@renown/sdk\",\n \"@renown/sdk/crypto\",\n \"@renown/sdk/trust\",\n \"@powerhousedao/reactor-attachments/client\",\n // One core and router for Connect and packages; the route tree, config and\n // embedded subpaths stay with the app.\n \"@powerhousedao/connect-core\",\n \"@powerhousedao/connect-core/router\",\n \"@powerhousedao/connect-core/plugins\",\n \"@powerhousedao/connect-core/runtime\",\n \"@powerhousedao/connect-core/views\",\n \"@tanstack/react-router\",\n];\n\nexport function connectOwnVendorDeps(dirname: string): {\n ownDeps?: { specs: string[]; from: string };\n} {\n const from = findPackageRoot(dirname, \"@powerhousedao/connect\");\n return from ? { ownDeps: { specs: CONNECT_OWN_VENDOR_DEPS, from } } : {};\n}\n\n/**\n * Turn the vendor's base-less URLs (`/__vendor__/x.js`) into the addresses\n * the page's import map ships, by prefixing the deploy base.\n *\n * An import map *address* must be a URL or begin with `/`, `./` or `../`;\n * anything else is a bare specifier, which the browser rejects — it drops the\n * entry, resolves the specifier to null, and every shared import then fails\n * with \"blocked by a null value\". So the base is applied rather than the\n * leading slash stripped: a root-relative address is both valid and correct\n * under a subpath deploy, and a dynamic-base build keeps its placeholder for\n * the serving proxy to substitute (the dynamic-base plugin leaves HTML\n * tokens alone by design).\n */\nexport function vendorImportMapEntries(\n imports: Record<string, string>,\n appBase: string,\n): Record<string, string> {\n return Object.fromEntries(\n Object.entries(imports).map(([spec, url]) => [\n spec,\n `${appBase}/${url}`.replace(/\\/{2,}/g, \"/\"),\n ]),\n );\n}\n\n/**\n * The production vendor prebuild runs on every `ph connect build` unless\n * disabled with PH_CONNECT_VENDOR=0 or false.\n */\nexport function isVendorEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n const raw = env.PH_CONNECT_VENDOR ?? \"1\";\n return raw !== \"0\" && raw !== \"false\";\n}\n\n/**\n * The reactor worker bundle prebuild runs on every `ph connect build` unless\n * disabled with PH_CONNECT_REACTOR_WORKER=0 or false. It is built even when\n * `connect.instance.reactorWorker` is off, because the `?reactorWorker=true`\n * runtime override can enable the feature on a flag-off deployment.\n */\nexport function isReactorWorkerBundleEnabled(\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n const raw = env.PH_CONNECT_REACTOR_WORKER ?? \"1\";\n return raw !== \"0\" && raw !== \"false\";\n}\n\n/**\n * Prebuild the reactor SharedWorker bundle into `<dist>/__reactor_worker__`.\n * Returns null when the prebuild is disabled, the installed Connect ships no\n * worker entry, or the build fails. A failure only fails `ph connect build`\n * when the project explicitly enables `connect.instance.reactorWorker` —\n * otherwise the feature degrades to unavailable and the build goes on.\n */\nasync function prebuildReactorWorkerBundle(\n dirname: string,\n outDirAbs: string,\n vendor: PrebuiltVendor | null,\n connectOverride: PHConnectRuntimeConfig | undefined,\n): Promise<PrebuiltReactorWorker | null> {\n if (!isReactorWorkerBundleEnabled()) return null;\n if (!resolveReactorWorkerSource(dirname)) return null;\n\n const errorRef: { message?: string } = {};\n const bundle = await prebuildReactorWorker({\n dirname,\n outDir: join(outDirAbs, \"__reactor_worker__\"),\n vendor: vendor\n ? { imports: vendor.imports, dir: join(outDirAbs, \"__vendor__\") }\n : undefined,\n nodeEnv: \"production\",\n errorRef,\n });\n if (bundle) return bundle;\n\n const message = `ph connect build: the reactor worker bundle failed to build${\n errorRef.message ? `:\\n${errorRef.message}` : \"\"\n }`;\n const phConfig = getConfig(join(dirname, \"powerhouse.config.json\"));\n const required =\n connectOverride?.instance?.reactorWorker ??\n phConfig.connect?.instance?.reactorWorker ??\n false;\n if (required) {\n throw new Error(message);\n }\n console.warn(\n `${message}\\nThe reactorWorker feature will be unavailable in this build.`,\n );\n return null;\n}\n\n/**\n * Build the project's `provider: \"local\"` packages into worker-loadable model\n * bundles beside the worker. A failure is a warning, not a build failure: the\n * worker still runs, and documents of registry types still work - only the\n * project's own types would be unavailable in worker mode.\n */\nasync function prebuildLocalWorkerPackages(\n dirname: string,\n outDirAbs: string,\n vendor: PrebuiltVendor | null,\n safeVendorImports: Record<string, string>,\n): Promise<void> {\n const config = getConfig(join(dirname, \"powerhouse.config.json\"));\n const configured = (config.packages ?? [])\n .filter((p) => p.provider === \"local\")\n .map((p) => p.packageName);\n // The project itself is a local package in all but name: a vetra project\n // declares no entry for itself, and its models are the ones the worker\n // cannot otherwise get.\n const own = ownProjectPackage(dirname);\n const localPackages = [...new Set([...configured, ...(own ? [own] : [])])];\n\n const errorRef: { message?: string } = {};\n const built = await prebuildWorkerPackages({\n dirname,\n packages: localPackages,\n outDir: join(outDirAbs, \"__reactor_worker__\", \"packages\"),\n vendor: vendor\n ? { imports: vendor.imports, dir: join(outDirAbs, \"__vendor__\") }\n : undefined,\n safeVendorImports,\n nodeEnv: \"production\",\n errorRef,\n });\n if (!built) {\n console.warn(\n `ph connect build: the reactor worker's local package bundles failed to build${\n errorRef.message ? `:\\n${errorRef.message}` : \"\"\n }\\nDocuments of this project's own types will not load in worker mode.`,\n );\n }\n}\n\n/**\n * Remove every top-level entry of `dist` except the kept names. Used between\n * the vendor prebuild and the app build so stale app output goes but the\n * just-built vendor stays (the build then runs with emptyOutDir: false).\n * Returns the number of entries removed.\n */\nexport function cleanDistExcept(dist: string, keep: string[] = []): number {\n if (!existsSync(dist)) return 0;\n let removed = 0;\n for (const entry of readdirSync(dist)) {\n if (keep.includes(entry)) continue;\n rmSync(join(dist, entry), { recursive: true, force: true });\n removed += 1;\n }\n return removed;\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":";;;;;;;;;;;;;;;;AAOA,MAAM,YAAY,UAAU,IAAI;;AAKhC,MAAM,YAAY;AAWlB,eAAe,YAAY,KAAgC;CAEzD,QAAO,MADe,QAAQ,KAAK;EAAE,WAAW;EAAM,eAAe;CAAK,CAAC,EAAA,CAExE,QACE,MACC,EAAE,OAAO,KACT,uBAAuB,MAAM,QAAQ,EAAE,KAAK,SAAS,GAAG,CAAC,CAC7D,CAAC,CACA,KAAK,MAAM,KAAK,EAAE,YAAY,EAAE,IAAI,CAAC;AAC1C;AAEA,eAAe,QAAQ,QAAgB,SAAmC;CACxE,IAAI;EACF,MAAM,CAAC,GAAG,KAAK,MAAM,QAAQ,IAAI,CAAC,KAAK,MAAM,GAAG,KAAK,OAAO,CAAC,CAAC;EAC9D,OAAO,EAAE,WAAW,EAAE;CACxB,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,eAAsB,kBACpB,KAC4B;CAC5B,MAAM,QAAQ,YAAY,IAAI;CAC9B,MAAM,UAAU,MAAM,YAAY,GAAG;CACrC,MAAM,SAA4B;EAChC,OAAO,QAAQ;EACf,SAAS;EACT,SAAS;EACT,YAAY;EACZ,aAAa;EACb,IAAI;CACN;CAEA,MAAM,yBAAS,IAAI,IAAoC;CAEvD,MAAM,QAAQ,IACZ,QAAQ,IAAI,OAAO,SAAS;EAC1B,MAAM,UAAU,OAAO;EACvB,IAAI,MAAM,QAAQ,MAAM,OAAO,GAAG;GAChC,OAAO,WAAW;GAClB;EACF;EACA,MAAM,SAAS,MAAM,SAAS,IAAI;EAClC,OAAO,cAAc,OAAO;EAC5B,MAAM,OAAO,WAAW,QAAQ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,CAAE,CAAC,CAAC;CAEzE,MAAM,WAAiC,CAAC;CAYxC,IAAI,CAAC,MAXe,uBAAuB;EACzC;EACA,UAAU;EACV,QAAQ,KAAK,WAAW,sBAAsB,UAAU;EACxD,QAAQ,SACJ;GAAE,SAAS,OAAO;GAAS,KAAK,KAAK,WAAW,YAAY;EAAE,IAC9D,KAAA;EACJ;EACA,SAAS;EACT;CACF,CAAC,GAEC,QAAQ,KACN,+EACE,SAAS,UAAU,MAAM,SAAS,YAAY,GAC/C,sEACH;AAEJ;;;;;;;AAQA,SAAgB,gBAAgB,MAAc,OAAiB,CAAC,GAAW;CACzE,IAAI,CAAC,WAAW,IAAI,GAAG,OAAO;CAC9B,IAAI,UAAU;CACd,KAAK,MAAM,SAAS,YAAY,IAAI,GAAG;EACrC,IAAI,KAAK,SAAS,KAAK,GAAG;EAC1B,OAAO,KAAK,MAAM,KAAK,GAAG;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;EAC1D,WAAW;CACb;CACA,OAAO;AACT;AAEA,SAAS,6BAA6B,aAAqB;CAEzD,MAAM,iBADS,UAAU,KAAK,aAAa,wBAAwB,CACvC,CAAC,CAAC,YAAY,CAAC,EAAA,CAAG,QAC3C,MAAM,EAAE,aAAa,OACxB;CACA,IAAI,cAAc,WAAW,GAAG;CAEhC,MAAM,UAAU,cAAc,QAC3B,MACC,CAAC,WACC,KAAK,aAAa,gBAAgB,EAAE,aAAa,cAAc,CACjE,CACJ;CACA,IAAI,QAAQ,WAAW,GAAG;CAE1B,MAAM,QAAQ,QAAQ,KAAK,MAAM,EAAE,WAAW;CAC9C,MAAM,IAAI,MACR,qJACE,MAAM,KAAK,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,IAAI,IACtC,gDAAgD,MAAM,KAAK,GAAG,GAClE;AACF","debug_id":"c09ed773-3f07-5190-b874-8bf442e45854"}
@@ -1,7 +1,7 @@
1
1
 
2
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]="edf7b6f1-f92c-5c1c-a38c-826e30b54557")}catch(e){}}();
3
3
  import { i as readProjectDefinitions } from "./run--de_-WAz.mjs";
4
- import { t as definitionChecks } from "./check-Bg06Tzgm.mjs";
4
+ import { t as definitionChecks } from "./check-BhYboAXc.mjs";
5
5
  //#region src/services/model/definitions-worker.ts
6
6
  async function check(projectRoot, profile) {
7
7
  const read = definitionChecks[profile];
@@ -1,11 +1,11 @@
1
1
  //#region src/get-version.ts
2
2
 
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]="6e165338-8aaa-542a-9b01-10e474658991")}catch(e){}}();
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]="3e646aca-1e4c-5a06-a68e-5c5b4b70a985")}catch(e){}}();
4
4
  function getVersion() {
5
- return "6.3.0-dev.5";
5
+ return "6.3.0-dev.7";
6
6
  }
7
7
  //#endregion
8
8
  export { getVersion as t };
9
9
 
10
- //# sourceMappingURL=get-version-C3ozwlOI.mjs.map
11
- //# debugId=6e165338-8aaa-542a-9b01-10e474658991
10
+ //# sourceMappingURL=get-version-COv7hnzB.mjs.map
11
+ //# debugId=3e646aca-1e4c-5a06-a68e-5c5b4b70a985
@@ -1 +1 @@
1
- {"version":3,"file":"get-version-C3ozwlOI.mjs","sources":["../src/get-version.ts"],"sourcesContent":["declare const CLI_VERSION: string | undefined;\ndeclare const CLI_GIT_SHA: string | undefined;\n\nexport function getVersion() {\n if (typeof CLI_VERSION !== \"undefined\") return CLI_VERSION;\n return (\n process.env.WORKSPACE_VERSION ||\n process.env.npm_package_version ||\n \"unknown\"\n );\n}\n\nexport function getGitHash() {\n if (typeof CLI_GIT_SHA !== \"undefined\") return CLI_GIT_SHA;\n return process.env.WORKSPACE_GIT_SHA || \"unknown\";\n}\n"],"names":[],"mappings":";;;AAGA,SAAgB,aAAa;CACa,OAAA;AAM1C","debug_id":"6e165338-8aaa-542a-9b01-10e474658991"}
1
+ {"version":3,"file":"get-version-COv7hnzB.mjs","sources":["../src/get-version.ts"],"sourcesContent":["declare const CLI_VERSION: string | undefined;\ndeclare const CLI_GIT_SHA: string | undefined;\n\nexport function getVersion() {\n if (typeof CLI_VERSION !== \"undefined\") return CLI_VERSION;\n return (\n process.env.WORKSPACE_VERSION ||\n process.env.npm_package_version ||\n \"unknown\"\n );\n}\n\nexport function getGitHash() {\n if (typeof CLI_GIT_SHA !== \"undefined\") return CLI_GIT_SHA;\n return process.env.WORKSPACE_GIT_SHA || \"unknown\";\n}\n"],"names":[],"mappings":";;;AAGA,SAAgB,aAAa;CACa,OAAA;AAM1C","debug_id":"3e646aca-1e4c-5a06-a68e-5c5b4b70a985"}
@@ -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]="c6f2ee71-d822-5093-a934-f099d9cb905b")}catch(e){}}();
3
- import { t as getVersion } from "./get-version-C3ozwlOI.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]="f3e59e59-12df-52be-aa98-48749adc299d")}catch(e){}}();
3
+ import { t as getVersion } from "./get-version-COv7hnzB.mjs";
4
4
  import { s as readVetraRuntime } from "./vetra-instance-CzhYIjxL.mjs";
5
5
  import { a as vetraCommandFor, n as ensureVetra, r as restartVetra, t as VetraStartError } from "./vetra-launch-qi10Unax.mjs";
6
6
  import { resolveSwitchboardPortDefault } from "@powerhousedao/shared/clis/args";
@@ -259,5 +259,5 @@ async function startMcpLauncher(options) {
259
259
  //#endregion
260
260
  export { startMcpLauncher };
261
261
 
262
- //# sourceMappingURL=mcp-4VkYD_JF.mjs.map
263
- //# debugId=c6f2ee71-d822-5093-a934-f099d9cb905b
262
+ //# sourceMappingURL=mcp-CLxrbUT1.mjs.map
263
+ //# debugId=f3e59e59-12df-52be-aa98-48749adc299d
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-4VkYD_JF.mjs","sources":["../src/services/mcp.ts"],"sourcesContent":["import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPError,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n CallToolRequestSchema,\n CallToolResultSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ListToolsRequestSchema,\n McpError,\n ReadResourceRequestSchema,\n type CallToolRequest,\n type CallToolResult,\n type Tool,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { createServer } from \"@powerhousedao/reactor-mcp\";\nimport { resolveSwitchboardPortDefault } from \"@powerhousedao/shared/clis/args\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getVersion } from \"../get-version.js\";\nimport {\n ensureVetra,\n restartVetra,\n vetraCommandFor,\n VetraStartError,\n type EnsureVetraOptions,\n type VetraCommand,\n} from \"../utils/vetra-launch.js\";\nimport {\n readVetraRuntime,\n type VetraRuntimeRecord,\n} from \"../utils/vetra-runtime.js\";\n\nconst CALL_TIMEOUT_MS = 10 * 60_000;\nconst CONFIG_FILE = \"powerhouse.config.json\";\n\nexport type McpLauncherOptions = {\n projectDir?: string;\n startTimeoutSeconds: number;\n /** Test seam: what starts Vetra; defaults to {@link vetraCommandFor}. */\n vetraCommand?: VetraCommand;\n};\n\n/** The nearest directory at or above `start` holding powerhouse.config.json. */\nexport function findProjectDir(start: string): string | undefined {\n let dir = path.resolve(start);\n for (;;) {\n if (fs.existsSync(path.join(dir, CONFIG_FILE))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\n// The tool list never touches the reactor, so a client that throws on use is enough.\nconst reactorlessClient = new Proxy({} as IReactorClient, {\n get(_target, property) {\n if (property === \"then\") return undefined;\n return () => {\n throw new Error(\"reactor-mcp's local tool list has no reactor\");\n };\n },\n});\n\n/** reactor-mcp's own server, in-process, for the tool list and resources. */\nasync function connectLocalReactorMcp(): Promise<Client> {\n const server = await createServer({ client: reactorlessClient });\n const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();\n await server.connect(serverSide);\n const client = new Client({ name: \"ph-mcp\", version: getVersion() });\n await client.connect(clientSide);\n return client;\n}\n\nfunction toolError(message: string): CallToolResult {\n return { isError: true, content: [{ type: \"text\", text: message }] };\n}\n\n/** The call never reached a live session: Vetra is down, or restarted since. */\nfunction isStaleConnection(error: unknown): boolean {\n if (error instanceof StreamableHTTPError) {\n return error.code === 404 || error.code === 400;\n }\n for (let e = error; e instanceof Error; e = e.cause) {\n if ((e as NodeJS.ErrnoException).code === \"ECONNREFUSED\") return true;\n }\n return false;\n}\n\nexport const RESTART_VETRA_TOOL = \"restartVetra\";\n\nconst restartVetraTool: Tool = {\n name: RESTART_VETRA_TOOL,\n description:\n \"Restart this project's Vetra (its Switchboard and Studio) and wait until it is ready. \" +\n \"Use it after a change Vetra reads only at startup, such as the reactor or packages settings \" +\n \"in powerhouse.config.json; Studio restarts by itself for connect.* changes. \" +\n \"Returns the new Connect, Switchboard and MCP URLs.\",\n inputSchema: { type: \"object\", properties: {} },\n outputSchema: {\n type: \"object\",\n properties: {\n pid: { type: \"number\" },\n connectUrl: { type: \"string\" },\n switchboardUrl: { type: \"string\" },\n mcpUrl: { type: \"string\" },\n },\n required: [\"pid\", \"mcpUrl\"],\n },\n};\n\nfunction vetraUrls(record: VetraRuntimeRecord) {\n return {\n pid: record.pid,\n ...(record.connectUrl ? { connectUrl: record.connectUrl } : {}),\n switchboardUrl:\n record.switchboardUrl ??\n `http://localhost:${record.switchboardPort}/graphql`,\n mcpUrl: record.mcpUrl || `http://localhost:${record.switchboardPort}/mcp`,\n };\n}\n\nfunction projectName(projectDir: string): string | undefined {\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(projectDir, \"package.json\"), \"utf8\"),\n ) as { name?: string };\n return pkg.name;\n } catch {\n return undefined;\n }\n}\n\n/** Connects to the project's Vetra `/mcp`, starting Vetra when it is down. */\ntype Progress = (message: string) => void;\n\nclass Upstream {\n #client: Promise<Client> | undefined;\n /** The Vetra the client talks to; another pid in the record means it restarted. */\n #pid: number | undefined;\n /** The calls waiting on the connection, told how Vetra's start goes. */\n #waiting = new Set<Progress>();\n\n constructor(\n private readonly projectDir: string | undefined,\n private readonly options: McpLauncherOptions,\n ) {}\n\n get(onProgress?: Progress): Promise<Client> {\n if (this.#client && this.#pid !== undefined && this.projectDir) {\n const pid = readVetraRuntime(this.projectDir)?.pid;\n if (pid !== this.#pid) this.reset();\n }\n this.#client ??= this.#connect(ensureVetra).catch((error: unknown) => {\n this.#client = undefined;\n throw error;\n });\n return this.#waitWith(this.#client, onProgress);\n }\n\n async #waitWith<T>(task: Promise<T>, onProgress?: Progress): Promise<T> {\n if (onProgress) this.#waiting.add(onProgress);\n try {\n return await task;\n } finally {\n if (onProgress) this.#waiting.delete(onProgress);\n }\n }\n\n #report = (message: string) => {\n for (const progress of this.#waiting) progress(message);\n };\n\n reset(): void {\n const stale = this.#client;\n this.#client = undefined;\n this.#pid = undefined;\n void stale?.then((client) => client.close()).catch(() => {});\n }\n\n /** Restarts Vetra and connects to the new one; resolves to its record. */\n async restart(onProgress?: Progress): Promise<VetraRuntimeRecord> {\n this.reset();\n let record: VetraRuntimeRecord | undefined;\n const connected = this.#connect(async (options) => {\n record = await restartVetra(options);\n return record;\n });\n this.#client = connected.catch((error: unknown) => {\n this.#client = undefined;\n throw error;\n });\n await this.#waitWith(this.#client, onProgress);\n return record!;\n }\n\n async #connect(\n start: (options: EnsureVetraOptions) => Promise<VetraRuntimeRecord>,\n ): Promise<Client> {\n const { projectDir } = this;\n if (!projectDir) {\n throw new VetraStartError(\n `No Powerhouse project (${CONFIG_FILE}) at or above ${process.cwd()}. Run \\`ph mcp\\` inside the project, or pass --project-dir.`,\n );\n }\n const name = projectName(projectDir);\n if (!name) {\n throw new VetraStartError(`${projectDir} has no package.json name.`);\n }\n console.error(`[ph mcp] connecting to Vetra for ${name}...`);\n const record = await start({\n projectDir,\n projectName: name,\n switchboardPort: resolveSwitchboardPortDefault(),\n command: this.options.vetraCommand ?? vetraCommandFor(projectDir),\n timeoutMs: this.options.startTimeoutSeconds * 1000,\n onProgress: this.#report,\n });\n const { mcpUrl } = vetraUrls(record);\n const client = new Client({ name: \"ph-mcp\", version: getVersion() });\n await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl)));\n this.#pid = record.pid;\n console.error(`[ph mcp] forwarding tool calls to ${mcpUrl}`);\n return client;\n }\n}\n\nasync function forwardToolCall(\n upstream: Upstream,\n params: CallToolRequest[\"params\"],\n signal: AbortSignal,\n onProgress: Progress,\n): Promise<CallToolResult> {\n for (let attempt = 0; ; attempt++) {\n const client = await upstream.get(onProgress);\n try {\n return await client.request(\n { method: \"tools/call\", params },\n CallToolResultSchema,\n { signal, timeout: CALL_TIMEOUT_MS },\n );\n } catch (error) {\n // It never arrived: Vetra went away or restarted, so find or start it again.\n if (attempt > 0 || !isStaleConnection(error)) throw error;\n upstream.reset();\n }\n }\n}\n\n/** `ph mcp`: tools listed by in-process reactor-mcp, calls forwarded to Vetra (started on first call). */\nexport async function startMcpLauncher(options: McpLauncherOptions) {\n // stdout carries JSON-RPC only.\n console.log = console.error;\n console.info = console.error;\n\n const projectDir = findProjectDir(\n options.projectDir ?? process.env.PH_CALLER_CWD ?? process.cwd(),\n );\n // Port resolution and `ph vetra` both read the project from the cwd.\n if (projectDir) process.chdir(projectDir);\n\n const local = await connectLocalReactorMcp();\n const upstream = new Upstream(projectDir, options);\n const server = new Server(\n local.getServerVersion() ?? { name: \"reactor-mcp-server\", version: \"\" },\n {\n capabilities: { tools: {}, resources: {} },\n instructions: local.getInstructions(),\n },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async (request) => {\n const listed = await local.listTools(request.params);\n return { ...listed, tools: [...listed.tools, restartVetraTool] };\n });\n server.setRequestHandler(ListResourcesRequestSchema, (request) =>\n local.listResources(request.params),\n );\n server.setRequestHandler(ListResourceTemplatesRequestSchema, (request) =>\n local.listResourceTemplates(request.params),\n );\n server.setRequestHandler(ReadResourceRequestSchema, (request) =>\n local.readResource(request.params),\n );\n server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\n // How Vetra's start goes: progress notifications when the client asked, else stderr.\n const token = request.params._meta?.progressToken;\n let progress = 0;\n const onProgress: Progress = (message) => {\n if (token === undefined) {\n console.error(`[ph mcp] ${message}`);\n return;\n }\n void extra\n .sendNotification({\n method: \"notifications/progress\",\n params: { progressToken: token, progress: ++progress, message },\n })\n .catch(() => {});\n };\n try {\n if (request.params.name === RESTART_VETRA_TOOL) {\n const urls = vetraUrls(await upstream.restart(onProgress));\n return {\n content: [{ type: \"text\", text: JSON.stringify(urls) }],\n structuredContent: urls,\n };\n }\n return await forwardToolCall(\n upstream,\n request.params,\n extra.signal,\n onProgress,\n );\n } catch (error) {\n // Protocol errors from reactor-mcp reach the agent as they would over HTTP.\n if (error instanceof McpError) throw error;\n const message = error instanceof Error ? error.message : String(error);\n return toolError(\n error instanceof VetraStartError\n ? message\n : `reactor-mcp request failed: ${message}`,\n );\n }\n });\n\n const transport = new StdioServerTransport();\n transport.onclose = () => process.exit(0);\n process.stdin.once(\"end\", () => process.exit(0));\n await server.connect(transport);\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAuCA,MAAM,kBAAkB;AACxB,MAAM,cAAc;;AAUpB,SAAgB,eAAe,OAAmC;CAChE,IAAI,MAAM,KAAK,QAAQ,KAAK;CAC5B,SAAS;EACP,IAAI,GAAG,WAAW,KAAK,KAAK,KAAK,WAAW,CAAC,GAAG,OAAO;EACvD,MAAM,SAAS,KAAK,QAAQ,GAAG;EAC/B,IAAI,WAAW,KAAK,OAAO,KAAA;EAC3B,MAAM;CACR;AACF;AAGA,MAAM,oBAAoB,IAAI,MAAM,CAAC,GAAqB,EACxD,IAAI,SAAS,UAAU;CACrB,IAAI,aAAa,QAAQ,OAAO,KAAA;CAChC,aAAa;EACX,MAAM,IAAI,MAAM,8CAA8C;CAChE;AACF,EACF,CAAC;;AAGD,eAAe,yBAA0C;CACvD,MAAM,SAAS,MAAM,aAAa,EAAE,QAAQ,kBAAkB,CAAC;CAC/D,MAAM,CAAC,YAAY,cAAc,kBAAkB,iBAAiB;CACpE,MAAM,OAAO,QAAQ,UAAU;CAC/B,MAAM,SAAS,IAAI,OAAO;EAAE,MAAM;EAAU,SAAS,WAAW;CAAE,CAAC;CACnE,MAAM,OAAO,QAAQ,UAAU;CAC/B,OAAO;AACT;AAEA,SAAS,UAAU,SAAiC;CAClD,OAAO;EAAE,SAAS;EAAM,SAAS,CAAC;GAAE,MAAM;GAAQ,MAAM;EAAQ,CAAC;CAAE;AACrE;;AAGA,SAAS,kBAAkB,OAAyB;CAClD,IAAI,iBAAiB,qBACnB,OAAO,MAAM,SAAS,OAAO,MAAM,SAAS;CAE9C,KAAK,IAAI,IAAI,OAAO,aAAa,OAAO,IAAI,EAAE,OAC5C,IAAK,EAA4B,SAAS,gBAA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A4B,YACnD,MAAM,aAAa,QAAQ,MAAM,CACnC;CACA,OAAO,kBAAkB,uBAAuB,OAAO,SAAS,UAAU;EAExE,MAAM,QAAQ,QAAQ,OAAO,OAAO;EACpC,IAAI,WAAW;EACf,MAAM,cAAwB,YAAY;GACxC,IAAI,UAAU,KAAA,GAAW;IACvB,QAAQ,MAAM,YAAY,SAAS;IACnC;GACF;GACA,MACG,iBAAiB;IAChB,QAAQ;IACR,QAAQ;KAAE,eAAe;KAAO,UAAU,EAAE;KAAU;IAAQ;GAChE,CAAC,CAAC,CACD,YAAY,CAAC,CAAC;EACnB;EACA,IAAI;GACF,IAAI,QAAQ,OAAO,SAAA,gBAA6B;IAC9C,MAAM,OAAO,UAAU,MAAM,SAAS,QAAQ,UAAU,CAAC;IACzD,OAAO;KACL,SAAS,CAAC;MAAE,MAAM;MAAQ,MAAM,KAAK,UAAU,IAAI;KAAE,CAAC;KACtD,mBAAmB;IACrB;GACF;GACA,OAAO,MAAM,gBACX,UACA,QAAQ,QACR,MAAM,QACN,UACF;EACF,SAAS,OAAO;GAEd,IAAI,iBAAiB,UAAU,MAAM;GACrC,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACrE,OAAO,UACL,iBAAiB,kBACb,UACA,+BAA+B,SACrC;EACF;CACF,CAAC;CAED,MAAM,YAAY,IAAI,qBAAqB;CAC3C,UAAU,gBAAgB,QAAQ,KAAK,CAAC;CACxC,QAAQ,MAAM,KAAK,aAAa,QAAQ,KAAK,CAAC,CAAC;CAC/C,MAAM,OAAO,QAAQ,SAAS;AAChC","debug_id":"c6f2ee71-d822-5093-a934-f099d9cb905b"}
1
+ {"version":3,"file":"mcp-CLxrbUT1.mjs","sources":["../src/services/mcp.ts"],"sourcesContent":["import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPError,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n CallToolRequestSchema,\n CallToolResultSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ListToolsRequestSchema,\n McpError,\n ReadResourceRequestSchema,\n type CallToolRequest,\n type CallToolResult,\n type Tool,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { createServer } from \"@powerhousedao/reactor-mcp\";\nimport { resolveSwitchboardPortDefault } from \"@powerhousedao/shared/clis/args\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getVersion } from \"../get-version.js\";\nimport {\n ensureVetra,\n restartVetra,\n vetraCommandFor,\n VetraStartError,\n type EnsureVetraOptions,\n type VetraCommand,\n} from \"../utils/vetra-launch.js\";\nimport {\n readVetraRuntime,\n type VetraRuntimeRecord,\n} from \"../utils/vetra-runtime.js\";\n\nconst CALL_TIMEOUT_MS = 10 * 60_000;\nconst CONFIG_FILE = \"powerhouse.config.json\";\n\nexport type McpLauncherOptions = {\n projectDir?: string;\n startTimeoutSeconds: number;\n /** Test seam: what starts Vetra; defaults to {@link vetraCommandFor}. */\n vetraCommand?: VetraCommand;\n};\n\n/** The nearest directory at or above `start` holding powerhouse.config.json. */\nexport function findProjectDir(start: string): string | undefined {\n let dir = path.resolve(start);\n for (;;) {\n if (fs.existsSync(path.join(dir, CONFIG_FILE))) return dir;\n const parent = path.dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\n// The tool list never touches the reactor, so a client that throws on use is enough.\nconst reactorlessClient = new Proxy({} as IReactorClient, {\n get(_target, property) {\n if (property === \"then\") return undefined;\n return () => {\n throw new Error(\"reactor-mcp's local tool list has no reactor\");\n };\n },\n});\n\n/** reactor-mcp's own server, in-process, for the tool list and resources. */\nasync function connectLocalReactorMcp(): Promise<Client> {\n const server = await createServer({ client: reactorlessClient });\n const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();\n await server.connect(serverSide);\n const client = new Client({ name: \"ph-mcp\", version: getVersion() });\n await client.connect(clientSide);\n return client;\n}\n\nfunction toolError(message: string): CallToolResult {\n return { isError: true, content: [{ type: \"text\", text: message }] };\n}\n\n/** The call never reached a live session: Vetra is down, or restarted since. */\nfunction isStaleConnection(error: unknown): boolean {\n if (error instanceof StreamableHTTPError) {\n return error.code === 404 || error.code === 400;\n }\n for (let e = error; e instanceof Error; e = e.cause) {\n if ((e as NodeJS.ErrnoException).code === \"ECONNREFUSED\") return true;\n }\n return false;\n}\n\nexport const RESTART_VETRA_TOOL = \"restartVetra\";\n\nconst restartVetraTool: Tool = {\n name: RESTART_VETRA_TOOL,\n description:\n \"Restart this project's Vetra (its Switchboard and Studio) and wait until it is ready. \" +\n \"Use it after a change Vetra reads only at startup, such as the reactor or packages settings \" +\n \"in powerhouse.config.json; Studio restarts by itself for connect.* changes. \" +\n \"Returns the new Connect, Switchboard and MCP URLs.\",\n inputSchema: { type: \"object\", properties: {} },\n outputSchema: {\n type: \"object\",\n properties: {\n pid: { type: \"number\" },\n connectUrl: { type: \"string\" },\n switchboardUrl: { type: \"string\" },\n mcpUrl: { type: \"string\" },\n },\n required: [\"pid\", \"mcpUrl\"],\n },\n};\n\nfunction vetraUrls(record: VetraRuntimeRecord) {\n return {\n pid: record.pid,\n ...(record.connectUrl ? { connectUrl: record.connectUrl } : {}),\n switchboardUrl:\n record.switchboardUrl ??\n `http://localhost:${record.switchboardPort}/graphql`,\n mcpUrl: record.mcpUrl || `http://localhost:${record.switchboardPort}/mcp`,\n };\n}\n\nfunction projectName(projectDir: string): string | undefined {\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(projectDir, \"package.json\"), \"utf8\"),\n ) as { name?: string };\n return pkg.name;\n } catch {\n return undefined;\n }\n}\n\n/** Connects to the project's Vetra `/mcp`, starting Vetra when it is down. */\ntype Progress = (message: string) => void;\n\nclass Upstream {\n #client: Promise<Client> | undefined;\n /** The Vetra the client talks to; another pid in the record means it restarted. */\n #pid: number | undefined;\n /** The calls waiting on the connection, told how Vetra's start goes. */\n #waiting = new Set<Progress>();\n\n constructor(\n private readonly projectDir: string | undefined,\n private readonly options: McpLauncherOptions,\n ) {}\n\n get(onProgress?: Progress): Promise<Client> {\n if (this.#client && this.#pid !== undefined && this.projectDir) {\n const pid = readVetraRuntime(this.projectDir)?.pid;\n if (pid !== this.#pid) this.reset();\n }\n this.#client ??= this.#connect(ensureVetra).catch((error: unknown) => {\n this.#client = undefined;\n throw error;\n });\n return this.#waitWith(this.#client, onProgress);\n }\n\n async #waitWith<T>(task: Promise<T>, onProgress?: Progress): Promise<T> {\n if (onProgress) this.#waiting.add(onProgress);\n try {\n return await task;\n } finally {\n if (onProgress) this.#waiting.delete(onProgress);\n }\n }\n\n #report = (message: string) => {\n for (const progress of this.#waiting) progress(message);\n };\n\n reset(): void {\n const stale = this.#client;\n this.#client = undefined;\n this.#pid = undefined;\n void stale?.then((client) => client.close()).catch(() => {});\n }\n\n /** Restarts Vetra and connects to the new one; resolves to its record. */\n async restart(onProgress?: Progress): Promise<VetraRuntimeRecord> {\n this.reset();\n let record: VetraRuntimeRecord | undefined;\n const connected = this.#connect(async (options) => {\n record = await restartVetra(options);\n return record;\n });\n this.#client = connected.catch((error: unknown) => {\n this.#client = undefined;\n throw error;\n });\n await this.#waitWith(this.#client, onProgress);\n return record!;\n }\n\n async #connect(\n start: (options: EnsureVetraOptions) => Promise<VetraRuntimeRecord>,\n ): Promise<Client> {\n const { projectDir } = this;\n if (!projectDir) {\n throw new VetraStartError(\n `No Powerhouse project (${CONFIG_FILE}) at or above ${process.cwd()}. Run \\`ph mcp\\` inside the project, or pass --project-dir.`,\n );\n }\n const name = projectName(projectDir);\n if (!name) {\n throw new VetraStartError(`${projectDir} has no package.json name.`);\n }\n console.error(`[ph mcp] connecting to Vetra for ${name}...`);\n const record = await start({\n projectDir,\n projectName: name,\n switchboardPort: resolveSwitchboardPortDefault(),\n command: this.options.vetraCommand ?? vetraCommandFor(projectDir),\n timeoutMs: this.options.startTimeoutSeconds * 1000,\n onProgress: this.#report,\n });\n const { mcpUrl } = vetraUrls(record);\n const client = new Client({ name: \"ph-mcp\", version: getVersion() });\n await client.connect(new StreamableHTTPClientTransport(new URL(mcpUrl)));\n this.#pid = record.pid;\n console.error(`[ph mcp] forwarding tool calls to ${mcpUrl}`);\n return client;\n }\n}\n\nasync function forwardToolCall(\n upstream: Upstream,\n params: CallToolRequest[\"params\"],\n signal: AbortSignal,\n onProgress: Progress,\n): Promise<CallToolResult> {\n for (let attempt = 0; ; attempt++) {\n const client = await upstream.get(onProgress);\n try {\n return await client.request(\n { method: \"tools/call\", params },\n CallToolResultSchema,\n { signal, timeout: CALL_TIMEOUT_MS },\n );\n } catch (error) {\n // It never arrived: Vetra went away or restarted, so find or start it again.\n if (attempt > 0 || !isStaleConnection(error)) throw error;\n upstream.reset();\n }\n }\n}\n\n/** `ph mcp`: tools listed by in-process reactor-mcp, calls forwarded to Vetra (started on first call). */\nexport async function startMcpLauncher(options: McpLauncherOptions) {\n // stdout carries JSON-RPC only.\n console.log = console.error;\n console.info = console.error;\n\n const projectDir = findProjectDir(\n options.projectDir ?? process.env.PH_CALLER_CWD ?? process.cwd(),\n );\n // Port resolution and `ph vetra` both read the project from the cwd.\n if (projectDir) process.chdir(projectDir);\n\n const local = await connectLocalReactorMcp();\n const upstream = new Upstream(projectDir, options);\n const server = new Server(\n local.getServerVersion() ?? { name: \"reactor-mcp-server\", version: \"\" },\n {\n capabilities: { tools: {}, resources: {} },\n instructions: local.getInstructions(),\n },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async (request) => {\n const listed = await local.listTools(request.params);\n return { ...listed, tools: [...listed.tools, restartVetraTool] };\n });\n server.setRequestHandler(ListResourcesRequestSchema, (request) =>\n local.listResources(request.params),\n );\n server.setRequestHandler(ListResourceTemplatesRequestSchema, (request) =>\n local.listResourceTemplates(request.params),\n );\n server.setRequestHandler(ReadResourceRequestSchema, (request) =>\n local.readResource(request.params),\n );\n server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\n // How Vetra's start goes: progress notifications when the client asked, else stderr.\n const token = request.params._meta?.progressToken;\n let progress = 0;\n const onProgress: Progress = (message) => {\n if (token === undefined) {\n console.error(`[ph mcp] ${message}`);\n return;\n }\n void extra\n .sendNotification({\n method: \"notifications/progress\",\n params: { progressToken: token, progress: ++progress, message },\n })\n .catch(() => {});\n };\n try {\n if (request.params.name === RESTART_VETRA_TOOL) {\n const urls = vetraUrls(await upstream.restart(onProgress));\n return {\n content: [{ type: \"text\", text: JSON.stringify(urls) }],\n structuredContent: urls,\n };\n }\n return await forwardToolCall(\n upstream,\n request.params,\n extra.signal,\n onProgress,\n );\n } catch (error) {\n // Protocol errors from reactor-mcp reach the agent as they would over HTTP.\n if (error instanceof McpError) throw error;\n const message = error instanceof Error ? error.message : String(error);\n return toolError(\n error instanceof VetraStartError\n ? message\n : `reactor-mcp request failed: ${message}`,\n );\n }\n });\n\n const transport = new StdioServerTransport();\n transport.onclose = () => process.exit(0);\n process.stdin.once(\"end\", () => process.exit(0));\n await server.connect(transport);\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAuCA,MAAM,kBAAkB;AACxB,MAAM,cAAc;;AAUpB,SAAgB,eAAe,OAAmC;CAChE,IAAI,MAAM,KAAK,QAAQ,KAAK;CAC5B,SAAS;EACP,IAAI,GAAG,WAAW,KAAK,KAAK,KAAK,WAAW,CAAC,GAAG,OAAO;EACvD,MAAM,SAAS,KAAK,QAAQ,GAAG;EAC/B,IAAI,WAAW,KAAK,OAAO,KAAA;EAC3B,MAAM;CACR;AACF;AAGA,MAAM,oBAAoB,IAAI,MAAM,CAAC,GAAqB,EACxD,IAAI,SAAS,UAAU;CACrB,IAAI,aAAa,QAAQ,OAAO,KAAA;CAChC,aAAa;EACX,MAAM,IAAI,MAAM,8CAA8C;CACh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QACN,UACF;EACF,SAAS,OAAO;GAEd,IAAI,iBAAiB,UAAU,MAAM;GACrC,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACrE,OAAO,UACL,iBAAiB,kBACb,UACA,+BAA+B,SACrC;EACF;CACF,CAAC;CAED,MAAM,YAAY,IAAI,qBAAqB;CAC3C,UAAU,gBAAgB,QAAQ,KAAK,CAAC;CACxC,QAAQ,MAAM,KAAK,aAAa,QAAQ,KAAK,CAAC,CAAC;CAC/C,MAAM,OAAO,QAAQ,SAAS;AAChC","debug_id":"f3e59e59-12df-52be-aa98-48749adc299d"}
@@ -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]="b6f29ae3-a4e2-58c6-af18-ca6b562f30c7")}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]="f78331b4-4fef-5a75-8cde-e77319b7a8ee")}catch(e){}}();
3
3
  import { c as isPowerhouseProject, i as findNodeProjectRoot } from "./utils-9KyRM0mf.mjs";
4
- import { n as unifiedDiff } from "./migrate-subgraphs-DWnMMl4X.mjs";
4
+ import { n as unifiedDiff } from "./migrate-subgraphs-B38Bh800.mjs";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { dirname, join, relative } from "node:path";
7
7
  import { execSync } from "node:child_process";
@@ -204,5 +204,5 @@ async function startMigrate({ versionPositional, version, force, debug, dryRun }
204
204
  //#endregion
205
205
  export { startMigrate };
206
206
 
207
- //# sourceMappingURL=migrate-HIHQdxMV.mjs.map
208
- //# debugId=b6f29ae3-a4e2-58c6-af18-ca6b562f30c7
207
+ //# sourceMappingURL=migrate-DufFMK7_.mjs.map
208
+ //# debugId=f78331b4-4fef-5a75-8cde-e77319b7a8ee
@@ -1 +1 @@
1
- {"version":3,"file":"migrate-HIHQdxMV.mjs","sources":["../src/services/migrate.ts"],"sourcesContent":["import {\n fetchPackageVersionFromNpmRegistry,\n injectPnpmAllowBuilds,\n spawnAsync,\n} from \"@powerhousedao/shared/clis\";\nimport { ALL_POWERHOUSE_DEPENDENCIES } from \"@powerhousedao/shared/constants\";\nimport { execSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join, relative } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { detect, resolveCommand } from \"package-manager-detector\";\nimport { compare, minVersion, prerelease, rcompare, valid } from \"semver\";\nimport type { MigrateArgs } from \"../types.js\";\nimport { findNodeProjectRoot, isPowerhouseProject } from \"../utils.js\";\nimport { unifiedDiff } from \"./migrate-subgraphs.js\";\n\n// Dist-tags a prerelease version can name its channel by.\nconst PRERELEASE_TAGS = [\"dev\", \"staging\", \"rc\"];\n\n// Set on the re-executed migrate, so the version check runs once.\nconst VERSION_CHECKED_ENV = \"PH_MIGRATE_VERSION_CHECKED\";\n\ntype ProjectPackageJson = Partial<\n Record<\n \"dependencies\" | \"devDependencies\" | \"peerDependencies\",\n Record<string, string>\n >\n>;\n\nfunction readProjectPackageJson(projectDir: string): ProjectPackageJson {\n try {\n return JSON.parse(\n readFileSync(join(projectDir, \"package.json\"), \"utf8\"),\n ) as ProjectPackageJson;\n } catch {\n return {};\n }\n}\n\n/** The newest Powerhouse package version the project's package.json pins */\nexport function newestPowerhouseVersion(packageJson: ProjectPackageJson) {\n const pinned = [\n packageJson.dependencies,\n packageJson.devDependencies,\n packageJson.peerDependencies,\n ].flatMap((deps) =>\n Object.entries(deps ?? {}).flatMap(([name, range]) => {\n if (!ALL_POWERHOUSE_DEPENDENCIES.includes(name)) return [];\n try {\n const version = minVersion(range)?.version;\n return version ? [{ name, version }] : [];\n } catch {\n // workspace:, catalog: and other non-semver specifiers\n return [];\n }\n }),\n );\n return pinned.sort((a, b) => rcompare(a.version, b.version)).at(0);\n}\n\n/** The dist-tag of the channel the project is on, and why */\nexport function inferReleaseTag(packageJson: ProjectPackageJson): {\n tag: string;\n reason: string;\n} {\n const newest = newestPowerhouseVersion(packageJson);\n if (!newest) {\n return { tag: \"latest\", reason: \"no Powerhouse package version is pinned\" };\n }\n const channel = prerelease(newest.version)?.[0];\n const pinned = `${newest.name}@${newest.version}`;\n if (typeof channel === \"string\" && PRERELEASE_TAGS.includes(channel)) {\n return { tag: channel, reason: `the project is on ${pinned}` };\n }\n return {\n tag: \"latest\",\n reason: `the project is on ${pinned}, ${channel === undefined ? \"a stable release\" : \"not on a dev, staging or rc channel\"}`,\n };\n}\n\n/** Whether `target` is an older release than `installed`: lower by semver, or\n * published earlier (6.2.3 ranks above 6.2.3-dev.49 but can predate it). */\nexport function isOlderRelease(\n installed: string,\n target: string,\n publishTimes: Partial<Record<string, string>> = {},\n): boolean {\n if (!valid(installed) || !valid(target)) return false;\n if (compare(target, installed) < 0) return true;\n const installedAt = publishTimes[installed];\n const targetAt = publishTimes[target];\n if (!installedAt || !targetAt) return false;\n return Date.parse(targetAt) < Date.parse(installedAt);\n}\n\nasync function fetchPublishTimes(\n packageName: string,\n): Promise<Partial<Record<string, string>>> {\n try {\n return JSON.parse(\n await spawnAsync(\"npm\", [\"view\", packageName, \"time\", \"--json\"]),\n ) as Partial<Record<string, string>>;\n } catch {\n return {};\n }\n}\n\nasync function warnIfOlderRelease(\n packageJson: ProjectPackageJson,\n targetVersion: string,\n) {\n const newest = newestPowerhouseVersion(packageJson);\n if (!newest) return;\n const publishTimes = await fetchPublishTimes(\"@powerhousedao/ph-cli\");\n if (!isOlderRelease(newest.version, targetVersion, publishTimes)) return;\n console.warn(\n `⚠ ${targetVersion} is an older release than the installed ${newest.name}@${newest.version}; migrating moves the project back. Pass a version or tag (e.g. \\`ph migrate dev\\`) to stay on yours.`,\n );\n}\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\ntype FileChange = {\n path: string;\n before: string | undefined;\n after: string | undefined;\n};\n\n/** What a dry run prints: one unified diff per file, paths relative to the\n * project, a deleted file against /dev/null. */\nexport function dryRunReport(\n projectDir: string,\n result: { changes: readonly FileChange[]; notRun: readonly string[] },\n): string {\n const diffs = result.changes.map(({ path, before, after }) => {\n const file = relative(projectDir, path).replaceAll(\"\\\\\", \"/\");\n if (after === undefined) {\n const removed = `--- a/${file}\\n+++ /dev/null\\n`;\n const diff = unifiedDiff({ path: file, before: before ?? \"\", after: \"\" });\n // An empty file has no lines to show.\n return diff === \"\"\n ? removed\n : diff.replace(`--- a/${file}\\n+++ b/${file}\\n`, removed);\n }\n // An added empty file has no lines either.\n return (\n unifiedDiff({ path: file, before: before ?? null, after }) ||\n `--- /dev/null\\n+++ b/${file}\\n`\n );\n });\n const notRun =\n result.notRun.length > 0\n ? `Not previewed; a real run would also:\\n${result.notRun.map((step) => ` - ${step}\\n`).join(\"\")}`\n : \"\";\n if (diffs.length === 0) {\n return `ph migrate would change no file.\\n${notRun}`;\n }\n return `${diffs.join(\"\")}ph migrate would write ${diffs.length} file(s); nothing was written.\\n${notRun}`;\n}\n\nexport async function startMigrate({\n versionPositional,\n version,\n force,\n debug,\n dryRun,\n}: MigrateArgs) {\n // The project is where powerhouse.config.json is: the command also runs\n // from a sub-folder, and from a package of a monorepo.\n const projectDir =\n findNodeProjectRoot(process.cwd(), isPowerhouseProject) ?? process.cwd();\n if (debug) console.log(`[migrate] project directory: ${projectDir}`);\n const packageJson = readProjectPackageJson(projectDir);\n let requested = versionPositional ?? version;\n if (requested === undefined) {\n const inferred = inferReleaseTag(packageJson);\n requested = inferred.tag;\n console.log(\n `No version given; migrating to \"${inferred.tag}\" because ${inferred.reason}.`,\n );\n }\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 if (targetVersion && !process.env[VERSION_CHECKED_ENV]) {\n await warnIfOlderRelease(packageJson, targetVersion);\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 const result = await codegenMod.migrate(\n targetVersion ?? requested,\n projectDir,\n { dryRun: Boolean(dryRun) },\n );\n if (dryRun) process.stdout.write(dryRunReport(projectDir, result));\n return;\n }\n\n const agent = (await detect({ cwd: projectDir }))?.agent ?? \"npm\";\n const resolved = resolveCommand(agent, \"execute\", [\n `@powerhousedao/ph-cli@${targetVersion}`,\n \"migrate\",\n \"--version\",\n targetVersion,\n ...(dryRun ? [\"--dry-run\"] : []),\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, {\n cwd: projectDir,\n stdio: \"inherit\",\n env: { ...process.env, [VERSION_CHECKED_ENV]: \"1\" },\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;AAiBA,MAAM,kBAAkB;CAAC;CAAO;CAAW;AAAI;AAG/C,MAAM,sBAAsB;AAS5B,SAAS,uBAAuB,YAAwC;CACtE,IAAI;EACF,OAAO,KAAK,MACV,aAAa,KAAK,YAAY,cAAc,GAAG,MAAM,CACvD;CACF,QAAQ;EACN,OAAO,CAAC;CACV;AACF;;AAGA,SAAgB,wBAAwB,aAAiC;CAiBvE,OAhBe;EACb,YAAY;EACZ,YAAY;EACZ,YAAY;CACd,CAAC,CAAC,SAAS,SACT,OAAO,QAAQ,QAAQ,CAAC,CAAC,CAAC,CA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K7_.mjs","sources":["../src/services/migrate.ts"],"sourcesContent":["import {\n fetchPackageVersionFromNpmRegistry,\n injectPnpmAllowBuilds,\n spawnAsync,\n} from \"@powerhousedao/shared/clis\";\nimport { ALL_POWERHOUSE_DEPENDENCIES } from \"@powerhousedao/shared/constants\";\nimport { execSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join, relative } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { detect, resolveCommand } from \"package-manager-detector\";\nimport { compare, minVersion, prerelease, rcompare, valid } from \"semver\";\nimport type { MigrateArgs } from \"../types.js\";\nimport { findNodeProjectRoot, isPowerhouseProject } from \"../utils.js\";\nimport { unifiedDiff } from \"./migrate-subgraphs.js\";\n\n// Dist-tags a prerelease version can name its channel by.\nconst PRERELEASE_TAGS = [\"dev\", \"staging\", \"rc\"];\n\n// Set on the re-executed migrate, so the version check runs once.\nconst VERSION_CHECKED_ENV = \"PH_MIGRATE_VERSION_CHECKED\";\n\ntype ProjectPackageJson = Partial<\n Record<\n \"dependencies\" | \"devDependencies\" | \"peerDependencies\",\n Record<string, string>\n >\n>;\n\nfunction readProjectPackageJson(projectDir: string): ProjectPackageJson {\n try {\n return JSON.parse(\n readFileSync(join(projectDir, \"package.json\"), \"utf8\"),\n ) as ProjectPackageJson;\n } catch {\n return {};\n }\n}\n\n/** The newest Powerhouse package version the project's package.json pins */\nexport function newestPowerhouseVersion(packageJson: ProjectPackageJson) {\n const pinned = [\n packageJson.dependencies,\n packageJson.devDependencies,\n packageJson.peerDependencies,\n ].flatMap((deps) =>\n Object.entries(deps ?? {}).flatMap(([name, range]) => {\n if (!ALL_POWERHOUSE_DEPENDENCIES.includes(name)) return [];\n try {\n const version = minVersion(range)?.version;\n return version ? [{ name, version }] : [];\n } catch {\n // workspace:, catalog: and other non-semver specifiers\n return [];\n }\n }),\n );\n return pinned.sort((a, b) => rcompare(a.version, b.version)).at(0);\n}\n\n/** The dist-tag of the channel the project is on, and why */\nexport function inferReleaseTag(packageJson: ProjectPackageJson): {\n tag: string;\n reason: string;\n} {\n const newest = newestPowerhouseVersion(packageJson);\n if (!newest) {\n return { tag: \"latest\", reason: \"no Powerhouse package version is pinned\" };\n }\n const channel = prerelease(newest.version)?.[0];\n const pinned = `${newest.name}@${newest.version}`;\n if (typeof channel === \"string\" && PRERELEASE_TAGS.includes(channel)) {\n return { tag: channel, reason: `the project is on ${pinned}` };\n }\n return {\n tag: \"latest\",\n reason: `the project is on ${pinned}, ${channel === undefined ? \"a stable release\" : \"not on a dev, staging or rc channel\"}`,\n };\n}\n\n/** Whether `target` is an older release than `installed`: lower by semver, or\n * published earlier (6.2.3 ranks above 6.2.3-dev.49 but can predate it). */\nexport function isOlderRelease(\n installed: string,\n target: string,\n publishTimes: Partial<Record<string, string>> = {},\n): boolean {\n if (!valid(installed) || !valid(target)) return false;\n if (compare(target, installed) < 0) return true;\n const installedAt = publishTimes[installed];\n const targetAt = publishTimes[target];\n if (!installedAt || !targetAt) return false;\n return Date.parse(targetAt) < Date.parse(installedAt);\n}\n\nasync function fetchPublishTimes(\n packageName: string,\n): Promise<Partial<Record<string, string>>> {\n try {\n return JSON.parse(\n await spawnAsync(\"npm\", [\"view\", packageName, \"time\", \"--json\"]),\n ) as Partial<Record<string, string>>;\n } catch {\n return {};\n }\n}\n\nasync function warnIfOlderRelease(\n packageJson: ProjectPackageJson,\n targetVersion: string,\n) {\n const newest = newestPowerhouseVersion(packageJson);\n if (!newest) return;\n const publishTimes = await fetchPublishTimes(\"@powerhousedao/ph-cli\");\n if (!isOlderRelease(newest.version, targetVersion, publishTimes)) return;\n console.warn(\n `⚠ ${targetVersion} is an older release than the installed ${newest.name}@${newest.version}; migrating moves the project back. Pass a version or tag (e.g. \\`ph migrate dev\\`) to stay on yours.`,\n );\n}\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\ntype FileChange = {\n path: string;\n before: string | undefined;\n after: string | undefined;\n};\n\n/** What a dry run prints: one unified diff per file, paths relative to the\n * project, a deleted file against /dev/null. */\nexport function dryRunReport(\n projectDir: string,\n result: { changes: readonly FileChange[]; notRun: readonly string[] },\n): string {\n const diffs = result.changes.map(({ path, before, after }) => {\n const file = relative(projectDir, path).replaceAll(\"\\\\\", \"/\");\n if (after === undefined) {\n const removed = `--- a/${file}\\n+++ /dev/null\\n`;\n const diff = unifiedDiff({ path: file, before: before ?? \"\", after: \"\" });\n // An empty file has no lines to show.\n return diff === \"\"\n ? removed\n : diff.replace(`--- a/${file}\\n+++ b/${file}\\n`, removed);\n }\n // An added empty file has no lines either.\n return (\n unifiedDiff({ path: file, before: before ?? null, after }) ||\n `--- /dev/null\\n+++ b/${file}\\n`\n );\n });\n const notRun =\n result.notRun.length > 0\n ? `Not previewed; a real run would also:\\n${result.notRun.map((step) => ` - ${step}\\n`).join(\"\")}`\n : \"\";\n if (diffs.length === 0) {\n return `ph migrate would change no file.\\n${notRun}`;\n }\n return `${diffs.join(\"\")}ph migrate would write ${diffs.length} file(s); nothing was written.\\n${notRun}`;\n}\n\nexport async function startMigrate({\n versionPositional,\n version,\n force,\n debug,\n dryRun,\n}: MigrateArgs) {\n // The project is where powerhouse.config.json is: the command also runs\n // from a sub-folder, and from a package of a monorepo.\n const projectDir =\n findNodeProjectRoot(process.cwd(), isPowerhouseProject) ?? process.cwd();\n if (debug) console.log(`[migrate] project directory: ${projectDir}`);\n const packageJson = readProjectPackageJson(projectDir);\n let requested = versionPositional ?? version;\n if (requested === undefined) {\n const inferred = inferReleaseTag(packageJson);\n requested = inferred.tag;\n console.log(\n `No version given; migrating to \"${inferred.tag}\" because ${inferred.reason}.`,\n );\n }\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 if (targetVersion && !process.env[VERSION_CHECKED_ENV]) {\n await warnIfOlderRelease(packageJson, targetVersion);\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 const result = await codegenMod.migrate(\n targetVersion ?? requested,\n projectDir,\n { dryRun: Boolean(dryRun) },\n );\n if (dryRun) process.stdout.write(dryRunReport(projectDir, result));\n return;\n }\n\n const agent = (await detect({ cwd: projectDir }))?.agent ?? \"npm\";\n const resolved = resolveCommand(agent, \"execute\", [\n `@powerhousedao/ph-cli@${targetVersion}`,\n \"migrate\",\n \"--version\",\n targetVersion,\n ...(dryRun ? [\"--dry-run\"] : []),\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, {\n cwd: projectDir,\n stdio: \"inherit\",\n env: { ...process.env, [VERSION_CHECKED_ENV]: \"1\" },\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;AAiBA,MAAM,kBAAkB;CAAC;CAAO;CAAW;AAAI;AAG/C,MAAM,sBAAsB;AAS5B,SAAS,uBAAuB,YAAwC;CACtE,IAAI;EACF,OAAO,KAAK,MACV,aAAa,KAAK,YAAY,cAAc,GAAG,MAAM,CACvD;CACF,QAAQ;EACN,OAAO,CAAC;CACV;AACF;;AAGA,SAAgB,wBAAwB,aAAiC;CAiBvE,OAhBe;EACb,YAAY;EACZ,YAAY;EACZ,YAAY;CACd,CAAC,CAAC,SAAS,SACT,OAAO,QAAQ,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,MAAM,WAAW;EACpD,IAAI,CAAC,4BAA4B,SAAS,IAAI,GAAG,OAAO,CAAC;EACzD,IAAI;GACF,MAAM,UAAU,WAAW,KAAK,CAAC,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AkB,aACzD;CACF;CAEA,IAAI,CAAC,iBAAiB,SAAS,kBAAkB,gBAAgB;EAC/D,IAAI,OAAO,QAAQ,IAAI,gDAAgD;EACvE,MAAM,aAAa,MAAM,OAAO;EAChC,MAAM,iBAAiB,sBACrB,UACF;EACA,4BAA4B;GAC1B;GACA;GACA,OAAO,QAAQ,KAAK;EACtB,CAAC;EACD,QAAQ,IACN,+CAA+C,kBAAkB,WACnE;EACA,MAAM,SAAS,MAAM,WAAW,QAC9B,iBAAiB,WACjB,YACA,EAAE,QAAQ,QAAQ,MAAM,EAAE,CAC5B;EACA,IAAI,QAAQ,QAAQ,OAAO,MAAM,aAAa,YAAY,MAAM,CAAC;EACjE;CACF;CAEA,MAAM,SAAS,MAAM,OAAO,EAAE,KAAK,WAAW,CAAC,EAAA,EAAI,SAAS;CAC5D,MAAM,WAAW,eAAe,OAAO,WAAW;EAChD,yBAAyB;EACzB;EACA;EACA;EACA,GAAI,SAAS,CAAC,WAAW,IAAI,CAAC;EAC9B,GAAI,QAAQ,CAAC,SAAS,IAAI,CAAC;CAC7B,CAAC;CACD,IAAI,CAAC,UACH,MAAM,IAAI,MACR,0DAA0D,MAAM,GAClE;CAGF,sBAAsB,OAAO,QAAQ;CAErC,MAAM,UAAU,GAAG,SAAS,QAAQ,GAAG,SAAS,KAAK,KAAK,GAAG;CAC7D,IAAI,OAAO;EACT,QAAQ,IAAI,uCAAuC,OAAO;EAC1D,QAAQ,IAAI,2BAA2B,SAAS;CAClD;CACA,SAAS,SAAS;EAChB,KAAK;EACL,OAAO;EACP,KAAK;GAAE,GAAG,QAAQ;IAAM,sBAAsB;EAAI;CACpD,CAAC;AACH","debug_id":"f78331b4-4fef-5a75-8cde-e77319b7a8ee"}
@@ -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]="dd143afd-4b2a-50dd-b189-6d3fea9769ef")}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]="812a7ca7-ade5-5eaa-98d0-1618f984ff4f")}catch(e){}}();
3
3
  import { i as readProjectDefinitions } from "./run--de_-WAz.mjs";
4
- import { a as errorText, c as toPosix, i as assertChangesWritable, l as writeChanges, n as unifiedDiff, o as readProjectFiles, r as projectModuleReferences, s as restoreChanges, u as outdatedDependency } from "./migrate-subgraphs-DWnMMl4X.mjs";
4
+ import { a as errorText, c as toPosix, i as assertChangesWritable, l as writeChanges, n as unifiedDiff, o as readProjectFiles, r as projectModuleReferences, s as restoreChanges, u as outdatedDependency } from "./migrate-subgraphs-B38Bh800.mjs";
5
5
  import { statSync } from "node:fs";
6
6
  import { basename, relative, resolve } from "node:path";
7
7
  import { assertDocumentModelBarrelsWritable, migrateDocumentModel, regenerateDocumentModelBarrels } from "@powerhousedao/codegen";
@@ -485,5 +485,5 @@ function refusalText(migration) {
485
485
  //#endregion
486
486
  export { migrateDocumentModels };
487
487
 
488
- //# sourceMappingURL=migrate-document-models-3ioRcLNQ.mjs.map
489
- //# debugId=dd143afd-4b2a-50dd-b189-6d3fea9769ef
488
+ //# sourceMappingURL=migrate-document-models-09A1X_-c.mjs.map
489
+ //# debugId=812a7ca7-ade5-5eaa-98d0-1618f984ff4f