@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
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"pull-D9WvpDYY.js","names":[],"sources":["../src/dev-db/attver.ts","../src/dev-db/pull.ts"],"sourcesContent":["/**\n * `pg_attver` in a dump, and taking it out before a restore.\n *\n * The November 2026 PostgreSQL minor releases (every branch from 14 up;\n * upstream commit c23382f0a8, \"Introduce attribute versioning to prevent\n * unsafe deforming\") keep a per-column version as an attribute option: a\n * `pg_attver` key in `pg_attribute.attoptions`, set on every column created or\n * altered. A `pg_dump` from before that release, pointed at a server from\n * after it, dumps the key like any other attribute option:\n *\n * ALTER TABLE ONLY public.authors ALTER COLUMN id SET (pg_attver=33846480);\n *\n * and every server without the change — PGlite, which the managed development\n * database runs on, and a local Postgres on an older minor — refuses it with\n * `unrecognized parameter \"pg_attver\"`. The statement sits in the same archive\n * entry as the table's `CREATE TABLE`, so that entry fails whole: no table,\n * and every row, index and constraint of it after. A server with the change\n * ignores the key on input, so it carries nothing a restore needs.\n *\n * pg_dump's own fix leaves the key out, but a pull should not depend on the\n * local client being newer than the source server. So the dump is edited in\n * place before pg_restore reads it: in each TOC entry's definition, the key is\n * overwritten with spaces — the whole statement when it is the only option,\n * the key and its comma when there are others. Byte for byte the same length,\n * because the TOC records the file offset of every data block after it.\n */\nimport fs from \"fs\";\n\nconst ATTVER_ONLY = /^(ALTER (?:FOREIGN )?TABLE (?:ONLY )?.* ALTER COLUMN .* SET )\\(pg_attver=\\d+\\);$/gm;\nconst ATTVER_FIRST = /(?<=^ALTER (?:FOREIGN )?TABLE (?:ONLY )?.* ALTER COLUMN .* SET \\()pg_attver=\\d+, (?=.*\\);$)/gm;\nconst ATTVER_LATER = /(?<=^ALTER (?:FOREIGN )?TABLE (?:ONLY )?.* ALTER COLUMN .* SET \\(.*), pg_attver=\\d+(?=.*\\);$)/gm;\n\nfunction spaces(text: string): string {\n return \" \".repeat(Buffer.byteLength(text, \"utf8\"));\n}\n\n/**\n * A TOC entry's definition without its `pg_attver` options, as the same\n * number of UTF-8 bytes: what was taken out is spaces.\n */\nexport function blankAttverOptions(definition: string): string {\n if (!definition.includes(\"pg_attver=\")) return definition;\n\n return definition\n .replace(ATTVER_ONLY, (statement) => spaces(statement))\n .replace(ATTVER_FIRST, (option) => spaces(option))\n .replace(ATTVER_LATER, (option) => spaces(option));\n}\n\n/** `K_VERS_1_12`…`K_VERS_1_16`: the custom-format archives pg_dump 11 to 18 write. */\nconst OLDEST = archiveVersion(1, 12, 0);\nconst NEWEST = archiveVersion(1, 16, 0);\nconst V1_14 = archiveVersion(1, 14, 0);\nconst V1_15 = archiveVersion(1, 15, 0);\nconst V1_16 = archiveVersion(1, 16, 0);\n/** `archCustom` in pg_backup.h. */\nconst CUSTOM_FORMAT = 1;\n/** `K_OFFSET_POS_SET` in pg_backup_custom.c: the entry's data block is at the offset that follows. */\nconst OFFSET_SET = 2;\n\nfunction archiveVersion(major: number, minor: number, revision: number): number {\n return (major << 16) | (minor << 8) | revision;\n}\n\n/** Reads a custom-format archive's header and TOC straight from the file, without loading its data. */\nclass ArchiveReader {\n position = 0;\n intSize = 4;\n offSize = 8;\n\n constructor(private readonly fd: number, private readonly size: number) {}\n\n bytes(length: number): Buffer {\n if (length < 0 || this.position + length > this.size) throw new RangeError(\"past the end of the archive\");\n const buffer = Buffer.alloc(length);\n let read = 0;\n while (read < length) {\n const n = fs.readSync(this.fd, buffer, read, length - read, this.position + read);\n if (n === 0) throw new RangeError(\"past the end of the archive\");\n read += n;\n }\n this.position += length;\n return buffer;\n }\n\n byte(): number {\n return this.bytes(1)[0] ?? 0;\n }\n\n /** `ReadInt`: a sign byte, then `intSize` bytes, least significant first. */\n int(): number {\n const negative = this.byte() !== 0;\n const digits = this.bytes(this.intSize);\n let value = 0;\n for (let i = digits.length - 1; i >= 0; i--) value = value * 256 + (digits[i] ?? 0);\n return negative ? -value : value;\n }\n\n /** `ReadStr`: a length, then that many bytes; a negative length is NULL. Returns where the bytes are. */\n str(): { at: number; text: string } | null {\n const length = this.int();\n if (length < 0) return null;\n const at = this.position;\n return { at, text: this.bytes(length).toString(\"utf8\") };\n }\n\n /** `ReadOffset`: a flag byte, then `offSize` bytes, least significant first. */\n offset(): { set: boolean; value: number } {\n const flag = this.byte();\n const digits = this.bytes(this.offSize);\n let value = 0;\n for (let i = digits.length - 1; i >= 0; i--) value = value * 256 + (digits[i] ?? 0);\n return { set: flag === OFFSET_SET, value };\n }\n}\n\ninterface Patch {\n at: number;\n bytes: Buffer;\n}\n\n/** The edits that blank `pg_attver` in an archive's TOC, or `null` when the file is not one this can read. */\nfunction planPatches(fd: number, size: number): Patch[] | null {\n const reader = new ArchiveReader(fd, size);\n if (reader.bytes(5).toString(\"latin1\") !== \"PGDMP\") return null;\n const major = reader.byte();\n const minor = reader.byte();\n const revision = reader.byte();\n const version = archiveVersion(major, minor, revision);\n if (version < OLDEST || version > NEWEST) return null;\n reader.intSize = reader.byte();\n reader.offSize = reader.byte();\n if (reader.intSize < 1 || reader.intSize > 8 || reader.offSize < 1 || reader.offSize > 8) return null;\n if (reader.byte() !== CUSTOM_FORMAT) return null;\n\n // ReadHead: compression, creation time, database name, server and pg_dump versions.\n if (version >= V1_15) reader.byte();\n else reader.int();\n for (let i = 0; i < 7; i++) reader.int();\n reader.str();\n reader.str();\n reader.str();\n\n // ReadToc, with the custom format's ReadExtraToc after each entry.\n const patches: Patch[] = [];\n let firstData = Number.POSITIVE_INFINITY;\n const entries = reader.int();\n if (entries < 0) return null;\n for (let i = 0; i < entries; i++) {\n reader.int(); // dumpId\n reader.int(); // hadDumper\n reader.str(); // tableoid\n reader.str(); // oid\n reader.str(); // tag\n reader.str(); // desc\n reader.int(); // section\n const definition = reader.str();\n reader.str(); // dropStmt\n reader.str(); // copyStmt\n reader.str(); // namespace\n reader.str(); // tablespace\n if (version >= V1_14) reader.str(); // tableam\n if (version >= V1_16) reader.int(); // relkind\n reader.str(); // owner\n reader.str(); // \"false\": the old withOids\n while (reader.str() !== null); // dependencies, ended by NULL\n const data = reader.offset();\n if (data.set) firstData = Math.min(firstData, data.value);\n\n if (definition) {\n const blanked = blankAttverOptions(definition.text);\n if (blanked !== definition.text) {\n const bytes = Buffer.from(blanked, \"utf8\");\n if (bytes.length !== Buffer.byteLength(definition.text, \"utf8\")) return null;\n patches.push({ at: definition.at, bytes });\n }\n }\n }\n\n // The data blocks follow the TOC. If they do not start after where this\n // read it to end, the layout was not the one assumed: change nothing.\n if (reader.position > firstData) return null;\n\n return patches;\n}\n\n/**\n * Blank every `pg_attver` attribute option in a custom-format dump, in place.\n * Returns how many TOC entries were changed; 0 also for a file this does not\n * recognise, which pg_restore then reads as it is.\n */\nexport function stripAttverFromArchive(dumpFile: string): number {\n const fd = fs.openSync(dumpFile, \"r+\");\n try {\n let patches: Patch[] | null;\n try {\n patches = planPatches(fd, fs.fstatSync(fd).size);\n } catch (error) {\n if (error instanceof RangeError) return 0;\n throw error;\n }\n if (!patches) return 0;\n for (const patch of patches) fs.writeSync(fd, patch.bytes, 0, patch.bytes.length, patch.at);\n return patches.length;\n } finally {\n fs.closeSync(fd);\n }\n}\n","/**\n * `rebase db pull` — copy a database's contents into local development.\n *\n * The common case is production into local, and the reason it exists is that\n * the alternative is worse: without it people hand-roll a `pg_dump | psql` and\n * get the flags wrong in ways that either fail loudly at 2am or, more often,\n * quietly restore half a schema.\n *\n * Three things this command insists on, because copying a production database\n * onto a laptop is a data-protection event whether or not anyone calls it one:\n *\n * 1. **It says what it is about to do, in full, before doing it** — which\n * database it will read, which one it will overwrite, and where the data will\n * come to rest on disk. The target path matters: people forget that\n * `.rebase/pgdata` is a directory their backup software may be indexing.\n *\n * 2. **It refuses to run unattended without being told to.** The target is\n * destroyed, so a mistyped `--from` with no confirmation would take the\n * developer's working database with it.\n *\n * 3. **It will not write to a remote database.** The target is always the local\n * development database; there is no flag that makes this push. A tool that\n * can copy in both directions eventually copies in the wrong one.\n *\n * Anonymization is opt-in (`--anonymize`), which is a deliberate choice and not\n * an obviously safe one — the flag nobody types is the flag nobody gets. It is\n * a best-effort pass over columns whose *names* look like personal data, and\n * {@link ANONYMIZE_PATTERNS} says exactly which. It cannot find personal data in\n * a column called `notes`, and this file says so rather than implying a\n * guarantee it cannot keep.\n *\n * What it does guarantee is that it never half-happens: {@link anonymizeCopy}\n * runs the pass in one transaction, and when the pass fails it empties the\n * tables it would have rewritten rather than leave their real values behind.\n */\n\nimport { execa } from \"execa\";\nimport fs from \"fs\";\nimport type { Client } from \"pg\";\n\nimport { stripAttverFromArchive } from \"./attver\";\nimport { banner, connectionErrorText, hostOf } from \"./connection-banner\";\nimport { PGLITE_EXTENSIONS } from \"./constraints\";\n\n/**\n * How one kind of personal-looking column is overwritten.\n *\n * Two forms, because a constant is the most readable replacement and is wrong\n * for exactly one kind of column: a unique one. Every `token_hash` becoming\n * `'REDACTED'` is what `UNIQUE(token_hash)` refused on the second row of\n * `rebase.refresh_tokens` — so on any project where someone had signed in twice.\n */\nexport interface AnonymizeRule {\n pattern: RegExp;\n /**\n * Only on a table of people (see {@link isPeopleTable}), when set. For a\n * column name that is personal on one table and not on another: a user's\n * `name` is a person's, a tag's is not.\n */\n peopleOnly?: true;\n /** The value for a column no unique index covers, or null to always use the unique form. */\n value: string | null;\n /** The unique form is `prefix` + random hex + `suffix`, cut to fit the column. */\n prefix: string;\n suffix: string;\n}\n\n/**\n * Tables whose rows are people, by name: `rebase.users`, the blog scaffold's\n * `authors`, and the usual spellings of a project's own. Singular or plural.\n */\nconst PERSON_TABLES = /^(users?|user_profiles?|profiles?|people|persons?|members?|customers?|contacts?|employees?|authors?)$/i;\n\n/** An email address column, by name: the email rule's own pattern. */\nconst EMAIL_COLUMN = /^(.*_)?e?mail(_.*)?$/i;\n\n/** The column types a replacement string fits. */\nconst TEXTUAL_TYPES = new Set([\"text\", \"character varying\", \"varchar\", \"character\", \"char\", \"citext\"]);\n\nfunction isTextual(column: ColumnRef): boolean {\n return TEXTUAL_TYPES.has(column.dataType.toLowerCase());\n}\n\n/** `\"schema\".\"table\"`, the key a column's table is known by. */\nfunction tableKey(column: ColumnRef): string {\n return `${quoteIdentifier(column.schema)}.${quoteIdentifier(column.table)}`;\n}\n\n/**\n * The tables whose rows are people: those {@link PERSON_TABLES} names, and any\n * that holds an email address column.\n *\n * The second is what reaches the tables no list of names could: a row with an\n * address of its own is a person's, so its `name` is one too. The blog\n * scaffold's `authors` (`name`, `email`, `picture`) arrived with every name\n * as it was. A table of organisations with a contact address gets its `name`\n * redacted too, which costs a local copy little.\n */\nexport function peopleTables(columns: readonly ColumnRef[]): Set<string> {\n const people = new Set<string>();\n for (const column of columns) {\n if (PERSON_TABLES.test(column.table) || (EMAIL_COLUMN.test(column.column) && isTextual(column))) {\n people.add(tableKey(column));\n }\n }\n return people;\n}\n\n/**\n * Column-name patterns the anonymizer overwrites.\n *\n * Names, not contents: inspecting values would be slower, and would still miss\n * the same things. This is a reasonable-effort measure for making a local copy\n * less dangerous, and it is not a compliance control.\n */\nexport const ANONYMIZE_PATTERNS: readonly AnonymizeRule[] = [\n // Emails are unique in practice even where nothing enforces it, so they\n // always get a value of their own.\n { pattern: EMAIL_COLUMN, value: null, prefix: \"user-\", suffix: \"@example.invalid\" },\n { pattern: /^(.*_)?(phone|mobile|tel|telephone)(_.*)?$/i, value: \"+10000000000\", prefix: \"+1-\", suffix: \"\" },\n // `display_name` is how `rebase.users` holds every user's name.\n {\n pattern: /^(.*_)?(display_name|first_name|last_name|full_name|middle_name|family_name|surname|given_name)(_.*)?$/i,\n value: \"Redacted\",\n prefix: \"Redacted-\",\n suffix: \"\"\n },\n // A bare `name` is a person's only on a table of people.\n { pattern: /^name$/i, peopleOnly: true, value: \"Redacted\", prefix: \"Redacted-\", suffix: \"\" },\n { pattern: /^(.*_)?(address|street|postcode|zip|zipcode)(_.*)?$/i, value: \"Redacted\", prefix: \"Redacted-\", suffix: \"\" },\n { pattern: /^(.*_)?(ssn|tax_id|national_id|passport)(_.*)?$/i, value: \"REDACTED\", prefix: \"REDACTED-\", suffix: \"\" },\n { pattern: /^(.*_)?(password|password_hash|secret|token|api_key|access_token|refresh_token)(_.*)?$/i, value: \"REDACTED\", prefix: \"REDACTED-\", suffix: \"\" },\n { pattern: /^(.*_)?(ip|ip_address|user_agent)(_.*)?$/i, value: \"REDACTED\", prefix: \"REDACTED-\", suffix: \"\" }\n];\n\n/** The rule that overwrites this column, if any. A people-only rule applies only on a table of people. */\nfunction ruleFor(columnName: string, onPeopleTable: boolean): AnonymizeRule | undefined {\n return ANONYMIZE_PATTERNS.find((rule) => rule.pattern.test(columnName) && (!rule.peopleOnly || onPeopleTable));\n}\n\n/**\n * Whether a column of this name is overwritten. A table is judged a table of\n * people by its name here; {@link anonymizableColumns}, which sees the\n * table's other columns, also counts one that holds an email address.\n */\nexport function shouldAnonymize(columnName: string, table?: string): boolean {\n return ruleFor(columnName, table !== undefined && PERSON_TABLES.test(table)) !== undefined;\n}\n\n/** A text-ish column the anonymizer can overwrite without a type error. */\nexport interface ColumnRef {\n schema: string;\n table: string;\n column: string;\n dataType: string;\n /** `character_maximum_length`: null or absent for an unbounded type. */\n maxLength?: number | null;\n /** Covered by a unique index — a primary key, a UNIQUE constraint, or a unique expression index. */\n unique?: boolean;\n}\n\n/** Random hex of this length, per row. `gen_random_uuid()` is core since PostgreSQL 13. */\nfunction randomHex(length: number): string {\n return `left(replace(gen_random_uuid()::text, '-', ''), ${length})`;\n}\n\nfunction sqlLiteral(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`;\n}\n\n/**\n * Fewest random hex digits a unique replacement keeps. Twelve is 16^12 values:\n * a collision needs millions of rows, where eight would need tens of thousands.\n */\nconst MIN_UNIQUE_HEX = 12;\n\n/**\n * The SQL expression that overwrites one column, or null when no rule names it.\n *\n * Unique per row when an index makes the column unique, and always cut to the\n * column's declared length — `zip char(5)` refused `'Redacted'` outright, and a\n * failed statement now empties the tables rather than skip one. To fit a short\n * unique column the prefix goes first, then the suffix, and the random part is\n * kept to at least {@link MIN_UNIQUE_HEX} digits while there is room for them.\n * A NULL stays NULL: an empty optional field is not personal data.\n */\nexport function replacementFor(column: ColumnRef, onPeopleTable = PERSON_TABLES.test(column.table)): string | null {\n const rule = ruleFor(column.column, onPeopleTable);\n if (!rule) return null;\n const limit = typeof column.maxLength === \"number\" && column.maxLength > 0 ? column.maxLength : null;\n\n let value: string;\n if (rule.value !== null && !column.unique) {\n value = sqlLiteral(limit === null ? rule.value : rule.value.slice(0, limit));\n } else {\n const shapes = [[rule.prefix, rule.suffix], [\"\", rule.suffix], [\"\", \"\"]];\n const fitting = shapes.find(([prefix, suffix]) =>\n limit === null || limit - prefix.length - suffix.length >= MIN_UNIQUE_HEX);\n const [prefix, suffix] = fitting ?? [\"\", \"\"];\n const hex = Math.min(32, limit === null ? 32 : limit - prefix.length - suffix.length);\n value = `concat(${sqlLiteral(prefix)}, ${randomHex(Math.max(1, hex))}, ${sqlLiteral(suffix)})`;\n }\n\n const name = quoteIdentifier(column.column);\n return `CASE WHEN ${name} IS NULL THEN NULL ELSE ${value} END`;\n}\n\n/** A double-quoted identifier, with any `\"` in it doubled — a table called `order` or `a\"b` still works. */\nexport function quoteIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/**\n * Anonymizable columns: name looks personal, and the type can hold the\n * replacement.\n *\n * The type check is what stops this generating `UPDATE … SET user_id =\n * 'Redacted'` for an integer column called `user_id_email_seq` and failing the\n * whole pass on a technicality.\n */\nexport function anonymizableColumns(columns: readonly ColumnRef[]): ColumnRef[] {\n const people = peopleTables(columns);\n\n return columns.filter((column) =>\n isTextual(column) && ruleFor(column.column, people.has(tableKey(column))) !== undefined);\n}\n\n/** `\"schema\".\"table\"` for each table the pass rewrites, sorted. */\nexport function anonymizedTables(columns: readonly ColumnRef[]): string[] {\n return [...new Set(anonymizableColumns(columns).map(tableKey))].sort();\n}\n\n/** `UPDATE` statements for one anonymization pass, in a stable order. */\nexport function anonymizeStatements(columns: readonly ColumnRef[]): string[] {\n const people = peopleTables(columns);\n const byTable = new Map<string, ColumnRef[]>();\n for (const column of anonymizableColumns(columns)) {\n const key = tableKey(column);\n byTable.set(key, [...(byTable.get(key) ?? []), column]);\n }\n\n return [...byTable.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([table, cols]) => {\n const assignments = [...cols]\n .sort((a, b) => a.column.localeCompare(b.column))\n .map((column) => `${quoteIdentifier(column.column)} = ${replacementFor(column, people.has(table))}`)\n .join(\", \");\n\n return `UPDATE ${table} SET ${assignments};`;\n });\n}\n\n/**\n * Every column the pass could overwrite, with what decides how.\n *\n * Base tables only — a view has an `email` column too, and is not something to\n * UPDATE. Generated columns are skipped for the same reason: `email_domain\n * GENERATED ALWAYS AS (…)` matches by name and refuses any value but DEFAULT,\n * and it follows the column it is generated from anyway. An extension type such\n * as `citext` reports `USER-DEFINED`, so its own name is what is compared.\n *\n * `unique` comes from the indexes, through `pg_depend` as well as `indkey`: a\n * unique index on `lower(email)` names no column in `indkey`, and is exactly\n * what a constant replacement would violate.\n */\nexport const ANONYMIZE_COLUMNS_SQL = `\nWITH unique_columns AS (\n SELECT DISTINCT i.indrelid AS relid, a.attname AS column_name\n FROM pg_index i\n JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum > 0 AND NOT a.attisdropped\n WHERE i.indisunique\n AND (a.attnum = ANY (i.indkey)\n OR EXISTS (SELECT 1 FROM pg_depend d\n WHERE d.classid = 'pg_class'::regclass AND d.objid = i.indexrelid\n AND d.refclassid = 'pg_class'::regclass AND d.refobjid = i.indrelid\n AND d.refobjsubid = a.attnum))\n)\nSELECT c.table_schema AS \"schema\",\n c.table_name AS \"table\",\n c.column_name AS \"column\",\n CASE WHEN c.data_type = 'USER-DEFINED' THEN c.udt_name ELSE c.data_type END AS \"dataType\",\n c.character_maximum_length AS \"maxLength\",\n (u.column_name IS NOT NULL) AS \"unique\"\n FROM information_schema.columns c\n JOIN information_schema.tables t ON t.table_schema = c.table_schema AND t.table_name = c.table_name\n LEFT JOIN unique_columns u\n ON u.relid = format('%I.%I', c.table_schema, c.table_name)::regclass AND u.column_name = c.column_name\n WHERE t.table_type = 'BASE TABLE'\n AND c.is_generated = 'NEVER'\n AND c.table_schema NOT IN ('pg_catalog', 'information_schema')`;\n\n/** How {@link anonymizeCopy} ended. */\nexport type AnonymizeOutcome =\n | { ok: true; tables: string[] }\n | {\n ok: false;\n /** Why the pass failed. Nothing it wrote was kept. */\n error: string;\n /** The tables emptied instead, so none of their real values are left. */\n emptied: string[];\n /** Why they could not be emptied, when they could not: the copy then holds real data. */\n emptyError: string | null;\n };\n\nfunction errorText(error: unknown): string {\n return error instanceof Error && error.message ? error.message : String(error);\n}\n\n/**\n * Overwrite the personal-looking columns of a restored copy, all or nothing.\n *\n * One transaction, so a failure part-way leaves no table half done — the old\n * pass ran its UPDATEs one by one, so a failure on `rebase.refresh_tokens` left\n * `public.authors` anonymized and `rebase.users` holding every real email.\n *\n * A rollback alone would be worse than that, though: it puts back the real\n * value of every column, in a copy the developer asked to be anonymized. So on\n * failure the tables the pass would have rewritten are emptied (`TRUNCATE …\n * CASCADE`, which takes the rows that reference them too), and the outcome\n * says which — or, if even that failed, says the copy holds real data, so the\n * caller can say it louder.\n *\n * `row_security = off` makes a role that RLS would filter fail the pass instead\n * of rewriting only the rows its policies show it, which looked like success.\n */\nexport async function anonymizeCopy(client: Client): Promise<AnonymizeOutcome> {\n let listed = false;\n let tables: string[] = [];\n try {\n const { rows } = await client.query<ColumnRef>(ANONYMIZE_COLUMNS_SQL);\n tables = anonymizedTables(rows);\n listed = true;\n await client.query(\"BEGIN\");\n await client.query(\"SET LOCAL row_security = off\");\n for (const statement of anonymizeStatements(rows)) await client.query(statement);\n await client.query(\"COMMIT\");\n\n return { ok: true, tables };\n } catch (error) {\n const reason = errorText(error);\n await client.query(\"ROLLBACK\").catch(() => undefined);\n if (!listed) {\n return { ok: false, error: reason, emptied: [], emptyError: \"the tables to empty could not be listed\" };\n }\n if (tables.length === 0) return { ok: false, error: reason, emptied: [], emptyError: null };\n try {\n await client.query(`TRUNCATE TABLE ${tables.join(\", \")} CASCADE`);\n\n return { ok: false, error: reason, emptied: tables, emptyError: null };\n } catch (emptyError) {\n return { ok: false, error: reason, emptied: [], emptyError: errorText(emptyError) };\n }\n }\n}\n\n/**\n * Schemas the restored copy needs the app role provisioned on.\n *\n * `pg_dump --no-privileges` strips every GRANT, so a pulled database arrives\n * with its RLS policies and its `FORCE ROW LEVEL SECURITY` intact and no\n * privileges behind them. Measured on a 30-table project: 68 policies restored,\n * 14 tables with RLS on, and **0** grants to `rebase_user` — where the source\n * had 60. Reading one table as the role Rebase serves every request through:\n *\n * source: 6\n * copy: ERROR: permission denied for table leads\n *\n * The dump flags are right and stay: without `--no-owner`/`--no-privileges`\n * every `ALTER … OWNER TO` and `GRANT … TO <prod role>` in the dump fails\n * against roles that do not exist on a laptop, and buries the real output. The\n * repair belongs after the restore, and belongs to `ensureAppRole` — the same\n * routine boot and `rebase db push` call — rather than to a second list of\n * grants written here.\n *\n * Which schemas: every non-system schema the restored database actually has.\n * Boot knows its `managedSchemas` from the collections; a restore knows only\n * what arrived, and a source may carry schemas this project does not declare.\n * `pg_catalog`, `information_schema` and the `pg_*` internals are never ours to\n * grant on and PostgreSQL would refuse anyway.\n */\nexport function provisionableSchemas(rows: readonly { schema: string }[]): string[] {\n const skip = (name: string) => name === \"information_schema\" || name.startsWith(\"pg_\");\n\n return [...new Set(rows.map((row) => row.schema))].filter((name) => !skip(name)).sort();\n}\n\n/**\n * libpq's `keyword=value` form (`host=db.example.com port=5432 dbname=app`):\n * one or more pairs, a value bare or single-quoted with `\\'` and `\\\\` escapes.\n */\nconst KEYWORD_VALUE_DSN = /^\\s*[a-z_]+\\s*=\\s*(?:'(?:[^'\\\\]|\\\\.)*'|[^\\s']+)(?:\\s+[a-z_]+\\s*=\\s*(?:'(?:[^'\\\\]|\\\\.)*'|[^\\s']+))*\\s*$/i;\n\n/** One keyword's value in a `keyword=value` connection string, unquoted. */\nfunction keywordValue(dsn: string, keyword: string): string | null {\n const match = new RegExp(`(?:^|\\\\s)${keyword}\\\\s*=\\\\s*('(?:[^'\\\\\\\\]|\\\\\\\\.)*'|[^\\\\s']+)`, \"i\").exec(dsn);\n if (!match) return null;\n const value = match[1];\n return value.startsWith(\"'\") ? value.slice(1, -1).replace(/\\\\(.)/g, \"$1\") : value;\n}\n\n/**\n * Why a `--from` value is not a connection string pg_dump reads, or null\n * when it is one: a `postgres://` or `postgresql://` URL, or libpq's\n * `keyword=value` pairs.\n *\n * Asked before anything else, because the answer is known from the string:\n * `--from garbage --yes` printed \"This will replace your local database.\n * From (unparseable connection string)\" and started dumping before pg_dump\n * refused it. The value is never quoted back: it may carry a password in a\n * shape no redaction recognises.\n */\nexport function sourceProblem(source: string): string | null {\n const scheme = /^([a-z][a-z0-9+.-]*):\\/\\//i.exec(source)?.[1]?.toLowerCase();\n if (scheme !== undefined) {\n if (scheme !== \"postgres\" && scheme !== \"postgresql\") {\n return `it is a ${scheme}:// URL, and a pull copies from PostgreSQL (postgres:// or postgresql://)`;\n }\n try {\n new URL(source);\n return null;\n } catch {\n return \"it starts like a postgres:// URL but is not a valid one\";\n }\n }\n if (KEYWORD_VALUE_DSN.test(source)) return null;\n return \"it is neither a postgres:// URL nor libpq keyword=value pairs\";\n}\n\n/** Host and database of a connection string, with no credentials in it. */\nexport function describeTarget(connectionString: string): string {\n try {\n const url = new URL(connectionString);\n const database = url.pathname.replace(/^\\//, \"\") || \"(default)\";\n\n return `${url.hostname}${url.port ? `:${url.port}` : \"\"}/${database}`;\n } catch {\n if (KEYWORD_VALUE_DSN.test(connectionString)) {\n const host = keywordValue(connectionString, \"host\") ?? keywordValue(connectionString, \"hostaddr\") ?? \"(local socket)\";\n const port = keywordValue(connectionString, \"port\");\n return `${host}${port ? `:${port}` : \"\"}/${keywordValue(connectionString, \"dbname\") ?? \"(default)\"}`;\n }\n // Never echo the raw string: it carries a password, and this line is\n // printed to a terminal people paste into issues.\n return \"(unparseable connection string)\";\n }\n}\n\n/**\n * What the local database runs on.\n *\n * `pglite` is the managed development database: one PGlite session behind a\n * socket server. Two things a restore relies on are not there. The server runs\n * each protocol message on its own, so the `CopyData` that follows a `COPY …\n * FROM stdin` never reaches the backend waiting for it: the COPY fails on\n * \"unexpected EOF\", and the session stops answering anyone until the daemon\n * is killed. And every connection shares that one session, so what pg_restore\n * `SET`s for itself stays set for everyone after it disconnects.\n */\nexport type PullTargetEngine = \"postgres\" | \"pglite\";\n\nexport interface PullPlan {\n /** Where the data comes from. */\n source: string;\n /** Where it lands. Always local. */\n target: string;\n anonymize: boolean;\n /** Schemas to copy. Empty means every non-system schema. */\n schemas: string[];\n /**\n * What the target runs on, which decides how the dump carries its rows.\n * Absent means `postgres`. {@link dumpSource} reads it off the target.\n */\n targetEngine?: PullTargetEngine;\n}\n\n/**\n * Rows per `INSERT` in a dump for the managed database.\n *\n * One per statement restored 100k rows in 8s; a hundred took 0.8s. A hundred\n * 512KB rows, a 100MB statement, still went in.\n */\nconst ROWS_PER_INSERT = 100;\n\n/**\n * `pg_dump` arguments for the source.\n *\n * `--no-owner` and `--no-acl` because the roles on a production server do not\n * exist locally, and without them every `ALTER … OWNER TO` in the dump fails and\n * buries the real output in noise. `--format=custom` so `pg_restore` can be told\n * to continue past errors selectively rather than all-or-nothing.\n *\n * For the managed database the rows travel as `INSERT`s, which PGlite takes\n * like any other statement, instead of `COPY` data, which it cannot take at\n * all — see {@link PullTargetEngine}. The copy is the same; only how the rows\n * are written in the dump differs.\n */\nexport function dumpArgs(plan: PullPlan): string[] {\n const args = [\"--format=custom\", \"--no-owner\", \"--no-acl\", \"--no-privileges\"];\n if (plan.targetEngine === \"pglite\") args.push(`--rows-per-insert=${ROWS_PER_INSERT}`);\n for (const schema of plan.schemas) args.push(\"--schema\", schema);\n args.push(\"--dbname\", splitPassword(plan.source).connectionString);\n\n return args;\n}\n\n/** The environment `pg_dump` runs with: the source's password, if it has one. */\nexport function dumpEnv(plan: PullPlan): Record<string, string> {\n return passwordEnv(plan.source);\n}\n\n/** The environment `pg_restore` runs with: the target's password, if it has one. */\nexport function restoreEnv(plan: PullPlan): Record<string, string> {\n return passwordEnv(plan.target);\n}\n\nfunction passwordEnv(connectionString: string): Record<string, string> {\n const { password } = splitPassword(connectionString);\n return password === null ? {} : { PGPASSWORD: password };\n}\n\n/**\n * A libpq connection string without its password, and the password.\n *\n * The password goes in `PGPASSWORD`, never on a command line, where every\n * process listing can read it and every failure prints it back (execa's error\n * repeats the command). The same rule `db backup` follows; this mirrors\n * `splitPassword` in `@rebasepro/server-postgres`'s connection-string utils,\n * which is not exported. Covers the user-info password and a `password=`\n * parameter; anything that does not parse as a postgres URL is left alone.\n */\nfunction splitPassword(connectionString: string): { connectionString: string; password: string | null } {\n let url: URL;\n try {\n url = new URL(connectionString);\n } catch {\n return { connectionString, password: null };\n }\n if (url.protocol !== \"postgres:\" && url.protocol !== \"postgresql:\") return { connectionString, password: null };\n\n const fromUserInfo = url.password ? decodePercent(url.password) : null;\n const fromParameter = url.searchParams.get(\"password\");\n if (fromUserInfo === null && fromParameter === null) return { connectionString, password: null };\n\n url.password = \"\";\n if (fromParameter !== null) {\n url.searchParams.delete(\"password\");\n // By hand: URLSearchParams writes a space as `+`, which libpq reads literally.\n url.search = Array.from(url.searchParams.entries())\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)\n .join(\"&\");\n }\n return { connectionString: url.toString(), password: fromUserInfo ?? fromParameter };\n}\n\nfunction decodePercent(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\n/**\n * `pg_restore` arguments for the target.\n *\n * It restores into schemas {@link restoreCopy} has already emptied, so\n * `--clean --if-exists` drops nothing that is there; it stays for whatever a\n * dump holds outside them — an extension, say — which would otherwise fail as\n * already existing. `--no-owner` for the same reason as the dump.\n */\nexport function restoreArgs(plan: PullPlan, dumpFile: string): string[] {\n return [\"--clean\", \"--if-exists\", \"--no-owner\", \"--no-privileges\", \"--dbname\", splitPassword(plan.target).connectionString, dumpFile];\n}\n\n/**\n * Is this PostgreSQL client tool on PATH, and what version? Both are checked\n * before anything destructive: discovering `pg_restore` is missing after the\n * dump has been taken — or after `--clean` has emptied the target — is the\n * worst possible ordering.\n */\nexport async function findPgTool(tool: \"pg_dump\" | \"pg_restore\"): Promise<string | null> {\n try {\n const { stdout } = await execa(tool, [\"--version\"]);\n\n return stdout.trim();\n } catch {\n return null;\n }\n}\n\n/** PGlite names itself in `version()`: `PostgreSQL 18.3 (PGlite 0.5.6) on wasm32-…`. */\nfunction engineOf(version: string): PullTargetEngine {\n return /\\bPGlite\\b/i.test(version) ? \"pglite\" : \"postgres\";\n}\n\nconst NOTHING_CHANGED = \"Nothing was changed: the local database is as it was.\";\n\n/** What the target database runs on, or why it could not be asked. */\nasync function readTargetEngine(target: string): Promise<{ engine: PullTargetEngine } | { error: unknown }> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: target, connectionTimeoutMillis: 10_000 });\n client.on(\"error\", () => undefined);\n try {\n await client.connect();\n const { rows } = await client.query<{ version: string }>(\"SELECT version() AS version\");\n\n return { engine: engineOf(rows[0]?.version ?? \"\") };\n } catch (error) {\n return { error };\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n/** How {@link dumpSource} ended. */\nexport type DumpOutcome =\n | {\n ok: true;\n /** The plan the dump was taken for, with its target's engine read: what {@link restoreCopy} takes. */\n plan: PullPlan;\n }\n | {\n ok: false;\n /** What failed and what to do, as plain lines for the caller to print. Nothing was changed. */\n lines: string[];\n };\n\n/**\n * `pg_dump` the source into `dumpFile`, in the form the target can restore.\n *\n * It asks the target what it runs on first — the managed database cannot take\n * `COPY` data, see {@link PullTargetEngine} — which also finds a local\n * database that is not there before anything is read from the source.\n *\n * pg_dump's stderr is kept rather than shown as it arrives, so a failure is\n * reported once, in the reader's terms: an unreachable source, or credentials\n * it refused, get the banner every database command prints for a connection\n * that failed, and anything else is pg_dump's own words with a line saying\n * nothing was changed. A dump that succeeds with warnings still shows them.\n * A dump that fails leaves no file behind.\n */\nexport async function dumpSource(plan: PullPlan, dumpFile: string): Promise<DumpOutcome> {\n try {\n const outcome = await dumpInto(plan, dumpFile);\n if (!outcome.ok) fs.rmSync(dumpFile, { force: true });\n\n return outcome;\n } catch (error) {\n fs.rmSync(dumpFile, { force: true });\n throw error;\n }\n}\n\nasync function dumpInto(plan: PullPlan, dumpFile: string): Promise<DumpOutcome> {\n let targetEngine = plan.targetEngine;\n if (!targetEngine) {\n const read = await readTargetEngine(plan.target);\n if (\"error\" in read) {\n return {\n ok: false,\n lines: banner(`Cannot connect to PostgreSQL at ${hostOf(plan.target)}`,\n `The driver said: ${connectionErrorText(read.error)}`, [\n \"That is the local database the pull would replace, and nothing\",\n \"was read from the source.\",\n \"Start it — `rebase dev` starts the managed one, `rebase dev --docker`\",\n \"Postgres in Docker — or check DATABASE_URL in .env, then pull again.\"\n ])\n };\n }\n targetEngine = read.engine;\n }\n\n const planned: PullPlan = { ...plan, targetEngine };\n const run = await execa(\"pg_dump\", [...dumpArgs(planned), \"--file\", dumpFile], {\n env: dumpEnv(planned),\n stdin: \"ignore\",\n stdout: \"inherit\",\n stderr: \"pipe\",\n reject: false\n });\n if (run.exitCode === 0) {\n if (run.stderr.trim()) process.stderr.write(`${run.stderr.trimEnd()}\\n`);\n\n return { ok: true, plan: planned };\n }\n\n return { ok: false, lines: describeDumpFailure(plan.source, run) };\n}\n\n/**\n * Why `pg_dump` could not read the source, as plain lines for the caller to\n * print. The dump is taken before anything local is touched, so every one of\n * them ends the same way: nothing was changed.\n */\nexport function describeDumpFailure(source: string, run: RestoreRun): string[] {\n if (run.signal) return [`✗ pg_dump was stopped by ${run.signal} before it finished.`, NOTHING_CHANGED];\n if (run.exitCode === undefined) {\n return [\n `✗ pg_dump could not be started (${run.code ?? \"unknown error\"}).`,\n NOTHING_CHANGED,\n \"Check that the PostgreSQL client tools are installed (`pg_dump --version`).\"\n ];\n }\n\n const stderr = (run.stderr ?? \"\").trim();\n const host = hostOf(source);\n const error = /pg_dump: error: (.+)/.exec(stderr)?.[1]?.trim() ?? null;\n const said = error ? `pg_dump said: ${error}` : null;\n\n if (/could not translate host name|could not connect to server|connection to server .* failed: (?:Connection refused|timeout expired|No route to host|Network is unreachable|Operation timed out|Host is down)/i.test(stderr)) {\n return banner(`Cannot connect to PostgreSQL at ${host}`, said, [\n \"That is the database --from names, which the pull reads.\",\n NOTHING_CHANGED,\n \"Check the host and port in --from, and that this machine can reach\",\n \"that server: a VPN, an allow-list, or an SSH tunnel.\"\n ]);\n }\n if (/password authentication failed|no pg_hba\\.conf entry|role \"[^\"]+\" does not exist/i.test(stderr)) {\n let user = \"unknown\";\n try {\n user = decodePercent(new URL(source).username) || \"unknown\";\n } catch { /* named as unknown */ }\n return banner(`Authentication failed for user \"${user}\" at ${host}`, said, [\n \"PostgreSQL rejected the credentials --from carries.\",\n NOTHING_CHANGED,\n \"Check the user and password in --from.\"\n ]);\n }\n // The server answered and has no database of that name: a typo in\n // --from, usually, or a database not created yet.\n const missing = /database \"([^\"]+)\" does not exist/i.exec(stderr)?.[1];\n if (missing) {\n return banner(`Database \"${missing}\" does not exist at ${host}`, said, [\n \"That is the database --from names, which the pull reads.\",\n NOTHING_CHANGED,\n \"Check the database name in --from.\"\n ]);\n }\n\n const versions = /server version mismatch/i.test(stderr)\n ? [\"pg_dump is older than the server: install client tools at least as new as it (`brew install libpq`).\"]\n : [];\n return [\n ...(stderr ? stderr.split(\"\\n\") : []),\n `✗ pg_dump could not dump ${describeTarget(source)} (exit code ${run.exitCode}).`,\n NOTHING_CHANGED,\n ...versions\n ];\n}\n\n/** The fields of a finished `pg_restore` (or `pg_dump`) run that decide {@link restoreOutcome}. */\nexport interface RestoreRun {\n exitCode?: number;\n signal?: string;\n /** A spawn failure's code — `ENOENT` when the binary vanished. */\n code?: string;\n stderr?: string;\n}\n\n/** What a `pg_restore` run says about the copy. */\nexport interface RestoreRunOutcome {\n /** Whether anything can have arrived — what decides whether an anonymization pass has data to redact. */\n started: boolean;\n /** Null when the copy is complete. */\n failure: string | null;\n /**\n * What to do about the failure. \"Pull again\" only where a second pull is\n * what finishes the job: everything else repeats until its cause is fixed.\n */\n advice: string | null;\n}\n\n/**\n * What a finished `pg_restore` says about the copy.\n *\n * The target was emptied before anything was written, so every way this can\n * end short of exit 0 leaves a partial or empty local database, and none of\n * them may be reported as a copy. A non-zero exit is pg_restore saying it\n * skipped statements — \"errors ignored on restore: N\" — and whatever those\n * statements created (a table, its rows, an RLS policy) is missing locally.\n *\n * Restoring into an emptied database, those errors come from what the source\n * holds that this Postgres cannot create — an extension it does not have, a\n * feature of a newer server — and a second pull meets them again. So the\n * advice names that, rather than \"pull again\", which sent people in a loop.\n * On the managed database an extension cannot be installed at all, so the\n * advice there is Postgres in Docker.\n */\nexport function restoreOutcome(run: RestoreRun, engine: PullTargetEngine = \"postgres\"): RestoreRunOutcome {\n if (run.signal) {\n return {\n started: true,\n failure: `pg_restore was stopped by ${run.signal} before it finished.`,\n advice: \"It was interrupted, not refused: pull again to finish the copy.\"\n };\n }\n if (run.exitCode === undefined) {\n return {\n started: false,\n failure: `pg_restore could not be started (${run.code ?? \"unknown error\"}).`,\n advice: \"Check that the PostgreSQL client tools are installed (`pg_restore --version`), then pull again.\"\n };\n }\n if (run.exitCode === 0) return { started: true, failure: null, advice: null };\n\n const ignored = /errors ignored on restore: (\\d+)/.exec(run.stderr ?? \"\");\n const repeats = engine === \"pglite\"\n ? \"Pulling again repeats these errors until what they name is fixed — most often an extension the \"\n + `source uses that the managed database does not have (it has ${PGLITE_EXTENSIONS.map(extension => extension.name).join(\", \")}). `\n + \"Pull into Postgres in Docker instead (`rebase db pull --docker`), or pull only the schemas that do \"\n + \"not need it (--schema).\"\n : \"Pulling again repeats these errors until what they name is fixed — most often an extension \"\n + \"the source uses that this Postgres does not have installed. Install it here, or pull only the schemas \"\n + \"that do not need it (--schema).\";\n\n return {\n started: true,\n failure: ignored\n ? `pg_restore could not restore ${ignored[1]} object(s) — the errors are above.`\n : `pg_restore exited with code ${run.exitCode} — the errors are above.`,\n advice: repeats\n };\n}\n\n/** How {@link restoreCopy} ended. */\nexport interface RestoreOutcome extends RestoreRunOutcome {\n /** Whether the local database was emptied first. False means it is exactly as it was. */\n cleared: boolean;\n}\n\n/**\n * The local schemas a pull empties before it restores: every one of the local\n * database's own for a whole-database pull, and those it copies for a\n * `--schema` pull. `pg_catalog`, `information_schema` and the `pg_*` internals\n * never — see {@link provisionableSchemas}.\n */\nexport function schemasToClear(present: readonly { schema: string }[], planned: readonly string[]): string[] {\n const local = provisionableSchemas(present);\n\n return planned.length === 0 ? local : local.filter((schema) => planned.includes(schema));\n}\n\n/**\n * The statements that empty those schemas, in one transaction.\n *\n * `CASCADE`, which `pg_restore --clean` never uses: a table the source lacks —\n * `rebase.atlas_schema_revisions` from `rebase db migrate`, a collection added\n * locally that references a pulled table — is exactly what blocked its plain\n * `DROP SCHEMA` and `DROP TABLE`. `public` is put back empty, with the access\n * every role has to it by default, because a dump does not create a default\n * `public` and every table in it would otherwise have nowhere to go.\n */\nexport function clearStatements(schemas: readonly string[]): string[] {\n const statements = schemas.map((schema) => `DROP SCHEMA IF EXISTS ${quoteIdentifier(schema)} CASCADE`);\n if (schemas.includes(\"public\")) statements.push(\"CREATE SCHEMA public\", \"GRANT USAGE ON SCHEMA public TO PUBLIC\");\n\n return statements;\n}\n\n/**\n * How long emptying the local database waits for a lock before giving up.\n *\n * A `rebase dev` serving from the database holds connections, and one inside\n * a transaction would otherwise make the pull hang without a word.\n */\nconst CLEAR_LOCK_TIMEOUT = \"15s\";\n\n/** Why emptying the local database failed, in the reader's terms, and what fixes it. */\nfunction clearFailure(error: unknown): RestoreOutcome {\n const code = typeof error === \"object\" && error !== null && \"code\" in error ? String(error.code) : \"\";\n const reason = errorText(error);\n const advice = code === \"55P03\"\n ? \"Something holds a lock on it — usually `rebase dev` serving from it. Stop that, then pull again.\"\n : code === \"42501\"\n ? \"This connection may not drop those schemas. Connect as the role that owns them — the one \"\n + \"that created them — and pull with that.\"\n : \"Fix what the error names; pulling again before that repeats it.\";\n\n return {\n cleared: false,\n started: false,\n failure: `Could not empty the local database before restoring: ${reason}`,\n advice\n };\n}\n\n/**\n * Replace the local database's contents with a dump: empty the schemas it\n * holds, then `pg_restore` into them.\n *\n * Only ever `plan.target`, the local development database the command\n * resolved — the pull's one destination, which no flag can change. Emptying it\n * is one transaction: if any schema cannot be dropped, none is, nothing is\n * restored, and the database is as it was.\n *\n * On the managed database the dump must be one {@link dumpSource} took for it,\n * with its rows as INSERTs: a COPY would leave the daemon answering nobody, so\n * one is refused before anything is emptied. And afterwards its one session —\n * every connection's — is given back its own settings: pg_restore leaves\n * `search_path` empty and `row_security` off behind it, which a running\n * `rebase dev` would otherwise query under.\n */\nexport async function restoreCopy(plan: PullPlan, dumpFile: string): Promise<RestoreOutcome> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: plan.target });\n client.on(\"error\", () => undefined);\n let engine: PullTargetEngine;\n try {\n await client.connect();\n engine = engineOf((await client.query<{ version: string }>(\"SELECT version() AS version\")).rows[0]?.version ?? \"\");\n if (engine === \"pglite\" && plan.targetEngine !== \"pglite\") {\n return {\n cleared: false,\n started: false,\n failure: \"The managed development database cannot take this dump: its rows are COPY data, which PGlite's socket server cannot receive.\",\n advice: \"Pull into Postgres in Docker instead: `rebase db pull --docker`.\"\n };\n }\n const { rows } = await client.query<{ schema: string }>(\"SELECT nspname AS \\\"schema\\\" FROM pg_namespace\");\n await client.query(\"BEGIN\");\n await client.query(`SET LOCAL lock_timeout = '${CLEAR_LOCK_TIMEOUT}'`);\n for (const statement of clearStatements(schemasToClear(rows, plan.schemas))) await client.query(statement);\n await client.query(\"COMMIT\");\n } catch (error) {\n await client.query(\"ROLLBACK\").catch(() => undefined);\n return clearFailure(error);\n } finally {\n await client.end().catch(() => undefined);\n }\n\n // A pg_dump older than the source server's minor writes its `pg_attver`\n // attribute options, which the target may refuse — see attver.ts.\n stripAttverFromArchive(dumpFile);\n\n // stderr is shown as it arrives and kept, for the count in its summary\n // line. Not rejected: every way this ends is judged by `restoreOutcome`.\n const run = await execa(\"pg_restore\", restoreArgs(plan, dumpFile), {\n env: restoreEnv(plan),\n stdin: \"ignore\",\n stdout: \"inherit\",\n stderr: [\"pipe\", \"inherit\"],\n reject: false\n });\n\n if (engine === \"pglite\") await resetSharedSession(plan.target);\n\n return { cleared: true, ...restoreOutcome(run, engine) };\n}\n\n/**\n * Put the managed database's one session back to its own settings.\n *\n * `RESET ALL` and `DEALLOCATE ALL`, not `DISCARD ALL`: the session is every\n * connection's, and `DISCARD` would also drop the `LISTEN` a running\n * `rebase dev`'s realtime holds on it. The same pair the backup service runs\n * after its tools (`resetSharedSession` in server-postgres' backup-service). Best effort: a daemon that cannot take this cannot take the\n * re-grant that follows either, and that step reports it.\n */\nasync function resetSharedSession(target: string): Promise<void> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: target, connectionTimeoutMillis: 10_000, query_timeout: 15_000 });\n client.on(\"error\", () => undefined);\n try {\n await client.connect();\n await client.query(\"RESET ALL\");\n await client.query(\"DEALLOCATE ALL\");\n } catch {\n // Reported by the next step that connects; see above.\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n/**\n * The lines that report a failed restore: what failed, what state the local\n * database is in now, and what to do. Plain text, for the caller to colour.\n */\nexport function describeRestoreFailure(outcome: RestoreOutcome, source: string): string[] {\n const state = outcome.started\n ? `The local database holds an incomplete copy of ${source}.`\n : outcome.cleared\n ? \"The local database was emptied, and nothing was restored into it.\"\n : \"Nothing was restored, and the local database is as it was.\";\n\n return [outcome.failure ?? \"The restore did not complete.\", state, ...(outcome.advice ? [outcome.advice] : [])];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,IAAM,cAAc;AACpB,IAAM,eAAe;AACrB,IAAM,eAAe;AAErB,SAAS,OAAO,MAAsB;CAClC,OAAO,IAAI,OAAO,OAAO,WAAW,MAAM,MAAM,CAAC;AACrD;;;;;AAMA,SAAgB,mBAAmB,YAA4B;CAC3D,IAAI,CAAC,WAAW,SAAS,YAAY,GAAG,OAAO;CAE/C,OAAO,WACF,QAAQ,cAAc,cAAc,OAAO,SAAS,CAAC,CAAC,CACtD,QAAQ,eAAe,WAAW,OAAO,MAAM,CAAC,CAAC,CACjD,QAAQ,eAAe,WAAW,OAAO,MAAM,CAAC;AACzD;;AAGA,IAAM,SAAS,eAAe,GAAG,IAAI,CAAC;AACtC,IAAM,SAAS,eAAe,GAAG,IAAI,CAAC;AACtC,IAAM,QAAQ,eAAe,GAAG,IAAI,CAAC;AACrC,IAAM,QAAQ,eAAe,GAAG,IAAI,CAAC;AACrC,IAAM,QAAQ,eAAe,GAAG,IAAI,CAAC;;AAErC,IAAM,gBAAgB;;AAEtB,IAAM,aAAa;AAEnB,SAAS,eAAe,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AAQ;CACZ,CAAC;CAED,IAAI,WAAW,UAAU,MAAM,mBAAmB,KAAK,MAAM;CAE7D,OAAO;EAAE,SAAS;EAAM,GAAG,eAAe,KAAK,MAAM;CAAE;AAC3D;;;;;;;;;;AAWA,eAAe,mBAAmB,QAA+B;CAC7D,MAAM,EAAE,WAAW,MAAM,OAAO;CAChC,MAAM,SAAS,IAAI,OAAO;EAAE,kBAAkB;EAAQ,yBAAyB;EAAQ,eAAe;CAAO,CAAC;CAC9G,OAAO,GAAG,eAAe,KAAA,CAAS;CAClC,IAAI;EACA,MAAM,OAAO,QAAQ;EACrB,MAAM,OAAO,MAAM,WAAW;EAC9B,MAAM,OAAO,MAAM,gBAAgB;CACvC,QAAQ,CAER,UAAU;EACN,MAAM,OAAO,IAAI,CAAC,CAAC,YAAY,KAAA,CAAS;CAC5C;AACJ;;;;;AAMA,SAAgB,uBAAuB,SAAyB,QAA0B;CACtF,MAAM,QAAQ,QAAQ,UAChB,kDAAkD,OAAO,KACzD,QAAQ,UACJ,sEACA;CAEV,OAAO;EAAC,QAAQ,WAAW;EAAiC;EAAO,GAAI,QAAQ,SAAS,CAAC,QAAQ,MAAM,IAAI,CAAC;CAAE;AAClH"}
|
package/dist/resolve-BY7bSFRT.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"schema-DwFDI1iU.js","names":[],"sources":["../src/commands/schema-reconcile.ts","../src/commands/schema.ts"],"sourcesContent":["/**\n * CLI command: rebase schema reconcile\n *\n * The reviewed step for what boot will not do. Boot only ever adds, so a\n * column made nullable keeps its NOT NULL, and a column removed from a table\n * leaves it behind, with its data, and blocking inserts if it was\n * required. This asks the running backend for the plan that fixes both, prints\n * it, and applies it only once confirmed.\n *\n * Through the backend rather than a database URL, because on Rebase Cloud the\n * backend is the one thing that can reach the database — and because it plans\n * against the tables it actually runs, not the ones in this checkout.\n * Columns are dropped only when named with `--drop`; the confirmation sends\n * the plan's digest, so the server runs exactly the statements printed here.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport readline from \"node:readline/promises\";\nimport { RebaseApiError } from \"@rebasepro/client\";\nimport type { SchemaReconcilePlan } from \"@rebasepro/types\";\nimport { requireProjectRoot, readEnvFile } from \"../utils/project\";\nimport { UsageError } from \"../utils/args\";\nimport { cliUserAgent } from \"../utils/version\";\nimport { describeFailure, requireBackendUrl } from \"./api-keys\";\n\nexport const RECONCILE_USAGE = \"rebase schema reconcile [--drop <table>.<column>]... [--yes]\";\n\nexport function parseReconcileArgs(rawArgs: string[]): { drop: string[]; yes: boolean } {\n const flags = arg({ \"--drop\": [String], \"--yes\": Boolean, \"-y\": \"--yes\" }, { argv: rawArgs.slice(2) });\n if (flags._.length > 0) throw new UsageError(`Unexpected argument \"${flags._[0]}\". Usage: ${RECONCILE_USAGE}`);\n return { drop: flags[\"--drop\"] ?? [], yes: flags[\"--yes\"] === true };\n}\n\n/** The plan, as a person reviews it. Returned as lines so it can be tested. */\nexport function describeReconcilePlan(plan: SchemaReconcilePlan): string[] {\n const lines: string[] = [];\n for (const r of plan.relaxed) {\n const why = r.undeclared\n ? `\"${r.collection}\" does not declare it, and every insert fails on it; its data stays`\n : `nullable in \"${r.collection}\", NOT NULL in the database`;\n lines.push(` ${chalk.cyan(\"relax\")} ${r.table}.${r.column} ${chalk.gray(why)}`);\n }\n for (const d of plan.dropped) {\n const rows = d.rowsWithValue === undefined ? \"\" : `${d.rowsWithValue.toLocaleString(\"en-US\")} row(s) hold a value`;\n lines.push(` ${chalk.red(\"drop\")} ${d.table}.${d.column} ${chalk.red(rows)}`);\n }\n const kept = plan.undeclared.filter(u =>\n !plan.dropped.some(d => d.table === u.table && d.column === u.column)\n && !plan.relaxed.some(r => r.undeclared && r.table === u.table && r.column === u.column));\n for (const u of kept) {\n const note = u.blocksInserts\n ? chalk.yellow(\"NOT NULL with no default: every insert fails until it is dropped or relaxed\")\n : chalk.gray(\"no table declares it; kept\");\n lines.push(` ${chalk.gray(\"keep\")} ${u.table}.${u.column} ${note}`);\n }\n return lines;\n}\n\ninterface Backend {\n baseUrl: string;\n post<T>(path: string, body: unknown): Promise<T>;\n}\n\n/** The project's backend, holding the service key. */\nfunction connect(): Backend {\n const projectRoot = requireProjectRoot();\n const env = readEnvFile(projectRoot);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n if (!serviceKey) {\n console.error(chalk.red(\"✗ REBASE_SERVICE_KEY not found in .env — required to change the database's schema.\"));\n process.exit(1);\n }\n const baseUrl = requireBackendUrl(env, projectRoot).replace(/\\/+$/, \"\");\n return {\n baseUrl,\n async post<T>(path: string, body: unknown): Promise<T> {\n let response: Response;\n try {\n response = await fetch(`${baseUrl}/api/admin/schema/reconcile${path}`, {\n method: \"POST\",\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n \"User-Agent\": cliUserAgent()\n },\n body: JSON.stringify(body)\n });\n } catch (error: unknown) {\n throw new RebaseApiError(error instanceof Error ? error.message : String(error), { status: 0, code: \"NETWORK_ERROR\" });\n }\n const answer: unknown = await response.json().catch(() => undefined);\n if (!response.ok) {\n const error = answer && typeof answer === \"object\" && \"error\" in answer && answer.error && typeof answer.error === \"object\"\n ? answer.error as { message?: unknown; code?: unknown; details?: unknown }\n : undefined;\n throw new RebaseApiError(\n typeof error?.message === \"string\" ? error.message : `The server answered ${response.status}.`,\n { status: response.status, code: typeof error?.code === \"string\" ? error.code : undefined, details: error?.details }\n );\n }\n return answer as T;\n }\n };\n}\n\nfunction fail(action: string, error: unknown, baseUrl: string): never {\n for (const line of describeFailure(action, error, baseUrl)) {\n console.error(line.startsWith(\"✗\") ? chalk.red(line) : chalk.gray(line));\n }\n if (error instanceof RebaseApiError && error.status === 404) {\n console.error(chalk.gray(\" This backend has no reconcile route: it needs a runtime that has `rebase schema reconcile`.\"));\n }\n process.exit(1);\n}\n\nexport async function schemaReconcileCommand(rawArgs: string[]): Promise<void> {\n const { drop, yes } = parseReconcileArgs(rawArgs);\n const backend = connect();\n\n let plan: SchemaReconcilePlan;\n try {\n plan = await backend.post<SchemaReconcilePlan>(\"/plan\", { drop });\n } catch (error) {\n fail(\"Failed to plan the reconcile\", error, backend.baseUrl);\n }\n\n console.log(chalk.bold(`\\nSchema reconcile for ${backend.baseUrl}\\n`));\n const described = describeReconcilePlan(plan);\n if (described.length > 0) console.log(described.join(\"\\n\"));\n\n if (plan.problems.length > 0) {\n console.error(chalk.red(\"\\n✗ This plan cannot be applied:\"));\n for (const problem of plan.problems) console.error(chalk.red(` • ${problem}`));\n process.exit(1);\n }\n if (plan.statements.length === 0) {\n console.log(chalk.green(\"✓ Nothing to do: the database already matches what the tables declare.\"));\n }\n if (plan.undeclared.length > plan.dropped.length) {\n console.log(chalk.gray(\" To drop a column no table declares, name it: --drop <table>.<column>\"));\n }\n if (plan.statements.length === 0) return;\n\n console.log(chalk.bold(\"\\nStatements\"));\n for (const statement of plan.statements) console.log(` ${statement}`);\n if (plan.dropped.length > 0) {\n console.log(chalk.red(\"\\n Dropping a column destroys its data. Back the database up first if you may want it back.\"));\n }\n\n if (!yes) {\n if (!process.stdin.isTTY) {\n console.error(chalk.red(\"\\n✗ Not applied: confirming needs a terminal. Re-run with --yes once you have read the plan.\"));\n process.exit(1);\n }\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n const answer = (await rl.question(`\\nApply ${plan.statements.length} statement(s)? Type \"yes\" to continue: `)).trim();\n rl.close();\n if (answer !== \"yes\") {\n console.log(chalk.gray(\"Aborted. Nothing was changed.\"));\n return;\n }\n }\n\n try {\n const result = await backend.post<{ applied: string[] }>(\"/apply\", { drop, confirm: plan.digest });\n console.log(chalk.green(`✓ Applied ${result.applied.length} statement(s).`));\n } catch (error) {\n if (error instanceof RebaseApiError && error.code === \"SCHEMA_RECONCILE_STALE\") {\n console.error(chalk.red(\"✗ Not applied: the database or the tables changed since this plan was made. Run it again to review the new plan.\"));\n process.exit(1);\n }\n fail(\"Failed to apply the reconcile\", error, backend.baseUrl);\n }\n}\n","/**\n * CLI command: rebase schema <action>\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { ensureDockerDatabase, spawnDriverCli } from \"./db\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile,\n exitDependenciesNotInstalled\n} from \"../utils/project\";\nimport { recordEvent } from \"../telemetry\";\nimport { wantsHelp } from \"../utils/args\";\nimport { reportSpawnFailure } from \"../utils/spawn-error\";\nimport { argsFromCommand } from \"../utils/command-words\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { DEV_DATABASE_KIND_ENV, devDatabaseKind, managedNotices, prepareDatabaseEnv } from \"../dev-db/prepare\";\nimport { absolutizeLocalPathArgs } from \"./db\";\nimport { SCHEMA_DIR_FLAG_HELP, refuseMissingSchemaDir, refuseRemovedCollectionsFlag } from \"../utils/path-flags\";\nimport { schemaDirArgs } from \"../utils/schema-dir\";\nimport { RECONCILE_USAGE } from \"./schema-reconcile\";\n\n/**\n * The line handed to the driver, its paths resolved from where the command was\n * run (the driver runs in `backend/`). `--schema` is left alone: on\n * `introspect` it names a Postgres schema, not a file.\n */\nexport function schemaDriverArgs(rawArgs: string[], cwd: string): string[] {\n return absolutizeLocalPathArgs(argsFromCommand(rawArgs, \"schema\"), cwd, [\"--schema-dir\", \"--output\", \"-o\", \"--out\"]);\n}\n\nexport async function schemaCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n // `--help` is answered here, before `requireProjectRoot` and before the\n // driver is spawned — the same shape `db.ts` already uses, and for the same\n // reason.\n //\n // `cli.ts` rewrites the subcommand to `\"--help\"` only when the user named\n // none, so `rebase schema --help` was covered and `rebase schema generate\n // --help` was not: the flag travelled into `rawArgs.slice(2)` and reached\n // the driver, whose own `schemaCommand` has no `--help` case. It *ran the\n // generator* — overwriting `src/schema.generated.ts` — for a flag whose\n // entire job is to print text. Worse, the first thing it hit outside a\n // project was `requireProjectRoot`, so `rebase schema introspect --help` in\n // an empty directory exited 1 with \"Could not find a Rebase project root\":\n // help you cannot read until you already have a project is help for nobody.\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printSchemaHelp(subcommand === \"--help\" ? undefined : subcommand);\n return;\n }\n\n // A typo is answered here, in the same words every other family uses.\n //\n // It used to travel to the driver, which said the bare line `Unknown schema\n // command.` — no list, no pointer, no did-you-mean, for a family with three\n // subcommands. The set comes from the help table, so what a typo is measured\n // against and what `--help` prints cannot drift apart.\n if (!SCHEMA_ACTION_HELP[subcommand]) {\n unknownCommand(subcommand, Object.keys(SCHEMA_ACTION_HELP), \"schema\");\n }\n\n // Before anything else runs.\n refuseRemovedCollectionsFlag(rawArgs.slice(2), `schema ${subcommand}`);\n\n const projectRoot = requireProjectRoot();\n\n // Talks to the running backend, not the driver: on Rebase Cloud the\n // backend is the only thing that reaches the database.\n if (subcommand === \"reconcile\") {\n void recordEvent(\"cli.schema\", { subcommand }, { projectRoot });\n const { schemaReconcileCommand } = await import(\"./schema-reconcile\");\n await schemaReconcileCommand(rawArgs);\n return;\n }\n\n // Fire-and-forget, and a no-op unless the developer opted in. Never awaited:\n // the command is what the user is waiting for, and a slow collector must not\n // sit in front of it.\n void recordEvent(\"cli.schema\", { subcommand: subcommand ?? \"none\" }, { projectRoot });\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n exitDependenciesNotInstalled(projectRoot);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n // Which database this project is on, so the driver's closing line does not\n // recommend a command that database refuses. A pure decision — nothing is\n // started, which matters here above all: `schema generate` reads the\n // schema directory and writes one file, and booting a database to run it would be a\n // side effect nobody asked for.\n env[DEV_DATABASE_KIND_ENV] = devDatabaseKind(projectRoot) ?? \"\";\n\n refuseMissingSchemaDir(rawArgs, process.cwd(), backendDir);\n\n // `introspect` is the one schema command that reads a database, and it\n // reads the project's — resolved the way every `db` command resolves it,\n // started if that is what it takes. It used to pass `.env` and nothing\n // else, so on the managed database or after `rebase dev --docker` (with\n // the scaffold's DATABASE_URL commented out, on purpose) it said\n // \"DATABASE_URL is not set\", and `--docker` and `--database-url` passed the\n // flag check only to be ignored.\n if (subcommand === \"introspect\") {\n const flags = arg(\n { \"--database-url\": String, \"--docker\": Boolean },\n { argv: rawArgs.slice(2), permissive: true }\n );\n await ensureDockerDatabase(projectRoot, rawArgs);\n const prepared = await prepareDatabaseEnv(projectRoot, {\n flagUrl: flags[\"--database-url\"] ?? null,\n flagDocker: flags[\"--docker\"] === true,\n onProgress: (message) => console.log(chalk.gray(` ${message}`))\n });\n Object.assign(env, prepared.env);\n env[DEV_DATABASE_KIND_ENV] = prepared.database.kind;\n for (const line of managedNotices(prepared)) console.log(chalk.gray(` ${line}`));\n }\n\n try {\n // The one spawn, shared with `db`. This file used to carry its own copy\n // of the tsx-or-node decision; three copies of that rule existed and two\n // were fixed while the third went on spawning plain node.\n const driverArgs = schemaDriverArgs(rawArgs, process.cwd());\n await spawnDriverCli(\n { projectRoot, backendDir, pluginCli, env },\n [...driverArgs, ...schemaDirArgs(projectRoot, driverArgs)]\n );\n } catch (error) {\n // A child that ran and exited non-zero already printed its diagnostics\n // through inherited stdio; a child that never started (ENOENT on tsx,\n // EACCES on the script) printed nothing at all, and this used to exit 1\n // in silence.\n reportSpawnFailure(error);\n process.exit(1);\n }\n}\n\n/** One page per subcommand, so `rebase schema <action> --help` says something. */\nconst SCHEMA_ACTION_HELP: Record<string, { usage: string; summary: string; notes?: string[] }> = {\n generate: {\n usage: \"rebase schema generate [--schema-dir <dir>] [--output <file>] [--watch]\",\n summary: \"Generate the Drizzle schema from the tables in backend/schema.\",\n notes: [\"--watch regenerates on every change to a schema file.\", `--schema-dir <dir>: ${SCHEMA_DIR_FLAG_HELP}.`]\n },\n introspect: {\n usage: \"rebase schema introspect [--schema-dir <dir>] [--schema <name>] [--force] [--data-inference | --no-data-inference]\",\n summary: \"Read an existing database and write its tables as defineTable modules into backend/schema.\",\n notes: [\n \"--force overwrites table modules that are already there.\",\n `--schema-dir <dir>: where the tables are written — ${SCHEMA_DIR_FLAG_HELP}.`,\n \"--data-inference samples up to 100 rows per table to detect formats, constraints and UI settings; \"\n + \"--no-data-inference reads the structure only. Without either it asks, and without a terminal \"\n + \"it reads the structure only.\",\n \"Reads this project's database, the one `rebase db url` prints: --database-url <url> names another; \"\n + \"--docker uses the compose one, starting it if needed.\"\n ]\n },\n reconcile: {\n usage: RECONCILE_USAGE,\n summary: \"Relax and drop what boot will not: NOT NULL on columns made nullable, and columns no table declares.\",\n notes: [\n \"Plans on the running backend (the one `.env` and the cloud link point at), prints the plan, and applies it once you type yes.\",\n \"A column is dropped only when named: --drop voice_cache.wav. Each drop shows how many rows hold a value.\",\n \"--yes skips the prompt, for a plan already read. Needs REBASE_SERVICE_KEY in .env.\"\n ]\n },\n stale: {\n usage: \"rebase schema stale [--schema-dir <dir>] [--output <file>] [--fix]\",\n summary: \"Report generated schema files that no longer match the tables.\",\n notes: [\"--fix regenerates them instead of only reporting.\"]\n }\n};\n\n/** Every subcommand the family dispatches — the help table's keys. */\nexport const SCHEMA_SUBCOMMANDS = Object.keys(SCHEMA_ACTION_HELP);\n\nfunction printSchemaHelp(action?: string) {\n const entry = action ? SCHEMA_ACTION_HELP[action] : undefined;\n if (entry) {\n console.log(`\n${chalk.bold(`rebase schema ${action}`)}\n\n ${entry.summary}\n\n${chalk.green.bold(\"Usage\")}\n ${chalk.blue(entry.usage)}\n${entry.notes?.length ? `\\n${chalk.green.bold(\"Notes\")}\\n${entry.notes.map(n => ` ${chalk.gray(`• ${n}`)}`).join(\"\\n\")}\\n` : \"\"}\n${chalk.gray(\"Run `rebase schema --help` for every subcommand.\")}\n`);\n return;\n }\n\n console.log(`\n${chalk.bold(\"rebase schema\")} — Schema management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase schema ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.gray(\"(Commands are provided by your active database driver plugin)\")}\n ${chalk.blue.bold(\"generate\")} Generate the Drizzle schema from the tables in backend/schema\n ${chalk.blue.bold(\"introspect\")} Introspect an existing database into defineTable modules in backend/schema\n ${chalk.blue.bold(\"stale\")} Report generated schema files that no longer match the tables\n ${chalk.blue.bold(\"reconcile\")} Relax NOT NULL and drop columns the tables no longer declare, after review\n\n${chalk.green.bold(\"generate / stale Options\")}\n ${chalk.blue(\"--schema-dir\")} ${SCHEMA_DIR_FLAG_HELP}\n ${chalk.blue(\"--output, -o\")} Output path for generated schema\n ${chalk.blue(\"--watch, -w\")} Watch for changes and regenerate automatically\n\n${chalk.green.bold(\"introspect Options\")}\n ${chalk.blue(\"--schema-dir\")} Where the tables are written ${chalk.gray(\"(default: backend/schema)\")}\n ${chalk.blue(\"--schema\")} Postgres schema to read (default: public)\n ${chalk.blue(\"--force, -f\")} Overwrite table modules that already exist\n ${chalk.blue(\"--database-url\")} Read this database instead of the project's own\n ${chalk.blue(\"--docker\")} Read the compose database, starting it if needed\n ${chalk.blue(\"--data-inference\")} Sample rows to detect formats and constraints ${chalk.gray(\"(asked when omitted)\")}\n ${chalk.blue(\"--no-data-inference\")} Read the structure only, without asking\n\n${chalk.green.bold(\"stale Options\")}\n ${chalk.blue(\"--fix\")} Regenerate the stale files instead of only reporting them\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,IAAa,kBAAkB;AAE/B,SAAgB,mBAAmB,SAAqD;CACpF,MAAM,QAAQ,IA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KAAK,+DAA+D,EAAE;IAC5E,MAAM,KAAK,KAAK,UAAU,EAAE;IAC5B,MAAM,KAAK,KAAK,YAAY,EAAE;IAC9B,MAAM,KAAK,KAAK,OAAO,EAAE;IACzB,MAAM,KAAK,KAAK,WAAW,EAAE;;EAE/B,MAAM,MAAM,KAAK,0BAA0B,EAAE;IAC3C,MAAM,KAAK,cAAc,EAAE,SAAS,qBAAqB;IACzD,MAAM,KAAK,cAAc,EAAE;IAC3B,MAAM,KAAK,aAAa,EAAE;;EAE5B,MAAM,MAAM,KAAK,oBAAoB,EAAE;IACrC,MAAM,KAAK,cAAc,EAAE,sCAAsC,MAAM,KAAK,2BAA2B,EAAE;IACzG,MAAM,KAAK,UAAU,EAAE;IACvB,MAAM,KAAK,aAAa,EAAE;IAC1B,MAAM,KAAK,gBAAgB,EAAE;IAC7B,MAAM,KAAK,UAAU,EAAE;IACvB,MAAM,KAAK,kBAAkB,EAAE,mDAAmD,MAAM,KAAK,sBAAsB,EAAE;IACrH,MAAM,KAAK,qBAAqB,EAAE;;EAEpC,MAAM,MAAM,KAAK,eAAe,EAAE;IAChC,MAAM,KAAK,OAAO,EAAE;CACvB;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"storage-iTqj5-Av.js","names":[],"sources":["../src/commands/storage.ts"],"sourcesContent":["/**\n * CLI command: rebase storage <action>\n *\n * Whole-store maintenance through the running backend's `/api/admin/storage`,\n * authenticated with the service key from `.env`.\n *\n * Subcommands:\n * orphans — Stored files no row names; `--delete` deletes them\n * move — Copy a folder of files to another storage source, same keys\n */\nimport chalk from \"chalk\";\nimport readline from \"node:readline/promises\";\nimport { RebaseApiError } from \"@rebasepro/client\";\nimport { requireProjectRoot, readEnvFile } from \"../utils/project\";\nimport { parseCommandArgs, UsageError, wantsHelp } from \"../utils/args\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { cliUserAgent } from \"../utils/version\";\nimport { describeFailure, requireBackendUrl } from \"./api-keys\";\n\n/** Everything the switch below dispatches, for the did-you-mean. */\nexport const STORAGE_SUBCOMMANDS = [\"orphans\", \"move\"] as const;\n\n/** The flags `rebase storage orphans` takes. */\nexport const ORPHANS_FLAGS = {\n \"--source\": String,\n \"--older-than\": Number,\n \"--delete\": Boolean,\n \"--yes\": Boolean,\n \"-y\": \"--yes\",\n \"--json\": Boolean\n} as const;\n\n/** The flags `rebase storage move` takes. */\nexport const MOVE_FLAGS = {\n \"--from\": String,\n \"--to\": String,\n \"--prefix\": String,\n \"--delete-source\": Boolean,\n \"--json\": Boolean\n} as const;\n\n/** One stored object, as the backend lists it. */\ninterface StoredObjectEntry {\n key: string;\n size?: number;\n updated?: string;\n}\n\n/** What `GET /admin/storage/orphans` answers. */\nexport interface OrphanReport {\n storageId: string;\n objects: number;\n orphans: StoredObjectEntry[];\n recent: number;\n scanned: string[];\n unscanned: { collection: string; reason: string }[];\n}\n\n/** An orphan scan's record, as `GET /admin/storage/orphans/scans/:id` answers it. */\ninterface OrphanScanState {\n id: string;\n storageId: string;\n runner: \"worker\" | \"in-process\";\n status: \"queued\" | \"running\" | \"completed\" | \"failed\";\n progress: {\n phase: string;\n filesScanned: number;\n rowsScanned: number;\n historyEntriesScanned: number;\n collectionsScanned: number;\n collectionsTotal: number;\n unscanned: { collection: string; reason: string }[];\n };\n result?: Omit<OrphanReport, \"storageId\">;\n error?: string;\n note?: string;\n deletion?: {\n status: \"queued\" | \"running\" | \"completed\" | \"failed\";\n progress: OrphanScanState[\"progress\"] & { candidates: number; deleted: number };\n result?: { deleted: string[]; kept: { key: string; reason: string }[]; failed: { key: string; error: string }[] };\n error?: string;\n note?: string;\n };\n}\n\n/** How often a running scan is asked about. A setting so the tests need not wait. */\nexport const orphanScanPolling = { intervalMs: 1_000 };\n\ninterface MovedObject {\n key: string;\n outcome: \"copied\" | \"exists\" | \"failed\";\n deleted?: boolean;\n error?: string;\n}\n\ninterface Backend {\n baseUrl: string;\n request<T>(method: string, path: string, body?: unknown): Promise<T>;\n}\n\n/** The project's backend, holding the service key — the `admin` role, every scope. */\nfunction connect(): Backend {\n const projectRoot = requireProjectRoot();\n const env = readEnvFile(projectRoot);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n if (!serviceKey) {\n console.error(chalk.red(\"✗ REBASE_SERVICE_KEY not found in .env — required for storage maintenance.\"));\n process.exit(1);\n }\n // Only an address this project recorded or the developer named: the\n // request carries the service key. See `resolveBackendAddress`.\n const baseUrl = requireBackendUrl(env, projectRoot).replace(/\\/+$/, \"\");\n return {\n baseUrl,\n async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n let response: Response;\n try {\n response = await fetch(`${baseUrl}/api/admin/storage${path}`, {\n method,\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Accept\": \"application/json\",\n \"User-Agent\": cliUserAgent(),\n ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" })\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) })\n });\n } catch (error: unknown) {\n throw new RebaseApiError(error instanceof Error ? error.message : String(error), { status: 0, code: \"NETWORK_ERROR\" });\n }\n const answer: unknown = await response.json().catch(() => undefined);\n if (!response.ok) {\n const error = answer && typeof answer === \"object\" && \"error\" in answer && answer.error && typeof answer.error === \"object\"\n ? answer.error as { message?: unknown; code?: unknown; details?: unknown }\n : undefined;\n throw new RebaseApiError(\n typeof error?.message === \"string\" ? error.message : `The server answered ${response.status}.`,\n { status: response.status, code: typeof error?.code === \"string\" ? error.code : undefined, details: error?.details }\n );\n }\n return (answer as { data: T }).data;\n }\n };\n}\n\nfunction fail(action: string, error: unknown, baseUrl: string): never {\n for (const line of describeFailure(action, error, baseUrl)) {\n console.error(line.startsWith(\"✗\") ? chalk.red(line) : chalk.gray(line));\n }\n if (error instanceof RebaseApiError && error.status === 404 && error.code !== \"UNKNOWN_STORAGE_SOURCE\") {\n console.error(chalk.gray(\" This backend has no storage maintenance routes: they arrived in 0.25, and need storage configured.\"));\n }\n process.exit(1);\n}\n\n/** Bytes, as a person reads them. */\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n const units = [\"KB\", \"MB\", \"GB\", \"TB\"];\n let value = bytes / 1024;\n let unit = 0;\n while (value >= 1024 && unit < units.length - 1) {\n value /= 1024;\n unit++;\n }\n return `${value.toFixed(value < 10 ? 1 : 0)} ${units[unit]}`;\n}\n\n/**\n * The lines that describe an orphan scan. Exported so its tests can read them\n * without a server.\n */\nexport function describeOrphanReport(report: OrphanReport, olderThanHours: number): string[] {\n const lines: string[] = [];\n const bytes = report.orphans.reduce((sum, orphan) => sum + (orphan.size ?? 0), 0);\n lines.push(` ${report.objects} file(s) in source \"${report.storageId}\", ${report.scanned.length} table(s) read.`);\n if (report.orphans.length === 0) {\n lines.push(\" No file older than \" + `${olderThanHours}h is unused.`);\n } else {\n lines.push(` ${report.orphans.length} file(s) no row names, ${formatBytes(bytes)}:`);\n for (const orphan of report.orphans) {\n lines.push(` ${orphan.key}${orphan.size !== undefined ? ` ${formatBytes(orphan.size)}` : \"\"}${orphan.updated ? ` ${orphan.updated}` : \"\"}`);\n }\n }\n if (report.recent > 0) {\n const one = report.recent === 1;\n const more = report.orphans.length > 0 ? \"more \" : \"\";\n lines.push(` ${report.recent} ${more}unused ${one ? \"file is\" : \"files are\"} left out: ` +\n `${one ? \"it is\" : \"they are\"} newer than ${olderThanHours}h, or ${one ? \"its\" : \"their\"} age is unknown, ` +\n \"and an upload can be saved before the row that names it.\");\n }\n for (const entry of report.unscanned) {\n lines.push(` ⚠ ${entry.collection} could not be read (${entry.reason}): a file only it names is listed above.`);\n }\n return lines;\n}\n\nasync function confirm(question: string): Promise<boolean> {\n const prompt = readline.createInterface({ input: process.stdin, output: process.stdout });\n try {\n return /^y(es)?$/i.test((await prompt.question(question)).trim());\n } finally {\n prompt.close();\n }\n}\n\nconst sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));\n\n/** Whether an error is a backend without the route asked for, as opposed to a source it does not serve. */\nconst isMissingRoute = (error: unknown) => error instanceof RebaseApiError && error.status === 404\n && error.code !== \"UNKNOWN_STORAGE_SOURCE\" && error.code !== \"STORAGE_SCAN_NOT_FOUND\";\n\n/** One line of a running scan's progress, rewritten in place on a terminal. */\nfunction progressLine(text: string, quiet: boolean): void {\n if (!quiet && process.stdout.isTTY) process.stdout.write(`\\r\\x1b[2K ${text}`);\n}\n\nfunction endProgressLine(quiet: boolean): void {\n if (!quiet && process.stdout.isTTY) process.stdout.write(\"\\n\");\n}\n\n/** Ask for a scan's record until `done` says so, printing its progress. */\nasync function pollScan(\n backend: Backend,\n id: string,\n sourceQuery: string,\n done: (state: OrphanScanState) => boolean,\n describe: (state: OrphanScanState) => string,\n quiet: boolean\n): Promise<OrphanScanState> {\n let noted = false;\n for (;;) {\n let state: OrphanScanState;\n try {\n state = await backend.request<OrphanScanState>(\"GET\", `/orphans/scans/${encodeURIComponent(id)}${sourceQuery}`);\n } catch (error: unknown) {\n endProgressLine(quiet);\n fail(\"Failed to read the scan's progress\", error, backend.baseUrl);\n }\n if (done(state)) {\n endProgressLine(quiet);\n return state;\n }\n progressLine(describe(state), quiet);\n const note = state.note ?? state.deletion?.note;\n if (note && !noted && !quiet) {\n noted = true;\n endProgressLine(quiet);\n console.log(chalk.yellow(` ${note}`));\n }\n await sleep(orphanScanPolling.intervalMs);\n }\n}\n\n/**\n * Scan for orphans: started on the backend and asked about until it is done,\n * so a scan longer than any request timeout still finishes. A backend from\n * before scans ran in the background is asked the old way, in one request.\n */\nasync function scanForOrphans(\n backend: Backend,\n query: URLSearchParams,\n sourceQuery: string,\n quiet: boolean\n): Promise<{ report: OrphanReport; scanId?: string }> {\n let started: OrphanScanState;\n try {\n started = await backend.request<OrphanScanState>(\"POST\", `/orphans/scans?${query}`);\n } catch (error: unknown) {\n if (!isMissingRoute(error)) fail(\"Failed to start a storage scan\", error, backend.baseUrl);\n try {\n return { report: await backend.request<OrphanReport>(\"GET\", `/orphans?${query}`) };\n } catch (legacyError: unknown) {\n fail(\"Failed to scan storage\", legacyError, backend.baseUrl);\n }\n }\n if (!quiet && started.runner === \"in-process\") {\n console.log(chalk.gray(\" This backend runs no job queue, so the scan runs inside the server process, in the background. A restart of that process stops it.\"));\n }\n const finished = await pollScan(\n backend,\n started.id,\n sourceQuery,\n state => state.status === \"completed\" || state.status === \"failed\",\n state => state.status === \"queued\"\n ? \"Waiting for the scan to start…\"\n : `Scanning \"${state.storageId}\": ${state.progress.filesScanned} file(s) listed, ${state.progress.rowsScanned} row(s) read, ` +\n `${state.progress.collectionsScanned}/${state.progress.collectionsTotal} table(s)` +\n (state.progress.unscanned.length > 0 ? `, ${state.progress.unscanned.length} unreadable` : \"\") + \"…\",\n quiet\n );\n if (finished.status === \"failed\" || !finished.result) {\n console.error(chalk.red(`✗ The scan failed: ${finished.error ?? \"no reason was recorded\"}`));\n process.exit(1);\n }\n return { report: { storageId: finished.storageId, ...finished.result }, scanId: finished.id };\n}\n\n/** Delete a completed scan's orphans, in the background, and wait for it. */\nasync function deleteFromScan(\n backend: Backend,\n scanId: string,\n sourceQuery: string,\n quiet: boolean\n): Promise<{ deleted: string[]; failed: { key: string; error: string }[]; kept: { key: string; reason: string }[]; error?: string }> {\n const deleteQuery = new URLSearchParams(sourceQuery.replace(/^\\?/, \"\"));\n deleteQuery.set(\"scan\", scanId);\n try {\n await backend.request(\"DELETE\", `/orphans?${deleteQuery}`);\n } catch (error: unknown) {\n fail(\"Failed to delete unused files\", error, backend.baseUrl);\n }\n const finished = await pollScan(\n backend,\n scanId,\n sourceQuery,\n state => state.deletion?.status === \"completed\" || state.deletion?.status === \"failed\",\n state => {\n const progress = state.deletion?.progress;\n if (!progress || state.deletion?.status === \"queued\") return \"Waiting for the delete to start…\";\n return progress.phase === \"deleting\"\n ? `Deleting: ${progress.deleted} of ${progress.candidates} file(s)…`\n : `Checking every row again before deleting: ${progress.rowsScanned} row(s) read, ` +\n `${progress.collectionsScanned}/${progress.collectionsTotal} table(s)…`;\n },\n quiet\n );\n const deletion = finished.deletion!;\n return {\n deleted: deletion.result?.deleted ?? [],\n failed: deletion.result?.failed ?? [],\n kept: deletion.result?.kept ?? [],\n ...(deletion.status === \"failed\" ? { error: deletion.error ?? \"no reason was recorded\" } : {})\n };\n}\n\nasync function orphans(rawArgs: string[]): Promise<void> {\n const { flags } = parseCommandArgs({ spec: ORPHANS_FLAGS, rawArgs, commandWords: 2, command: \"storage orphans\", maxPositionals: 0 });\n const olderThan = flags[\"--older-than\"] ?? 24;\n if (!Number.isFinite(olderThan) || olderThan < 0) {\n throw new UsageError(\"--older-than takes a number of hours, 0 or more.\");\n }\n const query = new URLSearchParams({ olderThanHours: String(olderThan) });\n if (flags[\"--source\"]) query.set(\"storageId\", flags[\"--source\"]);\n const sourceQuery = flags[\"--source\"] ? `?${new URLSearchParams({ storageId: flags[\"--source\"] })}` : \"\";\n const quiet = flags[\"--json\"] === true;\n const backend = connect();\n\n const { report, scanId } = await scanForOrphans(backend, query, sourceQuery, quiet);\n\n if (!flags[\"--delete\"]) {\n if (flags[\"--json\"]) {\n console.log(JSON.stringify({ ...report, ...(scanId ? { scanId } : {}) }, null, 2));\n return;\n }\n console.log(\"\");\n for (const line of describeOrphanReport(report, olderThan)) console.log(line);\n if (report.orphans.length > 0) {\n console.log(\"\");\n console.log(chalk.gray(\" Nothing was deleted. Run again with --delete to delete them.\"));\n }\n console.log(\"\");\n return;\n }\n\n if (!flags[\"--json\"]) {\n console.log(\"\");\n for (const line of describeOrphanReport(report, olderThan)) console.log(line);\n console.log(\"\");\n }\n if (report.orphans.length === 0) return;\n if (report.unscanned.length > 0) {\n console.error(chalk.red(\"✗ Not deleting: some tables could not be read, so a file they name would look unused.\"));\n process.exit(1);\n }\n if (!flags[\"--yes\"]) {\n if (!process.stdin.isTTY) {\n throw new UsageError(\"--delete deletes files for good; pass --yes to confirm when there is no terminal to ask.\");\n }\n if (!await confirm(` Delete these ${report.orphans.length} file(s) for good? [y/N] `)) {\n console.log(chalk.gray(\" Nothing was deleted.\"));\n return;\n }\n }\n\n let result: { deleted: string[]; failed: { key: string; error: string }[]; kept?: { key: string; reason: string }[]; error?: string };\n if (scanId) {\n // The server reads every row again against these files, and asks for\n // each file again right before deleting it: one a row has named since\n // the list was printed, or that was uploaded again, is kept.\n result = await deleteFromScan(backend, scanId, sourceQuery, quiet);\n } else {\n try {\n // A backend from before background scans finds them again, inside the request.\n result = await backend.request(\"DELETE\", `/orphans?${query}`);\n } catch (error: unknown) {\n fail(\"Failed to delete unused files\", error, backend.baseUrl);\n }\n }\n if (flags[\"--json\"]) {\n console.log(JSON.stringify({ storageId: report.storageId, ...result, recent: report.recent }, null, 2));\n } else {\n if (result.error) console.error(chalk.red(` ✗ ${result.error}`));\n console.log(chalk.green(` ✓ Deleted ${result.deleted.length} file(s).`));\n for (const kept of result.kept ?? []) console.log(chalk.yellow(` Kept ${kept.key}: ${kept.reason}`));\n for (const failure of result.failed) console.error(chalk.red(` ✗ ${failure.key}: ${failure.error}`));\n console.log(\"\");\n }\n if (result.failed.length > 0 || result.error) process.exitCode = 1;\n}\n\nasync function move(rawArgs: string[]): Promise<void> {\n const { flags } = parseCommandArgs({ spec: MOVE_FLAGS, rawArgs, commandWords: 2, command: \"storage move\", maxPositionals: 0 });\n const from = flags[\"--from\"];\n const to = flags[\"--to\"];\n if (!from && !to) {\n throw new UsageError(\"Name the sources: --from <source> --to <source>. The default source is \\\"(default)\\\", and either may be left out for it.\");\n }\n const backend = connect();\n const counts = { copied: 0, exists: 0, failed: 0, deleted: 0 };\n const failures: MovedObject[] = [];\n let cursor: string | undefined;\n do {\n let page: { moved: MovedObject[]; cursor?: string };\n try {\n page = await backend.request(\"POST\", \"/move\", {\n from,\n to,\n prefix: flags[\"--prefix\"],\n cursor,\n deleteSource: flags[\"--delete-source\"] === true\n });\n } catch (error: unknown) {\n fail(\"Failed to move files\", error, backend.baseUrl);\n }\n for (const object of page.moved) {\n counts[object.outcome]++;\n if (object.deleted) counts.deleted++;\n if (object.outcome === \"failed\") failures.push(object);\n }\n if (!flags[\"--json\"] && process.stdout.isTTY) {\n process.stdout.write(`\\r ${counts.copied} copied, ${counts.exists} already there, ${counts.failed} failed…`);\n }\n cursor = page.cursor;\n } while (cursor);\n\n // The source listed again, by a walk of its own: a move reports what its\n // walk saw, and a walk that skipped files once reported success over the\n // half it moved.\n const verified = await listLeftBehind(backend, {\n from,\n to,\n prefix: flags[\"--prefix\"],\n deleteSource: flags[\"--delete-source\"] === true\n }, flags[\"--json\"] === true);\n const reported = new Set(failures.map(failure => failure.key));\n const leftBehind = verified?.filter(entry => !reported.has(entry.key)) ?? [];\n\n if (flags[\"--json\"]) {\n console.log(JSON.stringify({ ...counts, failures, verified: verified !== undefined, notMoved: verified ?? [] }, null, 2));\n } else {\n if (process.stdout.isTTY) process.stdout.write(\"\\n\");\n console.log(chalk.green(` ✓ ${counts.copied} copied, ${counts.exists} already there` +\n `${flags[\"--delete-source\"] ? `, ${counts.deleted} deleted from the source` : \"\"}.`));\n for (const failure of failures) console.error(chalk.red(` ✗ ${failure.key}: ${failure.error ?? \"failed\"}`));\n if (verified === undefined) {\n console.log(chalk.gray(\" This backend cannot list the source again (it needs a backend newer than 0.25.1), so the CLI did not check for files the move left behind.\"));\n } else if (leftBehind.length > 0) {\n console.error(chalk.red(` ✗ Listed again, the source holds ${leftBehind.length} more file(s) the move did not report: ${leftBehind.length} file(s) were not moved.`));\n for (const entry of leftBehind) console.error(chalk.red(` ${entry.key}: ${entry.reason}`));\n console.error(chalk.gray(\" Run the same move again to pick them up.\"));\n }\n if (counts.copied + counts.exists > 0 && !flags[\"--delete-source\"]) {\n console.log(chalk.gray(\" The source keeps its copies. Point the property at the new source, then run again with --delete-source.\"));\n }\n }\n if (failures.length > 0 || leftBehind.length > 0) process.exitCode = 1;\n}\n\n/**\n * Every file under the moved folder the move did not move, read by the\n * backend's `/move/verify` — or `undefined` from a backend without it.\n */\nasync function listLeftBehind(\n backend: Backend,\n request: { from?: string; to?: string; prefix?: string; deleteSource: boolean },\n quiet: boolean\n): Promise<{ key: string; reason: string }[] | undefined> {\n const notMoved: { key: string; reason: string }[] = [];\n let cursor: string | undefined;\n let checked = 0;\n do {\n let page: { checked: number; notMoved: { key: string; reason: string }[]; cursor?: string };\n try {\n page = await backend.request(\"POST\", \"/move/verify\", { ...request, ...(cursor ? { cursor } : {}), limit: 500 });\n } catch (error: unknown) {\n if (error instanceof RebaseApiError && error.status === 404 && error.code !== \"UNKNOWN_STORAGE_SOURCE\") return undefined;\n fail(\"Failed to list the source again after the move\", error, backend.baseUrl);\n }\n checked += page.checked;\n notMoved.push(...page.notMoved);\n if (!quiet && process.stdout.isTTY) {\n process.stdout.write(`\\r Checking the source again: ${checked} file(s) listed…`);\n }\n cursor = page.cursor;\n } while (cursor);\n return notMoved;\n}\n\nexport async function storageCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printStorageHelp();\n return;\n }\n switch (subcommand) {\n case \"orphans\":\n await orphans(rawArgs);\n break;\n case \"move\":\n await move(rawArgs);\n break;\n default:\n unknownCommand(subcommand, STORAGE_SUBCOMMANDS, \"storage\");\n }\n}\n\nfunction printStorageHelp(): void {\n console.log(`\n${chalk.bold(\"rebase storage\")} — Maintain stored files, through the running backend\n\n${chalk.green.bold(\"Usage\")}\n rebase storage ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.blue.bold(\"orphans\")} List the stored files no row names\n ${chalk.blue.bold(\"move\")} Copy a folder of files to another storage source, same keys\n\n${chalk.green.bold(\"orphans Options\")}\n ${chalk.blue(\"--source\")} Storage source key ${chalk.gray(\"(default: the default source)\")}\n ${chalk.blue(\"--older-than\")} Hours a file must be old to count ${chalk.gray(\"(default: 24)\")}\n ${chalk.blue(\"--delete\")} Delete them, after asking\n ${chalk.blue(\"--yes, -y\")} Do not ask ${chalk.gray(\"(required with --delete when there is no terminal)\")}\n ${chalk.blue(\"--json\")} Print the report as JSON\n\n${chalk.green.bold(\"move Options\")}\n ${chalk.blue(\"--from\")} Source to copy from ${chalk.gray(\"(default: the default source)\")}\n ${chalk.blue(\"--to\")} Source to copy to ${chalk.gray(\"(default: the default source)\")}\n ${chalk.blue(\"--prefix\")} Folder to copy ${chalk.gray(\"(default: everything)\")}\n ${chalk.blue(\"--delete-source\")} Delete each file from the source once the target holds it\n ${chalk.blue(\"--json\")} Print the counts as JSON\n\n${chalk.green.bold(\"Notes\")}\n A file is unused when no string in any row of any table names it —\n a key, a URL, a ${chalk.blue(\"rebase-storage:\")} reference in text — whatever column\n or source holds it. Files newer than ${chalk.blue(\"--older-than\")} are left out: the admin\n panel uploads a file before the row that names it is saved. Files named only\n by tables backend/schema does not declare are not seen: check before deleting.\n\n The scan runs on the backend in the background — a ${chalk.blue(\"storage.orphans\")} job\n on the job queue, or inside the server process when there is none — and the\n CLI shows its progress until it is done. ${chalk.blue(\"--delete\")} deletes from that scan\n only; the backend reads every row again and asks for each file again first.\n\n Both read ${chalk.blue(\"REBASE_SERVICE_KEY\")} from .env and need the backend running.\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoBA,IAAa,sBAAsB,CAAC,WAAW,MAAM;;AAGrD,IAAa,gBAAgB;CACzB,YAAY;CACZ,gBAAgB;CAChB,YAAY;CACZ,SAAS;CACT,MAAM;CACN,UAAU;AACd;;AAGA,IAAa,aAAa;CACtB,UAAU;CACV,QAAQ;CACR,YAAY;CACZ,mBAAmB;CACnB,UAAU;AACd;;AA+CA,IAAa,oBAAoB,EAAE,YAAY,IAAM;;AAerD,SAAS,UAAmB;CACxB,MAAM,cAAc,mBAAmB;CACvC,MAAM,MAAM,YAAY,WAAW;CACnC,MAAM,aAAa,IAAI,eAAe,IAAI;CAC1C,IAAI,CAAC,YAAY;EACb,QAAQ,MAAM,MAAM,IAAI,4EAA4E,CAAC;EACrG,QAAQ,KAAK,CAAC;CAClB;CAGA,MAAM,UAAU,kBAAkB,KAAK,WAAW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EAAE;;EAEzC,MAAM,MAAM,KAAK,UAAU,EAAE;IAC3B,MAAM,KAAK,KAAK,SAAS,EAAE;IAC3B,MAAM,KAAK,KAAK,MAAM,EAAE;;EAE1B,MAAM,MAAM,KAAK,iBAAiB,EAAE;IAClC,MAAM,KAAK,UAAU,EAAE,+BAA+B,MAAM,KAAK,+BAA+B,EAAE;IAClG,MAAM,KAAK,cAAc,EAAE,0CAA0C,MAAM,KAAK,eAAe,EAAE;IACjG,MAAM,KAAK,UAAU,EAAE;IACvB,MAAM,KAAK,WAAW,EAAE,sBAAsB,MAAM,KAAK,oDAAoD,EAAE;IAC/G,MAAM,KAAK,QAAQ,EAAE;;EAEvB,MAAM,MAAM,KAAK,cAAc,EAAE;IAC/B,MAAM,KAAK,QAAQ,EAAE,kCAAkC,MAAM,KAAK,+BAA+B,EAAE;IACnG,MAAM,KAAK,MAAM,EAAE,kCAAkC,MAAM,KAAK,+BAA+B,EAAE;IACjG,MAAM,KAAK,UAAU,EAAE,2BAA2B,MAAM,KAAK,uBAAuB,EAAE;IACtF,MAAM,KAAK,iBAAiB,EAAE;IAC9B,MAAM,KAAK,QAAQ,EAAE;;EAEvB,MAAM,MAAM,KAAK,OAAO,EAAE;;oBAER,MAAM,KAAK,iBAAiB,EAAE;yCACT,MAAM,KAAK,cAAc,EAAE;;;;uDAIb,MAAM,KAAK,iBAAiB,EAAE;;6CAExC,MAAM,KAAK,UAAU,EAAE;;;cAGtD,MAAM,KAAK,oBAAoB,EAAE;CAC9C;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"verify-DkJqhYPI.js","names":[],"sources":["../src/commands/verify-cms.ts","../src/commands/verify.ts"],"sourcesContent":["/**\n * `rebase verify`, step \"CMS customizations\": the project's\n * `customizeTable(...)` calls held to the tables they customize.\n *\n * The panel applies a customization at runtime and, for a slug or a field the\n * tables do not have, only warns in the browser console in development\n * (`applyTableCustomizations`). An agent that misspells a slug, keeps a field\n * after renaming its column, or hides a required column from the form ships a\n * panel that silently ignores the edit — or one that cannot create a record.\n * The post-edit hook runs `rebase verify` after edits under `frontend/src/cms`,\n * so this step is what answers for those files.\n *\n * **Read statically.** A customization module imports `@rebasepro/cms` (React,\n * the browser panel) and the project's own components, so it cannot be\n * imported in Node without the frontend's toolchain. The calls are read with\n * ts-morph instead: the slug, the keys of `fields`, and the literal values of\n * the form options of each field. What a static read cannot see — a slug or\n * options computed at runtime, a spread, a computed key, a `dynamicProps` /\n * `conditions` that hides a field on some records, a global `beforeSave` hook\n * in `backend/hooks.ts` that fills a column — is either reported as not read\n * (`cms-not-static`) or not judged; it is never reported as a problem.\n *\n * Checks (stable ids):\n *\n * - `cms-unknown-table` — `customizeTable(\"x\")` for a slug no table declares.\n * - `cms-unknown-field` — a `fields` key that is neither a column key nor a\n * relation of that table.\n * - `cms-hidden-required` — a field kept off the form (`hiddenInForm`,\n * `readOnly`, `disabled`) whose column is `NOT NULL` with no default, that\n * neither the database nor the server fills, and that the customization does\n * not mark `filledByServer`: no record can be created from the panel. A\n * warning instead of an error when the table declares a `beforeSave` hook\n * (or the column a `beforeSave` transform), which may be what fills it.\n * - `cms-duplicate-customization` — two `customizeTable` calls for one slug.\n * The panel refuses to mount with both.\n * - `cms-not-static` — a call this step could not read (warning).\n * - `cms-ui-config-not-mounted` — `src/cms/ui-config.json` exists, where the\n * collection editor saves presentation in development, but no `<RebaseCMS>`\n * in the frontend passes `uiConfig`: the editor's changes are lost on\n * reload and never ship (warning). Said only when a `<RebaseCMS>` element\n * was found and none of them passes `uiConfig` or spreads props into it.\n * - `cms-backend-guard-missing` — the project has `backend/` and a frontend\n * whose Vite config does not use `rebaseBackendGuard()`: nothing refuses a\n * value import of a table, which would ship its server hooks to every\n * visitor (`utils/backend-guard.ts`). Quiet when the config imports a local\n * module that may add it, and checked whether or not `src/cms` exists.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport type { ColumnDescriptor, TableDescriptor } from \"@rebasepro/types\";\nimport type { Expression, Node, ObjectLiteralExpression, Project, SourceFile } from \"ts-morph\";\nimport { cmsDirectories } from \"../utils/cms-directories\";\nimport { BACKEND_GUARD_FIX, backendGuardMissingMessage, backendGuardStates } from \"../utils/backend-guard\";\n\ntype TsMorph = typeof import(\"ts-morph\");\n\n/** The package `customizeTable` is imported from. */\nconst CMS_PACKAGE = \"@rebasepro/cms\";\nconst CUSTOMIZE = \"customizeTable\";\n/** The panel's mount, and the file the collection editor writes presentation to in development. */\nconst MOUNT = \"RebaseCMS\";\nconst UI_CONFIG_FILE = \"ui-config.json\";\nconst SOURCE = /\\.(ts|tsx|mts|js|jsx|mjs)$/;\nconst NOT_SOURCE = /\\.(d|test|spec)\\.[cm]?[jt]sx?$/;\n\n/** The form options that keep a field from being edited on the form. */\nconst OFF_FORM_OPTIONS = [\"hiddenInForm\", \"readOnly\", \"disabled\"] as const;\ntype OffFormOption = typeof OFF_FORM_OPTIONS[number];\n\n/** A finding of this step, in `rebase verify`'s finding shape (step `cms`). */\nexport interface CmsFinding {\n check: \"cms-unknown-table\" | \"cms-unknown-field\" | \"cms-hidden-required\" | \"cms-duplicate-customization\" | \"cms-not-static\" | \"cms-ui-config-not-mounted\" | \"cms-backend-guard-missing\";\n severity: \"error\" | \"warning\";\n message: string;\n fix?: string;\n table?: string;\n /** Relative to the project root. */\n file: string;\n line: number;\n /** `customizeTable(\"posts\").fields.title`. */\n path?: string;\n}\n\n/** What the step read and found. */\nexport interface CmsCheckResult {\n /** The customization directories read, relative to the project root. Empty: nothing to check. */\n directories: string[];\n /** How many `customizeTable` calls were found. */\n customizations: number;\n findings: CmsFinding[];\n}\n\n/** One field of a customization, as far as a static read says. */\ninterface FieldRead {\n key: string;\n line: number;\n /** The off-form options written as `true` (an object for `disabled` counts). */\n offForm: OffFormOption[];\n /** `filledByServer` as written: true or false, `undefined` when not stated, `\"unknown\"` when not a literal. */\n filledByServer: boolean | undefined | \"unknown\";\n /** A spread in the field's options: what it carries is not known. */\n opaque: boolean;\n}\n\n/** One `customizeTable(...)` call, as far as a static read says. */\ninterface CustomizationRead {\n slug: string;\n file: string;\n line: number;\n fields: FieldRead[];\n /** What could not be read in it. */\n unread: string[];\n}\n\nfunction sourceFiles(dir: string): string[] {\n const out: string[] = [];\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) out.push(...sourceFiles(full));\n else if (SOURCE.test(entry.name) && !NOT_SOURCE.test(entry.name)) out.push(full);\n }\n return out.sort();\n}\n\n// ─── The static read ──────────────────────────────────────────────────────────\n\nclass Reader {\n constructor(private readonly tsm: TsMorph) {}\n\n private unwrap(node: Node): Node {\n const N = this.tsm.Node;\n let current = node;\n while (N.isAsExpression(current) || N.isSatisfiesExpression(current) || N.isParenthesizedExpression(current) ||\n N.isNonNullExpression(current) || N.isTypeAssertion(current)) {\n current = current.getExpression();\n }\n return current;\n }\n\n /** The initializer of the top-level `const` an identifier names, in its own file. */\n private constOf(node: Node): Expression | undefined {\n const N = this.tsm.Node;\n if (!N.isIdentifier(node)) return undefined;\n const declaration = node.getSourceFile().getVariableDeclaration(node.getText());\n const statement = declaration?.getVariableStatement();\n if (!declaration || !statement || !N.isSourceFile(statement.getParent())) return undefined;\n if (statement.getDeclarationKind() !== this.tsm.VariableDeclarationKind.Const) return undefined;\n return declaration.getInitializer();\n }\n\n /** A string a node denotes: a literal, or a same-file `const` holding one. */\n string(node: Node | undefined, depth = 0): string | undefined {\n if (!node || depth > 4) return undefined;\n const N = this.tsm.Node;\n const current = this.unwrap(node);\n if (N.isStringLiteral(current) || N.isNoSubstitutionTemplateLiteral(current)) return current.getLiteralValue();\n const initializer = this.constOf(current);\n return initializer ? this.string(initializer, depth + 1) : undefined;\n }\n\n /** The object literal a node denotes: itself, or a same-file `const` holding one. */\n object(node: Node | undefined, depth = 0): ObjectLiteralExpression | undefined {\n if (!node || depth > 4) return undefined;\n const N = this.tsm.Node;\n const current = this.unwrap(node);\n if (N.isObjectLiteralExpression(current)) return current;\n const initializer = this.constOf(current);\n return initializer ? this.object(initializer, depth + 1) : undefined;\n }\n\n /** A property's name as written, or undefined for a computed one. */\n name(member: Node): string | undefined {\n const N = this.tsm.Node;\n if (!N.isPropertyAssignment(member) && !N.isShorthandPropertyAssignment(member) && !N.isMethodDeclaration(member)) return undefined;\n const nameNode = member.getNameNode();\n if (N.isIdentifier(nameNode)) return nameNode.getText();\n if (N.isStringLiteral(nameNode) || N.isNoSubstitutionTemplateLiteral(nameNode)) return nameNode.getLiteralValue();\n if (N.isNumericLiteral(nameNode)) return String(nameNode.getLiteralValue());\n if (N.isComputedPropertyName(nameNode)) return this.string(nameNode.getExpression());\n return undefined;\n }\n\n /** The value of a member: an assignment's initializer, a shorthand's identifier. */\n value(member: Node): Node | undefined {\n const N = this.tsm.Node;\n if (N.isPropertyAssignment(member)) return member.getInitializer();\n if (N.isShorthandPropertyAssignment(member)) return member.getNameNode();\n return undefined;\n }\n\n /** `true` / `false` as written, an object literal as `true` (for `disabled: { … }`), else unknown. */\n flag(node: Node | undefined, objectIsTrue: boolean): boolean | \"unknown\" {\n if (!node) return \"unknown\";\n const N = this.tsm.Node;\n const { SyntaxKind } = this.tsm;\n const current = this.unwrap(node);\n if (current.getKind() === SyntaxKind.TrueKeyword) return true;\n if (current.getKind() === SyntaxKind.FalseKeyword) return false;\n if (objectIsTrue && N.isObjectLiteralExpression(current)) return true;\n return \"unknown\";\n }\n\n /** The local names `customizeTable` is bound to, and namespaces of the CMS package. */\n private bindings(sf: SourceFile): { names: Set<string>; namespaces: Set<string> } {\n const names = new Set<string>();\n const namespaces = new Set<string>();\n for (const declaration of sf.getImportDeclarations()) {\n if (declaration.getModuleSpecifierValue() !== CMS_PACKAGE || declaration.isTypeOnly()) continue;\n const namespace = declaration.getNamespaceImport();\n if (namespace) namespaces.add(namespace.getText());\n for (const named of declaration.getNamedImports()) {\n if (named.getName() === CUSTOMIZE && !named.isTypeOnly()) names.add(named.getAliasNode()?.getText() ?? CUSTOMIZE);\n }\n }\n return { names, namespaces };\n }\n\n field(key: string, member: Node): FieldRead {\n const N = this.tsm.Node;\n const read: FieldRead = { key, line: member.getStartLineNumber(), offForm: [], filledByServer: undefined, opaque: false };\n const options = this.object(this.value(member));\n if (!options) {\n read.opaque = true;\n return read;\n }\n for (const property of options.getProperties()) {\n if (N.isSpreadAssignment(property)) {\n read.opaque = true;\n continue;\n }\n const name = this.name(property);\n if (name === undefined) {\n read.opaque = true;\n continue;\n }\n const value = this.value(property);\n if (name === \"filledByServer\") read.filledByServer = this.flag(value, false);\n const option = OFF_FORM_OPTIONS.find(candidate => candidate === name);\n if (option && this.flag(value, option === \"disabled\") === true) read.offForm.push(option);\n }\n return read;\n }\n\n /** Every `customizeTable(...)` call in a file, read as far as the source says. */\n customizations(sf: SourceFile, relativeFile: string): CustomizationRead[] {\n const N = this.tsm.Node;\n const { SyntaxKind } = this.tsm;\n const { names, namespaces } = this.bindings(sf);\n if (names.size === 0 && namespaces.size === 0) return [];\n const out: CustomizationRead[] = [];\n for (const call of sf.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n const callee = call.getExpression();\n const isCustomize = (N.isIdentifier(callee) && names.has(callee.getText())) ||\n (N.isPropertyAccessExpression(callee) && callee.getName() === CUSTOMIZE && namespaces.has(callee.getExpression().getText()));\n if (!isCustomize) continue;\n const [slugNode, optionsNode] = call.getArguments();\n const read: CustomizationRead = { slug: \"\", file: relativeFile, line: call.getStartLineNumber(), fields: [], unread: [] };\n const slug = this.string(slugNode);\n if (slug === undefined) {\n read.unread.push(`the slug \\`${slugNode?.getText() ?? \"\"}\\` is not a string literal or a \\`const\\` of one in this file`);\n out.push(read);\n continue;\n }\n read.slug = slug;\n const options = this.object(optionsNode);\n if (!options) {\n read.unread.push(`the options \\`${optionsNode?.getText().split(\"\\n\")[0] ?? \"\"}\\` are not an object literal or a \\`const\\` of one in this file`);\n out.push(read);\n continue;\n }\n let fieldsNode: Node | undefined;\n for (const property of options.getProperties()) {\n if (N.isSpreadAssignment(property)) {\n read.unread.push(`\\`...${property.getExpression().getText()}\\` (line ${property.getStartLineNumber()}) may carry \\`fields\\``);\n continue;\n }\n if (this.name(property) === \"fields\") fieldsNode = this.value(property);\n }\n if (fieldsNode) {\n const fields = this.object(fieldsNode);\n if (!fields) {\n read.unread.push(`\\`fields\\` (line ${fieldsNode.getStartLineNumber()}) is not an object literal or a \\`const\\` of one in this file`);\n } else {\n for (const member of fields.getProperties()) {\n const key = this.name(member);\n if (key === undefined) {\n read.unread.push(`\\`${member.getText().split(\"\\n\")[0]}\\` (line ${member.getStartLineNumber()}) in \\`fields\\``);\n continue;\n }\n read.fields.push(this.field(key, member));\n }\n }\n }\n out.push(read);\n }\n return out;\n }\n}\n\n// ─── The checks ───────────────────────────────────────────────────────────────\n\n/** Levenshtein distance, for \"did you mean\". */\nfunction distance(a: string, b: string): number {\n const row = Array.from({ length: b.length + 1 }, (_, i) => i);\n for (let i = 1; i <= a.length; i++) {\n let previous = row[0];\n row[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const current = row[j];\n row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1].toLowerCase() === b[j - 1].toLowerCase() ? 0 : 1));\n previous = current;\n }\n }\n return row[b.length];\n}\n\nfunction closest(name: string, candidates: Iterable<string>): string | undefined {\n let best: string | undefined;\n let bestDistance = Math.max(2, Math.floor(name.length / 3)) + 1;\n for (const candidate of candidates) {\n const d = distance(name, candidate);\n if (d < bestDistance) {\n best = candidate;\n bestDistance = d;\n }\n }\n return best;\n}\n\nconst SERIAL_KINDS: ReadonlySet<string> = new Set([\"smallserial\", \"serial\", \"bigserial\"]);\n\n/**\n * Whether a create may leave the column out and still succeed without the\n * server's help from a hook: it is nullable, has a default (literal, SQL,\n * random uuid, identity, the database's), is a serial, is generated, is\n * stamped or read-only (the server writes it), or is the tenant column (the\n * server fills it from the caller).\n */\nfunction fillsItself(table: TableDescriptor, column: ColumnDescriptor): boolean {\n return column.nullable ||\n column.default !== undefined ||\n SERIAL_KINDS.has(column.type.kind) ||\n column.generated !== undefined ||\n column.stamp !== undefined ||\n column.readOnly === true ||\n table.tenant?.field === column.key;\n}\n\n/** The column a field key edits: the column itself, or the foreign key of a `belongsTo` relation. */\nfunction columnOfField(table: TableDescriptor, key: string): ColumnDescriptor | undefined {\n return table.columns.find(column => column.key === key) ??\n table.columns.find(column => column.foreignKeyOf === key);\n}\n\nfunction describeOffForm(options: readonly OffFormOption[]): string {\n return options.map(option => `\\`${option}\\``).join(\" and \");\n}\n\nfunction checkCustomization(read: CustomizationRead, table: TableDescriptor): CmsFinding[] {\n const findings: CmsFinding[] = [];\n const where = `customizeTable(\"${read.slug}\")`;\n const columnKeys = new Set(table.columns.map(column => column.key));\n const relationNames = new Set(table.relations.map(relation => relation.name));\n for (const field of read.fields) {\n const at = { table: table.slug, file: read.file, line: field.line, path: `${where}.fields.${field.key}` };\n if (!columnKeys.has(field.key) && !relationNames.has(field.key)) {\n const bySqlName = table.columns.find(column => column.column === field.key);\n const guess = bySqlName?.key ?? closest(field.key, [...columnKeys, ...relationNames]);\n findings.push({\n check: \"cms-unknown-field\",\n severity: \"error\",\n ...at,\n message: `${where} customizes \\`fields.${field.key}\\`, which is neither a column nor a relation of the \"${table.slug}\" table` +\n (bySqlName ? ` — that is the SQL name of the column whose key is \\`${bySqlName.key}\\`.` : \".\"),\n fix: guess\n ? `Rename the key to \\`${guess}\\`${bySqlName ? \" (fields are keyed by the column's key, as in `columns`)\" : \"\"}, or remove it.`\n : \"Remove it, or key it by one of the table's columns or relations (`columns` / `relations` in its `defineTable`).\"\n });\n continue;\n }\n if (field.offForm.length === 0 || field.filledByServer === true) continue;\n // A spread or a non-literal `filledByServer` may say it: not judged.\n if (field.opaque || field.filledByServer === \"unknown\") continue;\n const column = columnOfField(table, field.key);\n if (!column || fillsItself(table, column)) continue;\n const hooked = table.hooks?.beforeSave === true || column.transforms?.beforeSave === true;\n const what = column.key === field.key ? `the column \\`${column.column}\\`` : `its foreign key \\`${column.column}\\``;\n findings.push({\n check: \"cms-hidden-required\",\n severity: hooked ? \"warning\" : \"error\",\n ...at,\n message: `${where} keeps \\`${field.key}\\` off the form (${describeOffForm(field.offForm)}), but ${what} is NOT NULL with no default ` +\n (hooked\n ? `and only the table's \\`beforeSave\\` hook could fill it: unless it does, creating a record from the panel fails.`\n : `and nothing on the server fills it: creating a \"${table.slug}\" record from the panel always fails.`),\n fix: hooked\n ? `If the hook fills it on create, say so: \\`${field.key}: { …, filledByServer: true }\\`. Otherwise let the form edit it.`\n : `Let the form edit it (drop ${describeOffForm(field.offForm)}), give the column a default in its \\`defineTable\\` (\\`.default(…)\\`), ` +\n `or fill it in a \\`beforeSave\\` hook and mark the field \\`filledByServer: true\\`.`\n });\n }\n return findings;\n}\n\n/**\n * Read every `customizeTable(...)` call under the project's customization\n * directories and hold it to `tables`. Never throws on a file it cannot parse\n * as intended: what it cannot read is a `cms-not-static` warning.\n */\nexport async function checkCmsCustomizations(projectRoot: string, tables: readonly TableDescriptor[]): Promise<CmsCheckResult> {\n const directories = cmsDirectories(projectRoot);\n const result: CmsCheckResult = { directories: directories.map(dir => path.relative(projectRoot, dir)), customizations: 0, findings: [] };\n result.findings.push(...await backendGuardFindings(projectRoot));\n if (directories.length === 0) return result;\n\n const tsm: TsMorph = await import(\"ts-morph\");\n const project = new tsm.Project({\n useInMemoryFileSystem: true,\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true, jsx: tsm.ts.JsxEmit.Preserve, noLib: true }\n });\n const reader = new Reader(tsm);\n const bySlug = new Map(tables.map(table => [table.slug, table]));\n const first = new Map<string, CustomizationRead>();\n\n for (const dir of directories) {\n for (const file of sourceFiles(dir)) {\n const text = fs.readFileSync(file, \"utf-8\");\n if (!text.includes(CUSTOMIZE)) continue;\n const relativeFile = path.relative(projectRoot, file);\n const sf = project.createSourceFile(file, text, { overwrite: true });\n for (const read of reader.customizations(sf, relativeFile)) {\n result.customizations++;\n const label = read.slug ? `customizeTable(\"${read.slug}\")` : \"customizeTable(…)\";\n if (read.unread.length > 0) {\n result.findings.push({\n check: \"cms-not-static\",\n severity: \"warning\",\n file: read.file,\n line: read.line,\n ...(read.slug && { table: read.slug, path: label }),\n message: `${label} was not fully checked: ${read.unread.join(\"; \")}. ` +\n \"`rebase verify` reads customizations without running them, so only literals in the call are checked.\",\n fix: \"Write the slug and the `fields` object as literals in the call (a `const` in the same file also works), or ignore this warning.\"\n });\n }\n if (!read.slug) continue;\n const earlier = first.get(read.slug);\n if (earlier) {\n result.findings.push({\n check: \"cms-duplicate-customization\",\n severity: \"error\",\n table: read.slug,\n file: read.file,\n line: read.line,\n path: label,\n message: `${label} is written twice: here and in ${earlier.file}:${earlier.line}. The panel refuses to start with both.`,\n fix: \"Merge them into one `customizeTable` call and remove the other.\"\n });\n continue;\n }\n first.set(read.slug, read);\n const table = bySlug.get(read.slug);\n if (!table) {\n const guess = closest(read.slug, bySlug.keys());\n result.findings.push({\n check: \"cms-unknown-table\",\n severity: \"error\",\n table: read.slug,\n file: read.file,\n line: read.line,\n path: label,\n message: `${label} customizes \"${read.slug}\", which no table in the schema declares as its slug. The panel ignores it.`,\n fix: guess\n ? `Did you mean \"${guess}\"? The first argument is the table's slug (its \\`defineTable\\` name, unless it sets \\`slug\\`).`\n : \"Pass the slug of a table the schema index exports (its `defineTable` name, unless it sets `slug`), or remove the customization.\"\n });\n continue;\n }\n result.findings.push(...checkCustomization(read, table));\n }\n project.removeSourceFile(sf);\n }\n const unmounted = uiConfigNotMounted(tsm, project, projectRoot, dir);\n if (unmounted) result.findings.push(unmounted);\n }\n return result;\n}\n\n/**\n * The `cms-ui-config-not-mounted` finding for one customization directory, or\n * nothing. Undecided — no `<RebaseCMS>` element found under `src/` (mounted\n * through a wrapper, rendered without JSX) — is nothing, not a warning.\n */\nfunction uiConfigNotMounted(tsm: TsMorph, project: Project, projectRoot: string, cmsDir: string): CmsFinding | undefined {\n const uiConfig = path.join(cmsDir, UI_CONFIG_FILE);\n if (!fs.existsSync(uiConfig)) return undefined;\n const N = tsm.Node;\n const { SyntaxKind } = tsm;\n const mounts: { file: string; line: number; passes: boolean }[] = [];\n for (const file of sourceFiles(path.dirname(cmsDir))) {\n const text = fs.readFileSync(file, \"utf-8\");\n if (!text.includes(MOUNT)) continue;\n const sf = project.createSourceFile(file, text, { overwrite: true });\n const names = new Set<string>();\n for (const declaration of sf.getImportDeclarations()) {\n if (declaration.getModuleSpecifierValue() !== CMS_PACKAGE) continue;\n for (const named of declaration.getNamedImports()) {\n if (named.getName() === MOUNT) names.add(named.getAliasNode()?.getText() ?? MOUNT);\n }\n }\n const elements = [\n ...sf.getDescendantsOfKind(SyntaxKind.JsxOpeningElement),\n ...sf.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement)\n ];\n for (const element of elements) {\n if (!names.has(element.getTagNameNode().getText())) continue;\n const passes = element.getAttributes().some(attribute =>\n N.isJsxSpreadAttribute(attribute) || attribute.getNameNode().getText() === \"uiConfig\");\n mounts.push({ file: path.relative(projectRoot, file), line: element.getStartLineNumber(), passes });\n }\n project.removeSourceFile(sf);\n }\n if (mounts.length === 0 || mounts.some(mount => mount.passes)) return undefined;\n const [first] = mounts;\n return {\n check: \"cms-ui-config-not-mounted\",\n severity: \"warning\",\n file: first.file,\n line: first.line,\n message: `${path.relative(projectRoot, uiConfig)} holds what the collection editor saves in development, but \\`<RebaseCMS>\\` is not given it: ` +\n \"presentation edited in the editor is gone after a reload and never ships.\",\n fix: `Import it and pass it: \\`import uiConfig from \"./cms/${UI_CONFIG_FILE}\";\\` and \\`<RebaseCMS … uiConfig={uiConfig} />\\` ` +\n \"(the frontend's tsconfig needs `resolveJsonModule`).\"\n };\n}\n\n/**\n * `cms-backend-guard-missing`, one per frontend whose Vite config does not use\n * the guard. Nothing for a frontend the static read cannot decide.\n */\nasync function backendGuardFindings(projectRoot: string): Promise<CmsFinding[]> {\n return (await backendGuardStates(projectRoot))\n .filter(state => state.state === \"missing\")\n .map(state => ({\n check: \"cms-backend-guard-missing\",\n severity: \"error\",\n file: state.viteConfig,\n line: state.line,\n message: backendGuardMissingMessage(state),\n fix: BACKEND_GUARD_FIX\n }));\n}\n","/**\n * CLI command: rebase verify\n *\n * One command that says whether the tables are safe to ship, fast enough to\n * run after every edit. An agent editing `backend/schema/*.ts` gets a table\n * definition wrong — a relation to a table the index does not export, an\n * `rls: \"inherit\"` with no `defaultRls`, a table with no primary key — or\n * writes rules that hand every row of a per-user table to everyone; each of\n * those used to surface late: at boot, in review, or never. The project's\n * Claude Code hook (written by `rebase init` and `rebase skills --hooks`) runs\n * this after each edit to a schema file, and CI runs it on every push.\n *\n * Five steps, each reported on its own:\n *\n * 1. **Table definitions** — `backend/schema` loads and compiles through\n * `loadBackendSchema`, the loader the backend boots from, so every problem\n * it would refuse to boot on is a finding here, one per problem.\n * 2. **RLS coverage** — a table with a `user_id` / `owner_id` /\n * `organization_id` / `tenant_id` column whose rules (its own, or the\n * `defaultRls` it inherits) let a role read every row regardless of it.\n * `rls` itself is mandatory, so \"no rules at all\" is a step-1 error now.\n * 3. **CMS customizations** — every `customizeTable(...)` under\n * `frontend/src/cms`, read statically (`verify-cms.ts`): a slug no table\n * declares, a field that is not a column or relation of its table, a\n * required column kept off the form, one table customized twice. A\n * project without `frontend/src/cms` (headless) skips it.\n * 4. **Migration freshness** — whether `drizzle/migrations` still builds the\n * tables and columns the schema declares (offline), and with `--live`\n * whether the database has applied every migration.\n * 5. **Live RLS audit** — with `--live`, the `@rebasepro/rls-check` catalogue\n * against the project's database, resolved as `db *` resolves it (the\n * managed one unless something names another).\n *\n * `--json` prints one object an agent can act on: every finding carries the\n * file, the dotted path into the table and the fix.\n */\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport {\n parseEnvBoolean,\n type SecurityRule,\n type TableDescriptor\n} from \"@rebasepro/types\";\nimport { isSchemaDefinitionError } from \"@rebasepro/common\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { failAsJson, findBackendDir, getActiveBackendPlugin, readEnvFile, requireProjectRoot } from \"../utils/project\";\nimport { SCHEMA_DIR_FLAG_HELP, missingSchemaDir, refuseRemovedCollectionsFlag } from \"../utils/path-flags\";\nimport { resolveSchemaDir } from \"../utils/schema-dir\";\nimport { loadProjectSchema, type ModuleAliases, type ProjectSchema } from \"../utils/project-schema\";\nimport { checkCmsCustomizations } from \"./verify-cms\";\n\n/** The flags `rebase verify` takes. */\nexport const VERIFY_FLAGS = {\n \"--schema-dir\": String,\n \"--json\": Boolean,\n \"--quiet\": Boolean,\n \"-q\": \"--quiet\",\n \"--live\": Boolean,\n \"--database-url\": String,\n \"--docker\": Boolean\n} as const;\n\nconst VERIFY_FLAG_HELP: Record<string, string> = {\n \"--schema-dir\": SCHEMA_DIR_FLAG_HELP,\n \"--json\": \"Print one JSON object: every step, and every finding with its file, path and fix\",\n \"--quiet, -q\": \"Print nothing when everything passes; only the problems when something fails\",\n \"--live\": \"Also connect to the project's database: check migrations are applied and run the rls-check audit\",\n \"--database-url\": \"With --live: audit this database instead of the project's\",\n \"--docker\": \"With --live: use the database from docker compose, starting it if needed\"\n};\n\nexport type VerifyStepId = \"schema\" | \"rls\" | \"cms\" | \"migrations\" | \"live\";\n\nexport interface VerifyFinding {\n step: VerifyStepId;\n /** Stable, kebab-case: what kind of problem. An agent can branch on it. */\n check: string;\n severity: \"error\" | \"warning\";\n message: string;\n /** What to change, when there is one thing to change. */\n fix?: string;\n /** The table's slug. */\n table?: string;\n /** The file to open, relative to the project root. */\n file?: string;\n /** The line in {@link file}, when the finding points at one. */\n line?: number;\n /** Dotted path into the table definition — `posts.rls[0]`, `posts.author`. */\n path?: string;\n}\n\nexport interface VerifyStep {\n id: VerifyStepId;\n title: string;\n status: \"passed\" | \"failed\" | \"warnings\" | \"skipped\";\n /** Why a step was skipped, or what it covered. */\n detail?: string;\n}\n\nexport interface VerifyReport {\n ok: boolean;\n /** The schema directory, relative to the project root. */\n schemaDir: string;\n steps: VerifyStep[];\n findings: VerifyFinding[];\n summary: { errors: number; warnings: number };\n}\n\nexport interface VerifyOptions {\n projectRoot: string;\n /** The schema directory, absolute. */\n schemaDir: string;\n /** The backend package, where `drizzle/migrations` lives. Null for a project without one. */\n backendDir: string | null;\n live: boolean;\n databaseUrl?: string;\n /** Why no `databaseUrl` could be resolved for `--live`, when resolving it failed. */\n databaseUnavailable?: string;\n /**\n * Whether the backend refuses a request with no token (`AUTH_REQUIRE`, on\n * unless set to `false`). Decides how a Rebase-compiled public read reads.\n * Defaults to true, the runtime's default.\n */\n authRequired?: boolean;\n /** Module specifiers mapped to files when importing the schema (in-repo runs and tests). */\n moduleAliases?: ModuleAliases;\n}\n\nconst STEP_TITLES: Record<VerifyStepId, string> = {\n schema: \"Table definitions\",\n rls: \"RLS coverage\",\n cms: \"CMS customizations\",\n migrations: \"Migration freshness\",\n live: \"Live RLS audit\"\n};\n\n/**\n * Columns that say \"this row belongs to someone\". A table carrying one and\n * served without a row filter is the classic multi-tenant leak.\n */\nconst OWNER_COLUMNS: readonly string[] = [\"user_id\", \"owner_id\", \"organization_id\", \"tenant_id\"];\n\nconst MODULE_EXTENSIONS = [\".ts\", \".mts\", \".js\", \".mjs\"] as const;\n\n// ─── Step 1: table definitions ────────────────────────────────────────────────\n\n/** The schema as far as the later steps need it: the compiled tables, and where each one is written. */\ninterface VerifiedSchema {\n schema: ProjectSchema;\n descriptors: TableDescriptor[];\n /** The file each table is written in, by slug, relative to the project root. */\n files: Map<string, string>;\n}\n\n/**\n * Where a table is written, as far as the files say without running them:\n * the conventional `<schema>/<name>.ts` (or its slug, or its SQL name), else\n * the index that exports it.\n */\nfunction tableFile(projectRoot: string, schemaDir: string, indexFile: string, names: readonly string[]): string | undefined {\n for (const name of names) {\n for (const extension of MODULE_EXTENSIONS) {\n const candidate = path.join(schemaDir, `${name}${extension}`);\n if (fs.existsSync(candidate)) return path.relative(projectRoot, candidate);\n }\n }\n return indexFile ? path.relative(projectRoot, indexFile) : undefined;\n}\n\n/**\n * Load the schema the way the backend boots from it. A schema that does not\n * load or does not compile is a set of findings, not a crash — after an\n * agent's edit it is the most likely problem of all.\n */\nasync function loadSchema(\n options: VerifyOptions\n): Promise<{ verified: VerifiedSchema; failures: [] } | { verified: null; failures: VerifyFinding[] }> {\n const relative = (file: string) => path.relative(options.projectRoot, file);\n const indexOf = (): string => MODULE_EXTENSIONS\n .map(extension => path.join(options.schemaDir, `index${extension}`))\n .find(candidate => fs.existsSync(candidate)) ?? \"\";\n try {\n const schema = await loadProjectSchema(options.projectRoot, options.schemaDir, options.moduleAliases);\n const descriptors = schema.compiled.descriptors;\n const files = new Map<string, string>();\n for (const descriptor of descriptors) {\n const file = tableFile(options.projectRoot, options.schemaDir, schema.loaded.indexFile,\n [descriptor.name, descriptor.slug, descriptor.table]);\n if (file) files.set(descriptor.slug, file);\n }\n return { verified: { schema, descriptors, files }, failures: [] };\n } catch (error) {\n if (isSchemaDefinitionError(error)) {\n const index = indexOf();\n return {\n verified: null,\n failures: error.problems.map((problem): VerifyFinding => {\n const file = tableFile(options.projectRoot, options.schemaDir, index, [problem.table]);\n return {\n step: \"schema\",\n check: \"schema-definition\",\n severity: \"error\",\n table: problem.table,\n ...(file && { file }),\n path: problem.key ? `${problem.table}.${problem.key}` : problem.table,\n message: problem.message,\n fix: \"Change the definition as the message says. The backend refuses to boot on the same schema.\"\n };\n })\n };\n }\n const file = typeof error === \"object\" && error !== null && \"file\" in error && typeof error.file === \"string\"\n ? relative(error.file)\n : undefined;\n return {\n verified: null,\n failures: [{\n step: \"schema\",\n check: \"schema-load\",\n severity: \"error\",\n ...(file && { file }),\n message: error instanceof Error ? error.message : String(error),\n fix: \"Fix the module as the message says. The backend refuses to boot on the same files.\"\n }]\n };\n }\n}\n\n// ─── Step 2: RLS coverage ─────────────────────────────────────────────────────\n\n/** Whether a rule applies to reads. */\nfunction coversSelect(rule: SecurityRule): boolean {\n const operations = rule.operations ?? [rule.operation ?? \"all\"];\n return operations.includes(\"select\") || operations.includes(\"all\");\n}\n\n/**\n * A permissive read rule with no row filter: every row, to everyone the rule\n * names. `access: \"public\"` is the same thing said on purpose, so it is not\n * this; `roles: [\"admin\"]` restates the default admin read and adds nothing.\n */\nfunction isUnfilteredRead(rule: SecurityRule): boolean {\n if (!coversSelect(rule) || rule.mode === \"restrictive\") return false;\n if (rule.access === \"public\" || rule.ownerField || rule.condition) return false;\n if (rule.using !== undefined && !/^\\s*\\(?\\s*true\\s*\\)?\\s*$/i.test(rule.using)) return false;\n // A write-only check (`withCheck` with no `using`) filters nothing on read,\n // and it is not a read rule either.\n if (rule.using === undefined && rule.withCheck !== undefined) return false;\n const roles = rule.roles ?? [];\n return !(roles.length > 0 && roles.every(role => role === \"admin\"));\n}\n\n/** A read rule that returns every row to someone: an unfiltered one, or `access: \"public\"`. */\nfunction opensEveryRow(rule: SecurityRule): boolean {\n return isUnfilteredRead(rule) || (rule.access === \"public\" && coversSelect(rule) && rule.mode !== \"restrictive\");\n}\n\nfunction describeRuleTarget(rule: Pick<SecurityRule, \"roles\">): string {\n return rule.roles?.length ? `role${rule.roles.length > 1 ? \"s\" : \"\"} ${rule.roles.map(r => `\"${r}\"`).join(\", \")}` : \"every signed-in user\";\n}\n\nfunction checkRls(verified: VerifiedSchema): VerifyFinding[] {\n const findings: VerifyFinding[] = [];\n const defaultsFile = verified.schema.loaded.indexFile\n ? path.basename(verified.schema.loaded.indexFile)\n : \"the schema index\";\n for (const table of verified.descriptors) {\n // A view takes the policies of the tables it reads; the auth table gets\n // a self-read policy and an admin-only write gate from the framework.\n if (table.kind !== \"table\" || table.auth) continue;\n // `\"admin-only\"`, declared or inherited, is a posture said on purpose.\n if (table.rls.posture !== \"rules\") continue;\n // A tenant-scoped table is filtered by the tenant policy before any rule.\n if (table.tenant) continue;\n\n const owner = table.columns.find(column => OWNER_COLUMNS.includes(column.column));\n if (!owner) continue;\n\n const slug = table.slug;\n const file = verified.files.get(slug);\n const ownerField = owner.column;\n const perUser = ownerField === \"user_id\" || ownerField === \"owner_id\";\n const fix = perUser\n ? `Give it rules of its own: \\`rls: [{ operation: \"all\", ownerField: \"${ownerField}\" }]\\` so each user reaches only their own rows. ` +\n \"A table meant to be readable by everyone says so on the table: `{ operation: \\\"select\\\", access: \\\"public\\\" }`.\"\n : `Scope it with \\`tenant: { field: \"${owner.key}\", from: { claim: \"${ownerField}\" } }\\` (the claim that carries the caller's tenant), ` +\n \"plus the `rls` rules that grant access inside a tenant — e.g. `[{ operation: \\\"select\\\", access: \\\"public\\\" }]`.\";\n\n if (table.rls.inherited) {\n const opening = table.rls.rules.find(opensEveryRow);\n if (!opening) continue;\n // `defaultRls` is written for every table. On a tenant column,\n // inheriting an all-rows read is the cross-tenant leak; on a per-user\n // column it is often a public profile or author list, so it is said,\n // not failed.\n findings.push({\n step: \"rls\",\n check: perUser ? \"rls-inherited-read\" : \"rls-inherited-tenant-read\",\n severity: perUser ? \"warning\" : \"error\",\n table: slug,\n ...(file && { file }),\n path: `${slug}.rls`,\n message: `\"${slug}\" has a \\`${ownerField}\\` column and \\`rls: \"inherit\"\\`, so it takes \\`defaultRls\\` from ${defaultsFile}, ` +\n `which lets ${describeRuleTarget(opening)} read every row regardless of \\`${ownerField}\\`.`,\n fix\n });\n continue;\n }\n\n table.rls.rules.forEach((rule, index) => {\n if (!isUnfilteredRead(rule)) return;\n findings.push({\n step: \"rls\",\n check: \"rls-unfiltered-read\",\n severity: \"warning\",\n table: slug,\n ...(file && { file }),\n path: `${slug}.rls[${index}]`,\n message: `\"${slug}\" has a \\`${ownerField}\\` column, and rls[${index}] lets ${describeRuleTarget(rule)} read every row of it with no row filter.`,\n fix: `Filter the rule — \\`ownerField: \"${ownerField}\"\\` or a \\`condition\\` — or, if every row really is meant for ${describeRuleTarget(rule)}, keep it and ignore this warning.`\n });\n });\n }\n return findings;\n}\n\n// ─── Step 3: migration freshness ──────────────────────────────────────────────\n\nconst POSTGRES_PLUGIN = \"@rebasepro/server-postgres\";\n\n/** One row of `rebase.atlas_schema_revisions`, as far as \"applied\" needs it. */\nexport interface AppliedRevision {\n version: string;\n /** Atlas's revision type, a bit set: 1 baseline, 2 executed, 4 resolved (`migrate set`). */\n type: number;\n}\n\n/** Atlas's baseline bit in `atlas_schema_revisions.type`. */\nconst REVISION_TYPE_BASELINE = 1;\n\n/**\n * The migration files the database has not run, as Atlas's own `migrate status`\n * counts them.\n *\n * A file is applied when its version has a row, or when it is at or behind the\n * newest *baseline* row: `migrate apply --baseline V` records V alone, and\n * means \"everything up to V is already here\". `rebase db migrate --baseline` is\n * what the CLI prescribes for a booted database, so set membership alone\n * reported the earlier migrations of every baselined database as not applied —\n * and prescribed `rebase db migrate`, which answers \"No migration files to\n * execute\". That run failed forever.\n */\nexport function pendingMigrations(\n files: readonly string[],\n revisions: readonly AppliedRevision[],\n compare: (a: string, b: string) => number,\n versionOf: (file: string) => string\n): string[] {\n const recorded = new Set(revisions.map(row => row.version));\n const baseline = revisions\n .filter(row => (Number(row.type) & REVISION_TYPE_BASELINE) !== 0)\n .map(row => row.version)\n .reduce<string | null>((newest, version) => (newest === null || compare(version, newest) > 0 ? version : newest), null);\n return files.filter((file) => {\n const version = versionOf(file);\n if (recorded.has(version)) return false;\n return baseline === null || compare(version, baseline) > 0;\n });\n}\n\nasync function checkMigrations(\n options: VerifyOptions,\n verified: VerifiedSchema,\n step: VerifyStep\n): Promise<VerifyFinding[]> {\n const skip = (detail: string): VerifyFinding[] => {\n step.status = \"skipped\";\n step.detail = detail;\n return [];\n };\n if (!options.backendDir) return skip(\"no backend/ directory\");\n const plugin = getActiveBackendPlugin(options.backendDir);\n if (plugin !== POSTGRES_PLUGIN) {\n return skip(`migrations are checked for ${POSTGRES_PLUGIN} projects${plugin ? `; this one uses ${plugin}` : \"\"}`);\n }\n const migrationsDir = path.join(options.backendDir, \"drizzle\", \"migrations\");\n const files = fs.existsSync(migrationsDir)\n ? fs.readdirSync(migrationsDir).filter(f => f.endsWith(\".sql\")).sort()\n : [];\n if (files.length === 0) {\n return skip(\"no migrations yet — the schema is applied with `rebase db push`; `rebase db generate` starts versioned migrations\");\n }\n\n const relativeDir = path.relative(options.projectRoot, migrationsDir);\n const { findUnmigratedSchema } = await import(\"@rebasepro/server-postgres\");\n const findings: VerifyFinding[] = [];\n const fix = \"Run `rebase db generate` to write the migration, then `rebase db migrate` to apply it.\";\n\n let changes: ReturnType<typeof findUnmigratedSchema>;\n try {\n changes = findUnmigratedSchema(\n verified.schema.compiled.tables,\n files.map(f => fs.readFileSync(path.join(migrationsDir, f), \"utf-8\"))\n );\n } catch (error) {\n return [{\n step: \"migrations\",\n check: \"migration-plan\",\n severity: \"error\",\n message: `Could not derive the SQL schema from the tables: ${error instanceof Error ? error.message : String(error)}`,\n fix: \"`rebase schema generate` reports the same problem with more context.\"\n }];\n }\n\n for (const change of changes) {\n const where = change.column ? `${change.table}.${change.column}` : change.table;\n const message = change.kind === \"missing-table\"\n ? `Table ${where} is declared in the schema but no migration in ${relativeDir} creates it.`\n : change.kind === \"missing-column\"\n ? `Column ${where} is declared in the schema but no migration in ${relativeDir} adds it.`\n : `Column ${where} is no longer declared in the schema, but the migrations in ${relativeDir} still create it.`;\n const file = change.slug ? verified.files.get(change.slug) : undefined;\n findings.push({\n step: \"migrations\",\n check: change.kind === \"removed-column\" ? \"migration-stale-column\" : \"migration-missing\",\n severity: \"error\",\n message,\n fix,\n ...(change.slug && { table: change.slug }),\n ...(file && { file })\n });\n }\n\n step.detail = `${files.length} migration${files.length === 1 ? \"\" : \"s\"} in ${relativeDir}`;\n\n if (options.live && options.databaseUrl) {\n findings.push(...await checkAppliedMigrations(options.databaseUrl, files));\n }\n return findings;\n}\n\n/** Which migration files the database has not run, from Atlas's revision table. */\nasync function checkAppliedMigrations(databaseUrl: string, files: string[]): Promise<VerifyFinding[]> {\n const pg = await import(\"pg\");\n const client = new pg.default.Client({ connectionString: databaseUrl, connectionTimeoutMillis: 5_000 });\n try {\n await client.connect();\n const present = await client.query<{ present: boolean }>(\n \"SELECT to_regclass('rebase.atlas_schema_revisions') IS NOT NULL AS present\"\n );\n if (!present.rows[0]?.present) {\n return [{\n step: \"migrations\",\n check: \"migration-unapplied\",\n severity: \"warning\",\n message: \"The database has no migration history (rebase.atlas_schema_revisions) — it was provisioned with `rebase db push`, or never migrated.\",\n fix: \"`rebase db migrate --baseline <version>` adopts an existing database; `rebase db migrate` applies the migrations to a new one.\"\n }];\n }\n const applied = await client.query<{ version: string; type: string | number }>(\n \"SELECT version, type FROM rebase.atlas_schema_revisions WHERE error IS NULL OR error = ''\"\n );\n const { compareMigrationVersions, migrationVersionOf } = await import(\"@rebasepro/server-postgres\");\n const pending = pendingMigrations(\n files,\n applied.rows.map(row => ({ version: row.version, type: Number(row.type) })),\n compareMigrationVersions,\n migrationVersionOf\n );\n if (pending.length === 0) return [];\n return [{\n step: \"migrations\",\n check: \"migration-unapplied\",\n severity: \"error\",\n message: `${pending.length} migration${pending.length === 1 ? \" has\" : \"s have\"} not been applied to the database: ${pending.join(\", \")}.`,\n fix: \"Run `rebase db migrate`.\"\n }];\n } catch (error) {\n return [{\n step: \"migrations\",\n check: \"migration-unapplied\",\n severity: \"warning\",\n message: `Could not read the database's migration history: ${error instanceof Error ? error.message : String(error)}`\n }];\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n// ─── Step 4: live RLS audit ───────────────────────────────────────────────────\n\n/** rls-check's severities, folded onto this command's two. `info` is not reported. */\nfunction liveSeverity(severity: string): VerifyFinding[\"severity\"] | null {\n if (severity === \"critical\" || severity === \"high\") return \"error\";\n if (severity === \"medium\" || severity === \"low\") return \"warning\";\n return null;\n}\n\n/**\n * Why the database `--live` was pointed at cannot be opened, or `null` when it\n * can. Asked once, before the live steps, so an unreachable database is one\n * error rather than a skipped audit and a migration warning: under `--live`\n * the audit was asked for, and a CI run in which it never ran is not green.\n */\nasync function databaseUnreachable(databaseUrl: string): Promise<string | null> {\n const pg = await import(\"pg\");\n const client = new pg.default.Client({ connectionString: databaseUrl, connectionTimeoutMillis: 5_000 });\n try {\n await client.connect();\n return null;\n } catch (error) {\n return error instanceof Error ? error.message : String(error);\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n/**\n * A `USING (true)` read policy Rebase compiled from an `access: \"public\"`\n * select rule, on a backend that refuses a request with no token.\n *\n * rls-check reads the policy alone, and for the role every signed-in request\n * runs as it is \"every row to everyone\": critical. But the API answers 401\n * before RLS is consulted unless `AUTH_REQUIRE=false`, so what it grants is\n * every row to every *signed-in* user — exactly what step 2 accepts as a rule\n * said on purpose, and what boot reports as an info line. A fresh blog\n * scaffold failed its own `verify --live` with three such errors. It is a\n * warning here, as an unfiltered read is in step 2; with `AUTH_REQUIRE=false`\n * the rows really are public and it stays an error.\n */\nfunction isTokenGatedPublicRead(\n finding: { id: string; target: { table?: string; policy?: string } },\n authRequired: boolean,\n isGeneratedPolicyName: (name: string, table: string) => boolean\n): boolean {\n if (!authRequired || finding.id !== \"policy-always-true\") return false;\n const { table, policy } = finding.target;\n if (!table || !policy) return false;\n return isGeneratedPolicyName(policy, table) && policy.startsWith(`${table}_select_`);\n}\n\nasync function checkLive(databaseUrl: string, step: VerifyStep, authRequired: boolean): Promise<VerifyFinding[]> {\n const { scan, CHECKS } = await import(\"@rebasepro/rls-check\");\n const { isGeneratedPolicyName } = await import(\"@rebasepro/server-postgres\");\n let result: Awaited<ReturnType<typeof scan>>;\n try {\n result = await scan({ connectionString: databaseUrl, statementTimeoutMs: 10_000 });\n } catch (error) {\n step.detail = \"the audit did not run\";\n return [{\n step: \"live\",\n check: \"live-scan-failed\",\n severity: \"error\",\n message: `The live RLS audit failed: ${error instanceof Error ? error.message : String(error)}`,\n fix: \"`npx @rebasepro/rls-check <database-url>` runs the same audit on its own and reports the failure in full.\"\n }];\n }\n step.detail = `${CHECKS.length} rls-check checks against ${result.database.host}/${result.database.name}`;\n\n const findings: VerifyFinding[] = [];\n for (const finding of result.findings) {\n const severity = liveSeverity(finding.severity);\n if (!severity) continue;\n const tokenGated = severity === \"error\" && isTokenGatedPublicRead(finding, authRequired, isGeneratedPolicyName);\n findings.push({\n step: \"live\",\n check: finding.id,\n severity: tokenGated ? \"warning\" : severity,\n message: tokenGated\n ? `${finding.title} — compiled from an \\`access: \"public\"\\` read rule: every signed-in user reads every row. ` +\n \"A request with no token is refused by the API (AUTH_REQUIRE is on), so it is not an anonymous read.\"\n : finding.title,\n ...(finding.fix && { fix: finding.fix }),\n path: finding.target.table ? `${finding.target.schema}.${finding.target.table}` : finding.target.schema\n });\n }\n for (const degraded of result.diagnostics.degraded) {\n findings.push({\n step: \"live\",\n check: \"rls-check-degraded\",\n severity: \"warning\",\n message: `The audit could not read ${degraded.what}: ${degraded.error}. A clean result does not cover it.`\n });\n }\n return findings;\n}\n\n// ─── The run ──────────────────────────────────────────────────────────────────\n\nfunction settle(step: VerifyStep, findings: VerifyFinding[]): VerifyStep {\n if (step.status === \"skipped\") return step;\n const mine = findings.filter(f => f.step === step.id);\n step.status = mine.some(f => f.severity === \"error\") ? \"failed\" : mine.length > 0 ? \"warnings\" : \"passed\";\n return step;\n}\n/**\n * Run every step and return the report. Prints nothing and never exits, so a\n * caller — the command, a test — decides what to do with it.\n */\nexport async function runVerify(options: VerifyOptions): Promise<VerifyReport> {\n const findings: VerifyFinding[] = [];\n const steps: VerifyStep[] = ([\"schema\", \"rls\", \"cms\", \"migrations\", \"live\"] as const).map(id => ({\n id,\n title: STEP_TITLES[id],\n status: \"passed\"\n }));\n const [schemaStep, rlsStep, cmsStep, migrationsStep, liveStep] = steps;\n const schemaDir = path.relative(options.projectRoot, options.schemaDir) || \".\";\n const skipAll = (detail: string): VerifyReport => {\n for (const step of steps) {\n step.status = \"skipped\";\n step.detail = detail;\n }\n return { ok: true, schemaDir, steps, findings, summary: { errors: 0, warnings: 0 } };\n };\n\n // No schema is a project that declares no tables — its API is introspected\n // from the database (a headless one). A skip, not a failure.\n if (!fs.existsSync(options.schemaDir) || !fs.statSync(options.schemaDir).isDirectory()) {\n return skipAll(`no schema directory at ${schemaDir}`);\n }\n\n const { verified, failures } = await loadSchema(options);\n findings.push(...failures);\n if (verified && !verified.schema.loaded.indexFile) {\n return skipAll(`${schemaDir} has no index.ts, so it declares no tables`);\n }\n\n if (verified) {\n const tables = verified.descriptors.length;\n schemaStep.detail = `${tables} table${tables === 1 ? \"\" : \"s\"}, compiled as the backend boots them`;\n rlsStep.detail = `${tables} table${tables === 1 ? \"\" : \"s\"}`;\n findings.push(...checkRls(verified));\n const cms = await checkCmsCustomizations(options.projectRoot, verified.descriptors);\n if (cms.directories.length === 0) {\n cmsStep.status = \"skipped\";\n cmsStep.detail = \"no frontend/src/cms\";\n // A frontend without src/cms still builds without the backend guard.\n for (const finding of cms.findings) findings.push({ step: \"cms\", ...finding });\n } else {\n cmsStep.detail = `${cms.customizations} customization${cms.customizations === 1 ? \"\" : \"s\"} in ${cms.directories.join(\", \")}, read without running them`;\n for (const finding of cms.findings) findings.push({ step: \"cms\", ...finding });\n }\n } else {\n for (const step of [rlsStep, cmsStep]) {\n step.status = \"skipped\";\n step.detail = \"fix the table definitions first\";\n }\n }\n\n // The database the live steps read, once it is known to answer. Under\n // `--live` a database that is missing or does not answer is an error: the\n // audit was asked for, and exit 0 without it is a green CI run over nothing.\n let liveUrl: string | undefined;\n if (options.live) {\n if (!options.databaseUrl) {\n liveStep.detail = \"no database to audit\";\n findings.push({\n step: \"live\",\n check: \"live-no-database\",\n severity: \"error\",\n message: options.databaseUnavailable\n ? `--live was asked for, and the database could not be prepared: ${options.databaseUnavailable}`\n : \"--live was asked for, and no database is configured to audit.\",\n fix: \"Pass --database-url <url> (or set DATABASE_URL), or run without --live for the offline checks.\"\n });\n } else {\n const unreachable = await databaseUnreachable(options.databaseUrl);\n if (unreachable) {\n liveStep.detail = \"the database did not answer\";\n findings.push({\n step: \"live\",\n check: \"live-unreachable\",\n severity: \"error\",\n message: `--live was asked for, and the database could not be reached: ${unreachable}. Neither the migration check nor the RLS audit ran.`,\n fix: \"Check the database is running and the URL is right (`rebase db url` prints the one this project resolves), or run without --live for the offline checks.\"\n });\n } else {\n liveUrl = options.databaseUrl;\n }\n }\n }\n\n if (!verified) {\n migrationsStep.status = \"skipped\";\n migrationsStep.detail = \"fix the table definitions first\";\n } else {\n findings.push(...await checkMigrations({ ...options, databaseUrl: liveUrl }, verified, migrationsStep));\n }\n\n if (!options.live) {\n liveStep.status = \"skipped\";\n liveStep.detail = \"pass --live to audit the database\";\n } else if (liveUrl) {\n findings.push(...await checkLive(liveUrl, liveStep, options.authRequired ?? true));\n }\n\n steps.forEach(step => settle(step, findings));\n const errors = findings.filter(f => f.severity === \"error\").length;\n return {\n ok: errors === 0,\n schemaDir,\n steps,\n findings,\n summary: { errors, warnings: findings.length - errors }\n };\n}\n\n// ─── Output ───────────────────────────────────────────────────────────────────\n\nfunction printFinding(finding: VerifyFinding): void {\n const mark = finding.severity === \"error\" ? chalk.red(\"✗\") : chalk.yellow(\"!\");\n const file = finding.file && finding.line !== undefined ? `${finding.file}:${finding.line}` : finding.file;\n const where = [file, finding.path].filter(Boolean).join(\" → \");\n console.log(` ${mark} ${where ? `${chalk.bold(where)} ` : \"\"}${finding.message}`);\n if (finding.fix) console.log(chalk.gray(` fix: ${finding.fix}`));\n}\n\nfunction summaryLine(report: VerifyReport): string {\n const { errors, warnings } = report.summary;\n return `${errors} error${errors === 1 ? \"\" : \"s\"}, ${warnings} warning${warnings === 1 ? \"\" : \"s\"}`;\n}\n\nexport function printReport(report: VerifyReport, quiet: boolean): void {\n if (quiet) {\n if (report.findings.length === 0) return;\n if (!report.ok) console.log(chalk.red(`rebase verify: ${summaryLine(report)}`));\n for (const finding of report.findings) printFinding(finding);\n return;\n }\n\n console.log(\"\");\n console.log(` ${chalk.bold(\"rebase verify\")} ${chalk.gray(report.schemaDir)}`);\n console.log(\"\");\n for (const step of report.steps) {\n const mark = step.status === \"passed\" ? chalk.green(\"✓\")\n : step.status === \"failed\" ? chalk.red(\"✗\")\n : step.status === \"warnings\" ? chalk.yellow(\"!\")\n : chalk.gray(\"–\");\n const detail = step.detail ? chalk.gray(step.status === \"skipped\" ? `skipped: ${step.detail}` : step.detail) : \"\";\n console.log(` ${mark} ${step.title.padEnd(22)} ${detail}`);\n }\n if (report.findings.length > 0) {\n console.log(\"\");\n for (const finding of report.findings) printFinding(finding);\n }\n console.log(\"\");\n console.log(report.ok ? chalk.green(` ✓ ${summaryLine(report)}`) : chalk.red(` ✗ ${summaryLine(report)}`));\n console.log(\"\");\n}\n\nfunction printVerifyHelp(): void {\n console.log(`\n${chalk.bold(\"rebase verify\")} — Check the tables are safe to ship\n\n${chalk.green.bold(\"Usage\")}\n rebase verify [options]\n\n${chalk.green.bold(\"Options\")}\n${Object.entries(VERIFY_FLAG_HELP).map(([flag, help]) => ` ${chalk.blue(flag.padEnd(20))} ${help}`).join(\"\\n\")}\n\n${chalk.green.bold(\"Steps\")}\n 1. Table definitions backend/schema loads and compiles as the backend boots it\n 2. RLS coverage owner and tenant columns are filtered on by the rules that read them\n 3. CMS customizations frontend/src/cms: each customizeTable names a table, its fields, and a form that can create\n 4. Migration freshness drizzle/migrations builds every declared table and column\n 5. Live RLS audit with --live: the rls-check catalogue against the project's database\n\nExits 1 when any step reports an error; warnings do not fail. Under --live, a\ndatabase that is missing or does not answer is an error. Fast and offline\nwithout --live: for CI, and for the Claude Code hook that ${chalk.cyan(\"rebase skills --hooks\")} installs.\n`);\n}\n\n/**\n * Whether the backend refuses a request with no token: `AUTH_REQUIRE` from the\n * environment, else `.env`, read as every boolean env var is read\n * (`parseEnvBoolean`: `false`/`0`/`no`/`off` turn it off). On unless one of\n * those says otherwise — the runtime's default. Compared raw, `AUTH_REQUIRE=0`\n * read as \"on\", and a compiled public read was reported as token-gated on a\n * backend that serves it to anyone.\n */\nexport function authRequiredFrom(\n environment: Record<string, string | undefined>,\n envFile: Record<string, string | undefined>\n): boolean {\n return parseEnvBoolean(environment.AUTH_REQUIRE ?? envFile.AUTH_REQUIRE) !== false;\n}\n\n/**\n * The database `--live` audits, resolved as every other database door resolves\n * it (`db *`, `console`, `doctor`): `--database-url`, `DATABASE_URL`, `.env`,\n * `--docker` or the last `rebase dev --docker`, and otherwise the managed\n * development database — started if it is not running. Reading only\n * `DATABASE_URL` meant the audit never ran on a fresh scaffold, whose database\n * is the managed one.\n *\n * Progress goes to stderr, so `--json` keeps stdout to the report.\n */\nasync function resolveLiveDatabase(\n projectRoot: string,\n rawArgs: readonly string[],\n options: { flagUrl: string | null; flagDocker: boolean; quiet: boolean }\n): Promise<Pick<VerifyOptions, \"databaseUrl\" | \"databaseUnavailable\">> {\n try {\n const { ensureDockerDatabase, databaseUrlOf } = await import(\"./db\");\n await ensureDockerDatabase(projectRoot, rawArgs);\n const { prepareDatabaseEnv } = await import(\"../dev-db/prepare\");\n const prepared = await prepareDatabaseEnv(projectRoot, {\n flagUrl: options.flagUrl,\n flagDocker: options.flagDocker,\n quiet: options.quiet,\n onProgress: options.quiet ? undefined : (line) => console.error(chalk.gray(` ${line}`))\n });\n return { databaseUrl: databaseUrlOf(prepared, readEnvFile(projectRoot)) };\n } catch (error) {\n return { databaseUnavailable: error instanceof Error ? error.message : String(error) };\n }\n}\n\nexport async function verifyCommand(rawArgs: string[]): Promise<void> {\n if (wantsHelp(rawArgs)) {\n printVerifyHelp();\n return;\n }\n refuseRemovedCollectionsFlag(rawArgs.slice(2), \"verify\");\n const { flags } = parseCommandArgs({\n spec: VERIFY_FLAGS,\n rawArgs,\n commandWords: 1,\n command: \"verify\",\n maxPositionals: 0\n });\n\n const projectRoot = requireProjectRoot();\n const backendDir = findBackendDir(projectRoot);\n const typedDir = flags[\"--schema-dir\"];\n if (typedDir) {\n // A mistyped path used to skip every step and print \"0 errors\" with\n // exit 0 — a green CI run over nothing. Refused as `doctor` and\n // `schema` refuse it. Without the flag, a project with no schema\n // directory (a headless one) is still a skip, not a failure.\n const refusal = missingSchemaDir(rawArgs, process.cwd(), backendDir ?? projectRoot, \"verify\");\n if (refusal) {\n if (flags[\"--json\"]) {\n failAsJson(\n `Schema directory not found: \"${typedDir}\" (resolved to ${path.resolve(process.cwd(), typedDir)}).`,\n \"schema_dir_not_found\",\n \"Leave --schema-dir out (backend/schema is the default), or pass a directory that exists; relative paths are resolved from where you run the command.\"\n );\n }\n console.error(\"\");\n for (const line of refusal) console.error(line);\n console.error(\"\");\n process.exit(1);\n }\n }\n const schemaDir = typedDir ? path.resolve(process.cwd(), typedDir) : resolveSchemaDir(projectRoot);\n const live = flags[\"--live\"] === true;\n const database = live\n ? await resolveLiveDatabase(projectRoot, rawArgs, {\n flagUrl: flags[\"--database-url\"] ?? null,\n flagDocker: flags[\"--docker\"] === true,\n quiet: flags[\"--quiet\"] === true\n })\n : {};\n\n const report = await runVerify({\n projectRoot,\n schemaDir,\n backendDir,\n live,\n ...database,\n authRequired: authRequiredFrom(process.env, readEnvFile(projectRoot))\n });\n\n if (flags[\"--json\"]) {\n console.log(JSON.stringify(report, null, 2));\n } else {\n printReport(report, flags[\"--quiet\"] === true);\n }\n if (!report.ok) process.exitCode = 1;\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,IAAM,cAAc;AACpB,IAAM,YAAY;;AAElB,IAAM,QAAQ;AACd,IAAM,iBAAiB;AACvB,IAAM,SAAS;AACf,IAAM,aAAa;;AAGnB,IAAM,mBAAmB;CAAC;CAAgB;CAAY;AAAU;AAgDhE,SAAS,YAAY,KAAuB;CACxC,MAAM,MAAgB,CAAC;CACvB,KAAK,MAAM,SAAS,GAAG,YAAY,KAAK,EAAE,eAAe,KAAK,CAAC,GAAG;EAC9D,IAAI,MAAM,KAAK,WAAW,GAAG,KAAK,MAAM,SAAS,gBAAgB;EACjE,MAAM,OAAO,KAAK,KAAK,KAAK,MAAM,IAAI;EACtC,IAAI,MAAM,YAAY,GAAG,IAAI,KAAK,GAAG,YAAY,IAAI,CAAC;OACjD,IAAI,OAAO,KAAK,MAAM,IA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