@rebasepro/common 0.8.0 → 0.9.1-canary.09aaf62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +5 -5
  2. package/dist/collections/CollectionRegistry.d.ts +16 -16
  3. package/dist/collections/default-collections.d.ts +5 -1
  4. package/dist/data/buildRebaseData.d.ts +44 -3
  5. package/dist/data/buildRoutedRebaseData.d.ts +14 -9
  6. package/dist/data/filter-dialect.d.ts +18 -4
  7. package/dist/data/query_builder.d.ts +1 -1
  8. package/dist/data/resolveDataSource.d.ts +1 -1
  9. package/dist/data/sort-dialect.d.ts +41 -0
  10. package/dist/index.d.ts +1 -0
  11. package/dist/index.es.js +1236 -179
  12. package/dist/index.es.js.map +1 -1
  13. package/dist/util/auth-default-policies.d.ts +22 -0
  14. package/dist/util/builders.d.ts +19 -56
  15. package/dist/util/callbacks.d.ts +3 -3
  16. package/dist/util/collections.d.ts +4 -4
  17. package/dist/util/entities.d.ts +2 -2
  18. package/dist/util/filter-operator-resolution.d.ts +32 -0
  19. package/dist/util/identity.d.ts +83 -0
  20. package/dist/util/index.d.ts +4 -0
  21. package/dist/util/junction-policies.d.ts +108 -0
  22. package/dist/util/navigation_from_path.d.ts +4 -4
  23. package/dist/util/navigation_utils.d.ts +3 -3
  24. package/dist/util/parent_references_from_path.d.ts +2 -2
  25. package/dist/util/permissions.d.ts +6 -6
  26. package/dist/util/policy/evaluatePolicy.d.ts +8 -1
  27. package/dist/util/policy/index.d.ts +1 -0
  28. package/dist/util/policy/policyToPostgres.d.ts +14 -2
  29. package/dist/util/policy/sqlToPolicy.d.ts +24 -14
  30. package/dist/util/references.d.ts +2 -2
  31. package/dist/util/relations.d.ts +5 -5
  32. package/dist/util/resolutions.d.ts +2 -2
  33. package/package.json +7 -8
  34. package/src/collections/CollectionRegistry.ts +36 -36
  35. package/src/collections/default-collections.ts +2 -0
  36. package/src/data/buildRebaseData.ts +430 -60
  37. package/src/data/buildRoutedRebaseData.ts +22 -16
  38. package/src/data/filter-dialect.ts +151 -60
  39. package/src/data/query_builder.ts +11 -2
  40. package/src/data/resolveDataSource.ts +1 -1
  41. package/src/data/sort-dialect.ts +56 -0
  42. package/src/index.ts +1 -0
  43. package/src/util/auth-default-policies.ts +152 -0
  44. package/src/util/builders.ts +25 -99
  45. package/src/util/callbacks.ts +8 -8
  46. package/src/util/collections.ts +4 -4
  47. package/src/util/entities.ts +4 -4
  48. package/src/util/filter-operator-resolution.ts +81 -0
  49. package/src/util/identity.ts +166 -0
  50. package/src/util/index.ts +4 -0
  51. package/src/util/junction-policies.ts +353 -0
  52. package/src/util/navigation_from_path.ts +4 -4
  53. package/src/util/navigation_utils.ts +8 -8
  54. package/src/util/parent_references_from_path.ts +3 -3
  55. package/src/util/permissions.test.ts +2 -2
  56. package/src/util/permissions.ts +7 -7
  57. package/src/util/policy/evaluatePolicy.ts +26 -4
  58. package/src/util/policy/index.ts +1 -0
  59. package/src/util/policy/policyToPostgres.ts +123 -17
  60. package/src/util/policy/sqlToPolicy.ts +190 -13
  61. package/src/util/references.ts +2 -2
  62. package/src/util/relations.ts +12 -12
  63. package/src/util/resolutions.ts +5 -5
  64. package/dist/index.umd.js +0 -2901
  65. 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[];
@@ -1,11 +1,14 @@
1
- import { AdditionalFieldDelegate, ArrayProperty, BooleanProperty, DateProperty, EntityCallbacks, EntityCollection, EnumValueConfig, EnumValues, FirebaseCollection, FirebaseProperties, GeopointProperty, InferEntityType, MapProperty, MongoDBCollection, MongoProperties, NumberProperty, PostgresCollection, PostgresProperties, Properties, Property, ReferenceProperty, StringProperty, User } from "@rebasepro/types";
1
+ import { ArrayProperty, BooleanProperty, DateProperty, CollectionConfig, FirebaseCollectionConfig, FirebaseProperties, GeopointProperty, InferEntityType, MapProperty, MongoDBCollectionConfig, MongoProperties, NumberProperty, PostgresCollectionConfig, PostgresProperties, Property, ReferenceProperty, StringProperty, User } from "@rebasepro/types";
2
2
  /**
3
- * Identity function we use to defeat the type system of Typescript and build
4
- * collection views with all its properties
5
- * @param collection
3
+ * @deprecated Use {@link defineCollection} instead — it infers property
4
+ * types automatically (autocomplete on `titleProperty`, `sort`,
5
+ * `propertiesOrder`, callbacks) without manual generics.
6
+ * `buildCollection` is kept for FireCMS migration compatibility and will
7
+ * be removed before 1.0.
8
+ *
6
9
  * @group Builder
7
10
  */
8
- export declare function buildCollection<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User>(collection: EntityCollection<M, USER>): EntityCollection<M, USER>;
11
+ export declare function buildCollection<M extends Record<string, unknown> = Record<string, unknown>, USER extends User = User>(collection: CollectionConfig<M, USER>): CollectionConfig<M, USER>;
9
12
  /**
10
13
  * Define a PostgreSQL-backed collection with full type inference.
11
14
  *
@@ -30,75 +33,35 @@ export declare function buildCollection<M extends Record<string, unknown> = Reco
30
33
  *
31
34
  * @group Builder
32
35
  */
33
- export declare function defineCollection<const P extends PostgresProperties, USER extends User = User>(collection: Omit<PostgresCollection<InferEntityType<P>, USER>, "properties"> & {
36
+ export declare function defineCollection<const P extends PostgresProperties, USER extends User = User>(collection: Omit<PostgresCollectionConfig<InferEntityType<P>, USER>, "properties"> & {
34
37
  properties: P;
35
- }): PostgresCollection<InferEntityType<P>, USER> & {
38
+ }): PostgresCollectionConfig<InferEntityType<P>, USER> & {
36
39
  properties: P;
37
40
  };
38
41
  /**
39
42
  * Define a Firestore-backed collection with full type inference.
40
43
  * @group Builder
41
44
  */
42
- export declare function defineCollection<const P extends FirebaseProperties, USER extends User = User>(collection: Omit<FirebaseCollection<InferEntityType<P>, USER>, "properties"> & {
45
+ export declare function defineCollection<const P extends FirebaseProperties, USER extends User = User>(collection: Omit<FirebaseCollectionConfig<InferEntityType<P>, USER>, "properties"> & {
43
46
  properties: P;
44
- }): FirebaseCollection<InferEntityType<P>, USER> & {
47
+ }): FirebaseCollectionConfig<InferEntityType<P>, USER> & {
45
48
  properties: P;
46
49
  };
47
50
  /**
48
51
  * Define a MongoDB-backed collection with full type inference.
49
52
  * @group Builder
50
53
  */
51
- export declare function defineCollection<const P extends MongoProperties, USER extends User = User>(collection: Omit<MongoDBCollection<InferEntityType<P>, USER>, "properties"> & {
54
+ export declare function defineCollection<const P extends MongoProperties, USER extends User = User>(collection: Omit<MongoDBCollectionConfig<InferEntityType<P>, USER>, "properties"> & {
52
55
  properties: P;
53
- }): MongoDBCollection<InferEntityType<P>, USER> & {
56
+ }): MongoDBCollectionConfig<InferEntityType<P>, USER> & {
54
57
  properties: P;
55
58
  };
56
59
  /**
57
- * Identity function we use to defeat the type system of Typescript and preserve
58
- * the property keys.
59
- * @param property
60
+ * @deprecated Use plain typed property objects with {@link defineCollection}
61
+ * instead — `defineCollection` infers property types automatically, making
62
+ * this wrapper unnecessary. `buildProperty` is kept for FireCMS migration
63
+ * compatibility and will be removed before 1.0.
64
+ *
60
65
  * @group Builder
61
66
  */
62
67
  export declare function buildProperty<T, P extends Property = Property>(property: P): P extends StringProperty ? StringProperty : P extends NumberProperty ? NumberProperty : P extends BooleanProperty ? BooleanProperty : P extends DateProperty ? DateProperty : P extends GeopointProperty ? GeopointProperty : P extends ReferenceProperty ? ReferenceProperty : P extends ArrayProperty ? ArrayProperty : P extends MapProperty ? MapProperty : never;
63
- /**
64
- * Identity function we use to defeat the type system of Typescript and preserve
65
- * the properties keys.
66
- * @param properties
67
- * @group Builder
68
- */
69
- export declare function buildProperties<M extends Record<string, unknown>>(properties: Properties): Properties;
70
- /**
71
- * Identity function we use to defeat the type system of Typescript and preserve
72
- * the properties keys.
73
- * @param propertiesOrBuilder
74
- * @group Builder
75
- */
76
- export declare function buildPropertiesOrBuilder<M extends Record<string, unknown>>(propertiesOrBuilder: Properties): Properties;
77
- /**
78
- * Identity function we use to defeat the type system of Typescript and preserve
79
- * the properties keys.
80
- * @param enumValues
81
- * @group Builder
82
- */
83
- export declare function buildEnum(enumValues: EnumValues): EnumValues;
84
- /**
85
- * Identity function we use to defeat the type system of Typescript and preserve
86
- * the properties keys.
87
- * @param enumValueConfig
88
- * @group Builder
89
- */
90
- export declare function buildEnumValueConfig(enumValueConfig: EnumValueConfig): EnumValueConfig;
91
- /**
92
- * Identity function we use to defeat the type system of Typescript and preserve
93
- * the properties keys.
94
- * @param callbacks
95
- * @group Builder
96
- */
97
- export declare function buildEntityCallbacks<M extends Record<string, unknown> = Record<string, unknown>>(callbacks: EntityCallbacks<M>): EntityCallbacks<M>;
98
- /**
99
- * Identity function we use to defeat the type system of Typescript and build
100
- * additional field delegates views with all its properties
101
- * @param additionalFieldDelegate
102
- * @group Builder
103
- */
104
- export declare function buildAdditionalFieldDelegate<M extends Record<string, unknown>, USER extends User = User>(additionalFieldDelegate: AdditionalFieldDelegate<M, USER>): AdditionalFieldDelegate<M, USER>;
@@ -1,4 +1,4 @@
1
- import { EntityCallbacks, Properties, RebaseCallContext } from "@rebasepro/types";
1
+ import { CollectionCallbacks, Properties, RebaseCallContext } from "@rebasepro/types";
2
2
  /**
3
3
  * Context passed to entity lifecycle callbacks.
4
4
  * @group Models
@@ -6,6 +6,6 @@ import { EntityCallbacks, Properties, RebaseCallContext } from "@rebasepro/types
6
6
  export type EntityCallbackContext = RebaseCallContext;
7
7
  /**
8
8
  * Helper function to extract field-level PropertyCallbacks from a properties schema
9
- * and wrap them into an EntityCallbacks object recursively.
9
+ * and wrap them into an CollectionCallbacks object recursively.
10
10
  */
11
- export declare const buildPropertyCallbacks: (properties: Properties) => EntityCallbacks | undefined;
11
+ export declare const buildPropertyCallbacks: (properties: Properties) => CollectionCallbacks | undefined;
@@ -1,11 +1,11 @@
1
- import { DefaultSelectedViewBuilder, DefaultSelectedViewParams, EntityCollection, Properties } from "@rebasepro/types";
1
+ import { DefaultSelectedViewBuilder, DefaultSelectedViewParams, CollectionConfig, Properties } from "@rebasepro/types";
2
2
  export declare function sortProperties<M extends Record<string, unknown>>(properties: Properties, propertiesOrder?: string[]): Properties;
3
3
  export declare function resolveDefaultSelectedView(defaultSelectedView: string | DefaultSelectedViewBuilder | undefined, params: DefaultSelectedViewParams): string | undefined;
4
- export declare function getLocalChangesBackup(collection: EntityCollection): "manual_apply" | "auto_apply";
4
+ export declare function getLocalChangesBackup(collection: CollectionConfig): "manual_apply" | "auto_apply";
5
5
  /**
6
- * Returns the primary keys for an entity collection by inspecting the properties
6
+ * Returns the primary keys for a entity collection by inspecting the properties
7
7
  * and finding any properties with `isId`.
8
8
  * Fallbacks to `["id"]` if no properties are marked as `isId: true`.
9
9
  * @param collection
10
10
  */
11
- export declare function getPrimaryKeys<M extends Record<string, unknown>>(collection: EntityCollection<M>): Extract<keyof M, string>[];
11
+ export declare function getPrimaryKeys<M extends Record<string, unknown>>(collection: CollectionConfig<M>): Extract<keyof M, string>[];
@@ -6,7 +6,7 @@ export declare function getDefaultValuesFor<M extends Record<string, unknown>>(p
6
6
  export declare function getDefaultValueFor(property?: Property): unknown;
7
7
  export declare function getDefaultValueFortype(type: DataType): unknown;
8
8
  /**
9
- * Update the automatic values in an entity before save
9
+ * Update the automatic values in a entity before save
10
10
  * @group Driver
11
11
  */
12
12
  export declare function updateDateAutoValues<M extends Record<string, unknown>>({ inputValues, properties, status, timestampNowValue }: {
@@ -16,7 +16,7 @@ export declare function updateDateAutoValues<M extends Record<string, unknown>>(
16
16
  timestampNowValue: unknown;
17
17
  }): EntityValues<M>;
18
18
  /**
19
- * Add missing required fields, expected in the collection, to the values of an entity
19
+ * Add missing required fields, expected in the collection, to the values of a entity
20
20
  * @param values
21
21
  * @param properties
22
22
  * @group Driver
@@ -0,0 +1,32 @@
1
+ import { Property, WhereFilterOp } from "@rebasepro/types";
2
+ export interface ResolveFilterOperatorsParams {
3
+ /**
4
+ * The property to filter on. For array properties, pass the **item**
5
+ * property (`property.of`) together with `isArray: true` — the same
6
+ * convention the filter field dispatchers use.
7
+ */
8
+ property: Property;
9
+ /** True when filtering an array of `property`. */
10
+ isArray?: boolean;
11
+ /**
12
+ * The engine backing the collection (`collection.engine`, e.g.
13
+ * `"postgres"`, `"firestore"`). Falls back to the default engine's
14
+ * capabilities when omitted.
15
+ */
16
+ engine?: string;
17
+ }
18
+ /**
19
+ * Resolve which filter operators the UI should offer for a property.
20
+ *
21
+ * The result is the **intersection** of three sets:
22
+ * 1. what the engine can execute — {@link DataSourceCapabilities.filterOperators}
23
+ * (e.g. Firestore cannot run the LIKE family);
24
+ * 2. what makes sense for the property type (e.g. no `>` on booleans);
25
+ * 3. the developer's optional narrowing — `property.ui.filterOperators`.
26
+ *
27
+ * Returns an empty array when the property is not filterable (either by
28
+ * type, or because the developer disabled it with `filterOperators: []`).
29
+ *
30
+ * @group Models
31
+ */
32
+ export declare function resolveFilterOperators({ property, isArray, engine }: ResolveFilterOperatorsParams): WhereFilterOp[];
@@ -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[];
@@ -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,5 +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";
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[];
@@ -1,4 +1,4 @@
1
- import { EntityCollection } from "@rebasepro/types";
1
+ import { CollectionConfig } from "@rebasepro/types";
2
2
  type EntityCustomView<M extends Record<string, unknown> = Record<string, unknown>> = {
3
3
  key: string;
4
4
  [key: string]: unknown;
@@ -9,14 +9,14 @@ export interface NavigationViewEntityInternal<M extends Record<string, unknown>>
9
9
  entityId: string | number;
10
10
  slug: string;
11
11
  path: string;
12
- parentCollection: EntityCollection<M>;
12
+ parentCollection: CollectionConfig<M>;
13
13
  }
14
14
  export interface NavigationViewCollectionInternal<M extends Record<string, unknown>> {
15
15
  type: "collection";
16
16
  id: string;
17
17
  slug: string;
18
18
  path: string;
19
- collection: EntityCollection<M>;
19
+ collection: CollectionConfig<M>;
20
20
  }
21
21
  export interface NavigationViewEntityCustomInternal<M extends Record<string, unknown>> {
22
22
  type: "custom_view";
@@ -27,7 +27,7 @@ export interface NavigationViewEntityCustomInternal<M extends Record<string, unk
27
27
  }
28
28
  export declare function getNavigationEntriesFromPath(props: {
29
29
  path: string;
30
- collections: EntityCollection[] | undefined;
30
+ collections: CollectionConfig[] | undefined;
31
31
  currentFullPath?: string;
32
32
  contextEntityViews?: EntityCustomView[];
33
33
  }): NavigationViewInternal[];
@@ -1,17 +1,17 @@
1
- import { EntityCollection } from "@rebasepro/types";
1
+ import { CollectionConfig } from "@rebasepro/types";
2
2
  export declare function removeInitialAndTrailingSlashes(s: string): string;
3
3
  export declare function removeInitialSlash(s: string): string;
4
4
  export declare function removeTrailingSlash(s: string): string;
5
5
  export declare function addInitialSlash(s: string): string;
6
6
  export declare function getLastSegment(path: string): string;
7
- export declare function resolveCollectionPathIds(path: string, allCollections: EntityCollection[]): string;
7
+ export declare function resolveCollectionPathIds(path: string, allCollections: CollectionConfig[]): string;
8
8
  /**
9
9
  * Find the corresponding view at any depth for a given path.
10
10
  * Note that path or segments of the paths can be collection aliases.
11
11
  * @param slugOrPath
12
12
  * @param collections
13
13
  */
14
- export declare function getCollectionBySlugWithin(slugOrPath: string, collections: EntityCollection[]): EntityCollection | undefined;
14
+ export declare function getCollectionBySlugWithin(slugOrPath: string, collections: CollectionConfig[]): CollectionConfig | undefined;
15
15
  /**
16
16
  * Get the subcollection combinations from a path:
17
17
  * "sites/es/locales" => ["sites/es/locales", "sites"]
@@ -1,6 +1,6 @@
1
- import { EntityCollection, EntityReference } from "@rebasepro/types";
1
+ import { CollectionConfig, EntityReference } from "@rebasepro/types";
2
2
  export declare function getParentReferencesFromPath(props: {
3
3
  path: string;
4
- collections: EntityCollection[] | undefined;
4
+ collections: CollectionConfig[] | undefined;
5
5
  currentFullPath?: string;
6
6
  }): EntityReference[];
@@ -1,4 +1,4 @@
1
- import { Entity, EntityCollection, SecurityOperation, User } from "@rebasepro/types";
1
+ import { Entity, CollectionConfig, SecurityOperation, User } from "@rebasepro/types";
2
2
  /**
3
3
  * Minimal auth context for permission checking.
4
4
  * Only requires the user object — avoids forcing callers to construct
@@ -31,8 +31,8 @@ export interface CheckOperationOptions {
31
31
  * client-side (raw SQL, or row predicates with no row). Defaults to `"allow"`
32
32
  * for optimistic UI gating; enforcement callers should pass `"deny"`.
33
33
  */
34
- export declare function checkOperation<M extends Record<string, unknown>, USER extends User>(collection: EntityCollection<M>, authContext: AuthContext<USER>, entity: Entity<M> | null, targetOperation: SecurityOperation, options?: CheckOperationOptions): boolean;
35
- export declare function canReadCollection<M extends Record<string, unknown>, USER extends User>(collection: EntityCollection<M>, authContext: AuthContext<USER>): boolean;
36
- export declare function canEditEntity<M extends Record<string, unknown>, USER extends User>(collection: EntityCollection<M>, authContext: AuthContext<USER>, path: string, entity: Entity<M> | null): boolean;
37
- export declare function canCreateEntity<M extends Record<string, unknown>, USER extends User>(collection: EntityCollection<M>, authContext: AuthContext<USER>, path: string, entity: Entity<M> | null): boolean;
38
- export declare function canDeleteEntity<M extends Record<string, unknown>, USER extends User>(collection: EntityCollection<M>, authContext: AuthContext<USER>, path: string, entity: Entity<M> | null): boolean;
34
+ export declare function checkOperation<M extends Record<string, unknown>, USER extends User>(collection: CollectionConfig<M>, authContext: AuthContext<USER>, entity: Entity<M> | null, targetOperation: SecurityOperation, options?: CheckOperationOptions): boolean;
35
+ export declare function canReadCollection<M extends Record<string, unknown>, USER extends User>(collection: CollectionConfig<M>, authContext: AuthContext<USER>): boolean;
36
+ export declare function canEditEntity<M extends Record<string, unknown>, USER extends User>(collection: CollectionConfig<M>, authContext: AuthContext<USER>, path: string, entity: Entity<M> | null): boolean;
37
+ export declare function canCreateEntity<M extends Record<string, unknown>, USER extends User>(collection: CollectionConfig<M>, authContext: AuthContext<USER>, path: string, entity: Entity<M> | null): boolean;
38
+ export declare function canDeleteEntity<M extends Record<string, unknown>, USER extends User>(collection: CollectionConfig<M>, authContext: AuthContext<USER>, path: string, entity: Entity<M> | null): boolean;
@@ -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
- /** The current user's id, or null/undefined when unauthenticated. */
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,3 +1,4 @@
1
1
  export * from "./securityRuleToConditions";
2
+ export * from "./sqlToPolicy";
2
3
  export * from "./policyToPostgres";
3
4
  export * from "./evaluatePolicy";
@@ -1,4 +1,16 @@
1
- import { EntityCollection, PolicyExpression } from "@rebasepro/types";
1
+ import { CollectionConfig, PolicyExpression } from "@rebasepro/types";
2
+ /**
3
+ * Options for {@link policyToPostgres}.
4
+ */
5
+ export interface PolicyCompileOptions {
6
+ /**
7
+ * Resolve a collection by slug. Required to compile
8
+ * {@link ExistsInPolicyExpression} (`policy.existsIn`) — the compiler needs
9
+ * the joined collection to derive its table name / schema. When omitted, the
10
+ * join table falls back to a snake_cased slug.
11
+ */
12
+ resolveCollection?: (slug: string) => CollectionConfig | undefined;
13
+ }
2
14
  /**
3
15
  * Compiles a {@link PolicyExpression} to a PostgreSQL boolean SQL string,
4
16
  * suitable for a `USING (...)` / `WITH CHECK (...)` clause.
@@ -7,4 +19,4 @@ import { EntityCollection, PolicyExpression } from "@rebasepro/types";
7
19
  * {@link evaluatePolicy}); the Postgres schema generators call it so that DDL
8
20
  * and the admin UI derive from the exact same expression.
9
21
  */
10
- export declare function policyToPostgres(expr: PolicyExpression, collection?: EntityCollection): string;
22
+ export declare function policyToPostgres(expr: PolicyExpression, collection?: CollectionConfig, options?: PolicyCompileOptions): 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
- * A tiny, regex-based SQL "parser" for security rules.
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
- * This is NOT a full SQL parser. It is designed to handle the subset of SQL
6
- * commonly used in `USING` and `WITH CHECK` clauses, enough to drive the
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
- * It handles:
10
- * - `field = 'literal'`
11
- * - `field != 'literal'`
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
- * For anything it doesn't understand, it returns a `raw` expression, which
18
- * the evaluator treats as "unknown" (and usually optimistic true).
27
+ * Structured expressions are checked too, not just parsed SQL: `policy.compare`
28
+ * can spell the same mistake.
19
29
  */
20
- export declare function sqlToPolicy(sql: string): PolicyExpression;
30
+ export declare function findAnonymousGrants(expr: PolicyExpression): AnonymousGrantRisk[];
@@ -1,2 +1,2 @@
1
- import { EntityCollection } from "@rebasepro/types";
2
- export declare function getEntityImagePreviewPropertyKey<M extends Record<string, unknown>>(collection: EntityCollection<M>): string | undefined;
1
+ import { CollectionConfig } from "@rebasepro/types";
2
+ export declare function getEntityImagePreviewPropertyKey<M extends Record<string, unknown>>(collection: CollectionConfig<M>): string | undefined;
@@ -1,12 +1,12 @@
1
- import { EntityCollection, Property, Relation } from "@rebasepro/types";
2
- export declare function sanitizeRelation(relation: Partial<Relation>, sourceCollection: EntityCollection, resolveCollection?: (slugOrTable: string) => EntityCollection | undefined): Relation;
3
- export declare function resolveCollectionRelations(collection: EntityCollection): Record<string, Relation>;
1
+ import { CollectionConfig, Property, Relation } from "@rebasepro/types";
2
+ export declare function sanitizeRelation(relation: Partial<Relation>, sourceCollection: CollectionConfig, resolveCollection?: (slugOrTable: string) => CollectionConfig | undefined): Relation;
3
+ export declare function resolveCollectionRelations(collection: CollectionConfig): Record<string, Relation>;
4
4
  export declare function resolvePropertyRelation({ propertyKey, property, sourceCollection }: {
5
5
  propertyKey: string;
6
6
  property: Property;
7
- sourceCollection: EntityCollection;
7
+ sourceCollection: CollectionConfig;
8
8
  }): Relation | undefined;
9
- export declare function getTableName(collection: EntityCollection): string;
9
+ export declare function getTableName(collection: CollectionConfig): string;
10
10
  export declare function getTableVarName(tableName: string): string;
11
11
  export declare function getEnumVarName(tableName: string, propName: string): string;
12
12
  export declare function getColumnName(fullColumn: string): string;