@rebasepro/cli 0.30.1 → 0.31.0-canary.g59cd6fd

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/README.md +8 -7
  2. package/dist/{agent-setup-0uyfC7VX.js → agent-setup-DqAcoDcn.js} +10 -5
  3. package/dist/{agent-setup-0uyfC7VX.js.map → agent-setup-DqAcoDcn.js.map} +1 -1
  4. package/dist/{api-keys-Dfw5-9s1.js → api-keys-eIUjMqWn.js} +8 -7
  5. package/dist/api-keys-eIUjMqWn.js.map +1 -0
  6. package/dist/{apps-MKQbgDtN.js → apps-DExO4PEl.js} +8 -7
  7. package/dist/apps-DExO4PEl.js.map +1 -0
  8. package/dist/{project-CasK56vN.js → args-CaCcrYE1.js} +2 -351
  9. package/dist/args-CaCcrYE1.js.map +1 -0
  10. package/dist/{atlas-dev-database-BODqdCWt.js → atlas-dev-database-DOCKk6ht.js} +2 -2
  11. package/dist/{atlas-dev-database-BODqdCWt.js.map → atlas-dev-database-DOCKk6ht.js.map} +1 -1
  12. package/dist/{auth-Bv0rTbQX.js → auth-D96QYgFR.js} +7 -6
  13. package/dist/{auth-Bv0rTbQX.js.map → auth-D96QYgFR.js.map} +1 -1
  14. package/dist/backend-guard-C0mVkXBw.js +162 -0
  15. package/dist/backend-guard-C0mVkXBw.js.map +1 -0
  16. package/dist/{branch-pointer-BQUF6lYa.js → branch-pointer-DMPyvZoK.js} +1 -1
  17. package/dist/{build-BuKTnec8.js → build-CA5R07tw.js} +29 -9
  18. package/dist/build-CA5R07tw.js.map +1 -0
  19. package/dist/{bundle-BAH4FCju.js → bundle-DgILeA5b.js} +112 -138
  20. package/dist/bundle-DgILeA5b.js.map +1 -0
  21. package/dist/bundle.d.ts +35 -12
  22. package/dist/cli.d.ts +2 -2
  23. package/dist/{cloud-DtADfWwn.js → cloud-CYMk92iG.js} +72 -71
  24. package/dist/cloud-CYMk92iG.js.map +1 -0
  25. package/dist/cms-directories-BK3vcswg.js +33 -0
  26. package/dist/cms-directories-BK3vcswg.js.map +1 -0
  27. package/dist/codemod/collections-to-tables/ast.d.ts +135 -0
  28. package/dist/codemod/collections-to-tables/backend.d.ts +38 -0
  29. package/dist/codemod/collections-to-tables/command.d.ts +35 -0
  30. package/dist/codemod/collections-to-tables/comments.d.ts +45 -0
  31. package/dist/codemod/collections-to-tables/customization.d.ts +47 -0
  32. package/dist/codemod/collections-to-tables/dynamic-props.d.ts +34 -0
  33. package/dist/codemod/collections-to-tables/export-changes.d.ts +83 -0
  34. package/dist/codemod/collections-to-tables/firestore.d.ts +11 -0
  35. package/dist/codemod/collections-to-tables/helper-hooks.d.ts +41 -0
  36. package/dist/codemod/collections-to-tables/hooks.d.ts +44 -0
  37. package/dist/codemod/collections-to-tables/journal.d.ts +10 -0
  38. package/dist/codemod/collections-to-tables/legacy-shims.d.ts +52 -0
  39. package/dist/codemod/collections-to-tables/load-legacy.d.ts +81 -0
  40. package/dist/codemod/collections-to-tables/migrate.d.ts +20 -0
  41. package/dist/codemod/collections-to-tables/modules.d.ts +127 -0
  42. package/dist/codemod/collections-to-tables/moved-imports.d.ts +70 -0
  43. package/dist/codemod/collections-to-tables/moved-symbols.generated.d.ts +12 -0
  44. package/dist/codemod/collections-to-tables/own.d.ts +10 -0
  45. package/dist/codemod/collections-to-tables/path-aliases.d.ts +26 -0
  46. package/dist/codemod/collections-to-tables/plan-context.d.ts +49 -0
  47. package/dist/codemod/collections-to-tables/print-js.d.ts +44 -0
  48. package/dist/codemod/collections-to-tables/project-files.d.ts +144 -0
  49. package/dist/codemod/collections-to-tables/repoint.d.ts +50 -0
  50. package/dist/codemod/collections-to-tables/row-hands.d.ts +7 -0
  51. package/dist/codemod/collections-to-tables/sdk-calls.d.ts +88 -0
  52. package/dist/codemod/collections-to-tables/skills-step.d.ts +13 -0
  53. package/dist/codemod/collections-to-tables/split-constants.d.ts +42 -0
  54. package/dist/codemod/collections-to-tables/storage-paths.d.ts +28 -0
  55. package/dist/codemod/collections-to-tables/types.d.ts +164 -0
  56. package/dist/codemod/collections-to-tables/verify.d.ts +27 -0
  57. package/dist/codemod/collections-to-tables/vocabulary.d.ts +40 -0
  58. package/dist/command-D5lhW_-B.js +9984 -0
  59. package/dist/command-D5lhW_-B.js.map +1 -0
  60. package/dist/commands/agent-setup.d.ts +6 -2
  61. package/dist/commands/cloud/context.d.ts +1 -1
  62. package/dist/commands/cloud/init.d.ts +2 -2
  63. package/dist/commands/console.d.ts +1 -2
  64. package/dist/commands/db.d.ts +5 -6
  65. package/dist/commands/dev.d.ts +18 -17
  66. package/dist/commands/doctor.d.ts +4 -5
  67. package/dist/commands/eject.d.ts +17 -13
  68. package/dist/commands/generate-view.d.ts +20 -9
  69. package/dist/commands/generate_sdk.d.ts +27 -27
  70. package/dist/commands/init.d.ts +21 -8
  71. package/dist/commands/migrate.d.ts +24 -0
  72. package/dist/commands/schema-reconcile.d.ts +1 -1
  73. package/dist/commands/skills.d.ts +8 -0
  74. package/dist/commands/verify-cms.d.ts +28 -0
  75. package/dist/commands/verify.d.ts +14 -9
  76. package/dist/{consent-BD7F29T3.js → consent-BXLIrMl8.js} +2 -2
  77. package/dist/{consent-BD7F29T3.js.map → consent-BXLIrMl8.js.map} +1 -1
  78. package/dist/{console-CdwIYOMV.js → console-C1d3LwB7.js} +14 -14
  79. package/dist/console-C1d3LwB7.js.map +1 -0
  80. package/dist/{context-AXdAh-q8.js → context--JwaHaZp.js} +6 -5
  81. package/dist/context--JwaHaZp.js.map +1 -0
  82. package/dist/{daemon-Cp7oNXth.js → daemon-w30PsdwV.js} +2 -2
  83. package/dist/{daemon-Cp7oNXth.js.map → daemon-w30PsdwV.js.map} +1 -1
  84. package/dist/{db-DBbKpjYX.js → db-DQZK9n9c.js} +52 -51
  85. package/dist/db-DQZK9n9c.js.map +1 -0
  86. package/dist/{derive-ae9UOoOB.js → derive-C3ezmY-p.js} +105 -133
  87. package/dist/derive-C3ezmY-p.js.map +1 -0
  88. package/dist/{dev-C93d4QIv.js → dev-PY5h4O6u.js} +142 -84
  89. package/dist/dev-PY5h4O6u.js.map +1 -0
  90. package/dist/dev-db/attver.d.ts +32 -0
  91. package/dist/dev-db/pull.d.ts +15 -1
  92. package/dist/{dev-preflight-Cxv3TiD1.js → dev-preflight-DjvcV6SK.js} +5 -5
  93. package/dist/dev-preflight-DjvcV6SK.js.map +1 -0
  94. package/dist/{dev-server-OJsUGZEB.js → dev-server-BLxCbQEP.js} +2 -2
  95. package/dist/{dev-server-OJsUGZEB.js.map → dev-server-BLxCbQEP.js.map} +1 -1
  96. package/dist/{doctor-BBPQUO2g.js → doctor-CnUu8kpM.js} +39 -62
  97. package/dist/doctor-CnUu8kpM.js.map +1 -0
  98. package/dist/doctor-environment.d.ts +6 -6
  99. package/dist/{eject-DABcDnPN.js → eject-Bhzd6hgb.js} +25 -16
  100. package/dist/eject-Bhzd6hgb.js.map +1 -0
  101. package/dist/{fold-static-BWzxNn06.js → fold-static-CKewnAPX.js} +5 -3
  102. package/dist/fold-static-CKewnAPX.js.map +1 -0
  103. package/dist/{generate-view-IFwCADvb.js → generate-view-CTOluXvH.js} +160 -89
  104. package/dist/generate-view-CTOluXvH.js.map +1 -0
  105. package/dist/{generate_sdk-DNmNuFuW.js → generate_sdk-De-aLC1L.js} +120 -137
  106. package/dist/generate_sdk-De-aLC1L.js.map +1 -0
  107. package/dist/import-schema-module-Df67TIWj.js +51 -0
  108. package/dist/import-schema-module-Df67TIWj.js.map +1 -0
  109. package/dist/index.es.js +64 -51
  110. package/dist/index.es.js.map +1 -1
  111. package/dist/{init-vL1DWOeC.js → init-Dtl-IcXf.js} +83 -80
  112. package/dist/init-Dtl-IcXf.js.map +1 -0
  113. package/dist/last-dev-database-Dc8cP01o.js +2 -0
  114. package/dist/{manifest-BtzDy7KQ.js → manifest-C3uLDrrJ.js} +115 -40
  115. package/dist/manifest-C3uLDrrJ.js.map +1 -0
  116. package/dist/manifest.d.ts +79 -24
  117. package/dist/migrate-VrKoi3nB.js +138 -0
  118. package/dist/migrate-VrKoi3nB.js.map +1 -0
  119. package/dist/{normalize-imports-Bd5Y4yLp.js → normalize-imports-DwxqEMYq.js} +3 -3
  120. package/dist/{normalize-imports-Bd5Y4yLp.js.map → normalize-imports-DwxqEMYq.js.map} +1 -1
  121. package/dist/path-flags-7O5uPBcQ.js +139 -0
  122. package/dist/path-flags-7O5uPBcQ.js.map +1 -0
  123. package/dist/{prepare-CTw9NEkh.js → prepare-Ccxspoj-.js} +4 -4
  124. package/dist/{prepare-CTw9NEkh.js.map → prepare-Ccxspoj-.js.map} +1 -1
  125. package/dist/project-CLcF5i8c.js +360 -0
  126. package/dist/project-CLcF5i8c.js.map +1 -0
  127. package/dist/project-schema-CsSOG2gE.js +30 -0
  128. package/dist/project-schema-CsSOG2gE.js.map +1 -0
  129. package/dist/{pull-DDMpsZ5r.js → pull-DRWqBZp5.js} +327 -4
  130. package/dist/pull-DRWqBZp5.js.map +1 -0
  131. package/dist/resolve-BY7bSFRT.js +2 -0
  132. package/dist/resources/derive.d.ts +19 -13
  133. package/dist/{resources-CPSC5Kcu.js → resources-Dpfs2y8P.js} +5 -4
  134. package/dist/{resources-CPSC5Kcu.js.map → resources-Dpfs2y8P.js.map} +1 -1
  135. package/dist/{schema-DtLPsXbT.js → schema-CdDjv5zI.js} +41 -39
  136. package/dist/schema-CdDjv5zI.js.map +1 -0
  137. package/dist/schema-dir-Cd1kvYbf.js +98 -0
  138. package/dist/schema-dir-Cd1kvYbf.js.map +1 -0
  139. package/dist/schema-reconcile-BAupXfkd.js +2 -0
  140. package/dist/schema-text-CpNrsuMe.js +73 -0
  141. package/dist/schema-text-CpNrsuMe.js.map +1 -0
  142. package/dist/{skills-CbwV6vw_.js → skills-CXjA9TWw.js} +54 -10
  143. package/dist/skills-CXjA9TWw.js.map +1 -0
  144. package/dist/{start-YOr3X5Zm.js → start-Bwbtt2W5.js} +7 -10
  145. package/dist/{start-YOr3X5Zm.js.map → start-Bwbtt2W5.js.map} +1 -1
  146. package/dist/{status-BREvtzJm.js → status-D7XCGHu2.js} +12 -12
  147. package/dist/status-D7XCGHu2.js.map +1 -0
  148. package/dist/{storage-CO9ouK76.js → storage-iTqj5-Av.js} +12 -11
  149. package/dist/storage-iTqj5-Av.js.map +1 -0
  150. package/dist/{telemetry-DwK5RQJl.js → telemetry-BP_1Cl9r.js} +4 -4
  151. package/dist/{telemetry-DwK5RQJl.js.map → telemetry-BP_1Cl9r.js.map} +1 -1
  152. package/dist/{telemetry-CgwJPVMO.js → telemetry-M3HjlyhZ.js} +2 -2
  153. package/dist/{telemetry-CgwJPVMO.js.map → telemetry-M3HjlyhZ.js.map} +1 -1
  154. package/dist/{upgrade-B7sVwL8S.js → upgrade-oZzJ13jM.js} +5 -4
  155. package/dist/{upgrade-B7sVwL8S.js.map → upgrade-oZzJ13jM.js.map} +1 -1
  156. package/dist/utils/backend-guard.d.ts +47 -0
  157. package/dist/utils/cms-directories.d.ts +6 -0
  158. package/dist/utils/dev-preflight.d.ts +2 -2
  159. package/dist/utils/import-schema-module.d.ts +16 -0
  160. package/dist/utils/path-flags.d.ts +35 -16
  161. package/dist/utils/project-schema.d.ts +40 -0
  162. package/dist/utils/project.d.ts +8 -2
  163. package/dist/utils/schema-dir.d.ts +32 -0
  164. package/dist/utils/schema-drift.d.ts +6 -0
  165. package/dist/utils/schema-text.d.ts +24 -0
  166. package/dist/verify-5p_vaUG2.js +1160 -0
  167. package/dist/verify-5p_vaUG2.js.map +1 -0
  168. package/package.json +11 -8
  169. package/runtime/dev-server.mjs +5 -1
  170. package/templates/eject/Dockerfile +1 -4
  171. package/templates/eject/backend/src/env.ts +1 -1
  172. package/templates/eject/backend/src/index.ts +53 -40
  173. package/templates/eject/docker-compose.custom.yml +1 -1
  174. package/templates/overlays/baas/README.md +39 -12
  175. package/templates/overlays/baas/ai-instructions.md +8 -8
  176. package/templates/overlays/baas/{config → backend}/storage.ts +3 -4
  177. package/templates/overlays/baas/backend/tsconfig.json +10 -12
  178. package/templates/overlays/baas/package.json +1 -2
  179. package/templates/overlays/baas/pnpm-workspace.yaml +0 -1
  180. package/templates/presets/blank/backend/schema/index.ts +19 -0
  181. package/templates/presets/blank/frontend/src/App.tsx +56 -0
  182. package/templates/presets/ecommerce/backend/schema/categories.ts +12 -0
  183. package/templates/presets/ecommerce/backend/schema/index.ts +23 -0
  184. package/templates/presets/ecommerce/backend/schema/orders.ts +13 -0
  185. package/templates/presets/ecommerce/backend/schema/products.ts +18 -0
  186. package/templates/presets/ecommerce/frontend/src/App.tsx +59 -0
  187. package/templates/presets/ecommerce/frontend/src/cms/categories.tsx +12 -0
  188. package/templates/presets/ecommerce/frontend/src/cms/orders.tsx +38 -0
  189. package/templates/presets/ecommerce/frontend/src/cms/products.tsx +27 -0
  190. package/templates/resource-graphs/blank.json +2 -2
  191. package/templates/resource-graphs/blog.json +5 -5
  192. package/templates/resource-graphs/ecommerce.json +5 -5
  193. package/templates/resource-graphs/headless.json +1 -1
  194. package/templates/template/.claude/hooks/post-edit-collection.sh +27 -23
  195. package/templates/template/.cursorrules +2 -2
  196. package/templates/template/.env.example +6 -17
  197. package/templates/template/.github/copilot-instructions.md +2 -2
  198. package/templates/template/.windsurfrules +2 -2
  199. package/templates/template/AGENTS.md +2 -2
  200. package/templates/template/CLAUDE.md +2 -2
  201. package/templates/template/README.md +47 -13
  202. package/templates/template/ai-instructions.md +15 -14
  203. package/templates/template/backend/functions/hello.ts +1 -1
  204. package/templates/template/backend/package.json +0 -2
  205. package/templates/template/{config → backend}/resources.ts +3 -3
  206. package/templates/template/backend/schema/authors.ts +11 -0
  207. package/templates/template/backend/schema/index.ts +29 -0
  208. package/templates/template/backend/schema/posts.ts +29 -0
  209. package/templates/template/backend/schema/tags.ts +9 -0
  210. package/templates/template/backend/schema/users.ts +32 -0
  211. package/templates/template/{config → backend}/storage.ts +4 -4
  212. package/templates/template/backend/tsconfig.json +15 -20
  213. package/templates/template/docker-compose.yml +3 -3
  214. package/templates/template/frontend/package.json +0 -2
  215. package/templates/template/frontend/src/App.tsx +10 -4
  216. package/templates/template/frontend/src/cms/authors.tsx +7 -0
  217. package/templates/template/frontend/src/cms/posts.tsx +27 -0
  218. package/templates/template/frontend/src/cms/tags.tsx +11 -0
  219. package/templates/template/frontend/src/cms/ui-config.json +3 -0
  220. package/templates/template/frontend/src/cms/users.tsx +54 -0
  221. package/templates/template/frontend/src/{virtual.d.ts → vite-env.d.ts} +0 -4
  222. package/templates/template/frontend/vite.config.ts +6 -2
  223. package/templates/template/gitignore +1 -1
  224. package/templates/template/package.json +1 -2
  225. package/templates/template/pnpm-workspace.yaml +0 -1
  226. package/templates/template/scripts/example.ts +3 -3
  227. package/templates/template/tsconfig.json +1 -1
  228. package/templates/views/AppView.tsx.tmpl +4 -4
  229. package/templates/views/EntityView.tsx.tmpl +3 -4
  230. package/dist/api-keys-Dfw5-9s1.js.map +0 -1
  231. package/dist/apps-MKQbgDtN.js.map +0 -1
  232. package/dist/build-BuKTnec8.js.map +0 -1
  233. package/dist/bundle-BAH4FCju.js.map +0 -1
  234. package/dist/cloud-DtADfWwn.js.map +0 -1
  235. package/dist/collection-drift-BKj_BoMq.js +0 -106
  236. package/dist/collection-drift-BKj_BoMq.js.map +0 -1
  237. package/dist/collections-dir-DlvDhime.js +0 -69
  238. package/dist/collections-dir-DlvDhime.js.map +0 -1
  239. package/dist/console-CdwIYOMV.js.map +0 -1
  240. package/dist/context-AXdAh-q8.js.map +0 -1
  241. package/dist/db-DBbKpjYX.js.map +0 -1
  242. package/dist/derive-ae9UOoOB.js.map +0 -1
  243. package/dist/dev-C93d4QIv.js.map +0 -1
  244. package/dist/dev-preflight-Cxv3TiD1.js.map +0 -1
  245. package/dist/doctor-BBPQUO2g.js.map +0 -1
  246. package/dist/eject-DABcDnPN.js.map +0 -1
  247. package/dist/fold-static-BWzxNn06.js.map +0 -1
  248. package/dist/generate-view-IFwCADvb.js.map +0 -1
  249. package/dist/generate_sdk-DNmNuFuW.js.map +0 -1
  250. package/dist/init-vL1DWOeC.js.map +0 -1
  251. package/dist/last-dev-database-DpW5dfoX.js +0 -2
  252. package/dist/manifest-BtzDy7KQ.js.map +0 -1
  253. package/dist/path-flags-DNvtEi2-.js +0 -92
  254. package/dist/path-flags-DNvtEi2-.js.map +0 -1
  255. package/dist/project-CasK56vN.js.map +0 -1
  256. package/dist/pull-DDMpsZ5r.js.map +0 -1
  257. package/dist/resolve-D647F1LA.js +0 -2
  258. package/dist/schema-DtLPsXbT.js.map +0 -1
  259. package/dist/schema-reconcile-DkArN9jF.js +0 -2
  260. package/dist/skills-CbwV6vw_.js.map +0 -1
  261. package/dist/status-BREvtzJm.js.map +0 -1
  262. package/dist/storage-CO9ouK76.js.map +0 -1
  263. package/dist/utils/collection-drift.d.ts +0 -27
  264. package/dist/utils/collections-dir.d.ts +0 -14
  265. package/dist/verify-Y3rWSgfA.js +0 -730
  266. package/dist/verify-Y3rWSgfA.js.map +0 -1
  267. package/templates/overlays/baas/config/index.ts +0 -24
  268. package/templates/overlays/baas/config/package.json +0 -30
  269. package/templates/template/config/cms.d.ts +0 -15
  270. package/templates/template/config/collections/authors.ts +0 -47
  271. package/templates/template/config/collections/index.ts +0 -44
  272. package/templates/template/config/collections/posts.ts +0 -94
  273. package/templates/template/config/collections/presets/blank/index.ts +0 -5
  274. package/templates/template/config/collections/presets/ecommerce/categories.ts +0 -42
  275. package/templates/template/config/collections/presets/ecommerce/index.ts +0 -31
  276. package/templates/template/config/collections/presets/ecommerce/orders.ts +0 -78
  277. package/templates/template/config/collections/presets/ecommerce/products.ts +0 -73
  278. package/templates/template/config/collections/tags.ts +0 -27
  279. package/templates/template/config/collections/users.ts +0 -149
  280. package/templates/template/config/frontend-assets.d.ts +0 -17
  281. package/templates/template/config/index.ts +0 -12
  282. package/templates/template/config/package.json +0 -30
  283. package/templates/template/config/tsconfig.json +0 -35
  284. /package/templates/eject/{config → backend}/resources.ts +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify-5p_vaUG2.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,eA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AI,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;MAE3C,YAAY,QAAQ,MAAM,eAAe,IAAI;CAEjD,IAAI,CAAC,OAAO,IAAI,QAAQ,WAAW;AACvC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rebasepro/cli",
3
- "version": "0.30.1",
3
+ "version": "0.31.0-canary.g59cd6fd",
4
4
  "description": "Developer tools for Rebase projects",
5
5
  "keywords": [
6
6
  "cli",
@@ -44,13 +44,16 @@
44
44
  "inquirer": "14.0.2",
45
45
  "jiti": "^2.7.0",
46
46
  "pg": "^8.22.0",
47
- "@rebasepro/agent-skills": "0.30.1",
48
- "@rebasepro/codegen": "0.30.1",
49
- "@rebasepro/client": "0.30.1",
50
- "@rebasepro/rls-check": "0.30.1",
51
- "@rebasepro/server-postgres": "0.30.1",
52
- "@rebasepro/types": "0.30.1",
53
- "@rebasepro/server": "0.30.1"
47
+ "ts-morph": "28.0.0",
48
+ "@rebasepro/agent-skills": "0.31.0-canary.g59cd6fd",
49
+ "@rebasepro/client": "0.31.0-canary.g59cd6fd",
50
+ "@rebasepro/common": "0.31.0-canary.g59cd6fd",
51
+ "@rebasepro/codegen": "0.31.0-canary.g59cd6fd",
52
+ "@rebasepro/rls-check": "0.31.0-canary.g59cd6fd",
53
+ "@rebasepro/server": "0.31.0-canary.g59cd6fd",
54
+ "@rebasepro/server-postgres": "0.31.0-canary.g59cd6fd",
55
+ "@rebasepro/utils": "0.31.0-canary.g59cd6fd",
56
+ "@rebasepro/types": "0.31.0-canary.g59cd6fd"
54
57
  },
55
58
  "devDependencies": {
56
59
  "@types/node": "^26.1.2",
@@ -27,7 +27,11 @@ const optional = (value) => (value && value.length > 0 ? value : undefined);
27
27
 
28
28
  const bundle = createSourceBundle({
29
29
  projectRoot,
30
- config: optional(process.env.REBASE_DEV_CONFIG),
30
+ // The schema directory and the three backend modules beside it.
31
+ tables: optional(process.env.REBASE_DEV_TABLES),
32
+ resources: optional(process.env.REBASE_DEV_RESOURCES),
33
+ storage: optional(process.env.REBASE_DEV_STORAGE),
34
+ hooks: optional(process.env.REBASE_DEV_HOOKS),
31
35
  functions: optional(process.env.REBASE_DEV_FUNCTIONS),
32
36
  crons: optional(process.env.REBASE_DEV_CRONS),
33
37
  schema: optional(process.env.REBASE_DEV_SCHEMA),
@@ -41,7 +41,6 @@ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
41
41
  # Copy workspace packages. Every workspace the lockfile has an importer for,
42
42
  # so `--frozen-lockfile` below sees the same set of packages it was written from.
43
43
  COPY backend ./backend
44
- COPY config ./config
45
44
  # {{#frontend}}
46
45
  COPY frontend ./frontend
47
46
  # {{/frontend}}
@@ -55,8 +54,7 @@ COPY rebase.json ./
55
54
  # Install all deps (including devDependencies for build)
56
55
  RUN pnpm install --frozen-lockfile
57
56
 
58
- # Build config first, then the rest: both the frontend and the backend import it.
59
- RUN pnpm --filter "*-config" run build
57
+ # Build the frontend, then the backend.
60
58
  # {{#frontend}}
61
59
  # The image serves the built site itself (see the `serveSPA` call in
62
60
  # backend/src/index.ts), so the frontend is built here rather than deployed
@@ -87,7 +85,6 @@ WORKDIR /app
87
85
  COPY --from=builder /app/package.json /app/pnpm-lock.yaml /app/pnpm-workspace.yaml /app/.npmrc /app/rebase.json ./
88
86
  COPY --from=builder /app/node_modules ./node_modules
89
87
  COPY --from=builder /app/backend ./backend
90
- COPY --from=builder /app/config ./config
91
88
  # {{#frontend}}
92
89
  # The built site only — its sources and devDependencies stay in the builder.
93
90
  COPY --from=builder /app/frontend/dist ./frontend/dist
@@ -24,7 +24,7 @@ const __dirname = path.dirname(__filename);
24
24
  *
25
25
  * A fixed relative path can't work in both modes: in dev this file runs from
26
26
  * source at `backend/src/env.ts`, but the compiled output lives at
27
- * `backend/dist/backend/src/env.js` — two directories deeper — so
27
+ * `backend/dist/src/env.js` — one directory deeper — so
28
28
  * `../../.env` points at a file that doesn't exist in production. Walking up
29
29
  * finds the root `.env` from either location.
30
30
  */
@@ -24,15 +24,17 @@ import {
24
24
  import { declaredDataSources, declaredStorageSources } from "@rebasepro/types";
25
25
  // Side-effect import: declaring is what registers, so anything that dropped
26
26
  // this as "unused" would leave the backend with no buckets — silently.
27
- import "../../config/resources";
28
- // {{#collections}}
27
+ import "../resources";
28
+ // {{#tables}}
29
29
  import { enums, relations, tables } from "./schema.generated";
30
- // {{/collections}}
31
- import { storageAuthorize } from "../../config/storage";
30
+ // {{/tables}}
31
+ // {{#storage}}
32
+ import { storageAuthorize } from "../storage";
33
+ // {{/storage}}
34
+ // {{#hooks}}
35
+ import { hooks } from "../hooks";
36
+ // {{/hooks}}
32
37
  import { env } from "./env";
33
- // {{#collections}}
34
- import usersCollection from "../../config/collections/users";
35
- // {{/collections}}
36
38
 
37
39
  const __filename = fileURLToPath(import.meta.url);
38
40
  const __dirname = path.dirname(__filename);
@@ -41,9 +43,9 @@ const __dirname = path.dirname(__filename);
41
43
  * The project root: the nearest directory holding `rebase.json`.
42
44
  *
43
45
  * Walked up to rather than counted, because this file runs from two depths —
44
- * `backend/src` under `rebase dev`, `backend/dist/backend/src` compiled — and
45
- * a fixed `../..` from the compiled file is `backend/dist`, where local uploads
46
- * then landed and the next build wiped them.
46
+ * `backend/src` under `rebase dev`, `backend/dist/src` compiled — and a fixed
47
+ * `../..` from the compiled file is `backend/`, where local uploads then
48
+ * landed beside the code.
47
49
  */
48
50
  function findProjectRoot(from: string): string {
49
51
  for (let dir = from; ; dir = path.dirname(dir)) {
@@ -54,7 +56,7 @@ function findProjectRoot(from: string): string {
54
56
  const projectRoot = findProjectRoot(__dirname);
55
57
 
56
58
  // Which databases and buckets this project has, read from the declarations in
57
- // `config/resources.ts`. One declaration site, so this process, the platform
59
+ // `backend/resources.ts`. One declaration site, so this process, the platform
58
60
  // and the frontend all read the same list. A project that declares none gets
59
61
  // one default source of each, from the plain unsuffixed variables.
60
62
  const dataSources = declaredDataSources();
@@ -138,7 +140,7 @@ app.use("/*", overridableSecurityHeaders());
138
140
  //
139
141
  // Doing this by hand — one `createPostgresDatabaseConnection(env.DATABASE_URL)`
140
142
  // — is what this file used to do, and it quietly broke the moment anyone
141
- // declared a second database: collections routed to it fell back to the default
143
+ // declared a second database: tables routed to it fell back to the default
142
144
  // driver and their rows landed in the wrong database, behind a server that
143
145
  // looked healthy.
144
146
  const resolvedDataSources = resolveDataSources(process.env, dataSources);
@@ -157,7 +159,7 @@ async function startServer() {
157
159
  // Passed only when the directory exists, because a configured `cronsDir`
158
160
  // with nothing in it mounts the cron routes and warns at every boot.
159
161
  // Sibling-relative like `functionsDir`: both compile alongside this file, so
160
- // the same path is right from source and from `backend/dist/backend/src`.
162
+ // the same path is right from source and from `backend/dist/src`.
161
163
  const cronsDir = path.resolve(__dirname, "../crons");
162
164
 
163
165
  // Open a connection per declared database. Sequential, and a failure on the
@@ -165,42 +167,46 @@ async function startServer() {
165
167
  // server this process is about to abandon.
166
168
  const drivers = await initializeDataSources(
167
169
  resolvedDataSources,
168
- // {{#collections}}
170
+ // {{#tables}}
169
171
  { tables, enums, relations },
170
- // {{/collections}}
171
- // {{^collections}}
172
- // No generated schema: this project declares no collections in code.
172
+ // {{/tables}}
173
+ // {{^tables}}
174
+ // No generated schema: this project declares no tables in code.
173
175
  undefined,
174
- // {{/collections}}
176
+ // {{/tables}}
175
177
  [__dirname]
176
178
  );
177
179
 
178
180
  const backend = await initializeRebaseBackend({
179
- // {{#collections}}
180
- collectionsDir: path.resolve(__dirname, "../../config/collections"),
181
- // {{/collections}}
182
- // {{^collections}}
183
- // No `collectionsDir`: this project declares no collections in code, so
184
- // the server derives them from the live database schema at boot —
185
- // exactly what the managed runtime did for it.
186
- // {{/collections}}
181
+ // {{#tables}}
182
+ // The tables `backend/schema/index.ts` exports, loaded at boot through
183
+ // the same loader the managed runtime uses — and the directory the
184
+ // schema editor writes to. Sibling-relative, so it is `backend/schema`
185
+ // from source and `backend/dist/schema` compiled.
186
+ schemaDir: path.resolve(__dirname, "../schema"),
187
+ // {{/tables}}
188
+ // {{^tables}}
189
+ // No `schemaDir`: this project declares no tables in code, so the
190
+ // server derives them from the live database schema at boot — exactly
191
+ // what the managed runtime did for it.
192
+ // {{/tables}}
193
+ // {{#hooks}}
194
+ // Global table hooks, from backend/hooks.ts: run for every table.
195
+ hooks,
196
+ // {{/hooks}}
187
197
  functionsDir: path.resolve(__dirname, "../functions"),
188
198
  cronsDir: fs.existsSync(cronsDir) ? cronsDir : undefined,
189
199
  server,
190
200
  app,
191
201
  // One bootstrapper per data source, each registered under its own key —
192
- // the key is exactly what `collection.dataSource` routes against. Only
202
+ // the key is exactly what a table's `database` routes against. Only
193
203
  // the default source is handed the generated schema, which describes
194
204
  // this project's tables and they live in the default database.
195
205
  bootstrappers: drivers.map(driver => driver.bootstrapper),
206
+ // Users live in the table `backend/schema` defines with
207
+ // `defineAuthTable`; without one, auth falls back to its own default
208
+ // users table — the same fallback a headless bundle gets.
196
209
  auth: {
197
- // {{#collections}}
198
- collection: usersCollection,
199
- // {{/collections}}
200
- // {{^collections}}
201
- // No users collection is declared here, so auth falls back to its
202
- // own default users table — the same fallback a headless bundle gets.
203
- // {{/collections}}
204
210
  jwtSecret,
205
211
  accessExpiresIn: env.JWT_ACCESS_EXPIRES_IN,
206
212
  refreshExpiresIn: env.JWT_REFRESH_EXPIRES_IN,
@@ -256,9 +262,15 @@ pass: env.SMTP_PASS! }
256
262
  // Storage is not under row-level security, so this hook IS its access
257
263
  // model — the server refuses to boot in production without one, because
258
264
  // "signed in" would otherwise be the only thing between a visitor and
259
- // every file in the bucket. See config/storage.ts, which also shows the
265
+ // every file in the bucket. See backend/storage.ts, which also shows the
260
266
  // multi-tenant (per-owner) shape and the two escape hatches.
267
+ // {{#storage}}
261
268
  storageAuthorize,
269
+ // {{/storage}}
270
+ // {{^storage}}
271
+ // No backend/storage.ts: add one exporting `storageAuthorize` before
272
+ // configuring a bucket in production, or the server refuses to boot.
273
+ // {{/storage}}
262
274
  history: true
263
275
  });
264
276
 
@@ -311,15 +323,16 @@ pass: env.SMTP_PASS! }
311
323
  // {{#frontend}}
312
324
  // Serve the frontend in production.
313
325
  //
314
- // Four levels up, not two: in production this file runs compiled, from
315
- // `backend/dist/backend/src`. The paths above are the same in both modes
316
- // because `config/` is compiled alongside this file; `frontend/dist` is not
317
- // in the compiled tree at all, so it stays where the repository put it.
326
+ // Three levels up, not two: in production this file runs compiled, from
327
+ // `backend/dist/src`. The paths above are the same in both modes because
328
+ // `schema/` and `functions/` are compiled alongside this file;
329
+ // `frontend/dist` is not in the compiled tree at all, so it stays where the
330
+ // repository put it.
318
331
  // `serveSPA` only warns when the path is wrong, which is why the Dockerfile
319
332
  // that builds this image also copies `frontend` — verify a mount by
320
333
  // fetching `/`, never by reading the log.
321
334
  if (isProduction) {
322
- serveSPA(app, { frontendPath: path.resolve(__dirname, "../../../../frontend/dist") });
335
+ serveSPA(app, { frontendPath: path.resolve(__dirname, "../../../frontend/dist") });
323
336
  }
324
337
  // {{/frontend}}
325
338
 
@@ -65,7 +65,7 @@ services:
65
65
  CORS_ORIGINS: ${CORS_ORIGINS:?set CORS_ORIGINS to the origin you browse to}
66
66
  # A durable named volume, which is the case this flag acknowledges. It is
67
67
  # mounted at /storage, one level above STORAGE_PATH, because every bucket
68
- # declared in config/resources.ts gets a directory beside this one —
68
+ # declared in backend/resources.ts gets a directory beside this one —
69
69
  # bucket("media") is /storage/uploads__media — and all of them belong on
70
70
  # the volume. The Dockerfile creates /storage for the `rebase` user.
71
71
  STORAGE_PATH: /storage/uploads
@@ -3,9 +3,9 @@
3
3
  A headless Rebase backend: a REST API, auth, storage, realtime and backups over
4
4
  your PostgreSQL database.
5
5
 
6
- There are no collection files. The server reads your database schema at boot and
7
- serves your tables, so the API follows your migrations — change the schema,
8
- restart the backend, and the endpoints change with it.
6
+ There is no `backend/schema/` directory. The server reads your database schema
7
+ at boot and serves your tables, so the API follows your migrations — change the
8
+ schema, restart the backend, and the endpoints change with it.
9
9
 
10
10
  ## Serving a table
11
11
 
@@ -45,11 +45,11 @@ project's path rather than fixed, so several Rebase projects can run at once,
45
45
  and `PORT` in `.env` applies to `rebase start`, not here.
46
46
 
47
47
  - API: `<the printed URL>/api/data/<table>` — once a table is served
48
- - Docs: `<the printed URL>/api/swagger` — likewise
48
+ - Docs: `<the printed URL>/api/docs` — likewise; the OpenAPI document of the tables you may see, for a signed-in caller. Set `REBASE_ENABLE_SWAGGER=true` to publish it to everyone with the Swagger UI at `/api/swagger`
49
49
  - Health: `<the printed URL>/health`
50
50
 
51
51
  A headless project starts with no tables, so the first two answer
52
- `404 NO_COLLECTIONS` until you create one and restart — the box `rebase dev`
52
+ `404 NO_TABLES` until you create one and restart — the box `rebase dev`
53
53
  prints says the same thing. See [Serving a table](#serving-a-table).
54
54
 
55
55
  There is no database to install: with no `DATABASE_URL` set, `rebase dev` runs a
@@ -65,14 +65,41 @@ import { createRebaseClient } from "@rebasepro/client";
65
65
  // The URL `rebase dev` printed. `pnpm example` reads it from .rebase-dev-url
66
66
  // for you rather than hardcoding a port.
67
67
  const rebase = createRebaseClient({ baseUrl: process.env.REBASE_URL! });
68
- const posts = await rebase.data.collection("posts").find();
68
+ const posts = await rebase.data.table("posts").find();
69
+ ```
70
+
71
+ ## Declaring your tables in code
72
+
73
+ The one-line switch: create `backend/schema/index.ts`. Once it exists, the
74
+ tables it exports are the schema — `pnpm dev` creates and migrates them, and the
75
+ server serves those rather than reading the database. `pnpm schema:introspect`
76
+ writes that directory from the tables you already have, one
77
+ `defineTable(...)` per table, each with its row-level security written out:
78
+
79
+ ```ts
80
+ // backend/schema/posts.ts
81
+ import { defineTable, col } from "@rebasepro/server/schema";
82
+
83
+ export const posts = defineTable("posts", {
84
+ columns: {
85
+ id: col.uuid().primaryKey().defaultRandom(),
86
+ title: col.text().notNull(),
87
+ authorId: col.text().notNull()
88
+ },
89
+ rls: [{ operations: ["select", "update", "delete"], ownerField: "authorId" }]
90
+ });
91
+ ```
92
+
93
+ ```ts
94
+ // backend/schema/index.ts
95
+ export { posts } from "./posts";
69
96
  ```
70
97
 
71
98
  ## Adding an admin UI later
72
99
 
73
- Nothing here locks you out of it. Add a `config/collections/` directory and a
74
- frontend that renders them: the backend serves an admin panel once collections
75
- exist, because the mode is derived from whether any are declared rather than
76
- set anywhere. There is no `backend/src/index.ts` to edit — the published
77
- runtime boots this project — and `rebase eject` writes one if you want to own
78
- the entrypoint.
100
+ Nothing here locks you out of it. `rebase init` without `--headless` scaffolds
101
+ the same backend with a `frontend/` beside it: `<RebaseCMS />` lists every table
102
+ the backend serves with no code, and `frontend/src/cms/<table>.tsx` customizes
103
+ one with `customizeTable(...)`. There is no `backend/src/index.ts` to edit — the
104
+ published runtime boots this project — and `rebase eject` writes one if you want
105
+ to own the entrypoint.