@rebasepro/common 0.9.1-canary.fd3754b → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/collections/default-collections.d.ts +4 -0
- package/dist/data/buildRebaseData.d.ts +15 -2
- package/dist/index.es.js +676 -46
- package/dist/index.es.js.map +1 -1
- package/dist/util/auth-default-policies.d.ts +22 -0
- package/dist/util/identity.d.ts +83 -0
- package/dist/util/index.d.ts +3 -0
- package/dist/util/junction-policies.d.ts +108 -0
- package/dist/util/policy/evaluatePolicy.d.ts +8 -1
- package/dist/util/policy/index.d.ts +1 -0
- package/dist/util/policy/sqlToPolicy.d.ts +24 -14
- package/package.json +7 -8
- package/src/collections/default-collections.ts +2 -0
- package/src/data/buildRebaseData.ts +119 -24
- package/src/util/auth-default-policies.ts +152 -0
- package/src/util/identity.ts +166 -0
- package/src/util/index.ts +3 -0
- package/src/util/junction-policies.ts +353 -0
- package/src/util/policy/evaluatePolicy.ts +20 -4
- package/src/util/policy/index.ts +1 -0
- package/src/util/policy/policyToPostgres.ts +9 -4
- package/src/util/policy/sqlToPolicy.ts +196 -16
- package/dist/index.umd.js +0 -3328
- package/dist/index.umd.js.map +0 -1
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { CollectionConfig, SecurityRule } from "@rebasepro/types";
|
|
2
|
+
/**
|
|
3
|
+
* Returns the security rules that should be applied to a collection: the
|
|
4
|
+
* author's explicit `securityRules` plus the framework defaults described in
|
|
5
|
+
* the module doc (baseline server/admin read for all collections; self-read
|
|
6
|
+
* and the admin write gate for auth collections).
|
|
7
|
+
*
|
|
8
|
+
* Collections that opt out via `disableDefaultPolicies` are returned unchanged.
|
|
9
|
+
*/
|
|
10
|
+
export declare function getEffectiveSecurityRules(collection: CollectionConfig): SecurityRule[];
|
|
11
|
+
/**
|
|
12
|
+
* The framework defaults that {@link getEffectiveSecurityRules} would add to a
|
|
13
|
+
* collection, without the author's own rules.
|
|
14
|
+
*
|
|
15
|
+
* These policies appear in the database under names the author never wrote, and
|
|
16
|
+
* a permissive policy ORs with every other permissive policy — so someone
|
|
17
|
+
* reading their `securityRules` and then the real ACL sees more access than they
|
|
18
|
+
* declared. Dropping them by hand does nothing either: `db push` is declarative,
|
|
19
|
+
* so the next push asserts them again. Callers use this to say, in the generated
|
|
20
|
+
* DDL, which policies are injected and how to take them off.
|
|
21
|
+
*/
|
|
22
|
+
export declare function getInjectedSecurityRules(collection: CollectionConfig): SecurityRule[];
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Row identity: the address of a row, and how to derive it.
|
|
3
|
+
*
|
|
4
|
+
* Postgres has no `id`. A row is identified by its primary key — one or more
|
|
5
|
+
* columns, with any names and any types. `id` is something we synthesize on top
|
|
6
|
+
* of that: a single string token, because the admin needs *one* value it can put
|
|
7
|
+
* in a URL (`/products/1:::2`), use as a cache key, and hang a relation ref off.
|
|
8
|
+
*
|
|
9
|
+
* That token is an address, not data. It is derived from the row's columns and
|
|
10
|
+
* never stored in them — a row is exactly its columns, with their real types.
|
|
11
|
+
* Writing the address back into the row is what used to rename primary keys
|
|
12
|
+
* (`sku` → `id`) and restringify them (`42` → `"42"`) on the way out.
|
|
13
|
+
*
|
|
14
|
+
* These live in `common` because both sides need them and must agree exactly:
|
|
15
|
+
* the driver parses an incoming address back into key columns, and the admin
|
|
16
|
+
* derives the address from a row it was served.
|
|
17
|
+
*/
|
|
18
|
+
/**
|
|
19
|
+
* A primary-key column: its name, the type it round-trips as, and whether it is
|
|
20
|
+
* a UUID (which is a string despite sometimes being described as an id "number").
|
|
21
|
+
*/
|
|
22
|
+
export interface PrimaryKeyInfo {
|
|
23
|
+
fieldName: string;
|
|
24
|
+
type: "string" | "number";
|
|
25
|
+
isUUID?: boolean;
|
|
26
|
+
}
|
|
27
|
+
/** Separator between the parts of a composite address. */
|
|
28
|
+
export declare const COMPOSITE_ID_SEPARATOR = ":::";
|
|
29
|
+
/**
|
|
30
|
+
* Derive a row's address from its key columns.
|
|
31
|
+
*
|
|
32
|
+
* Single key → the value as a string. Composite → each part joined by
|
|
33
|
+
* {@link COMPOSITE_ID_SEPARATOR}, in primary-key order, which is what
|
|
34
|
+
* {@link parseIdValues} expects to invert.
|
|
35
|
+
*/
|
|
36
|
+
export declare function buildCompositeId(values: Record<string, unknown>, primaryKeys: PrimaryKeyInfo[]): string;
|
|
37
|
+
/**
|
|
38
|
+
* Invert {@link buildCompositeId}: turn an address back into key columns, each
|
|
39
|
+
* coerced to the type its column actually round-trips as.
|
|
40
|
+
*
|
|
41
|
+
* This is the boundary where a URL segment becomes a query parameter, so a
|
|
42
|
+
* malformed address must throw rather than silently produce a query that
|
|
43
|
+
* matches the wrong row (or none).
|
|
44
|
+
*/
|
|
45
|
+
export declare function parseIdValues(idValue: string | number, primaryKeys: PrimaryKeyInfo[]): Record<string, string | number>;
|
|
46
|
+
/**
|
|
47
|
+
* The primary keys of a collection, as declared by its properties.
|
|
48
|
+
*
|
|
49
|
+
* This is the only tier both sides can read, because it is the only one written
|
|
50
|
+
* in the config: the postgres driver can also infer keys from the Drizzle
|
|
51
|
+
* schema, which the browser never sees and is never sent — the admin compiles
|
|
52
|
+
* the collection files into its own bundle rather than being served them. A key
|
|
53
|
+
* that lives only in the Drizzle schema is therefore invisible here, and the
|
|
54
|
+
* server says so at boot (`warnOnKeysTheAdminCannotResolve`) naming the `isId`
|
|
55
|
+
* to add.
|
|
56
|
+
*
|
|
57
|
+
* Returns an empty array when a collection declares none, which callers must
|
|
58
|
+
* treat as "not addressable" rather than defaulting to `id`: guessing a key
|
|
59
|
+
* that is not the real one produces confidently wrong addresses.
|
|
60
|
+
*/
|
|
61
|
+
export declare function getDeclaredPrimaryKeys(collection: {
|
|
62
|
+
properties?: Record<string, unknown>;
|
|
63
|
+
}): PrimaryKeyInfo[];
|
|
64
|
+
/**
|
|
65
|
+
* The keys to address a collection's rows with, resolved the way the driver
|
|
66
|
+
* resolves them — minus the tier the browser cannot reach.
|
|
67
|
+
*
|
|
68
|
+
* The postgres driver tries, in order: properties marked `isId`; the primary
|
|
69
|
+
* keys of the Drizzle schema; and finally a column literally named `id`. Only
|
|
70
|
+
* the first and last are visible in a `CollectionConfig`, which is what both
|
|
71
|
+
* sides share.
|
|
72
|
+
*
|
|
73
|
+
* So the two agree except on a collection that declares no `isId` and whose key
|
|
74
|
+
* is known only to Drizzle. There, the driver reads the real key, and this
|
|
75
|
+
* either resolves nothing (reported to the console by the caller) or — if the
|
|
76
|
+
* table happens to have an unrelated `id` property — resolves `id`, which is
|
|
77
|
+
* the wrong key and cannot be detected from here: the addresses look right and
|
|
78
|
+
* route wrong. Only the config can settle it, so the server names both cases
|
|
79
|
+
* at boot (`warnOnKeysTheAdminCannotResolve`) with the `isId` to add.
|
|
80
|
+
*/
|
|
81
|
+
export declare function resolvePrimaryKeys(collection: {
|
|
82
|
+
properties?: Record<string, unknown>;
|
|
83
|
+
}): PrimaryKeyInfo[];
|
package/dist/util/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export * from "./collections";
|
|
2
2
|
export * from "./common";
|
|
3
3
|
export * from "./entities";
|
|
4
|
+
export * from "./identity";
|
|
4
5
|
export * from "./enums";
|
|
5
6
|
export * from "./paths";
|
|
6
7
|
export * from "./resolutions";
|
|
@@ -13,6 +14,8 @@ export * from "./builders";
|
|
|
13
14
|
export * from "./storage";
|
|
14
15
|
export * from "./callbacks";
|
|
15
16
|
export * from "./relations";
|
|
17
|
+
export * from "./auth-default-policies";
|
|
18
|
+
export * from "./junction-policies";
|
|
16
19
|
export * from "./conditions";
|
|
17
20
|
export * from "./navigation_utils";
|
|
18
21
|
export * from "./filter-operator-resolution";
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { CollectionConfig, PolicyExpression, Relation, SecurityRule } from "@rebasepro/types";
|
|
2
|
+
/**
|
|
3
|
+
* RLS derivation for many-to-many junction tables.
|
|
4
|
+
*
|
|
5
|
+
* A `through` relation makes the generator create a table nobody declared as a
|
|
6
|
+
* collection — `posts_tags`, `user_roles`. Those tables used to be the one kind
|
|
7
|
+
* of generated table with **no** RLS at all: `rebase_user` holds full DML grants,
|
|
8
|
+
* so with the endpoints locked down, any signed-up user could still read or wipe
|
|
9
|
+
* every edge between them. There is also nowhere in the config to write rules
|
|
10
|
+
* for a junction, so the author could not even fix it by hand.
|
|
11
|
+
*
|
|
12
|
+
* The architecture here is that a junction's security is *derived*, never
|
|
13
|
+
* hand-written:
|
|
14
|
+
*
|
|
15
|
+
* 1. **Locked baseline.** The same server-or-admin `default_admin` grants every
|
|
16
|
+
* collection gets, so the invariant holds again: every table the generator
|
|
17
|
+
* creates is default-deny, and rules only broaden.
|
|
18
|
+
*
|
|
19
|
+
* 2. **Reads follow the endpoints.** An edge is visible iff *both* endpoint
|
|
20
|
+
* rows are visible — two correlated `EXISTS` subqueries. The subqueries run
|
|
21
|
+
* under the caller's role, so each endpoint's own RLS filters them: junction
|
|
22
|
+
* visibility delegates to the endpoints' policies, whatever they become,
|
|
23
|
+
* with nothing duplicated. A public blog keeps rendering its tags; a private
|
|
24
|
+
* CRM's edges are exactly as hidden as its rows.
|
|
25
|
+
*
|
|
26
|
+
* 3. **Writes follow the owning side's update rules.** Linking or unlinking an
|
|
27
|
+
* edge *is* an edit of the owning row — tagging a post is editing the post —
|
|
28
|
+
* so edge writes inherit the declaring collection's explicit permissive
|
|
29
|
+
* `update` rules, each wrapped in an `EXISTS` against the owning row. Where
|
|
30
|
+
* a rule cannot be embedded faithfully (see below) it is dropped, so the
|
|
31
|
+
* failure mode is always *too locked*, never open. Explicit **restrictive**
|
|
32
|
+
* update rules are inherited as restrictive junction rules; if one of them
|
|
33
|
+
* cannot be embedded, the whole derived write grant for that side is
|
|
34
|
+
* suppressed — granting without the author's gate would be looser than the
|
|
35
|
+
* parent itself.
|
|
36
|
+
*
|
|
37
|
+
* **Embeddability.** A parent rule is embedded by moving its condition inside
|
|
38
|
+
* `EXISTS (SELECT 1 FROM parent WHERE parent.pk = junction.fk AND <condition>)`.
|
|
39
|
+
* In that scope, `field` operands bind to the parent — which is what the author
|
|
40
|
+
* meant. But `outerField` operands and `{column}` placeholders in `raw` SQL bind
|
|
41
|
+
* to the RLS row, which is now the junction, not the parent the author wrote
|
|
42
|
+
* them against. So: `raw` anywhere disqualifies a rule; a top-level `outerField`
|
|
43
|
+
* (equivalent to `field` outside a subquery) is rewritten to `field`; an
|
|
44
|
+
* `outerField` inside a nested `existsIn` cannot be re-scoped and disqualifies
|
|
45
|
+
* the rule.
|
|
46
|
+
*
|
|
47
|
+
* Injected parent defaults are never inherited — the junction's own baseline
|
|
48
|
+
* already covers the server/admin plane, and an auth collection's restrictive
|
|
49
|
+
* `require_admin_write` gate exists to protect privileged parent *columns*,
|
|
50
|
+
* which an edge write cannot touch. Inheriting it would stop users managing
|
|
51
|
+
* e.g. their own interests through a `users_interests` junction for no gain.
|
|
52
|
+
*
|
|
53
|
+
* Everything flows through the shared naming machinery, so the Studio
|
|
54
|
+
* recognises these policies as generated instead of offering to "import" them.
|
|
55
|
+
*/
|
|
56
|
+
/** One side of a junction: the collection and the FK column pointing at it. */
|
|
57
|
+
export interface JunctionEndpoint {
|
|
58
|
+
collection: CollectionConfig;
|
|
59
|
+
/** Junction column holding this endpoint's key. */
|
|
60
|
+
junctionColumn: string;
|
|
61
|
+
}
|
|
62
|
+
/** A collection that declares the `through` relation (owns the edge semantics). */
|
|
63
|
+
export interface JunctionDeclaringSide extends JunctionEndpoint {
|
|
64
|
+
relation: Relation;
|
|
65
|
+
}
|
|
66
|
+
export interface JunctionSpec {
|
|
67
|
+
/** Bare table name (schema stripped). */
|
|
68
|
+
table: string;
|
|
69
|
+
/** Schema the junction is created in — mirrors the CREATE TABLE path. */
|
|
70
|
+
schema: string;
|
|
71
|
+
/** The two endpoints, in [source, target] order of the first declaring relation. */
|
|
72
|
+
endpoints: [JunctionEndpoint, JunctionEndpoint];
|
|
73
|
+
/** Every collection that declares a relation through this table. */
|
|
74
|
+
declaringSides: JunctionDeclaringSide[];
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Walk every collection's resolved relations and aggregate the junction tables
|
|
78
|
+
* they declare. Two collections may declare the same junction from opposite
|
|
79
|
+
* sides (posts→tags and tags→posts through `posts_tags`); both become
|
|
80
|
+
* `declaringSides` of one spec, so derived write grants consider both.
|
|
81
|
+
*/
|
|
82
|
+
export declare function resolveJunctionSpecs(collections: CollectionConfig[]): Map<string, JunctionSpec>;
|
|
83
|
+
/**
|
|
84
|
+
* A synthetic CollectionConfig standing in for the junction during policy
|
|
85
|
+
* compilation and naming. Its two FK columns carry explicit `columnName`s so
|
|
86
|
+
* `outerField` operands resolve to the exact columns the CREATE TABLE emitted,
|
|
87
|
+
* whatever their casing.
|
|
88
|
+
*/
|
|
89
|
+
export declare function getJunctionCollectionConfig(spec: JunctionSpec): CollectionConfig;
|
|
90
|
+
/**
|
|
91
|
+
* Whether a parent-rule expression keeps its meaning when moved inside the
|
|
92
|
+
* junction's `EXISTS` subquery — and the re-scoped copy if it does.
|
|
93
|
+
*
|
|
94
|
+
* Returns `null` when the rule cannot be embedded faithfully: `raw` SQL
|
|
95
|
+
* anywhere (its `{column}` placeholders would bind to the junction), or an
|
|
96
|
+
* `outerField` inside a nested `existsIn` (it would bind to the junction while
|
|
97
|
+
* the author meant the parent, and no operand can express "the middle scope").
|
|
98
|
+
* Top-level `outerField`s are rewritten to `field`, which is what they meant.
|
|
99
|
+
*/
|
|
100
|
+
export declare function embedParentExpression(expr: PolicyExpression, depth?: number): PolicyExpression | null;
|
|
101
|
+
/**
|
|
102
|
+
* The full derived policy set for a junction table: the locked server/admin
|
|
103
|
+
* baseline, the endpoint-visibility read grant, inherited write grants, and
|
|
104
|
+
* inherited restrictive gates. Returns `[]` when every declaring collection set
|
|
105
|
+
* `disableDefaultPolicies` — the junction is then the author's to police, and
|
|
106
|
+
* stays locked (RLS is still enabled) until they write policies for it.
|
|
107
|
+
*/
|
|
108
|
+
export declare function getJunctionSecurityRules(spec: JunctionSpec): SecurityRule[];
|
|
@@ -13,7 +13,14 @@ export type TriState = boolean | "unknown";
|
|
|
13
13
|
* being evaluated (or none, for collection-level gating).
|
|
14
14
|
*/
|
|
15
15
|
export interface PolicyEvalContext {
|
|
16
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* The current user's id, or null/undefined when no user is signed in.
|
|
18
|
+
*
|
|
19
|
+
* Null here means *anonymous visitor*, not "server context" — a client is
|
|
20
|
+
* never the server context. `authUid` operands therefore resolve to
|
|
21
|
+
* {@link ANONYMOUS_USER_ID} rather than `null`, matching the `auth.uid()`
|
|
22
|
+
* the database would see for the same request.
|
|
23
|
+
*/
|
|
17
24
|
uid?: string | null;
|
|
18
25
|
/** The current user's application roles. */
|
|
19
26
|
roles?: string[];
|
|
@@ -1,20 +1,30 @@
|
|
|
1
1
|
import { PolicyExpression } from "@rebasepro/types";
|
|
2
|
+
export declare function sqlToPolicy(sql: string): PolicyExpression;
|
|
3
|
+
/** A clause that reads as a lockdown but admits anonymous callers. */
|
|
4
|
+
export interface AnonymousGrantRisk {
|
|
5
|
+
/** Which spelling was found. */
|
|
6
|
+
pattern: "foreign-uid-literal" | "uid-not-null";
|
|
7
|
+
/** The offending fragment — the literal, or the SQL that is a tautology. */
|
|
8
|
+
detail: string;
|
|
9
|
+
/** Why it admits anonymous callers, and what to write instead. */
|
|
10
|
+
explanation: string;
|
|
11
|
+
}
|
|
2
12
|
/**
|
|
3
|
-
*
|
|
13
|
+
* Find clauses that read as "signed-in users only" but admit anonymous callers.
|
|
14
|
+
*
|
|
15
|
+
* Both spellings come from the same place — Supabase, where `auth.uid()` really
|
|
16
|
+
* is NULL for an anonymous request. Rebase substitutes
|
|
17
|
+
* {@link ANONYMOUS_USER_ID} instead (a blank id would read back as NULL, which
|
|
18
|
+
* is how the trusted *server* context is recognised), so:
|
|
4
19
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* optimistic client-side UI decision.
|
|
20
|
+
* - `auth.uid() IS NOT NULL` is a tautology on the user path, and
|
|
21
|
+
* - `auth.uid() != 'anon'` compares against a string no caller ever has.
|
|
8
22
|
*
|
|
9
|
-
*
|
|
10
|
-
* -
|
|
11
|
-
*
|
|
12
|
-
* - `field = current_setting('app.user_id')`
|
|
13
|
-
* - `A AND B`
|
|
14
|
-
* - `true`
|
|
15
|
-
* - `IN (...)` (as optimistic true)
|
|
23
|
+
* Either one turns a lockdown into a full grant, and neither looks wrong. No
|
|
24
|
+
* real user id is ever one of these literals, and a user-context request is
|
|
25
|
+
* never NULL, so a match is always a mistake rather than a deliberate check.
|
|
16
26
|
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
27
|
+
* Structured expressions are checked too, not just parsed SQL: `policy.compare`
|
|
28
|
+
* can spell the same mistake.
|
|
19
29
|
*/
|
|
20
|
-
export declare function
|
|
30
|
+
export declare function findAnonymousGrants(expr: PolicyExpression): AnonymousGrantRisk[];
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rebasepro/common",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.10.0",
|
|
5
5
|
"description": "Awesome Firebase/Firestore-based headless open-source CMS",
|
|
6
6
|
"funding": {
|
|
7
7
|
"url": "https://github.com/sponsors/rebaseco"
|
|
@@ -13,12 +13,12 @@
|
|
|
13
13
|
"url": "https://github.com/rebasepro/rebase.git",
|
|
14
14
|
"directory": "packages/common"
|
|
15
15
|
},
|
|
16
|
-
"main": "./dist/index.
|
|
16
|
+
"main": "./dist/index.es.js",
|
|
17
17
|
"module": "./dist/index.es.js",
|
|
18
18
|
"types": "./dist/index.d.ts",
|
|
19
19
|
"source": "src/index.ts",
|
|
20
20
|
"engines": {
|
|
21
|
-
"node": ">=
|
|
21
|
+
"node": ">=20"
|
|
22
22
|
},
|
|
23
23
|
"keywords": [
|
|
24
24
|
"rebase",
|
|
@@ -33,16 +33,15 @@
|
|
|
33
33
|
".": {
|
|
34
34
|
"types": "./dist/index.d.ts",
|
|
35
35
|
"development": "./dist/index.es.js",
|
|
36
|
-
"import": "./dist/index.es.js"
|
|
37
|
-
"require": "./dist/index.umd.js"
|
|
36
|
+
"import": "./dist/index.es.js"
|
|
38
37
|
},
|
|
39
38
|
"./package.json": "./package.json"
|
|
40
39
|
},
|
|
41
40
|
"dependencies": {
|
|
42
41
|
"fast-equals": "6.0.0",
|
|
43
42
|
"json-logic-js": "^2.0.5",
|
|
44
|
-
"@rebasepro/types": "0.
|
|
45
|
-
"@rebasepro/utils": "0.
|
|
43
|
+
"@rebasepro/types": "0.10.0",
|
|
44
|
+
"@rebasepro/utils": "0.10.0"
|
|
46
45
|
},
|
|
47
46
|
"devDependencies": {
|
|
48
47
|
"@jest/globals": "^30.4.1",
|
|
@@ -100,7 +99,7 @@
|
|
|
100
99
|
},
|
|
101
100
|
"scripts": {
|
|
102
101
|
"watch": "vite build --watch",
|
|
103
|
-
"build": "vite build && tsc --emitDeclarationOnly -p tsconfig.prod.json",
|
|
102
|
+
"build": "vite build && tsc --emitDeclarationOnly -p tsconfig.prod.json && node ../../scripts/assert-build-output.mjs",
|
|
104
103
|
"test:lint": "eslint \"src/**\" --quiet",
|
|
105
104
|
"test": "jest --passWithNoTests",
|
|
106
105
|
"clean": "rm -rf dist && find ./src -name '*.js' -type f | xargs rm -f",
|
|
@@ -68,6 +68,7 @@ unique: true }
|
|
|
68
68
|
name: "Password Hash",
|
|
69
69
|
type: "string",
|
|
70
70
|
columnName: "password_hash",
|
|
71
|
+
excludeFromApi: true,
|
|
71
72
|
ui: { hideFromCollection: true,
|
|
72
73
|
disabled: { hidden: true } }
|
|
73
74
|
},
|
|
@@ -83,6 +84,7 @@ disabled: { hidden: true } }
|
|
|
83
84
|
name: "Email Verification Token",
|
|
84
85
|
type: "string",
|
|
85
86
|
columnName: "email_verification_token",
|
|
87
|
+
excludeFromApi: true,
|
|
86
88
|
ui: { hideFromCollection: true,
|
|
87
89
|
disabled: { hidden: true } }
|
|
88
90
|
},
|
|
@@ -17,14 +17,79 @@ import {
|
|
|
17
17
|
import { toSnakeCase } from "@rebasepro/utils";
|
|
18
18
|
import { QueryBuilder } from "./query_builder";
|
|
19
19
|
import { deserializeFilter } from "./filter-dialect";
|
|
20
|
+
import { buildCompositeId, resolvePrimaryKeys, PrimaryKeyInfo } from "../util/identity";
|
|
21
|
+
|
|
22
|
+
export interface EntityDataOptions {
|
|
23
|
+
/**
|
|
24
|
+
* Look up a collection's config by slug, to derive row addresses from its
|
|
25
|
+
* primary keys.
|
|
26
|
+
*
|
|
27
|
+
* Called lazily rather than up front: the data layer is created by `Rebase`,
|
|
28
|
+
* which sits *above* the admin that owns the collections, so a resolver
|
|
29
|
+
* registered on mount would otherwise arrive too late to be seen.
|
|
30
|
+
*/
|
|
31
|
+
resolveCollection?: (slug: string) => { properties?: Record<string, unknown> } | undefined;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function createPrimaryKeyResolver(options?: EntityDataOptions) {
|
|
35
|
+
const cache = new Map<string, PrimaryKeyInfo[]>();
|
|
36
|
+
const warned = new Set<string>();
|
|
37
|
+
|
|
38
|
+
return function primaryKeysFor(slug: string): PrimaryKeyInfo[] {
|
|
39
|
+
const cached = cache.get(slug);
|
|
40
|
+
if (cached) return cached;
|
|
41
|
+
|
|
42
|
+
const collection = options?.resolveCollection?.(slug);
|
|
43
|
+
if (!collection) {
|
|
44
|
+
// The registry may not have been registered yet. Don't memoize a
|
|
45
|
+
// miss, or the collection would stay address-less for this session.
|
|
46
|
+
return [];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const keys = resolvePrimaryKeys(collection);
|
|
50
|
+
if (keys.length > 0) {
|
|
51
|
+
// Memoized for the session: a collection's key does not change
|
|
52
|
+
// while the app runs, and this is called once per row. Editing
|
|
53
|
+
// `isId` in the schema editor needs a reload to take effect here.
|
|
54
|
+
cache.set(slug, keys);
|
|
55
|
+
return keys;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (!warned.has(slug)) {
|
|
59
|
+
warned.add(slug);
|
|
60
|
+
// Silence here surfaces much later as rows that cannot be opened,
|
|
61
|
+
// linked, or saved, with nothing pointing back at the cause.
|
|
62
|
+
console.warn(
|
|
63
|
+
`[rebase] Collection '${slug}' declares no primary key, so its rows have no address: ` +
|
|
64
|
+
`detail links, caching and relations will not work for it. ` +
|
|
65
|
+
`Mark the key property with \`isId\` in its collection config — the server logs which ` +
|
|
66
|
+
`column to mark at boot, if its schema knows the key.`
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
return keys;
|
|
70
|
+
};
|
|
71
|
+
}
|
|
20
72
|
|
|
21
73
|
/**
|
|
22
|
-
*
|
|
23
|
-
*
|
|
74
|
+
* Give a flat row the Entity view-model the admin renders.
|
|
75
|
+
*
|
|
76
|
+
* The address is *derived here* — it is not a column, and the row it came from
|
|
77
|
+
* does not contain one. Rows carry exactly what the table has, with the types
|
|
78
|
+
* Postgres returned; the id is this layer's invention, and this is the only
|
|
79
|
+
* place it is minted.
|
|
80
|
+
*
|
|
81
|
+
* `primaryKeys` empty falls back to a literal `id` on the row: drivers other
|
|
82
|
+
* than postgres still serve rows with one, and this keeps them working.
|
|
24
83
|
*/
|
|
25
|
-
function rowToEntity<M extends Record<string, unknown>>(
|
|
84
|
+
function rowToEntity<M extends Record<string, unknown>>(
|
|
85
|
+
row: Record<string, unknown>,
|
|
86
|
+
slug: string,
|
|
87
|
+
primaryKeys: PrimaryKeyInfo[] = []
|
|
88
|
+
): Entity<M> {
|
|
26
89
|
return {
|
|
27
|
-
id:
|
|
90
|
+
id: primaryKeys.length > 0
|
|
91
|
+
? buildCompositeId(row, primaryKeys)
|
|
92
|
+
: row.id as string | number,
|
|
28
93
|
path: slug,
|
|
29
94
|
values: row as EntityValues<M>
|
|
30
95
|
};
|
|
@@ -32,7 +97,8 @@ function rowToEntity<M extends Record<string, unknown>>(row: Record<string, unkn
|
|
|
32
97
|
|
|
33
98
|
function createDriverAccessor<M extends Record<string, unknown> = Record<string, unknown>>(
|
|
34
99
|
driver: DataDriver,
|
|
35
|
-
slug: string
|
|
100
|
+
slug: string,
|
|
101
|
+
getPks: () => PrimaryKeyInfo[] = () => []
|
|
36
102
|
): CollectionAccessor<M> {
|
|
37
103
|
const accessor: CollectionAccessor<M> = {
|
|
38
104
|
async find(params?: FindParams): Promise<FindResponse<M>> {
|
|
@@ -75,14 +141,14 @@ function createDriverAccessor<M extends Record<string, unknown> = Record<string,
|
|
|
75
141
|
}
|
|
76
142
|
|
|
77
143
|
return {
|
|
78
|
-
data: rows.map((row: Record<string, unknown>) => rowToEntity<M>(row, slug)),
|
|
144
|
+
data: rows.map((row: Record<string, unknown>) => rowToEntity<M>(row, slug, getPks())),
|
|
79
145
|
meta: { total, limit, offset, hasMore }
|
|
80
146
|
};
|
|
81
147
|
},
|
|
82
148
|
|
|
83
149
|
async findById(id: string | number): Promise<Entity<M> | undefined> {
|
|
84
150
|
const row = await driver.fetchOne<M>({ path: slug, id: id });
|
|
85
|
-
return row ? rowToEntity<M>(row, slug) : undefined;
|
|
151
|
+
return row ? rowToEntity<M>(row, slug, getPks()) : undefined;
|
|
86
152
|
},
|
|
87
153
|
|
|
88
154
|
async create(data: Partial<EntityValues<M>>, id?: string | number): Promise<Entity<M>> {
|
|
@@ -92,9 +158,20 @@ function createDriverAccessor<M extends Record<string, unknown> = Record<string,
|
|
|
92
158
|
id: id,
|
|
93
159
|
status: "new"
|
|
94
160
|
});
|
|
95
|
-
return rowToEntity<M>(row, slug);
|
|
161
|
+
return rowToEntity<M>(row, slug, getPks());
|
|
96
162
|
},
|
|
97
163
|
|
|
164
|
+
createMany: driver.saveMany
|
|
165
|
+
? async (data: Partial<EntityValues<M>>[], options?: { upsert?: boolean }): Promise<Entity<M>[]> => {
|
|
166
|
+
const rows = await driver.saveMany!<M>({
|
|
167
|
+
path: slug,
|
|
168
|
+
rows: data,
|
|
169
|
+
upsert: options?.upsert
|
|
170
|
+
});
|
|
171
|
+
return rows.map((row) => rowToEntity<M>(row, slug, getPks()));
|
|
172
|
+
}
|
|
173
|
+
: undefined,
|
|
174
|
+
|
|
98
175
|
async update(id: string | number, data: Partial<EntityValues<M>>): Promise<Entity<M>> {
|
|
99
176
|
const row = await driver.save<M>({
|
|
100
177
|
path: slug,
|
|
@@ -102,7 +179,7 @@ function createDriverAccessor<M extends Record<string, unknown> = Record<string,
|
|
|
102
179
|
id: id,
|
|
103
180
|
status: "existing"
|
|
104
181
|
});
|
|
105
|
-
return rowToEntity<M>(row, slug);
|
|
182
|
+
return rowToEntity<M>(row, slug, getPks());
|
|
106
183
|
},
|
|
107
184
|
|
|
108
185
|
async delete(id: string | number): Promise<void> {
|
|
@@ -137,7 +214,7 @@ values: {} as Record<string, unknown> }
|
|
|
137
214
|
searchString: params?.searchString,
|
|
138
215
|
onUpdate: (entities) => {
|
|
139
216
|
onUpdate({
|
|
140
|
-
data: entities.map((row: Record<string, unknown>) => rowToEntity<M>(row, slug)),
|
|
217
|
+
data: entities.map((row: Record<string, unknown>) => rowToEntity<M>(row, slug, getPks())),
|
|
141
218
|
meta: {
|
|
142
219
|
total: entities.length,
|
|
143
220
|
limit,
|
|
@@ -155,7 +232,7 @@ values: {} as Record<string, unknown> }
|
|
|
155
232
|
return driver.listenOne!<M>({
|
|
156
233
|
path: slug,
|
|
157
234
|
id: id,
|
|
158
|
-
onUpdate: (entity) => onUpdate(entity ? rowToEntity<M>(entity, slug) : undefined),
|
|
235
|
+
onUpdate: (entity) => onUpdate(entity ? rowToEntity<M>(entity, slug, getPks()) : undefined),
|
|
159
236
|
onError
|
|
160
237
|
});
|
|
161
238
|
} : undefined,
|
|
@@ -200,13 +277,14 @@ values: {} as Record<string, unknown> }
|
|
|
200
277
|
* await data.products.create({ name: "Camera", price: 299 });
|
|
201
278
|
* const { data: items } = await data.products.find({ where: { status: ["==", "published"] } });
|
|
202
279
|
*/
|
|
203
|
-
export function buildRebaseData(driver: DataDriver): RebaseData {
|
|
280
|
+
export function buildRebaseData(driver: DataDriver, options?: EntityDataOptions): RebaseData {
|
|
204
281
|
const cache = new Map<string, CollectionAccessor>();
|
|
282
|
+
const primaryKeysFor = createPrimaryKeyResolver(options);
|
|
205
283
|
|
|
206
284
|
function getAccessor(slug: string): CollectionAccessor {
|
|
207
285
|
let accessor = cache.get(slug);
|
|
208
286
|
if (!accessor) {
|
|
209
|
-
accessor = createDriverAccessor(driver, slug);
|
|
287
|
+
accessor = createDriverAccessor(driver, slug, () => primaryKeysFor(slug));
|
|
210
288
|
cache.set(slug, accessor);
|
|
211
289
|
}
|
|
212
290
|
return accessor;
|
|
@@ -236,8 +314,9 @@ export function buildRebaseData(driver: DataDriver): RebaseData {
|
|
|
236
314
|
// =============================================================================
|
|
237
315
|
|
|
238
316
|
/**
|
|
239
|
-
* Unwrap a Entity into
|
|
240
|
-
*
|
|
317
|
+
* Unwrap a Entity back into the flat row it was built from. `rowToEntity` keeps
|
|
318
|
+
* the row untouched under `.values` and derives `.id` alongside it, so dropping
|
|
319
|
+
* the wrapper is the whole operation — the address was never part of the row.
|
|
241
320
|
*/
|
|
242
321
|
function entityToRow<M extends Record<string, unknown>>(entity: Entity<M>): M {
|
|
243
322
|
return entity.values as unknown as M;
|
|
@@ -326,6 +405,20 @@ function toSdkCollectionClient<M extends Record<string, unknown>>(
|
|
|
326
405
|
async create(data: Partial<M>, id?: string | number): Promise<M> {
|
|
327
406
|
return entityToRow(await snap.create(data as Partial<EntityValues<M>>, id));
|
|
328
407
|
},
|
|
408
|
+
async createMany(data: Partial<M>[], options?: { upsert?: boolean }): Promise<M[]> {
|
|
409
|
+
if (!Array.isArray(data)) {
|
|
410
|
+
throw new TypeError("createMany expects an array of records.");
|
|
411
|
+
}
|
|
412
|
+
if (data.length === 0) return [];
|
|
413
|
+
if (!snap.createMany) {
|
|
414
|
+
throw new Error(
|
|
415
|
+
"Bulk writes are not supported by this collection's data source. " +
|
|
416
|
+
"Fall back to create() per record."
|
|
417
|
+
);
|
|
418
|
+
}
|
|
419
|
+
const rows = await snap.createMany(data as Partial<EntityValues<M>>[], options);
|
|
420
|
+
return rows.map(entityToRow);
|
|
421
|
+
},
|
|
329
422
|
async update(id: string | number, data: Partial<M>): Promise<M> {
|
|
330
423
|
return entityToRow(await snap.update(id, data as Partial<EntityValues<M>>));
|
|
331
424
|
},
|
|
@@ -364,24 +457,25 @@ function toSdkCollectionClient<M extends Record<string, unknown>>(
|
|
|
364
457
|
*/
|
|
365
458
|
function toEntityAccessor<M extends Record<string, unknown>>(
|
|
366
459
|
sdk: SDKCollectionClient<M>,
|
|
367
|
-
slug: string
|
|
460
|
+
slug: string,
|
|
461
|
+
getPks: () => PrimaryKeyInfo[] = () => []
|
|
368
462
|
): CollectionAccessor<M> {
|
|
369
463
|
const accessor: CollectionAccessor<M> = {
|
|
370
464
|
async find(params?: FindParams): Promise<FindResponse<M>> {
|
|
371
465
|
const res = await sdk.find(params);
|
|
372
|
-
return { data: res.data.map((row) => rowToEntity<M>(row, slug)), meta: res.meta };
|
|
466
|
+
return { data: res.data.map((row) => rowToEntity<M>(row, slug, getPks())), meta: res.meta };
|
|
373
467
|
},
|
|
374
468
|
async findById(id: string | number): Promise<Entity<M> | undefined> {
|
|
375
469
|
const row = await sdk.findById(id);
|
|
376
|
-
return row ? rowToEntity<M>(row, slug) : undefined;
|
|
470
|
+
return row ? rowToEntity<M>(row, slug, getPks()) : undefined;
|
|
377
471
|
},
|
|
378
472
|
async create(data: Partial<EntityValues<M>>, id?: string | number): Promise<Entity<M>> {
|
|
379
|
-
return rowToEntity<M>(await sdk.create(data as Partial<M>, id), slug);
|
|
473
|
+
return rowToEntity<M>(await sdk.create(data as Partial<M>, id), slug, getPks());
|
|
380
474
|
},
|
|
381
475
|
async update(id: string | number, data: Partial<EntityValues<M>>): Promise<Entity<M>> {
|
|
382
476
|
const row = await sdk.update(id, data as Partial<M>);
|
|
383
477
|
if (!row) throw new Error(`Update returned no data for id ${id}`);
|
|
384
|
-
return rowToEntity<M>(row, slug);
|
|
478
|
+
return rowToEntity<M>(row, slug, getPks());
|
|
385
479
|
},
|
|
386
480
|
delete(id: string | number): Promise<void> {
|
|
387
481
|
return sdk.delete(id);
|
|
@@ -389,11 +483,11 @@ function toEntityAccessor<M extends Record<string, unknown>>(
|
|
|
389
483
|
count: sdk.count ? (params?: FindParams) => sdk.count!(params) : undefined,
|
|
390
484
|
listen: sdk.listen
|
|
391
485
|
? (params: FindParams | undefined, onUpdate: (r: FindResponse<M>) => void, onError?: (e: Error) => void) =>
|
|
392
|
-
sdk.listen!(params, (res) => onUpdate({ data: res.data.map((row) => rowToEntity<M>(row, slug)), meta: res.meta }), onError)
|
|
486
|
+
sdk.listen!(params, (res) => onUpdate({ data: res.data.map((row) => rowToEntity<M>(row, slug, getPks())), meta: res.meta }), onError)
|
|
393
487
|
: undefined,
|
|
394
488
|
listenById: sdk.listenById
|
|
395
489
|
? (id: string | number, onUpdate: (s: Entity<M> | undefined) => void, onError?: (e: Error) => void) =>
|
|
396
|
-
sdk.listenById!(id, (row) => onUpdate(row ? rowToEntity<M>(row, slug) : undefined), onError)
|
|
490
|
+
sdk.listenById!(id, (row) => onUpdate(row ? rowToEntity<M>(row, slug, getPks()) : undefined), onError)
|
|
397
491
|
: undefined,
|
|
398
492
|
where(columnOrCondition: string | LogicalCondition, operator?: WhereFilterOp, value?: unknown) {
|
|
399
493
|
const builder = new QueryBuilder<M>(accessor);
|
|
@@ -420,13 +514,14 @@ function toEntityAccessor<M extends Record<string, unknown>>(
|
|
|
420
514
|
* CMS `RebaseDataContext` — without it the admin renders rows with only their
|
|
421
515
|
* `id`.
|
|
422
516
|
*/
|
|
423
|
-
export function wrapAsEntityData(sdkData: RebaseSdkData): RebaseData {
|
|
517
|
+
export function wrapAsEntityData(sdkData: RebaseSdkData, options?: EntityDataOptions): RebaseData {
|
|
424
518
|
const cache = new Map<string, CollectionAccessor>();
|
|
519
|
+
const primaryKeysFor = createPrimaryKeyResolver(options);
|
|
425
520
|
|
|
426
521
|
function getAccessor(slug: string): CollectionAccessor {
|
|
427
522
|
let accessor = cache.get(slug);
|
|
428
523
|
if (!accessor) {
|
|
429
|
-
accessor = toEntityAccessor(sdkData.collection(slug), slug);
|
|
524
|
+
accessor = toEntityAccessor(sdkData.collection(slug), slug, () => primaryKeysFor(slug));
|
|
430
525
|
cache.set(slug, accessor);
|
|
431
526
|
}
|
|
432
527
|
return accessor;
|