@powerhousedao/ph-cli 6.3.0-dev.11 → 6.3.0-dev.12

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 (96) hide show
  1. package/dist/{build-C9gXPccv.mjs → build-D3HxnZjA.mjs} +6 -6
  2. package/dist/{build-C9gXPccv.mjs.map → build-D3HxnZjA.mjs.map} +1 -1
  3. package/dist/build-K6A-jz9S.mjs +4 -0
  4. package/dist/{check-Bdvm8hz0.mjs → check-CD2wzmLq.mjs} +3 -3
  5. package/dist/{check-B8oqVMg7.mjs → check-DZpL_1W5.mjs} +4 -4
  6. package/dist/{check-B8oqVMg7.mjs.map → check-DZpL_1W5.mjs.map} +1 -1
  7. package/dist/{check-CBZ44SDf.mjs → check-DjJySqc9.mjs} +7 -7
  8. package/dist/check-DjJySqc9.mjs.map +1 -0
  9. package/dist/{classic-warnings-BR0S6lr5.mjs → classic-warnings-Hfz6cEEa.mjs} +4 -4
  10. package/dist/{classic-warnings-BR0S6lr5.mjs.map → classic-warnings-Hfz6cEEa.mjs.map} +1 -1
  11. package/dist/{cli-connect-override-D22yFWlC.mjs → cli-connect-override-BRU7ykux.mjs} +4 -4
  12. package/dist/{cli-connect-override-D22yFWlC.mjs.map → cli-connect-override-BRU7ykux.mjs.map} +1 -1
  13. package/dist/cli.mjs +5 -5
  14. package/dist/{compound-DKi56SSx-CXQHhS6t.mjs → compound-DKi56SSx-DAr69gXP.mjs} +63 -4
  15. package/dist/{compound-DKi56SSx-CXQHhS6t.mjs.map → compound-DKi56SSx-DAr69gXP.mjs.map} +1 -1
  16. package/dist/{connect-build-BqRWG3tZ.mjs → connect-build-D8qflzhZ.mjs} +5 -5
  17. package/dist/{connect-build-BqRWG3tZ.mjs.map → connect-build-D8qflzhZ.mjs.map} +1 -1
  18. package/dist/{connect-config-CVU4xhti.mjs → connect-config-sT4vaYEZ.mjs} +4 -4
  19. package/dist/{connect-config-CVU4xhti.mjs.map → connect-config-sT4vaYEZ.mjs.map} +1 -1
  20. package/dist/{connect-studio-D58ByAAn.mjs → connect-studio-BnmP_c9J.mjs} +3 -3
  21. package/dist/connect-studio-D0TWlOmf.mjs +182 -0
  22. package/dist/connect-studio-D0TWlOmf.mjs.map +1 -0
  23. package/dist/definitions-worker.mjs +4 -4
  24. package/dist/definitions-worker.mjs.map +1 -1
  25. package/dist/{dist-DXcB8fAF.mjs → dist-CuwtgEmh.mjs} +4 -4
  26. package/dist/{dist-DXcB8fAF.mjs.map → dist-CuwtgEmh.mjs.map} +1 -1
  27. package/dist/{explain-8OEXF2Dy.mjs → explain-BrZthZF6.mjs} +5 -5
  28. package/dist/{explain-8OEXF2Dy.mjs.map → explain-BrZthZF6.mjs.map} +1 -1
  29. package/dist/{export-DqbcbFU5.mjs → export-BvdnQIps.mjs} +4 -4
  30. package/dist/{export-DqbcbFU5.mjs.map → export-BvdnQIps.mjs.map} +1 -1
  31. package/dist/{generate-all-0YOnlZM0.mjs → generate-all-WJdSqrjR.mjs} +4 -4
  32. package/dist/{generate-all-0YOnlZM0.mjs.map → generate-all-WJdSqrjR.mjs.map} +1 -1
  33. package/dist/{generate-document-model-BiD6ovXc.mjs → generate-document-model-DjV0F1Y5.mjs} +7 -9
  34. package/dist/generate-document-model-DjV0F1Y5.mjs.map +1 -0
  35. package/dist/{generate-subgraph-DJZCr0Tk.mjs → generate-subgraph-BLPP_h4D.mjs} +11 -23
  36. package/dist/generate-subgraph-BLPP_h4D.mjs.map +1 -0
  37. package/dist/{get-version-DQ6JaxAS.mjs → get-version-B5gUHlx1.mjs} +4 -4
  38. package/dist/{get-version-DQ6JaxAS.mjs.map → get-version-B5gUHlx1.mjs.map} +1 -1
  39. package/dist/{inspect-CulIpVsF.mjs → inspect-BgKI8Fhd.mjs} +6 -6
  40. package/dist/{inspect-CulIpVsF.mjs.map → inspect-BgKI8Fhd.mjs.map} +1 -1
  41. package/dist/{mcp-DTGhGK20.mjs → mcp-TEkvF6hk.mjs} +6 -6
  42. package/dist/{mcp-DTGhGK20.mjs.map → mcp-TEkvF6hk.mjs.map} +1 -1
  43. package/dist/{migrate-B9Im3uim.mjs → migrate-BoJKeamS.mjs} +4 -4
  44. package/dist/{migrate-B9Im3uim.mjs.map → migrate-BoJKeamS.mjs.map} +1 -1
  45. package/dist/{migrate-document-models-BsHvClbh.mjs → migrate-document-models-LGZ9wpws.mjs} +5 -6
  46. package/dist/migrate-document-models-LGZ9wpws.mjs.map +1 -0
  47. package/dist/{migrate-subgraphs-CGIPAnQB.mjs → migrate-subgraphs-BnkaPlwk.mjs} +6 -7
  48. package/dist/migrate-subgraphs-BnkaPlwk.mjs.map +1 -0
  49. package/dist/migrate-subgraphs-DETFhWJF.mjs +4 -0
  50. package/dist/ph-cli-commands-CiZdPmxZ.mjs +4 -0
  51. package/dist/{ph-cli-commands-Bea3C3iI.mjs → ph-cli-commands-n6Jkxdrf.mjs} +37 -42
  52. package/dist/ph-cli-commands-n6Jkxdrf.mjs.map +1 -0
  53. package/dist/render-BQE20Cnd.mjs +4 -0
  54. package/dist/{render-SVfj3m8A.mjs → render-CQdi685k.mjs} +6 -6
  55. package/dist/render-CQdi685k.mjs.map +1 -0
  56. package/dist/{run-LRGy7zGo.mjs → run-C6Vha5VN.mjs} +3 -3
  57. package/dist/{run--de_-WAz.mjs → run-sVzTTEUx.mjs} +5 -36
  58. package/dist/run-sVzTTEUx.mjs.map +1 -0
  59. package/dist/{run-sugar-DpznOP1e.mjs → run-sugar-BqRKMdsc.mjs} +4 -4
  60. package/dist/{run-sugar-DpznOP1e.mjs.map → run-sugar-BqRKMdsc.mjs.map} +1 -1
  61. package/dist/runners/connect.d.mts +13 -2
  62. package/dist/runners/connect.d.mts.map +1 -1
  63. package/dist/runners/connect.mjs +13 -7
  64. package/dist/runners/connect.mjs.map +1 -1
  65. package/dist/runners/switchboard.mjs +3 -3
  66. package/dist/{subgraphs-7OYWwP-C.mjs → subgraphs-Bm9NHTCn.mjs} +5 -38
  67. package/dist/subgraphs-Bm9NHTCn.mjs.map +1 -0
  68. package/dist/{verify-BRofKAkt.mjs → verify-B_7ZadZ_.mjs} +4 -4
  69. package/dist/{verify-BRofKAkt.mjs.map → verify-B_7ZadZ_.mjs.map} +1 -1
  70. package/dist/{vetra-CVNZ46pK.mjs → vetra-DR1nNE7N.mjs} +16 -9
  71. package/dist/{vetra-CVNZ46pK.mjs.map → vetra-DR1nNE7N.mjs.map} +1 -1
  72. package/dist/{vetra-host-ChTpJiBJ.mjs → vetra-host-CHcHhb97.mjs} +6 -5
  73. package/dist/{vetra-host-ChTpJiBJ.mjs.map → vetra-host-CHcHhb97.mjs.map} +1 -1
  74. package/dist/vetra-instance-B94ivpPZ.mjs +33 -0
  75. package/dist/vetra-instance-B94ivpPZ.mjs.map +1 -0
  76. package/dist/{vetra-launch-qi10Unax.mjs → vetra-launch-sLUPOntK.mjs} +7 -6
  77. package/dist/{vetra-launch-qi10Unax.mjs.map → vetra-launch-sLUPOntK.mjs.map} +1 -1
  78. package/dist/{vetra-instance-CzhYIjxL.mjs → vetra-runtime-kxkKcxOw.mjs} +4 -30
  79. package/dist/vetra-runtime-kxkKcxOw.mjs.map +1 -0
  80. package/package.json +17 -16
  81. package/dist/build-BxoiFvnE.mjs +0 -4
  82. package/dist/check-CBZ44SDf.mjs.map +0 -1
  83. package/dist/connect-studio-BnfhpIv8.mjs +0 -97
  84. package/dist/connect-studio-BnfhpIv8.mjs.map +0 -1
  85. package/dist/generate-document-model-BiD6ovXc.mjs.map +0 -1
  86. package/dist/generate-subgraph-DJZCr0Tk.mjs.map +0 -1
  87. package/dist/migrate-document-models-BsHvClbh.mjs.map +0 -1
  88. package/dist/migrate-subgraphs-CGIPAnQB.mjs.map +0 -1
  89. package/dist/migrate-subgraphs-DrTVwm8g.mjs +0 -4
  90. package/dist/ph-cli-commands-Bea3C3iI.mjs.map +0 -1
  91. package/dist/ph-cli-commands-iEIgXAIf.mjs +0 -4
  92. package/dist/render-3M3DwFzO.mjs +0 -4
  93. package/dist/render-SVfj3m8A.mjs.map +0 -1
  94. package/dist/run--de_-WAz.mjs.map +0 -1
  95. package/dist/subgraphs-7OYWwP-C.mjs.map +0 -1
  96. package/dist/vetra-instance-CzhYIjxL.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vetra-runtime-kxkKcxOw.mjs","sources":["../src/utils/vetra-runtime.ts"],"sourcesContent":["import { resolvePhDir } from \"@powerhousedao/shared/clis/ph-dir\";\nimport fs from \"node:fs\";\nimport net from \"node:net\";\nimport path from \"node:path\";\n\nexport type VetraRuntimeRecord = {\n pid: number;\n projectName: string;\n switchboardPort: number;\n connectPort: number;\n /** The Switchboard's GraphQL endpoint; absent in records from before it was written. */\n switchboardUrl?: string;\n mcpUrl: string;\n /** Vetra Studio; absent with --disable-connect. */\n connectUrl?: string;\n startedAt: string;\n};\n\nexport type VetraProbe =\n | { status: \"none\" }\n | { status: \"stale\" }\n | { status: \"starting\"; record: VetraRuntimeRecord }\n | { status: \"live\"; record: VetraRuntimeRecord }\n | { status: \"foreign\"; record: VetraRuntimeRecord };\n\nconst READY_TIMEOUT_MS = 2000;\n\n// Under the project's .ph tree — relocated with it by PH_USER_DATA_DIR.\nconst recordPath = (projectDir: string) =>\n path.join(resolvePhDir(projectDir), \"vetra-runtime.json\");\n\nexport function readVetraRuntime(\n projectDir: string,\n): VetraRuntimeRecord | undefined {\n try {\n return JSON.parse(\n fs.readFileSync(recordPath(projectDir), \"utf8\"),\n ) as VetraRuntimeRecord;\n } catch {\n // Missing or corrupt: either way there is no usable record.\n return undefined;\n }\n}\n\nexport function writeVetraRuntime(\n projectDir: string,\n record: VetraRuntimeRecord,\n): void {\n const target = recordPath(projectDir);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, `${JSON.stringify(record, null, 2)}\\n`);\n}\n\n/**\n * The record this process publishes for the Vetra it started. `ph vetra` and\n * `ph run vetra` both build it here, so the two write the same fields. The\n * Switchboard's URLs follow from its port unless the caller knows them.\n */\nexport function vetraRuntimeRecord(input: {\n projectName: string;\n switchboardPort: number;\n connectPort: number;\n switchboardUrl?: string;\n mcpUrl?: string;\n /** Left out when no Vetra Studio runs. */\n connectUrl?: string;\n}): VetraRuntimeRecord {\n const { switchboardPort, connectUrl } = input;\n return {\n pid: process.pid,\n projectName: input.projectName,\n switchboardPort,\n connectPort: input.connectPort,\n switchboardUrl:\n input.switchboardUrl ?? `http://localhost:${switchboardPort}/graphql`,\n mcpUrl: input.mcpUrl ?? `http://localhost:${switchboardPort}/mcp`,\n ...(connectUrl ? { connectUrl } : {}),\n startedAt: new Date().toISOString(),\n };\n}\n\n/** Deletes the record; with `pid`, only the record of that process. */\nexport function clearVetraRuntime(projectDir: string, pid?: number): void {\n if (pid !== undefined && readVetraRuntime(projectDir)?.pid !== pid) return;\n try {\n fs.rmSync(recordPath(projectDir));\n } catch {\n // Already gone.\n }\n}\n\nfunction isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM means the process exists but belongs to another user.\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\nexport function isPortInUse(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = net.connect({ port, host: \"localhost\" });\n socket.once(\"connect\", () => {\n socket.destroy();\n resolve(true);\n });\n socket.once(\"error\", () => resolve(false));\n });\n}\n\nasync function isReady(port: number): Promise<boolean> {\n try {\n const response = await fetch(`http://localhost:${port}/ready`, {\n signal: AbortSignal.timeout(READY_TIMEOUT_MS),\n });\n return response.ok;\n } catch {\n return false;\n }\n}\n\n/**\n * Decide whether the recorded instance is actually serving this project.\n *\n * All three checks are load-bearing. A pid can be reused by an unrelated\n * process, so a live pid proves nothing on its own. Another project's\n * switchboard would answer `/ready` on its own port, so a healthy `/ready`\n * proves nothing either. And the recorded `projectName` is what separates\n * \"my instance\" from \"someone else's instance that happens to hold this\n * port\" — which is precisely the confusion that let an agent write document\n * models into a different project's drive.\n *\n * A stale record is deleted so the next start is unblocked. A foreign one is\n * left alone: it describes something that is alive.\n */\nexport async function probeVetraRuntime(\n projectDir: string,\n projectName: string,\n): Promise<VetraProbe> {\n const record = readVetraRuntime(projectDir);\n if (!record) return { status: \"none\" };\n\n const alive = isPidAlive(record.pid);\n const ready = alive && (await isReady(record.switchboardPort));\n // The record lands once the port is bound; `/ready` turns 200 later.\n const starting =\n alive && !ready && (await isPortInUse(record.switchboardPort));\n if (!ready && !starting) {\n clearVetraRuntime(projectDir);\n return { status: \"stale\" };\n }\n\n if (record.projectName !== projectName) {\n return { status: \"foreign\", record };\n }\n return ready ? { status: \"live\", record } : { status: \"starting\", record };\n}\n\nconst MCP_FILES = [\n \".mcp.json\",\n path.join(\".cursor\", \"mcp.json\"),\n path.join(\".gemini\", \"settings.json\"),\n];\n\ntype McpConfig = { mcpServers?: Record<string, { url?: string }> };\ntype UrlMcpConfig = [string, McpConfig, { url?: string }];\n\n/** Each MCP config whose `reactor-mcp` entry still points at a URL. */\nfunction urlMcpConfigs(projectDir: string): UrlMcpConfig[] {\n const found: UrlMcpConfig[] = [];\n for (const rel of MCP_FILES) {\n const target = path.join(projectDir, rel);\n if (!fs.existsSync(target)) continue;\n let parsed: McpConfig;\n try {\n parsed = JSON.parse(fs.readFileSync(target, \"utf8\")) as McpConfig;\n } catch {\n // Hand-broken JSON is the author's to fix; don't clobber it.\n continue;\n }\n const server = parsed.mcpServers?.[\"reactor-mcp\"];\n if (server?.url) found.push([rel, parsed, server]);\n }\n return found;\n}\n\n/** The MCP configs `ph migrate` would move to the `ph mcp` launcher. */\nexport function legacyMcpConfigs(projectDir: string): string[] {\n return urlMcpConfigs(projectDir).map(([rel]) => rel);\n}\n\n/**\n * Point every URL-style `reactor-mcp` entry at `port`, returning the files\n * changed. Stdio entries (`ph mcp`) carry no port and are left alone; this\n * keeps projects that have not run `ph migrate` working.\n */\nexport function syncMcpPort(projectDir: string, port: number): string[] {\n const changed: string[] = [];\n const wanted = `http://localhost:${port}/mcp`;\n for (const [rel, parsed, server] of urlMcpConfigs(projectDir)) {\n if (server.url === wanted) continue;\n server.url = wanted;\n fs.writeFileSync(\n path.join(projectDir, rel),\n `${JSON.stringify(parsed, null, 2)}\\n`,\n );\n changed.push(rel);\n }\n return changed;\n}\n\n/**\n * {@link syncMcpPort} for a Vetra that just bound `port`, returning what to\n * tell the user. An MCP client resolved `.mcp.json` before this process\n * started and cannot re-read it, so a drifted literal means the agent is\n * pointed at the wrong port — possibly another project's reactor. Correct the\n * file and say so plainly; we cannot fix the already-open client ourselves.\n */\nexport function syncMcpPortNotices(projectDir: string, port: number): string[] {\n const notices: string[] = [];\n const driftedMcpFiles = syncMcpPort(projectDir, port);\n if (driftedMcpFiles.length > 0) {\n notices.push(\n `Updated ${driftedMcpFiles.join(\" and \")} to port ${port}. ` +\n `Reconnect your MCP client (/mcp) to pick it up. ` +\n `This edit is local — do not commit it.`,\n );\n }\n if (legacyMcpConfigs(projectDir).length > 0) {\n notices.push(\n \"reactor-mcp still points at a URL; run `ph migrate` to switch it to the `ph mcp` launcher.\",\n );\n }\n return notices;\n}\n"],"names":[],"mappings":";;;;;;;AAyBA,MAAM,mBAAmB;AAGzB,MAAM,cAAc,eAClB,KAAK,KAAK,aAAa,UAAU,GAAG,oBAAoB;AAE1D,SAAgB,iBACd,YACgC;CAChC,IAAI;EACF,OAAO,KAAK,MACV,GAAG,aAAa,WAAW,UAAU,GAAG,MAAM,CAChD;CACF,QAAQ;EAEN;CACF;AACF;AAEA,SAAgB,kBACd,YACA,QACM;CACN,MAAM,SAAS,WAAW,UAAU;CACpC,GAAG,UAAU,KAAK,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;CACtD,GAAG,cAAc,QAAQ,GAAG,KAAK,UAAU,QAAQ,MAAM,CAAC,EAAE,GAAG;AACjE;;;;;;AAOA,SAAgB,mBAAmB,OAQZ;CACrB,MAAM,EAAE,iBAAiB,eAAe;CACxC,OAAO;EACL,KAAK,QAAQ;EACb,aAAa,MAAM;EACnB;EAC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AAoB,CAAC;CAC3B,MAAM,kBAAkB,YAAY,YAAY,IAAI;CACpD,IAAI,gBAAgB,SAAS,GAC3B,QAAQ,KACN,WAAW,gBAAgB,KAAK,OAAO,EAAE,WAAW,KAAK,yFAG3D;CAEF,IAAI,iBAAiB,UAAU,CAAC,CAAC,SAAS,GACxC,QAAQ,KACN,4FACF;CAEF,OAAO;AACT","debug_id":"3659f44e-51ed-51d5-bd30-cdb8c53ee9e3"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerhousedao/ph-cli",
3
- "version": "6.3.0-dev.11",
3
+ "version": "6.3.0-dev.12",
4
4
  "description": "",
5
5
  "license": "AGPL-3.0-only",
6
6
  "type": "module",
@@ -40,18 +40,19 @@
40
40
  "dependencies": {
41
41
  "@modelcontextprotocol/sdk": "1.29.0",
42
42
  "@originjs/vite-plugin-commonjs": "^1.0.3",
43
- "@powerhousedao/builder-tools": "6.3.0-dev.11",
44
- "@powerhousedao/codegen": "6.3.0-dev.11",
45
- "@powerhousedao/common": "6.3.0-dev.11",
46
- "@powerhousedao/config": "6.3.0-dev.11",
47
- "@powerhousedao/ph-run": "6.3.0-dev.11",
48
- "@powerhousedao/reactor": "6.3.0-dev.11",
49
- "@powerhousedao/reactor-api": "6.3.0-dev.11",
50
- "@powerhousedao/reactor-mcp": "6.3.0-dev.11",
51
- "@powerhousedao/shared": "6.3.0-dev.11",
52
- "@powerhousedao/switchboard": "6.3.0-dev.11",
53
- "@powerhousedao/vetra": "6.3.0-dev.11",
54
- "@renown/sdk": "6.3.0-dev.11",
43
+ "@powerhousedao/builder-tools": "6.3.0-dev.12",
44
+ "@powerhousedao/codegen": "6.3.0-dev.12",
45
+ "@powerhousedao/common": "6.3.0-dev.12",
46
+ "@powerhousedao/config": "6.3.0-dev.12",
47
+ "@powerhousedao/devtools": "6.3.0-dev.12",
48
+ "@powerhousedao/ph-run": "6.3.0-dev.12",
49
+ "@powerhousedao/reactor": "6.3.0-dev.12",
50
+ "@powerhousedao/reactor-api": "6.3.0-dev.12",
51
+ "@powerhousedao/reactor-mcp": "6.3.0-dev.12",
52
+ "@powerhousedao/shared": "6.3.0-dev.12",
53
+ "@powerhousedao/switchboard": "6.3.0-dev.12",
54
+ "@powerhousedao/vetra": "6.3.0-dev.12",
55
+ "@renown/sdk": "6.3.0-dev.12",
55
56
  "@sentry/node-core": "^10.52.0",
56
57
  "@tsdown/css": "0.23.0",
57
58
  "@vercel/nft": "^1.11.0",
@@ -60,7 +61,7 @@
60
61
  "change-case": "5.4.4",
61
62
  "cmd-ts": "0.15.0",
62
63
  "colorette": "2.0.20",
63
- "document-model": "6.3.0-dev.11",
64
+ "document-model": "6.3.0-dev.12",
64
65
  "dotenv": "16.4.7",
65
66
  "enquirer": "2.4.1",
66
67
  "graphql": "^16",
@@ -82,8 +83,8 @@
82
83
  "copyfiles": "2.4.1",
83
84
  "write-package": "7.2.0",
84
85
  "zod": "^4.5.4",
85
- "@powerhousedao/desktop": "6.3.0-dev.11",
86
- "@powerhousedao/host-core": "6.3.0-dev.11"
86
+ "@powerhousedao/desktop": "6.3.0-dev.12",
87
+ "@powerhousedao/host-core": "6.3.0-dev.12"
87
88
  },
88
89
  "scripts": {
89
90
  "tsc": "tsc",
@@ -1,4 +0,0 @@
1
- import { t as runBuild } from "./build-C9gXPccv.mjs";
2
- export { runBuild };
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="bf971130-eda9-5586-9e6f-f16f386d146d")}catch(e){}}();
4
- //# debugId=bf971130-eda9-5586-9e6f-f16f386d146d
@@ -1 +0,0 @@
1
- {"version":3,"file":"check-CBZ44SDf.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":"be97745f-8aa0-562a-92c8-9d848a2dd89e"}
@@ -1,97 +0,0 @@
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]="1a3d568e-d170-5077-a149-6eed15b0983a")}catch(e){}}();
3
- import { r as buildStudioConnectOverride } from "./cli-connect-override-D22yFWlC.mjs";
4
- import { t as switchboardProxy } from "./switchboard-proxy-CGfMtENM.mjs";
5
- import { readFileSync, watch } from "node:fs";
6
- import { join } from "node:path";
7
- import { getConnectBaseViteConfig } from "@powerhousedao/builder-tools";
8
- import { createServer, mergeConfig } from "vite";
9
- import { isDeepStrictEqual } from "node:util";
10
- //#region src/services/connect-studio.ts
11
- const CONFIG_FILE = "powerhouse.config.json";
12
- const RELOAD_DEBOUNCE_MS = 200;
13
- function readConfig(file) {
14
- try {
15
- return JSON.parse(readFileSync(file, "utf8"));
16
- } catch {
17
- return;
18
- }
19
- }
20
- /** Resolves to the first dev server; with reloadOnConfigChange a config change replaces it. */
21
- async function runConnectStudio(args, customLogger, callerOverride, { routes, cacheDir, reloadOnConfigChange, proxy, restartWith, exposeStop } = {}) {
22
- const { port, host, open, cors, strictPort, printUrls, bindCLIShortcuts } = args;
23
- const mode = "development";
24
- const dirname = process.cwd();
25
- const configFile = join(dirname, CONFIG_FILE);
26
- const start = async (first) => {
27
- const override = typeof callerOverride === "function" ? callerOverride() : callerOverride;
28
- const baseConfig = getConnectBaseViteConfig({
29
- mode,
30
- dirname,
31
- cliConnectOverride: buildStudioConnectOverride(args, override),
32
- routes,
33
- cacheDir
34
- });
35
- const devServerConfig = {
36
- server: {
37
- port,
38
- host,
39
- open: first && open,
40
- cors,
41
- strictPort,
42
- ...proxy ? { proxy: switchboardProxy(proxy) } : {}
43
- },
44
- customLogger
45
- };
46
- const server = await createServer(mergeConfig(baseConfig, devServerConfig));
47
- await server.listen();
48
- if (bindCLIShortcuts) server.bindCLIShortcuts({ print: first });
49
- return server;
50
- };
51
- let loaded = reloadOnConfigChange ? readConfig(configFile) : void 0;
52
- const first = await start(true);
53
- if (printUrls) first.printUrls();
54
- if (!reloadOnConfigChange) {
55
- exposeStop?.(() => first.close());
56
- return first;
57
- }
58
- let server = first;
59
- let timer;
60
- let restarts = Promise.resolve();
61
- let stopped = false;
62
- const restart = async () => {
63
- if (stopped) return;
64
- const current = readConfig(configFile);
65
- if (current === void 0 || isDeepStrictEqual(current, loaded)) return;
66
- loaded = current;
67
- server.config.logger.info(`[connect] ${CONFIG_FILE} changed; restarting Studio with it.`, { timestamp: true });
68
- await server.close();
69
- server = await (restartWith ? restartWith(() => start(false)) : start(false));
70
- };
71
- const queueRestart = () => {
72
- clearTimeout(timer);
73
- timer = setTimeout(() => {
74
- restarts = restarts.then(restart).catch((error) => {
75
- server.config.logger.error(`[connect] Could not restart Studio: ${error instanceof Error ? error.message : String(error)}`);
76
- });
77
- }, RELOAD_DEBOUNCE_MS);
78
- };
79
- const watcher = watch(dirname, (_event, file) => {
80
- if (file === CONFIG_FILE) queueRestart();
81
- });
82
- watcher.unref();
83
- exposeStop?.(async () => {
84
- stopped = true;
85
- clearTimeout(timer);
86
- watcher.close();
87
- await restarts;
88
- await server.close();
89
- });
90
- queueRestart();
91
- return first;
92
- }
93
- //#endregion
94
- export { runConnectStudio as t };
95
-
96
- //# sourceMappingURL=connect-studio-BnfhpIv8.mjs.map
97
- //# debugId=1a3d568e-d170-5077-a149-6eed15b0983a
@@ -1 +0,0 @@
1
- {"version":3,"file":"connect-studio-BnfhpIv8.mjs","sources":["../src/services/connect-studio.ts"],"sourcesContent":["import { getConnectBaseViteConfig } from \"@powerhousedao/builder-tools\";\nimport type { PHConnectRuntimeConfig } from \"@powerhousedao/shared/clis\";\nimport { readFileSync, watch } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport type { InlineConfig, Logger, ViteDevServer } from \"vite\";\nimport { createServer, mergeConfig } from \"vite\";\nimport type { ConnectStudioArgs } from \"../types.js\";\nimport { buildStudioConnectOverride } from \"../utils/cli-connect-override.js\";\nimport { switchboardProxy } from \"../utils/switchboard-proxy.js\";\n\nconst CONFIG_FILE = \"powerhouse.config.json\";\nconst RELOAD_DEBOUNCE_MS = 200;\n\nexport type ConnectStudioOptions = {\n routes?: string | false;\n cacheDir?: string;\n /** Starts a new dev server when powerhouse.config.json changes; the open tab reloads. */\n reloadOnConfigChange?: boolean;\n /** The switchboard origin whose paths this server proxies (runner.proxy). */\n proxy?: string;\n /** Runs each restart's server start, for a caller that started the first\n * one inside a wrapper of its own. */\n restartWith?: (start: () => Promise<ViteDevServer>) => Promise<ViteDevServer>;\n /** Handed what stops Studio for good, before it resolves: the config\n * watcher and whichever server is current. The first server's own `close`\n * stops neither once a config change has replaced it. */\n exposeStop?: (stop: () => Promise<void>) => void;\n};\n\nfunction readConfig(file: string): unknown {\n try {\n return JSON.parse(readFileSync(file, \"utf8\"));\n } catch {\n // Missing or mid-edit: nothing to compare yet.\n return undefined;\n }\n}\n\n/** Resolves to the first dev server; with reloadOnConfigChange a config change replaces it. */\nexport async function runConnectStudio(\n args: ConnectStudioArgs,\n customLogger?: Logger,\n callerOverride?:\n | PHConnectRuntimeConfig\n | (() => PHConnectRuntimeConfig | undefined),\n {\n routes,\n cacheDir,\n reloadOnConfigChange,\n proxy,\n restartWith,\n exposeStop,\n }: ConnectStudioOptions = {},\n): Promise<ViteDevServer> {\n const { port, host, open, cors, strictPort, printUrls, bindCLIShortcuts } =\n args;\n const mode = \"development\";\n\n const dirname = process.cwd();\n const configFile = join(dirname, CONFIG_FILE);\n\n const start = async (first: boolean) => {\n const override =\n typeof callerOverride === \"function\" ? callerOverride() : callerOverride;\n const baseConfig = getConnectBaseViteConfig({\n mode,\n dirname,\n cliConnectOverride: buildStudioConnectOverride(args, override),\n routes,\n cacheDir,\n });\n const devServerConfig: InlineConfig = {\n // A restart reloads the open tab rather than opening another.\n server: {\n port,\n host,\n open: first && open,\n cors,\n strictPort,\n ...(proxy ? { proxy: switchboardProxy(proxy) } : {}),\n },\n customLogger,\n };\n const server = await createServer(mergeConfig(baseConfig, devServerConfig));\n await server.listen();\n if (bindCLIShortcuts) server.bindCLIShortcuts({ print: first });\n return server;\n };\n\n let loaded = reloadOnConfigChange ? readConfig(configFile) : undefined;\n const first = await start(true);\n if (printUrls) first.printUrls();\n if (!reloadOnConfigChange) {\n exposeStop?.(() => first.close());\n return first;\n }\n\n let server = first;\n let timer: NodeJS.Timeout | undefined;\n let restarts = Promise.resolve();\n let stopped = false;\n const restart = async () => {\n if (stopped) return;\n const current = readConfig(configFile);\n if (current === undefined || isDeepStrictEqual(current, loaded)) return;\n loaded = current;\n server.config.logger.info(\n `[connect] ${CONFIG_FILE} changed; restarting Studio with it.`,\n { timestamp: true },\n );\n await server.close();\n server = await (restartWith\n ? restartWith(() => start(false))\n : start(false));\n };\n const queueRestart = () => {\n clearTimeout(timer);\n timer = setTimeout(() => {\n restarts = restarts.then(restart).catch((error: unknown) => {\n server.config.logger.error(\n `[connect] Could not restart Studio: ${error instanceof Error ? error.message : String(error)}`,\n );\n });\n }, RELOAD_DEBOUNCE_MS);\n };\n // The folder, not the file: editors save by replacing it.\n const watcher = watch(dirname, (_event, file) => {\n if (file === CONFIG_FILE) queueRestart();\n });\n watcher.unref();\n exposeStop?.(async () => {\n stopped = true;\n clearTimeout(timer);\n watcher.close();\n // A restart under way ends first: it leaves the server to close.\n await restarts;\n await server.close();\n });\n // Catch config edits made while the first server was starting.\n queueRestart();\n return first;\n}\n"],"names":[],"mappings":";;;;;;;;;;AAWA,MAAM,cAAc;AACpB,MAAM,qBAAqB;AAkB3B,SAAS,WAAW,MAAuB;CACzC,IAAI;EACF,OAAO,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;CAC9C,QAAQ;EAEN;CACF;AACF;;AAGA,eAAsB,iBACpB,MACA,cACA,gBAGA,EACE,QACA,UACA,sBACA,OACA,aACA,eACwB,CAAC,GACH;CACxB,MAAM,EAAE,MAAM,MAAM,MAAM,MAAM,YAAY,WAAW,qBACrD;CACF,MAAM,OAAO;CAEb,MAAM,UAAU,QAAQ,IAAI;CAC5B,MAAM,aAAa,KAAK,SAAS,WAAW;CAE5C,MAAM,QAAQ,OAAO,UAAmB;EACtC,MAAM,WACJ,OAAO,mBAAmB,aAAa,eAAe,IAAI;EAC5D,MA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U,MAAM,UAAU,QAAQ,SAAS;EAC/C,IAAI,SAAS,aAAa,aAAa;CACzC,CAAC;CACD,QAAQ,MAAM;CACd,aAAa,YAAY;EACvB,UAAU;EACV,aAAa,KAAK;EAClB,QAAQ,MAAM;EAEd,MAAM;EACN,MAAM,OAAO,MAAM;CACrB,CAAC;CAED,aAAa;CACb,OAAO;AACT","debug_id":"1a3d568e-d170-5077-a149-6eed15b0983a"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate-document-model-BiD6ovXc.mjs","sources":["../src/services/definitions/code-first-scaffold.ts","../src/services/generate-document-model.ts"],"sourcesContent":["import type { ModelGeneration } from \"@powerhousedao/codegen\";\nimport { capitalCase, kebabCase } from \"change-case\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { readPackage } from \"read-pkg\";\nimport type { Project } from \"ts-morph\";\n\nexport async function scaffoldCodeFirstDocumentModel(\n generation: ModelGeneration,\n name: string,\n projectDir: string,\n project: Project,\n) {\n const modelName = name.trim();\n if (modelName === \"\") {\n throw new Error(\"--name needs a document model name.\");\n }\n const namespace = await documentTypeNamespace(projectDir);\n const documentType = `${namespace}/${kebabCase(modelName)}`;\n const editorName = `${capitalCase(modelName)} Editor`;\n const editorDirName = kebabCase(editorName);\n if (existsSync(join(projectDir, \"editors\", editorDirName))) {\n throw new Error(\n `editors/${editorDirName} already exists. Choose another --name, or move that editor first.`,\n );\n }\n\n const result = await generation.scaffoldDocumentModel(\n {\n name: modelName,\n documentType,\n author: { name: namespace, website: null },\n },\n project,\n );\n for (const path of result.written) {\n console.log(`Wrote ${path}`);\n }\n\n await generation.generateEditor(\n {\n editorName,\n documentTypes: [documentType],\n editorId: editorDirName,\n editorDirName,\n },\n project,\n );\n await project.save();\n console.log(`Generated editor \"${editorName}\" in editors/${editorDirName}`);\n}\n\nasync function documentTypeNamespace(projectDir: string) {\n const { name } = await readPackage({ cwd: projectDir, normalize: false });\n if (!name) {\n throw new Error(\n \"--name puts the document type under the package name. Add a name to package.json.\",\n );\n }\n return name.replace(/^@/, \"\").replaceAll(\"/\", \"-\");\n}\n","import { loadDocumentModel, modelGeneration } from \"@powerhousedao/codegen\";\nimport {\n buildTsMorphProject,\n documentModelsDirOf,\n} from \"@powerhousedao/codegen/utils\";\nimport {\n extractDocumentModelDocuments,\n getDocument,\n saveSpec,\n} from \"@powerhousedao/vetra/codegen\";\nimport { handleMutuallyExclusiveOptions } from \"@powerhousedao/shared/clis\";\nimport type { DocumentModelDocument } from \"@powerhousedao/shared/document-model\";\nimport { existsSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport type { GenerateDocumentModelArgs } from \"../types.js\";\nimport { resolveModuleDirName } from \"../utils/module-dir.js\";\nimport { warnSubgraphTypeConflicts } from \"../utils/warn-subgraph-type-conflicts.js\";\nimport { scaffoldCodeFirstDocumentModel } from \"./definitions/code-first-scaffold.js\";\n\n/** The configured documentModelsDir, package-relative, for messages and paths. */\nfunction modelsDirOf(projectDir: string) {\n return relative(projectDir, documentModelsDirOf(projectDir).path).replaceAll(\n \"\\\\\",\n \"/\",\n );\n}\n\nexport async function startGenerateDocumentModel(\n args: GenerateDocumentModelArgs,\n projectDir: string,\n) {\n const { document, dir, all, extract, name, codeFirst, debug } = args;\n if (debug) {\n console.log({ args });\n }\n if (name !== undefined && !codeFirst) {\n throw new Error(\n \"--name creates a code-first document model. Pass --code-first.\",\n );\n }\n if (codeFirst && name === undefined) {\n throw new Error(\n \"--code-first only chooses how --name creates a model. Existing models of both styles are discovered without it; drop --code-first. To convert a schema-first model, run ph migrate --document-model <dir>.\",\n );\n }\n const project = buildTsMorphProject(projectDir);\n if (name !== undefined) {\n handleMutuallyExclusiveOptions(\n {\n \"--name\": name,\n \"--document\": document,\n \"--dir\": dir,\n \"--all\": all || undefined,\n \"--extract\": extract || undefined,\n },\n \"generation mode\",\n );\n await scaffoldCodeFirstDocumentModel(\n modelGeneration,\n name,\n projectDir,\n project,\n );\n return;\n }\n if (extract) {\n const docs = extractDocumentModelDocuments(project);\n for (const doc of docs) {\n const path = await saveSpec(doc, projectDir);\n console.log(`Wrote ${path}`);\n }\n return;\n }\n if (all) {\n const { documentModels, unreadableDirs, codeFirstDocumentModels } =\n await modelGeneration.generateAllDocumentModels(project);\n await project.save();\n if (\n documentModels.length === 0 &&\n unreadableDirs.length === 0 &&\n codeFirstDocumentModels.length === 0\n ) {\n console.log(`No document models found in ${modelsDirOf(projectDir)}/.`);\n }\n for (const { name } of documentModels) {\n console.log(`Regenerated document model \"${name}\"`);\n }\n for (const { name } of codeFirstDocumentModels) {\n console.log(`Updated the exports of code-first document model \"${name}\"`);\n }\n for (const dirName of unreadableDirs) {\n console.warn(\n `Skipped ${modelsDirOf(projectDir)}/${dirName}: it has no readable ${dirName}.json, and no index.ts in it exports a code-first model. Kept the manifest's document models.`,\n );\n }\n await warnSubgraphTypeConflicts(projectDir);\n return;\n } else if (document) {\n if (document.endsWith(\".phd\")) {\n const doc = (await getDocument(document)) as DocumentModelDocument;\n await modelGeneration.generateDocumentModel(doc.state.global, project);\n } else {\n const state = await loadDocumentModel(document);\n await modelGeneration.generateDocumentModel(state, project);\n }\n } else if (dir) {\n const modelsDir = modelsDirOf(projectDir);\n const dirName = resolveModuleDirName(\n projectDir,\n modelsDir,\n dir,\n \"my-document-model\",\n );\n const specPath = join(projectDir, modelsDir, dirName, `${dirName}.json`);\n if (!existsSync(specPath)) {\n throw new Error(`${modelsDir}/${dirName} has no ${dirName}.json.`);\n }\n const state = await loadDocumentModel(specPath);\n await modelGeneration.generateDocumentModel(state, project);\n await project.save();\n console.log(\n `Regenerated document model \"${state.name}\" in ${modelsDir}/${dirName}`,\n );\n await warnSubgraphTypeConflicts(projectDir);\n return;\n } else {\n console.log(\n \"Please specify one of `document`, `dir`, `all`, or `extract`.\",\n );\n return;\n }\n await project.save();\n await warnSubgraphTypeConflicts(projectDir);\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;AAOA,eAAsB,+BACpB,YACA,MACA,YACA,SACA;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AY,YAAY,UAAU;EACxC,MAAM,UAAU,qBACd,YACA,WACA,KACA,mBACF;EACA,MAAM,WAAW,KAAK,YAAY,WAAW,SAAS,GAAG,QAAQ,MAAM;EACvE,IAAI,CAAC,WAAW,QAAQ,GACtB,MAAM,IAAI,MAAM,GAAG,UAAU,GAAG,QAAQ,UAAU,QAAQ,OAAO;EAEnE,MAAM,QAAQ,MAAM,kBAAkB,QAAQ;EAC9C,MAAM,gBAAgB,sBAAsB,OAAO,OAAO;EAC1D,MAAM,QAAQ,KAAK;EACnB,QAAQ,IACN,+BAA+B,MAAM,KAAK,OAAO,UAAU,GAAG,SAChE;EACA,MAAM,0BAA0B,UAAU;EAC1C;CACF,OAAO;EACL,QAAQ,IACN,+DACF;EACA;CACF;CACA,MAAM,QAAQ,KAAK;CACnB,MAAM,0BAA0B,UAAU;AAC5C","debug_id":"d143ac9a-759c-5a5d-98d0-f6df3d4b1bfe"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate-subgraph-DJZCr0Tk.mjs","sources":["../src/services/generate-subgraph.ts"],"sourcesContent":["import {\n detectFeatures,\n generateAllSubgraphs,\n generateSubgraph,\n generateSubgraphDir,\n syncFeatureDependencies,\n} from \"@powerhousedao/codegen\";\nimport {\n buildTsMorphProject,\n subgraphDirStyle,\n type SubgraphStyle,\n} from \"@powerhousedao/codegen/utils\";\nimport {\n extractSubgraphDocuments,\n findSubgraphNameConflict,\n generateSubgraphFromDocument,\n getDocument,\n saveSpec,\n} from \"@powerhousedao/vetra/codegen\";\nimport type { SubgraphModuleDocument } from \"@powerhousedao/vetra/document-models/subgraph-module\";\nimport { kebabCase } from \"change-case\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { GenerateSubgraphArgs } from \"../types.js\";\nimport { installAddedDependencies } from \"../utils/install-added-dependencies.js\";\nimport { resolveModuleDirName } from \"../utils/module-dir.js\";\nimport { warnSubgraphTypeConflicts } from \"../utils/warn-subgraph-type-conflicts.js\";\n\nconst INDEX_FILE_EXPECTATION = {\n \"schema-first\": \"a class extending BaseSubgraph with a string literal `name`\",\n \"code-first\":\n \"a class extending Subgraph with a string literal `static subgraphName`\",\n} satisfies Record<SubgraphStyle, string>;\n\nasync function assertSubgraphNameFree(projectDir: string, name: string) {\n const conflict = await findSubgraphNameConflict(projectDir, name);\n if (conflict) throw new Error(conflict);\n}\n\n/** The notice for `--code-first` on an existing schema-first subgraph, which\n * is then left unchanged. */\nfunction codeFirstOnSchemaFirst(\n args: GenerateSubgraphArgs,\n projectDir: string,\n name: string,\n): string | undefined {\n if (!args.codeFirst) return undefined;\n const subgraphsDir = join(projectDir, \"subgraphs\");\n const dirName = kebabCase(name);\n if (\n !existsSync(join(subgraphsDir, dirName, \"index.ts\")) ||\n subgraphDirStyle(subgraphsDir, dirName) !== \"schema-first\"\n )\n return undefined;\n return `subgraphs/${dirName} is schema-first; --code-first only applies to new subgraphs. To convert it, run ph migrate --subgraph ${dirName}.`;\n}\n\nexport async function startGenerateSubgraph(\n args: GenerateSubgraphArgs,\n projectDir: string,\n) {\n const { name, document, dir, all, extract, debug } = args;\n if (debug) {\n console.log({ args });\n }\n const project = buildTsMorphProject(projectDir);\n if (extract) {\n const docs = extractSubgraphDocuments(project);\n if (docs.length === 0) {\n console.log(\"No subgraphs found in subgraphs/.\");\n }\n for (const doc of docs) {\n const path = await saveSpec(doc, projectDir);\n console.log(`Wrote ${path}`);\n }\n return;\n }\n const report: string[] = [];\n if (all) {\n const { subgraphNames, unreadableDirs } =\n await generateAllSubgraphs(project);\n if (subgraphNames.length === 0 && unreadableDirs.length === 0) {\n report.push(\"No subgraphs found in subgraphs/.\");\n }\n for (const subgraphName of subgraphNames) {\n report.push(`Regenerated subgraph \"${subgraphName}\"`);\n }\n for (const dirName of unreadableDirs) {\n console.warn(\n `Skipped subgraphs/${dirName}: expected its index.ts to export ${INDEX_FILE_EXPECTATION[subgraphDirStyle(join(projectDir, \"subgraphs\"), dirName)]}. Kept the manifest's subgraphs.`,\n );\n }\n } else if (document) {\n const doc = (await getDocument(document)) as SubgraphModuleDocument;\n const notice = codeFirstOnSchemaFirst(\n args,\n projectDir,\n doc.state.global.name,\n );\n if (notice) {\n console.log(notice);\n return;\n }\n await assertSubgraphNameFree(projectDir, doc.state.global.name);\n await generateSubgraphFromDocument(doc, project, {\n codeFirst: args.codeFirst,\n });\n } else if (name) {\n const notice = codeFirstOnSchemaFirst(args, projectDir, name);\n if (notice) {\n console.log(notice);\n return;\n }\n await assertSubgraphNameFree(projectDir, name);\n await generateSubgraph(name, project, { codeFirst: args.codeFirst });\n } else if (dir) {\n const dirName = resolveModuleDirName(\n projectDir,\n \"subgraphs\",\n dir,\n \"my-subgraph\",\n );\n if (!existsSync(join(projectDir, \"subgraphs\", dirName, \"index.ts\"))) {\n throw new Error(`subgraphs/${dirName} has no index.ts.`);\n }\n const { subgraphName, style } = await generateSubgraphDir(dirName, project);\n if (!subgraphName) {\n throw new Error(\n `Could not read subgraphs/${dirName}/index.ts: expected ${INDEX_FILE_EXPECTATION[style]}.`,\n );\n }\n report.push(`Regenerated subgraph \"${subgraphName}\"`);\n } else {\n console.log(\n \"Please specify one of `name`, `document`, `dir`, `all`, or `extract`.\",\n );\n return;\n }\n await project.save();\n for (const line of report) {\n console.log(line);\n }\n await warnSubgraphTypeConflicts(projectDir);\n const added = await syncFeatureDependencies(\n detectFeatures(projectDir),\n projectDir,\n );\n await installAddedDependencies(added, projectDir, args.skipInstall);\n}\n"],"names":["installAddedDependencies"],"mappings":";;;;;;;;;;;;AA4BA,MAAM,yBAAyB;CAC7B,gBAAgB;CAChB,cACE;AACJ;AAEA,eAAe,uBAAuB,YAAoB,MAAc;CACtE,MAAM,WAAW,MAAM,yBAAyB,YAAY,IAAI;CAChE,IAAI,UAAU,MAAM,IAAI,MAAM,QAAQ;AACxC;;;AAIA,SAAS,uBACP,MACA,YACA,MACoB;CACpB,IAAI,CAAC,KAAK,WAAW,OAAO,KAAA;CAC5B,MAAM,eAAe,KAAK,YAA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ACH,OAAO,IAAI,MAAM;EACf,MAAM,SAAS,uBAAuB,MAAM,YAAY,IAAI;EAC5D,IAAI,QAAQ;GACV,QAAQ,IAAI,MAAM;GAClB;EACF;EACA,MAAM,uBAAuB,YAAY,IAAI;EAC7C,MAAM,iBAAiB,MAAM,SAAS,EAAE,WAAW,KAAK,UAAU,CAAC;CACrE,OAAO,IAAI,KAAK;EACd,MAAM,UAAU,qBACd,YACA,aACA,KACA,aACF;EACA,IAAI,CAAC,WAAW,KAAK,YAAY,aAAa,SAAS,UAAU,CAAC,GAChE,MAAM,IAAI,MAAM,aAAa,QAAQ,kBAAkB;EAEzD,MAAM,EAAE,cAAc,UAAU,MAAM,oBAAoB,SAAS,OAAO;EAC1E,IAAI,CAAC,cACH,MAAM,IAAI,MACR,4BAA4B,QAAQ,sBAAsB,uBAAuB,OAAO,EAC1F;EAEF,OAAO,KAAK,yBAAyB,aAAa,EAAE;CACtD,OAAO;EACL,QAAQ,IACN,uEACF;EACA;CACF;CACA,MAAM,QAAQ,KAAK;CACnB,KAAK,MAAM,QAAQ,QACjB,QAAQ,IAAI,IAAI;CAElB,MAAM,0BAA0B,UAAU;CAC1C,MAAM,QAAQ,MAAM,wBAClB,eAAe,UAAU,GACzB,UACF;CACA,MAAMA,2BAAyB,OAAO,YAAY,KAAK,WAAW;AACpE","debug_id":"57f37708-e436-5415-9747-38ee27ce7f15"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"migrate-document-models-BsHvClbh.mjs","sources":["../src/services/migrate-document-models.ts"],"sourcesContent":["import {\n assertDocumentModelBarrelsWritable,\n type DocumentModelMigration,\n type DocumentModelMigrationFile,\n type DocumentModelMigrationReference,\n migrateDocumentModel,\n regenerateDocumentModelBarrels,\n} from \"@powerhousedao/codegen\";\nimport { documentModelsDirOf } from \"@powerhousedao/codegen/utils\";\nimport type {\n DocumentModelDefinition,\n DocumentModelModuleDefinition,\n DocumentModelOperationDefinition,\n DocumentModelSpecificationDefinition,\n StateDefinition,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n discoverDocumentModelDirectories,\n inspectProjectDefinitions,\n} from \"document-model/tooling\";\nimport { statSync } from \"node:fs\";\nimport { basename, relative, resolve } from \"node:path\";\nimport { outdatedDependency } from \"./installed-version.js\";\nimport { unifiedDiff } from \"./migrate-subgraphs.js\";\nimport { readProjectDefinitions } from \"./model/project.js\";\nimport { projectModuleReferences } from \"./project-module-references.js\";\nimport {\n assertChangesWritable,\n errorText,\n type FileBackup,\n readProjectFiles,\n restoreChanges,\n toPosix,\n writeChanges,\n} from \"./project-files.js\";\n\nconst SOURCE_FILE = /\\.(?:[cm]?[jt]sx?|json|graphql)$/;\nexport type MigrateDocumentModelsOptions = {\n readonly projectDir: string;\n /** Model directories to convert; empty converts every schema-first one. */\n readonly dirs: readonly string[];\n readonly dryRun: boolean;\n /** Renames a type named like a scalar instead of refusing its model. */\n readonly renameConflictingTypes?: boolean;\n readonly out?: (text: string) => void;\n};\n\ntype Definitions = ReadonlyMap<number, unknown>;\n\n/**\n * `ph migrate --document-models`: converts schema-first document models into\n * code-first ones. Each converted model is loaded again as `ph model inspect`\n * loads it, and every version must keep the definition it had: the same\n * state, operations, inputs and errors. Otherwise its files are restored.\n * Returns the exit code: 0 when every requested model converted or was\n * already code-first, 1 otherwise.\n */\nexport async function migrateDocumentModels(\n options: MigrateDocumentModelsOptions,\n): Promise<0 | 1> {\n const out =\n options.out ?? ((text: string) => void process.stdout.write(text));\n const { projectDir } = options;\n let resolved: { readonly path: string };\n try {\n resolved = documentModelsDirOf(projectDir);\n } catch (error) {\n out(`${errorText(error)}\\n`);\n return 1;\n }\n const modelsDir = toPosix(relative(projectDir, resolved.path));\n const directories = new Map(\n discoverDocumentModelDirectories(projectDir, resolved.path).directories.map(\n (directory) => [directory.name, directory.kind] as const,\n ),\n );\n let failed = false;\n const requested: string[] = [];\n if (options.dirs.length === 0) {\n for (const [name, kind] of directories) {\n if (kind === \"stored\") requested.push(name);\n }\n }\n for (const dir of options.dirs) {\n const name = basename(dir.replace(/[\\\\/]+$/, \"\"));\n // A path names a directory of the models directory, not any directory.\n if (\n /[\\\\/]/.test(dir.replace(/[\\\\/]+$/, \"\")) &&\n resolve(projectDir, dir, \"..\") !== resolved.path\n ) {\n out(\n `${dir}: not a directory of ${modelsDir}/. Name a model directory, such as ${modelsDir}/${name}.\\n`,\n );\n failed = true;\n continue;\n }\n if (!requested.includes(name)) requested.push(name);\n }\n if (requested.length === 0 && !failed) {\n out(\"No schema-first document models to convert.\\n\");\n return 0;\n }\n\n const pending: string[] = [];\n for (const dirName of requested) {\n const label = `${modelsDir}/${dirName}`;\n const kind = directories.get(dirName);\n if (kind === undefined || kind === \"none\" || kind === \"invalid\") {\n out(\n `${label}: not found. Name a directory of ${modelsDir}/ that holds a document model.\\n`,\n );\n failed = true;\n } else if (kind === \"module\") {\n out(`${label}: already code-first\\n`);\n } else if (kind === \"generated\") {\n out(\n `${label}: not converted. It has generated code but no ${dirName}.json, so its specification cannot be read. Restore ${dirName}.json, then migrate again.\\n`,\n );\n failed = true;\n } else {\n pending.push(dirName);\n }\n }\n if (pending.length === 0) return failed ? 1 : 0;\n // The barrels are regenerated after the models are written, so a barrel\n // codegen would refuse to rewrite stops the run before anything changes.\n try {\n assertChangesWritable(projectDir, [\n { path: \"document-models/index.ts\" },\n { path: \"document-models/document-models.ts\" },\n { path: \"document-models/upgrade-manifests.ts\" },\n { path: \"powerhouse.manifest.json\" },\n ]);\n assertDocumentModelBarrelsWritable(projectDir);\n } catch (error) {\n out(`No document model was converted. ${errorText(error)}\\n`);\n return 1;\n }\n\n let moduleReferences: readonly DocumentModelMigrationReference[];\n try {\n moduleReferences = projectModuleReferences(projectDir).map((reference) => ({\n file: reference.file,\n specifier: reference.specifier,\n targets: reference.targets\n .filter((target) =>\n statSync(resolve(projectDir, target.path), {\n throwIfNoEntry: false,\n })?.isFile(),\n )\n .map((target) => target.path),\n }));\n } catch (error) {\n out(`No document model was converted. ${errorText(error)}\\n`);\n return 1;\n }\n const outdated = outdatedDependency(projectDir, \"document-model\");\n const run: ModelRun = {\n projectDir,\n modelsDir,\n pending,\n renameConflictingTypes: options.renameConflictingTypes ?? false,\n moduleReferences,\n out,\n };\n if (options.dryRun) {\n if (outdated !== undefined) {\n out(`Note: ${outdated} Until then, a real run converts nothing.\\n`);\n }\n return (await previewModels(run)) || failed ? 1 : 0;\n }\n if (outdated !== undefined) {\n out(`No document model was converted. ${outdated}\\n`);\n return 1;\n }\n return (await convertModels(run)) || failed ? 1 : 0;\n}\n\ntype ModelRun = {\n readonly moduleReferences: readonly DocumentModelMigrationReference[];\n readonly projectDir: string;\n readonly modelsDir: string;\n readonly pending: readonly string[];\n readonly renameConflictingTypes: boolean;\n readonly out: (text: string) => void;\n};\n\n/** `--dry-run`: prints what each conversion would write. Returns whether one was refused. */\nasync function previewModels(run: ModelRun): Promise<boolean> {\n const { out } = run;\n let files = readSourceTexts(run.projectDir);\n let refused = false;\n const notes = new Set<string>();\n for (const dirName of run.pending) {\n const label = `${run.modelsDir}/${dirName}`;\n let migration: DocumentModelMigration;\n try {\n migration = await migrateDocumentModel({\n documentModelsDir: run.modelsDir,\n dirName,\n files,\n moduleReferences: run.moduleReferences,\n renameConflictingTypes: run.renameConflictingTypes,\n });\n if (migration.kind === \"converted\") {\n assertChangesWritable(run.projectDir, migration.files);\n }\n } catch (error) {\n out(\n `${label}: would not convert. The conversion failed unexpectedly: ${errorText(error)}\\n`,\n );\n refused = true;\n continue;\n }\n if (migration.kind !== \"converted\") {\n out(`${label}: ${refusalText(migration)}\\n`);\n refused = true;\n continue;\n }\n out(\n `${label}: would convert ${migration.documentType} (versions ${migration.versions.join(\", \")}) to code-first, if the converted model keeps its definition when loaded\\n`,\n );\n for (const file of migration.files) out(fileDiff(file));\n for (const note of migration.notes) notes.add(note);\n files = applied(files, migration.files);\n }\n for (const note of notes) out(`Note: ${note}\\n`);\n return refused;\n}\n\n/**\n * Converts each model, writes it, loads it again and keeps it only when every\n * version has its stored definition; then regenerates the barrels. Returns\n * whether a model was not converted.\n */\nasync function convertModels(run: ModelRun): Promise<boolean> {\n const { projectDir, out } = run;\n let files = readSourceTexts(projectDir);\n const before = await storedDefinitions(\n projectDir,\n run.modelsDir,\n run.pending,\n files,\n );\n let failed = false;\n const converted = new Set<string>();\n const notes = new Set<string>();\n for (const dirName of run.pending) {\n const label = `${run.modelsDir}/${dirName}`;\n let outcome: ModelOutcome;\n try {\n outcome = await convertModel(run, dirName, files, before);\n } catch (error) {\n outcome = {\n ok: false,\n text: `not converted; its files are unchanged. The conversion failed unexpectedly: ${errorText(error)}`,\n };\n }\n if (!outcome.ok) {\n out(`${label}: ${outcome.text}\\n`);\n failed = true;\n continue;\n }\n const { migration } = outcome;\n files = applied(files, migration.files);\n out(\n `${label}: converted ${migration.documentType} (versions ${migration.versions.join(\", \")}) to code-first; every version keeps its definition\\n`,\n );\n for (const note of migration.notes) notes.add(note);\n converted.add(dirName);\n }\n for (const note of notes) out(`Note: ${note}\\n`);\n if (converted.size > 0) {\n try {\n const changed = await regenerateDocumentModelBarrels(\n projectDir,\n converted,\n );\n if (changed.length > 0) {\n out(`Regenerated ${changed.join(\", \")}.\\n`);\n }\n } catch (error) {\n out(\n `The converted models are written, but the document-models barrels could not be regenerated: ${errorText(error)}\\nFix that, then run ph generate.\\n`,\n );\n failed = true;\n }\n }\n return failed;\n}\n\ntype ModelOutcome =\n | {\n readonly ok: true;\n readonly migration: Extract<\n DocumentModelMigration,\n { kind: \"converted\" }\n >;\n }\n | { readonly ok: false; readonly text: string };\n\n/** Converts, writes and verifies one model, restoring its files when it fails. */\nasync function convertModel(\n run: ModelRun,\n dirName: string,\n files: ReadonlyMap<string, string>,\n before: StoredDefinitions,\n): Promise<ModelOutcome> {\n const migration = await migrateDocumentModel({\n documentModelsDir: run.modelsDir,\n dirName,\n files,\n moduleReferences: run.moduleReferences,\n renameConflictingTypes: run.renameConflictingTypes,\n });\n if (migration.kind !== \"converted\") {\n return { ok: false, text: refusalText(migration) };\n }\n const stored = before.definitions.get(dirName);\n const unread = migration.versions.filter(\n (version) => stored?.has(version) !== true,\n );\n if (stored === undefined || unread.length > 0) {\n return {\n ok: false,\n text: `not converted. Version ${unread.join(\", \")} of its stored definition could not be read, so the conversion could not be checked. Run ph model check to see why.`,\n };\n }\n let backup: FileBackup;\n try {\n backup = writeChanges(run.projectDir, migration.files);\n } catch (error) {\n return {\n ok: false,\n text: `not converted; its files are restored. Writing them failed: ${errorText(error)}`,\n };\n }\n let verification: Awaited<ReturnType<typeof verify>>;\n try {\n verification = await verify(\n run.projectDir,\n migration.documentType,\n renameTypes(stored, migration.renamedTypes),\n before.known,\n );\n } catch (error) {\n verification = {\n ok: false,\n reason: `Checking the converted model failed: ${errorText(error)}`,\n };\n }\n if (!verification.ok) {\n restoreChanges(run.projectDir, backup);\n return {\n ok: false,\n text: `not converted; its files are restored. ${verification.reason}`,\n };\n }\n return { ok: true, migration };\n}\n\n/** The package's source files as text, by project-relative POSIX path. */\nfunction readSourceTexts(projectDir: string): Map<string, string> {\n return new Map(\n [...readProjectFiles(projectDir, SOURCE_FILE)].map(([path, bytes]) => [\n path,\n bytes.toString(\"utf8\"),\n ]),\n );\n}\n\nfunction applied(\n files: ReadonlyMap<string, string>,\n changes: readonly DocumentModelMigrationFile[],\n): Map<string, string> {\n const next = new Map(files);\n for (const file of changes) {\n if (file.after === null) next.delete(file.path);\n else next.set(file.path, file.after);\n }\n return next;\n}\n\ntype StoredDefinitions = {\n readonly definitions: ReadonlyMap<string, Definitions>;\n /** The errors the project reported before anything was written. */\n readonly known: ReadonlySet<string>;\n};\n\n/** The stored versions of each model, read before anything is written. */\nasync function storedDefinitions(\n projectDir: string,\n modelsDir: string,\n dirNames: readonly string[],\n files: ReadonlyMap<string, string>,\n): Promise<StoredDefinitions> {\n const wanted = dirNames.flatMap((dirName) => {\n const text = files.get(`${modelsDir}/${dirName}/${dirName}.json`);\n if (text === undefined) return [];\n try {\n const stored = JSON.parse(text) as {\n id: string;\n specifications: { version: number }[];\n };\n return [\n {\n dirName,\n documentType: stored.id,\n versions: stored.specifications.map(({ version }) => version),\n },\n ];\n } catch {\n // The migration refuses a specification that is not JSON, and says why.\n return [];\n }\n });\n return await readProjectDefinitions(projectDir, (project) => {\n const result = new Map<string, Definitions>();\n const known = new Set<string>();\n for (const { dirName, documentType, versions } of wanted) {\n const definitions = new Map<number, unknown>();\n for (const version of versions) {\n const report = inspectProjectDefinitions(project, {\n selection: { documentType, version },\n });\n if (\"definition\" in report) definitions.set(version, report.definition);\n for (const message of errorMessages(report.diagnostics)) {\n known.add(message);\n }\n }\n result.set(dirName, definitions);\n }\n return { definitions: result, known };\n });\n}\n\nfunction errorMessages(\n diagnostics: readonly {\n readonly severity: string;\n readonly message: string;\n readonly repair?: string;\n }[],\n): string[] {\n return diagnostics\n .filter(({ severity }) => severity === \"error\")\n .map(({ message, repair }) => `${message} ${repair ?? \"\"}`.trim());\n}\n\ntype Verification =\n | { readonly ok: true }\n | { readonly ok: false; readonly reason: string };\n\n/**\n * The stored definitions with the types the conversion renamed off a\n * scalar's name renamed too, so the comparison expects the new names. The\n * stored definition also lists the scalar the type's name collided with,\n * which the converted model no longer names.\n */\nfunction renameTypes(\n definitions: Definitions,\n renamed: readonly { version: number; from: string; to: string }[],\n): Definitions {\n if (renamed.length === 0) return definitions;\n const result = new Map<number, unknown>();\n for (const [version, definition] of definitions) {\n const names = new Map(\n renamed\n .filter((entry) => entry.version === version)\n .map(({ from, to }) => [from, to] as const),\n );\n // A type is named by `name` in its definition and in every reference;\n // unions and interfaces list members and implemented types by name.\n const walk = (value: unknown, key?: string): unknown => {\n if (key === \"scalars\" && Array.isArray(value)) {\n return value.filter(\n (scalar) =>\n !(\n isRecord(scalar) &&\n typeof scalar.name === \"string\" &&\n names.has(scalar.name)\n ),\n );\n }\n if (Array.isArray(value)) {\n return value.map((item) =>\n (key === \"members\" || key === \"implements\") &&\n typeof item === \"string\"\n ? (names.get(item) ?? item)\n : walk(item),\n );\n }\n if (!isRecord(value)) return value;\n return Object.fromEntries(\n Object.entries(value).map(([entryKey, entry]) => [\n entryKey,\n entryKey === \"name\" &&\n typeof entry === \"string\" &&\n typeof value.kind === \"string\"\n ? (names.get(entry) ?? entry)\n : walk(entry, entryKey),\n ]),\n );\n };\n result.set(version, walk(definition));\n }\n return result;\n}\n\n/** Loads the converted model and compares each version with its stored definition. */\nasync function verify(\n projectDir: string,\n documentType: string,\n expected: Definitions,\n known: ReadonlySet<string>,\n): Promise<Verification> {\n let actual: ReadonlyMap<number, unknown>;\n let problems: readonly string[];\n try {\n [actual, problems] = await readProjectDefinitions(projectDir, (project) => {\n const definitions = new Map<number, unknown>();\n const errors: string[] = [];\n for (const version of expected.keys()) {\n const report = inspectProjectDefinitions(project, {\n selection: { documentType, version },\n });\n if (\"definition\" in report) definitions.set(version, report.definition);\n for (const message of errorMessages(report.diagnostics)) {\n // Errors the project had before, such as another model's, are not this conversion's.\n if (!known.has(message)) errors.push(message);\n }\n }\n return [definitions, errors] as const;\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n ok: false,\n reason: `The converted model does not load: ${message.replaceAll(projectDir, \".\")}`,\n };\n }\n if (problems.length > 0) {\n return {\n ok: false,\n reason: `The converted model does not pass ph model check:\\n${[...new Set(problems)].map((problem) => ` ${problem}`).join(\"\\n\")}`,\n };\n }\n for (const [version, stored] of expected) {\n const converted = actual.get(version);\n if (converted === undefined) {\n return {\n ok: false,\n reason: `The converted model exports no version ${version} of ${documentType}.`,\n };\n }\n const differences = definitionDifferences(stored, converted);\n if (differences.length > 0) {\n return {\n ok: false,\n reason: `Version ${version} of the converted model has a different definition:\\n${differences\n .slice(0, 20)\n .map((line) => ` ${line}`)\n .join(\"\\n\")}`,\n };\n }\n }\n return { ok: true };\n}\n\n/**\n * What a stored definition and the code-first one differ in. IDs, the\n * stored names of modules and operations, the reducer and template text, and\n * the GraphQL text a schema-first model keeps derive from the authoring\n * style, so they are not compared. The model, every named type (operation\n * inputs included), the state roots and initial values, and each operation's\n * key, action type, scope, input and errors are.\n */\nexport function definitionDifferences(\n stored: unknown,\n converted: unknown,\n): string[] {\n const differences: string[] = [];\n const walk = (left: unknown, right: unknown, path: string) => {\n if (differences.length >= 50) return;\n if (Array.isArray(left) && Array.isArray(right)) {\n if (left.length !== right.length) {\n differences.push(\n `${path}: ${left.length} entries stored, ${right.length} converted`,\n );\n }\n for (\n let index = 0;\n index < Math.min(left.length, right.length);\n index++\n ) {\n walk(left[index], right[index], `${path}[${index}]`);\n }\n return;\n }\n if (isRecord(left) && isRecord(right)) {\n for (const key of new Set([\n ...Object.keys(left),\n ...Object.keys(right),\n ])) {\n walk(left[key], right[key], path === \"\" ? key : `${path}.${key}`);\n }\n return;\n }\n if (JSON.stringify(left) !== JSON.stringify(right)) {\n differences.push(\n `${path}: stored ${JSON.stringify(left)}, converted ${JSON.stringify(right)}`,\n );\n }\n };\n walk(canonical(stored), canonical(converted), \"\");\n return differences;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** The records of a list, or none when it is not one. */\nfunction records(value: unknown): Record<string, unknown>[] {\n return Array.isArray(value) ? value.filter(isRecord) : [];\n}\n\n/** Empty text and null both mean \"none\" in a stored model. */\nconst text = (value: unknown): unknown => (value === \"\" ? null : value);\n\n/** Members whose empty text means none, as the stored format writes it. */\nconst TEXT_KEYS = new Set([\"description\", \"deprecated\", \"template\"]);\n\n/** `value` with empty text read as none, and without `keys`, at any depth. */\nfunction normalized(value: unknown, keys: readonly string[] = []): unknown {\n if (Array.isArray(value)) return value.map((item) => normalized(item, keys));\n if (!isRecord(value)) return value;\n return Object.fromEntries(\n Object.entries(value)\n .filter(([key]) => !keys.includes(key))\n .map(([key, entry]) => [\n key,\n TEXT_KEYS.has(key) ? text(entry) : normalized(entry, keys),\n ]),\n );\n}\n\n/**\n * How one member of a definition is compared: `ignore` leaves it out, a\n * function maps it to what is compared. The tables are exhaustive over the\n * definition types, so a member added to them must be classified here; a\n * member the loaded definition has and a table lacks is compared as is.\n */\ntype Rule = \"ignore\" | ((value: unknown) => unknown);\ntype Rules<T> = { readonly [Key in keyof Required<T>]: Rule };\n\nconst same = (value: unknown) => normalized(value);\nconst exampleValues = (value: unknown) =>\n records(value).map((example) => example.value);\n\nfunction compared<T>(value: unknown, rules: Rules<T>): unknown {\n if (!isRecord(value)) return value;\n const result: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n const rule = (rules as Readonly<Record<string, Rule | undefined>>)[key];\n if (rule === \"ignore\") continue;\n result[key] = (rule ?? same)(entry);\n }\n return result;\n}\n\nconst STATE_RULES: Rules<StateDefinition> = {\n root: same,\n initialValue: (value) => value ?? {},\n examples: exampleValues,\n unknownKeys: same,\n // The GraphQL and JSON text the state is materialized from.\n materialized: \"ignore\",\n};\n\nconst OPERATION_RULES: Rules<DocumentModelOperationDefinition> = {\n id: \"ignore\",\n // The stored operation name; the key and action type derive from it.\n name: \"ignore\",\n key: same,\n description: text,\n actionType: same,\n creatorKey: same,\n scope: same,\n // Compared among the specification's types.\n input: (value) => (isRecord(value) ? value.name : null),\n errors: (value) => normalized(value, [\"id\", \"key\"]),\n examples: exampleValues,\n template: \"ignore\",\n reducer: \"ignore\",\n};\n\nconst MODULE_RULES: Rules<DocumentModelModuleDefinition> = {\n id: \"ignore\",\n // The stored module name; the key derives from it.\n name: \"ignore\",\n key: same,\n description: text,\n operations: (value) =>\n records(value).map((operation) => compared(operation, OPERATION_RULES)),\n};\n\n/** The named types of a specification, operation inputs included, by name. */\nfunction namedTypes(specification: Record<string, unknown>): unknown {\n const types = new Map<string, unknown>();\n const add = (type: unknown) => {\n if (isRecord(type) && typeof type.name === \"string\") {\n types.set(type.name, normalized(type, [\"key\"]));\n }\n };\n for (const type of records(specification.types)) add(type);\n for (const module of records(specification.modules)) {\n for (const operation of records(module.operations)) add(operation.input);\n }\n return Object.fromEntries(\n [...types].sort(([left], [right]) => left.localeCompare(right)),\n );\n}\n\nconst SPECIFICATION_RULES: Rules<DocumentModelSpecificationDefinition> = {\n version: same,\n changeLog: same,\n scalars: same,\n // The GraphQL text a schema-first model keeps.\n graphQLCompatibility: \"ignore\",\n types: \"ignore\",\n state: (value) =>\n isRecord(value)\n ? {\n global: compared(value.global, STATE_RULES),\n local: compared(value.local, STATE_RULES),\n }\n : value,\n modules: (value) =>\n records(value).map((module) => compared(module, MODULE_RULES)),\n};\n\nconst DEFINITION_RULES: Rules<DocumentModelDefinition> = {\n kind: same,\n formatVersion: same,\n // How identities and serialization derive differs by authoring style.\n compatibility: (value) =>\n isRecord(value) ? { scalarCoercion: value.scalarCoercion } : value,\n model: same,\n specifications: (value) =>\n records(value).map((specification) => {\n const result = compared(specification, SPECIFICATION_RULES);\n return isRecord(result)\n ? { ...result, types: namedTypes(specification) }\n : result;\n }),\n};\n\n/** The parts of a definition both authoring styles must agree on. */\nfunction canonical(definition: unknown): unknown {\n return compared(definition, DEFINITION_RULES);\n}\n\nfunction fileDiff(file: DocumentModelMigrationFile): string {\n if (file.after === null)\n return `--- a/${file.path}\\n+++ /dev/null\\n(deleted)\\n`;\n return unifiedDiff({\n path: file.path,\n before: file.before,\n after: file.after,\n });\n}\n\nfunction refusalText(\n migration: Extract<DocumentModelMigration, { kind: \"refused\" }>,\n): string {\n return `not converted\\n${migration.refusals\n .map(\n ({ file, line, reason, repair }) =>\n ` ${file}${line === undefined ? \"\" : `:${line}`}: ${reason}\\n ${repair}`,\n )\n .join(\"\\n\")}`;\n}\n"],"names":[],"mappings":";;;;;;;;;;AAoCA,MAAM,cAAc;;;;;;;;;AAqBpB,eAAsB,sBACpB,SACgB;CAChB,MAAM,MACJ,QAAQ,SAAS,SAAiB,KAAK,QAAQ,OAAO,MAAM,IAAI;CAClE,MAAM,EAAE,eAAe;CACvB,IAAI;CACJ,IAAI;EACF,WAAW,oBAAoB,UAAU;CAC3C,SAAS,OAAO;EACd,IAAI,GAAG,UAAU,KAAK,EAAE,GAAG;EAC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,UACd,SAAS,KAAK,IAAI,EAAE,gBAAgB,MAAM,eAAe,IAAI;CAC/D,OAAO;CACP,iBAAiB,UACf,QAAQ,KAAK,CAAC,CAAC,KAAK,kBAAkB;EACpC,MAAM,SAAS,SAAS,eAAe,mBAAmB;EAC1D,OAAO,SAAS,MAAM,IAClB;GAAE,GAAG;GAAQ,OAAO,WAAW,aAAa;EAAE,IAC9C;CACN,CAAC;AACL;;AAGA,SAAS,UAAU,YAA8B;CAC/C,OAAO,SAAS,YAAY,gBAAgB;AAC9C;AAEA,SAAS,SAAS,MAA0C;CAC1D,IAAI,KAAK,UAAU,MACjB,OAAO,SAAS,KAAK,KAAK;CAC5B,OAAO,YAAY;EACjB,MAAM,KAAK;EACX,QAAQ,KAAK;EACb,OAAO,KAAK;CACd,CAAC;AACH;AAEA,SAAS,YACP,WACQ;CACR,OAAO,kBAAkB,UAAU,SAChC,KACE,EAAE,MAAM,MAAM,QAAQ,aACrB,KAAK,OAAO,SAAS,KAAA,IAAY,KAAK,IAAI,OAAO,IAAI,OAAO,QAAQ,QACxE,CAAC,CACA,KAAK,IAAI;AACd","debug_id":"72fe8e37-deec-5226-8c68-de308ddea42a"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"migrate-subgraphs-CGIPAnQB.mjs","sources":["../src/services/installed-version.ts","../src/services/project-files.ts","../src/services/package-module-targets.ts","../src/services/project-module-references.ts","../src/services/subgraph-readers.ts","../src/services/migrate-subgraphs.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { lt, valid } from \"semver\";\nimport { getVersion } from \"../get-version.js\";\n\n/** The version of `packageName` that Node resolves from `projectDir`. */\nfunction installedVersion(\n projectDir: string,\n packageName: string,\n): string | undefined {\n for (let dir = projectDir; ; dir = dirname(dir)) {\n const manifest = join(dir, \"node_modules\", packageName, \"package.json\");\n if (existsSync(manifest)) {\n const { version } = JSON.parse(readFileSync(manifest, \"utf8\")) as {\n version?: unknown;\n };\n return typeof version === \"string\" ? version : undefined;\n }\n if (dirname(dir) === dir) return undefined;\n }\n}\n\n/**\n * Why the code `ph migrate` writes cannot run against the project's\n * `packageName`, or undefined when it can: the project must have the package\n * at this ph-cli's version or later. Unknown versions are not checked.\n */\nexport function outdatedDependency(\n projectDir: string,\n packageName: string,\n): string | undefined {\n const required = getVersion();\n if (valid(required) === null) return undefined;\n const installed = installedVersion(projectDir, packageName);\n if (installed === undefined) {\n return `${packageName} is not installed in this project. Install the project's dependencies, then migrate again.`;\n }\n if (valid(installed) === null || !lt(installed, required)) return undefined;\n return `This project has ${packageName} ${installed}, and what this ph migrate converts to code-first needs ${required} or later. Run ph migrate ${required} to upgrade the Powerhouse packages, then convert again.`;\n}\n","import {\n chmodSync,\n existsSync,\n lstatSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n rmdirSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\n\n/** Directories that never hold the package's own sources. */\nconst SKIPPED_DIRS = new Set([\n \"node_modules\",\n \"dist\",\n \"build\",\n \".ph\",\n \".git\",\n \".turbo\",\n \".vite\",\n \".tsbuild\",\n \"coverage\",\n]);\n\nexport const toPosix = (path: string) => path.split(sep).join(\"/\");\n\nexport const errorText = (error: unknown) =>\n error instanceof Error ? error.message : String(error);\n\n/** The package's files whose names match `pattern`, by project-relative POSIX path. */\nexport function readProjectFiles(\n projectDir: string,\n pattern: RegExp,\n): Map<string, Buffer> {\n const files = new Map<string, Buffer>();\n const visit = (dir: string) => {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (entry.isDirectory()) {\n if (!SKIPPED_DIRS.has(entry.name)) visit(join(dir, entry.name));\n } else if (entry.isFile() && pattern.test(entry.name)) {\n const path = join(dir, entry.name);\n files.set(toPosix(relative(projectDir, path)), readFileSync(path));\n }\n }\n };\n visit(projectDir);\n return files;\n}\n\n/** A file a migration writes, or deletes when `after` is null. */\nexport type FileChange = {\n readonly path: string;\n readonly after: string | null;\n};\n\n/** Each original file's contents and permissions, or null when it does not exist. */\nexport type FileBackup = ReadonlyMap<\n string,\n { readonly bytes: Buffer; readonly mode: number } | null\n>;\n\n/** Refuses links the source inventory cannot represent without following them. */\nexport function assertChangesWritable(\n projectDir: string,\n changes: readonly { readonly path: string }[],\n): void {\n const root = resolve(projectDir);\n for (const { path } of changes) {\n let current = resolve(root, path);\n const local = relative(root, current);\n if (\n local === \"\" ||\n local === \"..\" ||\n local.startsWith(`..${sep}`) ||\n isAbsolute(local)\n ) {\n throw new Error(`${path} is not a file inside this project.`);\n }\n while (current !== root) {\n if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink()) {\n throw new Error(\n `${toPosix(relative(root, current))} is a symbolic link. Replace it with a regular project file or directory before migrating; its target was not changed.`,\n );\n }\n current = dirname(current);\n }\n }\n}\n\n/**\n * Writes `changes` and returns the bytes they replaced. When a write fails,\n * everything already written is restored before the error is rethrown.\n */\nexport function writeChanges(\n projectDir: string,\n changes: readonly FileChange[],\n): FileBackup {\n assertChangesWritable(projectDir, changes);\n const backup = new Map<\n string,\n { readonly bytes: Buffer; readonly mode: number } | null\n >();\n for (const { path } of changes) {\n const absolute = join(projectDir, path);\n backup.set(\n path,\n existsSync(absolute)\n ? {\n bytes: readFileSync(absolute),\n mode: lstatSync(absolute).mode & 0o7777,\n }\n : null,\n );\n }\n try {\n for (const change of changes) put(projectDir, change.path, change.after);\n } catch (error) {\n restoreChanges(projectDir, backup);\n throw error;\n }\n return backup;\n}\n\n/** Restores the contents and permissions `writeChanges` replaced. */\nexport function restoreChanges(projectDir: string, backup: FileBackup) {\n for (const [path, file] of backup) {\n put(projectDir, path, file?.bytes ?? null);\n if (file !== null) chmodSync(join(projectDir, path), file.mode);\n }\n}\n\nfunction put(projectDir: string, path: string, bytes: string | Buffer | null) {\n const absolute = join(projectDir, path);\n if (bytes === null) {\n rmSync(absolute, { force: true });\n removeEmptyParents(projectDir, dirname(absolute));\n } else {\n mkdirSync(dirname(absolute), { recursive: true });\n writeFileSync(absolute, bytes);\n }\n}\n\n/** Removes `dir` and its parents while they are empty, up to the project. */\nfunction removeEmptyParents(projectDir: string, dir: string) {\n let current = dir;\n while (current.startsWith(projectDir) && current !== projectDir) {\n if (!existsSync(current) || readdirSync(current).length > 0) return;\n rmdirSync(current);\n current = dirname(current);\n }\n}\n","import { existsSync, realpathSync } from \"node:fs\";\nimport { dirname, join, relative, resolve, sep } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { type PackageJson, readPackageSync } from \"read-pkg\";\nimport { toPosix } from \"./project-files.js\";\n\n/** Every static alternative, without assuming which runtime conditions apply. */\nfunction alternatives(value: unknown): string[] {\n if (typeof value === \"string\") return [value];\n if (value === null || typeof value !== \"object\") return [];\n return Object.values(value).flatMap(alternatives);\n}\n\n/** Extra matching patterns are safe here: targets are protected, never rewritten. */\nfunction matchingTargets(\n mapping: unknown,\n specifier: string,\n): { pattern: string; targets: string[] }[] {\n if (mapping === null || typeof mapping !== \"object\") return [];\n return Object.entries(mapping).flatMap(([pattern, value]) => {\n if (pattern === specifier)\n return [{ pattern, targets: alternatives(value) }];\n const star = pattern.indexOf(\"*\");\n if (star === -1) return [];\n const prefix = pattern.slice(0, star);\n const suffix = pattern.slice(star + 1);\n if (\n !specifier.startsWith(prefix) ||\n !specifier.endsWith(suffix) ||\n specifier.length < prefix.length + suffix.length\n )\n return [];\n const matched = specifier.slice(\n prefix.length,\n specifier.length - suffix.length,\n );\n return [\n {\n pattern,\n targets: alternatives(value).map((target) =>\n target.replaceAll(\"*\", matched),\n ),\n },\n ];\n });\n}\n\n/** Static local targets of observed imports/self-exports in each file's package scope. */\nexport function packageModuleTargets(projectDir: string) {\n const root = resolve(projectDir);\n const packages = new Map<string, PackageJson | undefined>();\n const imports = (from: string, specifier: string) => {\n const redirects: { from: string; specifier: string }[] = [];\n let dir = dirname(join(root, from));\n for (;;) {\n if (!packages.has(dir)) {\n packages.set(\n dir,\n existsSync(join(dir, \"package.json\"))\n ? readPackageSync({ cwd: dir, normalize: false })\n : undefined,\n );\n }\n const metadata = packages.get(dir);\n if (metadata !== undefined) {\n const visit = (name: string, active: ReadonlySet<string>): string[] => {\n let matches: ReturnType<typeof matchingTargets> = [];\n if (name.startsWith(\"#\")) {\n matches = matchingTargets(metadata.imports, name);\n } else if (\n typeof metadata.name === \"string\" &&\n (name === metadata.name || name.startsWith(`${metadata.name}/`))\n ) {\n const subpath = `.${name.slice(metadata.name.length)}`;\n const exports = metadata.exports;\n const subpaths =\n exports !== null &&\n typeof exports === \"object\" &&\n Object.keys(exports).some((key) => key.startsWith(\".\"));\n matches =\n subpath === \".\" && !subpaths\n ? [{ pattern: \".\", targets: alternatives(exports) }]\n : matchingTargets(exports, subpath);\n }\n return matches.flatMap(({ pattern, targets }) => {\n const key = `${name.startsWith(\"#\") ? \"imports\" : \"exports\"}:${pattern}`;\n if (active.has(key)) {\n throw new Error(\n `Package mapping ${pattern} redirects recursively. Remove that redirect before migrating subgraphs.`,\n );\n }\n const next = new Set(active).add(key);\n return targets.flatMap((target) => {\n if (!target.startsWith(\"./\")) {\n if (\n target.startsWith(\"#\") ||\n (typeof metadata.name === \"string\" &&\n (target === metadata.name ||\n target.startsWith(`${metadata.name}/`)))\n ) {\n return visit(target, next);\n }\n redirects.push({\n from: toPosix(relative(root, join(dir, \"package.json\"))),\n specifier: target,\n });\n return [];\n }\n const file = fileURLToPath(\n new URL(target, pathToFileURL(dir + sep)),\n );\n return [toPosix(relative(root, file))];\n });\n });\n };\n return { targets: visit(specifier, new Set()), redirects };\n }\n if (dir === root) return { targets: [], redirects };\n dir = dirname(dir);\n }\n };\n const entries = (file: string, specifier: string): readonly string[] => {\n const targets = new Set<string>();\n for (const dir of new Set([dirname(file), dirname(realpathSync(file))])) {\n if (!packages.has(dir)) {\n packages.set(dir, readPackageSync({ cwd: dir, normalize: false }));\n }\n const metadata = packages.get(dir);\n if (metadata === undefined) continue;\n const paths = [\n \"./index.js\",\n ...alternatives(metadata.main),\n ...alternatives(metadata[\"module\"]),\n ...alternatives(metadata[\"browser\"]),\n ...alternatives(metadata[\"jsnext:main\"]),\n ...alternatives(metadata[\"jsnext\"]),\n ];\n const exports = metadata.exports;\n const subpaths =\n exports !== null &&\n typeof exports === \"object\" &&\n Object.keys(exports).some((key) => key.startsWith(\".\"));\n if (!subpaths) paths.push(...alternatives(exports));\n else {\n const parts = specifier.split(\"/\");\n const subpath = parts\n .slice(specifier.startsWith(\"@\") ? 2 : 1)\n .join(\"/\");\n for (const key of new Set([\n \".\",\n ...(subpath ? [`./${subpath}`] : []),\n ])) {\n paths.push(\n ...matchingTargets(exports, key).flatMap(({ targets }) => targets),\n );\n }\n }\n for (const target of paths) {\n // Legacy main fields are filesystem paths; URL-based loaders also decode them.\n targets.add(toPosix(relative(root, resolve(dir, target))));\n try {\n const url = new URL(target, pathToFileURL(dir + sep));\n if (url.protocol === \"file:\") {\n targets.add(toPosix(relative(root, fileURLToPath(url))));\n }\n } catch {\n // A literal filename need not be a valid URL.\n }\n }\n }\n return [...targets];\n };\n return { imports, entries };\n}\n","import { realpathSync } from \"node:fs\";\nimport { basename, join, posix, relative } from \"node:path\";\nimport { ts } from \"ts-morph\";\nimport { packageModuleTargets } from \"./package-module-targets.js\";\nimport { readProjectFiles, toPosix } from \"./project-files.js\";\n\nconst CODE_FILE = /\\.[cm]?[jt]sx?$/;\n\nexport type ProjectModuleReference = {\n readonly file: string;\n readonly specifier: string;\n /**\n * Some use of the specifier reads the module whole: a namespace import,\n * `export *`, or any use outside an import or export declaration, such as\n * a dynamic import.\n */\n readonly whole: boolean;\n readonly targets: readonly {\n readonly path: string;\n readonly throughPackage: boolean;\n }[];\n};\n\n/** Static module targets, including every package condition and redirected subpath. */\nexport function projectModuleReferences(\n projectDir: string,\n): readonly ProjectModuleReference[] {\n const root = realpathSync(projectDir);\n const configPath = ts.findConfigFile(root, (file) => ts.sys.fileExists(file));\n const configured =\n configPath === undefined\n ? undefined\n : ts.getParsedCommandLineOfConfigFile(\n configPath,\n {},\n {\n ...ts.sys,\n onUnRecoverableConfigFileDiagnostic: (diagnostic) => {\n throw new Error(\n ts.flattenDiagnosticMessageText(diagnostic.messageText, \"\\n\"),\n );\n },\n },\n );\n const options: ts.CompilerOptions = {\n ...configured?.options,\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n resolvePackageJsonImports: true,\n resolvePackageJsonExports: true,\n };\n const resolutions = new Map<\n string,\n {\n file: string | undefined;\n packages: readonly string[];\n }\n >();\n const contents = new Map<string, string | undefined>();\n const packageTargets = packageModuleTargets(root);\n const references: ProjectModuleReference[] = [];\n for (const [sourcePath, bytes] of readProjectFiles(root, CODE_FILE)) {\n const source = ts.createSourceFile(\n sourcePath,\n bytes.toString(\"utf8\"),\n ts.ScriptTarget.Latest,\n true,\n );\n /** Each literal, and whether some use of it reads the module whole. */\n const literals = new Map<string, boolean>();\n const visit = (node: ts.Node) => {\n if (ts.isStringLiteralLike(node)) {\n literals.set(\n node.text,\n (literals.get(node.text) ?? false) || readsWhole(node),\n );\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n for (const [literal, whole] of literals) {\n const targets = new Map<string, boolean>();\n const requests = new Map<string, { from: string; named: string }>();\n const enqueue = (from: string, literal: string) => {\n const unqualified =\n literal.slice(0, 1) + literal.slice(1).split(/[?#]/, 1)[0];\n for (const named of new Set([literal, unqualified])) {\n requests.set(JSON.stringify([from, named]), { from, named });\n try {\n const decoded = decodeURIComponent(named);\n requests.set(JSON.stringify([from, decoded]), {\n from,\n named: decoded,\n });\n } catch {\n // Preserve literals that are not valid URL encodings as written.\n }\n }\n };\n enqueue(sourcePath, literal);\n for (const { from, named } of requests.values()) {\n const isRelative = /^\\.{1,2}\\//.test(named);\n const protect = (target: string, throughPackage = false) => {\n targets.set(target, throughPackage || targets.get(target) === true);\n };\n const protectPackageTarget = (target: string) => {\n protect(target, true);\n const stem = target.replace(CODE_FILE, \"\");\n for (const extension of [\n \"ts\",\n \"tsx\",\n \"mts\",\n \"cts\",\n \"js\",\n \"jsx\",\n \"mjs\",\n \"cjs\",\n ]) {\n protect(`${stem}.${extension}`, true);\n protect(`${stem}/index.${extension}`, true);\n }\n };\n const mapping = packageTargets.imports(from, named);\n for (const redirect of mapping.redirects) {\n enqueue(redirect.from, redirect.specifier);\n }\n for (const target of mapping.targets) {\n protectPackageTarget(target);\n }\n for (const mode of [\n ts.ModuleKind.ESNext,\n ts.ModuleKind.CommonJS,\n ] as const) {\n const key = JSON.stringify([posix.dirname(from), named, mode]);\n let resolution = resolutions.get(key);\n if (resolution === undefined) {\n const consulted = new Set<string>();\n const resolved = ts.resolveModuleName(\n named,\n join(root, from),\n options,\n {\n ...ts.sys,\n readFile: (file) => {\n if (!contents.has(file))\n contents.set(file, ts.sys.readFile(file));\n const text = contents.get(file);\n if (text !== undefined && basename(file) === \"package.json\")\n consulted.add(file);\n return text;\n },\n },\n undefined,\n undefined,\n mode,\n ).resolvedModule;\n resolution = {\n file: resolved?.resolvedFileName,\n packages: [...consulted],\n };\n resolutions.set(key, resolution);\n }\n if (resolution.file !== undefined) {\n protect(toPosix(relative(root, resolution.file)));\n }\n for (const file of resolution.packages) {\n for (const target of packageTargets.entries(file, named))\n protectPackageTarget(target);\n }\n }\n // Keep complete paths even when the project's resolver cannot load them.\n const paths = isRelative\n ? [posix.join(posix.dirname(from), named)]\n : [...named.matchAll(/subgraphs\\//g)].map((match) =>\n named.slice(match.index),\n );\n for (const path of paths) {\n const target = path.replace(CODE_FILE, \"\");\n protect(`${target}.ts`);\n protect(`${target}/index.ts`);\n }\n }\n if (targets.size > 0) {\n references.push({\n file: sourcePath,\n specifier: literal,\n whole,\n targets: [...targets].map(([path, throughPackage]) => ({\n path,\n throughPackage,\n })),\n });\n }\n }\n }\n return references;\n}\n\n/** Whether `literal` reads its module whole, rather than by named bindings. */\nfunction readsWhole(literal: ts.StringLiteralLike): boolean {\n const parent = literal.parent;\n if (ts.isImportDeclaration(parent)) {\n const bindings = parent.importClause?.namedBindings;\n return bindings !== undefined && ts.isNamespaceImport(bindings);\n }\n if (ts.isExportDeclaration(parent)) {\n return (\n parent.exportClause === undefined ||\n ts.isNamespaceExport(parent.exportClause)\n );\n }\n return true;\n}\n","import { projectModuleReferences } from \"./project-module-references.js\";\n\n/** Readers outside the relative import graph that codegen can rewrite. */\nexport function subgraphReaders(projectDir: string): {\n /** Subgraph files read from outside their directory. */\n readonly imported: ReadonlySet<string>;\n /** Those of them some outside reader reads whole. */\n readonly readWhole: ReadonlySet<string>;\n} {\n const found = new Set<string>();\n const whole = new Set<string>();\n for (const reference of projectModuleReferences(projectDir)) {\n const isRelative = /^\\.{1,2}\\//.test(reference.specifier);\n for (const target of reference.targets) {\n const parts = target.path.split(\"/\");\n const [top, name] = parts;\n if (top !== \"subgraphs\" || parts.length < 2) continue;\n if (\n !target.throughPackage &&\n isRelative &&\n reference.file.startsWith(`subgraphs/${name}/`)\n )\n continue;\n found.add(target.path);\n if (reference.whole) whole.add(target.path);\n }\n }\n return { imported: found, readWhole: whole };\n}\n","import {\n castResolverTypeErrors,\n migrateSubgraph,\n type ProjectTypeCheck,\n type ProjectTypeError,\n projectTypeErrors,\n resolverCallErrors,\n type ResolverTypeError,\n typeErrorMessage,\n sortedSchemaText,\n type SubgraphMigration,\n} from \"@powerhousedao/codegen\";\nimport {\n subgraphDirStyles,\n uncachedDefinitionSourceRevision,\n ViteTypeScriptSourceImportAdapter,\n} from \"@powerhousedao/codegen/utils\";\nimport { projectSubgraphGraphQL } from \"document-model\";\nimport { readSubgraphDefinitions } from \"document-model/tooling\";\nimport type { DocumentNode } from \"graphql\";\nimport { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { outdatedDependency } from \"./installed-version.js\";\nimport { definitionChecks } from \"./model/check.js\";\nimport { readProjectDefinitions } from \"./model/project.js\";\nimport {\n assertChangesWritable,\n errorText,\n type FileBackup,\n restoreChanges,\n writeChanges,\n} from \"./project-files.js\";\nimport { subgraphReaders } from \"./subgraph-readers.js\";\n\n/** A module that hangs on a top-level await must not hang `ph migrate`. */\nconst IMPORT_TIMEOUT_MS = 60_000;\nconst SCALARS_ENTRY = \"scalars/index.ts\";\nconst SOURCE_FILE = /\\.(?:[cm]?[jt]sx?|graphql)$/;\n\nexport type MigrateSubgraphsOptions = {\n readonly projectDir: string;\n /** The `subgraphs/` directories to convert; empty converts every schema-first one. */\n readonly dirs: readonly string[];\n readonly dryRun: boolean;\n /** Leave the resolver calls tsc rejects without a cast. */\n readonly strictResolvers?: boolean;\n readonly out?: (text: string) => void;\n};\n\ntype Verification =\n | { readonly ok: true }\n | { readonly ok: false; readonly reason: string };\n\n/**\n * `ph migrate --subgraphs`: converts schema-first subgraphs into code-first\n * ones. Each written directory is loaded as `ph model check` loads it and\n * must serve the schema it served before; otherwise its files are restored.\n * Without named directories, a directory whose `index.ts` holds no class is\n * skipped. Returns the exit code: 0 when every requested subgraph converted\n * or was already code-first, 1 otherwise.\n */\nexport async function migrateSubgraphs(\n options: MigrateSubgraphsOptions,\n): Promise<0 | 1> {\n const out =\n options.out ?? ((text: string) => void process.stdout.write(text));\n const { projectDir, dryRun } = options;\n let outdated = outdatedDependency(projectDir, \"@powerhousedao/reactor-api\");\n /** The composition errors `ph model check` reported before this run converted anything. */\n let composition: ReadonlySet<string> | undefined;\n /** What the project's tsc reported in the subgraphs before this run wrote anything. */\n let typeBaseline: ProjectTypeCheck | undefined;\n const outsideReaders = subgraphReaders(projectDir);\n const styles = new Map(\n subgraphDirStyles(join(projectDir, \"subgraphs\")).map(\n ({ dirName, style }) => [dirName, style] as const,\n ),\n );\n let failed = false;\n let schemaFirst = 0;\n const named = options.dirs.length > 0;\n const requested = named ? options.dirs : [...styles.keys()];\n const converted: string[] = [];\n const importer = new ViteTypeScriptSourceImportAdapter();\n const revision = uncachedDefinitionSourceRevision();\n try {\n for (const dirName of requested) {\n const label = `subgraphs/${dirName}`;\n const style = styles.get(dirName);\n if (style === undefined) {\n out(\n `${label}: not found. Name a directory of subgraphs/ that has an index.ts.\\n`,\n );\n failed = true;\n continue;\n }\n if (style === \"code-first\") {\n out(`${label}: already code-first\\n`);\n continue;\n }\n const originals = readDirectory(projectDir, dirName);\n let written: FileBackup | undefined;\n try {\n const migration = await migrateSubgraph({\n dirName,\n files: new Map(\n [...originals].map(([path, bytes]) => [\n path,\n bytes.toString(\"utf8\"),\n ]),\n ),\n importedFromOutside: outsideReaders.imported,\n readWholeFromOutside: outsideReaders.readWhole,\n });\n if (migration.kind === \"no-subgraph-class\" && !named) {\n out(`${label}: no subgraph class, skipped\\n`);\n continue;\n }\n schemaFirst++;\n if (migration.kind !== \"converted\") {\n out(refusalText(label, migration));\n failed = true;\n continue;\n }\n if (dryRun) {\n assertChangesWritable(projectDir, migration.files);\n out(`${label}: would convert ${migration.className} to code-first\\n`);\n for (const file of migration.files) out(unifiedDiff(file));\n continue;\n }\n if (outdated !== undefined) {\n out(`${label}: not converted. ${outdated}\\n`);\n outdated = \"@powerhousedao/reactor-api is too old, as above.\";\n failed = true;\n continue;\n }\n // What the host already refuses, read before this run writes anything.\n composition ??= await compositionErrors(projectDir, new Set());\n typeBaseline ??= projectTypeErrors(\n projectDir,\n requested.map((name) => `subgraphs/${name}`),\n [],\n );\n try {\n written = writeChanges(projectDir, migration.files);\n } catch (error) {\n out(\n `${label}: not converted; its files are restored. Writing them failed: ${errorText(error)}\\n`,\n );\n failed = true;\n continue;\n }\n let verification = await verify(\n projectDir,\n migration,\n importer,\n revision,\n );\n if (verification.ok) {\n const added = await compositionErrors(projectDir, composition);\n if (added.size > 0) {\n verification = {\n ok: false,\n reason: `The host would not serve the package's code-first subgraphs together:\\n${[...added].map((error) => ` ${error}`).join(\"\\n\")}\\nRename the conflicting types in one of the subgraphs, then migrate again.`,\n };\n }\n }\n if (!verification.ok) {\n restoreChanges(projectDir, written);\n out(\n `${label}: not converted; its files are restored. ${verification.reason}\\n`,\n );\n failed = true;\n continue;\n }\n converted.push(dirName);\n out(\n `${label}: converted ${migration.className} to code-first; it serves the same schema\\n`,\n );\n for (const note of migration.notes) out(`Note: ${note}\\n`);\n if (migration.sdlFile.endsWith(\"/schema.graphql\")) {\n out(\n `${migration.sdlFile} is no longer used; the schema is now in ${label}/schema.ts. It was kept, and you can delete it.\\n`,\n );\n }\n } catch (error) {\n if (written !== undefined) restoreChanges(projectDir, written);\n out(\n `${label}: not converted; its files are ${written === undefined ? \"unchanged\" : \"restored\"}. The conversion failed unexpectedly: ${errorText(error)}\\n`,\n );\n failed = true;\n }\n }\n } finally {\n await importer.disposeRevision();\n }\n if (converted.length > 0) {\n out(\n await typeReport(\n projectDir,\n converted,\n options.strictResolvers ?? false,\n typeBaseline,\n ),\n );\n }\n if (!named && schemaFirst === 0) {\n out(\"No schema-first subgraphs to convert.\\n\");\n }\n return failed ? 1 : 0;\n}\n\n/**\n * The converted resolvers TypeScript rejects. The schema-first resolver map\n * never checked a resolver's types against the schema; each converted entry\n * calls its resolver with the schema's types, so a disagreement is now a\n * type error. Unless `strict`, each rejected call is cast where it fails, so\n * it runs as before and the project compiles. Any other error the\n * conversion added to the subgraphs, against `baseline`, is reported too.\n */\nasync function typeReport(\n projectDir: string,\n converted: readonly string[],\n strict: boolean,\n baseline: ProjectTypeCheck | undefined,\n): Promise<string> {\n const dirs = converted.map((dirName) => `subgraphs/${dirName}`);\n const indexPaths = dirs.map((dir) => `${dir}/index.ts`);\n const check = () => projectTypeErrors(projectDir, dirs, indexPaths);\n const first = check();\n if (first.kind === \"untyped\") return \"\";\n if (first.kind === \"skipped\") {\n return `Note: the converted resolvers were not type-checked: ${first.reason}.\\n`;\n }\n const list = (shown: readonly ResolverTypeError[]) =>\n shown\n .map(\n ({ file, line, coordinate, message }) =>\n ` ${file}:${line} ${coordinate}: ${message}\\n`,\n )\n .join(\"\");\n const calls = resolverCallErrors(projectDir, indexPaths, first.errors);\n let report = \"\";\n let final = first;\n if (calls.length > 0) {\n const count = `${calls.length === 1 ? \"1 resolver call disagrees\" : `${calls.length} resolver calls disagree`} with the schema the subgraph serves`;\n if (strict) {\n report += `Note: ${count}, so TypeScript rejects ${calls.length === 1 ? \"it\" : \"them\"}. The schema-first map never checked them; fix each resolver's types:\\n${list(calls)}`;\n } else {\n writeChanges(projectDir, await castResolverTypeErrors(projectDir, calls));\n let after = check();\n if (\n after.kind === \"checked\" &&\n calls.some(({ message }) =>\n /^Expected (?:\\d+-)?\\d+ arguments?, but got \\d+\\./.test(message),\n )\n ) {\n const exposed = resolverCallErrors(\n projectDir,\n indexPaths,\n after.errors,\n );\n if (exposed.length > 0) {\n writeChanges(\n projectDir,\n await castResolverTypeErrors(projectDir, exposed),\n );\n calls.push(...exposed);\n after = check();\n }\n }\n if (after.kind === \"checked\") final = after;\n const left = resolverCallErrors(projectDir, indexPaths, final.errors);\n report += `Note: ${count}. The schema-first map never checked them; each call is cast where TypeScript rejects it, under a \"ph migrate:\" comment, so it runs as before and the project compiles. Fix each resolver's types, then remove its cast:\\n${list(calls)}`;\n if (left.length > 0) {\n report += `Note: ${left.length === 1 ? \"1 resolver call is\" : `${left.length} resolver calls are`} still rejected after the casts; fix ${left.length === 1 ? \"it\" : \"them\"} by hand:\\n${list(left)}`;\n }\n }\n }\n // Errors besides the resolver calls that were not there before.\n if (baseline?.kind === \"checked\") {\n const key = (error: ProjectTypeError) =>\n `${error.file.split(\"/\").slice(0, 2).join(\"/\")}|${error.lines.join(\"|\")}`;\n const before = new Map<string, number>();\n for (const error of baseline.errors) {\n before.set(key(error), (before.get(key(error)) ?? 0) + 1);\n }\n const inSchema = new Set(\n resolverCallErrors(projectDir, indexPaths, final.errors).map(\n ({ file, line, column }) => `${file}:${line}:${column}`,\n ),\n );\n const introduced = final.errors.filter((error) => {\n if (inSchema.has(`${error.file}:${error.line}:${error.column}`)) {\n return false;\n }\n const remaining = before.get(key(error)) ?? 0;\n if (remaining > 0) {\n before.set(key(error), remaining - 1);\n return false;\n }\n return true;\n });\n if (introduced.length > 0) {\n report += `Note: the conversion added ${introduced.length === 1 ? \"1 type error\" : `${introduced.length} type errors`} besides the resolver calls. That is a bug in ph migrate; please report it, and fix ${introduced.length === 1 ? \"it\" : \"them\"} by hand:\\n${introduced\n .map(\n (error) =>\n ` ${error.file}:${error.line}: ${typeErrorMessage(error)}\\n`,\n )\n .join(\"\")}`;\n }\n }\n return report;\n}\n\n/** The directory's files and `scalars/index.ts`, by project-relative path. */\nfunction readDirectory(\n projectDir: string,\n dirName: string,\n): ReadonlyMap<string, Buffer> {\n const files = new Map<string, Buffer>();\n const dir = join(projectDir, \"subgraphs\", dirName);\n for (const entry of readdirSync(dir, {\n recursive: true,\n withFileTypes: true,\n })) {\n if (!entry.isFile() || !SOURCE_FILE.test(entry.name)) continue;\n const path = join(entry.parentPath, entry.name);\n files.set(\n path.slice(projectDir.length + 1).replaceAll(\"\\\\\", \"/\"),\n readFileSync(path),\n );\n }\n const scalars = join(projectDir, SCALARS_ENTRY);\n if (existsSync(scalars)) files.set(SCALARS_ENTRY, readFileSync(scalars));\n return files;\n}\n\nasync function withTimeout<T>(work: Promise<T>, timeoutMs: number): Promise<T> {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () =>\n reject(\n new Error(\n `it did not finish loading within ${timeoutMs / 1000} seconds`,\n ),\n ),\n timeoutMs,\n );\n timer.unref();\n });\n try {\n return await Promise.race([work, timeout]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * The subgraph composition errors `ph model check` reports for the project,\n * leaving out those in `known`. Converted subgraphs are composed with each\n * other: a type two of them declare differently keeps one out of the host.\n */\nasync function compositionErrors(\n projectDir: string,\n known: ReadonlySet<string>,\n): Promise<Set<string>> {\n const report = await readProjectDefinitions(projectDir, (project, modules) =>\n definitionChecks.edit(project, modules),\n );\n return new Set(\n report.diagnostics\n .filter(\n ({ severity, phase }) =>\n severity === \"error\" && phase === \"composition\",\n )\n .map(({ message }) => message)\n .filter((message) => !known.has(message)),\n );\n}\n\n/** Loads the written class without constructing it and compares the schema it serves. */\nasync function verify(\n projectDir: string,\n migration: Extract<SubgraphMigration, { kind: \"converted\" }>,\n importer: ViteTypeScriptSourceImportAdapter,\n revision: ReturnType<typeof uncachedDefinitionSourceRevision>,\n): Promise<Verification> {\n const specifier = `./subgraphs/${migration.dirName}/index.ts` as const;\n let namespace: Readonly<Record<string, unknown>>;\n try {\n namespace = await withTimeout(\n importer.importModule({\n packageRoot: projectDir,\n specifier,\n packageRevision: revision,\n }),\n IMPORT_TIMEOUT_MS,\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n ok: false,\n reason: `The converted module does not load: ${message.replaceAll(projectDir, \".\")}`,\n };\n }\n const { subgraphs, diagnostics } = readSubgraphDefinitions(namespace, {\n specifier,\n });\n const errors = diagnostics.filter(({ severity }) => severity === \"error\");\n if (errors.length > 0) {\n return {\n ok: false,\n reason: `The converted subgraph does not compile:\\n${errors.map(({ message, repair }) => ` ${message} ${repair}`).join(\"\\n\")}`,\n };\n }\n const subgraph = subgraphs.find(\n ({ name }) => name === migration.subgraphName,\n );\n if (subgraph === undefined) {\n return {\n ok: false,\n reason: `${specifier} exports no code-first subgraph named ${migration.subgraphName}.`,\n };\n }\n const served = sortedSchemaText(\n projectSubgraphGraphQL(subgraph.definition) as unknown as DocumentNode,\n );\n if (served === migration.sdl) return { ok: true };\n return {\n ok: false,\n reason: `The converted subgraph serves a different schema:\\n${unifiedDiff({\n path: \"schema\",\n before: migration.sdl,\n after: served,\n })}`,\n };\n}\n\nfunction refusalText(\n label: string,\n migration: Extract<\n SubgraphMigration,\n { kind: \"refused\" | \"no-subgraph-class\" }\n >,\n): string {\n return `${label}: not converted\\n${migration.refusals\n .map(\n ({ file, line, reason, repair }) =>\n ` ${file}:${line}: ${reason}\\n ${repair}\\n`,\n )\n .join(\"\")}`;\n}\n\ntype Line = { readonly kind: \" \" | \"-\" | \"+\"; readonly text: string };\n\n/** The line edits from `before` to `after`, by longest common subsequence. */\nfunction lineEdits(\n before: readonly string[],\n after: readonly string[],\n): Line[] {\n const common: number[][] = Array.from({ length: before.length + 1 }, () =>\n new Array<number>(after.length + 1).fill(0),\n );\n for (let i = before.length - 1; i >= 0; i--) {\n for (let j = after.length - 1; j >= 0; j--) {\n common[i][j] =\n before[i] === after[j]\n ? common[i + 1][j + 1] + 1\n : Math.max(common[i + 1][j], common[i][j + 1]);\n }\n }\n const lines: Line[] = [];\n let i = 0;\n let j = 0;\n while (i < before.length || j < after.length) {\n if (i < before.length && j < after.length && before[i] === after[j]) {\n lines.push({ kind: \" \", text: before[i++] });\n j++;\n } else if (\n i < before.length &&\n (j === after.length || common[i + 1][j] >= common[i][j + 1])\n ) {\n lines.push({ kind: \"-\", text: before[i++] });\n } else {\n lines.push({ kind: \"+\", text: after[j++] });\n }\n }\n return lines;\n}\n\nconst CONTEXT = 3;\n\n/** A unified diff of one file; a new file diffs against /dev/null. */\nexport function unifiedDiff(file: {\n readonly path: string;\n readonly before: string | null;\n readonly after: string | null;\n}): string {\n const split = (text: string) =>\n text === \"\" ? [] : text.replace(/\\n$/, \"\").split(\"\\n\");\n const lines = lineEdits(split(file.before ?? \"\"), split(file.after ?? \"\"));\n const changed = lines.flatMap((line, index) =>\n line.kind === \" \" ? [] : [index],\n );\n if (changed.length === 0) return \"\";\n const hunks: [number, number][] = [];\n for (const index of changed) {\n const start = Math.max(0, index - CONTEXT);\n const end = Math.min(lines.length, index + CONTEXT + 1);\n const last = hunks.at(-1);\n if (last !== undefined && start <= last[1]) last[1] = end;\n else hunks.push([start, end]);\n }\n const header = `--- ${file.before === null ? \"/dev/null\" : `a/${file.path}`}\\n+++ ${file.after === null ? \"/dev/null\" : `b/${file.path}`}\\n`;\n return (\n header +\n hunks\n .map(([start, end]) => {\n const lineBefore = (kind: Line[\"kind\"]) =>\n lines.slice(0, start).filter((line) => line.kind !== kind).length;\n const slice = lines.slice(start, end);\n const count = (kind: Line[\"kind\"]) =>\n slice.filter((line) => line.kind !== kind).length;\n const oldCount = count(\"+\");\n const newCount = count(\"-\");\n const oldStart = oldCount === 0 ? lineBefore(\"+\") : lineBefore(\"+\") + 1;\n const newStart = newCount === 0 ? lineBefore(\"-\") : lineBefore(\"-\") + 1;\n return `@@ -${oldStart},${oldCount} +${newStart},${newCount} @@\\n${slice\n .map((line) => `${line.kind}${line.text}`)\n .join(\"\\n\")}\\n`;\n })\n .join(\"\")\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAMA,SAAS,iBACP,YACA,aACoB;CACpB,KAAK,IAAI,MAAM,aAAc,MAAM,QAAQ,GAAG,GAAG;EAC/C,MAAM,WAAW,KAAK,KAAK,gBAAgB,aAAa,cAAc;EACtE,IAAI,WAAW,QAAQ,GAAG;GACxB,MAAM,EAAE,YAAY,KAAK,MAAM,aAAa,UAAU,MAAM,CAAC;GAG7D,OAAO,OAAO,YAAY,WAAW,UAAU,KAAA;EACjD;EACA,IAAI,QAAQ,GAAG,MAAM,KAAK,OAAO,KAAA;CACnC;AACF;;;;;;AAOA,SAAgB,mBACd,YACA,aACoB;CACpB,MAAM,WAAW,WAAW;CAC5B,IAAI,MAAM,QAAQ,MAAM,MAAM,OAAO,KAAA;CACrC,MAAM,YAAY,iBAAiB,YAAY,WAAW;CAC1D,IAAI,cAAc,KAAA,GAChB,OAAO,GAAG,YAAY;CAExB,IAAI,MAAM,SAAS,MAAM,QAAQ,CAAC,GAAG,WAAW,QAAQ,GAAG,OAAO,KAAA;CAClE,OAAO,oBAAoB,YAAY,GAAG,UAAU,0DAA0D,SAAS,4BAA4B,SAAS;AAC9J;;;;ACzBA,MAAM,+BAAe,IAAI,IAAI;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAa,WAAW,SAAiB,KAAK,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;AAEjE,MAAa,aAAa,UACxB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;;A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C;CACA,IAAI,QAAQ,WAAW,GAAG,OAAO;CACjC,MAAM,QAA4B,CAAC;CACnC,KAAK,MAAM,SAAS,SAAS;EAC3B,MAAM,QAAQ,KAAK,IAAI,GAAG,QAAQ,OAAO;EACzC,MAAM,MAAM,KAAK,IAAI,MAAM,QAAQ,QAAQ,UAAU,CAAC;EACtD,MAAM,OAAO,MAAM,GAAG,EAAE;EACxB,IAAI,SAAS,KAAA,KAAa,SAAS,KAAK,IAAI,KAAK,KAAK;OACjD,MAAM,KAAK,CAAC,OAAO,GAAG,CAAC;CAC9B;CAEA,OACE,OAFoB,KAAK,WAAW,OAAO,cAAc,KAAK,KAAK,OAAO,QAAQ,KAAK,UAAU,OAAO,cAAc,KAAK,KAAK,OAAO,MAGvI,MACG,KAAK,CAAC,OAAO,SAAS;EACrB,MAAM,cAAc,SAClB,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,QAAQ,SAAS,KAAK,SAAS,IAAI,CAAC,CAAC;EAC7D,MAAM,QAAQ,MAAM,MAAM,OAAO,GAAG;EACpC,MAAM,SAAS,SACb,MAAM,QAAQ,SAAS,KAAK,SAAS,IAAI,CAAC,CAAC;EAC7C,MAAM,WAAW,MAAM,GAAG;EAC1B,MAAM,WAAW,MAAM,GAAG;EAG1B,OAAO,OAFU,aAAa,IAAI,WAAW,GAAG,IAAI,WAAW,GAAG,IAAI,EAE/C,GAAG,SAAS,IADlB,aAAa,IAAI,WAAW,GAAG,IAAI,WAAW,GAAG,IAAI,EACtB,GAAG,SAAS,OAAO,MAChE,KAAK,SAAS,GAAG,KAAK,OAAO,KAAK,MAAM,CAAC,CACzC,KAAK,IAAI,EAAE;CAChB,CAAC,CAAC,CACD,KAAK,EAAE;AAEd","debug_id":"895c0741-3cff-5538-907b-b9dd892f93a7"}
@@ -1,4 +0,0 @@
1
- import { t as migrateSubgraphs } from "./migrate-subgraphs-CGIPAnQB.mjs";
2
- export { migrateSubgraphs };
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]="f69c24b1-981a-597f-a732-fb896479b890")}catch(e){}}();
4
- //# debugId=f69c24b1-981a-597f-a732-fb896479b890