@rebasepro/server-postgres 0.13.0 → 0.13.1-canary.g18cfeb7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/PostgresBackendDriver.d.ts +48 -1
- package/dist/{src-DlPBctw_.js → auth-users-columns-Do9mw5Y5.js} +318 -42
- package/dist/auth-users-columns-Do9mw5Y5.js.map +1 -0
- package/dist/{backup-service-CD8o_1Sl.js → backup-service-Bww-Lg0s.js} +2 -2
- package/dist/{backup-service-CD8o_1Sl.js.map → backup-service-Bww-Lg0s.js.map} +1 -1
- package/dist/cli-helpers.d.ts +1 -1
- package/dist/{ensure-collection-policies-ViG8XiPn.js → ensure-collection-policies-DMUdRQdM.js} +2 -2
- package/dist/{ensure-collection-policies-ViG8XiPn.js.map → ensure-collection-policies-DMUdRQdM.js.map} +1 -1
- package/dist/{ensure-collection-tables-CBQdOETu.js → ensure-collection-tables-DSIxvLLD.js} +59 -15
- package/dist/ensure-collection-tables-DSIxvLLD.js.map +1 -0
- package/dist/index.es.js +534 -200
- package/dist/index.es.js.map +1 -1
- package/dist/{policy-CeA1JcxP.js → policy-CPkCqVTz.js} +4 -4
- package/dist/policy-CPkCqVTz.js.map +1 -0
- package/dist/rls-bootstrap-sql-Bpv3nUZo.js +244 -0
- package/dist/rls-bootstrap-sql-Bpv3nUZo.js.map +1 -0
- package/dist/schema/auth-users-columns.d.ts +97 -0
- package/dist/schema/ensure-collection-tables.d.ts +1 -1
- package/dist/schema/generate-drizzle-schema-logic.d.ts +1 -1
- package/dist/schema/generate-postgres-ddl-logic.d.ts +5 -5
- package/dist/schema/generated-schema-staleness.d.ts +39 -0
- package/dist/schema/rls-bootstrap-sql.d.ts +135 -0
- package/dist/security/rls-enforcement.d.ts +53 -2
- package/dist/services/FetchService.d.ts +10 -7
- package/dist/services/dataService.d.ts +2 -0
- package/dist/services/realtimeService.d.ts +25 -21
- package/dist/{src-DoU9yPqq.js → src-C_wvdMnl.js} +91 -2
- package/dist/src-C_wvdMnl.js.map +1 -0
- package/dist/{websocket-B2LsrINK.js → websocket-D0TBU3ia.js} +3 -3
- package/dist/{websocket-B2LsrINK.js.map → websocket-D0TBU3ia.js.map} +1 -1
- package/package.json +9 -8
- package/src/PostgresBackendDriver.ts +165 -3
- package/src/PostgresBootstrapper.ts +41 -2
- package/src/auth/ensure-tables.ts +185 -86
- package/src/cli-helpers.ts +22 -9
- package/src/cli.ts +175 -30
- package/src/collections/validate-relations.ts +124 -17
- package/src/data-transformer.ts +13 -3
- package/src/history/ensure-history-table.ts +7 -0
- package/src/schema/auth-users-columns.ts +131 -0
- package/src/schema/doctor.ts +7 -5
- package/src/schema/ensure-collection-tables.ts +88 -19
- package/src/schema/generate-drizzle-schema-logic.ts +8 -2
- package/src/schema/generate-postgres-ddl-logic.ts +97 -13
- package/src/schema/generated-schema-staleness.ts +169 -0
- package/src/schema/introspect-db-logic.ts +1 -1
- package/src/schema/non-sql-collections.test.ts +131 -0
- package/src/schema/rls-bootstrap-sql.ts +288 -0
- package/src/security/anonymous-grants.test.ts +4 -2
- package/src/security/rls-enforcement.ts +141 -3
- package/src/services/BranchService.ts +5 -0
- package/src/services/FetchService.ts +10 -93
- package/src/services/PersistService.ts +14 -1
- package/src/services/channel-history.ts +8 -0
- package/src/services/channel-presence.ts +6 -0
- package/src/services/dataService.ts +2 -0
- package/src/services/realtimeService.ts +36 -33
- package/dist/ensure-collection-tables-CBQdOETu.js.map +0 -1
- package/dist/policy-CeA1JcxP.js.map +0 -1
- package/dist/schema/auth-bootstrap-sql.d.ts +0 -24
- package/dist/src-DlPBctw_.js.map +0 -1
- package/dist/src-DoU9yPqq.js.map +0 -1
- package/src/schema/auth-bootstrap-sql.ts +0 -47
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical SQL bootstrap for the RLS helper functions.
|
|
3
|
+
*
|
|
4
|
+
* Generated RLS policies reference `rebase.uid()` / `rebase.roles()` /
|
|
5
|
+
* `rebase.jwt()`, so any SQL stream that can contain policies must be
|
|
6
|
+
* self-contained: it has to (re)create these helpers first. This matters for
|
|
7
|
+
* the migration directory in particular — Atlas replays migrations against a
|
|
8
|
+
* clean dev database where no out-of-band bootstrap has ever run, so a
|
|
9
|
+
* migration carrying policies without this preamble fails with
|
|
10
|
+
* "function rebase.uid() does not exist".
|
|
11
|
+
*
|
|
12
|
+
* Idempotent (`IF NOT EXISTS` / `OR REPLACE`) so it can be prepended to every
|
|
13
|
+
* policies block and re-applied freely. The runtime boot path
|
|
14
|
+
* (`auth/ensure-tables.ts`) creates the same functions under an advisory lock
|
|
15
|
+
* for HMR-safety; keep the definitions in sync.
|
|
16
|
+
*
|
|
17
|
+
* ## Creating the `rebase` schema here is now safe, and required
|
|
18
|
+
*
|
|
19
|
+
* It deliberately did not, once. These functions lived in a schema called
|
|
20
|
+
* `auth`, and the note here read: creating `rebase` would leak it into Atlas's
|
|
21
|
+
* replayed migration state, and — absent from the desired `schema.sql` — Atlas
|
|
22
|
+
* would then plan `DROP SCHEMA "rebase" CASCADE`, taking the auth tables with
|
|
23
|
+
* it. That reasoning still holds; what changed is the second half of it. The
|
|
24
|
+
* DDL generator now emits `CREATE SCHEMA IF NOT EXISTS "rebase"`
|
|
25
|
+
* unconditionally, so the schema is always in the desired state and the diff is
|
|
26
|
+
* empty. (It used to appear only when some collection happened to declare
|
|
27
|
+
* `schema: "rebase"` — true for the scaffold's users collection, and not a
|
|
28
|
+
* property anything guaranteed.) `db push` additionally excludes the whole
|
|
29
|
+
* schema from the declarative apply.
|
|
30
|
+
*
|
|
31
|
+
* See `@rebasepro/types`' `rls-functions` for why the functions moved out of
|
|
32
|
+
* `auth` at all: the short version is that the name was Supabase's, and
|
|
33
|
+
* `CREATE OR REPLACE FUNCTION auth.uid() RETURNS text` cannot be applied over
|
|
34
|
+
* Supabase's `RETURNS uuid` — Postgres refuses, and the refusal used to be
|
|
35
|
+
* swallowed.
|
|
36
|
+
*/
|
|
37
|
+
/**
|
|
38
|
+
* The bootstrap as individual statements.
|
|
39
|
+
*
|
|
40
|
+
* Kept as an array because the two consumers need different shapes and only one
|
|
41
|
+
* of them can take a multi-command string: the migration preamble is written to
|
|
42
|
+
* a file and replayed by Atlas, but the boot path runs through drizzle, whose
|
|
43
|
+
* node-postgres handle speaks the extended query protocol and rejects more than
|
|
44
|
+
* one command per call. Splitting a joined string back apart on `$$;` would be
|
|
45
|
+
* a parser for a problem that does not need one.
|
|
46
|
+
*/
|
|
47
|
+
export declare const RLS_BOOTSTRAP_STATEMENTS: readonly string[];
|
|
48
|
+
/** The same statements as one script, for migration files and raw clients. */
|
|
49
|
+
export declare const RLS_BOOTSTRAP_SQL: string;
|
|
50
|
+
/**
|
|
51
|
+
* Removes the pre-1.0 `auth` schema, but only when Rebase is what put it there.
|
|
52
|
+
*
|
|
53
|
+
* ## Why this is safe against a Supabase database
|
|
54
|
+
*
|
|
55
|
+
* Two independent guards, and both have to pass:
|
|
56
|
+
*
|
|
57
|
+
* 1. **Each function is identified before it is dropped.** Ours returns `text`
|
|
58
|
+
* and reads the `app.uid` GUC; Supabase's returns `uuid` and reads
|
|
59
|
+
* `request.jwt.claims`. Nothing is dropped on a signature we did not write,
|
|
60
|
+
* so a Supabase database — where our `CREATE OR REPLACE` could never have
|
|
61
|
+
* succeeded in the first place, Postgres refusing to change a return type —
|
|
62
|
+
* matches nothing and this is a no-op.
|
|
63
|
+
* 2. **`DROP SCHEMA … RESTRICT`**, never CASCADE. If anything else at all still
|
|
64
|
+
* lives in `auth` (Supabase's `users` table, its other helpers), the drop
|
|
65
|
+
* fails and the schema stays. CASCADE here would be unrecoverable.
|
|
66
|
+
*
|
|
67
|
+
* ## Why it cannot run too early
|
|
68
|
+
*
|
|
69
|
+
* Postgres records a dependency from every RLS policy to the functions its body
|
|
70
|
+
* calls, so `DROP FUNCTION auth.uid()` fails for as long as a single policy
|
|
71
|
+
* still references it. That is the interlock, and it is load-bearing: the drop
|
|
72
|
+
* can only succeed once every policy has been recompiled to \`rebase.uid()\`.
|
|
73
|
+
* Callers therefore run this *after* applying policies, and treat a failure as
|
|
74
|
+
* "not yet — try again next boot" rather than as an error.
|
|
75
|
+
*/
|
|
76
|
+
export declare const DROP_LEGACY_AUTH_SCHEMA_SQL = "\nDO $rebase_drop_legacy$\nDECLARE\n dropped_any boolean := false;\nBEGIN\n -- Each function is matched on its own result type and body, so a schema\n -- that merely shares the name keeps everything it has.\n IF EXISTS (\n SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname = 'auth' AND p.proname = 'uid'\n AND pg_get_function_result(p.oid) = 'text'\n AND p.prosrc LIKE '%app.uid%'\n ) THEN\n DROP FUNCTION auth.uid();\n dropped_any := true;\n END IF;\n\n IF EXISTS (\n SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname = 'auth' AND p.proname = 'jwt'\n AND pg_get_function_result(p.oid) = 'jsonb'\n AND p.prosrc LIKE '%app.jwt%'\n ) THEN\n DROP FUNCTION auth.jwt();\n dropped_any := true;\n END IF;\n\n IF EXISTS (\n SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname = 'auth' AND p.proname = 'roles'\n AND pg_get_function_result(p.oid) = 'text'\n AND p.prosrc LIKE '%app.user_roles%'\n ) THEN\n DROP FUNCTION auth.roles();\n dropped_any := true;\n END IF;\n\n -- RESTRICT: only an empty schema goes. Anything else in there \u2014 including a\n -- Supabase installation left untouched above \u2014 keeps it.\n IF dropped_any THEN\n BEGIN\n EXECUTE 'DROP SCHEMA auth RESTRICT';\n EXCEPTION WHEN OTHERS THEN\n NULL;\n END;\n END IF;\nEND\n$rebase_drop_legacy$;\n";
|
|
77
|
+
/** Somebody's policy that still calls a pre-1.0 helper. */
|
|
78
|
+
export interface LegacyRlsDependent {
|
|
79
|
+
schema: string;
|
|
80
|
+
table: string;
|
|
81
|
+
policy: string;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Policies whose body still calls `auth.uid()` / `auth.roles()` / `auth.jwt()`.
|
|
85
|
+
*
|
|
86
|
+
* Postgres will not drop a function a policy depends on, so this is exactly the
|
|
87
|
+
* set standing between a database and losing the legacy schema. Rebase's own
|
|
88
|
+
* policies leave the list on the next push or boot, when they are recompiled —
|
|
89
|
+
* anything still here afterwards is hand-written, will never be recompiled by
|
|
90
|
+
* anybody, and is the reason the drop keeps being skipped. Silence there would
|
|
91
|
+
* leave an operator staring at a schema the release notes said would go.
|
|
92
|
+
*/
|
|
93
|
+
export declare const LEGACY_RLS_DEPENDENTS_SQL = "\n SELECT n.nspname AS schema, c.relname AS \"table\", p.polname AS policy\n FROM pg_policy p\n JOIN pg_class c ON c.oid = p.polrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE pg_get_expr(p.polqual, p.polrelid) ~* '\\mauth\\.(uid|jwt|roles)\\s*\\('\n OR pg_get_expr(p.polwithcheck, p.polrelid) ~* '\\mauth\\.(uid|jwt|roles)\\s*\\('\n ORDER BY 1, 2, 3\n";
|
|
94
|
+
/** Somebody's *function* that still calls a pre-1.0 helper from its own body. */
|
|
95
|
+
export interface LegacyRlsFunctionDependent {
|
|
96
|
+
schema: string;
|
|
97
|
+
function: string;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Functions whose body calls `auth.uid()` / `auth.roles()` / `auth.jwt()`.
|
|
101
|
+
*
|
|
102
|
+
* This is the half `DROP FUNCTION ... RESTRICT` cannot see, and the reason it
|
|
103
|
+
* needs its own query. Postgres records a dependency for a *policy* that calls a
|
|
104
|
+
* function, which is why the drop is safe against the policies above — but a
|
|
105
|
+
* `LANGUAGE sql` function whose body is a **string literal** is not parsed when
|
|
106
|
+
* it is created, so nothing is recorded and `RESTRICT` has nothing to refuse on.
|
|
107
|
+
* The drop succeeds and the caller is left pointing at a function that no longer
|
|
108
|
+
* exists, which fails at *query* time rather than at boot.
|
|
109
|
+
*
|
|
110
|
+
* A downstream project building on these helpers is not hypothetical: the Rebase
|
|
111
|
+
* control plane defines `auth.is_org_member(uuid)` and `auth.is_org_admin(uuid)`
|
|
112
|
+
* in this very schema, each calling `auth.uid()` in a string body, and eleven of
|
|
113
|
+
* its row-level-security policies go through them. Every one of those would have
|
|
114
|
+
* started failing the first time a recompile left no policy referencing
|
|
115
|
+
* `auth.uid()` directly — the drop's own precondition.
|
|
116
|
+
*
|
|
117
|
+
* Matching on the body text is the only option available, and it is deliberately
|
|
118
|
+
* broad: a false positive costs a schema that stays one release longer and says
|
|
119
|
+
* why, while a false negative costs somebody their policies.
|
|
120
|
+
*/
|
|
121
|
+
export declare const LEGACY_RLS_FUNCTION_DEPENDENTS_SQL = "\n SELECT n.nspname AS schema, p.proname AS function\n FROM pg_proc p\n JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')\n AND NOT (n.nspname = 'auth' AND p.proname IN ('uid', 'jwt', 'roles'))\n AND p.prosrc ~* '\\mauth\\.(uid|jwt|roles)\\s*\\('\n ORDER BY 1, 2\n";
|
|
122
|
+
/**
|
|
123
|
+
* Retire the pre-1.0 `auth` schema, reporting what is holding it back.
|
|
124
|
+
*
|
|
125
|
+
* The shared implementation behind the CLI's post-push step and the runtime's
|
|
126
|
+
* post-policy step. Both used to just fire {@link DROP_LEGACY_AUTH_SCHEMA_SQL}
|
|
127
|
+
* and swallow whatever came back, which is right for the ordinary case — a
|
|
128
|
+
* table not recompiled *yet* — and wrong for the one that never resolves: a
|
|
129
|
+
* hand-written policy nothing will ever rewrite. Then the schema stays forever
|
|
130
|
+
* and nothing ever says why.
|
|
131
|
+
*/
|
|
132
|
+
export declare function dropLegacyAuthSchema(run: (sql: string) => Promise<Record<string, unknown>[]>, report: {
|
|
133
|
+
info: (m: string) => void;
|
|
134
|
+
warn: (m: string) => void;
|
|
135
|
+
}): Promise<void>;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { SQL } from "drizzle-orm";
|
|
2
2
|
import { SecurityRule } from "@rebasepro/types";
|
|
3
|
+
import { REBASE_USER_ROLE } from "@rebasepro/common";
|
|
3
4
|
/**
|
|
4
5
|
* Unified RLS enforcement — the "user context vs server context" model.
|
|
5
6
|
*
|
|
@@ -32,8 +33,14 @@ import { SecurityRule } from "@rebasepro/types";
|
|
|
32
33
|
* self-creates the `auth` schema and functions) — enforcement is default-on,
|
|
33
34
|
* not an operator opt-in.
|
|
34
35
|
*/
|
|
35
|
-
/**
|
|
36
|
-
|
|
36
|
+
/**
|
|
37
|
+
* The restricted role every authenticated (user-context) request runs as.
|
|
38
|
+
*
|
|
39
|
+
* Re-exported, not re-declared: the same name is needed by
|
|
40
|
+
* `@rebasepro/common`'s internal-table revokes, and two spellings of a role name
|
|
41
|
+
* fail as a silent no-op rather than an error.
|
|
42
|
+
*/
|
|
43
|
+
export { REBASE_USER_ROLE };
|
|
37
44
|
/** Minimal SQL runner so callers can adapt drizzle or pg.Client. */
|
|
38
45
|
export type RawSqlRunner = (sqlText: string) => Promise<Record<string, unknown>[]>;
|
|
39
46
|
/** Minimal transaction surface needed by {@link applyAuthContext}. */
|
|
@@ -55,6 +62,34 @@ export interface AuthContext {
|
|
|
55
62
|
/** Raw roles as carried on the user (strings or `{ id }` objects). */
|
|
56
63
|
roles: unknown[];
|
|
57
64
|
}
|
|
65
|
+
/**
|
|
66
|
+
* Warn when the connection role shares its name with an existing schema.
|
|
67
|
+
*
|
|
68
|
+
* Postgres resolves unqualified names through `search_path`, which defaults to
|
|
69
|
+
* `"$user", public` — and `$user` is the connection ROLE. When a schema of that
|
|
70
|
+
* name exists it sits ahead of `public`, so every unqualified statement
|
|
71
|
+
* silently operates on it instead:
|
|
72
|
+
*
|
|
73
|
+
* CREATE TABLE posts (...); -- you meant public.posts; you got <role>.posts
|
|
74
|
+
*
|
|
75
|
+
* Nothing errors. You get a second table of the same name in the wrong schema,
|
|
76
|
+
* and reads that pin `public` cannot see it — which reads as "missing table" and
|
|
77
|
+
* sends people to re-run a push that creates a *third* copy. The bootstrapper
|
|
78
|
+
* has a whole branch dedicated to recognising the symptom after the fact.
|
|
79
|
+
*
|
|
80
|
+
* Rebase shipped straight into this: it creates a schema named `rebase` while
|
|
81
|
+
* every template named the database role `rebase` too. The scaffold uses
|
|
82
|
+
* `rebase_app` now, and every pool Rebase opens pins `search_path=public`
|
|
83
|
+
* (`pinSearchPath`), which covers the paths the framework controls. This covers
|
|
84
|
+
* the ones it does not — `psql`, `pg_dump`, drizzle-kit, a colleague's script,
|
|
85
|
+
* a hand-written migration — because the hazard is a property of the two NAMES,
|
|
86
|
+
* not of any one connection.
|
|
87
|
+
*
|
|
88
|
+
* A warning rather than a boot failure: the database works, the framework's own
|
|
89
|
+
* traffic is pinned, and refusing to start over a naming choice a user may have
|
|
90
|
+
* inherited would be worse than the risk.
|
|
91
|
+
*/
|
|
92
|
+
export declare function warnOnRoleSchemaCollision(run: RawSqlRunner): Promise<void>;
|
|
58
93
|
export declare function detectConnectionPosture(run: RawSqlRunner): Promise<ConnectionPosture>;
|
|
59
94
|
/**
|
|
60
95
|
* Human-actionable instructions for when the connection cannot provision the
|
|
@@ -123,6 +158,22 @@ export declare function warnOnAnonymousGrants(collections: {
|
|
|
123
158
|
slug?: string;
|
|
124
159
|
securityRules?: readonly SecurityRule[];
|
|
125
160
|
}[]): void;
|
|
161
|
+
/**
|
|
162
|
+
* Name the collections whose raw policy SQL still calls the pre-1.0 helpers.
|
|
163
|
+
*
|
|
164
|
+
* The compiler rewrites `auth.uid()` to `rebase.uid()` on the way into the
|
|
165
|
+
* database, so nothing is broken and no policy is wrong — which is exactly why
|
|
166
|
+
* this has to be said out loud. A silent rewrite that works forever is not a
|
|
167
|
+
* migration, it is a second supported spelling nobody wrote down, and the next
|
|
168
|
+
* person to read those rules will copy the old one.
|
|
169
|
+
*
|
|
170
|
+
* Only `raw` expressions can carry it. Structured rules (`policy.authUid()`,
|
|
171
|
+
* `policy.rolesOverlap(...)`) compile from the model and were never affected.
|
|
172
|
+
*/
|
|
173
|
+
export declare function warnOnLegacyRlsFunctions(collections: {
|
|
174
|
+
slug?: string;
|
|
175
|
+
securityRules?: readonly SecurityRule[];
|
|
176
|
+
}[]): void;
|
|
126
177
|
/**
|
|
127
178
|
* Reject `pgRoles` that this server can never satisfy.
|
|
128
179
|
*
|
|
@@ -153,6 +153,16 @@ export declare class FetchService {
|
|
|
153
153
|
*/
|
|
154
154
|
fetchCollection<M extends Record<string, unknown>>(collectionPath: string, options?: {
|
|
155
155
|
filter?: FilterValues<Extract<keyof M, string>>;
|
|
156
|
+
/**
|
|
157
|
+
* An `or(...)`/`and(...)` group, applied alongside `filter`.
|
|
158
|
+
*
|
|
159
|
+
* `fetchRowsWithConditions` below has always applied this; it was
|
|
160
|
+
* simply absent from this signature, so the only callers that could
|
|
161
|
+
* pass one were the ones that went around this method. Realtime
|
|
162
|
+
* came through here, which is why a subscription filtered by a
|
|
163
|
+
* logical group was pushed every row in the table.
|
|
164
|
+
*/
|
|
165
|
+
logical?: LogicalCondition;
|
|
156
166
|
orderBy?: string;
|
|
157
167
|
order?: "desc" | "asc";
|
|
158
168
|
limit?: number;
|
|
@@ -226,13 +236,6 @@ export declare class FetchService {
|
|
|
226
236
|
* Note: Primary path now uses inline `getQueryBuilder()` checks.
|
|
227
237
|
*/
|
|
228
238
|
private hasDrizzleQueryAPI;
|
|
229
|
-
/**
|
|
230
|
-
* Attempt to use Drizzle's relational query API (db.query.<table>.findMany)
|
|
231
|
-
* for efficient JOIN-based relation loading.
|
|
232
|
-
* Returns null if the API is not available or the query fails.
|
|
233
|
-
* Note: Primary path now uses `buildWithConfig` + `buildDrizzleQueryOptions`.
|
|
234
|
-
*/
|
|
235
|
-
private fetchWithDrizzleQuery;
|
|
236
239
|
/**
|
|
237
240
|
* Fallback path used when db.query is unavailable.
|
|
238
241
|
* The primary path uses db.query.findMany with `with` config, which
|
|
@@ -36,6 +36,8 @@ export declare class DataService implements DataRepository {
|
|
|
36
36
|
*/
|
|
37
37
|
fetchCollection<M extends Record<string, unknown>>(collectionPath: string, options?: {
|
|
38
38
|
filter?: FilterValues<Extract<keyof M, string>>;
|
|
39
|
+
/** An `or(...)`/`and(...)` group, applied alongside `filter`. */
|
|
40
|
+
logical?: LogicalCondition;
|
|
39
41
|
orderBy?: string;
|
|
40
42
|
order?: "desc" | "asc";
|
|
41
43
|
limit?: number;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { WebSocket } from "ws";
|
|
2
2
|
import { EventEmitter } from "events";
|
|
3
|
-
import { DataDriver, WebSocketMessage } from "@rebasepro/types";
|
|
3
|
+
import { DataDriver, WebSocketMessage, LogicalCondition } from "@rebasepro/types";
|
|
4
4
|
import { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
5
5
|
import { RealtimeProvider, CollectionSubscriptionConfig, SingleSubscriptionConfig } from "../interfaces";
|
|
6
6
|
import { PostgresCollectionRegistry } from "../collections/PostgresCollectionRegistry";
|
|
@@ -14,6 +14,27 @@ export interface SubscriptionAuthContext {
|
|
|
14
14
|
uid: string;
|
|
15
15
|
roles: string[];
|
|
16
16
|
}
|
|
17
|
+
/**
|
|
18
|
+
* The narrowing a collection subscription was created with, kept so that every
|
|
19
|
+
* refetch answers the same query the initial fetch did.
|
|
20
|
+
*
|
|
21
|
+
* Named once because it used to be written out inline in five places, and a
|
|
22
|
+
* field missing from one of them is accepted over the wire and then silently
|
|
23
|
+
* ignored: `offset` was declared on the incoming props and never stored, so a
|
|
24
|
+
* live list on page three served page one, and `logical` was never stored
|
|
25
|
+
* either, so an `or(...)` subscription was pushed every row in the table.
|
|
26
|
+
*/
|
|
27
|
+
type StoredCollectionRequest = {
|
|
28
|
+
filter?: Record<string, unknown>;
|
|
29
|
+
logical?: LogicalCondition;
|
|
30
|
+
orderBy?: string;
|
|
31
|
+
order?: "desc" | "asc";
|
|
32
|
+
limit?: number;
|
|
33
|
+
offset?: number;
|
|
34
|
+
startAfter?: Record<string, unknown>;
|
|
35
|
+
databaseId?: string;
|
|
36
|
+
searchString?: string;
|
|
37
|
+
};
|
|
17
38
|
/**
|
|
18
39
|
* PostgreSQL-specific realtime service.
|
|
19
40
|
* Handles WebSocket connections and subscriptions for real-time row updates.
|
|
@@ -128,16 +149,7 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
|
|
|
128
149
|
type: "collection" | "single";
|
|
129
150
|
path: string;
|
|
130
151
|
id?: string | number;
|
|
131
|
-
collectionRequest?:
|
|
132
|
-
filter?: Record<string, unknown>;
|
|
133
|
-
orderBy?: string;
|
|
134
|
-
order?: "desc" | "asc";
|
|
135
|
-
limit?: number;
|
|
136
|
-
offset?: number;
|
|
137
|
-
startAfter?: Record<string, unknown>;
|
|
138
|
-
databaseId?: string;
|
|
139
|
-
searchString?: string;
|
|
140
|
-
};
|
|
152
|
+
collectionRequest?: StoredCollectionRequest;
|
|
141
153
|
authContext?: SubscriptionAuthContext;
|
|
142
154
|
}>;
|
|
143
155
|
registerDataDriverSubscription(subscriptionId: string, subscription: {
|
|
@@ -145,16 +157,7 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
|
|
|
145
157
|
type: "collection" | "single";
|
|
146
158
|
path: string;
|
|
147
159
|
id?: string | number;
|
|
148
|
-
collectionRequest?:
|
|
149
|
-
filter?: Record<string, unknown>;
|
|
150
|
-
orderBy?: string;
|
|
151
|
-
order?: "desc" | "asc";
|
|
152
|
-
limit?: number;
|
|
153
|
-
offset?: number;
|
|
154
|
-
startAfter?: Record<string, unknown>;
|
|
155
|
-
databaseId?: string;
|
|
156
|
-
searchString?: string;
|
|
157
|
-
};
|
|
160
|
+
collectionRequest?: StoredCollectionRequest;
|
|
158
161
|
authContext?: SubscriptionAuthContext;
|
|
159
162
|
}): void;
|
|
160
163
|
addSubscriptionCallback(subscriptionId: string, callback: (data: Record<string, unknown>[] | Record<string, unknown> | null) => void): void;
|
|
@@ -497,3 +500,4 @@ export declare class RealtimeService extends EventEmitter implements RealtimePro
|
|
|
497
500
|
* This allows code to use PostgresRealtimeProvider alongside future MongoRealtimeProvider, etc.
|
|
498
501
|
*/
|
|
499
502
|
export declare const PostgresRealtimeProvider: typeof RealtimeService;
|
|
503
|
+
export {};
|
|
@@ -231,6 +231,95 @@ function getDeclaredSubcollections(collection) {
|
|
|
231
231
|
return collection.subcollections;
|
|
232
232
|
}
|
|
233
233
|
//#endregion
|
|
234
|
-
|
|
234
|
+
//#region ../types/src/types/rls-functions.ts
|
|
235
|
+
/**
|
|
236
|
+
* The SQL helper functions RLS policies call, and the schema they live in.
|
|
237
|
+
*
|
|
238
|
+
* ## One schema, and it is ours
|
|
239
|
+
*
|
|
240
|
+
* Rebase creates exactly one schema in a project's database: `rebase`. These
|
|
241
|
+
* three functions live in it alongside the framework's own tables, and that is
|
|
242
|
+
* the whole contract — a reader can look at a database and know precisely which
|
|
243
|
+
* namespace belongs to the framework and that nothing else was touched.
|
|
244
|
+
*
|
|
245
|
+
* It used to be two. `uid()`, `jwt()` and `roles()` sat in a schema called
|
|
246
|
+
* `auth`, which is Supabase's name, chosen so that a developer who had written
|
|
247
|
+
* Supabase RLS would recognise `auth.uid()`. The familiarity was real but the
|
|
248
|
+
* name was not Rebase's to take, and taking it had a concrete cost: pointing
|
|
249
|
+
* Rebase at a database that already had a Supabase `auth` schema meant
|
|
250
|
+
* `CREATE OR REPLACE FUNCTION auth.uid() RETURNS text` against Supabase's
|
|
251
|
+
* `RETURNS uuid`, which Postgres rejects outright —
|
|
252
|
+
*
|
|
253
|
+
* ERROR: cannot change return type of existing function
|
|
254
|
+
* HINT: Use DROP FUNCTION auth.uid() first.
|
|
255
|
+
*
|
|
256
|
+
* — and the failure landed inside a catch-all that logged a warning and carried
|
|
257
|
+
* on, leaving a database with auth tables, no helper functions, and policies
|
|
258
|
+
* calling functions that did not exist. Under `rebase db migrate` the same
|
|
259
|
+
* statements aborted the migration instead.
|
|
260
|
+
*
|
|
261
|
+
* `rebase.uid()` collides with nobody. A Supabase database keeps its `auth`
|
|
262
|
+
* schema untouched and gains a `rebase` one, which is what a gradual migration
|
|
263
|
+
* needs.
|
|
264
|
+
*
|
|
265
|
+
* ## Why functions at all, rather than inlining `current_setting`
|
|
266
|
+
*
|
|
267
|
+
* Because the indirection has already been spent once. `uid()` resolves
|
|
268
|
+
* `app.uid` and falls back to the pre-rename `app.user_id`, so that during a
|
|
269
|
+
* rolling deploy — old and new pods serving one database — both eras resolve
|
|
270
|
+
* the principal. That was a single `CREATE OR REPLACE`. Inlined into policy
|
|
271
|
+
* bodies it would have been a rewrite of every policy on every table.
|
|
272
|
+
*
|
|
273
|
+
* ## Why the name is not configurable
|
|
274
|
+
*
|
|
275
|
+
* A policy body is stored SQL: Postgres parses `USING (…)` once and keeps it, so
|
|
276
|
+
* these strings are written into every policy in every database Rebase has
|
|
277
|
+
* provisioned. Everything that reads policies back — the SQL-to-policy parser
|
|
278
|
+
* behind the admin UI, the drift checker, `rls-check` — would have to know the
|
|
279
|
+
* configured value to recognise its own output. One frozen name is the feature.
|
|
280
|
+
*/
|
|
281
|
+
/** The schema Rebase owns. The only schema Rebase creates. */
|
|
282
|
+
var REBASE_SCHEMA = "rebase";
|
|
283
|
+
/**
|
|
284
|
+
* The principal of the current request, as text, or NULL in the server context.
|
|
285
|
+
*
|
|
286
|
+
* Never NULL for a user request — an anonymous one carries
|
|
287
|
+
* {@link ANONYMOUS_USER_ID} — which is what makes `IS NULL` a reliable test for
|
|
288
|
+
* the trusted server plane and `IS NOT NULL` a tautology.
|
|
289
|
+
*/
|
|
290
|
+
var RLS_UID_SQL = `${REBASE_SCHEMA}.uid()`;
|
|
291
|
+
/** The request's roles as a comma-separated string, for `string_to_array`. */
|
|
292
|
+
var RLS_ROLES_SQL = `${REBASE_SCHEMA}.roles()`;
|
|
293
|
+
`${REBASE_SCHEMA}`;
|
|
294
|
+
/**
|
|
295
|
+
* The pre-1.0 spellings, for recognising policies and hand-written SQL that
|
|
296
|
+
* predate the move.
|
|
297
|
+
*
|
|
298
|
+
* Kept because policies outlive the server that wrote them: a database migrated
|
|
299
|
+
* by an older release still holds `auth.uid()` in its policy bodies until the
|
|
300
|
+
* next push or boot recompiles them, and anything that reads policies back has
|
|
301
|
+
* to recognise both eras or report the framework's own output as foreign drift.
|
|
302
|
+
* Also used to give a project whose `securityRules` contain raw `auth.uid()` a
|
|
303
|
+
* message naming the replacement, instead of a parse failure.
|
|
304
|
+
*/
|
|
305
|
+
var LEGACY_RLS_SCHEMA = "auth";
|
|
306
|
+
`${LEGACY_RLS_SCHEMA}`;
|
|
307
|
+
`${LEGACY_RLS_SCHEMA}`;
|
|
308
|
+
`${LEGACY_RLS_SCHEMA}`;
|
|
309
|
+
/**
|
|
310
|
+
* Rewrites the pre-1.0 function calls in a fragment of policy SQL.
|
|
311
|
+
*
|
|
312
|
+
* Deliberately anchored on a word boundary and the schema qualifier, so a column
|
|
313
|
+
* called `auth_uid` or a table named `auth` is left alone.
|
|
314
|
+
*/
|
|
315
|
+
function rewriteLegacyRlsFunctions(sql) {
|
|
316
|
+
return sql.replace(/\bauth\.(uid|jwt|roles)\s*\(\s*\)/gi, (_match, fn) => `${REBASE_SCHEMA}.${fn.toLowerCase()}()`);
|
|
317
|
+
}
|
|
318
|
+
/** Whether a fragment of SQL still calls the pre-1.0 functions. */
|
|
319
|
+
function usesLegacyRlsFunctions(sql) {
|
|
320
|
+
return /\bauth\.(uid|jwt|roles)\s*\(\s*\)/i.test(sql);
|
|
321
|
+
}
|
|
322
|
+
//#endregion
|
|
323
|
+
export { rewriteLegacyRlsFunctions as a, isPostgresCollectionConfig as c, getDataSourceCapabilities as d, NULL_OPS as f, RLS_UID_SQL as i, isRelationalCollectionConfig as l, toCanonicalOp as m, REBASE_SCHEMA as n, usesLegacyRlsFunctions as o, REST_TO_CANONICAL as p, RLS_ROLES_SQL as r, getDeclaredSubcollections as s, LEGACY_RLS_SCHEMA as t, DEFAULT_DATA_SOURCE_KEY as u };
|
|
235
324
|
|
|
236
|
-
//# sourceMappingURL=src-
|
|
325
|
+
//# sourceMappingURL=src-C_wvdMnl.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-C_wvdMnl.js","names":[],"sources":["../../types/src/types/filter-operators.ts","../../types/src/types/data_source.ts","../../types/src/types/collections.ts","../../types/src/types/rls-functions.ts"],"sourcesContent":["/**\n * Canonical filter operators and REST wire-format mappings.\n *\n * `WhereFilterOp` is THE operator type used at every layer — from React\n * components through the SDK, server, and down to the database driver.\n *\n * PostgREST short-codes (`eq`, `gt`, `cs`, …) exist **only** at the\n * HTTP wire boundary, handled by `serializeFilter` / `deserializeFilter`\n * in `@rebasepro/common`.\n *\n * ┌──────────────────────┬───────────────┬──────────────────────────────┐\n * │ Canonical │ REST short │ Meaning │\n * ├──────────────────────┼───────────────┼──────────────────────────────┤\n * │ \"==\" │ \"eq\" │ Equal │\n * │ \"!=\" │ \"neq\" │ Not equal │\n * │ \">\" │ \"gt\" │ Greater than │\n * │ \">=\" │ \"gte\" │ Greater than or equal │\n * │ \"<\" │ \"lt\" │ Less than │\n * │ \"<=\" │ \"lte\" │ Less than or equal │\n * │ \"in\" │ \"in\" │ Value in list │\n * │ \"not-in\" │ \"nin\" │ Value not in list │\n * │ \"array-contains\" │ \"cs\" │ Array contains element │\n * │ \"array-contains-any\" │ \"csa\" │ Array contains any of │\n * │ \"like\" │ \"like\" │ SQL LIKE (case-sensitive) │\n * │ \"ilike\" │ \"ilike\" │ SQL ILIKE (case-insensitive) │\n * │ \"not-like\" │ \"nlike\" │ NOT LIKE (case-sensitive) │\n * │ \"not-ilike\" │ \"nilike\" │ NOT ILIKE (case-insensitive) │\n * │ \"is-null\" │ \"isnull\" │ Field IS NULL │\n * │ \"is-not-null\" │ \"notnull\" │ Field IS NOT NULL │\n * └──────────────────────┴───────────────┴──────────────────────────────┘\n *\n * Pattern matching (`like`/`ilike`) uses SQL wildcard syntax: `%` matches any\n * sequence of characters, `_` matches a single character. On MongoDB these are\n * translated to anchored regular expressions; Firestore has no native pattern\n * matching and rejects these operators (use `searchString` instead).\n *\n * @module\n */\n\n/**\n * Canonical sort representation: `[fieldName, direction]`.\n *\n * Used in `FindParams.orderBy`, `collection.sort`, and `FilterPreset.sort`.\n * The colon-string form (`\"field:direction\"`) exists only at the HTTP wire\n * boundary, handled by `serializeOrderBy` / `deserializeOrderBy` in\n * `@rebasepro/common`.\n *\n * Design note: the natural extension for multi-column sort is\n * `OrderByTuple[]` — not implemented yet (server consumes only the first).\n *\n * @group Models\n */\nexport type OrderByTuple<Key extends string = string> = [Key, \"asc\" | \"desc\"];\n\n/**\n * Canonical filter operators supported across all database backends.\n * Each DB driver translates these to its native query format.\n *\n * @group Models\n */\nexport type WhereFilterOp =\n | \"<\"\n | \"<=\"\n | \"==\"\n | \"!=\"\n | \">=\"\n | \">\"\n | \"array-contains\"\n | \"in\"\n | \"not-in\"\n | \"array-contains-any\"\n | \"like\"\n | \"ilike\"\n | \"not-like\"\n | \"not-ilike\"\n | \"is-null\"\n | \"is-not-null\";\n\n/**\n * Used to define filters applied in collections.\n *\n * A single condition is a tuple `[operator, value]`.\n * Multiple conditions on the same field use an array of tuples.\n *\n * @example\n * // Single condition per field\n * { status: [\"==\", \"active\"], price: [\">=\", 9.99] }\n *\n * // Multiple conditions on one field\n * { age: [[\">=\", 18], [\"<\", 65]] }\n *\n * // Array operators\n * { role: [\"in\", [\"admin\", \"editor\"]] }\n * { tags: [\"array-contains\", \"featured\"] }\n *\n * // Pattern matching (SQL wildcards: % and _)\n * { name: [\"ilike\", \"%john%\"] }\n * { slug: [\"like\", \"post-%\"] }\n *\n * // Null checks (the value is ignored; `null` is conventional)\n * { deleted_at: [\"is-null\", null] }\n * { published_at: [\"is-not-null\", null] }\n *\n * @group Models\n */\nexport type FilterValues<Key extends string> =\n Partial<Record<Key, [WhereFilterOp, unknown] | [WhereFilterOp, unknown][]>>;\n\n/**\n * The field names a query may address on a row type: every column, plus a\n * dotted path reaching inside one.\n *\n * Only the **root** of a dotted path is checked. `\"meta.tag\"` requires a `meta`\n * column and says nothing about what is under it, because what is under it is a\n * `map`/jsonb value whose shape the row type does not describe — and rejecting\n * paths we cannot verify would make jsonb columns unqueryable.\n *\n * When `M` is left at its default `Record<string, unknown>`, `keyof M` is\n * `string` and a template literal over `string` is itself assignable to\n * `string`, so this collapses to `string` and every query stays permissive.\n * That is what keeps an untyped `createRebaseClient()` behaving exactly as it\n * did before the row type was threaded through.\n *\n * @group Models\n */\nexport type FieldPath<M extends Record<string, unknown> = Record<string, unknown>> =\n | Extract<keyof M, string>\n | `${Extract<keyof M, string>}.${string}`;\n\n/**\n * Relaxed filter type that also accepts pre-serialized PostgREST strings.\n * **Internal only** — used at the wire-format boundary\n * (`serializeFilter` / `deserializeFilter` in `@rebasepro/common`).\n *\n * Application code, UI components, and SDK consumers should use\n * {@link FilterValues} instead.\n *\n * @internal\n */\nexport type WireFilterValues<Key extends string> =\n Partial<Record<Key, [WhereFilterOp, unknown] | [WhereFilterOp, unknown][] | string>>;\n\n/**\n * A pre-defined filter preset for quick access in the collection toolbar.\n * Users can select a preset to instantly apply a set of filters and\n * optionally a sort order.\n *\n * @group Models\n */\nexport interface FilterPreset<Key extends string = string> {\n /**\n * Display label shown in the preset menu.\n * If omitted, a summary is auto-generated from the filter keys.\n */\n label?: string;\n\n /**\n * The filter values to apply when this preset is selected.\n */\n filterValues: FilterValues<Key>;\n\n /**\n * Optional sort override to apply alongside the filter values.\n */\n sort?: OrderByTuple<Key>;\n}\n\n/**\n * PostgREST short-code operators. Wire format only — these never appear\n * in application code. Used by `serializeFilter`/`deserializeFilter`\n * in `@rebasepro/common`.\n */\nexport type RestFilterOp =\n | \"eq\" | \"neq\"\n | \"gt\" | \"gte\"\n | \"lt\" | \"lte\"\n | \"in\" | \"nin\"\n | \"cs\" | \"csa\"\n | \"like\" | \"ilike\"\n | \"nlike\" | \"nilike\"\n | \"isnull\" | \"notnull\";\n\n/** Maps canonical operators to their REST short-code equivalents. */\nexport const CANONICAL_TO_REST: Readonly<Record<WhereFilterOp, RestFilterOp>> = {\n \"==\": \"eq\",\n \"!=\": \"neq\",\n \">\": \"gt\",\n \">=\": \"gte\",\n \"<\": \"lt\",\n \"<=\": \"lte\",\n \"in\": \"in\",\n \"not-in\": \"nin\",\n \"array-contains\": \"cs\",\n \"array-contains-any\": \"csa\",\n \"like\": \"like\",\n \"ilike\": \"ilike\",\n \"not-like\": \"nlike\",\n \"not-ilike\": \"nilike\",\n \"is-null\": \"isnull\",\n \"is-not-null\": \"notnull\"\n};\n\n/** Maps REST short-code operators to their canonical equivalents. */\nexport const REST_TO_CANONICAL: Readonly<Record<RestFilterOp, WhereFilterOp>> = {\n \"eq\": \"==\",\n \"neq\": \"!=\",\n \"gt\": \">\",\n \"gte\": \">=\",\n \"lt\": \"<\",\n \"lte\": \"<=\",\n \"in\": \"in\",\n \"nin\": \"not-in\",\n \"cs\": \"array-contains\",\n \"csa\": \"array-contains-any\",\n \"like\": \"like\",\n \"ilike\": \"ilike\",\n \"nlike\": \"not-like\",\n \"nilike\": \"not-ilike\",\n \"isnull\": \"is-null\",\n \"notnull\": \"is-not-null\"\n};\n\n/**\n * Operators that test for null/not-null and therefore ignore their value.\n * Codecs normalize the value of these conditions to `null`.\n */\nexport const NULL_OPS: ReadonlySet<WhereFilterOp> = new Set<WhereFilterOp>([\n \"is-null\", \"is-not-null\"\n]);\n\n/**\n * Every canonical operator, in a stable order. Useful for engine capability\n * declarations ({@link DataSourceCapabilities.filterOperators}) and for\n * building operator subsets.\n * @group Models\n */\nexport const ALL_WHERE_FILTER_OPS: readonly WhereFilterOp[] = [\n \"<\", \"<=\", \"==\", \"!=\", \">=\", \">\",\n \"in\", \"not-in\",\n \"array-contains\", \"array-contains-any\",\n \"like\", \"ilike\", \"not-like\", \"not-ilike\",\n \"is-null\", \"is-not-null\"\n];\n\n/** All canonical operator strings for runtime validation. */\nconst CANONICAL_OPS: ReadonlySet<string> = new Set<WhereFilterOp>(ALL_WHERE_FILTER_OPS);\n\n/**\n * Resolve any operator string (canonical or REST short-code) to its\n * canonical `WhereFilterOp` form. Returns `undefined` for unknown operators.\n *\n * @example\n * toCanonicalOp(\"==\") // \"==\"\n * toCanonicalOp(\"eq\") // \"==\"\n * toCanonicalOp(\"cs\") // \"array-contains\"\n * toCanonicalOp(\"xyz\") // undefined\n */\nexport function toCanonicalOp(op: string): WhereFilterOp | undefined {\n if (CANONICAL_OPS.has(op)) return op as WhereFilterOp;\n return (REST_TO_CANONICAL as Record<string, WhereFilterOp | undefined>)[op];\n}\n","import { ALL_WHERE_FILTER_OPS, WhereFilterOp } from \"./filter-operators\";\n\n/**\n * Describes the capabilities and features supported by a data source (driver).\n *\n * Each driver (Postgres, Firebase, MongoDB, etc.) declares which features it\n * supports. The admin uses this descriptor to:\n * - Show/hide editor tabs (e.g. Relations for SQL, Subcollections for Firebase)\n * - Filter the property type picker (e.g. `relation` for SQL, `reference` for Firebase)\n * - Toggle driver-specific form controls (e.g. `columnType` for SQL)\n *\n * @group Models\n */\nexport interface DataSourceCapabilities {\n /** Unique driver key (e.g. \"postgres\", \"firestore\", \"mongodb\") */\n key: string;\n\n /** Human-readable label for the UI (e.g. \"PostgreSQL\", \"Firebase / Firestore\") */\n label: string;\n\n // ── Feature flags ─────────────────────────────────────────────────\n /** Does this source support SQL-style relations (JOINs)? */\n supportsRelations: boolean;\n\n /** Does this source support nested subcollections? */\n supportsSubcollections: boolean;\n\n /** Does this source support Row Level Security policies? */\n supportsRLS: boolean;\n\n /** Does this source support document references (Firebase-style)? */\n supportsReferences: boolean;\n\n /** Does this source support SQL column type annotations? */\n supportsColumnTypes: boolean;\n\n /** Does this source support real-time listeners? */\n supportsRealtime: boolean;\n\n /**\n * Does this source store vectors natively?\n *\n * `VectorProperty` carries a `dimensions` and is pgvector-shaped. It was\n * the one driver-specific property kind with no flag to gate it, so unlike\n * every other field in this descriptor there was not even a runtime answer\n * to appeal to — a Firestore collection could declare an embedding column\n * and no driver would do anything with it.\n */\n supportsVectors: boolean;\n\n /**\n * Canonical filter operators this engine can execute.\n *\n * The admin UI intersects this set with the property-type defaults and\n * any per-property narrowing (`property.ui.filterOperators`) to decide\n * which operators to offer in filter fields — so an engine that cannot\n * run `ilike` (e.g. Firestore) never shows a \"Contains\" filter that\n * would throw at query time.\n */\n filterOperators: readonly WhereFilterOp[];\n\n /**\n * Relation kinds this engine's driver can compile into a filter.\n *\n * Only `belongsTo` puts a column on the row being filtered; the others are\n * answered with a correlated subquery over the junction or the target\n * table, which not every driver can build. An engine with no relations at\n * all declares none.\n *\n * The admin uses this to decide whether a relation column offers a filter\n * control. Offering one an engine cannot answer is not cosmetic: a driver\n * that drops the key it cannot resolve *widens* the read to every row, and\n * one that fails closed answers a control the admin itself put on screen\n * with a 400.\n *\n * Optional, so a third-party driver registered before this existed still\n * compiles. Omitted means {@link DEFAULT_FILTERABLE_RELATION_KINDS} — the\n * one kind that is a plain column comparison, which every relational\n * driver can do. The subquery kinds are a real capability and have to be\n * claimed rather than assumed: assuming them wrongly is the widening.\n */\n filterableRelationKinds?: readonly string[];\n\n // ── Admin capability flags ───────────────────────────────────────\n /** Does this source support SQL admin operations (SQL editor, EXPLAIN, etc.)? */\n supportsSQLAdmin: boolean;\n\n /** Does this source support document admin operations (aggregation, stats)? */\n supportsDocumentAdmin: boolean;\n\n /** Does this source support schema admin (unmapped tables, table metadata)? */\n supportsSchemaAdmin: boolean;\n}\n\n/**\n * Subset of DataSourceCapabilities containing only feature flags.\n * Useful when you only need to check capabilities without UI metadata.\n * @group Models\n */\nexport type DataSourceFeatures = Omit<DataSourceCapabilities, \"key\" | \"label\">;\n\n/**\n * The default data-source key, used when a collection does not name a\n * `dataSource`. Shared by the frontend router and the backend driver\n * registry so both agree on \"the default database\".\n * @group Models\n */\nexport const DEFAULT_DATA_SOURCE_KEY = \"(default)\";\n\n/**\n * How the *frontend* reaches a data source.\n *\n * - `\"server\"` — through the Rebase backend (the `RebaseClient`). The backend\n * holds the actual database adapter and routes by data-source key. This is\n * the default and covers Postgres, MongoDB, and any other server-mediated\n * engine.\n * - `\"direct\"` — straight from the client to the external backend via its own\n * SDK driver (e.g. Firestore). The Rebase backend is not in the data path.\n * - `\"custom\"` — a developer-supplied {@link DataDriver}, transport unspecified.\n *\n * @group Models\n */\nexport type DataSourceTransport = \"server\" | \"direct\" | \"custom\";\n\n/**\n * Declarative definition of a data source — a named place data lives.\n *\n * Declared once and shared front and back: the frontend uses it to decide\n * transport (client vs direct driver), the backend uses the same `key` to\n * resolve a database adapter, and the editor derives capabilities from\n * `engine`. Collections reference a definition by its `key` via\n * `collection.dataSource`.\n *\n * @group Models\n */\nexport interface DataSourceDefinition {\n /**\n * Unique identifier for this data source. Collections point at it via\n * `dataSource`. Defaults to {@link DEFAULT_DATA_SOURCE_KEY}.\n */\n key: string;\n\n /**\n * The engine backing this data source (e.g. `\"postgres\"`, `\"mongodb\"`,\n * `\"firestore\"`, or a custom id). Determines the\n * {@link DataSourceCapabilities} surfaced in the editor.\n */\n engine: string;\n\n /**\n * How the frontend reaches this source. Optional — when omitted it is\n * inferred: `\"direct\"` if the definition carries a client-side driver,\n * `\"server\"` otherwise.\n */\n transport?: DataSourceTransport;\n\n /**\n * The physical database/schema/Firestore-database within the engine.\n * Threaded to drivers/adapters as the existing `databaseId` runtime\n * parameter. Defaults to the engine's own default.\n */\n databaseId?: string;\n\n /** Human-readable label for the UI. */\n label?: string;\n}\n\n/**\n * The resolved data source for a collection: the single source of truth that\n * the frontend router, backend registry, and editor all derive from.\n * Produced by `resolveDataSource(collection, registry)`.\n *\n * @group Models\n */\nexport interface ResolvedDataSource {\n /** Data-source key (routing key, shared front + back). */\n key: string;\n /** Engine backing the source (drives capabilities). */\n engine: string;\n /** Frontend transport. */\n transport: DataSourceTransport;\n /** Within-engine instance, if any (the `databaseId` runtime param). */\n databaseId?: string;\n /** Capabilities derived from {@link engine}. */\n capabilities: DataSourceCapabilities;\n}\n\n/**\n * Relation kinds assumed filterable when a driver does not say.\n *\n * `belongsTo` alone: its filter is a comparison on a column of the row being\n * filtered, the one shape that needs no query construction a driver might not\n * have. Everything else is a correlated subquery over another table.\n *\n * @group Models\n */\nexport const DEFAULT_FILTERABLE_RELATION_KINDS: readonly string[] = [\"belongsTo\"];\n\n// ── Built-in driver capabilities ─────────────────────────────────────\n\n/** @group Models */\nexport const POSTGRES_CAPABILITIES: DataSourceCapabilities = {\n key: \"postgres\",\n label: \"PostgreSQL\",\n supportsRelations: true,\n supportsSubcollections: false,\n supportsRLS: true,\n supportsReferences: false,\n supportsColumnTypes: true,\n supportsRealtime: true,\n supportsVectors: true,\n filterOperators: ALL_WHERE_FILTER_OPS,\n // `via` is absent: its join path is authored source → target with no\n // stated inverse, so the driver has nothing to reverse into a filter.\n filterableRelationKinds: [\"belongsTo\", \"manyToMany\", \"hasMany\", \"hasOne\"],\n supportsSQLAdmin: true,\n supportsDocumentAdmin: false,\n supportsSchemaAdmin: true\n};\n\n/** @group Models */\nexport const FIREBASE_CAPABILITIES: DataSourceCapabilities = {\n key: \"firestore\",\n label: \"Firebase / Firestore\",\n supportsRelations: false,\n supportsSubcollections: true,\n supportsRLS: false,\n supportsReferences: true,\n supportsColumnTypes: false,\n supportsRealtime: true,\n supportsVectors: false,\n // Firestore has no SQL pattern matching — the driver throws on the LIKE\n // family, so the UI must never offer it.\n filterOperators: ALL_WHERE_FILTER_OPS.filter(op =>\n op !== \"like\" && op !== \"ilike\" && op !== \"not-like\" && op !== \"not-ilike\"),\n // No relations at all — a document store links by reference.\n filterableRelationKinds: [],\n supportsSQLAdmin: false,\n supportsDocumentAdmin: false,\n supportsSchemaAdmin: false\n};\n\n/** @group Models */\nexport const MONGODB_CAPABILITIES: DataSourceCapabilities = {\n key: \"mongodb\",\n label: \"MongoDB\",\n supportsRelations: false,\n supportsSubcollections: true,\n supportsRLS: false,\n supportsReferences: true,\n supportsColumnTypes: false,\n supportsRealtime: false,\n supportsVectors: false,\n filterOperators: ALL_WHERE_FILTER_OPS,\n filterableRelationKinds: [],\n supportsSQLAdmin: false,\n supportsDocumentAdmin: true,\n supportsSchemaAdmin: true\n};\n\n/**\n * Fallback capabilities when the driver is unknown.\n * Enables everything so nothing is hidden unexpectedly.\n * @group Models\n */\nexport const DEFAULT_CAPABILITIES: DataSourceCapabilities = {\n key: \"(default)\",\n label: \"Default\",\n supportsRelations: true,\n supportsSubcollections: true,\n supportsRLS: true,\n supportsReferences: true,\n supportsColumnTypes: true,\n supportsRealtime: true,\n supportsVectors: true,\n filterOperators: ALL_WHERE_FILTER_OPS,\n // The exception to this descriptor's \"enable everything\" rule. The other\n // flags hide a tab or a picker when they are wrong; this one decides\n // whether a query is sent that an unknown driver may answer by dropping\n // the condition — which returns every row rather than none.\n filterableRelationKinds: DEFAULT_FILTERABLE_RELATION_KINDS,\n supportsSQLAdmin: true,\n supportsDocumentAdmin: true,\n supportsSchemaAdmin: true\n};\n\nconst CAPABILITIES_REGISTRY: Record<string, DataSourceCapabilities> = {\n postgres: POSTGRES_CAPABILITIES,\n firestore: FIREBASE_CAPABILITIES,\n mongodb: MONGODB_CAPABILITIES,\n \"(default)\": DEFAULT_CAPABILITIES\n};\n\n/**\n * Look up capabilities for a given engine key.\n * If `engine` is undefined or not found, returns `DEFAULT_CAPABILITIES`.\n * @group Models\n */\nexport function getDataSourceCapabilities(engine?: string): DataSourceCapabilities {\n if (!engine) return POSTGRES_CAPABILITIES; // postgres is the default engine\n return CAPABILITIES_REGISTRY[engine] ?? DEFAULT_CAPABILITIES;\n}\n\n/**\n * Register custom capabilities for a third-party driver.\n * @group Models\n */\nexport function registerDataSourceCapabilities(capabilities: DataSourceCapabilities): void {\n CAPABILITIES_REGISTRY[capabilities.key] = capabilities;\n}\n","import type { CollectionCallbacks } from \"./entity_callbacks\";\n\nimport type { EnumValues, Properties, PostgresProperties, FirebaseProperties, MongoProperties } from \"./properties\";\n\nimport type { User } from \"../users\";\nimport type { Relation } from \"./relations\";\nimport type { SecurityRule } from \"./security_rules\";\nimport { getDataSourceCapabilities } from \"./data_source\";\nimport type { WhereFilterOp, FilterValues, FilterPreset } from \"./filter-operators\";\n\n/**\n * Base interface containing all driver-agnostic collection properties.\n * Use {@link PostgresCollectionConfig} or {@link FirebaseCollectionConfig} for\n * driver-specific type safety, or {@link CollectionConfig} when you\n * need to handle any collection regardless of backend.\n *\n * @group Models\n */\nexport interface BaseCollectionConfig<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User> {\n\n /**\n * The collection's identity. Required, and the value nearly everything else\n * keys on:\n *\n * - the REST path — `/api/data/<slug>`\n * - the SDK accessor — `client.data.<slug>` / `client.data.collection(\"<slug>\")`\n * - the admin panel's URL\n * - the target of a `reference` or `relation` property\n *\n * Conventionally kebab-case and plural (`blog-posts`). It is independent of\n * {@link table}: the slug is what callers say, the table is where the rows\n * live, and renaming one does not rename the other.\n *\n * Treat it as frozen once anything has shipped against it — changing a slug\n * changes every URL and every generated accessor at once.\n *\n * @example\n * defineCollection({\n * slug: \"blog-posts\", // /api/data/blog-posts, client.data.blogPosts\n * table: \"posts\",\n * properties: { … }\n * })\n */\n slug: string;\n\n /**\n * Name of the collection, typically plural.\n * E.g. `Products`, `Blog`\n */\n name: string;\n\n /**\n * Singular name of an entry in this collection\n * E.g. `Product`, `Blog entry`\n */\n singularName?: string;\n\n /**\n * Optional description of this view. You can use Markdown.\n */\n description?: string;\n\n /**\n * Child collections nested under entities of this collection.\n * Populated automatically during normalization from driver-specific fields\n * (e.g. Firebase `subcollections`, Postgres `relations` with many-cardinality).\n *\n * Custom drivers can set this directly to expose child collections to the UI.\n */\n childCollections?: () => CollectionConfig<Record<string, unknown>>[];\n\n\n /**\n * The data source this collection belongs to — the routing key shared by\n * the frontend router and the backend driver registry. It points at a\n * {@link DataSourceDefinition} registered on `<Rebase dataSources>` (front)\n * and `initializeRebaseBackend({ dataSources })` (back).\n *\n * If not specified, the default data source `\"(default)\"` is used, which\n * for a standard Rebase app is the server-mediated Postgres backend.\n *\n * @example\n * // Default data source (server-mediated Postgres)\n * { slug: \"products\" }\n *\n * // A direct-transport Firestore data source registered as \"analytics\"\n * { slug: \"events\", dataSource: \"analytics\" }\n */\n dataSource?: string;\n\n /**\n * The database engine backing this collection (`\"postgres\"`, `\"firestore\"`,\n * `\"mongodb\"`, or a custom id).\n *\n * On concrete collection types ({@link PostgresCollectionConfig},\n * {@link FirebaseCollectionConfig}, {@link MongoDBCollectionConfig}) this is a literal\n * discriminant. On the base type it is optional and gets stamped\n * automatically during collection normalization from the registered\n * {@link DataSourceDefinition}.\n *\n * Prefer setting {@link dataSource} and letting the engine be resolved.\n */\n engine?: string;\n\n /**\n * Which database within the engine.\n * - For Firestore: The Firestore database ID (e.g., for multi-database projects)\n * - For PostgreSQL: Schema or database name\n * - For MongoDB: Database name\n *\n * If not specified, the default database of the engine is used. Resolved\n * from the collection's {@link DataSourceDefinition} when omitted here.\n */\n databaseId?: string;\n\n /**\n * Set of properties that compose a entity\n */\n properties: Properties;\n\n\n\n\n\n\n\n\n\n\n\n\n /**\n * Mark this collection as an authentication collection.\n * When true, this collection is used for user management, login, password hashing, and invitation flows.\n */\n auth?: boolean | AuthCollectionConfig;\n\n\n\n\n\n\n\n /**\n * Row-level authorization rules for this collection.\n *\n * Driver-agnostic on purpose, unlike `disableDefaultPolicies`, `table` and\n * `relations`, which are declared on {@link PostgresCollectionConfig} only.\n * The rules are a *contract* — who may read or write which rows — and each\n * engine enforces it its own way:\n *\n * - **Postgres** compiles them to real `CREATE POLICY` statements and lets\n * the database enforce them (see {@link PostgresCollectionConfig.securityRules},\n * which narrows this with the raw-SQL details).\n * - **MongoDB** translates them into a query filter it AND-s into every\n * read and write, honouring `access`, `ownerField`, `roles`, `mode` and\n * the `operation`/`operations` selectors, and making a best effort at raw\n * `using`/`withCheck` SQL.\n * - **Firestore** does not implement them at all; its own rules language is\n * evaluated by Google, not from here. `supportsRLS` on\n * {@link DataSourceCapabilities} reports which engines generate policies,\n * which is not the same question as whether an engine honours a rule.\n */\n securityRules?: readonly SecurityRule[];\n\n /**\n * This interface defines all the callbacks that can be used when a entity\n * is being created, updated or deleted.\n * Useful for adding your own logic or blocking the execution of the operation.\n */\n readonly callbacks?: CollectionCallbacks<M, USER>;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n /**\n * User id of the owner of this collection. This is used only by plugins, or if you\n * are writing custom code\n */\n ownerId?: string;\n\n /**\n * Arbitrary key-value metadata for external consumers.\n * Not interpreted by Rebase — passed through serialization unchanged.\n * Used by domain apps to store custom per-collection config.\n */\n metadata?: Record<string, unknown>;\n\n\n\n\n /**\n * If set to true, changes to the entity will be saved in a subcollection.\n * This prop has no effect if the history plugin is not enabled\n */\n history?: boolean;\n\n /**\n * Whether a write naming a field this collection does not declare is\n * rejected with a 400. Defaults to `true`.\n *\n * Set to `false` to let unknown keys through to the database, which is what\n * happened before this existed: a typo reached the INSERT and came back as\n * a Postgres error about a column, or — where a column really does exist\n * that the config never declared, populated by a trigger or a default —\n * quietly worked. The second case is the reason for the escape hatch.\n */\n strictWrites?: boolean;\n\n\n\n\n\n\n\n\n}\n\n// ── Driver-specific collection types ──────────────────────────────────\n\n/**\n * A collection backed by PostgreSQL (or any SQL database).\n * Adds support for SQL-style relations (JOINs) and Row Level Security.\n *\n * Use this type instead of {@link CollectionConfig} when you want\n * compile-time safety that only SQL-relevant fields appear.\n *\n * @group Models\n */\nexport interface PostgresCollectionConfig<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User>\n extends BaseCollectionConfig<M, USER> {\n properties: PostgresProperties;\n\n /**\n * The database engine for this collection. For Postgres collections this\n * can be omitted (Postgres is the default) or set to `\"postgres\"`.\n */\n engine?: \"postgres\" | undefined;\n\n /**\n * The PostgreSQL table name for this collection.\n */\n table: string;\n\n /**\n * The PostgreSQL schema name for this table.\n * E.g. \"public\", \"rebase\", \"auth\".\n * If not specified, \"public\" is used (or the default search path).\n */\n schema?: string;\n\n /**\n * For SQL databases, you can define the relations between collections here.\n * Relations describe JOINs, foreign keys, and junction tables.\n */\n relations?: Relation[];\n\n /**\n * Security rules for this collection (PostgreSQL Row Level Security).\n * When defined, the schema generator will enable RLS on the table and\n * create the corresponding PostgreSQL policies.\n *\n * Supports three levels of expressiveness:\n * 1. **Convenience shortcuts** — `ownerField`, `access`, `roles`\n * 2. **Raw SQL** — `using` and `withCheck` for full PostgreSQL power\n * 3. **Combined** — mix shortcuts with `roles` for common patterns\n *\n * The authenticated user context is available in raw SQL via:\n * - `auth.uid()` — the current user's ID\n * - `auth.roles()` — comma-separated app role IDs\n * - `auth.jwt()` — full JWT claims as JSONB\n */\n securityRules?: readonly SecurityRule[];\n\n /**\n * Opt out of the framework's default Row Level Security policies.\n *\n * The schema generator automatically injects, for every collection, a\n * baseline SELECT policy granting the trusted server context and the\n * `admin` role read access (reads run under a restricted role, so RLS\n * default-denies without it). For auth collections it additionally injects\n * a self-read policy (`id = auth.uid()`) and an admin-only write gate\n * (INSERT/UPDATE/DELETE require the `admin` role or the trusted server\n * context), making privileged columns such as `roles` safe by default.\n *\n * Author-defined `securityRules` are permissive and broaden access on top\n * of these defaults. Set this flag to `true` to remove the defaults\n * entirely and take full responsibility for the collection's RLS.\n *\n * @default false\n */\n disableDefaultPolicies?: boolean;\n}\n\n/**\n * A collection backed by Firebase / Firestore.\n * Adds support for subcollections (nested document collections).\n *\n * Use this type instead of {@link CollectionConfig} when you want\n * compile-time safety that only Firestore-relevant fields appear.\n *\n * @group Models\n */\nexport interface FirebaseCollectionConfig<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User>\n extends BaseCollectionConfig<M, USER> {\n /**\n * The database engine for this collection. Must be set to `\"firestore\"`.\n */\n engine: \"firestore\";\n\n /**\n * Set of properties that compose a entity.\n * Firestore collections support `reference` properties but not `relation`.\n */\n properties: FirebaseProperties;\n\n /**\n * The Firestore collection path to query. Defaults to `slug` if not set.\n * Use this when the Firestore path differs from the slug\n * (e.g., when a PostgreSQL collection already uses the same slug).\n *\n * @example\n * ```typescript\n * const fsCustomer: FirebaseCollectionConfig = {\n * slug: \"fs_customer\", // URL: /c/fs_customer\n * path: \"customer\", // Firestore path: customer\n * name: \"Customers (Firestore)\",\n * engine: \"firestore\",\n * properties: { ... }\n * };\n * ```\n */\n path?: string;\n\n /**\n * You can add subcollections to your entity in the same way you define the root\n * collections. The collections added here will be displayed when opening\n * the side dialog of a entity.\n */\n subcollections?: () => CollectionConfig<Record<string, unknown>>[];\n}\n\n/**\n * A collection backed by MongoDB.\n *\n * Use this type instead of {@link CollectionConfig} when you want\n * compile-time safety that only MongoDB-relevant fields appear.\n *\n * @group Models\n */\nexport interface MongoDBCollectionConfig<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User>\n extends BaseCollectionConfig<M, USER> {\n\n /**\n * The database engine for this collection. Must be set to `\"mongodb\"`.\n */\n engine: \"mongodb\";\n\n /**\n * Set of properties that compose a entity.\n * MongoDB collections support `reference` properties but not `relation`.\n */\n properties: MongoProperties;\n\n /**\n * The MongoDB collection name to use. Defaults to `slug` if not set.\n * Use this when the MongoDB collection name differs from the slug\n * (e.g., when a PostgreSQL collection already uses the same slug).\n *\n * @example\n * ```typescript\n * const mongoCustomer: MongoDBCollectionConfig = {\n * slug: \"mongo_customer\", // URL: /c/mongo_customer\n * path: \"customer\", // MongoDB collection: customer\n * name: \"Customers (MongoDB)\",\n * engine: \"mongodb\",\n * properties: { ... }\n * };\n * ```\n */\n path?: string;\n}\n\n/**\n * A collection backed by any data source.\n * This is a discriminated union — use {@link PostgresCollectionConfig},\n * {@link FirebaseCollectionConfig}, or {@link MongoDBCollectionConfig} for\n * driver-specific type safety.\n *\n * @group Models\n */\nexport type CollectionConfig<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User> =\n | PostgresCollectionConfig<M, USER>\n | FirebaseCollectionConfig<M, USER>\n | MongoDBCollectionConfig<M, USER>;\n\n/**\n * A collection of *any* row type.\n *\n * `CollectionConfig` is **invariant** in `M`: `callbacks` both consumes `M`\n * (`AfterReadProps<M>`) and produces it, so neither direction of assignment\n * holds. `CollectionConfig<SomeRow>` is therefore not assignable to a bare\n * `CollectionConfig`, whose `M` defaults to `Record<string, unknown>`.\n *\n * That matters wherever a collection is merely *referred to* rather than read\n * from. `defineCollection` returns a config whose `M` is inferred from the\n * properties — the whole point of it — so a field typed `() => CollectionConfig`\n * rejects every collection the builder produces, and `target: () => otherCollection`\n * (the documented way to point a relation at its other end) does not compile in\n * any project that uses the builder.\n *\n * `any` is deliberate and is what it is for here: these positions never read the\n * target's rows, they only identify which collection is meant, so there is no\n * type safety to preserve and invariance is pure obstruction.\n *\n * @group Models\n */\nexport type AnyCollectionConfig = CollectionConfig<any, any>;\n\n/**\n * Type guard for PostgreSQL collections.\n * Returns true if the collection uses the Postgres engine (or the default engine).\n *\n * Generic over the *input* type, and narrows by intersection rather than\n * replacement. Narrowing to a bare `PostgresCollectionConfig` discarded whatever\n * the caller actually had — most visibly the admin panel's view model, whose\n * flattened presentation fields vanished the moment a collection passed through\n * one of these guards.\n *\n * @group Models\n */\nexport function isPostgresCollectionConfig<C extends CollectionConfig<any, any>>(\n collection: C\n): collection is C & PostgresCollectionConfig<any, any> {\n return !collection.engine || collection.engine === \"postgres\";\n}\n\n/**\n * Narrows to the SQL collection fields — `table`, `relations`,\n * `disableDefaultPolicies` — by asking the engine's declared capabilities\n * rather than by naming Postgres.\n *\n * The two halves of this already existed and were never joined. The engine\n * split (`PostgresCollectionConfig` / `FirebaseCollectionConfig` /\n * `MongoDBCollectionConfig`) said which fields belong to which engine at the\n * type level; {@link DataSourceCapabilities} said the same thing at runtime,\n * down to a `supportsRelations` flag. So call sites guarded on the capability\n * and then read a field the base type had to declare for them — which is why\n * those fields were on the base, and why a MongoDB collection could be written\n * with a `table`.\n *\n * Prefer this over {@link isPostgresCollectionConfig} wherever the question is\n * \"does this collection live in a SQL table\", so a custom SQL engine\n * registered through `registerDataSourceCapabilities` is included.\n *\n * @group Models\n */\nexport function isRelationalCollectionConfig<C extends CollectionConfig<any, any>>(\n collection: C\n): collection is C & PostgresCollectionConfig<any, any> {\n return getDataSourceCapabilities(collection.engine).supportsRelations;\n}\n\n/**\n * Type guard for Firebase / Firestore collections.\n * @group Models\n */\nexport function isFirebaseCollectionConfig<C extends CollectionConfig<any, any>>(\n collection: C\n): collection is C & FirebaseCollectionConfig<any, any> {\n return collection.engine === \"firestore\";\n}\n\n/**\n * Type guard for MongoDB collections.\n * @group Models\n */\nexport function isMongoDBCollectionConfig<C extends CollectionConfig<any, any>>(\n collection: C\n): collection is C & MongoDBCollectionConfig<any, any> {\n return collection.engine === \"mongodb\";\n}\n\n/**\n * Returns the data path for a collection.\n * For Firestore or MongoDB collections with a `path`, returns that value;\n * otherwise falls back to `slug`.\n */\nexport function getCollectionDataPath<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User>(\n collection: CollectionConfig<M, USER>\n): string {\n if (isFirebaseCollectionConfig(collection) && collection.path) {\n return collection.path;\n }\n if (isMongoDBCollectionConfig(collection) && collection.path) {\n return collection.path;\n }\n return collection.slug;\n}\n\n/**\n * Reads a collection's driver-declared subcollections thunk (the `subcollections`\n * field) independent of engine identity, so engine-agnostic code doesn't have to\n * type-guard against a specific driver. Returns `undefined` when the collection\n * declares none.\n *\n * Pair with `getDataSourceCapabilities(engine).supportsSubcollections` to decide\n * whether the engine honours subcollections at all before reading them.\n * @group Models\n */\nexport function getDeclaredSubcollections<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User>(\n collection: CollectionConfig<M, USER>\n): (() => CollectionConfig<Record<string, unknown>>[]) | undefined {\n return (collection as FirebaseCollectionConfig<M, USER>).subcollections;\n}\n\n/**\n * Where the rows in an {@link EntityChildView} come from.\n *\n * The two are not the same thing, and conflating them is what made a Postgres\n * relation borrow Firestore's addressing:\n *\n * - `subcollection` is **containment**. The rows live under the parent; the\n * path is their identity, and they cannot exist without it. This is what\n * Firestore has natively.\n * - `relation` is a **link**. The rows are an ordinary collection, narrowed to\n * those the parent reaches. `owned` means the child carries the parent's\n * foreign key and belongs to it alone; `linked` means the row is shared\n * through a junction, so what the parent controls is the link, not the row.\n *\n * @group Models\n */\nexport type ChildViewSource =\n | { kind: \"subcollection\" }\n | {\n kind: \"relation\";\n relationKey: string;\n mode: \"owned\" | \"linked\";\n /**\n * Slug of the collection the rows actually live in.\n *\n * Distinct from the view's `key`, which is the relation. A `linked` view\n * needs both: the key addresses the parent's set, and this addresses the\n * whole collection to pick an existing row out of.\n */\n targetSlug: string;\n };\n\n/**\n * A list of rows rendered inside an entity view — the tab under a record.\n *\n * This is a *presentation* descriptor, which is the whole point: rendering a\n * related list as a tab used to require minting a child `CollectionConfig` with\n * its own slug, which dragged a URL grammar, a path resolver and a second\n * read/write pipeline along with it. A tab needs a key, a collection to list,\n * and to know where its rows come from.\n *\n * @group Models\n */\nexport interface EntityChildView<M extends Record<string, unknown> = Record<string, unknown>> {\n /**\n * Stable identifier for this view: the tab id and the path segment.\n *\n * For a relation this is the **relation key** — the name the backend\n * resolves a nested path segment by — not the target collection's slug.\n * Those differ whenever a relation is named, which is every inline relation\n * property, and the mismatch is why such a tab used to open onto an error.\n */\n key: string;\n\n /** The collection whose rows this view lists, with any overrides applied. */\n collection: CollectionConfig<M>;\n\n source: ChildViewSource;\n}\n\n\nexport type { WhereFilterOp, FilterValues, WireFilterValues, FilterPreset } from \"./filter-operators\";\n\n\nexport type InferCollectionConfigType<S extends CollectionConfig> = S extends CollectionConfig<infer M> ? M : never;\n\n/**\n * Configuration for authentication collections.\n *\n * Controls what happens when admins create users, reset passwords,\n * and which entity actions are auto-injected.\n *\n * Use `auth: true` as sugar for `{ enabled: true }` with all defaults.\n *\n * @example Override user creation\n * ```ts\n * auth: {\n * enabled: true,\n * onCreateUser: async (values, ctx) => {\n * const hash = await ctx.hashPassword(\"welcome123\");\n * return {\n * values: { ...values, passwordHash: hash, emailVerified: true },\n * temporaryPassword: \"welcome123\",\n * };\n * },\n * }\n * ```\n *\n * @example Disable the reset-password entity action\n * ```ts\n * auth: {\n * enabled: true,\n * actions: { resetPassword: false },\n * }\n * ```\n *\n * @group Models\n */\nexport interface AuthCollectionConfig {\n /** Set to true to mark this collection as the authentication collection. */\n enabled: boolean;\n\n /**\n * Called when an admin creates a user via the collection REST API.\n *\n * Default: generate password → hash → normalize email → save →\n * send invitation email (or return temp password if no email configured).\n *\n * Override to implement custom invitation flows, LDAP sync, etc.\n */\n onCreateUser?: (\n values: Record<string, unknown>,\n ctx: AuthCollectionContext\n ) => Promise<AuthCollectionCreateResult>;\n\n /**\n * Called when an admin resets a user's password via the admin panel.\n *\n * Default: generate reset token → send email (or generate + return temp password).\n * Override for custom reset flows.\n */\n onResetPassword?: (\n uid: string,\n ctx: AuthCollectionContext\n ) => Promise<AuthCollectionResetResult>;\n\n /**\n * Control which auth-specific entity actions are auto-injected.\n *\n * Default: `{ resetPassword: true }` — the framework auto-injects\n * the built-in `resetPasswordAction` into the collection's entity actions.\n *\n * Set to `false` to disable, or pass a custom `EntityAction` to replace the UI.\n *\n * The object form is an `EntityAction` from `@rebasepro/admin-types`, typed\n * here as `object` because it is a React component with admin controllers in\n * its props and nothing on the server reads it — only whether the built-in\n * action is injected, which is the boolean.\n */\n actions?: {\n resetPassword?: boolean | object;\n };\n}\n\n/**\n * Context provided to collection-level auth hooks.\n *\n * This is a simplified facade over the server internals —\n * it exposes only what's needed for custom auth flows without\n * coupling collection config to internal interfaces.\n *\n * @group Models\n */\nexport interface AuthCollectionContext {\n /** Hash a password using the configured algorithm (scrypt by default). */\n hashPassword: (password: string) => Promise<string>;\n /** Send an email. Only available when email service is configured. */\n sendEmail?: (options: { to: string; subject: string; html: string; text?: string }) => Promise<void>;\n /** Whether the email service is configured and available. */\n emailConfigured: boolean;\n /** The app name from email config (for templates). */\n appName: string;\n /** The base URL for password reset links. */\n resetPasswordUrl: string;\n}\n\n/**\n * Result of a collection-level `onCreateUser` hook.\n * @group Models\n */\nexport interface AuthCollectionCreateResult {\n /** Processed values to persist (must include passwordHash, NOT raw password). */\n values: Record<string, unknown>;\n /** If set, shown to the admin in the creation result dialog. */\n temporaryPassword?: string;\n /** Whether an invitation email was sent. */\n invitationSent?: boolean;\n}\n\n/**\n * Result of a collection-level `onResetPassword` hook.\n * @group Models\n */\nexport interface AuthCollectionResetResult {\n /** If set, shown to the admin. */\n temporaryPassword?: string;\n /** Whether a reset email was sent. */\n invitationSent?: boolean;\n}\n","/**\n * The SQL helper functions RLS policies call, and the schema they live in.\n *\n * ## One schema, and it is ours\n *\n * Rebase creates exactly one schema in a project's database: `rebase`. These\n * three functions live in it alongside the framework's own tables, and that is\n * the whole contract — a reader can look at a database and know precisely which\n * namespace belongs to the framework and that nothing else was touched.\n *\n * It used to be two. `uid()`, `jwt()` and `roles()` sat in a schema called\n * `auth`, which is Supabase's name, chosen so that a developer who had written\n * Supabase RLS would recognise `auth.uid()`. The familiarity was real but the\n * name was not Rebase's to take, and taking it had a concrete cost: pointing\n * Rebase at a database that already had a Supabase `auth` schema meant\n * `CREATE OR REPLACE FUNCTION auth.uid() RETURNS text` against Supabase's\n * `RETURNS uuid`, which Postgres rejects outright —\n *\n * ERROR: cannot change return type of existing function\n * HINT: Use DROP FUNCTION auth.uid() first.\n *\n * — and the failure landed inside a catch-all that logged a warning and carried\n * on, leaving a database with auth tables, no helper functions, and policies\n * calling functions that did not exist. Under `rebase db migrate` the same\n * statements aborted the migration instead.\n *\n * `rebase.uid()` collides with nobody. A Supabase database keeps its `auth`\n * schema untouched and gains a `rebase` one, which is what a gradual migration\n * needs.\n *\n * ## Why functions at all, rather than inlining `current_setting`\n *\n * Because the indirection has already been spent once. `uid()` resolves\n * `app.uid` and falls back to the pre-rename `app.user_id`, so that during a\n * rolling deploy — old and new pods serving one database — both eras resolve\n * the principal. That was a single `CREATE OR REPLACE`. Inlined into policy\n * bodies it would have been a rewrite of every policy on every table.\n *\n * ## Why the name is not configurable\n *\n * A policy body is stored SQL: Postgres parses `USING (…)` once and keeps it, so\n * these strings are written into every policy in every database Rebase has\n * provisioned. Everything that reads policies back — the SQL-to-policy parser\n * behind the admin UI, the drift checker, `rls-check` — would have to know the\n * configured value to recognise its own output. One frozen name is the feature.\n */\n\n/** The schema Rebase owns. The only schema Rebase creates. */\nexport const REBASE_SCHEMA = \"rebase\";\n\n/**\n * The principal of the current request, as text, or NULL in the server context.\n *\n * Never NULL for a user request — an anonymous one carries\n * {@link ANONYMOUS_USER_ID} — which is what makes `IS NULL` a reliable test for\n * the trusted server plane and `IS NOT NULL` a tautology.\n */\nexport const RLS_UID_SQL = `${REBASE_SCHEMA}.uid()`;\n\n/** The request's roles as a comma-separated string, for `string_to_array`. */\nexport const RLS_ROLES_SQL = `${REBASE_SCHEMA}.roles()`;\n\n/** The request's JWT claims as `jsonb`, or `{}`. */\nexport const RLS_JWT_SQL = `${REBASE_SCHEMA}.jwt()`;\n\n/**\n * The pre-1.0 spellings, for recognising policies and hand-written SQL that\n * predate the move.\n *\n * Kept because policies outlive the server that wrote them: a database migrated\n * by an older release still holds `auth.uid()` in its policy bodies until the\n * next push or boot recompiles them, and anything that reads policies back has\n * to recognise both eras or report the framework's own output as foreign drift.\n * Also used to give a project whose `securityRules` contain raw `auth.uid()` a\n * message naming the replacement, instead of a parse failure.\n */\nexport const LEGACY_RLS_SCHEMA = \"auth\";\nexport const LEGACY_RLS_UID_SQL = `${LEGACY_RLS_SCHEMA}.uid()`;\nexport const LEGACY_RLS_ROLES_SQL = `${LEGACY_RLS_SCHEMA}.roles()`;\nexport const LEGACY_RLS_JWT_SQL = `${LEGACY_RLS_SCHEMA}.jwt()`;\n\n/**\n * Rewrites the pre-1.0 function calls in a fragment of policy SQL.\n *\n * Deliberately anchored on a word boundary and the schema qualifier, so a column\n * called `auth_uid` or a table named `auth` is left alone.\n */\nexport function rewriteLegacyRlsFunctions(sql: string): string {\n return sql.replace(\n /\\bauth\\.(uid|jwt|roles)\\s*\\(\\s*\\)/gi,\n (_match, fn: string) => `${REBASE_SCHEMA}.${fn.toLowerCase()}()`\n );\n}\n\n/** Whether a fragment of SQL still calls the pre-1.0 functions. */\nexport function usesLegacyRlsFunctions(sql: string): boolean {\n return /\\bauth\\.(uid|jwt|roles)\\s*\\(\\s*\\)/i.test(sql);\n}\n"],"mappings":";;;;;AA2MA,IAAa,oBAAmE;CAC5E,MAAM;CACN,OAAO;CACP,MAAM;CACN,OAAO;CACP,MAAM;CACN,OAAO;CACP,MAAM;CACN,OAAO;CACP,MAAM;CACN,OAAO;CACP,QAAQ;CACR,SAAS;CACT,SAAS;CACT,UAAU;CACV,UAAU;CACV,WAAW;AACf;;;;;AAMA,IAAa,2BAAuC,IAAI,IAAmB,CACvE,WAAW,aACf,CAAC;;;;;;;AAQD,IAAa,uBAAiD;CAC1D;CAAK;CAAM;CAAM;CAAM;CAAM;CAC7B;CAAM;CACN;CAAkB;CAClB;CAAQ;CAAS;CAAY;CAC7B;CAAW;AACf;;AAGA,IAAM,gBAAqC,IAAI,IAAmB,oBAAoB;;;;;;;;;;;AAYtF,SAAgB,cAAc,IAAuC;CACjE,IAAI,cAAc,IAAI,EAAE,GAAG,OAAO;CAClC,OAAQ,kBAAgE;AAC5E;;;;;;;;;ACzJA,IAAa,0BAA0B;;;;;;;;;;AAyFvC,IAAa,oCAAuD,CAAC,WAAW;;AAKhF,IAAa,wBAAgD;CACzD,KAAK;CACL,OAAO;CACP,mBAAmB;CACnB,wBAAwB;CACxB,aAAa;CACb,oBAAoB;CACpB,qBAAqB;CACrB,kBAAkB;CAClB,iBAAiB;CACjB,iBAAiB;CAGjB,yBAAyB;EAAC;EAAa;EAAc;EAAW;CAAQ;CACxE,kBAAkB;CAClB,uBAAuB;CACvB,qBAAqB;AACzB;;AAGA,IAAa,wBAAgD;CACzD,KAAK;CACL,OAAO;CACP,mBAAmB;CACnB,wBAAwB;CACxB,aAAa;CACb,oBAAoB;CACpB,qBAAqB;CACrB,kBAAkB;CAClB,iBAAiB;CAGjB,iBAAiB,qBAAqB,QAAO,OACzC,OAAO,UAAU,OAAO,WAAW,OAAO,cAAc,OAAO,WAAW;CAE9E,yBAAyB,CAAC;CAC1B,kBAAkB;CAClB,uBAAuB;CACvB,qBAAqB;AACzB;;AAGA,IAAa,uBAA+C;CACxD,KAAK;CACL,OAAO;CACP,mBAAmB;CACnB,wBAAwB;CACxB,aAAa;CACb,oBAAoB;CACpB,qBAAqB;CACrB,kBAAkB;CAClB,iBAAiB;CACjB,iBAAiB;CACjB,yBAAyB,CAAC;CAC1B,kBAAkB;CAClB,uBAAuB;CACvB,qBAAqB;AACzB;;;;;;AAOA,IAAa,uBAA+C;CACxD,KAAK;CACL,OAAO;CACP,mBAAmB;CACnB,wBAAwB;CACxB,aAAa;CACb,oBAAoB;CACpB,qBAAqB;CACrB,kBAAkB;CAClB,iBAAiB;CACjB,iBAAiB;CAKjB,yBAAyB;CACzB,kBAAkB;CAClB,uBAAuB;CACvB,qBAAqB;AACzB;AAEA,IAAM,wBAAgE;CAClE,UAAU;CACV,WAAW;CACX,SAAS;CACT,aAAa;AACjB;;;;;;AAOA,SAAgB,0BAA0B,QAAyC;CAC/E,IAAI,CAAC,QAAQ,OAAO;CACpB,OAAO,sBAAsB,WAAW;AAC5C;;;;;;;;;;;;;;;AC6IA,SAAgB,2BACZ,YACoD;CACpD,OAAO,CAAC,WAAW,UAAU,WAAW,WAAW;AACvD;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,6BACZ,YACoD;CACpD,OAAO,0BAA0B,WAAW,MAAM,CAAC,CAAC;AACxD;;;;;;;;;;;AAiDA,SAAgB,0BACZ,YAC+D;CAC/D,OAAQ,WAAiD;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC7dA,IAAa,gBAAgB;;;;;;;;AAS7B,IAAa,cAAc,GAAG,cAAc;;AAG5C,IAAa,gBAAgB,GAAG,cAAc;AAGnB,GAAG,cAAH;;;;;;;;;;;;AAa3B,IAAa,oBAAoB;AACC,GAAG,kBAAH;AACE,GAAG,kBAAH;AACF,GAAG,kBAAH;;;;;;;AAQlC,SAAgB,0BAA0B,KAAqB;CAC3D,OAAO,IAAI,QACP,wCACC,QAAQ,OAAe,GAAG,cAAc,GAAG,GAAG,YAAY,EAAE,GACjE;AACJ;;AAGA,SAAgB,uBAAuB,KAAsB;CACzD,OAAO,qCAAqC,KAAK,GAAG;AACxD"}
|
|
@@ -2,8 +2,8 @@ import { createRequire as __createRequire } from "module";
|
|
|
2
2
|
import process from "process";
|
|
3
3
|
__createRequire(import.meta.url);
|
|
4
4
|
import { c as __exportAll } from "./connection-BuZ97wsr.js";
|
|
5
|
-
import "./src-
|
|
6
|
-
import { t as ANONYMOUS_USER_ID } from "./policy-
|
|
5
|
+
import "./src-C_wvdMnl.js";
|
|
6
|
+
import { t as ANONYMOUS_USER_ID } from "./policy-CPkCqVTz.js";
|
|
7
7
|
import { extractUserFromToken, logger, resolveRequireAuth, safeCompare } from "@rebasepro/server";
|
|
8
8
|
import { WebSocketServer } from "ws";
|
|
9
9
|
import { inspect } from "util";
|
|
@@ -527,4 +527,4 @@ function createPostgresWebSocket(server, realtimeService, driver, authConfig, au
|
|
|
527
527
|
//#endregion
|
|
528
528
|
export { websocket_exports as n, createPostgresWebSocket as t };
|
|
529
529
|
|
|
530
|
-
//# sourceMappingURL=websocket-
|
|
530
|
+
//# sourceMappingURL=websocket-D0TBU3ia.js.map
|