@rebasepro/cli 0.31.0-canary.g902a0ce → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-setup-DqAcoDcn.js → agent-setup-Cg_zBWoW.js} +3 -3
- package/dist/{agent-setup-DqAcoDcn.js.map → agent-setup-Cg_zBWoW.js.map} +1 -1
- package/dist/api-TbmW33D7.js +275 -0
- package/dist/api-TbmW33D7.js.map +1 -0
- package/dist/{api-keys-eIUjMqWn.js → api-keys-fPQ55DCm.js} +151 -158
- package/dist/api-keys-fPQ55DCm.js.map +1 -0
- package/dist/{apps-DExO4PEl.js → apps-DBTRoOeP.js} +18 -13
- package/dist/apps-DBTRoOeP.js.map +1 -0
- package/dist/{args-CaCcrYE1.js → args-DHyrshtI.js} +3 -132
- package/dist/args-DHyrshtI.js.map +1 -0
- package/dist/{atlas-dev-database-DOCKk6ht.js → atlas-dev-database-D6h65f2x.js} +3 -3
- package/dist/{atlas-dev-database-DOCKk6ht.js.map → atlas-dev-database-D6h65f2x.js.map} +1 -1
- package/dist/{auth-CyADghFQ.js → auth-BpyYLEFY.js} +93 -12
- package/dist/auth-BpyYLEFY.js.map +1 -0
- package/dist/auth-session-B6aT0Dyj.js +371 -0
- package/dist/auth-session-B6aT0Dyj.js.map +1 -0
- package/dist/{backend-guard-C0mVkXBw.js → backend-guard-Cf8eMK_f.js} +2 -2
- package/dist/{backend-guard-C0mVkXBw.js.map → backend-guard-Cf8eMK_f.js.map} +1 -1
- package/dist/{branch-pointer-DMPyvZoK.js → branch-pointer-BJOF2Ubv.js} +1 -1
- package/dist/{build-CA5R07tw.js → build-BfdT-AUR.js} +12 -10
- package/dist/{build-CA5R07tw.js.map → build-BfdT-AUR.js.map} +1 -1
- package/dist/{bundle-DgILeA5b.js → bundle-CIiKGrte.js} +78 -12
- package/dist/bundle-CIiKGrte.js.map +1 -0
- package/dist/bundle.d.ts +31 -1
- package/dist/{cloud-CYMk92iG.js → cloud-MqnyPnmX.js} +1540 -1531
- package/dist/cloud-MqnyPnmX.js.map +1 -0
- package/dist/{cms-directories-BK3vcswg.js → cms-directories-BaV-Is9a.js} +2 -2
- package/dist/{cms-directories-BK3vcswg.js.map → cms-directories-BaV-Is9a.js.map} +1 -1
- package/dist/codemod/collections-to-tables/backend.d.ts +0 -2
- package/dist/codemod/collections-to-tables/customization.d.ts +2 -1
- package/dist/codemod/collections-to-tables/modules.d.ts +32 -0
- package/dist/codemod/collections-to-tables/plan-context.d.ts +7 -1
- package/dist/{command-D5lhW_-B.js → command-D9g46gg9.js} +68 -42
- package/dist/command-D9g46gg9.js.map +1 -0
- package/dist/commands/api-keys.d.ts +89 -52
- package/dist/commands/api.d.ts +114 -0
- package/dist/commands/auth-session.d.ts +94 -0
- package/dist/commands/auth.d.ts +1 -1
- package/dist/commands/cloud/alerts.d.ts +29 -0
- package/dist/commands/cloud/context.d.ts +8 -0
- package/dist/commands/cloud/debug.d.ts +16 -1
- package/dist/commands/cloud/deploy-hooks.d.ts +19 -0
- package/dist/commands/cloud/deploy.d.ts +25 -0
- package/dist/commands/cloud/env.d.ts +1 -0
- package/dist/commands/cloud/index.d.ts +5 -0
- package/dist/commands/cloud/maintenance.d.ts +26 -1
- package/dist/commands/cloud/not-served.d.ts +27 -0
- package/dist/commands/cloud/orgs.d.ts +5 -0
- package/dist/commands/cloud/resources.d.ts +82 -2
- package/dist/commands/cloud/runtime-logs.d.ts +57 -0
- package/dist/commands/cloud/settings.d.ts +3 -0
- package/dist/commands/cron.d.ts +68 -0
- package/dist/commands/data.d.ts +197 -0
- package/dist/commands/functions.d.ts +38 -0
- package/dist/commands/logs.d.ts +22 -0
- package/dist/commands/rls.d.ts +31 -0
- package/dist/commands/schema-reconcile.d.ts +2 -1
- package/dist/commands/schema-show.d.ts +38 -0
- package/dist/commands/storage-objects.d.ts +88 -0
- package/dist/commands/storage.d.ts +18 -2
- package/dist/commands/users.d.ts +147 -0
- package/dist/{consent-BXLIrMl8.js → consent-UV6ObCME.js} +2 -2
- package/dist/{consent-BXLIrMl8.js.map → consent-UV6ObCME.js.map} +1 -1
- package/dist/{console-CMjhgMUE.js → console-BVoYOLAO.js} +6 -6
- package/dist/{console-CMjhgMUE.js.map → console-BVoYOLAO.js.map} +1 -1
- package/dist/{context--JwaHaZp.js → context-BOMEoKxn.js} +80 -9
- package/dist/{context--JwaHaZp.js.map → context-BOMEoKxn.js.map} +1 -1
- package/dist/cron-CpUsQ739.js +298 -0
- package/dist/cron-CpUsQ739.js.map +1 -0
- package/dist/cron-ZRXsla0v.js +259 -0
- package/dist/cron-ZRXsla0v.js.map +1 -0
- package/dist/{daemon-w30PsdwV.js → daemon-D5gdG7gx.js} +3 -3
- package/dist/{daemon-w30PsdwV.js.map → daemon-D5gdG7gx.js.map} +1 -1
- package/dist/{daemon-entry-zOC1revO.js → daemon-entry--ummUJnk.js} +2 -2
- package/dist/{daemon-entry-zOC1revO.js.map → daemon-entry--ummUJnk.js.map} +1 -1
- package/dist/data-BJ9AZFUC.js +947 -0
- package/dist/data-BJ9AZFUC.js.map +1 -0
- package/dist/{db-A7XDCIIO.js → db-D_iF4E-v.js} +60 -36
- package/dist/db-D_iF4E-v.js.map +1 -0
- package/dist/debug-nNbbxAeo.js +1114 -0
- package/dist/debug-nNbbxAeo.js.map +1 -0
- package/dist/{derive-C3ezmY-p.js → derive-Mky_u59_.js} +3 -3
- package/dist/{derive-C3ezmY-p.js.map → derive-Mky_u59_.js.map} +1 -1
- package/dist/{dev-tWwPyWkQ.js → dev-bj6dEeSQ.js} +13 -13
- package/dist/{dev-tWwPyWkQ.js.map → dev-bj6dEeSQ.js.map} +1 -1
- package/dist/dev-db/__fixtures__/unanswering-postgres.d.ts +11 -0
- package/dist/dev-db/attver.d.ts +38 -6
- package/dist/dev-db/local-timeouts.d.ts +25 -0
- package/dist/dev-db/pull.d.ts +49 -9
- package/dist/{dev-preflight-DjvcV6SK.js → dev-preflight-BMOf2N6r.js} +2 -2
- package/dist/{dev-preflight-DjvcV6SK.js.map → dev-preflight-BMOf2N6r.js.map} +1 -1
- package/dist/{dev-server-BLxCbQEP.js → dev-server-2XHSHM_q.js} +2 -2
- package/dist/{dev-server-BLxCbQEP.js.map → dev-server-2XHSHM_q.js.map} +1 -1
- package/dist/{doctor-BBM0dWvZ.js → doctor-2Jlau0Rm.js} +9 -8
- package/dist/{doctor-BBM0dWvZ.js.map → doctor-2Jlau0Rm.js.map} +1 -1
- package/dist/{eject-Bhzd6hgb.js → eject-DK_M9kor.js} +4 -4
- package/dist/{eject-Bhzd6hgb.js.map → eject-DK_M9kor.js.map} +1 -1
- package/dist/{fold-static-CKewnAPX.js → fold-static-2t3UUX4z.js} +10 -6
- package/dist/fold-static-2t3UUX4z.js.map +1 -0
- package/dist/fold-static.d.ts +7 -0
- package/dist/functions-B4JR6EZL.js +120 -0
- package/dist/functions-B4JR6EZL.js.map +1 -0
- package/dist/{generate-view-CTOluXvH.js → generate-view-BMaLQm8H.js} +5 -5
- package/dist/{generate-view-CTOluXvH.js.map → generate-view-BMaLQm8H.js.map} +1 -1
- package/dist/{generate_sdk-De-aLC1L.js → generate_sdk-ByD-gTsK.js} +7 -7
- package/dist/{generate_sdk-De-aLC1L.js.map → generate_sdk-ByD-gTsK.js.map} +1 -1
- package/dist/index.es.js +123 -47
- package/dist/index.es.js.map +1 -1
- package/dist/{init-Dtl-IcXf.js → init-DHCe5mJ5.js} +59 -11
- package/dist/init-DHCe5mJ5.js.map +1 -0
- package/dist/{invoked-command-CG_rIa_o.js → invoked-command-FBeIBS8o.js} +2 -2
- package/dist/{invoked-command-CG_rIa_o.js.map → invoked-command-FBeIBS8o.js.map} +1 -1
- package/dist/last-dev-database-CBVkEUEl.js +2 -0
- package/dist/local-timeouts-B1Kwligw.js +30 -0
- package/dist/local-timeouts-B1Kwligw.js.map +1 -0
- package/dist/logs-CIgfLBsu.js +192 -0
- package/dist/logs-CIgfLBsu.js.map +1 -0
- package/dist/{manifest-C3uLDrrJ.js → manifest-RjqxfCpb.js} +114 -5
- package/dist/manifest-RjqxfCpb.js.map +1 -0
- package/dist/{migrate-VrKoi3nB.js → migrate-Cx8-Y4TG.js} +5 -4
- package/dist/{migrate-VrKoi3nB.js.map → migrate-Cx8-Y4TG.js.map} +1 -1
- package/dist/{normalize-imports-DwxqEMYq.js → normalize-imports-P86NVfpo.js} +3 -3
- package/dist/{normalize-imports-DwxqEMYq.js.map → normalize-imports-P86NVfpo.js.map} +1 -1
- package/dist/{path-flags-7O5uPBcQ.js → path-flags-ekLdkbra.js} +3 -3
- package/dist/{path-flags-7O5uPBcQ.js.map → path-flags-ekLdkbra.js.map} +1 -1
- package/dist/{prepare-Ccxspoj-.js → prepare-BaJe0Zik.js} +4 -4
- package/dist/{prepare-Ccxspoj-.js.map → prepare-BaJe0Zik.js.map} +1 -1
- package/dist/{project-CLcF5i8c.js → project-DALmhb5R.js} +2 -2
- package/dist/{project-CLcF5i8c.js.map → project-DALmhb5R.js.map} +1 -1
- package/dist/project-command-Cl9EZzjr.js +662 -0
- package/dist/project-command-Cl9EZzjr.js.map +1 -0
- package/dist/{project-schema-CsSOG2gE.js → project-schema-Dm6Jk0Y_.js} +4 -2
- package/dist/{project-schema-CsSOG2gE.js.map → project-schema-Dm6Jk0Y_.js.map} +1 -1
- package/dist/{pull-D9WvpDYY.js → pull-CTIsST6T.js} +336 -55
- package/dist/pull-CTIsST6T.js.map +1 -0
- package/dist/resolve-C36px9tR.js +2 -0
- package/dist/{resources-Dpfs2y8P.js → resources-Db3USuPO.js} +5 -5
- package/dist/{resources-Dpfs2y8P.js.map → resources-Db3USuPO.js.map} +1 -1
- package/dist/rls-BxrQ0P50.js +133 -0
- package/dist/rls-BxrQ0P50.js.map +1 -0
- package/dist/{schema-DwFDI1iU.js → schema-_FzZEoB8.js} +54 -40
- package/dist/schema-_FzZEoB8.js.map +1 -0
- package/dist/{schema-dir-Cd1kvYbf.js → schema-dir-ChcYfWjP.js} +2 -2
- package/dist/{schema-dir-Cd1kvYbf.js.map → schema-dir-ChcYfWjP.js.map} +1 -1
- package/dist/schema-reconcile-DV14XY4o.js +2 -0
- package/dist/schema-show-h72UJ9zH.js +127 -0
- package/dist/schema-show-h72UJ9zH.js.map +1 -0
- package/dist/{skills-CXjA9TWw.js → skills-DQ2bZGkj.js} +6 -5
- package/dist/{skills-CXjA9TWw.js.map → skills-DQ2bZGkj.js.map} +1 -1
- package/dist/star-nudge.d.ts +28 -0
- package/dist/{start-Bwbtt2W5.js → start-Cjx4W0bJ.js} +7 -7
- package/dist/{start-Bwbtt2W5.js.map → start-Cjx4W0bJ.js.map} +1 -1
- package/dist/{status-DQ_PPz4C.js → status-CDBk25VO.js} +9 -9
- package/dist/{status-DQ_PPz4C.js.map → status-CDBk25VO.js.map} +1 -1
- package/dist/{storage-iTqj5-Av.js → storage-Clc8dLG8.js} +79 -36
- package/dist/storage-Clc8dLG8.js.map +1 -0
- package/dist/storage-objects-CfRKlTDe.js +279 -0
- package/dist/storage-objects-CfRKlTDe.js.map +1 -0
- package/dist/{telemetry-BP_1Cl9r.js → telemetry-DZU2-NCm.js} +5 -4
- package/dist/{telemetry-BP_1Cl9r.js.map → telemetry-DZU2-NCm.js.map} +1 -1
- package/dist/{telemetry-M3HjlyhZ.js → telemetry-EVtASbKb.js} +2 -2
- package/dist/{telemetry-M3HjlyhZ.js.map → telemetry-EVtASbKb.js.map} +1 -1
- package/dist/unknown-command-DnZ2uhGs.js +139 -0
- package/dist/unknown-command-DnZ2uhGs.js.map +1 -0
- package/dist/{upgrade-oZzJ13jM.js → upgrade-DhpUFb6p.js} +5 -5
- package/dist/{upgrade-oZzJ13jM.js.map → upgrade-DhpUFb6p.js.map} +1 -1
- package/dist/users-5PkqBY6R.js +561 -0
- package/dist/users-5PkqBY6R.js.map +1 -0
- package/dist/utils/project-command.d.ts +38 -0
- package/dist/utils/project-target.d.ts +193 -0
- package/dist/{verify-DkJqhYPI.js → verify-BdeqNb-V.js} +138 -12
- package/dist/verify-BdeqNb-V.js.map +1 -0
- package/dist/{version-Buyyo1ut.js → version-ONIeo7jl.js} +7 -2
- package/dist/{version-Buyyo1ut.js.map → version-ONIeo7jl.js.map} +1 -1
- package/package.json +10 -10
- package/dist/api-keys-eIUjMqWn.js.map +0 -1
- package/dist/apps-DExO4PEl.js.map +0 -1
- package/dist/args-CaCcrYE1.js.map +0 -1
- package/dist/auth-CyADghFQ.js.map +0 -1
- package/dist/bundle-DgILeA5b.js.map +0 -1
- package/dist/cloud-CYMk92iG.js.map +0 -1
- package/dist/command-D5lhW_-B.js.map +0 -1
- package/dist/db-A7XDCIIO.js.map +0 -1
- package/dist/fold-static-CKewnAPX.js.map +0 -1
- package/dist/init-Dtl-IcXf.js.map +0 -1
- package/dist/last-dev-database-Dc8cP01o.js +0 -2
- package/dist/manifest-C3uLDrrJ.js.map +0 -1
- package/dist/pull-D9WvpDYY.js.map +0 -1
- package/dist/resolve-BY7bSFRT.js +0 -2
- package/dist/schema-DwFDI1iU.js.map +0 -1
- package/dist/schema-reconcile-Tto54Qbv.js +0 -2
- package/dist/storage-iTqj5-Av.js.map +0 -1
- package/dist/verify-DkJqhYPI.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"debug-nNbbxAeo.js","names":[],"sources":["../src/commands/cloud/debug.ts"],"sourcesContent":["/**\n * `rebase cloud debug <subcommand>` — one entry point for \"why is my deployed\n * app not behaving\".\n *\n * ## Why this exists\n *\n * The useful signals for a deployed project live in four different places — the\n * control plane, the workload's pods, the tenant database, and the public URL —\n * and each is normally reached with a different tool and a different set of\n * flags. Getting to a log should not be a research task. This started life as a\n * hand-rolled `prod-debug.sh` for a single project, with the namespace and the\n * URL hardcoded at the top; it earned its place twice in one week, so it is\n * generalised here to any project the CLI can already resolve.\n *\n * ## Read-only by default\n *\n * Every subcommand here only reads. The two things the original script could do\n * that mutate are deliberately NOT reproduced as-is:\n *\n * - restarting the workload lives at `rebase cloud restart`, which already\n * gates downtime behind `--yes`; duplicating it here would give the same\n * destructive act a second, ungated spelling.\n * - `debug db` prints the port-forward recipe and the connection's *shape*.\n * It opens no session and prints no password — `rebase cloud db info\n * --reveal` is the explicit, auditable way to get one.\n *\n * ## The probes are the point\n *\n * `debug health` is the highest-value piece and the reason the script existed.\n * A bare status code is not a diagnosis: a 404 from a functions route means\n * something completely different from a 404 at the root, and a 200 on an\n * unauthenticated read is a finding rather than a success. So every probe ships\n * with the interpretation of what it got, not just the number — see\n * {@link PROBES}.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { warnDeprecated } from \"@rebasepro/common\";\nimport { unknownCommandMessage } from \"../../utils/unknown-command\";\nimport {\n requireClient,\n requireProject,\n parseCloudArgs,\n displayProjectRef,\n fetchTenantBaseDomain,\n projectHost,\n colorStatus,\n keyValues,\n emit,\n printGroupHelp,\n fail,\n reportError,\n type CloudClient\n} from \"./context\";\n\n/* ═══════════════════════════════════════════════════════════════\n Health probes\n ═══════════════════════════════════════════════════════════════ */\n\n/** How a probe's outcome should be read. */\nexport type Verdict =\n /** Behaving as a healthy deployment should. */\n | \"ok\"\n /** Reachable and legal, but worth a human look (e.g. a public read). */\n | \"warn\"\n /** Broken, or wired up wrong. */\n | \"fail\"\n /** We could not classify the response. */\n | \"unknown\";\n\nexport interface ProbeReading {\n verdict: Verdict;\n /** What this status code *means for this endpoint*, in one sentence. */\n meaning: string;\n}\n\nexport interface ProbeSpec {\n id: string;\n /** Column label in human output. */\n label: string;\n method: \"GET\" | \"POST\";\n /** Path relative to the project origin. */\n path: (opts: ProbeTargets) => string;\n body?: unknown;\n /** One-line statement of what a healthy deployment answers here. */\n healthy: string;\n interpret: (status: number | null) => ProbeReading;\n /**\n * Read the response body as well. Set only where the body carries a fact the\n * status code cannot — today, the function listing.\n */\n needsBody?: boolean;\n /**\n * Sharpen the status-code reading using the parsed body. Returning null\n * keeps {@link interpret}'s verdict.\n */\n refine?: (body: unknown, targets: ProbeTargets) => ProbeReading | null;\n}\n\nexport interface ProbeTargets {\n /** Table used for the unauthenticated-read probe. */\n collection: string;\n /** Function to confirm exists, if the caller named one. */\n fn?: string;\n}\n\n/** A response never arrived: DNS, TLS, ingress, or the pod. */\nconst NO_RESPONSE: ProbeReading = {\n verdict: \"fail\",\n meaning:\n \"nothing answered — the hostname does not resolve, the ingress has no route, or no pod is running\"\n};\n\nfunction serverError(what: string): ProbeReading {\n return { verdict: \"fail\",\nmeaning: `the server is running but ${what}` };\n}\n\n/**\n * The probe set, in the order a failure cascades: if `health` is down, nothing\n * below it is meaningful, so it is checked first and reported first.\n */\nexport const PROBES: ProbeSpec[] = [\n {\n id: \"health\",\n label: \"health\",\n method: \"GET\",\n path: () => \"/health\",\n healthy: \"200 — the backend is up\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n if (status === 200) return { verdict: \"ok\",\nmeaning: \"the backend is up and serving\" };\n if (status === 404) {\n return {\n verdict: \"fail\",\n meaning:\n \"something answered but it is not a Rebase backend — the ingress is routing this host elsewhere\"\n };\n }\n if (status >= 500) return serverError(\"its health endpoint is failing\");\n return { verdict: \"unknown\",\nmeaning: \"unexpected for a health endpoint\" };\n }\n },\n {\n id: \"spa\",\n label: \"spa\",\n method: \"GET\",\n path: () => \"/\",\n healthy: \"200 — the frontend is being served\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n if (status === 200) return { verdict: \"ok\",\nmeaning: \"the frontend bundle is being served\" };\n if (status === 404) {\n return {\n verdict: \"warn\",\n meaning:\n \"no frontend at the root — expected for a backend-only project, otherwise the SPA assets were not bundled into the image\"\n };\n }\n if (status >= 500) return serverError(\"the root route throws\");\n return { verdict: \"unknown\",\nmeaning: \"unexpected at the site root\" };\n }\n },\n {\n id: \"auth\",\n label: \"auth\",\n method: \"POST\",\n path: () => \"/api/auth/login\",\n body: {},\n healthy: \"400 — auth is mounted and rejects an empty body\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n // The probe deliberately posts an empty body: a healthy auth route\n // must reject it. Reachability is what is being tested, not a login.\n if (status === 400 || status === 422) {\n return { verdict: \"ok\",\nmeaning: \"auth is mounted and rejected the empty body, as it should\" };\n }\n if (status === 401 || status === 403) {\n return { verdict: \"ok\",\nmeaning: \"auth is mounted and refused the credentials\" };\n }\n if (status === 404) {\n return {\n verdict: \"fail\",\n meaning: \"the auth routes are NOT mounted — this project cannot sign anyone in\"\n };\n }\n if (status === 200) {\n return {\n verdict: \"fail\",\n meaning: \"an EMPTY login body was accepted — a login with no credentials must never succeed\"\n };\n }\n if (status >= 500) return serverError(\"the login route throws — often a missing or unmigrated auth table\");\n return { verdict: \"unknown\",\nmeaning: \"unexpected for a login route\" };\n }\n },\n {\n id: \"unauthRead\",\n label: \"unauth read\",\n method: \"GET\",\n path: (t) => `/api/data/${encodeURIComponent(t.collection)}`,\n healthy: \"401 — reads require authentication\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n if (status === 401 || status === 403) {\n return { verdict: \"ok\",\nmeaning: \"unauthenticated reads are refused — row-level security is enforced\" };\n }\n if (status === 200) {\n // Legal, and sometimes intended. Never silently called healthy.\n return {\n verdict: \"warn\",\n meaning:\n \"this table is readable with NO authentication — correct only if it is deliberately public\"\n };\n }\n if (status === 404) {\n return {\n verdict: \"warn\",\n meaning: \"no such table on this deployment — check the name, or pass --table\"\n };\n }\n if (status >= 500) {\n return serverError(\n \"the read reached the database and failed — most often an RLS policy naming a column or table that is not there\"\n );\n }\n return { verdict: \"unknown\",\nmeaning: \"unexpected for a data read\" };\n }\n },\n {\n id: \"functions\",\n label: \"functions\",\n method: \"GET\",\n /**\n * The router's own listing endpoint, NOT a function's path.\n *\n * This matters, and it is the one place the original script got a wrong\n * answer. A function is a Hono sub-app mounted at `/<name>`, and it\n * usually defines only sub-routes (`/get`, `/list`) — so\n * `/api/functions/<name>` 404s **even when everything is mounted and\n * healthy**. Probing there cannot separate \"the router is missing\" from\n * \"that function defines no root route\", and reporting the first is how\n * you send someone to debug a deployment that was fine.\n *\n * `GET /api/functions` is unambiguous: the router registers a listing\n * route at its own root (see `createFunctionRoutes`), so a 200 proves\n * the mount *and* names every function that loaded.\n */\n path: () => \"/api/functions\",\n healthy: \"200 — the functions router is mounted and lists its functions\",\n interpret: (status) => {\n if (status === null) return NO_RESPONSE;\n if (status === 200) return { verdict: \"ok\",\nmeaning: \"the functions router is mounted\" };\n if (status === 401 || status === 403) {\n // The listing is behind auth on this deployment. That still\n // proves the router is there, which is what is being tested.\n return { verdict: \"ok\",\nmeaning: \"the functions router is mounted (its listing requires auth)\" };\n }\n if (status === 404) {\n return {\n verdict: \"fail\",\n meaning:\n \"the functions router did not mount — no functions directory was found at build time, or it held no functions, so every function on this project is unreachable\"\n };\n }\n if (status >= 500) return serverError(\"the functions router throws\");\n return { verdict: \"unknown\",\nmeaning: \"unexpected for the functions listing\" };\n },\n needsBody: true,\n refine: (body, t) => {\n const names = functionNames(body);\n if (!names) return null;\n if (t.fn && !names.includes(t.fn)) {\n // Definitive, because the listing is authoritative — no guessing\n // from a 404 that could equally mean the router is absent.\n return {\n verdict: \"fail\",\n meaning:\n `the router is mounted but no function is named \"${t.fn}\" — it loaded ${names.length}: ` +\n `${names.join(\", \")}`\n };\n }\n const found = t.fn ? `, including ${t.fn}` : \"\";\n return {\n verdict: \"ok\",\n meaning: `the functions router is mounted and loaded ${names.length} function${names.length === 1 ? \"\" : \"s\"}${found}`\n };\n }\n }\n];\n\n/** The function names out of a listing body, or null when it is not one. */\nexport function functionNames(body: unknown): string[] | null {\n const list = (body as { functions?: unknown } | null | undefined)?.functions;\n if (!Array.isArray(list)) return null;\n const names = list\n .map((f) => (f as { name?: unknown })?.name)\n .filter((n): n is string => typeof n === \"string\");\n return names.length === list.length ? names : null;\n}\n\nexport interface ProbeResult {\n id: string;\n label: string;\n method: string;\n url: string;\n status: number | null;\n ms: number;\n verdict: Verdict;\n meaning: string;\n healthy: string;\n /**\n * Whether the STATUS CODE alone looked healthy. False means the code itself\n * was wrong; true with a failing `verdict` means the code was fine and the\n * body carried the bad news (a named function that did not load). The\n * summary uses this so it never tells you to expect a 200 you already got.\n */\n statusOk: boolean;\n}\n\n/** Milliseconds before a probe is treated as unanswered. */\nconst PROBE_TIMEOUT_MS = 10_000;\n\n/**\n * Ceiling on a probe body we will parse. The only body read is the function\n * listing; anything larger is a page we have no use for, and a debug command\n * must not be the thing that runs a machine out of memory.\n */\nconst MAX_PROBE_BODY_BYTES = 256 * 1024;\n\n/**\n * Run one probe. A transport failure is a `null` status, never a thrown error:\n * \"nothing answered\" is a diagnosis in its own right and the other probes still\n * need to run.\n */\nexport async function runProbe(origin: string, spec: ProbeSpec, targets: ProbeTargets): Promise<ProbeResult> {\n const url = `${origin}${spec.path(targets)}`;\n const started = Date.now();\n let status: number | null = null;\n let body: unknown;\n try {\n const res = await fetch(url, {\n method: spec.method,\n headers: spec.body ? { \"Content-Type\": \"application/json\" } : undefined,\n body: spec.body ? JSON.stringify(spec.body) : undefined,\n redirect: \"manual\",\n signal: AbortSignal.timeout(PROBE_TIMEOUT_MS)\n });\n status = res.status;\n if (spec.needsBody && res.ok) {\n const text = await res.text();\n if (text.length <= MAX_PROBE_BODY_BYTES) {\n try {\n body = JSON.parse(text);\n } catch {\n // Not JSON — `refine` returns null and the status reading stands.\n }\n }\n }\n } catch {\n status = null;\n }\n const statusReading = spec.interpret(status);\n // The body can only sharpen a reading, never invent one where the request\n // failed outright.\n const reading = (status !== null && spec.refine?.(body, targets)) || statusReading;\n return {\n statusOk: statusReading.verdict === \"ok\",\n id: spec.id,\n label: spec.label,\n method: spec.method,\n url,\n status,\n ms: Date.now() - started,\n verdict: reading.verdict,\n meaning: reading.meaning,\n healthy: spec.healthy\n };\n}\n\n/** The worst verdict across probes — what the command's exit code keys off. */\nexport function overallVerdict(results: ProbeResult[]): Verdict {\n if (results.some((r) => r.verdict === \"fail\")) return \"fail\";\n if (results.some((r) => r.verdict === \"unknown\")) return \"unknown\";\n if (results.some((r) => r.verdict === \"warn\")) return \"warn\";\n return \"ok\";\n}\n\nfunction verdictMark(v: Verdict): string {\n switch (v) {\n case \"ok\":\n return chalk.green(\"✓\");\n case \"warn\":\n return chalk.yellow(\"!\");\n case \"fail\":\n return chalk.red(\"✗\");\n default:\n return chalk.gray(\"?\");\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Log parsing\n ═══════════════════════════════════════════════════════════════\n\n `runtime-logs` renders each line as `<rfc3339> [<pod>] <text>`, where <text>\n is normally the application's structured JSON. These helpers unwrap that so\n the derived views (errors / requests / boot) work on the payload rather than\n on the transport's formatting.\n*/\n\nexport interface ParsedLogLine {\n ts: string | null;\n pod: string | null;\n text: string;\n}\n\nconst LOG_PREFIX_RE = /^(?:(\\d{4}-\\d{2}-\\d{2}T[\\d:.]+Z?)\\s+)?(?:\\[([^\\]]+)\\]\\s+)?([\\s\\S]*)$/;\n\nexport function parseLogLine(line: string): ParsedLogLine {\n const m = LOG_PREFIX_RE.exec(line);\n if (!m) return { ts: null,\npod: null,\ntext: line };\n return { ts: m[1] ?? null,\npod: m[2] ?? null,\ntext: m[3] ?? \"\" };\n}\n\n/**\n * Lines an operator scanning for a fault wants to see.\n *\n * Matches the structured `severity` field first, then the shapes that show up\n * in unstructured output. `refus`/`denied` are in the list because a permission\n * failure often logs at info level and is exactly what one is hunting for.\n */\nexport function isErrorLine(text: string): boolean {\n return /\"(?:severity|level)\":\\s*\"(?:ERROR|WARN(?:ING)?|error|warn)\"|\\bError:|\\bERR!|refus|denied|EACCES|ECONNREFUSED/i.test(\n text\n );\n}\n\nexport interface RequestLogEntry {\n status: number | null;\n method: string;\n path: string;\n latencyMs: number | null;\n}\n\n/**\n * Pull an HTTP request record out of a log line, or null when it is not one.\n *\n * Only structured request lines are recognised. Guessing at prose would produce\n * a table with invented columns, which is worse than a short one.\n */\nexport function parseRequestLine(text: string): RequestLogEntry | null {\n const start = text.indexOf(\"{\");\n if (start === -1) return null;\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(text.slice(start)) as Record<string, unknown>;\n } catch {\n return null;\n }\n if (parsed.message !== \"request\" && parsed.msg !== \"request\") return null;\n\n const num = (v: unknown): number | null => {\n const n = typeof v === \"string\" ? Number(v) : typeof v === \"number\" ? v : NaN;\n return Number.isFinite(n) ? n : null;\n };\n return {\n status: num(parsed.status),\n method: typeof parsed.method === \"string\" ? parsed.method : \"\",\n path: typeof parsed.path === \"string\" ? parsed.path : \"\",\n latencyMs: num(parsed.latencyMs ?? parsed.durationMs)\n };\n}\n\n/**\n * Startup lines: what the server *decided* it was going to do. Which storage\n * backend it bound, which functions it loaded, whether auth tables were found.\n * This is the fastest way to tell a misconfiguration from a runtime fault.\n */\nexport function isBootLine(text: string): boolean {\n // \"Loaded custom functions\" and \"Loaded cron job…\" are 0.25's words for what\n // earlier runtimes logged as \"Mounted …\"; both are what a deployment runs.\n return /storage|Loaded (?:custom )?function|Loaded cron|Cron jobs scheduled|Cron scheduler|Mounted|Auth tables|Server running|listening|Refusing|migrat/i.test(text);\n}\n\n/** Render a number of seconds back as the compact duration a user would type. */\nexport function formatDuration(seconds: number): string {\n if (seconds % 86400 === 0 && seconds >= 86400) return `${seconds / 86400}d`;\n if (seconds % 3600 === 0 && seconds >= 3600) return `${seconds / 3600}h`;\n if (seconds % 60 === 0 && seconds >= 60) return `${seconds / 60}m`;\n return `${seconds}s`;\n}\n\n/**\n * Parse a duration like `15m`, `2h`, `90s`, `1d` (or a bare number of seconds)\n * into seconds. Returns null when it is not a duration.\n */\nexport function parseSince(input: string | undefined): number | null {\n if (!input) return null;\n const m = /^(\\d+(?:\\.\\d+)?)\\s*([smhd])?$/i.exec(input.trim());\n if (!m) return null;\n const value = parseFloat(m[1]);\n const unit = (m[2] || \"s\").toLowerCase();\n const mult = unit === \"s\" ? 1 : unit === \"m\" ? 60 : unit === \"h\" ? 3600 : 86400;\n return Math.round(value * mult);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Shared fetches\n ═══════════════════════════════════════════════════════════════ */\n\n/** One pod's entry in a `runtime-logs` answer. */\nexport interface RuntimeLogsPod {\n pod: string;\n state: string;\n /** Lines this pod returned. */\n lines: number;\n message: string | null;\n hint: string | null;\n /** The server's per-pod BYTE budget cut this pod's output. Says nothing about the line limit. */\n truncated?: boolean;\n}\n\nexport interface RuntimeLogsResponse {\n logs?: string;\n pods?: RuntimeLogsPod[];\n ordering?: string;\n /** A byte budget or the pod-count ceiling cut the result. Says nothing about the line limit. */\n truncated?: boolean;\n state?: string;\n message?: string | null;\n}\n\n/**\n * The most lines `runtime-logs` returns per pod.\n *\n * The control plane enforces this (`MAX_TAIL_LINES` in\n * `saas/backend/functions/runtime-logs.ts`) by clamping a larger `tailLines`\n * without saying so: its answer names neither the limit nor the value it used.\n * `--tail 200000` therefore came back as 2000 lines reported as untruncated.\n * The CLI clamps first, with the same number, so the lowering is something it\n * can print rather than something that happened out of sight.\n */\nexport const SERVER_MAX_TAIL_LINES = 2000;\n\n/** How many lines per pod a read asks for, and why that may be less than requested. */\nexport interface TailLimit {\n /** What `--tail` asked for, or the view's default. */\n requested: number;\n /** What is sent: `requested`, lowered to {@link SERVER_MAX_TAIL_LINES}. */\n applied: number;\n /** Whether `--tail` was given, so a message can name the flag or the default. */\n explicit: boolean;\n /** Set when `applied < requested`: the sentence that says so. */\n note: string | null;\n}\n\nexport function resolveTail(requested: number, explicit: boolean): TailLimit {\n const applied = Math.min(requested, SERVER_MAX_TAIL_LINES);\n return {\n requested,\n applied,\n explicit,\n note:\n applied < requested\n ? `--tail ${requested} was lowered to ${applied}: the control plane returns at most ` +\n `${SERVER_MAX_TAIL_LINES} lines per pod.`\n : null\n };\n}\n\n/** Read `--tail`, refusing anything that is not a positive whole number. */\nfunction tailFromFlag(value: number | undefined, fallback: number): TailLimit {\n if (value === undefined) return resolveTail(fallback, false);\n if (!Number.isInteger(value) || value <= 0) {\n fail(`--tail must be a positive whole number of lines; received \"${value}\".`, undefined, \"usage\");\n }\n return resolveTail(value, true);\n}\n\n/** What one pod's lines actually cover. */\nexport interface PodCoverage extends RuntimeLogsPod {\n /** Earliest and latest timestamps among the lines this pod returned. */\n firstTimestamp: string | null;\n lastTimestamp: string | null;\n /** A limit cut what this pod would otherwise have returned for the window. */\n truncated: boolean;\n /** Which limit: the per-pod line limit, or the server's byte budget. */\n truncatedBy: \"tail\" | \"bytes\" | null;\n /** The plain explanation, when truncated. */\n truncatedReason: string | null;\n /**\n * Every line this pod holds in the window came back. With no window (read\n * from the start), its first line is the start of its log.\n */\n complete: boolean;\n}\n\n/** The window asked for against the window delivered. */\nexport interface LogCoverage {\n /** Start of the window asked for, ISO. Null when reading each pod from its start. */\n requestedFrom: string | null;\n /** Earliest and latest timestamps across every line returned. */\n firstTimestamp: string | null;\n lastTimestamp: string | null;\n pods: PodCoverage[];\n truncated: boolean;\n truncatedReasons: string[];\n}\n\n/** A span of milliseconds as `29d 23h`, `2h 5m`, `35m`, `40s`. */\nexport function formatSpan(ms: number): string {\n const s = Math.max(0, Math.round(ms / 1000));\n const d = Math.floor(s / 86400);\n const h = Math.floor((s % 86400) / 3600);\n const m = Math.floor((s % 3600) / 60);\n if (d > 0) return h > 0 ? `${d}d ${h}h` : `${d}d`;\n if (h > 0) return m > 0 ? `${h}h ${m}m` : `${h}h`;\n if (m > 0) return `${m}m`;\n return `${s}s`;\n}\n\nfunction timestampRange(lines: ParsedLogLine[]): { first: string | null; last: string | null } {\n let first: { text: string; ms: number } | null = null;\n let last: { text: string; ms: number } | null = null;\n for (const l of lines) {\n if (!l.ts) continue;\n const ms = Date.parse(l.ts);\n if (Number.isNaN(ms)) continue;\n if (!first || ms < first.ms) first = { text: l.ts,\nms };\n if (!last || ms > last.ms) last = { text: l.ts,\nms };\n }\n return { first: first?.text ?? null,\nlast: last?.text ?? null };\n}\n\n/**\n * Compare what a read covered with what it asked for.\n *\n * The server's `truncated` describes only its byte budgets and pod ceiling, so\n * a pod that filled the line limit came back marked complete however much of\n * the window it left unread. The line limit is the cut that matters most, and\n * it is detected here: a pod that returned as many lines as the limit, whose\n * earliest line is later than the start of the window, was cut by it.\n *\n * Filling the limit is the half that separates a cut from a young pod. A pod\n * that started an hour ago also has no line older than an hour; it returned\n * fewer lines than the limit, so what came back is its whole log, and nothing\n * was cut.\n */\nexport function assessCoverage(opts: {\n res: RuntimeLogsResponse;\n lines: ParsedLogLine[];\n /** The window asked for. Null reads each pod from its start. */\n sinceSeconds: number | null;\n tail: TailLimit;\n now: number;\n}): LogCoverage {\n const { res, lines, sinceSeconds, tail, now } = opts;\n const windowStartMs = sinceSeconds === null ? null : now - sinceSeconds * 1000;\n const requestedFrom = windowStartMs === null ? null : new Date(windowStartMs).toISOString();\n const limitName = tail.note\n ? `the control plane's ceiling of ${tail.applied} lines per pod`\n : tail.explicit\n ? `the --tail ${tail.applied} limit`\n : `the default of ${tail.applied} lines per pod`;\n // Only worth saying when raising it would read further back.\n const raise = tail.applied < SERVER_MAX_TAIL_LINES\n ? ` Raise --tail (at most ${SERVER_MAX_TAIL_LINES}) to read further back.`\n : ` The control plane returns only each pod's newest ${SERVER_MAX_TAIL_LINES}, so older lines cannot be read from here.`;\n\n const pods: PodCoverage[] = (res.pods ?? []).map((p) => {\n const range = timestampRange(lines.filter((l) => l.pod === p.pod));\n const base = { ...p,\nfirstTimestamp: range.first,\nlastTimestamp: range.last };\n if (p.state !== \"ok\") {\n return { ...base,\ntruncated: false,\ntruncatedBy: null,\ntruncatedReason: null,\ncomplete: false };\n }\n if (p.truncated) {\n return {\n ...base,\n truncated: true,\n truncatedBy: \"bytes\" as const,\n truncatedReason:\n `${p.pod}: the control plane's per-pod byte budget cut this pod's output short` +\n (range.first ? ` — what fit runs ${range.first} to ${range.last}.` : \".\"),\n complete: false\n };\n }\n const firstMs = range.first ? Date.parse(range.first) : null;\n const startsLate = windowStartMs === null || firstMs === null || firstMs > windowStartMs;\n if (p.lines >= tail.applied && startsLate) {\n let reason: string;\n if (firstMs === null) {\n reason = `${p.pod}: returned ${p.lines} lines, ${limitName}; they carry no timestamps, so how far back they reach is unknown.`;\n } else if (sinceSeconds !== null && windowStartMs !== null) {\n reason =\n `${p.pod}: returned ${p.lines} lines, ${limitName}, and the earliest is ${range.first} — ` +\n `${formatSpan(firstMs - windowStartMs)} after the ${formatDuration(sinceSeconds)} ` +\n `window begins (${requestedFrom}). Lines in between were not read.${raise}`;\n } else {\n reason =\n `${p.pod}: returned ${p.lines} lines, ${limitName}, so its log before ${range.first} ` +\n `was not read.${raise}`;\n }\n return { ...base,\ntruncated: true,\ntruncatedBy: \"tail\" as const,\ntruncatedReason: reason,\ncomplete: false };\n }\n return { ...base,\ntruncated: false,\ntruncatedBy: null,\ntruncatedReason: null,\ncomplete: true };\n });\n\n const truncatedReasons = pods.flatMap((p) => (p.truncatedReason ? [p.truncatedReason] : []));\n // The server's flag also covers cuts no single pod owns: its total byte\n // budget across pods, and the cap on how many pods it reads.\n if (res.truncated && !pods.some((p) => p.truncatedBy === \"bytes\")) {\n truncatedReasons.push(\n \"The control plane trimmed the combined result (its total byte budget, or the most pods it reads at once); the oldest lines were dropped.\"\n );\n }\n const overall = timestampRange(lines);\n return {\n requestedFrom,\n firstTimestamp: overall.first,\n lastTimestamp: overall.last,\n pods,\n truncated: Boolean(res.truncated) || pods.some((p) => p.truncated),\n truncatedReasons\n };\n}\n\nasync function fetchRuntimeLogs(\n client: CloudClient,\n projectId: string,\n opts: { sinceSeconds?: number; tailLines?: number; previous?: boolean }\n): Promise<RuntimeLogsResponse> {\n const params = new URLSearchParams();\n if (opts.sinceSeconds !== undefined) params.set(\"sinceSeconds\", String(opts.sinceSeconds));\n if (opts.tailLines !== undefined) params.set(\"tailLines\", String(opts.tailLines));\n if (opts.previous) params.set(\"previous\", \"true\");\n params.set(\"timestamps\", \"true\");\n const qs = params.toString();\n return client.functions.invoke<RuntimeLogsResponse>(\"runtime-logs\", undefined, {\n method: \"GET\",\n path: `${projectId}${qs ? `?${qs}` : \"\"}`\n });\n}\n\n/** Print the per-pod states runtime-logs reports, including its hints. */\nfunction printPodStates(res: RuntimeLogsResponse): void {\n if (res.state === \"no_pods\") {\n console.log(chalk.yellow(` ${res.message ?? \"No pods are running for this project.\"}`));\n console.log(\"\");\n return;\n }\n for (const p of res.pods ?? []) {\n if (p.state === \"ok\") continue;\n console.log(` ${chalk.yellow(p.pod)} ${chalk.gray(`(${p.state})`)}`);\n if (p.message) console.log(chalk.gray(` ${p.message}`));\n // The hint is the actionable half — a crash-looping container's reason\n // is in its PREVIOUS instance, and that is only discoverable if we say so.\n if (p.hint) console.log(chalk.cyan(` → ${p.hint}`));\n }\n}\n\n/**\n * The window asked for, the window delivered, and every cut between them.\n * Printed after the lines, where a reader's eye is when the output ends.\n */\nfunction printCoverage(coverage: LogCoverage, tail: TailLimit): void {\n const asked = coverage.requestedFrom ? `from ${coverage.requestedFrom}` : \"from each pod's start\";\n const got = coverage.firstTimestamp && coverage.lastTimestamp\n ? `${coverage.firstTimestamp} → ${coverage.lastTimestamp} ` +\n `(${formatSpan(Date.parse(coverage.lastTimestamp) - Date.parse(coverage.firstTimestamp))})`\n : \"no timestamped lines\";\n console.log(chalk.gray(` Asked for: ${asked}`));\n console.log(chalk.gray(` Returned: ${got}`));\n if (tail.note) console.log(chalk.yellow(` ! ${tail.note}`));\n if (coverage.truncated) {\n console.log(chalk.yellow(\" ! Truncated — the lines above do not cover the window asked for:\"));\n for (const reason of coverage.truncatedReasons) console.log(chalk.yellow(` ${reason}`));\n }\n console.log(\"\");\n}\n\n/**\n * Resolve the public origin a project is served at — or `--host`, when given.\n *\n * Shared with `rebase cloud cron`, which reads the runtime at the same address\n * `debug health` probes.\n */\nexport async function resolveOrigin(\n rawArgs: string[],\n client: CloudClient,\n url: string,\n projectId: string\n): Promise<string> {\n const parsed = arg({ \"--host\": String }, { argv: rawArgs.slice(3),\npermissive: true });\n if (parsed[\"--host\"]) {\n const h = parsed[\"--host\"].trim().replace(/\\/+$/, \"\");\n return /^https?:\\/\\//.test(h) ? h : `https://${h}`;\n }\n\n const [project, baseDomain] = await Promise.all([\n client.data.table(\"projects\").findById(projectId) as Promise<\n { subdomain?: string; host?: string; customDomain?: string } | undefined\n >,\n fetchTenantBaseDomain(client, url)\n ]);\n if (!project) fail(`Project ${displayProjectRef(rawArgs)} not found.`);\n\n const host = projectHost(project, baseDomain);\n if (!host) {\n fail(\n \"Could not determine the public URL for this project.\",\n \"It may never have been deployed. Pass --host <hostname> to probe an address directly.\"\n );\n }\n return `https://${host}`;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: health\n ═══════════════════════════════════════════════════════════════ */\n\nasync function healthCommand(rawArgs: string[]): Promise<void> {\n // Strict: `--tabel users` used to be dropped and the probe then ran\n // against the default table while reporting on the one asked for.\n const { flags: parsed } = parseCloudArgs({\n spec: HEALTH_FLAGS,\n rawArgs,\n commandWords: 3, // cloud debug health\n command: \"cloud debug\",\n maxPositionals: 0\n });\n const targets: ProbeTargets = {\n collection: resolveProbeTable(parsed) || \"users\",\n // Optional: the listing endpoint proves the mount on its own. A name\n // here additionally asserts that this particular function loaded.\n fn: parsed[\"--function\"]\n };\n\n const { client, url } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n const origin = await resolveOrigin(rawArgs, client, url, projectId);\n\n // Sequential, not Promise.all: five simultaneous requests to a struggling\n // pod is a small load test, and the latency column would then measure our\n // own contention rather than the endpoint's.\n const results: ProbeResult[] = [];\n for (const spec of PROBES) results.push(await runProbe(origin, spec, targets));\n\n const overall = overallVerdict(results);\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🩺 Health — ${displayProjectRef(rawArgs)}`) + chalk.gray(` ${origin}`));\n console.log(\"\");\n const width = Math.max(...results.map((r) => r.label.length));\n for (const r of results) {\n const code = r.status === null ? chalk.red(\"---\") : String(r.status);\n console.log(\n ` ${verdictMark(r.verdict)} ${chalk.bold(r.label.padEnd(width))} ${code.padStart(3)} ${chalk.gray(`${r.ms}ms`)}`\n );\n console.log(` ${chalk.gray(r.meaning)}`);\n }\n console.log(\"\");\n if (overall === \"ok\") {\n console.log(chalk.green(\" Everything reachable and wired as expected.\"));\n } else {\n const bad = results.filter((r) => r.verdict === \"fail\" || r.verdict === \"warn\");\n console.log(chalk.gray(` ${bad.length} of ${results.length} check${bad.length === 1 ? \"\" : \"s\"} need attention.`));\n // Only where the status code itself was wrong — restating\n // \"expected 200\" under a probe that returned 200 reads as a bug.\n const wrongStatus = bad.filter((r) => !r.statusOk);\n if (wrongStatus.length > 0) {\n console.log(chalk.gray(\" A healthy deployment answers:\"));\n for (const r of wrongStatus) {\n console.log(chalk.gray(` ${r.label.padEnd(width)} ${r.healthy}`));\n }\n }\n }\n console.log(\"\");\n },\n { origin,\noverall,\nprobes: results }\n );\n\n // A failing probe is a failing command — this is meant to be usable in a\n // deploy script's `if`, not only read by a human.\n if (overall === \"fail\") process.exit(1);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: logs / errors / requests / boot\n ═══════════════════════════════════════════════════════════════ */\n\n/** What `debug logs`, `errors` and `boot` parse. Their help pairs against this. */\nexport const LOG_VIEW_FLAGS = {\n \"--since\": String,\n \"--tail\": Number,\n \"--previous\": Boolean\n} as const;\n\n/** What `debug requests` parses. */\nexport const REQUESTS_FLAGS = {\n \"--since\": String,\n \"--tail\": Number\n} as const;\n\n/** What `debug health` parses. */\nexport const HEALTH_FLAGS = {\n \"--table\": String,\n /** @deprecated Use `--table` instead. Accepted, with a warning, until a later release. */\n \"--collection\": String,\n \"--function\": String,\n // `--host` is read again inside `resolveOrigin`, which needs it before\n // the client exists; declared here because THIS is the parse that\n // decides whether the line is accepted at all.\n \"--host\": String\n} as const;\n\n/**\n * The table `debug health` probes, from `--table` or its deprecated spelling\n * `--collection`, which still works and warns once. Undefined when neither was\n * given.\n *\n * \"Table\" is the word for the app's data; \"collection\" is the CMS's. Both\n * spellings at once is refused unless they agree, since one of them would be\n * ignored.\n */\nexport function resolveProbeTable(flags: { \"--table\"?: string; \"--collection\"?: string }): string | undefined {\n const table = flags[\"--table\"];\n const collection = flags[\"--collection\"];\n if (collection === undefined) return table;\n warnDeprecated(\"cli.cloud-debug-health-collection\", \"`rebase cloud debug health --collection` is deprecated; use `--table` instead.\");\n if (table !== undefined && table !== collection) {\n fail(\"--table and --collection name the same thing; pass --table alone.\", undefined, \"usage\");\n }\n return table ?? collection;\n}\n\ninterface LogViewOptions {\n /** Keep only lines matching this. Omit to keep everything. */\n filter?: (text: string) => boolean;\n /** Default lookback when --since is not given. Null reads each pod from its start. */\n defaultSinceSeconds: number | null;\n /** Lines read per pod when --tail is not given. */\n defaultTail: number;\n /** Max lines rendered. */\n limit: number;\n title: string;\n /**\n * The lines wanted are the first a pod wrote, so a read that did not reach\n * a pod's start has not looked where they are — see {@link bootReach}.\n */\n needsStart?: boolean;\n}\n\nconst LOG_VIEWS = {\n logs: { defaultSinceSeconds: 900,\ndefaultTail: 500,\nlimit: 200,\ntitle: \"📄 Logs\" },\n errors: { filter: isErrorLine,\ndefaultSinceSeconds: 3600,\ndefaultTail: 500,\nlimit: 40,\ntitle: \"🔥 Errors\" },\n boot: {\n filter: isBootLine,\n // No window, and the most lines the control plane returns. Startup\n // happened when the pod started, which may have been days ago: a\n // 7-day window and the newest 500 lines missed it on any pod that had\n // served traffic since.\n defaultSinceSeconds: null,\n defaultTail: SERVER_MAX_TAIL_LINES,\n limit: 25,\n title: \"🚀 Boot\",\n needsStart: true\n }\n} satisfies Record<string, LogViewOptions>;\n\nconst REQUESTS_DEFAULTS = { sinceSeconds: 900,\ntail: 1000 };\n\n/** Read `--since`, refusing anything that is not a duration. Undefined when it was not given. */\nfunction sinceFromFlag(sinceArg: string | undefined): number | undefined {\n if (sinceArg === undefined) return undefined;\n const seconds = parseSince(sinceArg);\n if (seconds === null) fail(`--since must be a duration like 15m, 2h or 90s; received \"${sinceArg}\".`);\n return seconds;\n}\n\nfunction windowLabel(sinceSeconds: number | null): string {\n return sinceSeconds === null ? \"since each pod started\" : `last ${formatDuration(sinceSeconds)}`;\n}\n\n/**\n * Whether a boot read reached each pod's start, which is where its startup\n * lines are. A pod whose read was cut has not been looked at there, so finding\n * no startup lines in it means nothing — and a line from later in its life\n * that happens to mention `storage` is not its startup.\n *\n * Under `--since` a pod is never counted as reached: a complete read of the\n * window starts at the pod's first line only if the pod started inside it, and\n * nothing in the answer says whether it did.\n */\nexport function bootReach(pods: PodCoverage[], sinceSeconds: number | null): {\n reachedStart: boolean;\n unreached: string[];\n} {\n const unreached = pods\n .filter((p) => p.state === \"ok\" && (!p.complete || sinceSeconds !== null))\n .map((p) => p.pod);\n return { reachedStart: unreached.length === 0,\nunreached };\n}\n\nasync function logView(rawArgs: string[], view: LogViewOptions): Promise<void> {\n const { flags: parsed } = parseCloudArgs({\n spec: LOG_VIEW_FLAGS,\n rawArgs,\n commandWords: 3, // cloud debug logs|errors|boot\n command: \"cloud debug\",\n maxPositionals: 0\n });\n\n const sinceSeconds = sinceFromFlag(parsed[\"--since\"]) ?? view.defaultSinceSeconds;\n const tail = tailFromFlag(parsed[\"--tail\"], view.defaultTail);\n\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n let res: RuntimeLogsResponse;\n try {\n res = await fetchRuntimeLogs(client, projectId, {\n sinceSeconds: sinceSeconds ?? undefined,\n tailLines: tail.applied,\n previous: Boolean(parsed[\"--previous\"])\n });\n } catch (e) {\n reportError(e, \"Failed to fetch runtime logs\");\n }\n\n const all = (res.logs ?? \"\").split(\"\\n\").filter((l) => l !== \"\");\n const parsedLines = all.map(parseLogLine);\n const kept = view.filter ? parsedLines.filter((l) => view.filter!(l.text)) : parsedLines;\n const shown = kept.slice(-view.limit);\n const coverage = assessCoverage({ res,\nlines: parsedLines,\nsinceSeconds,\ntail,\nnow: Date.now() });\n const reach = view.needsStart ? bootReach(coverage.pods, sinceSeconds) : null;\n\n emit(\n () => {\n console.log(\"\");\n console.log(\n chalk.bold(` ${view.title} — ${displayProjectRef(rawArgs)}`) + chalk.gray(` ${windowLabel(sinceSeconds)}`)\n );\n console.log(\"\");\n printPodStates(res);\n if (shown.length === 0) {\n console.log(chalk.gray(\" (nothing matched in what was read)\"));\n console.log(\"\");\n } else {\n for (const l of shown) console.log(` ${l.pod ? chalk.gray(`[${l.pod}] `) : \"\"}${l.text}`);\n console.log(\"\");\n if (kept.length > shown.length) {\n console.log(chalk.gray(` (showing the last ${shown.length} of ${kept.length} matching lines)`));\n console.log(\"\");\n }\n }\n printCoverage(coverage, tail);\n if (reach && !reach.reachedStart) {\n const which = reach.unreached.join(\", \");\n console.log(\n chalk.yellow(\n sinceSeconds === null\n ? ` ! The start of ${which} was not read, so its startup lines are not among the lines above.`\n : ` ! The start of ${which} may not have been read: --since limits the read to a recent window. ` +\n \"Drop it to read each pod from its start.\"\n )\n );\n console.log(\"\");\n }\n },\n {\n sinceSeconds,\n tail: { requested: tail.requested,\napplied: tail.applied,\nserverMax: SERVER_MAX_TAIL_LINES,\nnote: tail.note },\n window: {\n requestedFrom: coverage.requestedFrom,\n firstTimestamp: coverage.firstTimestamp,\n lastTimestamp: coverage.lastTimestamp\n },\n state: res.state ?? null,\n pods: coverage.pods,\n truncated: coverage.truncated,\n truncatedReasons: coverage.truncatedReasons,\n ...(reach ? { reachedStart: reach.reachedStart,\nunreachedPods: reach.unreached } : {}),\n matched: kept.length,\n lines: shown\n }\n );\n}\n\nasync function requestsCommand(rawArgs: string[]): Promise<void> {\n const { flags: parsed } = parseCloudArgs({\n spec: REQUESTS_FLAGS,\n rawArgs,\n commandWords: 3, // cloud debug requests\n command: \"cloud debug\",\n maxPositionals: 0\n });\n const sinceSeconds = sinceFromFlag(parsed[\"--since\"]) ?? REQUESTS_DEFAULTS.sinceSeconds;\n const tail = tailFromFlag(parsed[\"--tail\"], REQUESTS_DEFAULTS.tail);\n\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n let res: RuntimeLogsResponse;\n try {\n res = await fetchRuntimeLogs(client, projectId, { sinceSeconds,\ntailLines: tail.applied });\n } catch (e) {\n reportError(e, \"Failed to fetch runtime logs\");\n }\n\n const parsedLines = (res.logs ?? \"\")\n .split(\"\\n\")\n .filter((l) => l !== \"\")\n .map(parseLogLine);\n const entries = parsedLines\n .map((l) => parseRequestLine(l.text))\n .filter((e): e is RequestLogEntry => e !== null);\n const shown = entries.slice(-40);\n const coverage = assessCoverage({ res,\nlines: parsedLines,\nsinceSeconds,\ntail,\nnow: Date.now() });\n\n emit(\n () => {\n console.log(\"\");\n console.log(\n chalk.bold(` 🌐 Requests — ${displayProjectRef(rawArgs)}`) +\n chalk.gray(` ${windowLabel(sinceSeconds)}`)\n );\n console.log(\"\");\n printPodStates(res);\n if (shown.length === 0) {\n console.log(chalk.gray(\" No structured request lines in what was read.\"));\n console.log(chalk.gray(\" (this view needs the server's request logging; try `debug logs`)\"));\n console.log(\"\");\n printCoverage(coverage, tail);\n return;\n }\n for (const e of shown) {\n const status = e.status ?? 0;\n const color = status >= 500 ? chalk.red : status >= 400 ? chalk.yellow : chalk.green;\n console.log(\n ` ${color(String(e.status ?? \"---\").padStart(3))} ${e.method.padEnd(6)} ${e.path.slice(0, 70).padEnd(70)} ${chalk.gray(\n e.latencyMs === null ? \"\" : `${e.latencyMs}ms`\n )}`\n );\n }\n console.log(\"\");\n printCoverage(coverage, tail);\n },\n {\n sinceSeconds,\n tail: { requested: tail.requested,\napplied: tail.applied,\nserverMax: SERVER_MAX_TAIL_LINES,\nnote: tail.note },\n window: {\n requestedFrom: coverage.requestedFrom,\n firstTimestamp: coverage.firstTimestamp,\n lastTimestamp: coverage.lastTimestamp\n },\n pods: coverage.pods,\n truncated: coverage.truncated,\n truncatedReasons: coverage.truncatedReasons,\n requests: shown\n }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: pod\n ═══════════════════════════════════════════════════════════════ */\n\nasync function podCommand(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud debug\",\nmaxPositionals: 0 });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n interface MetricsResponse {\n status?: string;\n cpu?: string | null;\n memory?: string | null;\n placement?: {\n cluster?: string | null;\n provider?: string | null;\n region?: string | null;\n namespace?: string | null;\n host?: string | null;\n image?: string | null;\n replicas?: { available?: number; desired?: number };\n };\n }\n\n let m: MetricsResponse;\n try {\n m = await client.functions.invoke<MetricsResponse>(\"metrics\", undefined, {\n method: \"GET\",\n path: projectId\n });\n } catch (e) {\n reportError(e, \"Failed to read workload placement\");\n }\n\n const p = m.placement ?? {};\n const replicas = p.replicas ?? {};\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` ☸ Workload — ${displayProjectRef(rawArgs)}`));\n console.log(\"\");\n keyValues([\n [\"Status\", m.status ? colorStatus(m.status === \"running\" ? \"active\" : m.status) : undefined],\n [\n \"Replicas\",\n replicas.desired === undefined\n ? undefined\n : `${replicas.available ?? 0} / ${replicas.desired} available`\n ],\n [\"Namespace\", p.namespace],\n [\"Cluster\", p.cluster],\n [\"Region\", [p.provider, p.region].filter(Boolean).join(\" · \") || undefined],\n [\"Host\", p.host],\n [\"Image\", p.image],\n // Reported as-is: the metrics function returns null for \"not\n // measurable\", which must not render as a number.\n [\"CPU\", m.cpu ?? undefined],\n [\"Memory\", m.memory ?? undefined]\n ]);\n console.log(\"\");\n if ((replicas.available ?? 0) === 0 && (replicas.desired ?? 0) > 0) {\n console.log(chalk.yellow(\" No replica is available — the pod is not passing its readiness check.\"));\n console.log(chalk.gray(\" See why with: \") + chalk.bold(\"rebase cloud debug logs --previous\"));\n console.log(\"\");\n }\n },\n { status: m.status ?? null,\nplacement: p }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Subcommand: db\n ═══════════════════════════════════════════════════════════════ */\n\nasync function dbDebugCommand(rawArgs: string[]): Promise<void> {\n parseCloudArgs({ spec: {},\nrawArgs,\ncommandWords: 3,\ncommand: \"cloud debug\",\nmaxPositionals: 0 });\n const { client } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n\n interface DbInfo {\n type?: string;\n host?: string | null;\n port?: string | null;\n database?: string | null;\n username?: string | null;\n passwordAvailable?: boolean;\n unavailableReason?: string | null;\n directAccess?: {\n via: \"tunnel\";\n kubectl?: { namespace: string; service: string; localPort: number; remotePort: number };\n } | null;\n }\n\n let info: DbInfo;\n try {\n info = await client.functions.invoke<DbInfo>(\"db-info\", undefined, { method: \"GET\",\npath: projectId });\n } catch (e) {\n reportError(e, \"Failed to read database connection info\");\n }\n\n // The host above is a Service inside the platform's cluster, so `debug db`\n // has to say what to do about that. It used to print `kubectl port-forward\n // -n rebase-tenant-…`, which needs a kubeconfig for OUR cluster: a customer\n // has none, and nothing in the platform issues one. The tunnel is the\n // remedy a reader can actually run.\n const access = info.directAccess;\n const connectCmd = access ? \"rebase cloud db connect\" : null;\n const LOCAL_PORT = 5432;\n const psqlCmd =\n access && info.username && info.database\n ? `psql -h 127.0.0.1 -p ${LOCAL_PORT} -U ${info.username} -d ${info.database}`\n : null;\n // Only for a cluster the customer owns, where the credentials are theirs.\n const kubectlCmd = access?.kubectl\n ? `kubectl port-forward -n ${access.kubectl.namespace} svc/${access.kubectl.service} `\n + `${access.kubectl.localPort}:${access.kubectl.remotePort}`\n : null;\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` 🐘 Database — ${displayProjectRef(rawArgs)}`));\n console.log(\"\");\n if (info.unavailableReason) {\n console.log(chalk.yellow(` ${info.unavailableReason}`));\n console.log(\"\");\n return;\n }\n keyValues([\n [\"Type\", info.type],\n [\"Host\", info.host],\n [\"Port\", info.port],\n [\"Database\", info.database],\n [\"Username\", info.username],\n [\"Password\", info.passwordAvailable ? chalk.gray(\"stored — not shown here\") : chalk.yellow(\"none stored\")]\n ]);\n console.log(\"\");\n if (connectCmd) {\n // Printed rather than run. Opening a tunnel and a database shell\n // is not something a command called `debug` should do implicitly.\n console.log(chalk.gray(\" That host is inside the platform's cluster and does not resolve here.\"));\n console.log(chalk.gray(\" To reach the database from this machine:\"));\n console.log(\"\");\n console.log(` ${connectCmd}`);\n if (psqlCmd) console.log(` ${psqlCmd}`);\n console.log(\"\");\n if (kubectlCmd) {\n console.log(chalk.gray(\" Or, on your own cluster:\"));\n console.log(` ${kubectlCmd}`);\n console.log(\"\");\n }\n if (info.passwordAvailable) {\n console.log(\n chalk.gray(\" Get the password with: \") + chalk.bold(\"rebase cloud db info --reveal\")\n );\n console.log(\"\");\n }\n }\n },\n {\n type: info.type ?? null,\n host: info.host ?? null,\n port: info.port ?? null,\n database: info.database ?? null,\n username: info.username ?? null,\n passwordAvailable: Boolean(info.passwordAvailable),\n connectCommand: connectCmd,\n kubectlCommand: kubectlCmd,\n psqlCommand: psqlCmd\n }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Dispatch\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * Everything the switch below dispatches, for the did-you-mean. `workload` is\n * the older spelling of `pod` and stays out of it: suggesting the name we no\n * longer print in the help would teach the wrong one.\n */\nconst DEBUG_SUBCOMMANDS = [\"health\", \"logs\", \"errors\", \"boot\", \"requests\", \"pod\", \"db\"] as const;\n\nexport async function debugCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n switch (action) {\n case undefined:\n case \"health\":\n // Bare `rebase cloud debug` runs the probes: it is the answer to\n // \"something is wrong\" more often than any other view here.\n await healthCommand(rawArgs);\n break;\n case \"logs\":\n case \"errors\":\n case \"boot\":\n await logView(rawArgs, LOG_VIEWS[action]);\n break;\n case \"requests\":\n await requestsCommand(rawArgs);\n break;\n case \"pod\":\n case \"workload\":\n await podCommand(rawArgs);\n break;\n case \"db\":\n await dbDebugCommand(rawArgs);\n break;\n case \"help\":\n case \"--help\":\n printDebugHelp();\n break;\n default:\n // One refusal path in both modes. The terminal branch used to print\n // the whole help page to STDOUT — the results stream — after a\n // command that produced no result, which is the same shape the\n // index dispatcher was fixed out of. `fail` writes the machine\n // envelope under `--json` and one red line to stderr otherwise, and\n // the words come from the shared builder so the human line and the\n // machine one cannot drift apart: it carries the near-miss when\n // there is one, and names the page for the rest.\n fail(unknownCommandMessage(action, DEBUG_SUBCOMMANDS, \"cloud debug\"), undefined, \"unknown_command\");\n }\n}\n\n/**\n * The log flags as one action's help lists them, with THAT action's defaults.\n * They were one group-wide list saying \"Default: 500\", which was true of two of\n * the four actions, and offered `--previous` to `requests`, which rejects it.\n */\nfunction logFlagHelp(defaults: { sinceSeconds: number | null; tail: number }, previous: boolean): Array<[string, string]> {\n const flags: Array<[string, string]> = [\n [\n \"--since <dur>\",\n defaults.sinceSeconds === null\n ? \"Only lines this recent: 90s, 15m, 2h, 1d. Default: from each pod's start\"\n : `Lookback window: 90s, 15m, 2h, 1d. Default: ${formatDuration(defaults.sinceSeconds)}`\n ],\n [\"--tail <n>\", `Newest lines to read per pod, at most ${SERVER_MAX_TAIL_LINES}. Default: ${defaults.tail}`]\n ];\n if (previous) flags.push([\"--previous\", \"Read the CRASHED container instance, where the reason lives\"]);\n return flags;\n}\n\nfunction logViewFlagHelp(view: LogViewOptions): Array<[string, string]> {\n return logFlagHelp({ sinceSeconds: view.defaultSinceSeconds,\ntail: view.defaultTail }, true);\n}\n\nexport function printDebugHelp(): void {\n printGroupHelp({\n command: \"cloud debug\",\n title: \"Find out why a deployed project is misbehaving\",\n actions: [\n {\n action: \"health\",\n section: \"End-to-end\",\n description: \"Probe the live URL and explain every status code (the default)\",\n flags: [\n [\"--host <hostname>\", \"Probe this address instead of the project's own\"],\n [\"--table <name>\", \"Table for the unauth-read probe. Default: users\"],\n [\"--collection <name>\", \"Deprecated spelling of --table. Still works, and warns\"],\n [\"--function <name>\", \"Also assert this function loaded, against the listing\"]\n ]\n },\n { action: \"logs\",\nsection: \"Runtime\",\ndescription: \"Recent application logs\",\nflags: logViewFlagHelp(LOG_VIEWS.logs) },\n { action: \"errors\",\nsection: \"Runtime\",\ndescription: \"Error and warning lines only\",\nflags: logViewFlagHelp(LOG_VIEWS.errors) },\n { action: \"requests\",\nsection: \"Runtime\",\ndescription: \"HTTP requests the server logged: status, path, latency\",\nflags: logFlagHelp(REQUESTS_DEFAULTS, false) },\n { action: \"boot\",\nsection: \"Runtime\",\ndescription: \"What the server decided at startup: storage, functions, auth\",\nflags: logViewFlagHelp(LOG_VIEWS.boot) },\n { action: \"pod\",\nsection: \"Runtime\",\ndescription: \"Replicas, image, namespace, cluster placement\" },\n { action: \"db\",\nsection: \"Data\",\ndescription: \"Connection shape and the port-forward recipe. Never the password\" }\n ],\n notes: [\n \"Everything here is read-only. `health` exits non-zero when a check fails, so it works in a\",\n \"deploy script. To restart a workload, use `rebase cloud restart`.\",\n \"The log views end with the window asked for, the window returned, and anything that cut\",\n `between them. The control plane returns at most ${SERVER_MAX_TAIL_LINES} lines per pod.`\n ]\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA,IAAM,cAA4B;CAC9B,SAAS;CACT,SACI;AACR;AAEA,SAAS,YAAY,MAA4B;CAC7C,OAAO;EAAE,SAAS;EACtB,SAAS,6BAA6B;CAAO;AAC7C;;;;;AAMA,IAAa,SAAsB;CAC/B;EACI,IAAI;EACJ,OAAO;EACP,QAAQ;EACR,YAAY;EACZ,SAAS;EACT,YAAY,WAAW;GACnB,IAAI,WAAW,MAAM,OAAO;GAC5B,IAAI,WAAW,KAAK,OAAO;IAAE,SAAS;IAClD,SAAS;GAAgC;GAC7B,IAAI,WAAW,KACX,OAAO;IACH,SAAS;IACT,SACI;GACR;GAEJ,IAAI,UAAU,KAAK,OAAO,YAAY,gCAAgC;GACtE,OAAO;IAAE,SAAS;IAC9B,SAAS;GAAmC;EACpC;CACJ;CACA;EACI,IAAI;EACJ,OAAO;EACP,QAAQ;EACR,YAAY;EACZ,SAAS;EACT,YAAY,WAAW;GACnB,IAAI,WAAW,MAAM,OAAO;GAC5B,IAAI,WAAW,KAAK,OAAO;IAAE,SAAS;IAClD,SAAS;GAAsC;GACnC,IAAI,WAAW,KAC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,UAAU,IAAI;GAAE;GAC3B;IAAE,QAAQ;IACtB,SAAS;IACT,aAAa;IACb,OAAO,gBAAgB,UAAU,MAAM;GAAE;GAC7B;IAAE,QAAQ;IACtB,SAAS;IACT,aAAa;IACb,OAAO,YAAY,mBAAmB,KAAK;GAAE;GACjC;IAAE,QAAQ;IACtB,SAAS;IACT,aAAa;IACb,OAAO,gBAAgB,UAAU,IAAI;GAAE;GAC3B;IAAE,QAAQ;IACtB,SAAS;IACT,aAAa;GAAgD;GACjD;IAAE,QAAQ;IACtB,SAAS;IACT,aAAa;GAAmE;EACxE;EACA,OAAO;GACH;GACA;GACA;GACA,mDAAmD,sBAAsB;EAC7E;CACJ,CAAC;AACL"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
|
-
import { C as resolveBackendPaths } from "./manifest-
|
|
3
|
-
import { n as cliVersion } from "./version-
|
|
2
|
+
import { C as resolveBackendPaths } from "./manifest-RjqxfCpb.js";
|
|
3
|
+
import { n as cliVersion } from "./version-ONIeo7jl.js";
|
|
4
4
|
import { t as createSchemaModuleImporter } from "./import-schema-module-Df67TIWj.js";
|
|
5
5
|
import { t as analyseFunctionsDirectory } from "./function-portability-BIvlvR9q.js";
|
|
6
6
|
import fs from "fs";
|
|
@@ -468,4 +468,4 @@ function projectResourceGraph(graph) {
|
|
|
468
468
|
//#endregion
|
|
469
469
|
export { projectResourceGraph as a, withImplicitDefaults as c, derive_exports as i, writeResourceGraphFile as l, deriveOptionsFor as n, readResourceGraphFile as o, deriveResourceGraph as r, serializeResourceGraph as s, RESOURCE_GRAPH_FILENAME as t };
|
|
470
470
|
|
|
471
|
-
//# sourceMappingURL=derive-
|
|
471
|
+
//# sourceMappingURL=derive-Mky_u59_.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"derive-C3ezmY-p.js","names":[],"sources":["../src/resources/derive.ts"],"sourcesContent":["/**\n * Deriving the resource graph from a project's backend, and recording it.\n *\n * ## Why the graph is derived rather than authored\n *\n * A resource is declared once, in code. But a host has to know what a project\n * needs *before* it runs anything — that is how a console can say \"this project\n * wants a `media` bucket and has none\" on a first deploy, and it is the reason\n * storage topology used to be hand-written into `rebase.json` in the first\n * place. A `custom` runtime makes it sharper still: it emits no bundle\n * manifest, so without a committed artifact there is nothing to read at all.\n *\n * So the graph is derived by evaluating `backend/resources.ts` and the tables\n * in `backend/schema`, and written to\n * `rebase.resources.json`, which is committed. Same arrangement as\n * `schema.generated.ts`: authored in one place, generated into another, and a\n * gate fails if the two disagree. The file is an *output*, never an input —\n * which is what removes the old silent merge, because there is no longer a\n * second declaration for anything to be merged with.\n *\n * ## Why evaluation rather than static analysis\n *\n * Encore parses the source and builds the graph from the AST. Rebase already\n * evaluates `backend/schema` to load the tables, and evaluation is exact where a parser\n * is approximate — a resource declared in a loop, or behind a helper, is\n * invisible to a parser and obvious to an interpreter. The cost is running user\n * code at build time, which this project already accepts everywhere else.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { createRequire } from \"module\";\nimport { fileURLToPath } from \"url\";\nimport {\n DEFAULT_RESOURCE_KEY,\n buildResourceGraph,\n declareFunction,\n declaredQueueConsumers,\n declaredResources,\n declaredSubscriptions,\n findEnvSuffixCollision,\n isResourceHandle,\n resetDeclaredQueueConsumers,\n resetDeclaredResources,\n resetDeclaredSubscriptions,\n resourceId,\n type ColumnStorage,\n type JsonShape,\n type RebaseBackendAppConfig,\n type ResourceDeclaration,\n type ResourceGraph,\n type TableDescriptor\n} from \"@rebasepro/types\";\nimport { analyseFunctionsDirectory } from \"../function-portability\";\nimport { resolveBackendPaths } from \"../manifest\";\nimport { createSchemaModuleImporter } from \"../utils/import-schema-module\";\nimport type { ModuleAliases } from \"../utils/project-schema\";\nimport type { SchemaModuleImporter } from \"@rebasepro/server\";\nimport { cliVersion } from \"../utils/version\";\n\n/** The committed, generated record of what a project needs. */\nexport const RESOURCE_GRAPH_FILENAME = \"rebase.resources.json\";\n\n/** A problem found while deriving, reported with the rest rather than thrown one at a time. */\nexport interface ResourceIssue {\n path: string;\n message: string;\n}\n\n/**\n * Which `@rebasepro/*` package a module error is about, when it is about one.\n *\n * Both directions of a version skew arrive as an error about the *user's* file:\n * `resources.ts The requested module '@rebasepro/types' does not provide an\n * export named 'queue'`. Nothing in that says which copy of `@rebasepro/types`\n * is installed, what version this CLI is, or that the two disagree — so the\n * reader goes looking for a typo in code they just copied out of the docs.\n *\n * Two shapes, because the two directions produce different errors: a named\n * export the installed copy is too old for, and a package the installed tree\n * does not have at all.\n */\nconst NAMED_EXPORT_MISSING = /does not provide an export named ['\"]([^'\"]+)['\"]/;\nconst SPECIFIER = /(@rebasepro\\/[a-z0-9-]+)/;\n\n/** The version of a package as resolved from the project, or null. */\nfunction installedVersion(specifier: string, from: string): string | null {\n try {\n const require = createRequire(path.join(from, \"noop.js\"));\n const manifest = require.resolve(`${specifier}/package.json`);\n const version: unknown = JSON.parse(fs.readFileSync(manifest, \"utf-8\")).version;\n return typeof version === \"string\" ? version : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The message an issue carries, with the skew named when there is one.\n *\n * `main` runs 497 commits ahead of npm `latest` and the docs site publishes from\n * `main`, so the shape this exists for is routine: a scaffold pinned to the\n * published version, backend code written against today's documentation, and an\n * error about the project's file. The fix is one command and the error named none\n * of it — the same failure as `404 No PUT route on collection 'projects'`, one\n * layer down.\n *\n * Says nothing extra when the two versions agree, or when either is unreadable:\n * a sentence naming one version twice is worse than no sentence.\n */\nexport function describeIssue(err: unknown, projectRoot: string, ownVersion = cliVersion()): string {\n const message = err instanceof Error ? err.message : String(err);\n const code = (err as { code?: unknown } | null)?.code;\n const missingExport = NAMED_EXPORT_MISSING.exec(message);\n const isSkewShaped = missingExport !== null || code === \"ERR_MODULE_NOT_FOUND\";\n if (!isSkewShaped) return message;\n\n const specifier = SPECIFIER.exec(message)?.[1];\n if (!specifier) return message;\n\n // One line, not two: every caller renders an issue as `path message` on a\n // single row, so a newline here would land the useful half unindented under\n // the file name.\n const lead = /[.!?]$/.test(message.trim()) ? message.trim() : `${message.trim()}.`;\n\n const installed = installedVersion(specifier, projectRoot);\n if (installed === null) {\n return `${lead} ${specifier} is not installed in this project; this CLI is ${ownVersion}. `\n + `Run pnpm add ${specifier}@${ownVersion}`;\n }\n if (ownVersion === \"unknown\" || installed === ownVersion) return message;\n\n // Which side to move is the question the reader actually has, and it has a\n // right answer: the CLI is what evaluates this file, so the packages follow\n // it — unless the CLI is the older one, in which case following it would\n // move the project backwards.\n const cliIsNewer = compareVersions(ownVersion, installed) > 0;\n return cliIsNewer\n ? `${lead} ${specifier} ${installed} is installed; this CLI is ${ownVersion}. `\n + `Run pnpm add ${specifier}@${ownVersion}`\n : `${lead} ${specifier} ${installed} is installed; this CLI is ${ownVersion}, which is older. `\n + `Update the CLI to ${installed}, or pin ${specifier} back to ${ownVersion}`;\n}\n\n/** -1 / 0 / 1 on the numeric parts, ignoring any prerelease tail. */\nfunction compareVersions(a: string, b: string): number {\n const parts = (v: string): number[] => v.split(\"-\")[0].split(\".\").map(n => Number(n) || 0);\n const [x, y] = [parts(a), parts(b)];\n for (let i = 0; i < 3; i++) {\n if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) < (y[i] ?? 0) ? -1 : 1;\n }\n return 0;\n}\n\n/** The spellings of the resources module, tried in order, after its path without extension. */\nconst RESOURCE_MODULE_SUFFIXES = [\".ts\", \".mts\", \".js\", \".mjs\", \"/index.ts\", \"/index.js\"];\n\n/** The resources module under `base` (a path without extension), or undefined. */\nfunction findResourcesModule(base: string): string | undefined {\n return RESOURCE_MODULE_SUFFIXES.map(suffix => `${base}${suffix}`)\n .find(candidate => fs.existsSync(candidate) && fs.statSync(candidate).isFile());\n}\n\nexport interface DeriveOptions {\n /** The project root, absolute: what the importer is rooted at and every recorded path is relative to. */\n projectRoot: string;\n /**\n * The resources module, absolute, without or with its extension:\n * `<root>/backend/resources`. Its `database()` / `bucket()` / `topic()` /\n * `queue()` declarations are the graph's nodes.\n */\n resources?: string;\n /**\n * The schema directory, absolute. Its tables are evaluated too: a table\n * reaches its database and every bucket a storage column stores into, and a\n * bucket may be declared beside the table that stores into it.\n */\n schemaDir?: string;\n /**\n * Absolute path to the crons directory. Each file is evaluated through the\n * same loader the runtime uses, which declares the cron under the same id\n * the scheduler runs it as. Absent, or missing on disk: no crons.\n */\n cronsDir?: string;\n /**\n * Absolute path to the functions directory. Read statically — the\n * bundler's portability analysis — never evaluated: a function's module\n * scope belongs to a running backend, not a build.\n */\n functionsDir?: string;\n /** Module specifiers mapped to files when importing (in-repo runs and tests). */\n moduleAliases?: ModuleAliases;\n}\n\n/** The derive options for a backend app, from its manifest entry. */\nexport function deriveOptionsFor(projectRoot: string, app: RebaseBackendAppConfig): DeriveOptions {\n const paths = resolveBackendPaths(app, projectRoot);\n return {\n projectRoot,\n resources: path.join(projectRoot, paths.resources).replace(/\\.[mc]?[jt]s$/, \"\"),\n schemaDir: path.join(projectRoot, paths.tables),\n cronsDir: path.join(projectRoot, paths.crons),\n functionsDir: path.join(projectRoot, paths.functions)\n };\n}\n\n/** Every storage setting in a JSON shape, with its dotted path below the column. */\nfunction jsonStorage(shape: JsonShape, prefix: string): Array<[string, ColumnStorage]> {\n switch (shape.kind) {\n case \"string\":\n return shape.storage ? [[prefix, shape.storage]] : [];\n case \"object\":\n return Object.entries(shape.fields).flatMap(([name, field]) => jsonStorage(field, `${prefix}.${name}`));\n case \"array\":\n return jsonStorage(shape.of, prefix);\n case \"oneOf\":\n return Object.entries(shape.variants).flatMap(([name, variant]) => jsonStorage(variant, `${prefix}.${name}`));\n default:\n return [];\n }\n}\n\n/**\n * Every storage setting a table's columns carry, keyed by the dotted path to\n * it: a storage column, the items of a storage array, a file inside a JSON\n * document.\n */\nfunction tableStorage(table: TableDescriptor): Array<[string, ColumnStorage]> {\n return table.columns.flatMap((column): Array<[string, ColumnStorage]> => [\n ...(column.storage ? [[column.key, column.storage] satisfies [string, ColumnStorage]] : []),\n ...(column.element?.storage ? [[column.key, column.element.storage] satisfies [string, ColumnStorage]] : []),\n ...(column.json ? jsonStorage(column.json, column.key) : [])\n ]);\n}\n\n/**\n * The resources a table reaches: its database, and every bucket a storage\n * column stores into. Only resources the graph declares get an edge — the\n * implicit default database is not in the graph, so a table that names no\n * `database` records nothing.\n *\n * The ids are `table:<slug>` and `column:<slug>.<path>`; a host's topology\n * view parses them.\n */\nfunction tableEdges(table: TableDescriptor, declared: Set<string>): Array<[string, string]> {\n const edges: Array<[string, string]> = [];\n const databaseId = resourceId(\"database\", table.database ?? DEFAULT_RESOURCE_KEY);\n if (declared.has(databaseId)) edges.push([databaseId, `table:${table.slug}`]);\n for (const [where, storage] of tableStorage(table)) {\n const bucketId = resourceId(\"bucket\", storage.source ?? DEFAULT_RESOURCE_KEY);\n if (declared.has(bucketId)) edges.push([bucketId, `column:${table.slug}.${where}`]);\n }\n return edges;\n}\n\n/**\n * A cron file that would not import, said in terms somebody can act on.\n *\n * The graph is derived by evaluating each cron module, in a process with none\n * of the deployment's environment — so a cron that reaches a module validating\n * `DATABASE_URL` at import fails here and works perfectly at boot. The raw\n * message is a Zod error about a variable, which reads as \"the environment is\n * wrong\" when the environment is not the point.\n */\nfunction cronLoadIssue(problem: string): string {\n return `${summariseCronProblem(problem)}\\n` +\n \" `rebase resources` evaluates each cron file to read its schedule, and it is a build \" +\n \"step: no .env, no secrets. Move work that needs the deployment's environment inside the \" +\n \"handler — `const { x } = await import(\\\"…\\\")` — so the module scope imports nothing that \" +\n \"reads configuration.\";\n}\n\n/**\n * The cron loader's `<file> (threw: <message>)`, as one line.\n *\n * The message is whatever the module threw, and the common case is a schema\n * validator: `loadEnv()` at module scope with no `.env` present throws a\n * `ZodError`, whose `.message` is the JSON array of its issues. That arrived\n * here verbatim — ten lines of `{ \"expected\": \"string\", \"code\":\n * \"invalid_type\", … }` — with the sentence that says what to do underneath it,\n * so the reader met \"Invalid input: expected string, received undefined\" twice\n * before reaching the explanation.\n *\n * A validator's own sentences are the useful half of that object, so they are\n * kept and the serialisation is dropped.\n */\nfunction summariseCronProblem(problem: string): string {\n const match = problem.match(/^(.*) \\(threw: ([\\s\\S]*)\\)$/);\n if (!match) return problem.split(\"\\n\")[0];\n const [, file, thrown] = match;\n return `${file}: ${summariseThrownMessage(thrown)}`;\n}\n\n/** One sentence out of a thrown message, whatever shape it arrived in. */\nfunction summariseThrownMessage(message: string): string {\n const trimmed = message.trim();\n if (trimmed.startsWith(\"[\") || trimmed.startsWith(\"{\")) {\n try {\n const parsed: unknown = JSON.parse(trimmed);\n const issues = Array.isArray(parsed) ? parsed : [parsed];\n const sentences = [...new Set(\n issues\n .map(issue => (issue as { message?: unknown } | null)?.message)\n .filter((m): m is string => typeof m === \"string\" && m.length > 0)\n )];\n if (sentences.length > 0) return sentences.join(\"; \");\n } catch {\n // Not JSON after all — fall through to the first line.\n }\n }\n return trimmed.split(\"\\n\")[0];\n}\n\n/**\n * Evaluate a project's resources and tables and return the graph they declare.\n *\n * Clears any previously registered declarations first, so deriving twice in one\n * process — a watch mode, a test — describes the project rather than the union\n * of every project seen so far.\n */\nexport async function deriveResourceGraph(options: DeriveOptions): Promise<{ graph: ResourceGraph; issues: ResourceIssue[] }> {\n const { projectRoot, cronsDir, functionsDir } = options;\n // One importer for everything evaluated here: the resources module, the\n // tables that import its handles and the crons see one copy of each module,\n // so a handle a table imports is the handle the graph declared. A new\n // importer reads every file as it is now, so deriving again in one process\n // evaluates the declarations again. Created on first use: a project with\n // nothing to evaluate pays nothing for it.\n let importer: SchemaModuleImporter | undefined;\n const importModule: SchemaModuleImporter = async (file) => {\n importer ??= await createSchemaModuleImporter(projectRoot, options.moduleAliases);\n return importer(file);\n };\n\n // All three registries, and the side lists are the easy ones to forget:\n // resetting only the resources leaves one project's handlers attached\n // while its topics are gone — every one of them then reads as orphaned\n // against the *next* project. Caught by deriving twice in one process,\n // which is what a watch mode does.\n resetDeclaredResources();\n resetDeclaredSubscriptions();\n resetDeclaredQueueConsumers();\n\n const issues: ResourceIssue[] = [];\n const usedBy = new Map<string, string[]>();\n // `recordUse`, not `use`: React 19 made `use` a hook name, and\n // `react-hooks/rules-of-hooks` refuses a call to one from a plain function\n // — a lint error on a file with no React in it.\n const recordUse = (resource: string, by: string): void => {\n const list = usedBy.get(resource) ?? [];\n if (!list.includes(by)) list.push(by);\n usedBy.set(resource, list);\n };\n\n // ── Declarations ─────────────────────────────────────────────────────\n // Which export name is which resource, so a function's `import { media }`\n // can be recorded as reaching `bucket:media` without evaluating the\n // function. The export name and the key are usually the same word and\n // nothing requires them to be.\n const handleExports = new Map<string, string>();\n const resourcesModule = options.resources ? findResourcesModule(options.resources.replace(/\\.[mc]?[jt]s$/, \"\")) : undefined;\n if (resourcesModule) {\n try {\n const mod = await importModule(resourcesModule);\n for (const [exportName, value] of Object.entries(mod)) {\n if (isResourceHandle(value)) handleExports.set(exportName, resourceId(value.kind, value.key));\n }\n } catch (err) {\n issues.push({ path: path.relative(projectRoot, resourcesModule), message: describeIssue(err, projectRoot) });\n }\n }\n\n // ── Tables ───────────────────────────────────────────────────────────\n // Through the loader the runtime boots from, so a table that would not\n // load at boot is an issue here too, named by its file and table.\n let tables: TableDescriptor[] = [];\n if (options.schemaDir) {\n try {\n const { loadBackendSchema, compileLoadedSchema } = await import(\"@rebasepro/server\");\n const loaded = await loadBackendSchema(options.schemaDir, { projectRoot, importModule });\n tables = compileLoadedSchema(loaded).descriptors;\n } catch (err) {\n // Imported here: `@rebasepro/common` is the whole compiler, and a\n // derivation that never reads a schema has no use for it.\n const { isSchemaDefinitionError } = await import(\"@rebasepro/common\");\n if (isSchemaDefinitionError(err)) {\n for (const problem of err.problems) {\n issues.push({\n path: `table.${problem.key ? `${problem.table}.${problem.key}` : problem.table}`,\n message: problem.message\n });\n }\n } else {\n const file = typeof err === \"object\" && err !== null && \"file\" in err && typeof err.file === \"string\"\n ? err.file\n : options.schemaDir;\n issues.push({ path: path.relative(projectRoot, file), message: describeIssue(err, projectRoot) });\n }\n }\n }\n\n // ── Crons ────────────────────────────────────────────────────────────\n // Through the runtime's own loader, so the id the graph records is the id\n // the scheduler runs — the filename — and a cron that would not load at\n // boot does not load here either.\n //\n // Which means the module is EVALUATED, in a build step that has none of the\n // deployment's environment. A cron whose module scope reaches something that\n // validates `DATABASE_URL` at import therefore derives on a laptop with a\n // `.env` and nowhere else. That is worth an explicit sentence rather than a\n // stack, so `cronLoadIssue` adds one.\n if (cronsDir && fs.existsSync(cronsDir)) {\n // The runtime's loader logs each job as it loads, to stdout, as JSON\n // — which is also where `rebase resources --json` writes the graph.\n // Its problems come back as a list, so the log adds nothing here.\n const previousLevel = process.env.LOG_LEVEL;\n process.env.LOG_LEVEL = \"error\";\n try {\n const { loadCrons, declareCrons } = await import(\"@rebasepro/server\");\n const reportProblem = (problem: string) => {\n issues.push({ path: path.relative(projectRoot, cronsDir), message: cronLoadIssue(problem) });\n };\n // The importer above, not the loader's `new Function` import: plain\n // Node cannot import TypeScript, and a test runner's module sandbox\n // answers that one with \"a dynamic import callback was not\n // specified\" — the same trap the split-roles e2e records.\n const crons = await loadCrons(cronsDir, {\n importModule: url => importModule(url.startsWith(\"file:\") ? fileURLToPath(url) : url),\n onSkip: reportProblem\n });\n // One at a time, so a cron the graph refuses is reported by name\n // and the others are still declared.\n for (const [id, definition] of Object.entries(crons)) {\n try {\n declareCrons({ [id]: definition });\n } catch (err) {\n reportProblem(`${id} (threw: ${err instanceof Error ? err.message : String(err)})`);\n }\n }\n } catch (err) {\n issues.push({\n path: path.relative(projectRoot, cronsDir),\n message: cronLoadIssue(err instanceof Error ? err.message : String(err))\n });\n } finally {\n if (previousLevel === undefined) delete process.env.LOG_LEVEL;\n else process.env.LOG_LEVEL = previousLevel;\n }\n }\n\n // ── Functions ────────────────────────────────────────────────────────\n if (functionsDir && fs.existsSync(functionsDir)) {\n for (const report of analyseFunctionsDirectory(functionsDir, projectRoot)) {\n const requires = [...new Set(\n report.issues\n .filter(issue => issue.kind === \"node-builtin\" || issue.kind === \"node-only-package\")\n .map(issue => issue.message)\n )];\n try {\n declareFunction(report.name, {\n file: report.file,\n portable: report.portable,\n ...(requires.length > 0 ? { requires } : {})\n });\n } catch (err) {\n issues.push({ path: report.file, message: describeIssue(err, projectRoot) });\n }\n for (const imported of report.resourceImports) {\n const resource = handleExports.get(imported);\n if (resource) recordUse(resource, `function:${report.name}`);\n }\n }\n }\n\n // ── Edges ────────────────────────────────────────────────────────────\n const declared = new Set(declaredResources().map(r => resourceId(r.kind, r.key)));\n for (const table of tables) {\n for (const [resource, by] of tableEdges(table, declared)) recordUse(resource, by);\n }\n for (const sub of declaredSubscriptions()) {\n const id = resourceId(\"topic\", sub.topic);\n if (declared.has(id)) recordUse(id, `subscription:${sub.topic}.${sub.name}`);\n }\n for (const consumer of declaredQueueConsumers()) {\n const id = resourceId(\"queue\", consumer.queue);\n if (declared.has(id)) recordUse(id, `handler:${consumer.queue}`);\n }\n\n const graph = buildResourceGraph(usedBy);\n\n // Two resources of a kind whose env suffixes collide would silently read\n // each other's configuration, which is indistinguishable from a\n // misconfigured deployment.\n const byKind = new Map<string, string[]>();\n for (const r of graph.resources) {\n byKind.set(r.kind, [...(byKind.get(r.kind) ?? []), r.key]);\n }\n for (const [kind, keys] of byKind) {\n const collision = findEnvSuffixCollision(keys);\n if (collision) {\n issues.push({\n path: `${kind}.${collision.b}`,\n message:\n `\"${collision.a}\" and \"${collision.b}\" both bind from ${collision.suffix}, so one would ` +\n \"read the other's configuration. Rename one.\"\n });\n }\n }\n\n // A subscription on a topic nobody declared is a handler that will never\n // run, and nothing else would ever say so.\n const topics = new Set(graph.resources.filter(r => r.kind === \"topic\").map(r => r.key));\n for (const sub of declaredSubscriptions()) {\n if (!topics.has(sub.topic)) {\n issues.push({\n path: `topic.${sub.topic}`,\n message:\n `Subscription \"${sub.name}\" is declared on topic \"${sub.topic}\", which nothing declares. ` +\n \"The handler would never run.\"\n });\n }\n }\n\n // A table routed to a database nothing declares boots into a refusal, and\n // a column stored in a bucket nothing declares answers 501 on its first\n // upload. Both are cheaper to hear about here.\n const databases = new Set(graph.resources.filter(r => r.kind === \"database\").map(r => r.key));\n const buckets = new Set(graph.resources.filter(r => r.kind === \"bucket\").map(r => r.key));\n for (const table of tables) {\n if (table.database && table.database !== DEFAULT_RESOURCE_KEY && !databases.has(table.database)) {\n issues.push({\n path: `table.${table.slug}`,\n message:\n `lives in database \"${table.database}\", which nothing declares. ` +\n `Add database(\"${table.database}\") to backend/resources.ts, or import the handle and use it here.`\n });\n }\n for (const [where, storage] of tableStorage(table)) {\n const key = storage.source;\n if (key !== undefined && key !== DEFAULT_RESOURCE_KEY && buckets.size > 0 && !buckets.has(key)) {\n issues.push({\n path: `table.${table.slug}.${where}`,\n message: `stores into bucket \"${key}\", which nothing declares. Add bucket(\"${key}\") to backend/resources.ts.`\n });\n }\n }\n }\n\n return { graph, issues };\n}\n\n/** The graph as it is written to disk: stable key order, trailing newline. */\nexport function serializeResourceGraph(graph: ResourceGraph): string {\n const resources = graph.resources.map(r => ({\n kind: r.kind,\n key: r.key,\n engine: r.engine,\n transport: r.transport,\n ...(r.label !== undefined ? { label: r.label } : {}),\n ...(Object.keys(r.options).length > 0 ? { options: r.options } : {}),\n ...(r.usedBy && r.usedBy.length > 0 ? { usedBy: r.usedBy } : {})\n }));\n return JSON.stringify({\n $generated: `Generated from backend/resources.ts and backend/schema by \\`rebase resources\\`. Edit the declarations, not this file.`,\n version: graph.version,\n resources\n }, null, 4) + \"\\n\";\n}\n\n/** Read the committed graph, or null when a project has none yet. */\nexport function readResourceGraphFile(projectRoot: string): string | null {\n const file = path.join(projectRoot, RESOURCE_GRAPH_FILENAME);\n return fs.existsSync(file) ? fs.readFileSync(file, \"utf-8\") : null;\n}\n\n/**\n * Write the graph, and say whether the file changed.\n *\n * The boolean is what a `--check` mode reports on: a project whose committed\n * graph disagrees with its declarations has a host reading one thing and a runtime\n * doing another.\n */\nexport function writeResourceGraphFile(projectRoot: string, graph: ResourceGraph): { changed: boolean; file: string } {\n const file = path.join(projectRoot, RESOURCE_GRAPH_FILENAME);\n const next = serializeResourceGraph(graph);\n const previous = fs.existsSync(file) ? fs.readFileSync(file, \"utf-8\") : null;\n if (previous === next) return { changed: false, file };\n fs.writeFileSync(file, next);\n return { changed: true, file };\n}\n\n/** Parse a committed graph file, tolerating the `$generated` banner. */\nexport function parseResourceGraph(contents: string): ResourceGraph {\n const raw = JSON.parse(contents) as { version?: number; resources?: unknown };\n if (raw.version !== 1) {\n throw new Error(\n `Unsupported resource graph version ${String(raw.version)}. ` +\n \"This project was generated by a newer Rebase; upgrade rather than provisioning half of it.\"\n );\n }\n const entries = Array.isArray(raw.resources) ? raw.resources as Record<string, unknown>[] : [];\n // `options` is omitted from the file when empty; a reader of the graph\n // expects it present, so it is restored here.\n return { version: 1, resources: entries.map(r => ({ options: {}, ...r })) as ResourceGraph[\"resources\"] };\n}\n\n/**\n * Add the resources a project has without declaring them.\n *\n * A backend has a database whether or not anyone said so, and a project that\n * declares no buckets still gets one default storage source from the plain\n * unsuffixed variables. Both are load-bearing defaults and both are invisible\n * in the graph, so a status view built only from declarations would show an\n * empty screen to the majority of projects — the ones that most need to be told\n * which variable their one database reads.\n *\n * Declaring a *named* one leaves the default where it is, as the server does\n * (`resolveDataSources` and `resolveStorageSources` in `@rebasepro/server`):\n * `bucket(\"media\")` adds a source and never moves the files the default holds,\n * so both are listed. The default is displaced only by declaring it — or, for a\n * bucket, by marking exactly one server-side bucket `default: true`, which then\n * serves the uploads that name no `storageSource`. This used to drop the\n * default once a bucket was declared, and `rebase status` and `rebase\n * resources` stopped listing a source the server was still serving.\n */\nexport function withImplicitDefaults(graph: ResourceGraph): {\n declaration: ResourceDeclaration;\n implicit: boolean;\n}[] {\n const entries = graph.resources.map(declaration => ({ declaration, implicit: false }));\n const declaresDefault = (kind: string) => graph.resources.some(r => r.kind === kind && r.key === DEFAULT_RESOURCE_KEY);\n const markedDefault = graph.resources.filter(r =>\n r.kind === \"bucket\" && (r.transport ?? \"server\") === \"server\" && r.options.default === true);\n\n if (!declaresDefault(\"database\")) {\n entries.unshift({\n declaration: {\n kind: \"database\",\n key: DEFAULT_RESOURCE_KEY,\n engine: \"postgres\",\n transport: \"server\",\n options: {}\n },\n implicit: true\n });\n }\n if (!declaresDefault(\"bucket\") && markedDefault.length !== 1) {\n const implicitBucket = {\n declaration: {\n kind: \"bucket\",\n key: DEFAULT_RESOURCE_KEY,\n // `local` is what an unconfigured default source resolves to,\n // and naming it here keeps the row honest about what a project\n // with no S3 variables actually gets: a directory that a\n // container erases on restart, which production then drops.\n engine: \"local\",\n transport: \"server\" as const,\n options: {}\n },\n implicit: true\n };\n // First among the buckets, as the database default is first among the\n // databases; last when there are none.\n const firstBucket = entries.findIndex(entry => entry.declaration.kind === \"bucket\");\n if (firstBucket === -1) entries.push(implicitBucket);\n else entries.splice(firstBucket, 0, implicitBucket);\n }\n return entries;\n}\n\n/**\n * The resources a project *has*, which is what a person is asking about.\n *\n * One projection, because two of them disagreed. `rebase status` built its\n * rows from {@link withImplicitDefaults} and listed `buckets ✓ (default) local\n * · implicit`; `rebase resources` and `rebase resources --json` built theirs\n * from the raw graph and listed only the database and the function. Two\n * commands whose whole job is to answer \"what does this project need\", on the\n * same stock scaffold, giving different answers.\n *\n * The implicit entries are marked rather than hidden, because the distinction\n * is real and load-bearing: a declared resource is recorded in\n * `rebase.resources.json` for a host to provision, and an implicit one is a\n * default the runtime supplies whether or not anyone wrote it down. That file\n * still holds declarations only — it is a wire contract a host reads, and\n * putting defaults in it would ask for something to be provisioned that\n * nobody declared.\n */\nexport type ProjectedResource = ResourceDeclaration & { implicit?: true };\n\nexport function projectResourceGraph(graph: ResourceGraph): ProjectedResource[] {\n return withImplicitDefaults(graph).map(({ declaration, implicit }) =>\n (implicit ? { ...declaration, implicit: true as const } : declaration));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,IA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CAAC,CAAC,KAAK,EAAE,aAAa,eAClD,WAAW;EAAE,GAAG;EAAa,UAAU;CAAc,IAAI,WAAY;AAC9E"}
|
|
1
|
+
{"version":3,"file":"derive-Mky_u59_.js","names":[],"sources":["../src/resources/derive.ts"],"sourcesContent":["/**\n * Deriving the resource graph from a project's backend, and recording it.\n *\n * ## Why the graph is derived rather than authored\n *\n * A resource is declared once, in code. But a host has to know what a project\n * needs *before* it runs anything — that is how a console can say \"this project\n * wants a `media` bucket and has none\" on a first deploy, and it is the reason\n * storage topology used to be hand-written into `rebase.json` in the first\n * place. A `custom` runtime makes it sharper still: it emits no bundle\n * manifest, so without a committed artifact there is nothing to read at all.\n *\n * So the graph is derived by evaluating `backend/resources.ts` and the tables\n * in `backend/schema`, and written to\n * `rebase.resources.json`, which is committed. Same arrangement as\n * `schema.generated.ts`: authored in one place, generated into another, and a\n * gate fails if the two disagree. The file is an *output*, never an input —\n * which is what removes the old silent merge, because there is no longer a\n * second declaration for anything to be merged with.\n *\n * ## Why evaluation rather than static analysis\n *\n * Encore parses the source and builds the graph from the AST. Rebase already\n * evaluates `backend/schema` to load the tables, and evaluation is exact where a parser\n * is approximate — a resource declared in a loop, or behind a helper, is\n * invisible to a parser and obvious to an interpreter. The cost is running user\n * code at build time, which this project already accepts everywhere else.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { createRequire } from \"module\";\nimport { fileURLToPath } from \"url\";\nimport {\n DEFAULT_RESOURCE_KEY,\n buildResourceGraph,\n declareFunction,\n declaredQueueConsumers,\n declaredResources,\n declaredSubscriptions,\n findEnvSuffixCollision,\n isResourceHandle,\n resetDeclaredQueueConsumers,\n resetDeclaredResources,\n resetDeclaredSubscriptions,\n resourceId,\n type ColumnStorage,\n type JsonShape,\n type RebaseBackendAppConfig,\n type ResourceDeclaration,\n type ResourceGraph,\n type TableDescriptor\n} from \"@rebasepro/types\";\nimport { analyseFunctionsDirectory } from \"../function-portability\";\nimport { resolveBackendPaths } from \"../manifest\";\nimport { createSchemaModuleImporter } from \"../utils/import-schema-module\";\nimport type { ModuleAliases } from \"../utils/project-schema\";\nimport type { SchemaModuleImporter } from \"@rebasepro/server\";\nimport { cliVersion } from \"../utils/version\";\n\n/** The committed, generated record of what a project needs. */\nexport const RESOURCE_GRAPH_FILENAME = \"rebase.resources.json\";\n\n/** A problem found while deriving, reported with the rest rather than thrown one at a time. */\nexport interface ResourceIssue {\n path: string;\n message: string;\n}\n\n/**\n * Which `@rebasepro/*` package a module error is about, when it is about one.\n *\n * Both directions of a version skew arrive as an error about the *user's* file:\n * `resources.ts The requested module '@rebasepro/types' does not provide an\n * export named 'queue'`. Nothing in that says which copy of `@rebasepro/types`\n * is installed, what version this CLI is, or that the two disagree — so the\n * reader goes looking for a typo in code they just copied out of the docs.\n *\n * Two shapes, because the two directions produce different errors: a named\n * export the installed copy is too old for, and a package the installed tree\n * does not have at all.\n */\nconst NAMED_EXPORT_MISSING = /does not provide an export named ['\"]([^'\"]+)['\"]/;\nconst SPECIFIER = /(@rebasepro\\/[a-z0-9-]+)/;\n\n/** The version of a package as resolved from the project, or null. */\nfunction installedVersion(specifier: string, from: string): string | null {\n try {\n const require = createRequire(path.join(from, \"noop.js\"));\n const manifest = require.resolve(`${specifier}/package.json`);\n const version: unknown = JSON.parse(fs.readFileSync(manifest, \"utf-8\")).version;\n return typeof version === \"string\" ? version : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The message an issue carries, with the skew named when there is one.\n *\n * `main` runs 497 commits ahead of npm `latest` and the docs site publishes from\n * `main`, so the shape this exists for is routine: a scaffold pinned to the\n * published version, backend code written against today's documentation, and an\n * error about the project's file. The fix is one command and the error named none\n * of it — the same failure as `404 No PUT route on collection 'projects'`, one\n * layer down.\n *\n * Says nothing extra when the two versions agree, or when either is unreadable:\n * a sentence naming one version twice is worse than no sentence.\n */\nexport function describeIssue(err: unknown, projectRoot: string, ownVersion = cliVersion()): string {\n const message = err instanceof Error ? err.message : String(err);\n const code = (err as { code?: unknown } | null)?.code;\n const missingExport = NAMED_EXPORT_MISSING.exec(message);\n const isSkewShaped = missingExport !== null || code === \"ERR_MODULE_NOT_FOUND\";\n if (!isSkewShaped) return message;\n\n const specifier = SPECIFIER.exec(message)?.[1];\n if (!specifier) return message;\n\n // One line, not two: every caller renders an issue as `path message` on a\n // single row, so a newline here would land the useful half unindented under\n // the file name.\n const lead = /[.!?]$/.test(message.trim()) ? message.trim() : `${message.trim()}.`;\n\n const installed = installedVersion(specifier, projectRoot);\n if (installed === null) {\n return `${lead} ${specifier} is not installed in this project; this CLI is ${ownVersion}. `\n + `Run pnpm add ${specifier}@${ownVersion}`;\n }\n if (ownVersion === \"unknown\" || installed === ownVersion) return message;\n\n // Which side to move is the question the reader actually has, and it has a\n // right answer: the CLI is what evaluates this file, so the packages follow\n // it — unless the CLI is the older one, in which case following it would\n // move the project backwards.\n const cliIsNewer = compareVersions(ownVersion, installed) > 0;\n return cliIsNewer\n ? `${lead} ${specifier} ${installed} is installed; this CLI is ${ownVersion}. `\n + `Run pnpm add ${specifier}@${ownVersion}`\n : `${lead} ${specifier} ${installed} is installed; this CLI is ${ownVersion}, which is older. `\n + `Update the CLI to ${installed}, or pin ${specifier} back to ${ownVersion}`;\n}\n\n/** -1 / 0 / 1 on the numeric parts, ignoring any prerelease tail. */\nfunction compareVersions(a: string, b: string): number {\n const parts = (v: string): number[] => v.split(\"-\")[0].split(\".\").map(n => Number(n) || 0);\n const [x, y] = [parts(a), parts(b)];\n for (let i = 0; i < 3; i++) {\n if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) < (y[i] ?? 0) ? -1 : 1;\n }\n return 0;\n}\n\n/** The spellings of the resources module, tried in order, after its path without extension. */\nconst RESOURCE_MODULE_SUFFIXES = [\".ts\", \".mts\", \".js\", \".mjs\", \"/index.ts\", \"/index.js\"];\n\n/** The resources module under `base` (a path without extension), or undefined. */\nfunction findResourcesModule(base: string): string | undefined {\n return RESOURCE_MODULE_SUFFIXES.map(suffix => `${base}${suffix}`)\n .find(candidate => fs.existsSync(candidate) && fs.statSync(candidate).isFile());\n}\n\nexport interface DeriveOptions {\n /** The project root, absolute: what the importer is rooted at and every recorded path is relative to. */\n projectRoot: string;\n /**\n * The resources module, absolute, without or with its extension:\n * `<root>/backend/resources`. Its `database()` / `bucket()` / `topic()` /\n * `queue()` declarations are the graph's nodes.\n */\n resources?: string;\n /**\n * The schema directory, absolute. Its tables are evaluated too: a table\n * reaches its database and every bucket a storage column stores into, and a\n * bucket may be declared beside the table that stores into it.\n */\n schemaDir?: string;\n /**\n * Absolute path to the crons directory. Each file is evaluated through the\n * same loader the runtime uses, which declares the cron under the same id\n * the scheduler runs it as. Absent, or missing on disk: no crons.\n */\n cronsDir?: string;\n /**\n * Absolute path to the functions directory. Read statically — the\n * bundler's portability analysis — never evaluated: a function's module\n * scope belongs to a running backend, not a build.\n */\n functionsDir?: string;\n /** Module specifiers mapped to files when importing (in-repo runs and tests). */\n moduleAliases?: ModuleAliases;\n}\n\n/** The derive options for a backend app, from its manifest entry. */\nexport function deriveOptionsFor(projectRoot: string, app: RebaseBackendAppConfig): DeriveOptions {\n const paths = resolveBackendPaths(app, projectRoot);\n return {\n projectRoot,\n resources: path.join(projectRoot, paths.resources).replace(/\\.[mc]?[jt]s$/, \"\"),\n schemaDir: path.join(projectRoot, paths.tables),\n cronsDir: path.join(projectRoot, paths.crons),\n functionsDir: path.join(projectRoot, paths.functions)\n };\n}\n\n/** Every storage setting in a JSON shape, with its dotted path below the column. */\nfunction jsonStorage(shape: JsonShape, prefix: string): Array<[string, ColumnStorage]> {\n switch (shape.kind) {\n case \"string\":\n return shape.storage ? [[prefix, shape.storage]] : [];\n case \"object\":\n return Object.entries(shape.fields).flatMap(([name, field]) => jsonStorage(field, `${prefix}.${name}`));\n case \"array\":\n return jsonStorage(shape.of, prefix);\n case \"oneOf\":\n return Object.entries(shape.variants).flatMap(([name, variant]) => jsonStorage(variant, `${prefix}.${name}`));\n default:\n return [];\n }\n}\n\n/**\n * Every storage setting a table's columns carry, keyed by the dotted path to\n * it: a storage column, the items of a storage array, a file inside a JSON\n * document.\n */\nfunction tableStorage(table: TableDescriptor): Array<[string, ColumnStorage]> {\n return table.columns.flatMap((column): Array<[string, ColumnStorage]> => [\n ...(column.storage ? [[column.key, column.storage] satisfies [string, ColumnStorage]] : []),\n ...(column.element?.storage ? [[column.key, column.element.storage] satisfies [string, ColumnStorage]] : []),\n ...(column.json ? jsonStorage(column.json, column.key) : [])\n ]);\n}\n\n/**\n * The resources a table reaches: its database, and every bucket a storage\n * column stores into. Only resources the graph declares get an edge — the\n * implicit default database is not in the graph, so a table that names no\n * `database` records nothing.\n *\n * The ids are `table:<slug>` and `column:<slug>.<path>`; a host's topology\n * view parses them.\n */\nfunction tableEdges(table: TableDescriptor, declared: Set<string>): Array<[string, string]> {\n const edges: Array<[string, string]> = [];\n const databaseId = resourceId(\"database\", table.database ?? DEFAULT_RESOURCE_KEY);\n if (declared.has(databaseId)) edges.push([databaseId, `table:${table.slug}`]);\n for (const [where, storage] of tableStorage(table)) {\n const bucketId = resourceId(\"bucket\", storage.source ?? DEFAULT_RESOURCE_KEY);\n if (declared.has(bucketId)) edges.push([bucketId, `column:${table.slug}.${where}`]);\n }\n return edges;\n}\n\n/**\n * A cron file that would not import, said in terms somebody can act on.\n *\n * The graph is derived by evaluating each cron module, in a process with none\n * of the deployment's environment — so a cron that reaches a module validating\n * `DATABASE_URL` at import fails here and works perfectly at boot. The raw\n * message is a Zod error about a variable, which reads as \"the environment is\n * wrong\" when the environment is not the point.\n */\nfunction cronLoadIssue(problem: string): string {\n return `${summariseCronProblem(problem)}\\n` +\n \" `rebase resources` evaluates each cron file to read its schedule, and it is a build \" +\n \"step: no .env, no secrets. Move work that needs the deployment's environment inside the \" +\n \"handler — `const { x } = await import(\\\"…\\\")` — so the module scope imports nothing that \" +\n \"reads configuration.\";\n}\n\n/**\n * The cron loader's `<file> (threw: <message>)`, as one line.\n *\n * The message is whatever the module threw, and the common case is a schema\n * validator: `loadEnv()` at module scope with no `.env` present throws a\n * `ZodError`, whose `.message` is the JSON array of its issues. That arrived\n * here verbatim — ten lines of `{ \"expected\": \"string\", \"code\":\n * \"invalid_type\", … }` — with the sentence that says what to do underneath it,\n * so the reader met \"Invalid input: expected string, received undefined\" twice\n * before reaching the explanation.\n *\n * A validator's own sentences are the useful half of that object, so they are\n * kept and the serialisation is dropped.\n */\nfunction summariseCronProblem(problem: string): string {\n const match = problem.match(/^(.*) \\(threw: ([\\s\\S]*)\\)$/);\n if (!match) return problem.split(\"\\n\")[0];\n const [, file, thrown] = match;\n return `${file}: ${summariseThrownMessage(thrown)}`;\n}\n\n/** One sentence out of a thrown message, whatever shape it arrived in. */\nfunction summariseThrownMessage(message: string): string {\n const trimmed = message.trim();\n if (trimmed.startsWith(\"[\") || trimmed.startsWith(\"{\")) {\n try {\n const parsed: unknown = JSON.parse(trimmed);\n const issues = Array.isArray(parsed) ? parsed : [parsed];\n const sentences = [...new Set(\n issues\n .map(issue => (issue as { message?: unknown } | null)?.message)\n .filter((m): m is string => typeof m === \"string\" && m.length > 0)\n )];\n if (sentences.length > 0) return sentences.join(\"; \");\n } catch {\n // Not JSON after all — fall through to the first line.\n }\n }\n return trimmed.split(\"\\n\")[0];\n}\n\n/**\n * Evaluate a project's resources and tables and return the graph they declare.\n *\n * Clears any previously registered declarations first, so deriving twice in one\n * process — a watch mode, a test — describes the project rather than the union\n * of every project seen so far.\n */\nexport async function deriveResourceGraph(options: DeriveOptions): Promise<{ graph: ResourceGraph; issues: ResourceIssue[] }> {\n const { projectRoot, cronsDir, functionsDir } = options;\n // One importer for everything evaluated here: the resources module, the\n // tables that import its handles and the crons see one copy of each module,\n // so a handle a table imports is the handle the graph declared. A new\n // importer reads every file as it is now, so deriving again in one process\n // evaluates the declarations again. Created on first use: a project with\n // nothing to evaluate pays nothing for it.\n let importer: SchemaModuleImporter | undefined;\n const importModule: SchemaModuleImporter = async (file) => {\n importer ??= await createSchemaModuleImporter(projectRoot, options.moduleAliases);\n return importer(file);\n };\n\n // All three registries, and the side lists are the easy ones to forget:\n // resetting only the resources leaves one project's handlers attached\n // while its topics are gone — every one of them then reads as orphaned\n // against the *next* project. Caught by deriving twice in one process,\n // which is what a watch mode does.\n resetDeclaredResources();\n resetDeclaredSubscriptions();\n resetDeclaredQueueConsumers();\n\n const issues: ResourceIssue[] = [];\n const usedBy = new Map<string, string[]>();\n // `recordUse`, not `use`: React 19 made `use` a hook name, and\n // `react-hooks/rules-of-hooks` refuses a call to one from a plain function\n // — a lint error on a file with no React in it.\n const recordUse = (resource: string, by: string): void => {\n const list = usedBy.get(resource) ?? [];\n if (!list.includes(by)) list.push(by);\n usedBy.set(resource, list);\n };\n\n // ── Declarations ─────────────────────────────────────────────────────\n // Which export name is which resource, so a function's `import { media }`\n // can be recorded as reaching `bucket:media` without evaluating the\n // function. The export name and the key are usually the same word and\n // nothing requires them to be.\n const handleExports = new Map<string, string>();\n const resourcesModule = options.resources ? findResourcesModule(options.resources.replace(/\\.[mc]?[jt]s$/, \"\")) : undefined;\n if (resourcesModule) {\n try {\n const mod = await importModule(resourcesModule);\n for (const [exportName, value] of Object.entries(mod)) {\n if (isResourceHandle(value)) handleExports.set(exportName, resourceId(value.kind, value.key));\n }\n } catch (err) {\n issues.push({ path: path.relative(projectRoot, resourcesModule), message: describeIssue(err, projectRoot) });\n }\n }\n\n // ── Tables ───────────────────────────────────────────────────────────\n // Through the loader the runtime boots from, so a table that would not\n // load at boot is an issue here too, named by its file and table.\n let tables: TableDescriptor[] = [];\n if (options.schemaDir) {\n try {\n const { loadBackendSchema, compileLoadedSchema } = await import(\"@rebasepro/server\");\n const loaded = await loadBackendSchema(options.schemaDir, { projectRoot, importModule });\n tables = compileLoadedSchema(loaded).descriptors;\n } catch (err) {\n // Imported here: `@rebasepro/common` is the whole compiler, and a\n // derivation that never reads a schema has no use for it.\n const { isSchemaDefinitionError } = await import(\"@rebasepro/common\");\n if (isSchemaDefinitionError(err)) {\n for (const problem of err.problems) {\n issues.push({\n path: `table.${problem.key ? `${problem.table}.${problem.key}` : problem.table}`,\n message: problem.message\n });\n }\n } else {\n const file = typeof err === \"object\" && err !== null && \"file\" in err && typeof err.file === \"string\"\n ? err.file\n : options.schemaDir;\n issues.push({ path: path.relative(projectRoot, file), message: describeIssue(err, projectRoot) });\n }\n }\n }\n\n // ── Crons ────────────────────────────────────────────────────────────\n // Through the runtime's own loader, so the id the graph records is the id\n // the scheduler runs — the filename — and a cron that would not load at\n // boot does not load here either.\n //\n // Which means the module is EVALUATED, in a build step that has none of the\n // deployment's environment. A cron whose module scope reaches something that\n // validates `DATABASE_URL` at import therefore derives on a laptop with a\n // `.env` and nowhere else. That is worth an explicit sentence rather than a\n // stack, so `cronLoadIssue` adds one.\n if (cronsDir && fs.existsSync(cronsDir)) {\n // The runtime's loader logs each job as it loads, to stdout, as JSON\n // — which is also where `rebase resources --json` writes the graph.\n // Its problems come back as a list, so the log adds nothing here.\n const previousLevel = process.env.LOG_LEVEL;\n process.env.LOG_LEVEL = \"error\";\n try {\n const { loadCrons, declareCrons } = await import(\"@rebasepro/server\");\n const reportProblem = (problem: string) => {\n issues.push({ path: path.relative(projectRoot, cronsDir), message: cronLoadIssue(problem) });\n };\n // The importer above, not the loader's `new Function` import: plain\n // Node cannot import TypeScript, and a test runner's module sandbox\n // answers that one with \"a dynamic import callback was not\n // specified\" — the same trap the split-roles e2e records.\n const crons = await loadCrons(cronsDir, {\n importModule: url => importModule(url.startsWith(\"file:\") ? fileURLToPath(url) : url),\n onSkip: reportProblem\n });\n // One at a time, so a cron the graph refuses is reported by name\n // and the others are still declared.\n for (const [id, definition] of Object.entries(crons)) {\n try {\n declareCrons({ [id]: definition });\n } catch (err) {\n reportProblem(`${id} (threw: ${err instanceof Error ? err.message : String(err)})`);\n }\n }\n } catch (err) {\n issues.push({\n path: path.relative(projectRoot, cronsDir),\n message: cronLoadIssue(err instanceof Error ? err.message : String(err))\n });\n } finally {\n if (previousLevel === undefined) delete process.env.LOG_LEVEL;\n else process.env.LOG_LEVEL = previousLevel;\n }\n }\n\n // ── Functions ────────────────────────────────────────────────────────\n if (functionsDir && fs.existsSync(functionsDir)) {\n for (const report of analyseFunctionsDirectory(functionsDir, projectRoot)) {\n const requires = [...new Set(\n report.issues\n .filter(issue => issue.kind === \"node-builtin\" || issue.kind === \"node-only-package\")\n .map(issue => issue.message)\n )];\n try {\n declareFunction(report.name, {\n file: report.file,\n portable: report.portable,\n ...(requires.length > 0 ? { requires } : {})\n });\n } catch (err) {\n issues.push({ path: report.file, message: describeIssue(err, projectRoot) });\n }\n for (const imported of report.resourceImports) {\n const resource = handleExports.get(imported);\n if (resource) recordUse(resource, `function:${report.name}`);\n }\n }\n }\n\n // ── Edges ────────────────────────────────────────────────────────────\n const declared = new Set(declaredResources().map(r => resourceId(r.kind, r.key)));\n for (const table of tables) {\n for (const [resource, by] of tableEdges(table, declared)) recordUse(resource, by);\n }\n for (const sub of declaredSubscriptions()) {\n const id = resourceId(\"topic\", sub.topic);\n if (declared.has(id)) recordUse(id, `subscription:${sub.topic}.${sub.name}`);\n }\n for (const consumer of declaredQueueConsumers()) {\n const id = resourceId(\"queue\", consumer.queue);\n if (declared.has(id)) recordUse(id, `handler:${consumer.queue}`);\n }\n\n const graph = buildResourceGraph(usedBy);\n\n // Two resources of a kind whose env suffixes collide would silently read\n // each other's configuration, which is indistinguishable from a\n // misconfigured deployment.\n const byKind = new Map<string, string[]>();\n for (const r of graph.resources) {\n byKind.set(r.kind, [...(byKind.get(r.kind) ?? []), r.key]);\n }\n for (const [kind, keys] of byKind) {\n const collision = findEnvSuffixCollision(keys);\n if (collision) {\n issues.push({\n path: `${kind}.${collision.b}`,\n message:\n `\"${collision.a}\" and \"${collision.b}\" both bind from ${collision.suffix}, so one would ` +\n \"read the other's configuration. Rename one.\"\n });\n }\n }\n\n // A subscription on a topic nobody declared is a handler that will never\n // run, and nothing else would ever say so.\n const topics = new Set(graph.resources.filter(r => r.kind === \"topic\").map(r => r.key));\n for (const sub of declaredSubscriptions()) {\n if (!topics.has(sub.topic)) {\n issues.push({\n path: `topic.${sub.topic}`,\n message:\n `Subscription \"${sub.name}\" is declared on topic \"${sub.topic}\", which nothing declares. ` +\n \"The handler would never run.\"\n });\n }\n }\n\n // A table routed to a database nothing declares boots into a refusal, and\n // a column stored in a bucket nothing declares answers 501 on its first\n // upload. Both are cheaper to hear about here.\n const databases = new Set(graph.resources.filter(r => r.kind === \"database\").map(r => r.key));\n const buckets = new Set(graph.resources.filter(r => r.kind === \"bucket\").map(r => r.key));\n for (const table of tables) {\n if (table.database && table.database !== DEFAULT_RESOURCE_KEY && !databases.has(table.database)) {\n issues.push({\n path: `table.${table.slug}`,\n message:\n `lives in database \"${table.database}\", which nothing declares. ` +\n `Add database(\"${table.database}\") to backend/resources.ts, or import the handle and use it here.`\n });\n }\n for (const [where, storage] of tableStorage(table)) {\n const key = storage.source;\n if (key !== undefined && key !== DEFAULT_RESOURCE_KEY && buckets.size > 0 && !buckets.has(key)) {\n issues.push({\n path: `table.${table.slug}.${where}`,\n message: `stores into bucket \"${key}\", which nothing declares. Add bucket(\"${key}\") to backend/resources.ts.`\n });\n }\n }\n }\n\n return { graph, issues };\n}\n\n/** The graph as it is written to disk: stable key order, trailing newline. */\nexport function serializeResourceGraph(graph: ResourceGraph): string {\n const resources = graph.resources.map(r => ({\n kind: r.kind,\n key: r.key,\n engine: r.engine,\n transport: r.transport,\n ...(r.label !== undefined ? { label: r.label } : {}),\n ...(Object.keys(r.options).length > 0 ? { options: r.options } : {}),\n ...(r.usedBy && r.usedBy.length > 0 ? { usedBy: r.usedBy } : {})\n }));\n return JSON.stringify({\n $generated: `Generated from backend/resources.ts and backend/schema by \\`rebase resources\\`. Edit the declarations, not this file.`,\n version: graph.version,\n resources\n }, null, 4) + \"\\n\";\n}\n\n/** Read the committed graph, or null when a project has none yet. */\nexport function readResourceGraphFile(projectRoot: string): string | null {\n const file = path.join(projectRoot, RESOURCE_GRAPH_FILENAME);\n return fs.existsSync(file) ? fs.readFileSync(file, \"utf-8\") : null;\n}\n\n/**\n * Write the graph, and say whether the file changed.\n *\n * The boolean is what a `--check` mode reports on: a project whose committed\n * graph disagrees with its declarations has a host reading one thing and a runtime\n * doing another.\n */\nexport function writeResourceGraphFile(projectRoot: string, graph: ResourceGraph): { changed: boolean; file: string } {\n const file = path.join(projectRoot, RESOURCE_GRAPH_FILENAME);\n const next = serializeResourceGraph(graph);\n const previous = fs.existsSync(file) ? fs.readFileSync(file, \"utf-8\") : null;\n if (previous === next) return { changed: false, file };\n fs.writeFileSync(file, next);\n return { changed: true, file };\n}\n\n/** Parse a committed graph file, tolerating the `$generated` banner. */\nexport function parseResourceGraph(contents: string): ResourceGraph {\n const raw = JSON.parse(contents) as { version?: number; resources?: unknown };\n if (raw.version !== 1) {\n throw new Error(\n `Unsupported resource graph version ${String(raw.version)}. ` +\n \"This project was generated by a newer Rebase; upgrade rather than provisioning half of it.\"\n );\n }\n const entries = Array.isArray(raw.resources) ? raw.resources as Record<string, unknown>[] : [];\n // `options` is omitted from the file when empty; a reader of the graph\n // expects it present, so it is restored here.\n return { version: 1, resources: entries.map(r => ({ options: {}, ...r })) as ResourceGraph[\"resources\"] };\n}\n\n/**\n * Add the resources a project has without declaring them.\n *\n * A backend has a database whether or not anyone said so, and a project that\n * declares no buckets still gets one default storage source from the plain\n * unsuffixed variables. Both are load-bearing defaults and both are invisible\n * in the graph, so a status view built only from declarations would show an\n * empty screen to the majority of projects — the ones that most need to be told\n * which variable their one database reads.\n *\n * Declaring a *named* one leaves the default where it is, as the server does\n * (`resolveDataSources` and `resolveStorageSources` in `@rebasepro/server`):\n * `bucket(\"media\")` adds a source and never moves the files the default holds,\n * so both are listed. The default is displaced only by declaring it — or, for a\n * bucket, by marking exactly one server-side bucket `default: true`, which then\n * serves the uploads that name no `storageSource`. This used to drop the\n * default once a bucket was declared, and `rebase status` and `rebase\n * resources` stopped listing a source the server was still serving.\n */\nexport function withImplicitDefaults(graph: ResourceGraph): {\n declaration: ResourceDeclaration;\n implicit: boolean;\n}[] {\n const entries = graph.resources.map(declaration => ({ declaration, implicit: false }));\n const declaresDefault = (kind: string) => graph.resources.some(r => r.kind === kind && r.key === DEFAULT_RESOURCE_KEY);\n const markedDefault = graph.resources.filter(r =>\n r.kind === \"bucket\" && (r.transport ?? \"server\") === \"server\" && r.options.default === true);\n\n if (!declaresDefault(\"database\")) {\n entries.unshift({\n declaration: {\n kind: \"database\",\n key: DEFAULT_RESOURCE_KEY,\n engine: \"postgres\",\n transport: \"server\",\n options: {}\n },\n implicit: true\n });\n }\n if (!declaresDefault(\"bucket\") && markedDefault.length !== 1) {\n const implicitBucket = {\n declaration: {\n kind: \"bucket\",\n key: DEFAULT_RESOURCE_KEY,\n // `local` is what an unconfigured default source resolves to,\n // and naming it here keeps the row honest about what a project\n // with no S3 variables actually gets: a directory that a\n // container erases on restart, which production then drops.\n engine: \"local\",\n transport: \"server\" as const,\n options: {}\n },\n implicit: true\n };\n // First among the buckets, as the database default is first among the\n // databases; last when there are none.\n const firstBucket = entries.findIndex(entry => entry.declaration.kind === \"bucket\");\n if (firstBucket === -1) entries.push(implicitBucket);\n else entries.splice(firstBucket, 0, implicitBucket);\n }\n return entries;\n}\n\n/**\n * The resources a project *has*, which is what a person is asking about.\n *\n * One projection, because two of them disagreed. `rebase status` built its\n * rows from {@link withImplicitDefaults} and listed `buckets ✓ (default) local\n * · implicit`; `rebase resources` and `rebase resources --json` built theirs\n * from the raw graph and listed only the database and the function. Two\n * commands whose whole job is to answer \"what does this project need\", on the\n * same stock scaffold, giving different answers.\n *\n * The implicit entries are marked rather than hidden, because the distinction\n * is real and load-bearing: a declared resource is recorded in\n * `rebase.resources.json` for a host to provision, and an implicit one is a\n * default the runtime supplies whether or not anyone wrote it down. That file\n * still holds declarations only — it is a wire contract a host reads, and\n * putting defaults in it would ask for something to be provisioned that\n * nobody declared.\n */\nexport type ProjectedResource = ResourceDeclaration & { implicit?: true };\n\nexport function projectResourceGraph(graph: ResourceGraph): ProjectedResource[] {\n return withImplicitDefaults(graph).map(({ declaration, implicit }) =>\n (implicit ? { ...declaration, implicit: true as const } : declaration));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,IAAa,0BAA0B;;;;;;;;;;;;;;AAqBvC,IAAM,uBAAuB;AAC7B,IAAM,YAAY;;AAGlB,SAAS,iBAAiB,WAAmB,MAA6B;CACtE,IAAI;EAEA,MAAM,WADU,cAAc,KAAK,KAAK,MAAM,SAAS,CACtC,CAAA,CAAQ,QAAQ,GAAG,UAAU,cAAc;EAC5D,MAAM,UAAmB,KAAK,MAAM,GAAG,aAAa,UAAU,OAAO,CAAC,CAAC,CAAC;EACxE,OAAO,OAAO,YAAY,WAAW,UAAU;CACnD,QAAQ;EACJ,OAAO;CACX;AACJ;;;;;;;;;;;;;;AAeA,SAAgB,cAAc,KAAc,aAAqB,aAAa,WAAW,GAAW;CAChG,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;CAC/D,MAAM,OAAQ,KAAmC;CAGjD,IAAI,EAFkB,qBAAqB,KAAK,OAC3B,MAAkB,QAAQ,SAAS,yBACrC,OAAO;CAE1B,MAAM,YAAY,UAAU,KAAK,OAAO,CAAC,GAAG;CAC5C,IAAI,CAAC,WAAW,OAAO;CAKvB,MAAM,OAAO,SAAS,KAAK,QAAQ,KAAK,CAAC,IAAI,QAAQ,KAAK,IAAI,GAAG,QAAQ,KAAK,EAAE;CAEhF,MAAM,YAAY,iBAAiB,WAAW,WAAW;CACzD,IAAI,cAAc,MACd,OAAO,GAAG,KAAK,GAAG,UAAU,iDAAiD,WAAW,iBAClE,UAAU,GAAG;CAEvC,IAAI,eAAe,aAAa,cAAc,YAAY,OAAO;CAOjE,OADmB,gBAAgB,YAAY,SAAS,IAAI,IAEtD,GAAG,KAAK,GAAG,UAAU,GAAG,UAAU,6BAA6B,WAAW,iBACtD,UAAU,GAAG,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AAY,SAAS,QAAQ;EAClF,IAAI,gBAAgB,IAAI,QAAQ,KAAK,cAAc;OAC9C,QAAQ,OAAO,aAAa,GAAG,cAAc;CACtD;CACA,OAAO;AACX;AAsBA,SAAgB,qBAAqB,OAA2C;CAC5E,OAAO,qBAAqB,KAAK,CAAC,CAAC,KAAK,EAAE,aAAa,eAClD,WAAW;EAAE,GAAG;EAAa,UAAU;CAAc,IAAI,WAAY;AAC9E"}
|
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import { i as recordEvent } from "./telemetry-
|
|
1
|
+
import { i as recordEvent } from "./telemetry-EVtASbKb.js";
|
|
2
2
|
import { n as getPMCommands, t as detectPackageManager } from "./package-manager-DSEOwTqM.js";
|
|
3
|
-
import { a as wantsHelp, i as switchOn, n as parseCommandArgs, t as UsageError } from "./args-
|
|
4
|
-
import { a as findBackendDir, g as resolveTsx, h as resolvePluginCliScript, l as getActiveBackendPlugin, n as dependenciesNotInstalled, o as findEnvFile, p as requireProjectRoot, s as findFrontendDir, v as validateTsxInstallation } from "./project-
|
|
5
|
-
import { C as resolveBackendPaths, T as staticAppAddress, _ as findBackendApp, a as DEFAULT_TABLES_DIR, b as loadManifest, d as STORAGE_FILE, h as cmsMountOf, i as DEFAULT_SCHEMA_FILE, n as DEFAULT_CRONS_DIR, r as DEFAULT_FUNCTIONS_DIR, s as HOOKS_FILE, u as RESOURCES_FILE, v as findTablesIndex, y as formatAppAddress } from "./manifest-
|
|
6
|
-
import { n as resolveSchemaDir, r as schemaDirArgs } from "./schema-dir-
|
|
7
|
-
import { a as backendGuardMissingMessage, n as BACKEND_GUARD_FIX, o as backendGuardStates } from "./backend-guard-
|
|
8
|
-
import { r as getProjectPort, t as DEV_BACKEND_URL_ENV } from "./dev-server-
|
|
3
|
+
import { a as wantsHelp, i as switchOn, n as parseCommandArgs, t as UsageError } from "./args-DHyrshtI.js";
|
|
4
|
+
import { a as findBackendDir, g as resolveTsx, h as resolvePluginCliScript, l as getActiveBackendPlugin, n as dependenciesNotInstalled, o as findEnvFile, p as requireProjectRoot, s as findFrontendDir, v as validateTsxInstallation } from "./project-DALmhb5R.js";
|
|
5
|
+
import { C as resolveBackendPaths, T as staticAppAddress, _ as findBackendApp, a as DEFAULT_TABLES_DIR, b as loadManifest, d as STORAGE_FILE, h as cmsMountOf, i as DEFAULT_SCHEMA_FILE, n as DEFAULT_CRONS_DIR, r as DEFAULT_FUNCTIONS_DIR, s as HOOKS_FILE, u as RESOURCES_FILE, v as findTablesIndex, y as formatAppAddress } from "./manifest-RjqxfCpb.js";
|
|
6
|
+
import { n as resolveSchemaDir, r as schemaDirArgs } from "./schema-dir-ChcYfWjP.js";
|
|
7
|
+
import { a as backendGuardMissingMessage, n as BACKEND_GUARD_FIX, o as backendGuardStates } from "./backend-guard-Cf8eMK_f.js";
|
|
8
|
+
import { r as getProjectPort, t as DEV_BACKEND_URL_ENV } from "./dev-server-2XHSHM_q.js";
|
|
9
9
|
import { t as Refusal } from "./refusal-ReeeGP8a.js";
|
|
10
|
-
import { i as ensureDevDatabase, o as probeTcp } from "./dev-preflight-
|
|
10
|
+
import { i as ensureDevDatabase, o as probeTcp } from "./dev-preflight-BMOf2N6r.js";
|
|
11
11
|
import { t as MANAGED_IDLE_TIMEOUT_MS } from "./constraints-CtiylsGf.js";
|
|
12
|
-
import { a as resolveCliEntry, o as resolveSpawn } from "./daemon-
|
|
13
|
-
import { DEV_DATABASE_KIND_ENV, i as lastDevDatabaseNotice, managedNotices, prepareDatabaseEnv, resolveProjectDatabase, s as recordLastDevDatabase } from "./prepare-
|
|
14
|
-
import { runDriverDbCommand, runDriverSchemaCommand } from "./db-
|
|
12
|
+
import { a as resolveCliEntry, o as resolveSpawn } from "./daemon-D5gdG7gx.js";
|
|
13
|
+
import { DEV_DATABASE_KIND_ENV, i as lastDevDatabaseNotice, managedNotices, prepareDatabaseEnv, resolveProjectDatabase, s as recordLastDevDatabase } from "./prepare-BaJe0Zik.js";
|
|
14
|
+
import { runDriverDbCommand, runDriverSchemaCommand } from "./db-D_iF4E-v.js";
|
|
15
15
|
import chalk from "chalk";
|
|
16
16
|
import fs from "fs";
|
|
17
17
|
import os from "os";
|
|
@@ -504,7 +504,7 @@ async function declaredAdditionalDatabases(projectRoot) {
|
|
|
504
504
|
try {
|
|
505
505
|
const backend = findBackendApp(loadManifest(projectRoot).manifest);
|
|
506
506
|
if (!backend) return [];
|
|
507
|
-
const { deriveResourceGraph, deriveOptionsFor } = await import("./derive-
|
|
507
|
+
const { deriveResourceGraph, deriveOptionsFor } = await import("./derive-Mky_u59_.js").then((n) => n.i);
|
|
508
508
|
const { graph } = await deriveResourceGraph({
|
|
509
509
|
...deriveOptionsFor(projectRoot, backend.app),
|
|
510
510
|
schemaDir: void 0,
|
|
@@ -1949,4 +1949,4 @@ ${chalk.green.bold("Description")}
|
|
|
1949
1949
|
//#endregion
|
|
1950
1950
|
export { devCommand };
|
|
1951
1951
|
|
|
1952
|
-
//# sourceMappingURL=dev-
|
|
1952
|
+
//# sourceMappingURL=dev-bj6dEeSQ.js.map
|