@rebasepro/common 0.7.0 → 0.8.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.
Files changed (42) hide show
  1. package/dist/collections/CollectionRegistry.d.ts +17 -2
  2. package/dist/collections/default-collections.d.ts +255 -2
  3. package/dist/data/filter-dialect.d.ts +61 -0
  4. package/dist/data/query_builder.d.ts +4 -4
  5. package/dist/data/resolveDataSource.d.ts +7 -7
  6. package/dist/index.d.ts +1 -0
  7. package/dist/index.es.js +604 -188
  8. package/dist/index.es.js.map +1 -1
  9. package/dist/index.umd.js +611 -186
  10. package/dist/index.umd.js.map +1 -1
  11. package/dist/util/builders.d.ts +48 -1
  12. package/dist/util/callbacks.d.ts +6 -1
  13. package/dist/util/index.d.ts +1 -0
  14. package/dist/util/permissions.d.ts +26 -2
  15. package/dist/util/policy/evaluatePolicy.d.ts +31 -0
  16. package/dist/util/policy/index.d.ts +3 -0
  17. package/dist/util/policy/policyToPostgres.d.ts +10 -0
  18. package/dist/util/policy/securityRuleToConditions.d.ts +24 -0
  19. package/dist/util/policy/sqlToPolicy.d.ts +20 -0
  20. package/dist/util/storage.d.ts +26 -1
  21. package/package.json +13 -13
  22. package/src/collections/CollectionRegistry.ts +59 -28
  23. package/src/collections/default-collections.ts +4 -4
  24. package/src/data/buildRebaseData.ts +9 -120
  25. package/src/data/filter-dialect.ts +318 -0
  26. package/src/data/query_builder.ts +10 -10
  27. package/src/data/resolveDataSource.ts +9 -9
  28. package/src/index.ts +1 -0
  29. package/src/util/builders.ts +78 -1
  30. package/src/util/callbacks.ts +8 -1
  31. package/src/util/index.ts +1 -0
  32. package/src/util/permissions.test.ts +5 -3
  33. package/src/util/permissions.ts +85 -158
  34. package/src/util/policy/evaluatePolicy.ts +146 -0
  35. package/src/util/policy/index.ts +3 -0
  36. package/src/util/policy/policyToPostgres.ts +85 -0
  37. package/src/util/policy/securityRuleToConditions.ts +67 -0
  38. package/src/util/policy/sqlToPolicy.ts +88 -0
  39. package/src/util/references.ts +1 -1
  40. package/src/util/relations.ts +8 -9
  41. package/src/util/resolutions.ts +6 -6
  42. package/src/util/storage.ts +34 -1
@@ -0,0 +1,88 @@
1
+ import { PolicyExpression, policy } from "@rebasepro/types";
2
+
3
+ /**
4
+ * A tiny, regex-based SQL "parser" for security rules.
5
+ *
6
+ * This is NOT a full SQL parser. It is designed to handle the subset of SQL
7
+ * commonly used in `USING` and `WITH CHECK` clauses, enough to drive the
8
+ * optimistic client-side UI decision.
9
+ *
10
+ * It handles:
11
+ * - `field = 'literal'`
12
+ * - `field != 'literal'`
13
+ * - `field = current_setting('app.user_id')`
14
+ * - `A AND B`
15
+ * - `true`
16
+ * - `IN (...)` (as optimistic true)
17
+ *
18
+ * For anything it doesn't understand, it returns a `raw` expression, which
19
+ * the evaluator treats as "unknown" (and usually optimistic true).
20
+ */
21
+ export function sqlToPolicy(sql: string): PolicyExpression {
22
+ const trimmed = sql.trim();
23
+
24
+ if (trimmed.toLowerCase() === "true") return policy.true();
25
+ if (trimmed.toLowerCase() === "false") return policy.false();
26
+
27
+ // Handle roles overlap (&&)
28
+ // Matches: string_to_array(auth.roles(), ',') && ARRAY['admin', 'editor']
29
+ const overlapMatch = trimmed.match(/^string_to_array\s*\(\s*auth\.roles\(\)\s*,\s*','\s*\)\s*&&\s*ARRAY\s*\[(.+)\]$/i);
30
+ if (overlapMatch) {
31
+ const roles = overlapMatch[1].split(",").map(s => s.trim().replace(/^'|'$/g, ""));
32
+ return policy.rolesOverlap(roles);
33
+ }
34
+
35
+ // Handle roles containment (@>)
36
+ // Matches: string_to_array(auth.roles(), ',') @> ARRAY['admin']
37
+ const containMatch = trimmed.match(/^string_to_array\s*\(\s*auth\.roles\(\)\s*,\s*','\s*\)\s*@>\s*ARRAY\s*\[(.+)\]$/i);
38
+ if (containMatch) {
39
+ const roles = containMatch[1].split(",").map(s => s.trim().replace(/^'|'$/g, ""));
40
+ return policy.rolesContain(roles);
41
+ }
42
+
43
+ // Handle OR
44
+ if (trimmed.toUpperCase().includes(" OR ")) {
45
+ const parts = trimmed.split(/ OR /i);
46
+ return policy.or(...parts.map(sqlToPolicy));
47
+ }
48
+
49
+ // Handle AND (very basic split, doesn't handle nested parens properly)
50
+ if (trimmed.toUpperCase().includes(" AND ")) {
51
+ const parts = trimmed.split(/ AND /i);
52
+ return policy.and(...parts.map(sqlToPolicy));
53
+ }
54
+
55
+ // Handle = and !=
56
+ const match = trimmed.match(/^(.+?)\s*(!?=)\s*(.+)$/);
57
+ if (match) {
58
+ const [, leftStr, op, rightStr] = match;
59
+ const left = parseOperand(leftStr.trim());
60
+ const right = parseOperand(rightStr.trim());
61
+ if (left && right) {
62
+ return policy.compare(left, op === "=" ? "eq" : "neq", right);
63
+ }
64
+ }
65
+
66
+ // Fallback to raw
67
+ return policy.raw(sql);
68
+ }
69
+
70
+ function parseOperand(str: string) {
71
+ // current_setting('app.user_id') or auth.uid()
72
+ if (/current_setting\s*\(\s*'app\.user_id'\s*\)/i.test(str) || /auth\.uid\(\)/i.test(str)) {
73
+ return policy.authUid();
74
+ }
75
+
76
+ // Literal string: 'value'
77
+ const stringMatch = str.match(/^'(.+)'$/);
78
+ if (stringMatch) {
79
+ return policy.literal(stringMatch[1]);
80
+ }
81
+
82
+ // Bare field name
83
+ if (/^\w+$/.test(str)) {
84
+ return policy.field(str);
85
+ }
86
+
87
+ return null;
88
+ }
@@ -26,7 +26,7 @@ export function getEntityImagePreviewPropertyKey<M extends Record<string, unknow
26
26
  // and arrays of URL properties with image preview type
27
27
  for (const key in collection.properties) {
28
28
  const property = collection.properties[key];
29
- if (property.type === "array" && property.of && !Array.isArray(property.of) && property.of.type === "string" && property.of.url === "image") {
29
+ if (property.type === "array" && property.of && !Array.isArray(property.of) && property.of.type === "string" && property.of.ui?.url === "image") {
30
30
  return key;
31
31
  }
32
32
  }
@@ -1,4 +1,4 @@
1
- import { CollectionWithRelations, EntityCollection, getDataSourceCapabilities, Property, Relation, RelationProperty } from "@rebasepro/types";
1
+ import { EntityCollection, getDataSourceCapabilities, Property, Relation, RelationProperty } from "@rebasepro/types";
2
2
  import { toSnakeCase } from "@rebasepro/utils";
3
3
  import { generateForeignKeyName } from "@rebasepro/utils";
4
4
 
@@ -89,7 +89,7 @@ name: evaluated } as EntityCollection;
89
89
 
90
90
  try {
91
91
  // Look for an owning relation on the target that points back to this collection
92
- const targetRelations = getDataSourceCapabilities(targetCollection.driver).supportsRelations ? (((targetCollection as CollectionWithRelations).relations) || []) : [];
92
+ const targetRelations = getDataSourceCapabilities(targetCollection.engine).supportsRelations ? (targetCollection.relations || []) : [];
93
93
  for (const targetRel of targetRelations) {
94
94
  if (targetRel.direction === "owning" &&
95
95
  targetRel.cardinality === "one" &&
@@ -135,7 +135,7 @@ name: evaluated } as EntityCollection;
135
135
  // `cardinality: "many" + direction: "owning"` is sufficient to identify owning M2M.
136
136
 
137
137
  // 1. Check the explicit relations[] array
138
- const targetRelations = getDataSourceCapabilities(targetCollection.driver).supportsRelations ? (((targetCollection as CollectionWithRelations).relations) || []) : [];
138
+ const targetRelations = getDataSourceCapabilities(targetCollection.engine).supportsRelations ? (targetCollection.relations || []) : [];
139
139
  for (const targetRel of targetRelations) {
140
140
  if (targetRel.cardinality === "many" &&
141
141
  (targetRel.direction === "owning" || !targetRel.direction) &&
@@ -206,8 +206,7 @@ export function resolveCollectionRelations(
206
206
  const cached = _resolvedRelationsCache.get(collection);
207
207
  if (cached) return cached;
208
208
 
209
- if (!getDataSourceCapabilities(collection.driver).supportsRelations) return {};
210
- const relCollection = collection as CollectionWithRelations;
209
+ if (!getDataSourceCapabilities(collection.engine).supportsRelations) return {};
211
210
  const relations: Record<string, Relation> = {};
212
211
 
213
212
  // Track which explicit relationName values have been registered so that
@@ -217,8 +216,8 @@ export function resolveCollectionRelations(
217
216
 
218
217
  // 1. Process explicit relations from the `relations` field.
219
218
  // Each relation is stored once under its canonical relationName key.
220
- if (relCollection.relations) {
221
- relCollection.relations.forEach((relation: Relation) => {
219
+ if (collection.relations) {
220
+ collection.relations.forEach((relation: Relation) => {
222
221
  try {
223
222
  const normalizedRelation = sanitizeRelation(relation, collection);
224
223
  const relationKey = normalizedRelation.relationName;
@@ -306,8 +305,8 @@ export function resolvePropertyRelation({
306
305
  }
307
306
 
308
307
  export function getTableName(collection: EntityCollection): string {
309
- if (getDataSourceCapabilities(collection.driver).supportsRelations) {
310
- return (collection as CollectionWithRelations).table ?? toSnakeCase(collection.slug) ?? toSnakeCase(collection.name);
308
+ if (getDataSourceCapabilities(collection.engine).supportsRelations) {
309
+ return collection.table ?? toSnakeCase(collection.slug) ?? toSnakeCase(collection.name);
311
310
  }
312
311
  return toSnakeCase(collection.slug) ?? toSnakeCase(collection.name);
313
312
  }
@@ -1,8 +1,6 @@
1
1
  import {
2
2
  ArrayProperty,
3
3
  AuthController,
4
- CollectionWithRelations,
5
- CollectionWithSubcollections,
6
4
  EntityCollection,
7
5
  EnumValueConfig,
8
6
  EnumValues,
@@ -12,7 +10,8 @@ import {
12
10
  Relation,
13
11
  RelationProperty,
14
12
  StringProperty,
15
- getDataSourceCapabilities
13
+ getDataSourceCapabilities,
14
+ getDeclaredSubcollections
16
15
  } from "@rebasepro/types";
17
16
 
18
17
  type PropertyConfig = { property: unknown; [key: string]: unknown };
@@ -347,11 +346,12 @@ export function getSubcollections<M extends Record<string, unknown> = Record<str
347
346
  return collection.childCollections() ?? [];
348
347
  }
349
348
 
350
- if (getDataSourceCapabilities(collection.driver).supportsSubcollections && (collection as CollectionWithSubcollections).subcollections) {
351
- return (collection as CollectionWithSubcollections).subcollections!() ?? [];
349
+ const declaredSubcollections = getDeclaredSubcollections(collection);
350
+ if (getDataSourceCapabilities(collection.engine).supportsSubcollections && declaredSubcollections) {
351
+ return declaredSubcollections() ?? [];
352
352
  }
353
353
 
354
- if (getDataSourceCapabilities(collection.driver).supportsRelations) {
354
+ if (getDataSourceCapabilities(collection.engine).supportsRelations) {
355
355
  const resolvedRelations = resolveCollectionRelations(collection);
356
356
  const manyRelations = Object.values(resolvedRelations).filter((r: Relation) => r.cardinality === "many");
357
357
 
@@ -1,6 +1,39 @@
1
- import { ArrayProperty, EntityValues, StorageConfig, StringProperty, UploadedFileContext } from "@rebasepro/types";
1
+ import { ArrayProperty, EntityValues, StorageConfig, StorageSource, StorageSourceRegistry, StringProperty, UploadedFileContext } from "@rebasepro/types";
2
2
  import { randomString } from "@rebasepro/utils";
3
3
 
4
+ /**
5
+ * Resolve the {@link StorageSource} to use for a property, given the key
6
+ * referenced by `StorageConfig.storageSource`.
7
+ *
8
+ * Resolution priority:
9
+ * 1. No `sourceKey` → the default source (backward compatible).
10
+ * 2. An explicit {@link StorageSourceRegistry} (e.g. `client.storageRegistry`).
11
+ * 3. A `sources` lookup map (e.g. the `StorageSourcesContext`).
12
+ * 4. Fall back to the default source.
13
+ *
14
+ * Shared by the upload hook, the markdown editor, and the read-only previews
15
+ * so the resolution logic lives in one place.
16
+ *
17
+ * @group Storage
18
+ */
19
+ export function resolveStorageSource(params: {
20
+ /** Key from `StorageConfig.storageSource`. */
21
+ sourceKey?: string | null;
22
+ /** Built sources keyed by storage-source key (e.g. from context). */
23
+ sources?: Record<string, StorageSource>;
24
+ /** Optional explicit registry — takes precedence over `sources`. */
25
+ registry?: StorageSourceRegistry;
26
+ /** Default source, used when no key is set or the key cannot be resolved. */
27
+ defaultSource: StorageSource;
28
+ }): StorageSource {
29
+ const { sourceKey, sources, registry, defaultSource } = params;
30
+ if (!sourceKey) return defaultSource;
31
+ if (registry) return registry.getOrDefault(sourceKey);
32
+ const fromSources = sources?.[sourceKey];
33
+ if (fromSources) return fromSources;
34
+ return defaultSource;
35
+ }
36
+
4
37
  interface ResolveFilenameStringParams<M extends Record<string, unknown>> {
5
38
  input: string | ((context: UploadedFileContext) => (Promise<string> | string));
6
39
  storage: StorageConfig;