@rebasepro/server-postgres 0.17.3 → 0.18.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.
- package/LICENSE +0 -1
- package/README.md +31 -0
- package/dist/BranchService-ByLfM_Tt.js +360 -0
- package/dist/BranchService-ByLfM_Tt.js.map +1 -0
- package/dist/__vite-browser-external-BnuHet1e.js +46 -0
- package/dist/__vite-browser-external-BnuHet1e.js.map +1 -0
- package/dist/arg-Dni7MzLB.js +87 -0
- package/dist/arg-Dni7MzLB.js.map +1 -0
- package/dist/auth-users-columns-D2LBFrMH.js +116 -0
- package/dist/auth-users-columns-D2LBFrMH.js.map +1 -0
- package/dist/backup-argv.d.ts +19 -0
- package/dist/backup-cli-oM9WQVlV.js +408 -0
- package/dist/backup-cli-oM9WQVlV.js.map +1 -0
- package/dist/backup-service-Br3tqwsy.js +715 -0
- package/dist/backup-service-Br3tqwsy.js.map +1 -0
- package/dist/branch-argv.d.ts +28 -0
- package/dist/branch-prune.d.ts +77 -0
- package/dist/cli-collections-path.d.ts +31 -0
- package/dist/cli-errors-DxN4yzdH.js +657 -0
- package/dist/cli-errors-DxN4yzdH.js.map +1 -0
- package/dist/cli-errors.d.ts +123 -0
- package/dist/cli-flags.d.ts +101 -0
- package/dist/cli-helpers.d.ts +94 -10
- package/dist/cli-output-CNdMql-L.js +47 -0
- package/dist/cli-output-CNdMql-L.js.map +1 -0
- package/dist/cli.js +2020 -0
- package/dist/cli.js.map +1 -0
- package/dist/collection-index-BHgT_TKd.js +276 -0
- package/dist/collection-index-BHgT_TKd.js.map +1 -0
- package/dist/{collections-schema-version-BMeu3cgv.js → collections-schema-version-T6cGvrDi.js} +1 -2
- package/dist/{collections-schema-version-BMeu3cgv.js.map → collections-schema-version-T6cGvrDi.js.map} +1 -1
- package/dist/{connection-GOKU3Hu5.js → databasePoolManager-Bj5FbeAs.js} +112 -40
- package/dist/databasePoolManager-Bj5FbeAs.js.map +1 -0
- package/dist/databasePoolManager.d.ts +27 -0
- package/dist/doctor-D7HWmGzs.js +974 -0
- package/dist/doctor-D7HWmGzs.js.map +1 -0
- package/dist/{ensure-collection-policies-UCqgv_8c.js → ensure-collection-policies-2c2NV8zX.js} +7 -27
- package/dist/ensure-collection-policies-2c2NV8zX.js.map +1 -0
- package/dist/ensure-collection-tables-D4wJzM4y.js +820 -0
- package/dist/ensure-collection-tables-D4wJzM4y.js.map +1 -0
- package/dist/ensure-tables-CIojK-Rx.js +650 -0
- package/dist/ensure-tables-CIojK-Rx.js.map +1 -0
- package/dist/generate-drizzle-schema-CwEgVyjO.js +123 -0
- package/dist/generate-drizzle-schema-CwEgVyjO.js.map +1 -0
- package/dist/generate-drizzle-schema-logic-so2Z_lyC.js +528 -0
- package/dist/generate-drizzle-schema-logic-so2Z_lyC.js.map +1 -0
- package/dist/{ensure-collection-tables-DgVixhX3.js → generate-postgres-ddl-logic-CtnpIBVv.js} +126 -984
- package/dist/generate-postgres-ddl-logic-CtnpIBVv.js.map +1 -0
- package/dist/generated-schema-staleness-DQdfJl2A.js +157 -0
- package/dist/generated-schema-staleness-DQdfJl2A.js.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.es.js +7423 -1133
- package/dist/index.es.js.map +1 -1
- package/dist/introspect-db-logic-C6LQdTxj.js +1378 -0
- package/dist/introspect-db-logic-C6LQdTxj.js.map +1 -0
- package/dist/policy-drift-kNJ6X2Uj.js +313 -0
- package/dist/policy-drift-kNJ6X2Uj.js.map +1 -0
- package/dist/{backup-service-DCk7KhhL.js → rls-bootstrap-sql-DLDnUjtx.js} +737 -2689
- package/dist/rls-bootstrap-sql-DLDnUjtx.js.map +1 -0
- package/dist/{rls-enforcement-DvAbL9YJ.js → rls-enforcement-DeYEjYLt.js} +65 -190
- package/dist/rls-enforcement-DeYEjYLt.js.map +1 -0
- package/dist/schema/bin/generate-drizzle-schema.d.ts +1 -0
- package/dist/schema/bin/generate-postgres-ddl.d.ts +1 -0
- package/dist/schema/column-type-drift.d.ts +79 -0
- package/dist/schema/doctor-cli.js +129 -0
- package/dist/schema/doctor-cli.js.map +1 -0
- package/dist/schema/doctor.d.ts +42 -0
- package/dist/schema/ensure-collection-tables.d.ts +90 -0
- package/dist/schema/generate-drizzle-schema.d.ts +1 -1
- package/dist/schema/generate-drizzle-schema.js +24 -0
- package/dist/schema/generate-drizzle-schema.js.map +1 -0
- package/dist/schema/generate-next-step.d.ts +30 -0
- package/dist/schema/generate-postgres-ddl-logic.d.ts +28 -0
- package/dist/schema/generate-postgres-ddl.d.ts +1 -1
- package/dist/schema/generate-postgres-ddl.js +138 -0
- package/dist/schema/generate-postgres-ddl.js.map +1 -0
- package/dist/schema/generated-schema-staleness.d.ts +37 -0
- package/dist/schema/introspect-db-queries.d.ts +34 -0
- package/dist/schema/introspect-db.js +866 -0
- package/dist/schema/introspect-db.js.map +1 -0
- package/dist/security/rls-enforcement.d.ts +63 -2
- package/dist/services/BranchService.d.ts +86 -1
- package/dist/services/collection-helpers.d.ts +1 -1
- package/dist/services/realtimeService.d.ts +30 -2
- package/dist/services/row-pipeline.d.ts +12 -1
- package/dist/source-Br7L7GOI.js +410 -0
- package/dist/source-Br7L7GOI.js.map +1 -0
- package/dist/utils/pg-error-utils.d.ts +3 -1
- package/dist/utils/pg-numeric-number-patch.d.ts +31 -0
- package/dist/vector-index-DkWxm2de.js +309 -0
- package/dist/vector-index-DkWxm2de.js.map +1 -0
- package/package.json +32 -27
- package/dist/backup-service-DCk7KhhL.js.map +0 -1
- package/dist/collection-index-BRUg10H5.js +0 -5690
- package/dist/collection-index-BRUg10H5.js.map +0 -1
- package/dist/connection-GOKU3Hu5.js.map +0 -1
- package/dist/ensure-collection-policies-UCqgv_8c.js.map +0 -1
- package/dist/ensure-collection-tables-DgVixhX3.js.map +0 -1
- package/dist/rls-bootstrap-sql-B5C9LoJ6.js +0 -244
- package/dist/rls-bootstrap-sql-B5C9LoJ6.js.map +0 -1
- package/dist/rls-enforcement-DvAbL9YJ.js.map +0 -1
- package/dist/src-DiB5RP2Z.js +0 -541
- package/dist/src-DiB5RP2Z.js.map +0 -1
- package/dist/websocket-BZ4H5wUz.js +0 -8198
- package/dist/websocket-BZ4H5wUz.js.map +0 -1
- package/src/PostgresAdapter.ts +0 -91
- package/src/PostgresBackendDriver.ts +0 -1857
- package/src/PostgresBootstrapper.ts +0 -1157
- package/src/auth/ensure-tables.ts +0 -896
- package/src/auth/schema-version.ts +0 -260
- package/src/auth/services.ts +0 -1610
- package/src/backup/backup-cli.ts +0 -520
- package/src/backup/backup-cron.ts +0 -212
- package/src/backup/backup-logic.ts +0 -93
- package/src/backup/backup-service.ts +0 -485
- package/src/backup/index.ts +0 -12
- package/src/backup/pg-tools.ts +0 -403
- package/src/backup/retention.ts +0 -86
- package/src/cli-errors.ts +0 -265
- package/src/cli-helpers.ts +0 -569
- package/src/cli-output.ts +0 -43
- package/src/cli.ts +0 -1339
- package/src/collections/PostgresCollectionRegistry.ts +0 -108
- package/src/collections/buildRegistry.ts +0 -68
- package/src/collections/validate-relations.ts +0 -402
- package/src/connection.ts +0 -333
- package/src/data-transformer.ts +0 -845
- package/src/databasePoolManager.ts +0 -95
- package/src/history/HistoryService.ts +0 -254
- package/src/history/ensure-history-table.ts +0 -53
- package/src/index.ts +0 -19
- package/src/interfaces.ts +0 -60
- package/src/module-dir.ts +0 -7
- package/src/schema/atlas-argv.ts +0 -94
- package/src/schema/auth-schema.ts +0 -298
- package/src/schema/auth-users-columns.ts +0 -131
- package/src/schema/carved-out-migration.ts +0 -404
- package/src/schema/classify-change.ts +0 -436
- package/src/schema/collection-index.ts +0 -427
- package/src/schema/collections-schema-version.ts +0 -103
- package/src/schema/destructive-sql.ts +0 -94
- package/src/schema/doctor-cli.ts +0 -66
- package/src/schema/doctor-policy-checks.ts +0 -105
- package/src/schema/doctor.ts +0 -837
- package/src/schema/drizzle-ddl.ts +0 -33
- package/src/schema/dynamic-tables.test.ts +0 -302
- package/src/schema/dynamic-tables.ts +0 -293
- package/src/schema/ensure-collection-policies.ts +0 -198
- package/src/schema/ensure-collection-tables.test.ts +0 -518
- package/src/schema/ensure-collection-tables.ts +0 -1267
- package/src/schema/generate-drizzle-schema-logic.ts +0 -957
- package/src/schema/generate-drizzle-schema.ts +0 -143
- package/src/schema/generate-postgres-ddl-logic.ts +0 -1339
- package/src/schema/generate-postgres-ddl.ts +0 -180
- package/src/schema/generate-schema-commit.ts +0 -267
- package/src/schema/generated-schema-staleness.ts +0 -284
- package/src/schema/introspect-db-constraints.ts +0 -385
- package/src/schema/introspect-db-inference.ts +0 -255
- package/src/schema/introspect-db-logic.ts +0 -1387
- package/src/schema/introspect-db-naming.ts +0 -15
- package/src/schema/introspect-db-project.ts +0 -78
- package/src/schema/introspect-db-queries.ts +0 -326
- package/src/schema/introspect-db-structure.ts +0 -670
- package/src/schema/introspect-db-types.ts +0 -56
- package/src/schema/introspect-db.ts +0 -257
- package/src/schema/introspect-runtime.test.ts +0 -260
- package/src/schema/introspect-runtime.ts +0 -327
- package/src/schema/non-sql-collections.test.ts +0 -131
- package/src/schema/rls-bootstrap-sql.ts +0 -288
- package/src/schema/search-column.ts +0 -643
- package/src/schema/test-schema.ts +0 -11
- package/src/schema/vector-index.ts +0 -491
- package/src/security/anonymous-grants.test.ts +0 -73
- package/src/security/policy-drift.test.ts +0 -435
- package/src/security/policy-drift.ts +0 -473
- package/src/security/rls-enforcement.ts +0 -505
- package/src/services/BranchService.ts +0 -326
- package/src/services/FetchService.ts +0 -2115
- package/src/services/PersistService.ts +0 -557
- package/src/services/RelationService.ts +0 -978
- package/src/services/RelationWriteService.ts +0 -653
- package/src/services/cdc/CdcListener.ts +0 -103
- package/src/services/cdc/junction-tables.ts +0 -91
- package/src/services/cdc/trigger-cdc.ts +0 -173
- package/src/services/channel-bus/ChannelBus.ts +0 -44
- package/src/services/channel-bus/PostgresChannelBus.ts +0 -299
- package/src/services/channel-bus/index.ts +0 -114
- package/src/services/channel-history.ts +0 -424
- package/src/services/channel-presence.ts +0 -185
- package/src/services/collection-helpers.ts +0 -420
- package/src/services/dataService.ts +0 -256
- package/src/services/index.ts +0 -14
- package/src/services/junction-writes.ts +0 -295
- package/src/services/nested-path.ts +0 -145
- package/src/services/pg-notify-listener.ts +0 -151
- package/src/services/realtimeService.ts +0 -2545
- package/src/services/row-pipeline.ts +0 -240
- package/src/services/write-denial.ts +0 -55
- package/src/types.ts +0 -4
- package/src/utils/connection-string.ts +0 -58
- package/src/utils/drizzle-conditions.ts +0 -2743
- package/src/utils/pg-array-null-patch.ts +0 -42
- package/src/utils/pg-error-utils.ts +0 -391
- package/src/websocket.ts +0 -855
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"introspect-db.js","names":[],"sources":["../../src/schema/introspect-db-project.ts","../../src/schema/introspect-db-queries.ts","../../src/schema/introspect-db-constraints.ts","../../src/schema/introspect-db.ts"],"sourcesContent":["/**\n * What the project being introspected into can actually import.\n *\n * The generator is pure — `introspect-db-logic.ts` reads no files — so the one\n * question it cannot answer for itself lives here: which `defineCollection`, if\n * any, will resolve from the directory the collections are written to.\n */\nimport fs from \"fs\";\nimport path from \"path\";\n\nimport { ADMIN_TYPES_PACKAGE, COMMON_PACKAGE, type CollectionBuilder } from \"./introspect-db-logic\";\n\n/** How far up to look before giving up, if no project root announces itself. */\nconst MAX_LEVELS = 8;\n\n/** Every dependency name a manifest declares, in any of the three fields. */\nfunction declaredDependencies(manifestPath: string): Set<string> {\n const names = new Set<string>();\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(manifestPath, \"utf-8\"));\n } catch {\n // A malformed or unreadable package.json is not this function's problem\n // to report — it answers \"can this import resolve\", and the answer is no.\n return names;\n }\n if (typeof parsed !== \"object\" || parsed === null) return names;\n const manifest = parsed as Record<string, unknown>;\n for (const field of [\"dependencies\", \"devDependencies\", \"peerDependencies\"]) {\n const block = manifest[field];\n if (typeof block === \"object\" && block !== null) {\n for (const name of Object.keys(block)) names.add(name);\n }\n }\n return names;\n}\n\n/**\n * Which `defineCollection` to generate against, for collections written to `outDir`.\n *\n * **The detection is the package manifests above the output directory**, unioned from\n * `outDir` up to and including the project root — the first ancestor holding a\n * `rebase.json`, or `MAX_LEVELS` up if there is none.\n *\n * That is the rule Node itself applies: a file in `config/collections` resolves a bare\n * specifier through `config/node_modules`, then `<project>/node_modules`, and so on up.\n * Reading the manifests along that same path answers the only question that matters —\n * *will this import resolve in the project I am writing into* — from the state on disk\n * at the moment of generation. The alternatives are all proxies for it: `rebase.json`'s\n * `apps` block says a CMS scaffold declared an admin app, and a `frontend/` directory\n * says one was scaffolded, but neither is what the compiler consults, and either can be\n * true of a project whose `config` package does not depend on `@rebasepro/cms-types`.\n *\n * Ambiguity resolves towards the admin panel: a project that declares both packages has\n * a panel, and `@rebasepro/cms-types` is the flavour that keeps the `admin` block.\n */\nexport function detectCollectionBuilder(outDir: string): CollectionBuilder {\n let dir = path.resolve(outDir);\n const declared = new Set<string>();\n\n for (let level = 0; level < MAX_LEVELS; level++) {\n const manifest = path.join(dir, \"package.json\");\n if (fs.existsSync(manifest)) {\n for (const name of declaredDependencies(manifest)) declared.add(name);\n }\n // The project root, and the last level worth reading: anything above it\n // belongs to whatever the project happens to be checked out inside.\n if (fs.existsSync(path.join(dir, \"rebase.json\"))) break;\n\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n\n if (declared.has(ADMIN_TYPES_PACKAGE)) return \"admin-types\";\n if (declared.has(COMMON_PACKAGE)) return \"common\";\n return \"annotation\";\n}\n","/**\n * The catalog queries introspection runs, and the shape they produce.\n *\n * These live apart from {@link ./introspect-db.ts} (the CLI entry point) on\n * purpose: the fixture-capture script and the live e2e read a database through\n * this module too, so what the tests see is what the CLI sees. A query that\n * only exists inside the CLI's `main()` can only be tested by running the CLI.\n *\n * No side effects beyond `SELECT`. Introspection reads a database it does not\n * own — it must never `ANALYZE`, create a temp table, or otherwise write.\n */\nimport type {\n TableRow,\n TableColumn,\n EnumValue,\n PrimaryKeyRow,\n ForeignKeyRow,\n UniqueConstraintRow,\n CheckConstraintRow,\n CommentRow,\n SchemaMetadata\n} from \"./introspect-db-logic\";\n\n/** The subset of `pg.Client` this module needs, so tests can pass a fake. */\nexport interface QueryableClient {\n query<R = Record<string, unknown>>(text: string, values?: unknown[]): Promise<{ rows: R[] }>;\n}\n\n/**\n * A Postgres identifier, quoted so that whatever is inside it stays inside it.\n *\n * Introspection reads table and schema names out of `pg_class` and puts them\n * straight back into SQL, and wrapping a name in double quotes is not the same\n * as escaping it: a table named `x\" ; DROP TABLE users; --` closes the quote\n * and then the statement. Postgres's own escape for a quote inside a quoted\n * identifier is to double it, which is what this does.\n *\n * \"The catalogue is trusted\" is true of your own database, and is exactly the\n * assumption this tool cannot make. Introspection exists to be pointed at\n * databases somebody else built, and it runs with the privileges of whoever\n * ran it — which is usually a superuser, because that is who has a connection\n * string to a database they are adopting.\n */\nexport function quoteIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n}\n\n/** `\"schema\".\"table\"`, both halves quoted. */\nexport function quoteRelation(schema: string, table: string): string {\n return `${quoteIdentifier(schema)}.${quoteIdentifier(table)}`;\n}\n\n/**\n * Can this table's name be the name of the file describing it?\n *\n * Introspection writes `<collectionsDir>/<tableName>.ts`, and the table name\n * came from a database this tool did not create. Postgres will hold a table\n * called `../../../etc/cron.d/x`, and `path.join` resolves it — so without this\n * the generator writes a file wherever the name points, as whoever ran the\n * command.\n *\n * Deliberately narrow, and deliberately not a blocklist of `..` and `/`: the\n * question is \"is this a plain file name?\", and every answer that is not\n * obviously yes is a table better written by hand. NUL and the Windows\n * separator are in scope because a collections directory is checked out on\n * whatever machine the developer has.\n */\nexport function isUsableFileName(name: string): boolean {\n if (name.length === 0 || name.length > 200) return false;\n if (name === \".\" || name === \"..\") return false;\n // Path separators (both platforms'), the Windows drive separator, and any\n // control character — a NUL truncates the path at the OS boundary, so a\n // name that reads as harmless in a log can be something else on disk.\n // eslint-disable-next-line no-control-regex\n if (/[/\\\\:\\u0000-\\u001f]/.test(name)) return false;\n // A leading dot makes a hidden file, and a trailing one is invalid on\n // Windows; neither is a table anyone means to generate.\n return !name.startsWith(\".\") && !name.endsWith(\".\");\n}\n\n/**\n * Base tables, excluding partitions.\n *\n * `relispartition` is the reason this reads `pg_class` rather than\n * `information_schema.tables`, which reports every partition as a base table of\n * its own. Pagila partitions `payment` by month; introspected through\n * information_schema it yields `payment` plus 26 near-identical\n * `payment_p2022_*` collections, each with its own nav entry.\n *\n * `relkind = 'p'` (the partitioned parent) is included and `'r'` partitions are\n * dropped, which is the right way round: the parent is the queryable table.\n */\nexport const TABLES_QUERY = `\n SELECT c.relname AS table_name,\n c.relkind = 'p' AS is_partitioned\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = $1\n AND c.relkind IN ('r', 'p')\n AND NOT c.relispartition\n AND c.relname NOT LIKE 'drizzle_%'\n AND c.relname NOT LIKE 'rebase_%'\n ORDER BY c.relname\n`;\n\n/**\n * Columns, with the catalog facts that say a column is not the user's to edit.\n *\n * `is_generated`/`is_identity` are read for that reason: a generated column\n * rejects any write, so a form that offers it is offering a field that always\n * errors. `character_maximum_length` is the declared `varchar(n)` bound —\n * already enforced by the database, and free to surface as validation.\n */\nexport const COLUMNS_QUERY = `\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 c.ordinal_position,\n c.is_generated,\n c.is_identity,\n c.identity_generation,\n c.character_maximum_length,\n c.numeric_precision,\n c.numeric_scale,\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 ORDER BY c.table_name, c.ordinal_position\n`;\n\nexport const ENUMS_QUERY = `\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`;\n\n/**\n * Primary key columns, in key order.\n *\n * `ORDER BY k.ord` matters for composite keys: the position of a column inside\n * the key is what tells a two-column PK made of two foreign keys apart from an\n * ordinary composite key, and `= ANY(i.indkey)` (the shape this replaced)\n * returns catalog order instead.\n */\nexport const PRIMARY_KEYS_QUERY = `\n SELECT t.relname AS table_name,\n a.attname AS column_name\n FROM pg_index i\n JOIN pg_class t ON t.oid = i.indrelid\n JOIN pg_namespace n ON n.oid = t.relnamespace\n CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord)\n JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum\n WHERE i.indisprimary AND n.nspname = $1\n ORDER BY t.relname, k.ord\n`;\n\n/**\n * Foreign keys, one row per referencing column, with the delete rule.\n *\n * Read from `pg_constraint` rather than through\n * `information_schema.constraint_column_usage`, which does not preserve the\n * pairing on a composite foreign key: it reports the cross product of the\n * constraint's columns, so a two-column FK comes back as four rows, two of them\n * pairing the wrong columns. `unnest(...) WITH ORDINALITY` on both sides joined\n * on the ordinal keeps each referencing column with the column it references.\n *\n * `confdeltype` is carried because `ON DELETE CASCADE` is the schema author\n * saying, in the database, that the child cannot outlive the parent — the one\n * unambiguous declaration of ownership a schema contains.\n *\n * Constraints declared on a *partition* are attributed to the partition root,\n * because that is the table this run generates a collection for. Pagila declares\n * `payment`'s three foreign keys on each monthly partition and none on the\n * parent, so reading `pg_constraint` at face value gives the `payment`\n * collection no relations at all. `pick = 1` then keeps one row per logical key,\n * preferring the root's own constraint when it has one, so a schema that\n * declares the key on the parent *and* inherits it onto 26 partitions does not\n * yield 27 copies of the same relation.\n */\nexport const FOREIGN_KEYS_QUERY = `\n WITH fk AS (\n SELECT con.oid,\n con.conname,\n con.conrelid,\n con.confrelid,\n con.conkey,\n con.confkey,\n con.confdeltype,\n COALESCE(pg_partition_root(con.conrelid), con.conrelid) AS root_oid,\n row_number() OVER (\n PARTITION BY COALESCE(pg_partition_root(con.conrelid), con.conrelid),\n con.confrelid, con.conkey, con.confkey\n ORDER BY (con.conrelid = COALESCE(pg_partition_root(con.conrelid), con.conrelid)) DESC,\n con.oid\n ) AS pick\n FROM pg_constraint con\n JOIN pg_namespace n ON n.oid = con.connamespace\n WHERE con.contype = 'f' AND n.nspname = $1\n )\n SELECT root.relname AS table_name,\n sa.attname AS column_name,\n tgt.relname AS foreign_table_name,\n ta.attname AS foreign_column_name,\n fk.conname AS constraint_name,\n s.ord::int AS ordinal,\n CASE fk.confdeltype\n WHEN 'a' THEN 'NO ACTION'\n WHEN 'r' THEN 'RESTRICT'\n WHEN 'c' THEN 'CASCADE'\n WHEN 'n' THEN 'SET NULL'\n WHEN 'd' THEN 'SET DEFAULT'\n END AS delete_rule\n FROM fk\n JOIN pg_class root ON root.oid = fk.root_oid\n JOIN pg_class tgt ON tgt.oid = fk.confrelid\n CROSS JOIN LATERAL unnest(fk.conkey) WITH ORDINALITY AS s(attnum, ord)\n JOIN pg_attribute sa ON sa.attrelid = fk.conrelid AND sa.attnum = s.attnum\n CROSS JOIN LATERAL unnest(fk.confkey) WITH ORDINALITY AS f(attnum, ord)\n JOIN pg_attribute ta ON ta.attrelid = fk.confrelid AND ta.attnum = f.attnum\n WHERE fk.pick = 1 AND s.ord = f.ord\n ORDER BY root.relname, fk.conname, s.ord\n`;\n\n/**\n * Unique constraints and unique indexes, as ordered column lists.\n *\n * Indexes rather than constraints alone, because `CREATE UNIQUE INDEX` and\n * `ADD CONSTRAINT ... UNIQUE` produce the same guarantee and schemas use both.\n * Partial indexes (`indpred IS NOT NULL`) are excluded: they promise uniqueness\n * only over the rows matching their predicate, which is not the promise a\n * `validation: { unique: true }` field makes.\n */\nexport const UNIQUE_CONSTRAINTS_QUERY = `\n SELECT t.relname AS table_name,\n ic.relname AS constraint_name,\n -- ::text, because the driver has no parser for an array of \\`name\\`\n -- and hands back the raw \\`{a,b}\\` literal as a string. Every consumer\n -- here indexes and compares it as an array, and a string of that\n -- shape fails those silently rather than loudly.\n array_agg(a.attname::text ORDER BY k.ord) AS column_names\n FROM pg_index i\n JOIN pg_class t ON t.oid = i.indrelid\n JOIN pg_class ic ON ic.oid = i.indexrelid\n JOIN pg_namespace n ON n.oid = t.relnamespace\n CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord)\n JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum\n WHERE i.indisunique\n AND NOT i.indisprimary\n AND i.indpred IS NULL\n AND n.nspname = $1\n AND NOT t.relispartition\n GROUP BY t.relname, ic.relname\n ORDER BY t.relname, ic.relname\n`;\n\n/**\n * CHECK constraints, as the source text Postgres reproduces them from.\n *\n * `pg_get_constraintdef` output is normalized by the server — the parser in\n * {@link ./introspect-db-constraints.ts} reads that normalized form, not\n * whatever the author typed.\n */\nexport const CHECK_CONSTRAINTS_QUERY = `\n SELECT DISTINCT\n root.relname AS table_name,\n con.conname AS constraint_name,\n pg_get_constraintdef(con.oid) AS definition\n FROM pg_constraint con\n JOIN pg_namespace n ON n.oid = con.connamespace\n JOIN pg_class root ON root.oid = COALESCE(pg_partition_root(con.conrelid), con.conrelid)\n WHERE con.contype = 'c'\n AND n.nspname = $1\n ORDER BY root.relname, con.conname\n`;\n\n/**\n * `COMMENT ON TABLE` / `COMMENT ON COLUMN`, which is documentation the author\n * already wrote and which nothing downstream has ever read.\n */\nexport const COMMENTS_QUERY = `\n SELECT t.relname AS table_name,\n a.attname AS column_name,\n d.description AS comment\n FROM pg_description d\n JOIN pg_class t ON t.oid = d.objoid\n JOIN pg_namespace n ON n.oid = t.relnamespace\n LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = d.objsubid\n WHERE n.nspname = $1\n AND t.relkind IN ('r', 'p')\n AND (d.objsubid = 0 OR a.attname IS NOT NULL)\n ORDER BY t.relname, d.objsubid\n`;\n\n/**\n * Counts a table's rows, stopping once the answer can only be \"more than\n * `limit`\".\n *\n * Introspection asks this to tell a small reference table from a table that\n * merely looks like one (see `classifyTables`). `reltuples` would answer for\n * free but lies on a table that has never been analyzed — which is every table\n * in a database restored from a dump, i.e. exactly the case introspection meets\n * — and reports -1 there rather than an error, so the lie is silent.\n *\n * The subquery's LIMIT caps the work at `limit + 1` rows however large the\n * table is, so this stays cheap on a table with a billion rows.\n */\nexport async function countRowsUpTo(\n client: QueryableClient,\n schema: string,\n table: string,\n limit: number\n): Promise<number> {\n const { rows } = await client.query<{ count: string }>(\n `SELECT count(*)::text AS count FROM (SELECT 1 FROM ${quoteRelation(schema, table)} LIMIT ${limit + 1}) probe`\n );\n return Number(rows[0]?.count ?? 0);\n}\n\n/**\n * Reads everything the generator needs, in one pass.\n *\n * `rowCounts` is deliberately absent here: it costs a query per table and only\n * a handful of tables can possibly need it. The caller fills it in for the\n * candidates `lookupCandidates()` names.\n */\nexport async function readSchemaMetadata(\n client: QueryableClient,\n schema: string\n): Promise<SchemaMetadata> {\n // Sequential, not `Promise.all`. A `pg.Client` is a single connection with\n // one protocol stream: concurrent `query()` calls on one are queued and\n // deprecated (removed in pg@9), so the parallel version buys nothing and\n // warns while doing it.\n const tables = await client.query<TableRow>(TABLES_QUERY, [schema]);\n const columns = await client.query<TableColumn>(COLUMNS_QUERY, [schema]);\n const enumValues = await client.query<EnumValue>(ENUMS_QUERY, [schema]);\n const pks = await client.query<PrimaryKeyRow>(PRIMARY_KEYS_QUERY, [schema]);\n const fks = await client.query<ForeignKeyRow>(FOREIGN_KEYS_QUERY, [schema]);\n const uniques = await client.query<UniqueConstraintRow>(UNIQUE_CONSTRAINTS_QUERY, [schema]);\n const checks = await client.query<CheckConstraintRow>(CHECK_CONSTRAINTS_QUERY, [schema]);\n const comments = await client.query<CommentRow>(COMMENTS_QUERY, [schema]);\n\n // A column list scoped to the schema still names tables this run excludes —\n // views, partitions, the drizzle bookkeeping tables. Narrow every row set to\n // the tables actually being introspected so downstream code never has to\n // ask whether a table it found in `columns` really exists.\n const known = new Set(tables.rows.map((t) => t.table_name));\n const scoped = <T extends { table_name: string }>(rows: T[]) => rows.filter((r) => known.has(r.table_name));\n\n return {\n schema,\n tables: tables.rows,\n columns: scoped(columns.rows),\n enumValues: enumValues.rows,\n pks: scoped(pks.rows),\n // A foreign key pointing *out* of the introspected set (into another\n // schema, or at a view) cannot be turned into a relation: there is no\n // collection on the other end to link to.\n fks: scoped(fks.rows).filter((fk) => known.has(fk.foreign_table_name)),\n uniques: scoped(uniques.rows),\n checks: scoped(checks.rows),\n comments: scoped(comments.rows),\n rowCounts: {}\n };\n}\n","/**\n * Reading validation rules out of CHECK constraints.\n *\n * A CHECK constraint is the schema author stating a rule the database already\n * enforces. Introspection has never read them, so a generated form let the user\n * type a value the database was always going to reject — the rule was written\n * down, in the schema, and the UI asked anyway.\n *\n * Everything here parses the *normalized* text `pg_get_constraintdef` produces,\n * not what the author typed: Postgres re-renders the expression from its parse\n * tree, so `CHECK (price > 0)` on a `numeric` column always comes back as\n * `CHECK ((price > (0)::numeric))`. That normalization is what makes a\n * string-level parser tractable — the input is generated, and the shapes are\n * few.\n *\n * Constraints this cannot read are skipped in full. A partially-understood\n * constraint is worse than an unread one: it would produce validation that\n * *narrows* differently from the database, so a value the UI accepts still\n * fails on write, or — worse — a value the database allows is refused in the\n * form with no way to see why.\n *\n * Pure module: no I/O, no logging.\n */\nimport type { CheckConstraintRow } from \"./introspect-db-logic\";\n\n/** What a table's CHECK constraints say about one column. */\nexport interface ColumnCheckFacts {\n /** Allowed values, from `IN (…)` / `= ANY (ARRAY[…])` / `= 'literal'`. */\n enumValues?: string[];\n /** `x >= n` */\n min?: number;\n /** `x <= n` */\n max?: number;\n /** `x > n` */\n moreThan?: number;\n /** `x < n` */\n lessThan?: number;\n /** `length(x) >= n` */\n lengthMin?: number;\n /** `length(x) <= n` */\n lengthMax?: number;\n}\n\n/** Per-table, per-column facts. */\nexport type CheckFactsByTable = Map<string, Map<string, ColumnCheckFacts>>;\n\n/** The length functions whose argument is the column being constrained. */\nconst LENGTH_FUNCTIONS = new Set([\"length\", \"char_length\", \"character_length\", \"octet_length\"]);\n\n/**\n * Splits on a separator that appears at paren depth 0 and outside string\n * literals.\n *\n * Depth tracking is the whole job: `ARRAY['a', 'b']` contains a comma that must\n * not split the enclosing argument list, and `'it''s'` contains a quote that\n * must not end the literal.\n */\nfunction splitTopLevel(input: string, separator: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let inString = false;\n let current = \"\";\n\n for (let i = 0; i < input.length; i++) {\n const ch = input[i];\n\n if (inString) {\n current += ch;\n if (ch === \"'\") {\n // '' inside a literal is an escaped quote, not the end of it.\n if (input[i + 1] === \"'\") {\n current += input[++i];\n } else {\n inString = false;\n }\n }\n continue;\n }\n\n if (ch === \"'\") {\n inString = true;\n current += ch;\n continue;\n }\n if (ch === \"(\" || ch === \"[\") depth++;\n if (ch === \")\" || ch === \"]\") depth--;\n\n if (depth === 0 && input.startsWith(separator, i)) {\n // A word separator must not match inside an identifier: \"AND\" is a\n // separator in `a AND b` but not in `brand = 1`.\n const before = input[i - 1];\n const after = input[i + separator.length];\n const wordish = /[A-Za-z]/.test(separator[0]);\n const boundedOk = !wordish || ((before === undefined || !/[A-Za-z0-9_]/.test(before)) &&\n (after === undefined || !/[A-Za-z0-9_]/.test(after)));\n if (boundedOk) {\n parts.push(current);\n current = \"\";\n i += separator.length - 1;\n continue;\n }\n }\n\n current += ch;\n }\n\n parts.push(current);\n return parts.map((p) => p.trim()).filter((p) => p.length > 0);\n}\n\n/** Removes one layer of wrapping parentheses, repeatedly, when balanced. */\nexport function unwrapParens(input: string): string {\n let s = input.trim();\n while (s.startsWith(\"(\") && s.endsWith(\")\")) {\n let depth = 0;\n let balanced = true;\n let inString = false;\n for (let i = 0; i < s.length; i++) {\n const ch = s[i];\n if (inString) {\n if (ch === \"'\") {\n if (s[i + 1] === \"'\") i++;\n else inString = false;\n }\n continue;\n }\n if (ch === \"'\") { inString = true; continue; }\n if (ch === \"(\") depth++;\n else if (ch === \")\") {\n depth--;\n // The opening paren closed before the end, so the outer pair is\n // not a wrapper: `(a) AND (b)`.\n if (depth === 0 && i < s.length - 1) { balanced = false; break; }\n }\n }\n if (!balanced) break;\n s = s.slice(1, -1).trim();\n }\n return s;\n}\n\n/** Drops trailing `::type` casts, including array and quoted forms. */\nexport function stripCasts(input: string): string {\n let s = unwrapParens(input);\n let previous: string;\n do {\n previous = s;\n s = unwrapParens(\n s.replace(/::\\s*\"?[A-Za-z_][A-Za-z0-9_ ]*\"?(\\s*\\(\\s*\\d+\\s*(,\\s*\\d+\\s*)?\\))?(\\s*\\[\\s*\\])*\\s*$/, \"\").trim()\n );\n } while (s !== previous);\n return s;\n}\n\n/** A bare, unquoted column reference — anything else is an expression. */\nfunction asColumnName(input: string): string | null {\n const s = stripCasts(input);\n if (/^[a-z_][a-z0-9_$]*$/i.test(s)) return s;\n // A quoted identifier keeps its case: \"userId\".\n const quoted = s.match(/^\"([^\"]+)\"$/);\n return quoted ? quoted[1] : null;\n}\n\n/** `length(col)` and friends → the column they measure. */\nfunction asLengthOfColumn(input: string): string | null {\n const s = stripCasts(input);\n const match = s.match(/^([a-z_]+)\\s*\\((.*)\\)$/is);\n if (!match || !LENGTH_FUNCTIONS.has(match[1].toLowerCase())) return null;\n return asColumnName(match[2]);\n}\n\n/** A numeric literal, after casts are removed. Rejects anything else. */\nfunction asNumber(input: string): number | null {\n const s = stripCasts(input).replace(/^'(.*)'$/s, \"$1\");\n if (!/^[+-]?(\\d+\\.?\\d*|\\.\\d+)$/.test(s)) return null;\n const n = Number(s);\n return Number.isFinite(n) ? n : null;\n}\n\n/** A single-quoted string literal, with `''` unescaped. */\nfunction asStringLiteral(input: string): string | null {\n const s = stripCasts(input);\n if (!s.startsWith(\"'\") || !s.endsWith(\"'\") || s.length < 2) return null;\n const body = s.slice(1, -1);\n // Any unescaped quote inside means this was not one literal.\n if (/(^|[^'])'($|[^'])/.test(body)) return null;\n return body.replace(/''/g, \"'\");\n}\n\n/** The element list of `ARRAY[…]`, or of a parenthesised `IN (…)` list. */\nfunction asValueList(input: string): string[] | null {\n const s = stripCasts(input);\n const arrayMatch = s.match(/^ARRAY\\s*\\[(.*)\\]$/is);\n const body = arrayMatch ? arrayMatch[1] : (s.startsWith(\"(\") && s.endsWith(\")\") ? s.slice(1, -1) : null);\n if (body === null) return null;\n if (body.trim() === \"\") return null;\n\n const values: string[] = [];\n for (const element of splitTopLevel(body, \",\")) {\n const literal = asStringLiteral(element);\n if (literal !== null) {\n values.push(literal);\n continue;\n }\n const numeric = asNumber(element);\n if (numeric !== null) {\n values.push(String(numeric));\n continue;\n }\n return null; // A non-literal element means this is not an enumeration.\n }\n return values;\n}\n\n/** One understood comparison, already resolved to the column it constrains. */\ninterface CheckTerm {\n column: string;\n apply: (facts: ColumnCheckFacts) => void;\n}\n\n/**\n * Parses one conjunct. Returns null when the shape is not one of the few this\n * understands, which is the signal to abandon the whole constraint.\n */\nfunction parseTerm(rawTerm: string): CheckTerm | null {\n const term = unwrapParens(rawTerm);\n\n // ── Membership: `x = ANY (ARRAY[…])`, `x IN (…)` ──────────────────\n const anyMatch = term.match(/^(.*?)\\s*=\\s*ANY\\s*(\\(.*\\))$/is);\n const inMatch = anyMatch ? null : term.match(/^(.*?)\\s+IN\\s*(\\(.*\\))$/is);\n const membership = anyMatch ?? inMatch;\n if (membership) {\n const column = asColumnName(membership[1]);\n const values = asValueList(membership[2]);\n if (!column || !values || values.length === 0) return null;\n return {\n column,\n apply: (facts) => {\n // Two membership checks on one column mean both must hold.\n facts.enumValues = facts.enumValues\n ? facts.enumValues.filter((v) => values.includes(v))\n : values;\n }\n };\n }\n\n // ── Comparison: `x >= n`, `length(x) <= n`, `x = 'literal'` ───────\n // Longest operators first so `>=` is not read as `>`.\n for (const operator of [\">=\", \"<=\", \"<>\", \"!=\", \"=\", \">\", \"<\"] as const) {\n const parts = splitTopLevel(term, operator);\n if (parts.length !== 2) continue;\n const [rawLeft, rawRight] = parts;\n\n const lengthColumn = asLengthOfColumn(rawLeft);\n if (lengthColumn) {\n const bound = asNumber(rawRight);\n if (bound === null) return null;\n switch (operator) {\n case \">=\": return { column: lengthColumn, apply: (f) => { f.lengthMin = Math.max(f.lengthMin ?? bound, bound); } };\n case \">\": return { column: lengthColumn, apply: (f) => { f.lengthMin = Math.max(f.lengthMin ?? bound + 1, bound + 1); } };\n case \"<=\": return { column: lengthColumn, apply: (f) => { f.lengthMax = Math.min(f.lengthMax ?? bound, bound); } };\n case \"<\": return { column: lengthColumn, apply: (f) => { f.lengthMax = Math.min(f.lengthMax ?? bound - 1, bound - 1); } };\n case \"=\": return { column: lengthColumn, apply: (f) => { f.lengthMin = bound; f.lengthMax = bound; } };\n default: return null;\n }\n }\n\n const column = asColumnName(rawLeft);\n if (!column) continue;\n\n if (operator === \"=\") {\n const literal = asStringLiteral(rawRight);\n if (literal !== null) {\n return {\n column,\n apply: (facts) => {\n facts.enumValues = facts.enumValues\n ? facts.enumValues.filter((v) => v === literal)\n : [literal];\n }\n };\n }\n // `x = 5` pins a number. Expressed as both bounds rather than as a\n // one-value enum, which for a number would render as a dropdown.\n const pinned = asNumber(rawRight);\n if (pinned === null) return null;\n return { column, apply: (f) => { f.min = pinned; f.max = pinned; } };\n }\n\n const bound = asNumber(rawRight);\n if (bound === null) return null;\n switch (operator) {\n case \">=\": return { column, apply: (f) => { f.min = Math.max(f.min ?? bound, bound); } };\n case \">\": return { column, apply: (f) => { f.moreThan = Math.max(f.moreThan ?? bound, bound); } };\n case \"<=\": return { column, apply: (f) => { f.max = Math.min(f.max ?? bound, bound); } };\n case \"<\": return { column, apply: (f) => { f.lessThan = Math.min(f.lessThan ?? bound, bound); } };\n default: return null; // `<>` / `!=` exclude rather than bound.\n }\n }\n\n return null;\n}\n\n/**\n * Reads one constraint definition into per-column facts.\n *\n * Returns an empty map for anything not understood — including a constraint\n * that is understood but spans two columns (`start_date < end_date`), which no\n * per-property validation rule can express.\n */\nexport function parseCheckDefinition(definition: string): Map<string, ColumnCheckFacts> {\n const result = new Map<string, ColumnCheckFacts>();\n\n const body = definition\n .trim()\n .replace(/\\s+NOT\\s+VALID\\s*$/i, \"\")\n .replace(/^CHECK\\s*/i, \"\")\n .trim();\n if (body === definition.trim()) return result; // Not a CHECK definition.\n\n const expression = unwrapParens(body);\n if (!expression) return result;\n\n // Only conjunctions. A disjunction (`a OR b`) does not narrow a column: each\n // branch may allow what the other forbids, so no single bound follows.\n if (splitTopLevel(expression, \" OR \").length > 1) return result;\n\n const terms = splitTopLevel(expression, \" AND \");\n const parsed: CheckTerm[] = [];\n for (const term of terms) {\n const one = parseTerm(term);\n if (!one) return result; // One unreadable conjunct voids the constraint.\n parsed.push(one);\n }\n\n // A CHECK naming two columns constrains their *relationship*; keeping the\n // half that mentions one column would assert something the database does not.\n const columns = new Set(parsed.map((t) => t.column));\n if (columns.size !== 1) return result;\n\n const facts: ColumnCheckFacts = {};\n for (const term of parsed) term.apply(facts);\n if (Object.keys(facts).length === 0) return result;\n\n result.set(parsed[0].column, facts);\n return result;\n}\n\n/** Merges every readable CHECK in the schema into per-table, per-column facts. */\nexport function parseCheckConstraints(rows: CheckConstraintRow[]): CheckFactsByTable {\n const byTable: CheckFactsByTable = new Map();\n\n for (const row of rows) {\n const parsed = parseCheckDefinition(row.definition);\n if (parsed.size === 0) continue;\n\n let table = byTable.get(row.table_name);\n if (!table) {\n table = new Map();\n byTable.set(row.table_name, table);\n }\n\n for (const [column, facts] of parsed) {\n const existing = table.get(column);\n if (!existing) {\n table.set(column, facts);\n continue;\n }\n // Separate constraints on the same column all hold at once.\n if (facts.enumValues) {\n existing.enumValues = existing.enumValues\n ? existing.enumValues.filter((v) => facts.enumValues!.includes(v))\n : facts.enumValues;\n }\n if (facts.min !== undefined) existing.min = Math.max(existing.min ?? facts.min, facts.min);\n if (facts.max !== undefined) existing.max = Math.min(existing.max ?? facts.max, facts.max);\n if (facts.moreThan !== undefined) existing.moreThan = Math.max(existing.moreThan ?? facts.moreThan, facts.moreThan);\n if (facts.lessThan !== undefined) existing.lessThan = Math.min(existing.lessThan ?? facts.lessThan, facts.lessThan);\n if (facts.lengthMin !== undefined) existing.lengthMin = Math.max(existing.lengthMin ?? facts.lengthMin, facts.lengthMin);\n if (facts.lengthMax !== undefined) existing.lengthMax = Math.min(existing.lengthMax ?? facts.lengthMax, facts.lengthMax);\n }\n }\n\n return byTable;\n}\n","import chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport pg from \"pg\";\nimport arg from \"arg\";\nimport * as dotenv from \"dotenv\";\nimport readline from \"readline\";\n\nimport {\n buildTablesMap,\n buildEnumMap,\n generateCollectionFile,\n generateIndexContent,\n mergeIndexContent,\n safeHostFromUrl\n} from \"./introspect-db-logic\";\nimport { detectCollectionBuilder } from \"./introspect-db-project\";\nimport { countRowsUpTo, isUsableFileName, quoteRelation, readSchemaMetadata } from \"./introspect-db-queries\";\nimport { classifyTables, lookupCandidates, LOOKUP_MAX_ROWS } from \"./introspect-db-structure\";\nimport { parseCheckConstraints } from \"./introspect-db-constraints\";\nimport { out, outWarn, outError } from \"../cli-output\";\n\nasync function main() {\n const args = arg(\n {\n \"--output\": String,\n \"--collections\": String,\n \"--force\": Boolean,\n \"--schema\": String,\n \"--data-inference\": Boolean,\n \"--no-data-inference\": Boolean,\n \"-o\": \"--output\",\n \"-c\": \"--collections\",\n \"-f\": \"--force\"\n },\n { permissive: true }\n );\n\n const cwd = process.cwd();\n const isBackendDir = path.basename(cwd) === \"backend\";\n const defaultOutDir = isBackendDir\n ? path.resolve(cwd, \"..\", \"config\", \"collections\")\n : path.resolve(cwd, \"config\", \"collections\");\n\n const outDir = args[\"--output\"] || args[\"--collections\"] || defaultOutDir;\n const force = args[\"--force\"] || false;\n const pgSchema = args[\"--schema\"] || \"public\";\n\n if (!fs.existsSync(outDir)) {\n fs.mkdirSync(outDir, { recursive: true });\n }\n\n // Load env\n const envPaths = [\n process.env.DOTENV_CONFIG_PATH,\n path.resolve(process.cwd(), \".env\"),\n path.resolve(process.cwd(), \"../.env\"),\n path.resolve(process.cwd(), \"../../.env\")\n ].filter(Boolean) as string[];\n\n for (const p of envPaths) {\n if (fs.existsSync(p)) {\n dotenv.config({ path: p, quiet: true });\n break;\n }\n }\n\n const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;\n if (!databaseUrl) {\n outError(chalk.red(\"✗ DATABASE_URL is not set. Make sure your .env file is configured.\"));\n process.exit(1);\n }\n\n const client = new pg.Client({ connectionString: databaseUrl });\n\n try {\n await client.connect();\n } catch (err) {\n outError(chalk.red(`✗ Failed to connect to database: ${err instanceof Error ? err.message : String(err)}`));\n outError(chalk.gray(\" Check your DATABASE_URL and ensure the database is reachable.\"));\n process.exit(1);\n }\n\n // Log the host portion safely — handle URLs without \"@\"\n const hostPart = safeHostFromUrl(databaseUrl);\n out(chalk.gray(`Connected to database: ${hostPart}`));\n out(chalk.gray(`Introspecting schema '${pgSchema}'...`));\n\n try {\n const metadata = await readSchemaMetadata(client, pgSchema);\n const enumMap = buildEnumMap(metadata.enumValues);\n const tablesMap = buildTablesMap(metadata.tables, metadata.columns, metadata.pks, metadata.fks);\n const fks = metadata.fks;\n\n // Only tables that could structurally be a code list are counted, and\n // each count stops at the threshold — see `countRowsUpTo`. Introspection\n // runs against a database it does not own, so \"cheap on a table of any\n // size\" is a requirement, not an optimization.\n for (const table of lookupCandidates(metadata, tablesMap)) {\n try {\n metadata.rowCounts[table] = await countRowsUpTo(client, pgSchema, table, LOOKUP_MAX_ROWS);\n } catch (err) {\n // A table this run cannot read is simply not classified as a code\n // list; everything else about it still generates.\n out(chalk.gray(` (skipped row count for ${table}: ${err instanceof Error ? err.message : String(err)})`));\n }\n }\n\n const classifications = classifyTables(metadata, tablesMap);\n const checkFacts = parseCheckConstraints(metadata.checks);\n\n // Which builder the generated files may import — read from the manifests\n // above `outDir`, because a project without `@rebasepro/cms-types` cannot\n // resolve that import and has no `admin` block to write into either.\n const builder = detectCollectionBuilder(outDir);\n if (builder === \"annotation\") {\n outWarn(chalk.yellow(\n \"⚠ Neither @rebasepro/cms-types nor @rebasepro/common is declared above \" +\n `${outDir}.`\n ));\n outWarn(chalk.gray(\n \" Generating plain type annotations, which widen the property keys to `string`: \" +\n \"`propertiesOrder` and friends will not be checked. Add @rebasepro/common to the \" +\n \"config package to turn that checking on.\"\n ));\n }\n const joinTables = new Set(\n Array.from(classifications.values())\n .filter((c) => c.role === \"junction\")\n .map((c) => c.table)\n );\n\n const roleCount = (role: string) =>\n Array.from(classifications.values()).filter((c) => c.role === role).length;\n\n out(chalk.blue(`Found ${tablesMap.size} tables.`));\n out(chalk.gray(\n ` ${roleCount(\"entity\")} entities, ${joinTables.size} join tables (folded into relations), ` +\n `${roleCount(\"lookup\")} code lists, ${roleCount(\"owned-child\")} owned by another table (hidden from navigation).`\n ));\n\n let runDataInference = false;\n if (args[\"--no-data-inference\"]) {\n runDataInference = false;\n } else if (args[\"--data-inference\"] !== undefined) {\n runDataInference = args[\"--data-inference\"];\n } else if (!process.stdin.isTTY) {\n // No terminal to answer the question below (scaffolding scripts, CI,\n // `rebase init --introspect`) — asking would hang forever.\n out(chalk.gray(\"Skipping data inference (non-interactive run; pass --data-inference to enable).\"));\n } else {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n const answer = await new Promise<string>((resolve) => rl.question(chalk.yellow(\"? Do you want to run comprehensive data inference on sampled rows to auto-detect types, formats, constraints, and UI configurations? (y/N) \"), resolve));\n runDataInference = answer.trim().toLowerCase() === \"y\";\n rl.close();\n }\n\n if (runDataInference) {\n out(chalk.gray(\"Sampling database rows for data inference...\"));\n }\n\n // Generate Collections\n const generatedFiles: string[] = [];\n const skippedFiles: string[] = [];\n\n const tablesToProcess = Array.from(tablesMap.entries()).filter(([tableName]) => !joinTables.has(tableName));\n\n const BATCH_SIZE = 10;\n for (let i = 0; i < tablesToProcess.length; i += BATCH_SIZE) {\n const batch = tablesToProcess.slice(i, i + BATCH_SIZE);\n\n await Promise.all(batch.map(async ([tableName, meta]) => {\n // ── The name has to be usable as a filename ────────────────\n //\n // `tableName` came out of `pg_class` in a database this tool\n // did not create — adopting somebody else's database is the\n // whole point of introspection — and it is about to be joined\n // onto a path. Postgres will happily hold a table called\n // `../../../etc/cron.d/x`, and `path.join` resolves it: the\n // generator would write a TypeScript file wherever that\n // pointed, as whoever ran the command.\n //\n // Skipped rather than sanitised. A file named something other\n // than its table is a collection that does not round-trip, and\n // silently renaming it would be a worse surprise than one line\n // saying which table was left out.\n if (!isUsableFileName(tableName)) {\n outWarn(chalk.yellow(\n `⚠ Skipping table ${JSON.stringify(tableName)}: its name cannot be used as a ` +\n \"filename. Rename the table, or write this collection by hand.\"\n ));\n skippedFiles.push(tableName);\n return;\n }\n\n // ── File overwrite protection ──────────────────────────────\n const filePath = path.join(outDir, `${tableName}.ts`);\n if (fs.existsSync(filePath) && !force) {\n skippedFiles.push(tableName);\n return;\n }\n\n let sampleData: Record<string, unknown>[] | undefined = undefined;\n if (runDataInference) {\n try {\n // Quoted by `quoteRelation`, which doubles an embedded\n // quote. Wrapping a catalogue name in `\"` is not\n // escaping it — see that function.\n const { rows } = await client.query(`SELECT * FROM ${quoteRelation(pgSchema, tableName)} LIMIT 100`);\n sampleData = rows;\n } catch (err) {\n outError(chalk.yellow(`⚠ Failed to sample data for table ${tableName}: ${err instanceof Error ? err.message : String(err)}`));\n }\n }\n\n const fileContent = generateCollectionFile(\n tableName,\n meta,\n fks,\n joinTables,\n tablesMap,\n enumMap,\n sampleData,\n { metadata, classifications, checkFacts, builder }\n );\n\n fs.writeFileSync(filePath, fileContent, \"utf-8\");\n generatedFiles.push(tableName);\n out(chalk.green(` ✓ ${filePath}`));\n }));\n }\n\n // Generate index.ts (sorted alphabetically for deterministic output)\n if (generatedFiles.length > 0) {\n const indexPath = path.join(outDir, \"index.ts\");\n\n if (fs.existsSync(indexPath) && !force) {\n // Merge: read existing index, add new exports that don't already exist\n const existing = fs.readFileSync(indexPath, \"utf-8\");\n const merged = mergeIndexContent(existing, generatedFiles);\n fs.writeFileSync(indexPath, merged, \"utf-8\");\n } else {\n // --force replaces collections derived from the database, but the\n // directory can also hold hand-written ones with no table in the\n // introspected schema (the auth users collection lives in\n // \"rebase\"). The backend discovers the whole directory, so an\n // index listing only introspected tables would silently drop them\n // from the admin UI while the API still served them.\n const siblings = fs.readdirSync(outDir)\n .filter(f => f.endsWith(\".ts\") && f !== \"index.ts\")\n .map(f => f.replace(/\\.ts$/, \"\"));\n const allFiles = [...new Set([...generatedFiles, ...siblings])];\n const indexContent = generateIndexContent(allFiles);\n fs.writeFileSync(indexPath, indexContent, \"utf-8\");\n }\n out(chalk.green(` ✓ ${indexPath}`));\n }\n\n out(\"\");\n if (skippedFiles.length > 0) {\n out(chalk.yellow(`⚠ Skipped ${skippedFiles.length} existing file(s): ${skippedFiles.join(\", \")}`));\n out(chalk.gray(\" Use --force to overwrite existing files.\"));\n out(\"\");\n }\n out(chalk.bold.green(`✓ Introspected ${tablesMap.size} tables — generated ${generatedFiles.length} collection(s).`));\n out(chalk.gray(` Review the generated files in ${outDir} and customize properties as needed.`));\n out(\"\");\n\n } catch (e) {\n outError(chalk.red(`✗ Error introspecting database: ${e instanceof Error ? e.message : String(e)}`));\n process.exit(1);\n } finally {\n await client.end();\n }\n}\n\nmain().catch((err) => {\n outError(String(err));\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAaA,IAAM,aAAa;;AAGnB,SAAS,qBAAqB,cAAmC;CAC7D,MAAM,wBAAQ,IAAI,IAAY;CAC9B,IAAI;CACJ,IAAI;EACA,SAAS,KAAK,MAAM,GAAG,aAAa,cAAc,OAAO,CAAC;CAC9D,QAAQ;EAGJ,OAAO;CACX;CACA,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAA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,OAAO,GAAG,CAAC;CACpB,QAAQ,KAAK,CAAC;AAClB,CAAC"}
|
|
@@ -57,8 +57,24 @@ export interface ConnectionPosture {
|
|
|
57
57
|
role: string;
|
|
58
58
|
superuser: boolean;
|
|
59
59
|
bypassRLS: boolean;
|
|
60
|
-
/**
|
|
60
|
+
/**
|
|
61
|
+
* Owns at least one user table — owners bypass non-FORCE RLS.
|
|
62
|
+
*
|
|
63
|
+
* "Owns" in Postgres's sense, not by name: a role that INHERITs the owner is
|
|
64
|
+
* the owner for every ownership test the planner makes, including the one
|
|
65
|
+
* that decides whether a policy applies at all.
|
|
66
|
+
*/
|
|
61
67
|
ownsTables: boolean;
|
|
68
|
+
/**
|
|
69
|
+
* May create tables somewhere the server writes — and would then own them.
|
|
70
|
+
*
|
|
71
|
+
* The reason this is part of the posture rather than a separate question:
|
|
72
|
+
* the posture is decided ONCE, at boot, and on a fresh database the
|
|
73
|
+
* catalogue has nothing to report yet. The process that asks then goes on to
|
|
74
|
+
* create every table in the schema and owns all of them for the rest of its
|
|
75
|
+
* life. Asking only what is already there answers about the wrong instant.
|
|
76
|
+
*/
|
|
77
|
+
canCreateTables: boolean;
|
|
62
78
|
/** True when RLS would NOT constrain this connection. */
|
|
63
79
|
privileged: boolean;
|
|
64
80
|
}
|
|
@@ -66,6 +82,21 @@ export interface AuthContext {
|
|
|
66
82
|
uid: string;
|
|
67
83
|
/** Raw roles as carried on the user (strings or `{ id }` objects). */
|
|
68
84
|
roles: unknown[];
|
|
85
|
+
/**
|
|
86
|
+
* Whether this session came from anonymous sign-in rather than an account.
|
|
87
|
+
*
|
|
88
|
+
* Anonymous sign-in mints a real user row and a real uid, so a guest was
|
|
89
|
+
* indistinguishable from a registered account inside a policy: same
|
|
90
|
+
* `rebase.uid()`, same default role. Every rule meaning "a signed-in
|
|
91
|
+
* person" was therefore also a rule about anybody who had called
|
|
92
|
+
* `POST /auth/anonymous`, which asks for no email, no password and no
|
|
93
|
+
* agreement to anything.
|
|
94
|
+
*
|
|
95
|
+
* Optional, and absent reads as `false`: a caller that predates this — a
|
|
96
|
+
* realtime subscription, a custom validator — keeps the behaviour it had
|
|
97
|
+
* rather than having every one of its users reclassified as guests.
|
|
98
|
+
*/
|
|
99
|
+
isAnonymous?: boolean;
|
|
69
100
|
}
|
|
70
101
|
/**
|
|
71
102
|
* Warn when the connection role shares its name with an existing schema.
|
|
@@ -95,7 +126,37 @@ export interface AuthContext {
|
|
|
95
126
|
* inherited would be worse than the risk.
|
|
96
127
|
*/
|
|
97
128
|
export declare function warnOnRoleSchemaCollision(run: RawSqlRunner): Promise<void>;
|
|
98
|
-
|
|
129
|
+
/**
|
|
130
|
+
* Would RLS actually constrain this connection?
|
|
131
|
+
*
|
|
132
|
+
* Four ways the answer is no, and only two of them are obvious. Superuser and
|
|
133
|
+
* BYPASSRLS announce themselves in `pg_roles`. The other two are about
|
|
134
|
+
* ownership, and both used to read as "no bypass here":
|
|
135
|
+
*
|
|
136
|
+
* - **Ownership through membership.** The old query compared
|
|
137
|
+
* `pg_tables.tableowner` to `current_user` as a string. Postgres does not: a
|
|
138
|
+
* role that INHERITs the owner passes every ownership test the planner makes,
|
|
139
|
+
* including the one that decides whether a policy applies. So a perfectly
|
|
140
|
+
* ordinary "app role that is a member of the owner role" setup reported
|
|
141
|
+
* unprivileged and bypassed every policy — permanently, since no restart
|
|
142
|
+
* changes a string comparison's answer.
|
|
143
|
+
*
|
|
144
|
+
* - **Ownership that has not happened yet.** The posture is decided once, at
|
|
145
|
+
* boot, and on a fresh database there is nothing in the catalogue to find. The
|
|
146
|
+
* same process then creates every table and owns all of them. The first boot
|
|
147
|
+
* of a new deployment therefore served every request unconstrained, the log
|
|
148
|
+
* said RLS was fine, and the SECOND boot silently fixed it — which is the
|
|
149
|
+
* worst possible shape for a security check, because the state that reproduces
|
|
150
|
+
* it is gone by the time anyone looks. Asking "may this role create tables
|
|
151
|
+
* where the server provisions?" answers about the process's whole life rather
|
|
152
|
+
* than about one instant of it.
|
|
153
|
+
*
|
|
154
|
+
* `schemas` narrows the CREATE question to where the server actually writes.
|
|
155
|
+
* Omitted, it asks about every schema the role can see, which is the safe
|
|
156
|
+
* direction: over-reporting costs a role switch that was not strictly needed,
|
|
157
|
+
* under-reporting costs the entire authorization model.
|
|
158
|
+
*/
|
|
159
|
+
export declare function detectConnectionPosture(run: RawSqlRunner, schemas?: string[]): Promise<ConnectionPosture>;
|
|
99
160
|
/**
|
|
100
161
|
* Human-actionable instructions for when the connection cannot provision the
|
|
101
162
|
* user role itself (no CREATEROLE and role not pre-created by the platform).
|
|
@@ -8,11 +8,38 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import { BranchInfo } from "@rebasepro/types";
|
|
10
10
|
import { DrizzleClient } from "../interfaces.js";
|
|
11
|
+
import { BranchRow } from "../branch-prune.js";
|
|
11
12
|
import { DatabasePoolManager } from "../databasePoolManager.js";
|
|
13
|
+
/**
|
|
14
|
+
* The connected server cannot branch, so nothing was done.
|
|
15
|
+
*
|
|
16
|
+
* A refusal, not a fault: typed so the transports can forward it intact.
|
|
17
|
+
* `websocket.ts` answers it with its own code and message rather than letting
|
|
18
|
+
* it fall into the generic handler, which suppresses the text in production —
|
|
19
|
+
* and the text is the only part that says what to do instead.
|
|
20
|
+
*/
|
|
21
|
+
export declare class BranchingUnsupportedError extends Error {
|
|
22
|
+
/** Wire code, forwarded verbatim to the client. */
|
|
23
|
+
readonly code = "BRANCHING_UNSUPPORTED";
|
|
24
|
+
constructor(message: string);
|
|
25
|
+
}
|
|
12
26
|
export declare class BranchService {
|
|
13
27
|
private db;
|
|
14
28
|
private poolManager;
|
|
15
29
|
constructor(db: DrizzleClient, poolManager: DatabasePoolManager);
|
|
30
|
+
/**
|
|
31
|
+
* Refuse a branch mutation the connected server cannot honour.
|
|
32
|
+
*
|
|
33
|
+
* The check lives here rather than in the CLI's argv parsing because the
|
|
34
|
+
* CLI is not the only caller: Studio reaches `createBranch` over the
|
|
35
|
+
* websocket, and before this it got "Branch created successfully" and a
|
|
36
|
+
* detail pane promising isolation for a database that is the parent.
|
|
37
|
+
*
|
|
38
|
+
* Reads only, and only mutations are guarded: `listBranches` on a managed
|
|
39
|
+
* database is an honest empty list, and refusing it would turn the Branches
|
|
40
|
+
* pane into a failure with a "Try again" that can never succeed.
|
|
41
|
+
*/
|
|
42
|
+
private assertBranchingSupported;
|
|
16
43
|
/**
|
|
17
44
|
* Ensure the `rebase.branches` metadata table exists in the default database.
|
|
18
45
|
* Idempotent — safe to call on every startup.
|
|
@@ -29,12 +56,70 @@ export declare class BranchService {
|
|
|
29
56
|
*/
|
|
30
57
|
createBranch(name: string, options?: {
|
|
31
58
|
source?: string;
|
|
59
|
+
force?: boolean;
|
|
32
60
|
}): Promise<BranchInfo>;
|
|
33
61
|
/**
|
|
34
62
|
* Delete a branch database and remove its metadata.
|
|
35
63
|
* Cannot delete the main/default database.
|
|
36
64
|
*/
|
|
37
|
-
deleteBranch(name: string
|
|
65
|
+
deleteBranch(name: string, options?: {
|
|
66
|
+
force?: boolean;
|
|
67
|
+
}): Promise<void>;
|
|
68
|
+
/**
|
|
69
|
+
* Who is holding the database open, in words a developer can act on.
|
|
70
|
+
*
|
|
71
|
+
* `CREATE DATABASE ... TEMPLATE` and `DROP DATABASE` both require that no
|
|
72
|
+
* other session is connected, and the one thing the old message could not
|
|
73
|
+
* say is the only thing worth knowing: *which* session. "Close other
|
|
74
|
+
* clients or connections and try again" is advice you cannot follow when
|
|
75
|
+
* you do not know there is a `rebase dev` in another terminal — and that is
|
|
76
|
+
* the common case, because wanting a branch and running the app are the
|
|
77
|
+
* same moment.
|
|
78
|
+
*
|
|
79
|
+
* `application_name` is the useful column: node-postgres sends none by
|
|
80
|
+
* default, so a Rebase process shows as `(unnamed)` while DBeaver, pgAdmin
|
|
81
|
+
* and psql all name themselves. Counting by it separates "my own dev
|
|
82
|
+
* server" from "the GUI I forgot about" without any guessing.
|
|
83
|
+
*
|
|
84
|
+
* Best-effort by construction: this runs while reporting a failure, and a
|
|
85
|
+
* diagnostic that throws would replace a real error with its own.
|
|
86
|
+
*/
|
|
87
|
+
private describeBlockingConnections;
|
|
88
|
+
/**
|
|
89
|
+
* Disconnect every other session on a database, and say how many.
|
|
90
|
+
*
|
|
91
|
+
* `pg_terminate_backend` rather than `pg_cancel_backend`: cancelling a
|
|
92
|
+
* query leaves the session connected, and a connected session is exactly
|
|
93
|
+
* what blocks the operation.
|
|
94
|
+
*
|
|
95
|
+
* The current backend is excluded — terminating the connection running this
|
|
96
|
+
* statement would abort the command that asked for it.
|
|
97
|
+
*/
|
|
98
|
+
private terminateConnections;
|
|
99
|
+
/**
|
|
100
|
+
* Everything prune needs to decide, in two queries.
|
|
101
|
+
*
|
|
102
|
+
* Reads the rows and the server's database list rather than joining them,
|
|
103
|
+
* so the *disagreements* between the two are visible — a row whose database
|
|
104
|
+
* is gone and a database with no row are the two things prune exists to
|
|
105
|
+
* find, and a join hides both.
|
|
106
|
+
*/
|
|
107
|
+
pruneCandidates(): Promise<{
|
|
108
|
+
rows: BranchRow[];
|
|
109
|
+
databases: string[];
|
|
110
|
+
}>;
|
|
111
|
+
/** Remove a metadata row whose database is already gone. */
|
|
112
|
+
forgetBranchRow(name: string): Promise<void>;
|
|
113
|
+
/**
|
|
114
|
+
* Drop a database by name, with no metadata row required.
|
|
115
|
+
*
|
|
116
|
+
* `deleteBranch` deliberately takes its database name from the row, because
|
|
117
|
+
* the row is the only value that is true by construction. Prune has the
|
|
118
|
+
* opposite job — the cases it handles are exactly the ones where row and
|
|
119
|
+
* database disagree — so it needs to name a database directly. Guarded the
|
|
120
|
+
* same way regardless: the main database is never droppable.
|
|
121
|
+
*/
|
|
122
|
+
dropDatabase(dbName: string): Promise<void>;
|
|
38
123
|
/**
|
|
39
124
|
* List all branches recorded in the metadata table.
|
|
40
125
|
* Optionally fetches database sizes from pg_database.
|
|
@@ -51,7 +51,7 @@ export declare function getCollectionByPath(collectionPath: string, registry: Po
|
|
|
51
51
|
* thing against the *config* and is skipped on four paths — `strictWrites:
|
|
52
52
|
* false`, a collection declaring no properties, an auth adapter that owns the
|
|
53
53
|
* body's shape, and a nested route whose target cannot be walked — and it never
|
|
54
|
-
* sees an in-process `rebase.
|
|
54
|
+
* sees an in-process `rebase.dataAsAdmin` write at all.
|
|
55
55
|
*
|
|
56
56
|
* It also gives `strictWrites: false` a truthful implementation. The flag is
|
|
57
57
|
* documented for "a column that really does exist which the config never
|
|
@@ -13,6 +13,14 @@ import type { ChannelRetentionRule } from "@rebasepro/types";
|
|
|
13
13
|
export interface SubscriptionAuthContext {
|
|
14
14
|
uid: string;
|
|
15
15
|
roles: string[];
|
|
16
|
+
/**
|
|
17
|
+
* Whether this session is a guest — anonymous sign-in rather than an
|
|
18
|
+
* account. Carried so a refetch's policies see the same principal the
|
|
19
|
+
* initial fetch did; without it a rule that excludes guests would filter on
|
|
20
|
+
* the REST read and not on the frames that follow, which is the shape that
|
|
21
|
+
* makes a realtime leak invisible from the surface people test.
|
|
22
|
+
*/
|
|
23
|
+
isAnonymous?: boolean;
|
|
16
24
|
}
|
|
17
25
|
/** What a channel frame is asking to do. */
|
|
18
26
|
export type ChannelAction = "join" | "broadcast" | "presence" | "history";
|
|
@@ -225,8 +233,15 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
|
|
|
225
233
|
* would leak rows the initial (isolated) fetch correctly hid.
|
|
226
234
|
*/
|
|
227
235
|
rlsUserRole?: string;
|
|
228
|
-
/**
|
|
229
|
-
|
|
236
|
+
/**
|
|
237
|
+
* Verbose subscription tracing.
|
|
238
|
+
*
|
|
239
|
+
* Through the logger at `debug`, behind the same switch that lifts the
|
|
240
|
+
* `Failed query:` redaction: these lines quote paths, filters and refetch
|
|
241
|
+
* SQL, and a `console.debug` gated on `NODE_ENV` alone wrote them to stdout
|
|
242
|
+
* whatever `LOG_LEVEL` said, without passing through the one function where
|
|
243
|
+
* redaction lives.
|
|
244
|
+
*/
|
|
230
245
|
private debugLog;
|
|
231
246
|
setDataDriver(driver: DataDriver): void;
|
|
232
247
|
get subscriptions(): Map<string, Subscription>;
|
|
@@ -366,6 +381,19 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
|
|
|
366
381
|
*/
|
|
367
382
|
/** The key columns of the collection at `path`, if they can be resolved. */
|
|
368
383
|
private primaryKeysForPath;
|
|
384
|
+
/**
|
|
385
|
+
* `channel` addresses the error to the channel frame it is about.
|
|
386
|
+
*
|
|
387
|
+
* Without it the client had nowhere to deliver a channel error: channel
|
|
388
|
+
* frames are fire-and-forget, so there is no pending request to reject and
|
|
389
|
+
* no subscription id to match, and `CHANNEL_FORBIDDEN`, `RATE_LIMITED` and
|
|
390
|
+
* the two history failures fell through every branch of the client's
|
|
391
|
+
* message handler into a console warning. The client already routes
|
|
392
|
+
* channel-addressed frames by name — `onChannelMessage(channel, …)` — so
|
|
393
|
+
* naming the channel is all that was missing.
|
|
394
|
+
*
|
|
395
|
+
* Additive on the wire: a client that does not read it behaves as before.
|
|
396
|
+
*/
|
|
369
397
|
private sendError;
|
|
370
398
|
private sendMessage;
|
|
371
399
|
/**
|
|
@@ -12,7 +12,7 @@ import { PostgresCollectionRegistry } from "../collections/PostgresCollectionReg
|
|
|
12
12
|
* target's values. This is what the admin renders.
|
|
13
13
|
* - `"inline"` — the target's own columns, flat. This is what REST serves, and
|
|
14
14
|
* — since the in-process SDK reads through the same pipeline — what
|
|
15
|
-
* `rebase.
|
|
15
|
+
* `rebase.dataAsAdmin` / `context.data` serve too. A developer never sees a ref.
|
|
16
16
|
*
|
|
17
17
|
* They used to be two functions that happened to agree, and the agreement was
|
|
18
18
|
* not enforced by anything: the row-identity bug had to be fixed five times
|
|
@@ -29,6 +29,17 @@ export type RelationStyle = "ref" | "inline";
|
|
|
29
29
|
* to unwrap that same level back out.
|
|
30
30
|
*/
|
|
31
31
|
export declare function isJunctionRelation(relation: ResolvedRelation): boolean;
|
|
32
|
+
/** Render one target row in the requested style. */
|
|
33
|
+
/**
|
|
34
|
+
* Drop every column the collection marked `excludeFromApi`.
|
|
35
|
+
*
|
|
36
|
+
* Password hashes and verification tokens have to be readable server-side but
|
|
37
|
+
* must never reach a client — and "never" has to mean every exit from this
|
|
38
|
+
* pipeline, including relation targets, or a secret leaks through whichever
|
|
39
|
+
* path was overlooked. Keyed by both the property name and its column name,
|
|
40
|
+
* since a row can arrive keyed either way depending on the caller.
|
|
41
|
+
*/
|
|
42
|
+
export declare function stripExcluded(row: Record<string, unknown>, collection: CollectionConfig): Record<string, unknown>;
|
|
32
43
|
/**
|
|
33
44
|
* The address a relation ref points at.
|
|
34
45
|
*
|