@rebasepro/server-postgres 0.29.0 → 0.29.1

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 (109) hide show
  1. package/dist/{BranchService-JiYJ_n9E.js → BranchService-BIIBF5ZL.js} +3 -3
  2. package/dist/{BranchService-JiYJ_n9E.js.map → BranchService-BIIBF5ZL.js.map} +1 -1
  3. package/dist/PostgresBackendDriver.d.ts +27 -9
  4. package/dist/PostgresBootstrapper.d.ts +14 -0
  5. package/dist/{backup-cli-D_aKXPyX.js → backup-cli-QcOpmRpQ.js} +3 -3
  6. package/dist/{backup-cli-D_aKXPyX.js.map → backup-cli-QcOpmRpQ.js.map} +1 -1
  7. package/dist/{boot-ddl-D4W9o9xE.js → boot-ddl-BSNpEUOS.js} +2 -2
  8. package/dist/{boot-ddl-D4W9o9xE.js.map → boot-ddl-BSNpEUOS.js.map} +1 -1
  9. package/dist/{cli-console-DPdZCWTi.js → cli-console-DTsm96lW.js} +5 -5
  10. package/dist/{cli-console-DPdZCWTi.js.map → cli-console-DTsm96lW.js.map} +1 -1
  11. package/dist/{cli-errors-D8s4z_3g.js → cli-errors-DwqFRIWz.js} +49 -6
  12. package/dist/{cli-errors-D8s4z_3g.js.map → cli-errors-DwqFRIWz.js.map} +1 -1
  13. package/dist/cli.js +81 -41
  14. package/dist/cli.js.map +1 -1
  15. package/dist/database-preflight-D5JtPt8i.js +151 -0
  16. package/dist/database-preflight-D5JtPt8i.js.map +1 -0
  17. package/dist/db-subcommands.d.ts +1 -1
  18. package/dist/{deferred-index-build-F2GWu009.js → deferred-index-build-B8feKnUj.js} +12 -8
  19. package/dist/deferred-index-build-B8feKnUj.js.map +1 -0
  20. package/dist/{doctor-_g2tHRtG.js → doctor-BaR11xUe.js} +6 -6
  21. package/dist/{doctor-_g2tHRtG.js.map → doctor-BaR11xUe.js.map} +1 -1
  22. package/dist/{ensure-collection-policies-DUpWJb5D.js → ensure-collection-policies-85HiG-k1.js} +8 -8
  23. package/dist/{ensure-collection-policies-DUpWJb5D.js.map → ensure-collection-policies-85HiG-k1.js.map} +1 -1
  24. package/dist/{ensure-collection-tables-BK--gDo6.js → ensure-collection-tables-DR_WcxLA.js} +15 -10
  25. package/dist/ensure-collection-tables-DR_WcxLA.js.map +1 -0
  26. package/dist/{ensure-tables-Bx1DYarz.js → ensure-tables-Dh5UP_Zs.js} +4 -4
  27. package/dist/{ensure-tables-Bx1DYarz.js.map → ensure-tables-Dh5UP_Zs.js.map} +1 -1
  28. package/dist/{enum-labels-kept-DyFE4Gaq.js → enum-labels-kept-DSU8lAnd.js} +3 -3
  29. package/dist/{enum-labels-kept-DyFE4Gaq.js.map → enum-labels-kept-DSU8lAnd.js.map} +1 -1
  30. package/dist/{generate-drizzle-schema-taNTu3xv.js → generate-drizzle-schema-5spbTyQ6.js} +2 -2
  31. package/dist/{generate-drizzle-schema-taNTu3xv.js.map → generate-drizzle-schema-5spbTyQ6.js.map} +1 -1
  32. package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js → generate-drizzle-schema-logic-C5FB7Fpo.js} +2 -2
  33. package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js.map → generate-drizzle-schema-logic-C5FB7Fpo.js.map} +1 -1
  34. package/dist/{generate-files-DbwU8Btx.js → generate-files-Bl3_D_oP.js} +3 -3
  35. package/dist/{generate-files-DbwU8Btx.js.map → generate-files-Bl3_D_oP.js.map} +1 -1
  36. package/dist/{generate-postgres-ddl-logic-ISVgsP34.js → generate-postgres-ddl-logic-BC3JA93M.js} +3 -3
  37. package/dist/{generate-postgres-ddl-logic-ISVgsP34.js.map → generate-postgres-ddl-logic-BC3JA93M.js.map} +1 -1
  38. package/dist/{generated-schema-diff-4lOC0g1_.js → generated-schema-diff-Jm93vyJB.js} +12 -4
  39. package/dist/generated-schema-diff-Jm93vyJB.js.map +1 -0
  40. package/dist/index.d.ts +2 -1
  41. package/dist/index.es.js +20 -12
  42. package/dist/index.es.js.map +1 -1
  43. package/dist/{migrate-baseline-BeepEphh.js → migrate-baseline-BfHmq3vN.js} +49 -4
  44. package/dist/{migrate-baseline-BeepEphh.js.map → migrate-baseline-BfHmq3vN.js.map} +1 -1
  45. package/dist/{migrate-policy-stamps-cYMJ_9Ha.js → migrate-policy-stamps-B4k1ggma.js} +6 -6
  46. package/dist/{migrate-policy-stamps-cYMJ_9Ha.js.map → migrate-policy-stamps-B4k1ggma.js.map} +1 -1
  47. package/dist/{open-rebase-CTNBmmH8.js → open-rebase-CiO_sjMT.js} +465 -80
  48. package/dist/open-rebase-CiO_sjMT.js.map +1 -0
  49. package/dist/open-rebase.d.ts +6 -1
  50. package/dist/{pg-error-utils-BLOVXK67.js → pg-error-utils-D1Nc0UML.js} +2 -2
  51. package/dist/{pg-error-utils-BLOVXK67.js.map → pg-error-utils-D1Nc0UML.js.map} +1 -1
  52. package/dist/{plan-schema-CMNWvqIa.js → plan-schema-BYxOzflz.js} +89 -9
  53. package/dist/plan-schema-BYxOzflz.js.map +1 -0
  54. package/dist/{policy-drift-IjD2AUD-.js → policy-drift-DKuTJHfc.js} +2 -2
  55. package/dist/{policy-drift-IjD2AUD-.js.map → policy-drift-DKuTJHfc.js.map} +1 -1
  56. package/dist/{push-index-prebuild-CIvajIrL.js → push-index-prebuild-bqXimSZz.js} +4 -4
  57. package/dist/{push-index-prebuild-CIvajIrL.js.map → push-index-prebuild-bqXimSZz.js.map} +1 -1
  58. package/dist/{push-kept-defaults-CLbsuSmo.js → push-kept-defaults-CN9R8cHf.js} +2 -2
  59. package/dist/{push-kept-defaults-CLbsuSmo.js.map → push-kept-defaults-CN9R8cHf.js.map} +1 -1
  60. package/dist/{push-legacy-renames-DeW_HTLJ.js → push-legacy-renames-CU_UYPbz.js} +4 -4
  61. package/dist/{push-legacy-renames-DeW_HTLJ.js.map → push-legacy-renames-CU_UYPbz.js.map} +1 -1
  62. package/dist/{push-policy-plan--oRXOj4X.js → push-policy-plan-JcyK94bc.js} +4 -4
  63. package/dist/{push-policy-plan--oRXOj4X.js.map → push-policy-plan-JcyK94bc.js.map} +1 -1
  64. package/dist/{render-ddl-CzVcbbR1.js → render-ddl-DCdVP-pQ.js} +27 -10
  65. package/dist/render-ddl-DCdVP-pQ.js.map +1 -0
  66. package/dist/request-role-cli-DSdRtvgH.js +260 -0
  67. package/dist/request-role-cli-DSdRtvgH.js.map +1 -0
  68. package/dist/request-role-cli.d.ts +86 -0
  69. package/dist/request-role-migration-D9BZ5Uba.js +150 -0
  70. package/dist/request-role-migration-D9BZ5Uba.js.map +1 -0
  71. package/dist/rls-enforcement-BO618rnr.js +992 -0
  72. package/dist/rls-enforcement-BO618rnr.js.map +1 -0
  73. package/dist/rls-settings-De5NoHHy.js +211 -0
  74. package/dist/rls-settings-De5NoHHy.js.map +1 -0
  75. package/dist/schema/doctor-cli.js +144 -6
  76. package/dist/schema/doctor-cli.js.map +1 -1
  77. package/dist/schema/doctor-database.d.ts +27 -0
  78. package/dist/schema/generate-drizzle-schema.js +1 -1
  79. package/dist/schema/generate-postgres-ddl.js +1 -1
  80. package/dist/schema/introspect-db.js +1 -1
  81. package/dist/schema/plan/diff-plan.d.ts +6 -1
  82. package/dist/schema/plan/render-ddl.d.ts +10 -3
  83. package/dist/schema/plan/tenant-keep-trigger.d.ts +9 -0
  84. package/dist/schema/plan/types.d.ts +15 -0
  85. package/dist/schema/plan/updated-at-trigger.d.ts +1 -1
  86. package/dist/schema/plan/view-names.d.ts +6 -0
  87. package/dist/schema/rls-bootstrap-sql.d.ts +23 -0
  88. package/dist/security/caller-sql-columns.d.ts +60 -0
  89. package/dist/security/caller-sql.d.ts +8 -0
  90. package/dist/security/database-preflight.d.ts +24 -0
  91. package/dist/security/request-role-migration.d.ts +36 -0
  92. package/dist/security/rls-enforcement.d.ts +191 -21
  93. package/dist/security/rls-settings.d.ts +177 -0
  94. package/dist/services/dataService.d.ts +2 -0
  95. package/dist/services/realtimeService.d.ts +3 -0
  96. package/dist/services/view-access.d.ts +2 -2
  97. package/dist/view-names-Dscp6--B.js +24 -0
  98. package/dist/view-names-Dscp6--B.js.map +1 -0
  99. package/dist/{websocket-D2y88dOa.js → websocket-B33YjKhs.js} +3 -3
  100. package/dist/{websocket-D2y88dOa.js.map → websocket-B33YjKhs.js.map} +1 -1
  101. package/package.json +7 -7
  102. package/dist/deferred-index-build-F2GWu009.js.map +0 -1
  103. package/dist/ensure-collection-tables-BK--gDo6.js.map +0 -1
  104. package/dist/generated-schema-diff-4lOC0g1_.js.map +0 -1
  105. package/dist/open-rebase-CTNBmmH8.js.map +0 -1
  106. package/dist/plan-schema-CMNWvqIa.js.map +0 -1
  107. package/dist/render-ddl-CzVcbbR1.js.map +0 -1
  108. package/dist/rls-enforcement-jZTv1yci.js +0 -534
  109. package/dist/rls-enforcement-jZTv1yci.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generated-schema-diff-Jm93vyJB.js","names":[],"sources":["../src/schema/introspect-runtime.ts","../src/schema/dynamic-tables.ts","../src/schema/config-relations.ts","../src/schema/catalogue-schema.ts","../src/schema/generated-schema-diff.ts"],"sourcesContent":["/**\n * Runtime introspection — builds collections in memory from the live database.\n *\n * This is what makes BaaS mode work with zero configuration: instead of loading\n * collection files from disk, the server reads `information_schema` at boot and\n * derives a collection per table, so any database is served over REST without a\n * single config file.\n *\n * Distinct from `introspect-db.ts`, which runs the same queries but emits\n * TypeScript *source* for a developer to edit and commit (declared collections). The two\n * share the mapping helpers in `introspect-db-logic.ts` so a table is described\n * the same way whether it was generated or introspected.\n */\nimport type { PostgresCollectionConfig } from \"@rebasepro/types\";\n\nimport {\n TableRow,\n TableColumn,\n EnumValue,\n PrimaryKeyRow,\n ForeignKeyRow,\n TableMeta,\n buildTablesMap,\n buildEnumMap,\n identifyJoinTables,\n singularize,\n mapPgType,\n getIconForTable\n} from \"./introspect-db-logic\";\nimport { humanize } from \"./introspect-db-naming\";\nimport { firstFreeKey, toWireKey } from \"@rebasepro/utils\";\n\nexport interface IntrospectedSchema {\n tablesMap: Map<string, TableMeta>;\n enumMap: Map<string, string[]>;\n joinTables: Set<string>;\n}\n\n/** Whether a table carries an authorization model of its own. */\nexport interface TableRlsStatus {\n table: string;\n /** ALTER TABLE … ENABLE ROW LEVEL SECURITY has been run. */\n rlsEnabled: boolean;\n /** Policies attached to it. RLS enabled with none = nothing is visible. */\n policyCount: number;\n}\n\n/**\n * Read the RLS posture of each table in a schema.\n *\n * This is what decides whether baas mode may serve a table. A table with RLS\n * disabled has no authorization model: since every authenticated request runs\n * as `rebase_user`, and that role is granted DML on the schema, serving such a\n * table hands every row to every logged-in user.\n */\nexport async function readRlsStatus(client: Queryable, pgSchema: string): Promise<Map<string, TableRlsStatus>> {\n const { rows } = await client.query<{ table: string; rls_enabled: boolean; policy_count: string | number }>(\n `SELECT c.relname AS table,\n c.relrowsecurity AS rls_enabled,\n (SELECT count(*) FROM pg_policy p WHERE p.polrelid = c.oid) AS policy_count\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = $1 AND c.relkind = 'r'`,\n [pgSchema]\n );\n\n return new Map(\n rows.map((r) => [\n r.table,\n { table: r.table, rlsEnabled: r.rls_enabled === true, policyCount: Number(r.policy_count ?? 0) }\n ])\n );\n}\n\n/** Minimal query surface — satisfied by pg.Client and pg.Pool alike. */\nexport interface Queryable {\n query<R>(text: string, values?: unknown[]): Promise<{ rows: R[] }>;\n}\n\n/**\n * Read tables, columns, enums, primary keys and foreign keys for a schema.\n * Mirrors the queries in introspect-db.ts.\n */\nexport async function introspectSchema(\n client: Queryable,\n pgSchema: string,\n /**\n * Read views and materialized views too, as tables to read from — what\n * the runtime catalogue needs for collections that declare `view`. Off\n * for introspection that turns relations into collections, where a view\n * is not one.\n */\n options: { views?: boolean } = {}\n): Promise<IntrospectedSchema> {\n const { rows: tables } = await client.query<TableRow>(\n `SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = $1 AND table_type ${options.views ? \"IN ('BASE TABLE', 'VIEW')\" : \"= 'BASE TABLE'\"}\n AND table_name NOT LIKE 'drizzle_%'\n AND table_name NOT LIKE 'rebase_%'\n ${options.views ? `UNION\n SELECT c.relname AS table_name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = $1 AND c.relkind = 'm'\n AND COALESCE(obj_description(c.oid, 'pg_class'), '') NOT LIKE 'rebase:view-rows:%'` : \"\"}\n ORDER BY table_name`,\n [pgSchema]\n );\n\n const { rows: columns } = await client.query<TableColumn>(\n `SELECT\n c.table_name,\n c.column_name,\n c.data_type,\n c.udt_name,\n c.is_nullable,\n c.column_default,\n -- A stored generated column must be declared as one, or drizzle\n -- writes DEFAULT into it on every INSERT. Postgres tolerates that\n -- today; the generated module has always declared them properly,\n -- and the runtime tables are built to match it.\n c.is_generated,\n c.generation_expression,\n (SELECT a.atttypmod FROM pg_attribute a\n JOIN pg_class pc ON a.attrelid = pc.oid\n WHERE pc.relname = c.table_name\n AND a.attname = c.column_name\n AND pc.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = c.table_schema)) as atttypmod\n FROM information_schema.columns c\n WHERE c.table_schema = $1\n -- A table has no column of that name (it is a system column); the\n -- gate of a materialized view carries one for fingerprint(), and it\n -- is not the collection's.\n AND NOT (c.column_name = 'xmin' AND EXISTS (\n SELECT 1 FROM information_schema.views v\n WHERE v.table_schema = c.table_schema AND v.table_name = c.table_name))\n ${options.views ? `UNION ALL\n -- A materialized view is in neither information_schema.tables nor\n -- .columns: its columns, in the same shape, from the catalogue.\n SELECT c.relname, a.attname,\n CASE WHEN t.typcategory = 'A' THEN 'ARRAY' WHEN t.typtype = 'e' THEN 'USER-DEFINED'\n ELSE format_type(a.atttypid, NULL) END,\n t.typname, CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END, NULL, 'NEVER', NULL, a.atttypmod\n FROM pg_attribute a\n JOIN pg_class c ON c.oid = a.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n JOIN pg_type t ON t.oid = a.atttypid\n WHERE n.nspname = $1 AND c.relkind = 'm' AND a.attnum > 0 AND NOT a.attisdropped\n AND COALESCE(obj_description(c.oid, 'pg_class'), '') NOT LIKE 'rebase:view-rows:%'` : \"\"}`,\n [pgSchema]\n );\n\n const { rows: enumValues } = await client.query<EnumValue>(\n `SELECT t.typname AS enum_name,\n e.enumlabel AS enum_value,\n e.enumsortorder AS sort_order\n FROM pg_type t\n JOIN pg_enum e ON t.oid = e.enumtypid\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE n.nspname = $1\n ORDER BY t.typname, e.enumsortorder`,\n [pgSchema]\n );\n\n const { rows: pks } = await client.query<PrimaryKeyRow>(\n `SELECT t.relname as table_name, a.attname as column_name\n FROM pg_index i\n JOIN pg_attribute a ON a.attrelid = i.indrelid\n AND a.attnum = ANY(i.indkey)\n JOIN pg_class t ON t.oid = i.indrelid\n JOIN pg_namespace n ON n.oid = t.relnamespace\n WHERE i.indisprimary AND n.nspname = $1`,\n [pgSchema]\n );\n\n const { rows: fks } = await client.query<ForeignKeyRow>(\n `SELECT\n tc.table_name,\n kcu.column_name,\n ccu.table_name AS foreign_table_name,\n ccu.column_name AS foreign_column_name\n FROM information_schema.table_constraints AS tc\n JOIN information_schema.key_column_usage AS kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n JOIN information_schema.constraint_column_usage AS ccu\n ON ccu.constraint_name = tc.constraint_name\n AND ccu.table_schema = tc.table_schema\n WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = $1`,\n [pgSchema]\n );\n\n const tablesMap = buildTablesMap(tables, columns, pks, fks);\n return {\n tablesMap,\n enumMap: buildEnumMap(enumValues),\n joinTables: identifyJoinTables(tablesMap)\n };\n}\n\n/** Derive the `isId` flavour for a primary-key column. */\nfunction idKindFor(col: TableColumn, propType: string): \"uuid\" | \"increment\" | true {\n if (col.data_type.toLowerCase() === \"uuid\") return \"uuid\";\n if (propType === \"number\") return \"increment\";\n return true;\n}\n\nfunction buildProperties(\n meta: TableMeta,\n enumMap: Map<string, string[]>\n): Record<string, Record<string, unknown>> {\n const properties: Record<string, Record<string, unknown>> = {};\n const takenKeys = new Set<string>();\n\n for (const col of meta.columns) {\n const isPk = meta.pks.includes(col.column_name);\n // Foreign keys surface as relations below, unless they are also part of\n // the primary key, in which case the column itself must stay.\n const isFk = meta.fks.some((fk) => fk.column_name === col.column_name);\n if (isFk && !isPk) continue;\n\n const enumValues = enumMap.get(col.udt_name);\n const isEnum = col.data_type === \"USER-DEFINED\" && enumValues !== undefined;\n const isVector = col.udt_name === \"vector\";\n const propType = isEnum ? \"string\" : isVector ? \"vector\" : mapPgType(col.data_type);\n\n const property: Record<string, unknown> = {\n name: humanize(col.column_name),\n columnName: col.column_name,\n type: propType\n };\n\n // The wire name, with `columnName` above carrying the column. The two\n // are different names for different things — this used to serve the\n // column, so a runtime-introspected collection answered `user_id` while\n // every authored one beside it answered `displayName`.\n //\n // `user_id` and `userId` as two real columns camel-case to one key, so\n // the first free candidate wins and the second falls back to its own\n // column name, then to a numbered tail. Never dropped, and stable for a\n // given database: columns arrive in ordinal order.\n const key = firstFreeKey([toWireKey(col.column_name), col.column_name], takenKeys);\n takenKeys.add(key);\n\n if (isPk) {\n property.isId = idKindFor(col, propType);\n } else if (col.is_nullable === \"NO\" && col.column_default === null) {\n property.validation = { required: true };\n }\n\n if (isEnum && enumValues) {\n property.enum = enumValues.map((value) => ({ id: value, label: humanize(value) }));\n }\n\n properties[key] = property;\n }\n\n return properties;\n}\n\n/**\n * Owning relations, derived from this table's foreign keys — the same shape\n * `generateCollectionFile` writes into a collection file: a `relation` property\n * whose nested descriptor carries `kind`, a `target` thunk and the `localKey`.\n *\n * The shape is load-bearing, not cosmetic. `resolveCollectionRelations` reads\n * relations from `property.relation` and `resolveRelation` requires `target` to\n * be a thunk; this used to emit `target`/`cardinality`/`localKey` flat on the\n * property with the slug as a bare string, which satisfies neither. Nothing\n * threw — the resolver simply skipped every such property and reported that the\n * collection had no relations. So an introspected BaaS collection had its FK\n * columns removed from `properties` (they \"surface as relations\") and then no\n * resolvable relation to surface as, which is why writing the FK column\n * directly came back as `has no field 'product_id'`: `assertKnownWriteFields`\n * learns that column from the resolved relation's `localKey`.\n *\n * The thunk closes over the collections being built in this same pass rather\n * than importing a module, which is what a runtime introspection has instead of\n * generated files. It is called lazily, after the map is fully populated, so a\n * table may reference one introspected later.\n */\nfunction buildRelations(\n meta: TableMeta,\n slugByTable: Map<string, string>,\n collectionBySlug: Map<string, PostgresCollectionConfig>\n): Record<string, Record<string, unknown>> {\n const relations: Record<string, Record<string, unknown>> = {};\n\n for (const fk of meta.fks) {\n const targetSlug = slugByTable.get(fk.foreign_table_name);\n if (!targetSlug) continue;\n\n // Strip the conventional _id suffix: author_id -> author\n let key = toWireKey(fk.column_name.replace(/_id$/, \"\"));\n if (meta.pks.includes(fk.column_name) && key === fk.column_name) {\n // The FK is also the PK and its name doesn't imply a relation (e.g.\n // \"id\"), so naming the relation after the column would collide with\n // the primary-key property.\n key = fk.foreign_table_name;\n }\n\n relations[key] = {\n name: humanize(key),\n type: \"relation\",\n relation: {\n kind: \"belongsTo\",\n target: () => collectionBySlug.get(targetSlug),\n localKey: fk.column_name\n }\n };\n }\n\n return relations;\n}\n\n/**\n * Turn an introspected schema into collections.\n *\n * Join tables are skipped: they carry no identity of their own and exist to\n * express a many-to-many edge between two other tables.\n */\nexport function buildCollectionsFromSchema(\n { tablesMap, enumMap, joinTables }: IntrospectedSchema,\n pgSchema: string\n): PostgresCollectionConfig[] {\n const slugByTable = new Map<string, string>();\n for (const tableName of tablesMap.keys()) {\n if (!joinTables.has(tableName)) slugByTable.set(tableName, tableName);\n }\n\n const collections: PostgresCollectionConfig[] = [];\n // Filled as we go; the relation thunks read it lazily, so a table may point\n // at one that has not been built yet at the moment its relation is created.\n const collectionBySlug = new Map<string, PostgresCollectionConfig>();\n\n for (const [tableName, meta] of tablesMap) {\n if (joinTables.has(tableName)) continue;\n\n const collectionName = humanize(tableName);\n const collection = {\n name: collectionName,\n singularName: singularize(collectionName),\n slug: tableName,\n table: tableName,\n schema: pgSchema,\n icon: getIconForTable(tableName),\n properties: {\n ...buildProperties(meta, enumMap),\n ...buildRelations(meta, slugByTable, collectionBySlug)\n }\n // A collection synthesised from a catalogue read, not authored.\n // `PostgresCollectionConfig` is generic over the row type `M`, and\n // there is no `M` here — the columns were discovered a moment ago —\n // so the object is built from the fields introspection can supply\n // and asserted into the config the rest of the server consumes.\n } as unknown as PostgresCollectionConfig;\n\n collections.push(collection);\n collectionBySlug.set(tableName, collection);\n }\n\n return collections;\n}\n\n/** Introspect the database and return ready-to-serve collections. */\nexport async function introspectCollections(\n client: Queryable,\n pgSchema: string\n): Promise<PostgresCollectionConfig[]> {\n const schema = await introspectSchema(client, pgSchema);\n return buildCollectionsFromSchema(schema, pgSchema);\n}\n","/**\n * Build drizzle tables at runtime from an introspected schema.\n *\n * **Every** data source's tables are built here, from `information_schema`,\n * after boot-ensure has run — a project with declared collections included. The\n * committed `schema.generated.ts` is a build artefact for Atlas, `db push`,\n * `eject` and user code; the runtime does not read it for its tables, because a\n * file that is one commit behind the database used to change what the server\n * served (a renamed foreign-key column 500'd every request, a lost relation\n * silently emptied a list). See `catalogue-schema.ts` for the caller.\n *\n * These are handed to drizzle as its schema, which keeps the relational query\n * path (`db.query.*`) working; without them FetchService would fall back to\n * plain selects and lose relation loading.\n *\n * Two things a caller has to supply for the tables to match what the generated\n * module used to produce, both about *names*: the Drizzle object is keyed by the\n * wire name of a column and not by the column (`authorId`, not `author_id`), and\n * a relation is keyed by the collection's own relation key rather than by a\n * guess made from the foreign key. Both come from the collections — see\n * `columnKeysFromCollections` and `buildDrizzleRelationsFromCollections`.\n */\nimport {\n bigint,\n boolean,\n char,\n cidr,\n customType,\n date,\n doublePrecision,\n geometry,\n inet,\n integer,\n interval,\n json,\n jsonb,\n line,\n macaddr,\n macaddr8,\n numeric,\n pgSchema,\n pgTable,\n point,\n primaryKey,\n real,\n smallint,\n text,\n time,\n timestamp,\n uuid,\n varchar,\n vector,\n type PgColumnBuilderBase,\n type PgTable\n} from \"drizzle-orm/pg-core\";\n\nimport { getTableColumns, relations, sql, type Relations } from \"drizzle-orm\";\nimport { toWireKey } from \"@rebasepro/utils\";\n\nimport type { TableColumn, TableMeta } from \"./introspect-db-logic\";\n\n/**\n * The Drizzle object key a column is served under, given its table.\n *\n * Defaults to the column name — right for a junction table and for a database\n * nothing declares — and is supplied from the collections wherever there is\n * one, because there the wire name is the property key. Every read and write\n * path in this driver indexes tables and rows by that key.\n */\nexport type ColumnKeyResolver = (tableName: string, columnName: string) => string;\n\nconst columnNameAsKey: ColumnKeyResolver = (_table, column) => column;\n\n/** drizzle ships no bytea builder; binary must round-trip as a Buffer. */\nconst bytea = customType<{ data: Buffer; driverData: Buffer }>({\n dataType: () => \"bytea\"\n});\n\n/**\n * A full-text search column, declared with its real SQL type.\n *\n * Not cosmetic: `isSearchIndexColumn` asks the column for its type and drops\n * every `tsvector` from the projection, so a search column that fell through to\n * `text` (the old default for an unrecognised type) would be selected, returned\n * to callers, and rendered in the admin as a wall of lexemes. drizzle ships no\n * builder for these two.\n */\nconst tsvector = customType<{ data: string; driverData: string }>({\n dataType: () => \"tsvector\"\n});\n\nconst tsquery = customType<{ data: string; driverData: string }>({\n dataType: () => \"tsquery\"\n});\n\n/**\n * Postgres stores a column's type modifier (varchar length, vector dimensions)\n * in `atttypmod`. For length-carrying string types it is length + VARHDRSZ(4);\n * for pgvector it is the dimension count as-is. -1 means unspecified.\n */\nfunction varlenLength(col: TableColumn): number | undefined {\n return col.atttypmod && col.atttypmod > 4 ? col.atttypmod - 4 : undefined;\n}\n\n/**\n * Map a Postgres type to a drizzle column builder, keyed on `udt_name` — the\n * concrete underlying type, which is exact where `data_type` reports umbrella\n * values like \"ARRAY\" or \"USER-DEFINED\".\n *\n * Unknown types fall back to `text`: the driver still reads and writes them,\n * with the value passing through as a string, which beats dropping the column.\n */\nfunction scalarBuilder(udtName: string, name: string, col: TableColumn): PgColumnBuilderBase {\n switch (udtName) {\n case \"uuid\":\n return uuid(name);\n case \"bool\":\n return boolean(name);\n case \"int2\":\n return smallint(name);\n case \"int4\":\n return integer(name);\n case \"int8\":\n return bigint(name, { mode: \"number\" });\n case \"float4\":\n return real(name);\n case \"float8\":\n return doublePrecision(name);\n case \"numeric\":\n case \"money\":\n return numeric(name);\n case \"json\":\n return json(name);\n case \"jsonb\":\n return jsonb(name);\n case \"date\":\n return date(name);\n case \"time\":\n return time(name);\n case \"timetz\":\n return time(name, { withTimezone: true });\n // `mode: \"string\"`, both of them, because that is what the generated\n // module declared for every `date` property: the value Postgres sent,\n // untouched. Drizzle's default mode is `date`, which parses it into a\n // `Date` — the same instant in a different shape, and a difference that\n // would have appeared only on the read path of a project that changed\n // nothing. (`parsePropertyFromServer` normalises either shape to an ISO\n // string for a declared `date` property, so what a REST caller sees is\n // the same; a raw `db.select()` is where the two differ.)\n case \"timestamp\":\n return timestamp(name, { mode: \"string\" });\n case \"timestamptz\":\n return timestamp(name, { withTimezone: true, mode: \"string\" });\n case \"interval\":\n return interval(name);\n case \"bytea\":\n return bytea(name);\n case \"inet\":\n return inet(name);\n case \"cidr\":\n return cidr(name);\n case \"macaddr\":\n return macaddr(name);\n case \"macaddr8\":\n return macaddr8(name);\n case \"point\":\n return point(name);\n case \"line\":\n return line(name);\n case \"geometry\":\n return geometry(name);\n case \"vector\": {\n // drizzle requires the dimension count; without it fall back to text\n // rather than declaring a vector of unknown width.\n const dimensions = col.atttypmod && col.atttypmod > 0 ? col.atttypmod : undefined;\n return dimensions ? vector(name, { dimensions }) : text(name);\n }\n case \"bpchar\": {\n const length = varlenLength(col);\n return length ? char(name, { length }) : char(name);\n }\n case \"varchar\": {\n const length = varlenLength(col);\n return length ? varchar(name, { length }) : text(name);\n }\n case \"tsvector\":\n return tsvector(name);\n case \"tsquery\":\n return tsquery(name);\n default:\n // Includes text, enums (pg enums are strings on the wire), citext,\n // geography, and anything else this driver hasn't met yet.\n //\n // An enum deliberately stays `text`, which is what the generated\n // module's `pgEnum` column also serves: drizzle does no runtime\n // validation of enum members either way, and Postgres rejects a\n // label it does not have. The difference is only in the type the\n // generated *types* carry, and those come from the collection.\n return text(name);\n }\n}\n\n/**\n * The fluent methods this file calls on a column builder.\n *\n * Drizzle's `PgColumnBuilderBase` exposes none of them by design: they live on\n * the concrete `PgColumnBuilder` subclasses, each generic over the column's\n * TypeScript type, its name and whether it is notNull / hasDefault — a chain\n * resolved when you *write* a schema, and not resolvable when you build one\n * from a catalogue read at runtime, which is all this file does.\n *\n * So a conversion here is irreducible; what was avoidable was doing it four\n * separate times, each declaring its own one-method slice of the builder and\n * each free to disagree with the others about a name or a signature. Declaring\n * the methods as an *extension* of the base also drops the `as unknown as`: the\n * two types overlap, so tsc will still refuse this if drizzle ever gives\n * `PgColumnBuilderBase` a conflicting member.\n */\ninterface FluentColumnBuilder extends PgColumnBuilderBase {\n array(): PgColumnBuilderBase;\n notNull(): PgColumnBuilderBase;\n primaryKey(): PgColumnBuilderBase;\n generatedAlwaysAs(expr: unknown): PgColumnBuilderBase;\n}\n\n/** See {@link FluentColumnBuilder}. */\nconst fluent = (builder: PgColumnBuilderBase): FluentColumnBuilder => builder as FluentColumnBuilder;\n\nfunction columnBuilderFor(col: TableColumn): PgColumnBuilderBase {\n // Array types are named after their element with a leading underscore\n // (_int4 = int4[]), so the element mapping is reused verbatim.\n if (col.udt_name.startsWith(\"_\")) {\n const element = scalarBuilder(col.udt_name.slice(1), col.column_name, col);\n return fluent(element).array();\n }\n return scalarBuilder(col.udt_name, col.column_name, col);\n}\n\n/**\n * Build one drizzle table per introspected table, keyed by table name.\n *\n * @param columnKey how a column is named on the wire — see {@link ColumnKeyResolver}.\n */\nexport function buildDrizzleTablesFromSchema(\n tablesMap: Map<string, TableMeta>,\n pgSchemaName = \"public\",\n columnKey: ColumnKeyResolver = columnNameAsKey\n): Record<string, PgTable> {\n const schema = pgSchemaName === \"public\" ? null : pgSchema(pgSchemaName);\n // The column set is only known at runtime, so drizzle's generic table\n // signature can't be satisfied statically; call it through a loose type.\n const createTable = (schema ? schema.table.bind(schema) : pgTable) as (\n name: string,\n columns: Record<string, PgColumnBuilderBase>,\n extras?: (self: Record<string, unknown>) => unknown[]\n ) => PgTable;\n\n const tables: Record<string, PgTable> = {};\n\n for (const [tableName, meta] of tablesMap) {\n const columns: Record<string, PgColumnBuilderBase> = {};\n const keyOf = new Map<string, string>();\n\n for (const col of meta.columns) {\n let builder = columnBuilderFor(col);\n\n if (col.is_nullable === \"NO\") {\n builder = fluent(builder).notNull();\n }\n // Single-column primary keys are marked inline; composite keys are\n // declared in the table extras below.\n if (meta.pks.length === 1 && meta.pks[0] === col.column_name) {\n builder = fluent(builder).primaryKey();\n }\n // A stored generated column must be left out of every INSERT, which\n // is what `.generatedAlwaysAs` tells drizzle. The expression is\n // carried through so a drizzle-kit run over these tables describes\n // the column it actually found; nothing at runtime evaluates it.\n if (col.is_generated === \"ALWAYS\") {\n builder = fluent(builder).generatedAlwaysAs(sql.raw(col.generation_expression ?? \"\"));\n }\n\n const key = columnKey(tableName, col.column_name);\n keyOf.set(col.column_name, key);\n columns[key] = builder;\n }\n\n const isComposite = meta.pks.length > 1;\n tables[tableName] = createTable(\n tableName,\n columns,\n isComposite\n ? (t) => [primaryKey({ columns: meta.pks.map((pk) => t[keyOf.get(pk) ?? pk]) as never })]\n : undefined\n );\n }\n\n return tables;\n}\n\n/**\n * Build drizzle `relations()` for the foreign keys, so the relational query\n * path can actually load them.\n *\n * FetchService asks drizzle for `with: { <key>: true }`, keyed by the relation\n * property on the collection. Tables alone don't satisfy that — without these,\n * `?include=author` silently returns the raw `author_id` and no author.\n *\n * The keys here must match `buildRelations` in introspect-runtime.ts, which is\n * what names the collection's relation properties.\n */\nexport function buildDrizzleRelationsFromSchema(\n tablesMap: Map<string, TableMeta>,\n tables: Record<string, PgTable>,\n columnKey: ColumnKeyResolver = columnNameAsKey\n): Record<string, Relations> {\n /** Owning side, per table: the `one()` relations from its foreign keys. */\n const owning = new Map<string, { key: string; targetTable: string; fkColumn: string; targetColumn: string; relationName: string }[]>();\n /** Inverse side, per referenced table: the matching `many()` back-references. */\n const inverse = new Map<string, { key: string; sourceTable: string; relationName: string }[]>();\n\n for (const [tableName, meta] of tablesMap) {\n if (!tables[tableName]) continue;\n // The keys the table actually carries — what a relation key must not\n // collide with, since both live in one Drizzle object.\n const columnNames = new Set(meta.columns.map((c) => columnKey(tableName, c.column_name)));\n\n for (const fk of meta.fks) {\n if (!tables[fk.foreign_table_name]) continue;\n\n // Mirrors buildRelations in introspect-runtime: author_id -> author,\n // falling back to the target table when the column name carries no\n // hint. `toWireKey` for the same reason it is there — the two keys\n // must be the same string or the collection advertises a relation key\n // drizzle has never heard of (`author_ref` here, `authorRef` there).\n let key = toWireKey(fk.column_name.replace(/_id$/, \"\"));\n if (meta.pks.includes(fk.column_name) && key === fk.column_name) {\n key = fk.foreign_table_name;\n }\n // A relation key must not shadow a real column.\n if (columnNames.has(key)) continue;\n\n // Pairs the two sides. Drizzle matches a named one() to the many()\n // carrying the same name, and disambiguates multiple foreign keys\n // into the same table.\n const relationName = `${tableName}_${fk.column_name}`;\n\n owning.set(tableName, [\n ...(owning.get(tableName) ?? []),\n {\n key,\n targetTable: fk.foreign_table_name,\n // The Drizzle keys, not the columns: `fields`/`references`\n // index the built table objects, which are keyed by the\n // wire name wherever a collection supplies one.\n fkColumn: columnKey(tableName, fk.column_name),\n targetColumn: columnKey(fk.foreign_table_name, fk.foreign_column_name),\n relationName\n }\n ]);\n\n const backKey = tableName;\n const targetColumns = new Set(\n (tablesMap.get(fk.foreign_table_name)?.columns ?? [])\n .map((c) => columnKey(fk.foreign_table_name, c.column_name))\n );\n if (targetColumns.has(backKey)) continue;\n\n inverse.set(fk.foreign_table_name, [\n ...(inverse.get(fk.foreign_table_name) ?? []),\n { key: backKey, sourceTable: tableName, relationName }\n ]);\n }\n }\n\n const built: Record<string, Relations> = {};\n\n for (const tableName of tablesMap.keys()) {\n const table = tables[tableName];\n const ones = owning.get(tableName) ?? [];\n const manys = inverse.get(tableName) ?? [];\n if (!table || (ones.length === 0 && manys.length === 0)) continue;\n\n built[`${tableName}Relations`] = relations(table, ({ one, many }) => {\n const map: Record<string, unknown> = {};\n\n for (const rel of ones) {\n map[rel.key] = one(tables[rel.targetTable], {\n // `getTableColumns` is drizzle's own accessor for this.\n // Indexing the table object — which is what the casts here\n // were for — also reaches its methods and symbols, so a\n // foreign key named after one of them yields something that\n // is not a column; and the target type they used,\n // `Record<string, never>`, makes every lookup `never`,\n // which is assignable to anything and therefore checks\n // nothing at all.\n fields: [getTableColumns(table)[rel.fkColumn]],\n references: [getTableColumns(tables[rel.targetTable])[rel.targetColumn]],\n relationName: rel.relationName\n });\n }\n\n // Drizzle needs the inverse of every named one(); without it,\n // normalizeRelation throws and the relational path is dead.\n for (const rel of manys) {\n // An inverse must not collide with an owning key on this table.\n if (map[rel.key]) continue;\n map[rel.key] = many(tables[rel.sourceTable], { relationName: rel.relationName });\n }\n\n return map as never;\n });\n }\n\n return built;\n}\n","/**\n * Build drizzle `relations()` for declared collections, from the collections.\n *\n * The heuristic builder in `dynamic-tables.ts` names a relation after the\n * foreign-key column (`author_id` → `author`), which is the only evidence a\n * database offers and is right for BaaS mode. It is wrong for a project that\n * declares its collections: there the relation's name is whatever the author\n * called it, `include=writer` addresses that name, and a relation whose key was\n * guessed from the column simply does not answer to it — the read returns the\n * bare foreign key and no target, silently, which is how a demo lost every\n * relation in its list view while the detail view (a different code path) kept\n * working.\n *\n * So when there are collections, they are the authority for *which* relations\n * exist and what they are called; the live catalogue is the authority for the\n * columns underneath. This is the same pairing `generate-drizzle-schema-logic`\n * emits into `schema.generated.ts` — kind for kind, key for key, and paired by\n * the same {@link sharedRelationName} — only built against tables read back from\n * `information_schema` rather than against a file.\n */\nimport { getTableColumns, relations, type Relations } from \"drizzle-orm\";\nimport type { PgTable } from \"drizzle-orm/pg-core\";\nimport { CollectionConfig, ResolvedRelation, type ResolvedForeignKeyOnTarget } from \"@rebasepro/types\";\nimport { fieldKeyForColumn, getTableName, resolveCollectionRelations } from \"@rebasepro/common\";\nimport { logger } from \"@rebasepro/server\";\n\nimport { sharedRelationName } from \"./relation-names\";\n\n/** A collection's table, with any schema prefix stripped — as the DDL creates it. */\nexport function bareTableName(name: string): string {\n return name.includes(\".\") ? name.split(\".\").pop()! : name;\n}\n\n/**\n * The field key a collection's rows are addressed by, as the generated module\n * spells it: the property marked `isId`, else `id`.\n *\n * Deliberately the config's answer rather than the catalogue's primary key —\n * `references: [users.id]` in the generated file is keyed the same way, and the\n * two have to name the same Drizzle key for a relation to compile at all.\n */\nfunction primaryKeyFieldKey(collection: CollectionConfig): string {\n for (const [key, prop] of Object.entries(collection.properties ?? {})) {\n if (prop && typeof prop === \"object\" && \"isId\" in prop && Boolean((prop as { isId?: unknown }).isId)) {\n return key;\n }\n }\n return \"id\";\n}\n\n/**\n * The field key on the source table that a `hasOne`/`hasMany` foreign key\n * holds: its `sourceKey` when the link names one, else the primary key.\n */\nfunction sourceKeyFieldKey(\n relation: ResolvedForeignKeyOnTarget,\n collection: CollectionConfig\n): string {\n return relation.sourceKey\n ? fieldKeyForColumn(collection, relation.sourceKey)\n : primaryKeyFieldKey(collection);\n}\n\n/**\n * A column of a built table, by its Drizzle key or by its column name.\n *\n * The key is the answer in the ordinary case, and the name is the fallback for\n * the one place a caller holds a column and not a field: a junction table's two\n * foreign keys, which are keyed by column *unless* the project also declares a\n * collection over that table, in which case they are keyed by its property\n * names. Looking both up costs a scan of one table and removes the difference.\n */\nfunction columnOf(table: PgTable | undefined, key: string): unknown {\n if (!table) return undefined;\n // Drizzle's column map is keyed by the JS property name, which is exactly\n // the \"keyed by its property names\" case this function's docblock\n // describes — so `getTableColumns` answers it, and indexing the table\n // object (which also reaches its methods and symbols) was never needed.\n const direct = getTableColumns(table)[key];\n if (direct) return direct;\n for (const column of Object.values(getTableColumns(table))) {\n if ((column as { name?: unknown })?.name === key) return column;\n }\n return undefined;\n}\n\ninterface OneSpec {\n key: string;\n target: PgTable;\n fields: unknown[];\n references: unknown[];\n relationName: string;\n}\n\ninterface ManySpec {\n key: string;\n target: PgTable;\n relationName: string;\n}\n\n/**\n * Drizzle relations for every declared collection, keyed `<table>Relations`.\n *\n * @param collections every collection backed by a table in `tables`\n * @param tables catalogue-built tables, keyed by bare table name\n */\nexport function buildDrizzleRelationsFromCollections(\n collections: CollectionConfig[],\n tables: Record<string, PgTable>\n): Record<string, Relations> {\n const ones = new Map<string, OneSpec[]>();\n const manys = new Map<string, ManySpec[]>();\n /** `<relationName>::<kind>` already emitted on a table — the generator dedupes the same way. */\n const emitted = new Map<string, Set<string>>();\n\n const claim = (table: string, name: string, kind: string): boolean => {\n const seen = emitted.get(table) ?? new Set<string>();\n emitted.set(table, seen);\n const key = `${name}::${kind}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n };\n\n const addOne = (table: string, spec: OneSpec) => ones.set(table, [...(ones.get(table) ?? []), spec]);\n const addMany = (table: string, spec: ManySpec) => manys.set(table, [...(manys.get(table) ?? []), spec]);\n\n const byTable = new Map<string, CollectionConfig>();\n for (const collection of collections) {\n const table = bareTableName(getTableName(collection));\n if (table && tables[table]) byTable.set(table, collection);\n }\n\n for (const [tableName, collection] of byTable) {\n const table = tables[tableName];\n\n for (const [relationKey, relation] of Object.entries(resolveCollectionRelations(collection))) {\n let target: CollectionConfig;\n try {\n target = relation.target();\n } catch (err) {\n // Nothing to build against, and nothing to fail over: the boot\n // relation check reports an unresolvable target by name.\n logger.debug(`[schema] Relation ${collection.slug}.${relationKey} has no resolvable target`, { error: err });\n continue;\n }\n const targetTableName = bareTableName(getTableName(target));\n const targetTable = tables[targetTableName];\n const name = sharedRelationName(relation, collection);\n\n switch (relation.kind) {\n case \"belongsTo\": {\n if (!targetTable) continue;\n if (!claim(tableName, name, relation.kind)) continue;\n const localKey = fieldKeyForColumn(collection, relation.localKey);\n const referenced = primaryKeyFieldKey(target);\n const field = columnOf(table, localKey);\n const reference = columnOf(targetTable, referenced);\n // A column the catalogue does not have would make drizzle\n // throw `Cannot read properties of undefined` from inside\n // `normalizeRelation`, three frames from anything nameable.\n // The boot relation check reports the same defect in terms\n // of the collection; this only declines to build it.\n if (!field || !reference) continue;\n addOne(tableName, {\n key: relationKey,\n target: targetTable,\n fields: [field],\n references: [reference],\n relationName: name\n });\n break;\n }\n\n case \"hasOne\": {\n if (!targetTable) continue;\n if (!claim(tableName, name, relation.kind)) continue;\n // The foreign key lives on the target, so this side states\n // the join from its own end: its source key against the\n // target's foreign key. Drizzle has no `one()` that is paired\n // by `relationName` alone — `createOne` reads\n // `config.fields.reduce(...)` as the relations are evaluated,\n // which is at `drizzle({ schema })` — and a bare `one(target)`\n // is paired by table, which is ambiguous as soon as the target\n // has two links back here or the link is to its own table.\n // These are the columns drizzle would infer from the owning\n // side, given outright.\n const field = columnOf(table, sourceKeyFieldKey(relation, collection));\n const reference = columnOf(targetTable, fieldKeyForColumn(target, relation.foreignKeyOnTarget));\n if (!field || !reference) continue;\n addOne(tableName, {\n key: relationKey,\n target: targetTable,\n fields: [field],\n references: [reference],\n relationName: name\n });\n break;\n }\n\n case \"hasMany\": {\n if (!targetTable) continue;\n if (!claim(tableName, name, relation.kind)) continue;\n addMany(tableName, { key: relationKey, target: targetTable, relationName: name });\n break;\n }\n\n case \"manyToMany\": {\n const junctionName = bareTableName(relation.through.table);\n const junction = tables[junctionName];\n if (!junction) continue;\n if (!claim(tableName, name, relation.kind)) continue;\n addMany(tableName, { key: relationKey, target: junction, relationName: name });\n addJunctionSides(relation, collection, target, junctionName, tables, addOne, claim);\n break;\n }\n\n case \"via\":\n // A join chain is resolved at query time, not modelled as a\n // drizzle relation — same as the generator.\n break;\n }\n }\n }\n\n // The reciprocal a `many()` needs. A `hasMany` gives drizzle no columns to\n // join on; it finds them on the owning side, which exists only if the other\n // collection happens to declare a `belongsTo` back. Where it does not, the\n // generated file synthesizes one under a `_synth_` key, and so does this.\n // A `hasOne` names its own columns, and gets the same owning side so the\n // target's table carries the link back under the same `relationName`.\n for (const [tableName, collection] of byTable) {\n const table = tables[tableName];\n for (const [, relation] of Object.entries(resolveCollectionRelations(collection))) {\n if (relation.kind !== \"hasMany\" && relation.kind !== \"hasOne\") continue;\n let target: CollectionConfig;\n try {\n target = relation.target();\n } catch {\n continue;\n }\n const targetTableName = bareTableName(getTableName(target));\n const targetTable = tables[targetTableName];\n if (!targetTable) continue;\n\n const name = sharedRelationName(relation, collection);\n if (!claim(targetTableName, name, \"belongsTo\")) continue;\n\n const fkKey = fieldKeyForColumn(target, relation.foreignKeyOnTarget);\n const field = columnOf(targetTable, fkKey);\n const reference = columnOf(table, sourceKeyFieldKey(relation, collection));\n if (!field || !reference) continue;\n\n addOne(targetTableName, {\n key: `_synth_${targetTableName}_${fkKey}`,\n target: tables[tableName],\n fields: [field],\n references: [reference],\n relationName: name\n });\n }\n }\n\n const built: Record<string, Relations> = {};\n for (const tableName of new Set([...ones.keys(), ...manys.keys()])) {\n const table = tables[tableName];\n if (!table) continue;\n const tableOnes = ones.get(tableName) ?? [];\n const tableManys = manys.get(tableName) ?? [];\n\n built[`${tableName}Relations`] = relations(table, ({ one, many }) => {\n const map: Record<string, unknown> = {};\n for (const spec of tableOnes) {\n map[spec.key] = one(spec.target, {\n fields: spec.fields as never,\n references: spec.references as never,\n relationName: spec.relationName\n });\n }\n for (const spec of tableManys) {\n if (map[spec.key]) continue;\n map[spec.key] = many(spec.target, { relationName: spec.relationName });\n }\n return map as never;\n });\n }\n\n return built;\n}\n\n/**\n * The junction table's own two `one()` sides.\n *\n * A many-to-many is a `many(junction)` on each endpoint, so the junction has to\n * carry the matching `one()` back to each — without them drizzle can join a\n * post to its `posts_tags` rows and no further, and the tags come back as\n * junction rows. Keyed by the junction's own columns, which is how the\n * generated file keys them too.\n */\nfunction addJunctionSides(\n relation: Extract<ResolvedRelation, { kind: \"manyToMany\" }>,\n sourceCollection: CollectionConfig,\n targetCollection: CollectionConfig,\n junctionName: string,\n tables: Record<string, PgTable>,\n addOne: (table: string, spec: OneSpec) => void,\n claim: (table: string, name: string, kind: string) => boolean\n): void {\n const junction = tables[junctionName];\n const sourceTable = tables[bareTableName(getTableName(sourceCollection))];\n const targetTable = tables[bareTableName(getTableName(targetCollection))];\n if (!junction || !sourceTable || !targetTable) return;\n\n const sourceName = sharedRelationName(relation, sourceCollection);\n // The far endpoint pairs with whatever *it* calls this junction, so the two\n // sides are looked up rather than assumed: an inverse declared on the target\n // owns the name, and only a junction nothing points back through needs a\n // synthesized one.\n const inverse = Object.values(resolveCollectionRelations(targetCollection))\n .find(r => r.kind === \"manyToMany\"\n && bareTableName(r.through.table) === junctionName);\n const targetName = inverse\n ? sharedRelationName(inverse, targetCollection)\n : `${junctionName}_${relation.through.targetColumn}`;\n\n const pairs: [string, PgTable, string, CollectionConfig, string][] = [\n [relation.through.sourceColumn, sourceTable, sourceName, sourceCollection, \"source\"],\n [relation.through.targetColumn, targetTable, targetName, targetCollection, \"target\"]\n ];\n\n for (const [column, endpointTable, relationName, endpointCollection] of pairs) {\n if (!claim(junctionName, relationName, \"junction\")) continue;\n const field = columnOf(junction, column);\n const reference = columnOf(endpointTable, primaryKeyFieldKey(endpointCollection));\n if (!field || !reference) continue;\n addOne(junctionName, {\n key: column,\n target: endpointTable,\n fields: [field],\n references: [reference],\n relationName\n });\n }\n}\n","/**\n * The runtime's Drizzle schema, read back from the database it is about to\n * serve.\n *\n * This is the whole point of the module: **the live catalogue is the schema**.\n * Boot-ensure has already created and altered whatever the collections describe\n * by the time this runs, so `information_schema` is both current and complete,\n * and the committed `schema.generated.ts` — which is a build artefact for Atlas,\n * `db push`, `eject` and user code — never decides what the server serves.\n *\n * It used to. The default data source was handed the bundle's generated module\n * and nothing reconciled it, so a file one commit behind the database changed\n * behaviour in ways that looked nothing like \"your schema file is old\":\n *\n * - a foreign-key column renamed by boot-ensure (`categorie_id` → `category_id`)\n * left every request 500ing, because the module still declared the old name;\n * - a property added to a collection answered `400 VALIDATION_UNKNOWN_FIELDS`\n * on first save, because the write check reads the table and the table came\n * from the file, while the column itself existed;\n * - relations missing from the module were silently missing from list reads.\n *\n * The catalogue cannot drift from itself. What the generated module is still\n * good for is telling the developer their file is stale — see\n * `generated-schema-diff.ts`, which is now its only reader at boot.\n */\nimport type { PgTable } from \"drizzle-orm/pg-core\";\nimport type { Relations } from \"drizzle-orm\";\nimport { CollectionConfig } from \"@rebasepro/types\";\nimport { fieldKeyForColumn, getJunctionCollectionConfig, getTableName, resolveJunctionSpecs } from \"@rebasepro/common\";\n\nimport { buildDrizzleRelationsFromSchema, buildDrizzleTablesFromSchema, type ColumnKeyResolver } from \"./dynamic-tables\";\nimport { bareTableName, buildDrizzleRelationsFromCollections } from \"./config-relations\";\nimport { introspectSchema, type Queryable } from \"./introspect-runtime\";\nimport type { TableMeta } from \"./introspect-db-logic\";\nimport { searchColumnNames } from \"./search-column\";\n\n/** The Postgres schema a collection's table lives in. */\nexport function schemaOfCollection(collection: CollectionConfig, fallback: string): string {\n const declared = (collection as { schema?: unknown }).schema;\n return typeof declared === \"string\" && declared.length > 0 ? declared : fallback;\n}\n\n/**\n * How a column of each table is keyed in the Drizzle object.\n *\n * The wire name, which is the property key — `authorId`, never `author_id` —\n * because that is what every read and write path in this driver indexes tables\n * and rows by, and what the generated module has always emitted. Getting this\n * wrong does not throw: drizzle leaves an unknown key out of the statement and\n * the write reports success having stored nothing.\n *\n * Two exceptions, both columns no property declares:\n *\n * - the generated search columns keep their raw names, because `search_vector`\n * is how `searchColumnNames` excludes them from responses and how the\n * condition builder finds the one to match against;\n * - a table no collection claims (a junction) is keyed by its **key** columns'\n * names, which is also what the generated file does for them — but a\n * junction that declares `through.properties` keys those payload columns by\n * their property key, for the same reason a collection does. `joinedAt` with\n * `columnName: \"joined_at\"` has to be one name on both sides or a `_pivot`\n * write is silently dropped by drizzle and the read serves a key the caller\n * never declared.\n */\nexport function columnKeysFromCollections(\n collections: CollectionConfig[]\n): ColumnKeyResolver {\n const byTable = new Map<string, CollectionConfig>();\n const rawColumns = new Map<string, Set<string>>();\n for (const collection of collections) {\n const table = bareTableName(getTableName(collection));\n if (!table) continue;\n byTable.set(table, collection);\n rawColumns.set(table, new Set(searchColumnNames(collection)));\n }\n // The junctions' payload columns, as the synthetic collection that owns\n // them — the same one the planner emitted the columns from, so the runtime\n // table and the generated one cannot key them differently.\n const junctionByTable = new Map<string, CollectionConfig>();\n for (const spec of resolveJunctionSpecs(collections).values()) {\n if (Object.keys(spec.properties).length === 0) continue;\n junctionByTable.set(bareTableName(spec.table), getJunctionCollectionConfig(spec));\n }\n return (tableName, columnName) => {\n const collection = byTable.get(tableName);\n if (!collection) {\n const junction = junctionByTable.get(tableName);\n return junction ? fieldKeyForColumn(junction, columnName) : columnName;\n }\n if (rawColumns.get(tableName)?.has(columnName)) return columnName;\n return fieldKeyForColumn(collection, columnName);\n };\n}\n\nexport interface CatalogueSchema {\n /** Drizzle tables, keyed by bare table name. */\n tables: Record<string, PgTable>;\n /** Drizzle relations, keyed `<table>Relations`. */\n relations: Record<string, Relations>;\n /** Introspected metadata per table — what the boot diff compares against. */\n meta: Map<string, TableMeta>;\n /** Tables a collection declares that the database does not have. */\n missing: string[];\n}\n\n/**\n * Read the tables this data source serves out of `information_schema`.\n *\n * Restricted to the collections handed in, because the driver is given every\n * collection the project declares while each database holds only its own: an\n * unfiltered read had a second source (`database(\"analytics\")`) reporting the\n * default's tables as its own. Junction tables come too — they back no\n * collection and a many-to-many is unreadable without them.\n *\n * Every schema the collections name is read, not just `public`. The users\n * collection lives in `rebase`, and a run restricted to `public` would leave the\n * registry with no table for it at all.\n */\nexport async function readCatalogueSchema(options: {\n client: Queryable;\n collections: CollectionConfig[];\n defaultSchema: string;\n}): Promise<CatalogueSchema> {\n const { client, collections, defaultSchema } = options;\n\n /** schema → the tables wanted from it. */\n const wanted = new Map<string, Set<string>>();\n const want = (schema: string, table: string) => {\n const set = wanted.get(schema) ?? new Set<string>();\n wanted.set(schema, set);\n set.add(table);\n };\n\n for (const collection of collections) {\n const table = bareTableName(getTableName(collection));\n if (table) want(schemaOfCollection(collection, defaultSchema), table);\n }\n // Junctions are created in `public`, full stop — `resolveJunctionSpecs`\n // hardcodes it and the three generators agree with it.\n for (const spec of resolveJunctionSpecs(collections).values()) {\n want(spec.schema, bareTableName(spec.table));\n }\n\n const columnKey = columnKeysFromCollections(collections);\n const tables: Record<string, PgTable> = {};\n const meta = new Map<string, TableMeta>();\n const missing: string[] = [];\n\n for (const [schema, names] of wanted) {\n // Views too: a collection that declares `view` reads one.\n const live = await introspectSchema(client, schema, { views: true });\n const present = new Map<string, TableMeta>();\n for (const name of names) {\n const found = live.tablesMap.get(name);\n if (!found) {\n missing.push(schema === defaultSchema ? name : `${schema}.${name}`);\n continue;\n }\n // First schema to carry a name wins. Two schemas holding a table of\n // the same name is the `search_path` hazard the drift report\n // explains; the registry is keyed by bare name either way, so this\n // only picks which one is served — the one whose collection asked.\n if (tables[name]) continue;\n present.set(name, found);\n meta.set(name, found);\n }\n Object.assign(tables, buildDrizzleTablesFromSchema(present, schema, columnKey));\n }\n\n return {\n tables,\n relations: buildDrizzleRelationsFromCollections(collections, tables),\n meta,\n missing\n };\n}\n\n/**\n * The BaaS variant: no collections are declared, so every table in one schema is\n * served and both the collections and the relations are derived from the\n * foreign keys.\n *\n * Kept apart from {@link readCatalogueSchema} because the two answer different\n * questions. Here the database is the entire specification; there it supplies\n * the columns for a specification the project already wrote down.\n */\nexport function buildBaasSchema(\n tablesMap: Map<string, TableMeta>,\n pgSchemaName: string,\n collections: CollectionConfig[]\n): { tables: Record<string, PgTable>; relations: Record<string, Relations> } {\n const columnKey = columnKeysFromCollections(collections);\n const tables = buildDrizzleTablesFromSchema(tablesMap, pgSchemaName, columnKey);\n return {\n tables,\n relations: buildDrizzleRelationsFromSchema(tablesMap, tables, columnKey)\n };\n}\n","/**\n * Compare the committed `schema.generated.ts` against the live catalogue, and\n * say so — once per difference, at boot, as a warning and nothing more.\n *\n * The runtime stopped reading that file for its tables (see\n * `catalogue-schema.ts`), which removes an entire class of production failure\n * and creates a smaller one: a stale file is now *invisible*. It is still real —\n * it is what Atlas plans migrations from, what `db push` diffs, what `eject`\n * writes out and what user code imports — so a project whose file no longer\n * describes its database will hit it later, in a tool, with no clue that boot\n * already knew.\n *\n * Hence this: a guard rather than a doc. It never fails boot and never changes\n * what is served — the previous arrangement, where the file could do both,\n * is exactly what was removed.\n *\n * `generated-schema-staleness.ts` answers a narrower question (does the file\n * name every table the collections do) from the file's *source text*. This one\n * compares the loaded module against the database, column by column.\n */\nimport { getTableColumns, getTableName as drizzleTableName, isTable } from \"drizzle-orm\";\nimport type { PgTable } from \"drizzle-orm/pg-core\";\nimport { CollectionConfig } from \"@rebasepro/types\";\nimport { fieldKeyForColumn, getTableName } from \"@rebasepro/common\";\nimport { logger } from \"@rebasepro/server\";\n\nimport { AUTH_USERS_COLUMNS, isAuthCollection } from \"./auth-users-columns\";\nimport type { TableMeta } from \"./introspect-db-logic\";\nimport { bareTableName } from \"./config-relations\";\nimport { readCatalogueSchema } from \"./catalogue-schema\";\nimport type { Queryable } from \"./introspect-runtime\";\n\nexport type SchemaDifferenceKind =\n | \"missing-table\"\n | \"missing-column\"\n | \"extra-column\"\n | \"type\"\n | \"nullability\";\n\nexport interface SchemaDifference {\n kind: SchemaDifferenceKind;\n /** Bare table name, as both sides spell it. */\n table: string;\n /** The collection backed by that table, when one is. */\n collection?: string;\n /** The column, in database terms. */\n column?: string;\n /** The field it is served under — the property key, where there is one. */\n property?: string;\n /** What `schema.generated.ts` says. */\n generated?: string;\n /** What the database says. */\n live?: string;\n}\n\n/**\n * The families a boot warning is worth raising over.\n *\n * Deliberately coarse. `varchar(120)` and `text` are the same family because the\n * runtime treats them identically and a warning about the difference would fire\n * on every boot of a correct project — the widths still reach Postgres, which\n * enforces them. What this is looking for is the kind of drift that changes what\n * a value *is*: a number that became text, a timestamp that became a date, a\n * column that stopped existing.\n */\nexport function typeFamily(sqlType: string | undefined): string {\n if (!sqlType) return \"unknown\";\n let type = sqlType.trim().toLowerCase();\n const isArray = type.endsWith(\"[]\") || type.startsWith(\"_\");\n type = type.replace(/\\[\\]$/, \"\").replace(/^_/, \"\");\n // Strip the modifier: varchar(255), numeric(10,2), vector(1536), char(2).\n type = type.replace(/\\s*\\([^)]*\\)\\s*$/, \"\").trim();\n\n const family = FAMILIES[type] ?? type;\n return isArray ? `${family}[]` : family;\n}\n\nconst FAMILIES: Record<string, string> = {\n // strings\n text: \"text\",\n varchar: \"text\",\n \"character varying\": \"text\",\n bpchar: \"text\",\n char: \"text\",\n character: \"text\",\n citext: \"text\",\n name: \"text\",\n // integers\n int2: \"integer\",\n smallint: \"integer\",\n smallserial: \"integer\",\n int4: \"integer\",\n int: \"integer\",\n integer: \"integer\",\n serial: \"integer\",\n int8: \"bigint\",\n bigint: \"bigint\",\n bigserial: \"bigint\",\n // approximate and exact numerics: kept apart, because one rounds\n float4: \"float\",\n real: \"float\",\n float8: \"float\",\n \"double precision\": \"float\",\n numeric: \"numeric\",\n decimal: \"numeric\",\n money: \"numeric\",\n // the rest\n bool: \"boolean\",\n boolean: \"boolean\",\n uuid: \"uuid\",\n json: \"json\",\n jsonb: \"jsonb\",\n date: \"date\",\n time: \"time\",\n \"time without time zone\": \"time\",\n timetz: \"time\",\n \"time with time zone\": \"time\",\n timestamp: \"timestamp\",\n \"timestamp without time zone\": \"timestamp\",\n timestamptz: \"timestamptz\",\n \"timestamp with time zone\": \"timestamptz\",\n interval: \"interval\",\n bytea: \"bytea\",\n tsvector: \"tsvector\",\n tsquery: \"tsquery\",\n vector: \"vector\"\n};\n\n/** One catalogue column, reduced to the three facts this compares. */\ninterface CatalogueColumn {\n name: string;\n family: string;\n notNull: boolean;\n}\n\nfunction catalogueColumns(meta: TableMeta): Map<string, CatalogueColumn> {\n const columns = new Map<string, CatalogueColumn>();\n for (const col of meta.columns) {\n columns.set(col.column_name, {\n name: col.column_name,\n // `udt_name` over `data_type`: the latter reports \"ARRAY\" and\n // \"USER-DEFINED\" where the former is the concrete type, and an enum\n // has to compare by its own type name against the module's pgEnum.\n family: typeFamily(col.udt_name || col.data_type),\n notNull: col.is_nullable === \"NO\"\n });\n }\n return columns;\n}\n\n/**\n * Every way the generated module and the database disagree, for the tables both\n * describe.\n *\n * One-directional in one respect only: a table the module has and the database\n * does not is reported (that is the stale-file case), while a table the database\n * has and the module does not is left alone — a database may hold anything, and\n * the collections-vs-file question is `generated-schema-staleness`'s.\n */\nexport function diffGeneratedSchemaAgainstCatalogue(options: {\n /** The `tables` export of the bundle's schema module. */\n generated: Record<string, unknown> | undefined;\n /** What was introspected for this data source, keyed by bare table name. */\n catalogue: Map<string, TableMeta>;\n /** Collections of this source, so a column can be named as a property. */\n collections: CollectionConfig[];\n}): SchemaDifference[] {\n const { generated, catalogue, collections } = options;\n if (!generated) return [];\n\n const collectionByTable = new Map<string, CollectionConfig>();\n for (const collection of collections) {\n const table = getTableName(collection);\n if (table) collectionByTable.set(bareTableName(table), collection);\n }\n\n const differences: SchemaDifference[] = [];\n\n for (const value of Object.values(generated)) {\n if (!isTable(value)) continue;\n const table = drizzleTableName(value as PgTable);\n const collection = collectionByTable.get(table);\n const at = { table, collection: collection?.slug };\n\n const meta = catalogue.get(table);\n if (!meta) {\n // Only for a table a collection of this source claims: the module\n // carries every table of the project, including the ones another\n // data source holds, and those are legitimately absent here.\n if (collection) differences.push({ ...at, kind: \"missing-table\" });\n continue;\n }\n\n const live = catalogueColumns(meta);\n const seen = new Set<string>();\n\n // On the auth table, auth owns its own columns' contract and the\n // generated file deliberately does not carry it: `render-drizzle` drops\n // the columns a users collection does not declare (`is_anonymous`,\n // `tokens_valid_after`) because drizzle-kit creates no auth table, and\n // the collection's own property definitions say nothing about the\n // `NOT NULL DEFAULT` that `ensureAuthTablesExist` applies.\n //\n // Comparing them anyway reported seven differences on a project nobody\n // had touched yet, and prescribed `rebase schema generate` — which\n // regenerates the file from the same collection and cannot change any\n // of them. A warning that survives its own remedy teaches the reader to\n // ignore the next one, so these are not differences. A *type* mismatch\n // still is: that is the file and the database disagreeing about\n // something neither side intends.\n const authOwned = isAuthCollection(collection)\n ? new Set(AUTH_USERS_COLUMNS.map(c => c.column))\n : undefined;\n\n for (const [key, column] of Object.entries(getTableColumns(value as PgTable))) {\n const name = (column as { name?: string }).name ?? key;\n seen.add(name);\n const property = collection ? fieldKeyForColumn(collection, name) : key;\n const generatedFamily = typeFamily((column as { getSQLType?: () => string }).getSQLType?.());\n const generatedNotNull = Boolean((column as { notNull?: boolean }).notNull);\n\n const found = live.get(name);\n if (!found) {\n differences.push({ ...at, kind: \"missing-column\", column: name, property, generated: generatedFamily });\n continue;\n }\n if (found.family !== generatedFamily) {\n differences.push({\n ...at,\n kind: \"type\",\n column: name,\n property,\n generated: generatedFamily,\n live: found.family\n });\n }\n if (found.notNull !== generatedNotNull && !authOwned?.has(name)) {\n differences.push({\n ...at,\n kind: \"nullability\",\n column: name,\n property,\n generated: generatedNotNull ? \"NOT NULL\" : \"nullable\",\n live: found.notNull ? \"NOT NULL\" : \"nullable\"\n });\n }\n }\n\n for (const [name, column] of live) {\n if (seen.has(name)) continue;\n if (authOwned?.has(name)) continue;\n differences.push({\n ...at,\n kind: \"extra-column\",\n column: name,\n property: collection ? fieldKeyForColumn(collection, name) : name,\n live: column.family\n });\n }\n }\n\n return differences;\n}\n\n/**\n * Boot's drift question, asked of a database from outside a boot.\n *\n * The same two calls boot makes before it warns, with the arguments it makes\n * them with: the catalogue read the way the registry reads it\n * ({@link readCatalogueSchema}), then {@link diffGeneratedSchemaAgainstCatalogue}\n * over its metadata. `rebase doctor` asks through here, because the boot\n * warning sends the reader to the doctor for \"the full report\" — and while the\n * doctor compared on its own terms, it answered \"In sync\" over a NOT NULL and a\n * left-behind column that boot had just warned about.\n *\n * `collections` are the data source's own, as boot filters them.\n */\nexport async function readGeneratedSchemaDrift(options: {\n client: Queryable;\n /** The `tables` export of `schema.generated.ts`. */\n generated: Record<string, unknown> | undefined;\n collections: CollectionConfig[];\n defaultSchema: string;\n}): Promise<SchemaDifference[]> {\n const { client, generated, collections, defaultSchema } = options;\n if (!generated || collections.length === 0) return [];\n const catalogue = await readCatalogueSchema({ client, collections, defaultSchema });\n return diffGeneratedSchemaAgainstCatalogue({ generated, catalogue: catalogue.meta, collections });\n}\n\n/** One line, in the terms the reader has: collection, property, column. */\nexport function describeSchemaDifference(difference: SchemaDifference): string {\n const where = difference.collection\n ? `${difference.collection} (table \"${difference.table}\")`\n : `table \"${difference.table}\"`;\n const field = difference.column\n ? `${difference.property && difference.property !== difference.column\n ? `${difference.property} → \"${difference.column}\"`\n : `\"${difference.column}\"`}`\n : undefined;\n\n switch (difference.kind) {\n case \"missing-table\":\n return `${where} is in schema.generated.ts but not in the database`;\n case \"missing-column\":\n return `${where}: ${field} is in schema.generated.ts but not in the database`;\n case \"extra-column\":\n return `${where}: ${field} is in the database but not in schema.generated.ts (${difference.live})`;\n case \"type\":\n return `${where}: ${field} is ${difference.generated} in schema.generated.ts and ${difference.live} in the database`;\n case \"nullability\":\n return `${where}: ${field} is ${difference.generated} in schema.generated.ts and ${difference.live} in the database`;\n }\n}\n\n/**\n * The `rebase schema reconcile` line for a difference it can apply: a column\n * the database requires and the collection made optional, or one the\n * collection no longer declares. Undefined for the rest.\n */\nexport function reconcileFix(difference: SchemaDifference): string | undefined {\n if (difference.kind === \"nullability\" && difference.live === \"NOT NULL\") return \"rebase schema reconcile\";\n if (difference.kind === \"extra-column\" && difference.collection) {\n return `rebase schema reconcile --drop ${difference.collection}.${difference.column}`;\n }\n return undefined;\n}\n\n/**\n * Report the differences, one warning each, and never throw.\n *\n * Per difference rather than one summary block on purpose: these are read out of\n * a log aggregator as often as a terminal, and a single multi-line message\n * cannot be filtered down to the one collection somebody is looking at.\n *\n * The fix it names is `rebase db push`. `rebase dev` rewrites\n * schema.generated.ts from the collections on every change, and boot applies\n * only additive changes, so what is still different at boot is the database\n * behind the file: a rename, a dropped column, a narrowed type, a NOT NULL.\n * `rebase schema generate` rewrites the file and leaves the database as it is,\n * so it is named only for collections that changed since the file was written.\n */\nexport function warnOnGeneratedSchemaDrift(differences: SchemaDifference[]): void {\n if (differences.length === 0) return;\n\n logger.warn(\n `📄 [schema] schema.generated.ts and the database disagree (${differences.length} difference` +\n `${differences.length === 1 ? \"\" : \"s\"}). Boot applies only additive changes; these are the ones it ` +\n \"left for you. Run `rebase db push` to apply them (it shows the plan and asks before anything \" +\n \"destructive), or `rebase db generate` for a migration. A NOT NULL to relax or a column to drop \" +\n \"can also be applied through the running backend, Rebase Cloud included: `rebase schema reconcile`. \" +\n \"If the collections changed since schema.generated.ts was written, run `rebase schema generate` first.\"\n );\n\n for (const difference of differences) {\n logger.warn(` • ${describeSchemaDifference(difference)}`, {\n schemaDrift: {\n kind: difference.kind,\n table: difference.table,\n collection: difference.collection,\n column: difference.column,\n property: difference.property,\n generated: difference.generated,\n live: difference.live\n },\n fix: reconcileFix(difference) ?? \"rebase db push\"\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuDA,eAAsB,cAAc,QAAmB,UAAwD;CAC3G,MAAM,EAAE,SAAS,MAAM,OAAO,MAC1B;;;;;oDAMA,CAAC,QAAQ,CACb;CAEA,OAAO,IAAI,IACP,KAAK,KAAK,MAAM,CACZ,EAAE,OACF;EAAE,OAAO,EAAE;EAAO,YAAY,EAAE,gBAAgB;EAAM,aAAa,OAAO,EAAE,gBAAgB,CAAC;CAAE,CACnG,CAAC,CACL;AACJ;;;;;AAWA,eAAsB,iBAClB,QACA,UAOA,UAA+B,CAAC,GACL;CAC3B,MAAM,EAAE,MAAM,WAAW,MAAM,OAAO,MAClC;;kDAE0C,QAAQ,QAAQ,8BAA8B,iBAAiB;;;WAGtG,QAAQ,QAAQ;;;iGAGsE,GAAG;+BAE5F,CAAC,QAAQ,CACb;CAEA,MAAM,EAAE,MAAM,YAAY,MAAM,OAAO,MACnC;;;;;;;;;;;;;;;;;;;;;;;;;;WA0B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AAG,WAAW;AAGrF;;;;;;;;;;;;;;;AAgBA,SAAgB,2BAA2B,aAAuC;CAC9E,IAAI,YAAY,WAAW,GAAG;CAE9B,OAAO,KACH,8DAA8D,YAAY,OAAO,aAC9E,YAAY,WAAW,IAAI,KAAK,IAAI,0cAK3C;CAEA,KAAK,MAAM,cAAc,aACrB,OAAO,KAAK,QAAQ,yBAAyB,UAAU,KAAK;EACxD,aAAa;GACT,MAAM,WAAW;GACjB,OAAO,WAAW;GAClB,YAAY,WAAW;GACvB,QAAQ,WAAW;GACnB,UAAU,WAAW;GACrB,WAAW,WAAW;GACtB,MAAM,WAAW;EACrB;EACA,KAAK,aAAa,UAAU,KAAK;CACrC,CAAC;AAET"}
package/dist/index.d.ts CHANGED
@@ -50,4 +50,5 @@ export { isGeneratedPolicyName } from "./security/policy-drift.js";
50
50
  * `PostgresBootstrapper` and `rebase db push` already do, and needs it to be
51
51
  * the same code rather than a second description of the same grants.
52
52
  */
53
- export { ensureAppRole, detectConnectionPosture, REBASE_USER_ROLE } from "./security/rls-enforcement.js";
53
+ export { ensureAppRole, ensureAppRoleGrants, detectConnectionPosture, findOtherRoleMembers, readRecordedRequestRoles, recordRequestRoles, REBASE_USER_ROLE, type EnsureAppRoleOptions, type ManagedTable } from "./security/rls-enforcement.js";
54
+ export { cliRlsSettings, resolveRlsSettings, rlsConfigFromEnv, type GrantsMode, type IdentityMode, type PolicyTargetMode, type PostgresRlsConfig, type ProvisionRoleMode, type RequestIdentity, type RequestRoleMap, type RlsSettings, type SharedRoleMode } from "./security/rls-settings.js";
package/dist/index.es.js CHANGED
@@ -1,18 +1,20 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { a as createPostgresDatabaseConnection, c as guardPoolAgainstDirtyRelease, d as poolMaxCeiling, i as createDirectDatabaseConnection, o as createReadReplicaConnection, s as defaultPoolTimeouts, t as cappedPoolMax, u as pinSearchPath } from "./connection-COuS5Fm-.js";
4
- import { $ as AuthenticatedPostgresBackendDriver, B as mfaFactors, C as PG_NOTIFY_MAX_PAYLOAD_BYTES, D as MemoryChannelBus, E as parseChannelBusPayload, F as createAuthSchema, G as recoveryCodesRelations, H as passwordResetTokens, I as magicLinkTokens, J as userIdentities, K as refreshTokens, L as magicLinkTokensRelations, O as frameByteLength, P as appConfig, Q as usersSchema, R as mfaChallenges, S as DEFAULT_BATCH_WINDOW_MS, T as parseChannelBusFrame, U as passwordResetTokensRelations, V as mfaFactorsRelations, W as recoveryCodes, X as users, Y as userIdentitiesRelations, Z as usersRelations, _ as parseRealtimeTuning, _t as listedColumnKeys, a as openPostgresDriver, at as isRoleSwitchingOptedOut, b as resolveChannelBusSetting, c as resolveSourceUrls, d as DEFAULT_RECOUNT_MIN_ROWS, dt as DrizzleConditionBuilder, et as CONNECTION_OWNER, f as PostgresRealtimeProvider, ft as PostgresConditionBuilder, g as parseMaxSubscriptionsPerSocket, gt as joinColumn, h as parseMaxSocketsPerUser, ht as getUnknownFilterFieldsMode, i as isScaffoldedLocalDatabase, it as effectiveSqlRole, k as isChannelBusInstance, l as PostgresCollectionRegistry, m as packEntityChanges, mt as escapeLikePattern, n as createPostgresBootstrapper, nt as RoleSwitchUnavailableError, o as postgresDriverConfigFromEnv, ot as sqlRoleRanAs, p as RealtimeService, pt as configureUnknownFilterFields, q as refreshTokensRelations, r as describeSchemaDriftCause, rt as branchParentDatabase, s as resolveDriftCheckName, t as openRebase, tt as PostgresBackendDriver, u as DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET, v as refetchConcurrencyFor, w as PostgresChannelBus, x as CHANNEL_BUS_NOTIFY_CHANNEL, y as createChannelBus, z as mfaChallengesRelations } from "./open-rebase-CTNBmmH8.js";
5
- import { a as reopenedDatabasesNotice, i as reopenClosedDatabases, r as BranchingUnsupportedError, t as BranchService } from "./BranchService-JiYJ_n9E.js";
6
- import { a as ensureAppRole, i as detectConnectionPosture, t as REBASE_USER_ROLE } from "./rls-enforcement-jZTv1yci.js";
7
- import { n as planSchema } from "./plan-schema-CMNWvqIa.js";
8
- import { t as generateSchema } from "./generate-drizzle-schema-logic-DpFA1UVd.js";
4
+ import { $ as AuthenticatedPostgresBackendDriver, B as mfaFactors, C as PG_NOTIFY_MAX_PAYLOAD_BYTES, D as MemoryChannelBus, E as parseChannelBusPayload, F as createAuthSchema, G as recoveryCodesRelations, H as passwordResetTokens, I as magicLinkTokens, J as userIdentities, K as refreshTokens, L as magicLinkTokensRelations, O as frameByteLength, P as appConfig, Q as usersSchema, R as mfaChallenges, S as DEFAULT_BATCH_WINDOW_MS, T as parseChannelBusFrame, U as passwordResetTokensRelations, V as mfaFactorsRelations, W as recoveryCodes, X as users, Y as userIdentitiesRelations, Z as usersRelations, _ as parseRealtimeTuning, _t as listedColumnKeys, a as openPostgresDriver, at as isRoleSwitchingOptedOut, b as resolveChannelBusSetting, c as resolveSourceUrls, d as DEFAULT_RECOUNT_MIN_ROWS, dt as DrizzleConditionBuilder, et as CONNECTION_OWNER, f as PostgresRealtimeProvider, ft as PostgresConditionBuilder, g as parseMaxSubscriptionsPerSocket, gt as joinColumn, h as parseMaxSocketsPerUser, ht as getUnknownFilterFieldsMode, i as isScaffoldedLocalDatabase, it as effectiveSqlRole, k as isChannelBusInstance, l as PostgresCollectionRegistry, m as packEntityChanges, mt as escapeLikePattern, n as createPostgresBootstrapper, nt as RoleSwitchUnavailableError, o as postgresDriverConfigFromEnv, ot as sqlRoleRanAs, p as RealtimeService, pt as configureUnknownFilterFields, q as refreshTokensRelations, r as describeSchemaDriftCause, rt as branchParentDatabase, s as resolveDriftCheckName, t as openRebase, tt as PostgresBackendDriver, u as DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET, v as refetchConcurrencyFor, w as PostgresChannelBus, x as CHANNEL_BUS_NOTIFY_CHANNEL, y as createChannelBus, z as mfaChallengesRelations } from "./open-rebase-CiO_sjMT.js";
5
+ import { a as reopenedDatabasesNotice, i as reopenClosedDatabases, r as BranchingUnsupportedError, t as BranchService } from "./BranchService-BIIBF5ZL.js";
6
+ import { c as ensureAppRole, d as findOtherRoleMembers, g as recordRequestRoles, h as readRecordedRequestRoles, l as ensureAppRoleGrants, s as detectConnectionPosture, t as REBASE_USER_ROLE } from "./rls-enforcement-BO618rnr.js";
7
+ import { n as planSchema } from "./plan-schema-BYxOzflz.js";
8
+ import { t as generateSchema } from "./generate-drizzle-schema-logic-C5FB7Fpo.js";
9
9
  import { a as mergeDatabaseBranch, i as diffDatabaseBranch, n as DEFAULT_BRANCH_DIFF_SAMPLE_LIMIT, t as DEFAULT_BRANCH_DIFF_MAX_ROWS } from "./branch-diff-CxE4VlxT.js";
10
10
  import { t as DatabasePoolManager } from "./databasePoolManager-7hXVurmG.js";
11
- import { t as main } from "./generate-drizzle-schema-taNTu3xv.js";
12
- import { a as createPostgresWebSocket, i as TOO_MANY_SOCKETS_CLOSE_CODE, n as PUBLIC_TYPES, o as isSocketRealtimeService, r as SESSION_ENDED_CLOSE_CODE, s as socketRealtimeMissing, t as ADMIN_PLANE_TYPES } from "./websocket-D2y88dOa.js";
13
- import { A as buildBackupFilename, B as diagnoseRowSecurityDumpFailure, C as restoreDumpReplacing, D as resolvePgBinary, E as pgToolVariable, F as buildPgRestoreScriptArgs, G as parseBackupTimestamp, H as isBackupOfDatabase, I as buildPsqlScriptArgs, J as parsePgToolMajor, K as parseDbNameFromUrl, L as buildRowSecurityPgOptions, M as buildPgDumpallGlobalsArgs, N as buildPgRestoreArgs, O as selectBackupsToPrune, P as buildPgRestoreListArgs, Q as withDatabaseName, R as checkToolServerCompatibility, S as restoreDump, T as validateDump, U as joinStorageKey, V as globalsFileForDump, W as parseBackupDestination, X as serverVersionNumToMajor, Y as resolveConnectionString, Z as splitGlobalsStatements, _ as listBackups, a as BackupToolError, b as readDumpObjects, d as detectToolMajor, f as discardPartialDump, g as getServerVersionMajor, h as findRestoreConflicts, i as parseRestoreLine, j as buildPgDumpArgs, k as CLEAN_LOCK_TIMEOUT, l as createDump, m as findCleanExtras, n as parseBackupLine, o as CleanRestoreFailed, p as ensureDatabaseExists, q as parseDumpObjects, r as parseBackupsListLine, s as applyGlobals, u as describeUnreadableDump, v as preflight, w as uploadBackup, x as resetSharedSession, y as pruneBackups, z as cleanRestorePrelude } from "./backup-cli-D_aKXPyX.js";
14
- import { a as migrationVersionOf, c as isDriverDbSubcommand, g as assertKnownFlags, l as backupActionOf, n as compareMigrationVersions, u as assertKnownBranchFlags } from "./migrate-baseline-BeepEphh.js";
15
- import { i as isGeneratedPolicyName } from "./policy-drift-IjD2AUD-.js";
11
+ import { t as main } from "./generate-drizzle-schema-5spbTyQ6.js";
12
+ import { a as createPostgresWebSocket, i as TOO_MANY_SOCKETS_CLOSE_CODE, n as PUBLIC_TYPES, o as isSocketRealtimeService, r as SESSION_ENDED_CLOSE_CODE, s as socketRealtimeMissing, t as ADMIN_PLANE_TYPES } from "./websocket-B33YjKhs.js";
13
+ import { A as buildBackupFilename, B as diagnoseRowSecurityDumpFailure, C as restoreDumpReplacing, D as resolvePgBinary, E as pgToolVariable, F as buildPgRestoreScriptArgs, G as parseBackupTimestamp, H as isBackupOfDatabase, I as buildPsqlScriptArgs, J as parsePgToolMajor, K as parseDbNameFromUrl, L as buildRowSecurityPgOptions, M as buildPgDumpallGlobalsArgs, N as buildPgRestoreArgs, O as selectBackupsToPrune, P as buildPgRestoreListArgs, Q as withDatabaseName, R as checkToolServerCompatibility, S as restoreDump, T as validateDump, U as joinStorageKey, V as globalsFileForDump, W as parseBackupDestination, X as serverVersionNumToMajor, Y as resolveConnectionString, Z as splitGlobalsStatements, _ as listBackups, a as BackupToolError, b as readDumpObjects, d as detectToolMajor, f as discardPartialDump, g as getServerVersionMajor, h as findRestoreConflicts, i as parseRestoreLine, j as buildPgDumpArgs, k as CLEAN_LOCK_TIMEOUT, l as createDump, m as findCleanExtras, n as parseBackupLine, o as CleanRestoreFailed, p as ensureDatabaseExists, q as parseDumpObjects, r as parseBackupsListLine, s as applyGlobals, u as describeUnreadableDump, v as preflight, w as uploadBackup, x as resetSharedSession, y as pruneBackups, z as cleanRestorePrelude } from "./backup-cli-QcOpmRpQ.js";
14
+ import { a as migrationVersionOf, c as isDriverDbSubcommand, g as assertKnownFlags, l as backupActionOf, n as compareMigrationVersions, u as assertKnownBranchFlags } from "./migrate-baseline-BfHmq3vN.js";
15
+ import { n as resolveRlsSettings, r as rlsConfigFromEnv, t as cliRlsSettings } from "./rls-settings-De5NoHHy.js";
16
+ import { n as parseRequestRoleLine, t as parseProvisionLine } from "./request-role-cli-DSdRtvgH.js";
17
+ import { i as isGeneratedPolicyName } from "./policy-drift-DKuTJHfc.js";
16
18
  import { logger } from "@rebasepro/server";
17
19
  import fs from "fs";
18
20
  //#region src/backup/backup-cron.ts
@@ -99,7 +101,7 @@ function createBackupCron(config) {
99
101
  enabled: config.enabled ?? true,
100
102
  timeoutSeconds: 3600,
101
103
  async handler({ log }) {
102
- const { createDump, discardPartialDump, pruneBackups, uploadBackup, validateDump } = await import("./backup-cli-D_aKXPyX.js").then((n) => n.c);
104
+ const { createDump, discardPartialDump, pruneBackups, uploadBackup, validateDump } = await import("./backup-cli-QcOpmRpQ.js").then((n) => n.c);
103
105
  const { destination } = config;
104
106
  if (destination.kind !== "local" && !config.storage) throw new Error(`Backup destination is ${destination.kind} but no storage controller was provided. Pass the backend's configured StorageController to createBackupCron({ storage }).`);
105
107
  log(`Starting backup of "${dbName}"…`);
@@ -240,6 +242,12 @@ var LINE_CHECKS = {
240
242
  },
241
243
  backups: (args) => {
242
244
  if (args[2] === "list") parseBackupsListLine(args);
245
+ },
246
+ "request-role": (args) => {
247
+ parseRequestRoleLine(args);
248
+ },
249
+ provision: (args) => {
250
+ parseProvisionLine(args);
243
251
  }
244
252
  };
245
253
  /**
@@ -477,6 +485,6 @@ function findUnmigratedSchema(collections, migrations) {
477
485
  return changes;
478
486
  }
479
487
  //#endregion
480
- export { ADMIN_PLANE_TYPES, AuthenticatedPostgresBackendDriver, BackupToolError, BranchService, BranchingUnsupportedError, CHANNEL_BUS_NOTIFY_CHANNEL, CLEAN_LOCK_TIMEOUT, CONNECTION_OWNER, CleanRestoreFailed, DEFAULT_BATCH_WINDOW_MS, DEFAULT_BRANCH_DIFF_MAX_ROWS, DEFAULT_BRANCH_DIFF_SAMPLE_LIMIT, DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET, DEFAULT_RECOUNT_MIN_ROWS, DatabasePoolManager, DrizzleConditionBuilder, MemoryChannelBus, PG_NOTIFY_MAX_PAYLOAD_BYTES, PUBLIC_TYPES, PostgresBackendDriver, PostgresChannelBus, PostgresCollectionRegistry, PostgresConditionBuilder, PostgresRealtimeProvider, REBASE_USER_ROLE, RealtimeService, RoleSwitchUnavailableError, SESSION_ENDED_CLOSE_CODE, TOO_MANY_SOCKETS_CLOSE_CODE, appConfig, applyGlobals, assertDbCommandLine, backupCronConfigFromEnv, branchParentDatabase, buildBackupFilename, buildPgDumpArgs, buildPgDumpallGlobalsArgs, buildPgRestoreArgs, buildPgRestoreListArgs, buildPgRestoreScriptArgs, buildPsqlScriptArgs, buildRowSecurityPgOptions, cappedPoolMax, checkToolServerCompatibility, cleanRestorePrelude, compareMigrationVersions, configureUnknownFilterFields, createAuthSchema, createBackupCron, createChannelBus, createDirectDatabaseConnection, createDump, createPostgresAdapter, createPostgresBootstrapper, createPostgresDatabaseConnection, createPostgresWebSocket, createReadReplicaConnection, defaultPoolTimeouts, describeSchemaDriftCause, describeUnreadableDump, detectConnectionPosture, detectToolMajor, diagnoseRowSecurityDumpFailure, diffDatabaseBranch, discardPartialDump, effectiveSqlRole, ensureAppRole, ensureDatabaseExists, escapeLikePattern, findCleanExtras, findRestoreConflicts, findUnmigratedSchema, frameByteLength, generateSchema, getServerVersionMajor, getUnknownFilterFieldsMode, globalsFileForDump, guardPoolAgainstDirtyRelease, isBackupOfDatabase, isChannelBusInstance, isGeneratedPolicyName, isRoleSwitchingOptedOut, isScaffoldedLocalDatabase, isSocketRealtimeService, joinColumn, joinStorageKey, listBackups, listedColumnKeys, magicLinkTokens, magicLinkTokensRelations, main, mergeDatabaseBranch, mfaChallenges, mfaChallengesRelations, mfaFactors, mfaFactorsRelations, migrationVersionOf, openPostgresDriver, openRebase, packEntityChanges, parseBackupDestination, parseBackupTimestamp, parseChannelBusFrame, parseChannelBusPayload, parseDbNameFromUrl, parseDumpObjects, parseMaxSocketsPerUser, parseMaxSubscriptionsPerSocket, parsePgToolMajor, parseRealtimeTuning, passwordResetTokens, passwordResetTokensRelations, pinSearchPath, poolMaxCeiling, postgresDriverConfigFromEnv, preflight, pruneBackups, readDumpObjects, recoveryCodes, recoveryCodesRelations, refetchConcurrencyFor, refreshTokens, refreshTokensRelations, reopenClosedDatabases, reopenedDatabasesNotice, resetSharedSession, resolveChannelBusSetting, resolveConnectionString, resolveDriftCheckName, resolvePgBinary, resolveSourceUrls, restoreDump, restoreDumpReplacing, selectBackupsToPrune, serverVersionNumToMajor, socketRealtimeMissing, splitGlobalsStatements, sqlRoleRanAs, uploadBackup, userIdentities, userIdentitiesRelations, users, usersRelations, usersSchema, validateDump, withDatabaseName };
488
+ export { ADMIN_PLANE_TYPES, AuthenticatedPostgresBackendDriver, BackupToolError, BranchService, BranchingUnsupportedError, CHANNEL_BUS_NOTIFY_CHANNEL, CLEAN_LOCK_TIMEOUT, CONNECTION_OWNER, CleanRestoreFailed, DEFAULT_BATCH_WINDOW_MS, DEFAULT_BRANCH_DIFF_MAX_ROWS, DEFAULT_BRANCH_DIFF_SAMPLE_LIMIT, DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET, DEFAULT_RECOUNT_MIN_ROWS, DatabasePoolManager, DrizzleConditionBuilder, MemoryChannelBus, PG_NOTIFY_MAX_PAYLOAD_BYTES, PUBLIC_TYPES, PostgresBackendDriver, PostgresChannelBus, PostgresCollectionRegistry, PostgresConditionBuilder, PostgresRealtimeProvider, REBASE_USER_ROLE, RealtimeService, RoleSwitchUnavailableError, SESSION_ENDED_CLOSE_CODE, TOO_MANY_SOCKETS_CLOSE_CODE, appConfig, applyGlobals, assertDbCommandLine, backupCronConfigFromEnv, branchParentDatabase, buildBackupFilename, buildPgDumpArgs, buildPgDumpallGlobalsArgs, buildPgRestoreArgs, buildPgRestoreListArgs, buildPgRestoreScriptArgs, buildPsqlScriptArgs, buildRowSecurityPgOptions, cappedPoolMax, checkToolServerCompatibility, cleanRestorePrelude, cliRlsSettings, compareMigrationVersions, configureUnknownFilterFields, createAuthSchema, createBackupCron, createChannelBus, createDirectDatabaseConnection, createDump, createPostgresAdapter, createPostgresBootstrapper, createPostgresDatabaseConnection, createPostgresWebSocket, createReadReplicaConnection, defaultPoolTimeouts, describeSchemaDriftCause, describeUnreadableDump, detectConnectionPosture, detectToolMajor, diagnoseRowSecurityDumpFailure, diffDatabaseBranch, discardPartialDump, effectiveSqlRole, ensureAppRole, ensureAppRoleGrants, ensureDatabaseExists, escapeLikePattern, findCleanExtras, findOtherRoleMembers, findRestoreConflicts, findUnmigratedSchema, frameByteLength, generateSchema, getServerVersionMajor, getUnknownFilterFieldsMode, globalsFileForDump, guardPoolAgainstDirtyRelease, isBackupOfDatabase, isChannelBusInstance, isGeneratedPolicyName, isRoleSwitchingOptedOut, isScaffoldedLocalDatabase, isSocketRealtimeService, joinColumn, joinStorageKey, listBackups, listedColumnKeys, magicLinkTokens, magicLinkTokensRelations, main, mergeDatabaseBranch, mfaChallenges, mfaChallengesRelations, mfaFactors, mfaFactorsRelations, migrationVersionOf, openPostgresDriver, openRebase, packEntityChanges, parseBackupDestination, parseBackupTimestamp, parseChannelBusFrame, parseChannelBusPayload, parseDbNameFromUrl, parseDumpObjects, parseMaxSocketsPerUser, parseMaxSubscriptionsPerSocket, parsePgToolMajor, parseRealtimeTuning, passwordResetTokens, passwordResetTokensRelations, pinSearchPath, poolMaxCeiling, postgresDriverConfigFromEnv, preflight, pruneBackups, readDumpObjects, readRecordedRequestRoles, recordRequestRoles, recoveryCodes, recoveryCodesRelations, refetchConcurrencyFor, refreshTokens, refreshTokensRelations, reopenClosedDatabases, reopenedDatabasesNotice, resetSharedSession, resolveChannelBusSetting, resolveConnectionString, resolveDriftCheckName, resolvePgBinary, resolveRlsSettings, resolveSourceUrls, restoreDump, restoreDumpReplacing, rlsConfigFromEnv, selectBackupsToPrune, serverVersionNumToMajor, socketRealtimeMissing, splitGlobalsStatements, sqlRoleRanAs, uploadBackup, userIdentities, userIdentitiesRelations, users, usersRelations, usersSchema, validateDump, withDatabaseName };
481
489
 
482
490
  //# sourceMappingURL=index.es.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","names":[],"sources":["../src/backup/backup-cron.ts","../src/PostgresAdapter.ts","../src/db-command-line.ts","../src/schema/migration-freshness.ts"],"sourcesContent":["/**\n * Scheduled backups, wired into the server cron system.\n *\n * A backend enables nightly (or custom-schedule) backups by dropping a cron\n * file that default-exports {@link createBackupCron}. The heavy lifting —\n * dump, upload, prune — reuses the same primitives as the CLI so behaviour\n * is identical between a manual `rebase db backup` and an automated run.\n */\nimport fs from \"fs\";\nimport type { CronJobDefinition } from \"@rebasepro/types\";\nimport type { StorageController } from \"@rebasepro/server\";\nimport { logger } from \"@rebasepro/server\";\nimport { pgToolVariable, resolvePgBinary, type PgTool } from \"./pg-binary\";\nimport {\n BackupDestination,\n parseBackupDestination,\n parseDbNameFromUrl,\n resolveConnectionString\n} from \"./pg-tools\";\n// NOTE: `./backup-service` pulls in `execa` (ESM-only). It is imported\n// lazily inside the handler so the pure `backupCronConfigFromEnv` parser can\n// be unit-tested under CommonJS without loading it.\n\nexport interface BackupCronConfig {\n /** Cron expression, e.g. `\"0 3 * * *\"` for 03:00 daily. */\n schedule: string;\n /** Postgres connection string. Defaults to `DATABASE_URL`. */\n connectionString: string;\n /** Where backups are written: a local path or an `s3://` / `gs://` URL. */\n destination: BackupDestination;\n /**\n * Storage controller used for `s3`/`gcs` destinations. Reuse the one the\n * backend already configured (S3/GCS/Local StorageController). Not needed\n * for local destinations.\n */\n storage?: StorageController;\n /** Delete backups older than this many days. `0` disables pruning. */\n retentionDays?: number;\n /** Always keep at least this many recent backups regardless of age. */\n keepMinimum?: number;\n /**\n * Schemas to exclude from the dump. Defaults to none, the same as\n * `rebase db backup` — see {@link createBackupCron} for why `rebase` in\n * particular must stay in.\n */\n excludeSchemas?: string[];\n /** Cron job display name. */\n name?: string;\n /** Whether the job is enabled. */\n enabled?: boolean;\n}\n\nexport interface EnvResolution {\n /** Resolved config, present when a schedule is configured. */\n config?: Omit<BackupCronConfig, \"storage\">;\n /** True when `BACKUP_SCHEDULE` is unset — the cron should be a no-op. */\n disabled?: boolean;\n /** Human-readable reason the config could not be built. */\n error?: string;\n}\n\n/**\n * Build backup-cron config purely from environment variables.\n * Recognised keys:\n * - `BACKUP_SCHEDULE` cron expression (required to enable)\n * - `BACKUP_DESTINATION` local path or `s3://` / `gs://` URL (required)\n * - `BACKUP_RETENTION_DAYS` integer days (optional)\n * - `BACKUP_KEEP_MINIMUM` integer count (optional)\n * - `DATABASE_URL` connection string\n *\n * Pure and side-effect free so it can be unit-tested without a database.\n */\nexport function backupCronConfigFromEnv(env: Record<string, string | undefined>): EnvResolution {\n const schedule = env.BACKUP_SCHEDULE?.trim();\n if (!schedule) {\n return { disabled: true };\n }\n\n const connectionString = resolveConnectionString(env);\n if (!connectionString) {\n return { error: \"BACKUP_SCHEDULE is set but DATABASE_URL is not configured.\" };\n }\n\n const destinationRaw = env.BACKUP_DESTINATION?.trim();\n if (!destinationRaw) {\n return { error: \"BACKUP_SCHEDULE is set but BACKUP_DESTINATION is not configured.\" };\n }\n const destination = parseBackupDestination(destinationRaw);\n\n const retentionDays = parseOptionalInt(env.BACKUP_RETENTION_DAYS);\n if (retentionDays === \"invalid\") {\n return { error: `BACKUP_RETENTION_DAYS must be an integer, got \"${env.BACKUP_RETENTION_DAYS}\".` };\n }\n const keepMinimum = parseOptionalInt(env.BACKUP_KEEP_MINIMUM);\n if (keepMinimum === \"invalid\") {\n return { error: `BACKUP_KEEP_MINIMUM must be an integer, got \"${env.BACKUP_KEEP_MINIMUM}\".` };\n }\n\n return {\n config: {\n schedule,\n connectionString,\n destination,\n retentionDays: retentionDays ?? undefined,\n keepMinimum: keepMinimum ?? undefined\n }\n };\n}\n\nfunction parseOptionalInt(value: string | undefined): number | null | \"invalid\" {\n if (value === undefined || value.trim() === \"\") return null;\n const n = Number(value);\n if (!Number.isInteger(n) || n < 0) return \"invalid\";\n return n;\n}\n\n/**\n * Create a {@link CronJobDefinition} that dumps the database, uploads the\n * result to the configured destination, and prunes old backups. Object\n * destinations require {@link BackupCronConfig.storage}.\n *\n * The dump excludes nothing unless `excludeSchemas` says otherwise, and that\n * default is not this function's to set: the option goes to `createDump`\n * untouched, so `buildPgDumpArgs` decides for the cron and `rebase db backup`\n * alike. The cron used to carry its own default of `[\"rebase\"]`, meant to\n * leave out Atlas's revision table, and it left out a lot more. `rebase` is\n * where the framework keeps\n * everything that is not a collection: the auth tables (`users`, identities,\n * refresh tokens, MFA factors, recovery codes, `app_config`, `schema_meta`),\n * API keys, record history, the job queue, cron logs, channel history,\n * branches and idempotency keys. It also holds the functions that every\n * generated RLS policy and CDC trigger calls (`rebase.uid()`,\n * `rebase.roles()`, `rebase.rebase_cdc_notify()`).\n *\n * None of that can be left for boot to rebuild. Boot recreates the tables\n * and functions, but never the rows in them. And a dump that has a policy\n * or trigger on a `public` table without the function it calls cannot be\n * restored into an empty database: `pg_restore --exit-on-error` stops at\n * the first such statement, and every collection's generated policies call\n * `rebase.uid()`. So every scheduled backup lost every user account, and\n * could not be restored anyway, while `rebase db backup` took a complete\n * one. The revision table belongs in a backup too: without it, a restored\n * database has tables but no record of the migrations that made them.\n */\nexport function createBackupCron(config: BackupCronConfig): CronJobDefinition {\n const dbName = parseDbNameFromUrl(config.connectionString) ?? \"database\";\n if (config.enabled ?? true) warnOfMissingTools(config.name ?? \"Scheduled database backup\");\n\n const job: CronJobDefinition = {\n name: config.name ?? \"Scheduled database backup\",\n schedule: config.schedule,\n description: \"Dumps the Postgres database and uploads it to the configured backup destination.\",\n enabled: config.enabled ?? true,\n // Backups of a large database can take a while; allow up to an hour.\n timeoutSeconds: 3600,\n async handler({ log }) {\n const { createDump, discardPartialDump, pruneBackups, uploadBackup, validateDump } =\n await import(\"./backup-service\");\n const { destination } = config;\n\n if (destination.kind !== \"local\" && !config.storage) {\n throw new Error(\n `Backup destination is ${destination.kind} but no storage controller was provided. ` +\n \"Pass the backend's configured StorageController to createBackupCron({ storage }).\"\n );\n }\n\n log(`Starting backup of \"${dbName}\"…`);\n const outDir = destination.kind === \"local\" ? destination.path : undefined;\n const dump = await createDump({\n connectionString: config.connectionString,\n dbName,\n outDir,\n excludeSchemas: config.excludeSchemas\n });\n log(`Dump created: ${dump.fileName} (${formatBytes(dump.sizeBytes)})`);\n\n // Validate BEFORE pruning: a corrupt-but-exit-0 dump must never be\n // the reason the last good backup gets deleted.\n const check = await validateDump(dump.localFile);\n if (!check.ok) {\n // Discarded for every destination, the roles sidecar with it.\n // On a local one the file *is* the backup: left behind, it\n // keeps a valid backup's name, and retention — which ranks by\n // timestamp and never opens a file — counts it among the\n // newest it keeps while pruning a real backup beneath it.\n if (dump.globalsFile) discardPartialDump(dump.globalsFile);\n discardPartialDump(dump.localFile);\n throw new Error(`New backup failed validation — skipping upload and pruning to protect existing backups. ${check.reason}`);\n }\n\n let storedKey = dump.localFile;\n try {\n if (destination.kind !== \"local\") {\n const uploaded = await uploadBackup(config.storage!, dump.localFile, destination);\n storedKey = uploaded.storageUrl;\n log(`Uploaded to ${uploaded.storageUrl}`);\n // Upload the roles sidecar so a restore can recreate the\n // roles the dump's GRANT/RLS statements depend on.\n if (dump.globalsFile && fs.existsSync(dump.globalsFile)) {\n const g = await uploadBackup(config.storage!, dump.globalsFile, destination);\n log(`Uploaded roles sidecar to ${g.storageUrl}`);\n }\n }\n } finally {\n // For object-storage destinations the local dump was a temp\n // file — remove it once uploaded (or on failure).\n if (destination.kind !== \"local\" && fs.existsSync(dump.localFile)) {\n fs.unlinkSync(dump.localFile);\n }\n if (dump.globalsFile && destination.kind !== \"local\" && fs.existsSync(dump.globalsFile)) {\n fs.unlinkSync(dump.globalsFile);\n }\n }\n\n let pruned: string[] = [];\n if (config.retentionDays && config.retentionDays > 0) {\n pruned = await pruneBackups(\n destination,\n { retentionDays: config.retentionDays, keepMinimum: config.keepMinimum, database: dbName },\n config.storage\n );\n if (pruned.length > 0) {\n log(`Pruned ${pruned.length} backup(s) older than ${config.retentionDays} day(s).`);\n }\n }\n\n return {\n backup: storedKey,\n sizeBytes: dump.sizeBytes,\n pruned: pruned.length\n };\n }\n };\n\n // How the Backups panel finds this job among the project's crons: its id is\n // the cron file's name and its display name is configurable. A registry\n // symbol, so `@rebasepro/server` reads it without importing this package\n // (it must not), and non-enumerable, so a spread or a JSON dump of the\n // definition is unchanged. See `readBackupSchedule` in the server package.\n Object.defineProperty(job, Symbol.for(\"rebase.backupCron\"), { value: true });\n return job;\n}\n\n/**\n * Say at registration, not at 03:00, that the job cannot run.\n *\n * Each run needs `pg_dump` for the dump and `pg_dumpall` for the roles\n * sidecar. Without them every run fails with \"Could not find the 'pg_dump'\n * binary\", and that was the first an operator heard of it — a runtime image\n * once shipped without the client tools, and every nightly backup failed.\n */\nfunction warnOfMissingTools(jobName: string): void {\n const needed: PgTool[] = [\"pg_dump\", \"pg_dumpall\"];\n const missing = needed.filter(tool => !resolvePgBinary(tool));\n if (missing.length === 0) return;\n logger.error(\n `\"${jobName}\" is scheduled, but ${missing.map(tool => `'${tool}'`).join(\" and \")} ` +\n `${missing.length > 1 ? \"were\" : \"was\"} not found on this machine, so every run will fail. ` +\n \"Install the PostgreSQL client tools (the same major version as the server, or newer), \" +\n `or set ${missing.map(pgToolVariable).join(\" / \")} to the binary.`\n );\n}\n\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;\n}\n","import { DatabaseAdapter, InitializedDriver, RealtimeProvider, DataDriver, DatabaseAdmin, BootstrappedAuth } from \"@rebasepro/types\";\nimport { createPostgresBootstrapper } from \"./PostgresBootstrapper\";\nimport type { PostgresDriverConfig } from \"./PostgresBootstrapper\";\n\n/**\n * Creates a Postgres database adapter for Rebase.\n */\nexport function createPostgresAdapter(pgConfig: PostgresDriverConfig): DatabaseAdapter {\n const bootstrapper = createPostgresBootstrapper(pgConfig);\n\n return {\n type: bootstrapper.type,\n\n async initializeDriver(config) {\n return bootstrapper.initializeDriver(config);\n },\n\n async initializeRealtime(driverResult) {\n if (bootstrapper.initializeRealtime) {\n return bootstrapper.initializeRealtime({}, driverResult);\n }\n return undefined;\n },\n\n async initializeAuth(config, driverResult) {\n if (bootstrapper.initializeAuth) {\n return bootstrapper.initializeAuth(config, driverResult);\n }\n return undefined;\n },\n\n async initializeHistory(config, driverResult) {\n if (bootstrapper.initializeHistory) {\n return bootstrapper.initializeHistory(config, driverResult);\n }\n return undefined;\n },\n\n // `adapter` and `limits` are forwarded for the same reason the schema\n // hooks below are: dropping an argument here is invisible at the call\n // site and silent at runtime. `adapter` decided whether the realtime\n // socket authenticates at all — without it, a server whose auth comes\n // from an AuthAdapter fell back to \"is a jwtSecret set?\", answered no,\n // and admitted every client. `limits` are the data API's body and rate\n // limits; dropped, the socket has neither.\n initializeWebsockets(server, realtimeService, driver, config, adapter, limits) {\n if (bootstrapper.initializeWebsockets) {\n return bootstrapper.initializeWebsockets(server, realtimeService, driver, config, adapter, limits);\n }\n },\n\n // Forwarded so the boot-time schema/RLS provisioning is reachable when\n // this adapter is wrapped back into a bootstrapper. Omitting either left\n // a managed tenant with no tables (500 on every data route) or tables\n // but no policies (401 on every read) — the create step never ran.\n verifyConnection: bootstrapper.verifyConnection\n ? (driverResult) => bootstrapper.verifyConnection!(driverResult)\n : undefined,\n\n ensureCollectionSchema: bootstrapper.ensureCollectionSchema\n ? (collections, driverResult, log) =>\n bootstrapper.ensureCollectionSchema!(collections, driverResult, log)\n : undefined,\n\n // Same rule, and it bit at once: the method existed on the bootstrapper,\n // this wrapper did not forward it, and a second database booted with\n // tables and no helper functions — every policy on it silently failed\n // to create. The adapter type is where a forgotten forward should fail\n // to compile; `adapter-forwarding.test.ts` sweeps for exactly this.\n ensureRlsRuntime: bootstrapper.ensureRlsRuntime\n ? (driverResult) => bootstrapper.ensureRlsRuntime!(driverResult)\n : undefined,\n\n ensureCollectionPolicies: bootstrapper.ensureCollectionPolicies\n ? (collections, driverResult, log) =>\n bootstrapper.ensureCollectionPolicies!(collections, driverResult, log)\n : undefined,\n\n finalizeSecurityPosture: bootstrapper.finalizeSecurityPosture\n ? (driverResult) => bootstrapper.finalizeSecurityPosture!(driverResult)\n : undefined,\n\n // Same forwarding rule, third instance. Dropping these is not a type\n // error and not a runtime error: the stamp is simply never written and\n // never read, so a split deployment loses the only thing that would tell\n // it a unit is serving against a schema it was not built for — and a\n // check that is off looks exactly like a check that passed. This one was\n // in fact dropped on the first attempt, and the e2e caught it.\n readCollectionsSchemaVersion: bootstrapper.readCollectionsSchemaVersion\n ? (driverResult) => bootstrapper.readCollectionsSchemaVersion!(driverResult)\n : undefined,\n\n stampCollectionsSchemaVersion: bootstrapper.stampCollectionsSchemaVersion\n ? (version, driverResult) => bootstrapper.stampCollectionsSchemaVersion!(version, driverResult)\n : undefined,\n\n getAdmin(driverResult) {\n if (bootstrapper.getAdmin) {\n return bootstrapper.getAdmin(driverResult);\n }\n return undefined;\n }\n };\n}\n","/**\n * Every `rebase db …` line this driver answers, judged without connecting to\n * anything.\n *\n * The driver refuses a flag a command does not take, but it is spawned only\n * once the CLI has a database for it, and getting one means starting one: the\n * remembered compose container, or the managed PGlite daemon. So `rebase db\n * push --dry-rn` booted the database and then said the flag did not exist.\n * The CLI runs this first, from the driver's own code, so the answer it gives\n * before starting anything and the one the driver would give after are one\n * check, not two lists to keep in step.\n *\n * Each entry calls the parse its command runs itself, never a copy of it.\n */\nimport { assertKnownFlags } from \"./cli-flags\";\nimport { assertKnownBranchFlags } from \"./branch-argv\";\nimport { backupActionOf } from \"./backup-argv\";\nimport { parseBackupLine, parseBackupsListLine, parseRestoreLine } from \"./backup/backup-cli\";\nimport { isDriverDbSubcommand, type DriverDbSubcommand } from \"./db-subcommands\";\n\n/**\n * The check each subcommand's line gets. A `Record` over the union, so a\n * subcommand added to `DRIVER_DB_SUBCOMMANDS` does not compile until it says\n * how its line is judged.\n */\nconst LINE_CHECKS: Record<DriverDbSubcommand, (args: string[]) => void> = {\n push: args => assertKnownFlags(\"db\", \"push\", args),\n generate: args => assertKnownFlags(\"db\", \"generate\", args),\n migrate: args => assertKnownFlags(\"db\", \"migrate\", args),\n // The action's own table; an action the table does not list is the\n // dispatch's to answer, in its own words.\n branch: (args) => {\n if (args[2] !== undefined) assertKnownBranchFlags(args[2], args.slice(3));\n },\n backup: (args) => {\n if (backupActionOf(args) === \"list\") parseBackupsListLine(args);\n else parseBackupLine(args);\n },\n restore: (args) => { parseRestoreLine(args); },\n backups: (args) => {\n if (args[2] === \"list\") parseBackupsListLine(args);\n }\n};\n\n/**\n * Throw what the driver would say of a `rebase db …` line it refuses on its\n * flags, before it would connect: an option the command does not take, and\n * the checks `db backup` and `db restore` make of their own line (a stray\n * word, a pattern that leaves out the rebase schema).\n *\n * Reads no environment and opens nothing, so it is safe to run before a\n * database exists.\n *\n * @param args the driver's line: `[\"db\", \"<subcommand>\", …]`, without the\n * CLI's own words in front. A line for a subcommand this driver does not\n * answer passes, for the dispatch to refuse.\n */\nexport function assertDbCommandLine(args: readonly string[]): void {\n const [domain, subcommand] = args;\n if (domain !== \"db\" || !isDriverDbSubcommand(subcommand)) return;\n // `--help` is answered before any check, by the CLI and by the dispatch.\n if (args.includes(\"--help\") || args.includes(\"-h\")) return;\n LINE_CHECKS[subcommand]([...args]);\n}\n","/**\n * Do the migration files still describe the collections?\n *\n * `rebase db generate` asks Atlas, which needs a dev database to replay the\n * migrations into — seconds of Docker, or the managed PGlite, before it can say\n * a word. `rebase verify` runs after every edit an agent makes to a collection\n * file and in CI, where neither is acceptable, so this answers the narrower\n * question offline: replay the `CREATE TABLE` / `ALTER TABLE` / `DROP TABLE`\n * statements the migrations contain, and compare the tables and columns that\n * leaves with the ones the schema plan derives from the collections.\n *\n * Deliberately tables and columns only. A changed type or default is a real\n * drift too, but reading it back out of Atlas's SQL means parsing every type\n * spelling Postgres accepts, and a check that misreads `character varying(255)`\n * as a change cries wolf on every run. A missing table or column is the drift\n * that breaks a deploy — the runtime queries a column the migrated database\n * does not have — and it is unambiguous in the text.\n *\n * Policies are not compared: the runtime applies a collection's policies at\n * boot whether or not a migration carries them.\n */\nimport type { CollectionConfig } from \"@rebasepro/types\";\nimport { planSchema } from \"./plan/plan-schema\";\n\n/** One difference between the collections and what the migrations build. */\nexport interface UnmigratedChange {\n /**\n * - `missing-table` / `missing-column` — the collections declare it and no\n * migration creates it.\n * - `removed-column` — a migration creates it, the collection no longer\n * declares it, and no later migration drops it.\n */\n kind: \"missing-table\" | \"missing-column\" | \"removed-column\";\n /** `schema.table`. */\n table: string;\n column?: string;\n /** The collection that declares the table, when one does (a junction has none). */\n slug?: string;\n}\n\n/** A table as the migrations leave it. */\ninterface MigratedTable {\n /** Every column, however it was added. */\n columns: Set<string>;\n /**\n * The columns Atlas wrote: from a `CREATE TABLE` or an `ADD COLUMN` without\n * `IF NOT EXISTS`. The search, vector and trigger DDL `db generate` appends\n * after Atlas's half always says `IF NOT EXISTS`, and the planner keeps\n * those columns out of `TablePlan.columns` — so only these are candidates\n * for \"removed from the collection\".\n */\n managed: Set<string>;\n}\n\n/** Blank out `--` and `/* *\\/` comments, leaving string and identifier literals alone. */\nfunction stripComments(sql: string): string {\n let out = \"\";\n let i = 0;\n while (i < sql.length) {\n const ch = sql[i];\n if (ch === \"'\" || ch === \"\\\"\") {\n const end = sql.indexOf(ch, i + 1);\n const stop = end === -1 ? sql.length : end + 1;\n out += sql.slice(i, stop);\n i = stop;\n } else if (ch === \"-\" && sql[i + 1] === \"-\") {\n const end = sql.indexOf(\"\\n\", i);\n i = end === -1 ? sql.length : end;\n } else if (ch === \"/\" && sql[i + 1] === \"*\") {\n const end = sql.indexOf(\"*/\", i + 2);\n i = end === -1 ? sql.length : end + 2;\n } else if (ch === \"$\") {\n // A dollar-quoted body (`$$ … $$`, `$fn$ … $fn$`) is copied whole: a\n // function body is full of `--` and `;` that are not ours to read.\n const tag = /^\\$[A-Za-z_]*\\$/.exec(sql.slice(i))?.[0];\n if (!tag) {\n out += ch;\n i++;\n continue;\n }\n const end = sql.indexOf(tag, i + tag.length);\n const stop = end === -1 ? sql.length : end + tag.length;\n out += sql.slice(i, stop);\n i = stop;\n } else {\n out += ch;\n i++;\n }\n }\n return out;\n}\n\n/**\n * Split on a separator at nesting depth zero, outside quotes and dollar quotes.\n * `;` splits a file into statements, `,` a column list into its elements.\n */\nfunction splitTopLevel(text: string, separator: \";\" | \",\"): string[] {\n const parts: string[] = [];\n let depth = 0;\n let start = 0;\n let i = 0;\n while (i < text.length) {\n const ch = text[i];\n if (ch === \"'\" || ch === \"\\\"\") {\n const end = text.indexOf(ch, i + 1);\n i = end === -1 ? text.length : end + 1;\n continue;\n }\n if (ch === \"$\") {\n const tag = /^\\$[A-Za-z_]*\\$/.exec(text.slice(i))?.[0];\n if (tag) {\n const end = text.indexOf(tag, i + tag.length);\n i = end === -1 ? text.length : end + tag.length;\n continue;\n }\n }\n if (ch === \"(\") depth++;\n else if (ch === \")\") depth--;\n else if (ch === separator && depth === 0) {\n parts.push(text.slice(start, i));\n start = i + 1;\n }\n i++;\n }\n parts.push(text.slice(start));\n return parts.map(p => p.trim()).filter(p => p.length > 0);\n}\n\n/** One identifier: `\"Quoted\"` keeps its case, a bare word folds to lower case as Postgres folds it. */\nconst IDENT = String.raw`(?:\"(?:[^\"]|\"\")+\"|[A-Za-z_][A-Za-z0-9_$]*)`;\n/** An optionally schema-qualified name. */\nconst QUALIFIED = String.raw`${IDENT}(?:\\s*\\.\\s*${IDENT})?`;\n\nfunction unquote(identifier: string): string {\n const trimmed = identifier.trim();\n return trimmed.startsWith(\"\\\"\") ? trimmed.slice(1, -1).replace(/\"\"/g, \"\\\"\") : trimmed.toLowerCase();\n}\n\n/** `\"public\".\"posts\"` → `public.posts`; an unqualified name is in `public`. */\nfunction qualifiedName(name: string): string {\n const [first = \"\", second] = name.match(new RegExp(IDENT, \"g\")) ?? [];\n return second !== undefined ? `${unquote(first)}.${unquote(second)}` : `public.${unquote(first)}`;\n}\n\n/** Words that open a table constraint rather than a column, inside `CREATE TABLE ( … )`. */\nconst TABLE_CONSTRAINT = /^(CONSTRAINT|PRIMARY|UNIQUE|FOREIGN|CHECK|EXCLUDE|LIKE)\\b/i;\n\nconst CREATE_TABLE = new RegExp(String.raw`^CREATE\\s+(?:UNLOGGED\\s+)?TABLE\\s+(IF\\s+NOT\\s+EXISTS\\s+)?(${QUALIFIED})\\s*\\(([\\s\\S]*)\\)[^)]*$`, \"i\");\nconst ALTER_TABLE = new RegExp(String.raw`^ALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?(${QUALIFIED})\\s+([\\s\\S]*)$`, \"i\");\nconst DROP_TABLE = /^DROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?([\\s\\S]*?)(?:\\s+(?:CASCADE|RESTRICT))?$/i;\nconst ADD_COLUMN = new RegExp(String.raw`^ADD\\s+(?:COLUMN\\s+)?(IF\\s+NOT\\s+EXISTS\\s+)?(${IDENT})`, \"i\");\nconst DROP_COLUMN = new RegExp(String.raw`^DROP\\s+(?:COLUMN\\s+)?(?:IF\\s+EXISTS\\s+)?(${IDENT})`, \"i\");\nconst RENAME_COLUMN = new RegExp(String.raw`^RENAME\\s+(?:COLUMN\\s+)?(${IDENT})\\s+TO\\s+(${IDENT})$`, \"i\");\nconst RENAME_TABLE = new RegExp(String.raw`^RENAME\\s+TO\\s+(${IDENT})$`, \"i\");\n\n/**\n * The tables and columns the migrations leave behind, replayed in order.\n *\n * Exported for its tests.\n */\nexport function replayMigrationTables(migrations: readonly string[]): Map<string, MigratedTable> {\n const tables = new Map<string, MigratedTable>();\n const tableOf = (name: string): MigratedTable => {\n let table = tables.get(name);\n if (!table) {\n table = { columns: new Set(), managed: new Set() };\n tables.set(name, table);\n }\n return table;\n };\n\n for (const migration of migrations) {\n for (const raw of splitTopLevel(stripComments(migration), \";\")) {\n const statement = raw.replace(/\\s+/g, \" \").trim();\n\n const created = CREATE_TABLE.exec(statement);\n if (created) {\n const table = tableOf(qualifiedName(created[2]));\n const managed = !created[1];\n for (const element of splitTopLevel(created[3], \",\")) {\n if (TABLE_CONSTRAINT.test(element)) continue;\n const column = new RegExp(`^${IDENT}`).exec(element)?.[0];\n if (!column) continue;\n table.columns.add(unquote(column));\n if (managed) table.managed.add(unquote(column));\n }\n continue;\n }\n\n const altered = ALTER_TABLE.exec(statement);\n if (altered) {\n const name = qualifiedName(altered[1]);\n for (const action of splitTopLevel(altered[2], \",\")) {\n const renamedTable = RENAME_TABLE.exec(action);\n if (renamedTable) {\n const existing = tables.get(name);\n tables.delete(name);\n const target = `${name.split(\".\")[0]}.${unquote(renamedTable[1])}`;\n if (existing) tables.set(target, existing);\n continue;\n }\n const renamed = RENAME_COLUMN.exec(action);\n if (renamed) {\n const table = tableOf(name);\n const from = unquote(renamed[1]);\n const to = unquote(renamed[2]);\n table.columns.delete(from);\n table.columns.add(to);\n if (table.managed.delete(from)) table.managed.add(to);\n continue;\n }\n const added = ADD_COLUMN.exec(action);\n if (added && !/^ADD\\s+(CONSTRAINT|PRIMARY|UNIQUE|FOREIGN|CHECK|EXCLUDE)\\b/i.test(action)) {\n const table = tableOf(name);\n const column = unquote(added[2]);\n table.columns.add(column);\n if (!added[1]) table.managed.add(column);\n continue;\n }\n const dropped = DROP_COLUMN.exec(action);\n if (dropped && !/^DROP\\s+(CONSTRAINT|DEFAULT|NOT|EXPRESSION|IDENTITY)\\b/i.test(action)) {\n const table = tableOf(name);\n const column = unquote(dropped[1]);\n table.columns.delete(column);\n table.managed.delete(column);\n }\n }\n continue;\n }\n\n const droppedTables = DROP_TABLE.exec(statement);\n if (droppedTables) {\n for (const name of splitTopLevel(droppedTables[1], \",\")) tables.delete(qualifiedName(name));\n }\n }\n }\n return tables;\n}\n\n/**\n * What the collections declare that the migrations do not build, and what the\n * migrations still build that the collections dropped.\n *\n * `migrations` are the contents of every `.sql` file in the migrations\n * directory, in file-name order — Atlas's order. An empty list is a project\n * with no migrations at all, for which everything is missing; whether that is a\n * problem (a project on `db push` has none by design) is the caller's call.\n *\n * Throws what {@link planSchema} throws for a configuration it cannot plan.\n */\nexport function findUnmigratedSchema(\n collections: CollectionConfig[],\n migrations: readonly string[]\n): UnmigratedChange[] {\n const plan = planSchema(collections);\n const migrated = replayMigrationTables(migrations);\n const changes: UnmigratedChange[] = [];\n\n for (const table of plan.tables) {\n const slug = table.slug;\n const existing = migrated.get(table.qualified);\n if (!existing) {\n changes.push({ kind: \"missing-table\", table: table.qualified, ...(slug && { slug }) });\n continue;\n }\n // The users table is shared with the auth tables boot provisions\n // (`auth-users-columns`), which add columns no collection declares and\n // no migration has to carry. The table's existence is the fact here.\n if (table.auth) continue;\n\n // A search column is carved out of Atlas's diff and added by the\n // search DDL `db generate` appends (`ADD COLUMN IF NOT EXISTS`), which\n // a migration from before the block was declared does not carry and\n // the runtime applies itself — not a migration's to own.\n const planned = new Set(table.columns\n .filter(column => column.source.kind !== \"search\")\n .map(column => column.column));\n for (const column of planned) {\n if (!existing.columns.has(column)) {\n changes.push({ kind: \"missing-column\", table: table.qualified, column, ...(slug && { slug }) });\n }\n }\n for (const column of existing.managed) {\n if (!planned.has(column)) {\n changes.push({ kind: \"removed-column\", table: table.qualified, column, ...(slug && { slug }) });\n }\n }\n }\n return changes;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwEA,SAAgB,w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AK;GAAE,MAAM;GAAkB,OAAO,MAAM;GAAW;GAAQ,GAAI,QAAQ,EAAE,KAAK;EAAG,CAAC;EAGtG,KAAK,MAAM,UAAU,SAAS,SAC1B,IAAI,CAAC,QAAQ,IAAI,MAAM,GACnB,QAAQ,KAAK;GAAE,MAAM;GAAkB,OAAO,MAAM;GAAW;GAAQ,GAAI,QAAQ,EAAE,KAAK;EAAG,CAAC;CAG1G;CACA,OAAO;AACX"}
1
+ {"version":3,"file":"index.es.js","names":[],"sources":["../src/backup/backup-cron.ts","../src/PostgresAdapter.ts","../src/db-command-line.ts","../src/schema/migration-freshness.ts"],"sourcesContent":["/**\n * Scheduled backups, wired into the server cron system.\n *\n * A backend enables nightly (or custom-schedule) backups by dropping a cron\n * file that default-exports {@link createBackupCron}. The heavy lifting —\n * dump, upload, prune — reuses the same primitives as the CLI so behaviour\n * is identical between a manual `rebase db backup` and an automated run.\n */\nimport fs from \"fs\";\nimport type { CronJobDefinition } from \"@rebasepro/types\";\nimport type { StorageController } from \"@rebasepro/server\";\nimport { logger } from \"@rebasepro/server\";\nimport { pgToolVariable, resolvePgBinary, type PgTool } from \"./pg-binary\";\nimport {\n BackupDestination,\n parseBackupDestination,\n parseDbNameFromUrl,\n resolveConnectionString\n} from \"./pg-tools\";\n// NOTE: `./backup-service` pulls in `execa` (ESM-only). It is imported\n// lazily inside the handler so the pure `backupCronConfigFromEnv` parser can\n// be unit-tested under CommonJS without loading it.\n\nexport interface BackupCronConfig {\n /** Cron expression, e.g. `\"0 3 * * *\"` for 03:00 daily. */\n schedule: string;\n /** Postgres connection string. Defaults to `DATABASE_URL`. */\n connectionString: string;\n /** Where backups are written: a local path or an `s3://` / `gs://` URL. */\n destination: BackupDestination;\n /**\n * Storage controller used for `s3`/`gcs` destinations. Reuse the one the\n * backend already configured (S3/GCS/Local StorageController). Not needed\n * for local destinations.\n */\n storage?: StorageController;\n /** Delete backups older than this many days. `0` disables pruning. */\n retentionDays?: number;\n /** Always keep at least this many recent backups regardless of age. */\n keepMinimum?: number;\n /**\n * Schemas to exclude from the dump. Defaults to none, the same as\n * `rebase db backup` — see {@link createBackupCron} for why `rebase` in\n * particular must stay in.\n */\n excludeSchemas?: string[];\n /** Cron job display name. */\n name?: string;\n /** Whether the job is enabled. */\n enabled?: boolean;\n}\n\nexport interface EnvResolution {\n /** Resolved config, present when a schedule is configured. */\n config?: Omit<BackupCronConfig, \"storage\">;\n /** True when `BACKUP_SCHEDULE` is unset — the cron should be a no-op. */\n disabled?: boolean;\n /** Human-readable reason the config could not be built. */\n error?: string;\n}\n\n/**\n * Build backup-cron config purely from environment variables.\n * Recognised keys:\n * - `BACKUP_SCHEDULE` cron expression (required to enable)\n * - `BACKUP_DESTINATION` local path or `s3://` / `gs://` URL (required)\n * - `BACKUP_RETENTION_DAYS` integer days (optional)\n * - `BACKUP_KEEP_MINIMUM` integer count (optional)\n * - `DATABASE_URL` connection string\n *\n * Pure and side-effect free so it can be unit-tested without a database.\n */\nexport function backupCronConfigFromEnv(env: Record<string, string | undefined>): EnvResolution {\n const schedule = env.BACKUP_SCHEDULE?.trim();\n if (!schedule) {\n return { disabled: true };\n }\n\n const connectionString = resolveConnectionString(env);\n if (!connectionString) {\n return { error: \"BACKUP_SCHEDULE is set but DATABASE_URL is not configured.\" };\n }\n\n const destinationRaw = env.BACKUP_DESTINATION?.trim();\n if (!destinationRaw) {\n return { error: \"BACKUP_SCHEDULE is set but BACKUP_DESTINATION is not configured.\" };\n }\n const destination = parseBackupDestination(destinationRaw);\n\n const retentionDays = parseOptionalInt(env.BACKUP_RETENTION_DAYS);\n if (retentionDays === \"invalid\") {\n return { error: `BACKUP_RETENTION_DAYS must be an integer, got \"${env.BACKUP_RETENTION_DAYS}\".` };\n }\n const keepMinimum = parseOptionalInt(env.BACKUP_KEEP_MINIMUM);\n if (keepMinimum === \"invalid\") {\n return { error: `BACKUP_KEEP_MINIMUM must be an integer, got \"${env.BACKUP_KEEP_MINIMUM}\".` };\n }\n\n return {\n config: {\n schedule,\n connectionString,\n destination,\n retentionDays: retentionDays ?? undefined,\n keepMinimum: keepMinimum ?? undefined\n }\n };\n}\n\nfunction parseOptionalInt(value: string | undefined): number | null | \"invalid\" {\n if (value === undefined || value.trim() === \"\") return null;\n const n = Number(value);\n if (!Number.isInteger(n) || n < 0) return \"invalid\";\n return n;\n}\n\n/**\n * Create a {@link CronJobDefinition} that dumps the database, uploads the\n * result to the configured destination, and prunes old backups. Object\n * destinations require {@link BackupCronConfig.storage}.\n *\n * The dump excludes nothing unless `excludeSchemas` says otherwise, and that\n * default is not this function's to set: the option goes to `createDump`\n * untouched, so `buildPgDumpArgs` decides for the cron and `rebase db backup`\n * alike. The cron used to carry its own default of `[\"rebase\"]`, meant to\n * leave out Atlas's revision table, and it left out a lot more. `rebase` is\n * where the framework keeps\n * everything that is not a collection: the auth tables (`users`, identities,\n * refresh tokens, MFA factors, recovery codes, `app_config`, `schema_meta`),\n * API keys, record history, the job queue, cron logs, channel history,\n * branches and idempotency keys. It also holds the functions that every\n * generated RLS policy and CDC trigger calls (`rebase.uid()`,\n * `rebase.roles()`, `rebase.rebase_cdc_notify()`).\n *\n * None of that can be left for boot to rebuild. Boot recreates the tables\n * and functions, but never the rows in them. And a dump that has a policy\n * or trigger on a `public` table without the function it calls cannot be\n * restored into an empty database: `pg_restore --exit-on-error` stops at\n * the first such statement, and every collection's generated policies call\n * `rebase.uid()`. So every scheduled backup lost every user account, and\n * could not be restored anyway, while `rebase db backup` took a complete\n * one. The revision table belongs in a backup too: without it, a restored\n * database has tables but no record of the migrations that made them.\n */\nexport function createBackupCron(config: BackupCronConfig): CronJobDefinition {\n const dbName = parseDbNameFromUrl(config.connectionString) ?? \"database\";\n if (config.enabled ?? true) warnOfMissingTools(config.name ?? \"Scheduled database backup\");\n\n const job: CronJobDefinition = {\n name: config.name ?? \"Scheduled database backup\",\n schedule: config.schedule,\n description: \"Dumps the Postgres database and uploads it to the configured backup destination.\",\n enabled: config.enabled ?? true,\n // Backups of a large database can take a while; allow up to an hour.\n timeoutSeconds: 3600,\n async handler({ log }) {\n const { createDump, discardPartialDump, pruneBackups, uploadBackup, validateDump } =\n await import(\"./backup-service\");\n const { destination } = config;\n\n if (destination.kind !== \"local\" && !config.storage) {\n throw new Error(\n `Backup destination is ${destination.kind} but no storage controller was provided. ` +\n \"Pass the backend's configured StorageController to createBackupCron({ storage }).\"\n );\n }\n\n log(`Starting backup of \"${dbName}\"…`);\n const outDir = destination.kind === \"local\" ? destination.path : undefined;\n const dump = await createDump({\n connectionString: config.connectionString,\n dbName,\n outDir,\n excludeSchemas: config.excludeSchemas\n });\n log(`Dump created: ${dump.fileName} (${formatBytes(dump.sizeBytes)})`);\n\n // Validate BEFORE pruning: a corrupt-but-exit-0 dump must never be\n // the reason the last good backup gets deleted.\n const check = await validateDump(dump.localFile);\n if (!check.ok) {\n // Discarded for every destination, the roles sidecar with it.\n // On a local one the file *is* the backup: left behind, it\n // keeps a valid backup's name, and retention — which ranks by\n // timestamp and never opens a file — counts it among the\n // newest it keeps while pruning a real backup beneath it.\n if (dump.globalsFile) discardPartialDump(dump.globalsFile);\n discardPartialDump(dump.localFile);\n throw new Error(`New backup failed validation — skipping upload and pruning to protect existing backups. ${check.reason}`);\n }\n\n let storedKey = dump.localFile;\n try {\n if (destination.kind !== \"local\") {\n const uploaded = await uploadBackup(config.storage!, dump.localFile, destination);\n storedKey = uploaded.storageUrl;\n log(`Uploaded to ${uploaded.storageUrl}`);\n // Upload the roles sidecar so a restore can recreate the\n // roles the dump's GRANT/RLS statements depend on.\n if (dump.globalsFile && fs.existsSync(dump.globalsFile)) {\n const g = await uploadBackup(config.storage!, dump.globalsFile, destination);\n log(`Uploaded roles sidecar to ${g.storageUrl}`);\n }\n }\n } finally {\n // For object-storage destinations the local dump was a temp\n // file — remove it once uploaded (or on failure).\n if (destination.kind !== \"local\" && fs.existsSync(dump.localFile)) {\n fs.unlinkSync(dump.localFile);\n }\n if (dump.globalsFile && destination.kind !== \"local\" && fs.existsSync(dump.globalsFile)) {\n fs.unlinkSync(dump.globalsFile);\n }\n }\n\n let pruned: string[] = [];\n if (config.retentionDays && config.retentionDays > 0) {\n pruned = await pruneBackups(\n destination,\n { retentionDays: config.retentionDays, keepMinimum: config.keepMinimum, database: dbName },\n config.storage\n );\n if (pruned.length > 0) {\n log(`Pruned ${pruned.length} backup(s) older than ${config.retentionDays} day(s).`);\n }\n }\n\n return {\n backup: storedKey,\n sizeBytes: dump.sizeBytes,\n pruned: pruned.length\n };\n }\n };\n\n // How the Backups panel finds this job among the project's crons: its id is\n // the cron file's name and its display name is configurable. A registry\n // symbol, so `@rebasepro/server` reads it without importing this package\n // (it must not), and non-enumerable, so a spread or a JSON dump of the\n // definition is unchanged. See `readBackupSchedule` in the server package.\n Object.defineProperty(job, Symbol.for(\"rebase.backupCron\"), { value: true });\n return job;\n}\n\n/**\n * Say at registration, not at 03:00, that the job cannot run.\n *\n * Each run needs `pg_dump` for the dump and `pg_dumpall` for the roles\n * sidecar. Without them every run fails with \"Could not find the 'pg_dump'\n * binary\", and that was the first an operator heard of it — a runtime image\n * once shipped without the client tools, and every nightly backup failed.\n */\nfunction warnOfMissingTools(jobName: string): void {\n const needed: PgTool[] = [\"pg_dump\", \"pg_dumpall\"];\n const missing = needed.filter(tool => !resolvePgBinary(tool));\n if (missing.length === 0) return;\n logger.error(\n `\"${jobName}\" is scheduled, but ${missing.map(tool => `'${tool}'`).join(\" and \")} ` +\n `${missing.length > 1 ? \"were\" : \"was\"} not found on this machine, so every run will fail. ` +\n \"Install the PostgreSQL client tools (the same major version as the server, or newer), \" +\n `or set ${missing.map(pgToolVariable).join(\" / \")} to the binary.`\n );\n}\n\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;\n}\n","import { DatabaseAdapter, InitializedDriver, RealtimeProvider, DataDriver, DatabaseAdmin, BootstrappedAuth } from \"@rebasepro/types\";\nimport { createPostgresBootstrapper } from \"./PostgresBootstrapper\";\nimport type { PostgresDriverConfig } from \"./PostgresBootstrapper\";\n\n/**\n * Creates a Postgres database adapter for Rebase.\n */\nexport function createPostgresAdapter(pgConfig: PostgresDriverConfig): DatabaseAdapter {\n const bootstrapper = createPostgresBootstrapper(pgConfig);\n\n return {\n type: bootstrapper.type,\n\n async initializeDriver(config) {\n return bootstrapper.initializeDriver(config);\n },\n\n async initializeRealtime(driverResult) {\n if (bootstrapper.initializeRealtime) {\n return bootstrapper.initializeRealtime({}, driverResult);\n }\n return undefined;\n },\n\n async initializeAuth(config, driverResult) {\n if (bootstrapper.initializeAuth) {\n return bootstrapper.initializeAuth(config, driverResult);\n }\n return undefined;\n },\n\n async initializeHistory(config, driverResult) {\n if (bootstrapper.initializeHistory) {\n return bootstrapper.initializeHistory(config, driverResult);\n }\n return undefined;\n },\n\n // `adapter` and `limits` are forwarded for the same reason the schema\n // hooks below are: dropping an argument here is invisible at the call\n // site and silent at runtime. `adapter` decided whether the realtime\n // socket authenticates at all — without it, a server whose auth comes\n // from an AuthAdapter fell back to \"is a jwtSecret set?\", answered no,\n // and admitted every client. `limits` are the data API's body and rate\n // limits; dropped, the socket has neither.\n initializeWebsockets(server, realtimeService, driver, config, adapter, limits) {\n if (bootstrapper.initializeWebsockets) {\n return bootstrapper.initializeWebsockets(server, realtimeService, driver, config, adapter, limits);\n }\n },\n\n // Forwarded so the boot-time schema/RLS provisioning is reachable when\n // this adapter is wrapped back into a bootstrapper. Omitting either left\n // a managed tenant with no tables (500 on every data route) or tables\n // but no policies (401 on every read) — the create step never ran.\n verifyConnection: bootstrapper.verifyConnection\n ? (driverResult) => bootstrapper.verifyConnection!(driverResult)\n : undefined,\n\n ensureCollectionSchema: bootstrapper.ensureCollectionSchema\n ? (collections, driverResult, log) =>\n bootstrapper.ensureCollectionSchema!(collections, driverResult, log)\n : undefined,\n\n // Same rule, and it bit at once: the method existed on the bootstrapper,\n // this wrapper did not forward it, and a second database booted with\n // tables and no helper functions — every policy on it silently failed\n // to create. The adapter type is where a forgotten forward should fail\n // to compile; `adapter-forwarding.test.ts` sweeps for exactly this.\n ensureRlsRuntime: bootstrapper.ensureRlsRuntime\n ? (driverResult) => bootstrapper.ensureRlsRuntime!(driverResult)\n : undefined,\n\n ensureCollectionPolicies: bootstrapper.ensureCollectionPolicies\n ? (collections, driverResult, log) =>\n bootstrapper.ensureCollectionPolicies!(collections, driverResult, log)\n : undefined,\n\n finalizeSecurityPosture: bootstrapper.finalizeSecurityPosture\n ? (driverResult) => bootstrapper.finalizeSecurityPosture!(driverResult)\n : undefined,\n\n // Same forwarding rule, third instance. Dropping these is not a type\n // error and not a runtime error: the stamp is simply never written and\n // never read, so a split deployment loses the only thing that would tell\n // it a unit is serving against a schema it was not built for — and a\n // check that is off looks exactly like a check that passed. This one was\n // in fact dropped on the first attempt, and the e2e caught it.\n readCollectionsSchemaVersion: bootstrapper.readCollectionsSchemaVersion\n ? (driverResult) => bootstrapper.readCollectionsSchemaVersion!(driverResult)\n : undefined,\n\n stampCollectionsSchemaVersion: bootstrapper.stampCollectionsSchemaVersion\n ? (version, driverResult) => bootstrapper.stampCollectionsSchemaVersion!(version, driverResult)\n : undefined,\n\n getAdmin(driverResult) {\n if (bootstrapper.getAdmin) {\n return bootstrapper.getAdmin(driverResult);\n }\n return undefined;\n }\n };\n}\n","/**\n * Every `rebase db …` line this driver answers, judged without connecting to\n * anything.\n *\n * The driver refuses a flag a command does not take, but it is spawned only\n * once the CLI has a database for it, and getting one means starting one: the\n * remembered compose container, or the managed PGlite daemon. So `rebase db\n * push --dry-rn` booted the database and then said the flag did not exist.\n * The CLI runs this first, from the driver's own code, so the answer it gives\n * before starting anything and the one the driver would give after are one\n * check, not two lists to keep in step.\n *\n * Each entry calls the parse its command runs itself, never a copy of it.\n */\nimport { assertKnownFlags } from \"./cli-flags\";\nimport { assertKnownBranchFlags } from \"./branch-argv\";\nimport { backupActionOf } from \"./backup-argv\";\nimport { parseBackupLine, parseBackupsListLine, parseRestoreLine } from \"./backup/backup-cli\";\nimport { isDriverDbSubcommand, type DriverDbSubcommand } from \"./db-subcommands\";\nimport { parseProvisionLine, parseRequestRoleLine } from \"./request-role-cli\";\n\n/**\n * The check each subcommand's line gets. A `Record` over the union, so a\n * subcommand added to `DRIVER_DB_SUBCOMMANDS` does not compile until it says\n * how its line is judged.\n */\nconst LINE_CHECKS: Record<DriverDbSubcommand, (args: string[]) => void> = {\n push: args => assertKnownFlags(\"db\", \"push\", args),\n generate: args => assertKnownFlags(\"db\", \"generate\", args),\n migrate: args => assertKnownFlags(\"db\", \"migrate\", args),\n // The action's own table; an action the table does not list is the\n // dispatch's to answer, in its own words.\n branch: (args) => {\n if (args[2] !== undefined) assertKnownBranchFlags(args[2], args.slice(3));\n },\n backup: (args) => {\n if (backupActionOf(args) === \"list\") parseBackupsListLine(args);\n else parseBackupLine(args);\n },\n restore: (args) => { parseRestoreLine(args); },\n backups: (args) => {\n if (args[2] === \"list\") parseBackupsListLine(args);\n },\n \"request-role\": (args) => { parseRequestRoleLine(args); },\n provision: (args) => { parseProvisionLine(args); }\n};\n\n/**\n * Throw what the driver would say of a `rebase db …` line it refuses on its\n * flags, before it would connect: an option the command does not take, and\n * the checks `db backup` and `db restore` make of their own line (a stray\n * word, a pattern that leaves out the rebase schema).\n *\n * Reads no environment and opens nothing, so it is safe to run before a\n * database exists.\n *\n * @param args the driver's line: `[\"db\", \"<subcommand>\", …]`, without the\n * CLI's own words in front. A line for a subcommand this driver does not\n * answer passes, for the dispatch to refuse.\n */\nexport function assertDbCommandLine(args: readonly string[]): void {\n const [domain, subcommand] = args;\n if (domain !== \"db\" || !isDriverDbSubcommand(subcommand)) return;\n // `--help` is answered before any check, by the CLI and by the dispatch.\n if (args.includes(\"--help\") || args.includes(\"-h\")) return;\n LINE_CHECKS[subcommand]([...args]);\n}\n","/**\n * Do the migration files still describe the collections?\n *\n * `rebase db generate` asks Atlas, which needs a dev database to replay the\n * migrations into — seconds of Docker, or the managed PGlite, before it can say\n * a word. `rebase verify` runs after every edit an agent makes to a collection\n * file and in CI, where neither is acceptable, so this answers the narrower\n * question offline: replay the `CREATE TABLE` / `ALTER TABLE` / `DROP TABLE`\n * statements the migrations contain, and compare the tables and columns that\n * leaves with the ones the schema plan derives from the collections.\n *\n * Deliberately tables and columns only. A changed type or default is a real\n * drift too, but reading it back out of Atlas's SQL means parsing every type\n * spelling Postgres accepts, and a check that misreads `character varying(255)`\n * as a change cries wolf on every run. A missing table or column is the drift\n * that breaks a deploy — the runtime queries a column the migrated database\n * does not have — and it is unambiguous in the text.\n *\n * Policies are not compared: the runtime applies a collection's policies at\n * boot whether or not a migration carries them.\n */\nimport type { CollectionConfig } from \"@rebasepro/types\";\nimport { planSchema } from \"./plan/plan-schema\";\n\n/** One difference between the collections and what the migrations build. */\nexport interface UnmigratedChange {\n /**\n * - `missing-table` / `missing-column` — the collections declare it and no\n * migration creates it.\n * - `removed-column` — a migration creates it, the collection no longer\n * declares it, and no later migration drops it.\n */\n kind: \"missing-table\" | \"missing-column\" | \"removed-column\";\n /** `schema.table`. */\n table: string;\n column?: string;\n /** The collection that declares the table, when one does (a junction has none). */\n slug?: string;\n}\n\n/** A table as the migrations leave it. */\ninterface MigratedTable {\n /** Every column, however it was added. */\n columns: Set<string>;\n /**\n * The columns Atlas wrote: from a `CREATE TABLE` or an `ADD COLUMN` without\n * `IF NOT EXISTS`. The search, vector and trigger DDL `db generate` appends\n * after Atlas's half always says `IF NOT EXISTS`, and the planner keeps\n * those columns out of `TablePlan.columns` — so only these are candidates\n * for \"removed from the collection\".\n */\n managed: Set<string>;\n}\n\n/** Blank out `--` and `/* *\\/` comments, leaving string and identifier literals alone. */\nfunction stripComments(sql: string): string {\n let out = \"\";\n let i = 0;\n while (i < sql.length) {\n const ch = sql[i];\n if (ch === \"'\" || ch === \"\\\"\") {\n const end = sql.indexOf(ch, i + 1);\n const stop = end === -1 ? sql.length : end + 1;\n out += sql.slice(i, stop);\n i = stop;\n } else if (ch === \"-\" && sql[i + 1] === \"-\") {\n const end = sql.indexOf(\"\\n\", i);\n i = end === -1 ? sql.length : end;\n } else if (ch === \"/\" && sql[i + 1] === \"*\") {\n const end = sql.indexOf(\"*/\", i + 2);\n i = end === -1 ? sql.length : end + 2;\n } else if (ch === \"$\") {\n // A dollar-quoted body (`$$ … $$`, `$fn$ … $fn$`) is copied whole: a\n // function body is full of `--` and `;` that are not ours to read.\n const tag = /^\\$[A-Za-z_]*\\$/.exec(sql.slice(i))?.[0];\n if (!tag) {\n out += ch;\n i++;\n continue;\n }\n const end = sql.indexOf(tag, i + tag.length);\n const stop = end === -1 ? sql.length : end + tag.length;\n out += sql.slice(i, stop);\n i = stop;\n } else {\n out += ch;\n i++;\n }\n }\n return out;\n}\n\n/**\n * Split on a separator at nesting depth zero, outside quotes and dollar quotes.\n * `;` splits a file into statements, `,` a column list into its elements.\n */\nfunction splitTopLevel(text: string, separator: \";\" | \",\"): string[] {\n const parts: string[] = [];\n let depth = 0;\n let start = 0;\n let i = 0;\n while (i < text.length) {\n const ch = text[i];\n if (ch === \"'\" || ch === \"\\\"\") {\n const end = text.indexOf(ch, i + 1);\n i = end === -1 ? text.length : end + 1;\n continue;\n }\n if (ch === \"$\") {\n const tag = /^\\$[A-Za-z_]*\\$/.exec(text.slice(i))?.[0];\n if (tag) {\n const end = text.indexOf(tag, i + tag.length);\n i = end === -1 ? text.length : end + tag.length;\n continue;\n }\n }\n if (ch === \"(\") depth++;\n else if (ch === \")\") depth--;\n else if (ch === separator && depth === 0) {\n parts.push(text.slice(start, i));\n start = i + 1;\n }\n i++;\n }\n parts.push(text.slice(start));\n return parts.map(p => p.trim()).filter(p => p.length > 0);\n}\n\n/** One identifier: `\"Quoted\"` keeps its case, a bare word folds to lower case as Postgres folds it. */\nconst IDENT = String.raw`(?:\"(?:[^\"]|\"\")+\"|[A-Za-z_][A-Za-z0-9_$]*)`;\n/** An optionally schema-qualified name. */\nconst QUALIFIED = String.raw`${IDENT}(?:\\s*\\.\\s*${IDENT})?`;\n\nfunction unquote(identifier: string): string {\n const trimmed = identifier.trim();\n return trimmed.startsWith(\"\\\"\") ? trimmed.slice(1, -1).replace(/\"\"/g, \"\\\"\") : trimmed.toLowerCase();\n}\n\n/** `\"public\".\"posts\"` → `public.posts`; an unqualified name is in `public`. */\nfunction qualifiedName(name: string): string {\n const [first = \"\", second] = name.match(new RegExp(IDENT, \"g\")) ?? [];\n return second !== undefined ? `${unquote(first)}.${unquote(second)}` : `public.${unquote(first)}`;\n}\n\n/** Words that open a table constraint rather than a column, inside `CREATE TABLE ( … )`. */\nconst TABLE_CONSTRAINT = /^(CONSTRAINT|PRIMARY|UNIQUE|FOREIGN|CHECK|EXCLUDE|LIKE)\\b/i;\n\nconst CREATE_TABLE = new RegExp(String.raw`^CREATE\\s+(?:UNLOGGED\\s+)?TABLE\\s+(IF\\s+NOT\\s+EXISTS\\s+)?(${QUALIFIED})\\s*\\(([\\s\\S]*)\\)[^)]*$`, \"i\");\nconst ALTER_TABLE = new RegExp(String.raw`^ALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?(${QUALIFIED})\\s+([\\s\\S]*)$`, \"i\");\nconst DROP_TABLE = /^DROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?([\\s\\S]*?)(?:\\s+(?:CASCADE|RESTRICT))?$/i;\nconst ADD_COLUMN = new RegExp(String.raw`^ADD\\s+(?:COLUMN\\s+)?(IF\\s+NOT\\s+EXISTS\\s+)?(${IDENT})`, \"i\");\nconst DROP_COLUMN = new RegExp(String.raw`^DROP\\s+(?:COLUMN\\s+)?(?:IF\\s+EXISTS\\s+)?(${IDENT})`, \"i\");\nconst RENAME_COLUMN = new RegExp(String.raw`^RENAME\\s+(?:COLUMN\\s+)?(${IDENT})\\s+TO\\s+(${IDENT})$`, \"i\");\nconst RENAME_TABLE = new RegExp(String.raw`^RENAME\\s+TO\\s+(${IDENT})$`, \"i\");\n\n/**\n * The tables and columns the migrations leave behind, replayed in order.\n *\n * Exported for its tests.\n */\nexport function replayMigrationTables(migrations: readonly string[]): Map<string, MigratedTable> {\n const tables = new Map<string, MigratedTable>();\n const tableOf = (name: string): MigratedTable => {\n let table = tables.get(name);\n if (!table) {\n table = { columns: new Set(), managed: new Set() };\n tables.set(name, table);\n }\n return table;\n };\n\n for (const migration of migrations) {\n for (const raw of splitTopLevel(stripComments(migration), \";\")) {\n const statement = raw.replace(/\\s+/g, \" \").trim();\n\n const created = CREATE_TABLE.exec(statement);\n if (created) {\n const table = tableOf(qualifiedName(created[2]));\n const managed = !created[1];\n for (const element of splitTopLevel(created[3], \",\")) {\n if (TABLE_CONSTRAINT.test(element)) continue;\n const column = new RegExp(`^${IDENT}`).exec(element)?.[0];\n if (!column) continue;\n table.columns.add(unquote(column));\n if (managed) table.managed.add(unquote(column));\n }\n continue;\n }\n\n const altered = ALTER_TABLE.exec(statement);\n if (altered) {\n const name = qualifiedName(altered[1]);\n for (const action of splitTopLevel(altered[2], \",\")) {\n const renamedTable = RENAME_TABLE.exec(action);\n if (renamedTable) {\n const existing = tables.get(name);\n tables.delete(name);\n const target = `${name.split(\".\")[0]}.${unquote(renamedTable[1])}`;\n if (existing) tables.set(target, existing);\n continue;\n }\n const renamed = RENAME_COLUMN.exec(action);\n if (renamed) {\n const table = tableOf(name);\n const from = unquote(renamed[1]);\n const to = unquote(renamed[2]);\n table.columns.delete(from);\n table.columns.add(to);\n if (table.managed.delete(from)) table.managed.add(to);\n continue;\n }\n const added = ADD_COLUMN.exec(action);\n if (added && !/^ADD\\s+(CONSTRAINT|PRIMARY|UNIQUE|FOREIGN|CHECK|EXCLUDE)\\b/i.test(action)) {\n const table = tableOf(name);\n const column = unquote(added[2]);\n table.columns.add(column);\n if (!added[1]) table.managed.add(column);\n continue;\n }\n const dropped = DROP_COLUMN.exec(action);\n if (dropped && !/^DROP\\s+(CONSTRAINT|DEFAULT|NOT|EXPRESSION|IDENTITY)\\b/i.test(action)) {\n const table = tableOf(name);\n const column = unquote(dropped[1]);\n table.columns.delete(column);\n table.managed.delete(column);\n }\n }\n continue;\n }\n\n const droppedTables = DROP_TABLE.exec(statement);\n if (droppedTables) {\n for (const name of splitTopLevel(droppedTables[1], \",\")) tables.delete(qualifiedName(name));\n }\n }\n }\n return tables;\n}\n\n/**\n * What the collections declare that the migrations do not build, and what the\n * migrations still build that the collections dropped.\n *\n * `migrations` are the contents of every `.sql` file in the migrations\n * directory, in file-name order — Atlas's order. An empty list is a project\n * with no migrations at all, for which everything is missing; whether that is a\n * problem (a project on `db push` has none by design) is the caller's call.\n *\n * Throws what {@link planSchema} throws for a configuration it cannot plan.\n */\nexport function findUnmigratedSchema(\n collections: CollectionConfig[],\n migrations: readonly string[]\n): UnmigratedChange[] {\n const plan = planSchema(collections);\n const migrated = replayMigrationTables(migrations);\n const changes: UnmigratedChange[] = [];\n\n for (const table of plan.tables) {\n const slug = table.slug;\n const existing = migrated.get(table.qualified);\n if (!existing) {\n changes.push({ kind: \"missing-table\", table: table.qualified, ...(slug && { slug }) });\n continue;\n }\n // The users table is shared with the auth tables boot provisions\n // (`auth-users-columns`), which add columns no collection declares and\n // no migration has to carry. The table's existence is the fact here.\n if (table.auth) continue;\n\n // A search column is carved out of Atlas's diff and added by the\n // search DDL `db generate` appends (`ADD COLUMN IF NOT EXISTS`), which\n // a migration from before the block was declared does not carry and\n // the runtime applies itself — not a migration's to own.\n const planned = new Set(table.columns\n .filter(column => column.source.kind !== \"search\")\n .map(column => column.column));\n for (const column of planned) {\n if (!existing.columns.has(column)) {\n changes.push({ kind: \"missing-column\", table: table.qualified, column, ...(slug && { slug }) });\n }\n }\n for (const column of existing.managed) {\n if (!planned.has(column)) {\n changes.push({ kind: \"removed-column\", table: table.qualified, column, ...(slug && { slug }) });\n }\n }\n }\n return changes;\n}\n"],"mappings":";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