@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
package/dist/index.umd.js DELETED
@@ -1,2901 +0,0 @@
1
- (function(global, factory) {
2
- typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("@rebasepro/types"), require("@rebasepro/utils"), require("json-logic-js"), require("fast-equals")) : typeof define === "function" && define.amd ? define([
3
- "exports",
4
- "@rebasepro/types",
5
- "@rebasepro/utils",
6
- "json-logic-js",
7
- "fast-equals"
8
- ], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global["Rebase Util"] = {}, global._rebasepro_types, global._rebasepro_utils, global.jsonLogic, global.fastEquals));
9
- })(this, function(exports, _rebasepro_types, _rebasepro_utils, json_logic_js, fast_equals) {
10
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
11
- //#region \0rolldown/runtime.js
12
- var __create = Object.create;
13
- var __defProp = Object.defineProperty;
14
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
15
- var __getOwnPropNames = Object.getOwnPropertyNames;
16
- var __getProtoOf = Object.getPrototypeOf;
17
- var __hasOwnProp = Object.prototype.hasOwnProperty;
18
- var __copyProps = (to, from, except, desc) => {
19
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
20
- key = keys[i];
21
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
22
- get: ((k) => from[k]).bind(null, key),
23
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
24
- });
25
- }
26
- return to;
27
- };
28
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
29
- value: mod,
30
- enumerable: true
31
- }) : target, mod));
32
- //#endregion
33
- json_logic_js = __toESM(json_logic_js, 1);
34
- //#region src/util/common.ts
35
- var DEFAULT_ONE_OF_TYPE = "type";
36
- var DEFAULT_ONE_OF_VALUE = "value";
37
- //#endregion
38
- //#region src/util/entities.ts
39
- function isReadOnly(property) {
40
- if (property.ui?.readOnly) return true;
41
- if (property.type === "date") {
42
- if (property.autoValue) return true;
43
- }
44
- if (property.type === "reference") return !property.path && !("Field" in (property.ui || {}) && property.ui?.Field);
45
- return false;
46
- }
47
- function isHidden(property) {
48
- return typeof property.ui?.disabled === "object" && Boolean(property.ui?.disabled.hidden);
49
- }
50
- function isPropertyBuilder(property) {
51
- return typeof property?.dynamicProps === "function";
52
- }
53
- function getDefaultValuesFor(properties) {
54
- if (!properties) return {};
55
- return Object.entries(properties).map(([key, property]) => {
56
- if (!property) return {};
57
- const value = getDefaultValueFor(property);
58
- return value === void 0 ? {} : { [key]: value };
59
- }).reduce((a, b) => ({
60
- ...a,
61
- ...b
62
- }), {});
63
- }
64
- function getDefaultValueFor(property) {
65
- if (!property) return void 0;
66
- if (isPropertyBuilder(property)) return void 0;
67
- if (property.defaultValue || property.defaultValue === null) return property.defaultValue;
68
- else if (property.type === "map" && property.properties) {
69
- const defaultValuesFor = getDefaultValuesFor(property.properties);
70
- if (Object.keys(defaultValuesFor).length === 0) return void 0;
71
- return defaultValuesFor;
72
- } else return getDefaultValueFortype(property.type);
73
- }
74
- function getDefaultValueFortype(type) {
75
- if (type === "string") return null;
76
- else if (type === "number") return null;
77
- else if (type === "boolean") return false;
78
- else if (type === "date") return null;
79
- else if (type === "array") return [];
80
- else if (type === "map") return {};
81
- else if (type === "vector") return null;
82
- else if (type === "binary") return null;
83
- else return null;
84
- }
85
- /**
86
- * Update the automatic values in an entity before save
87
- * @group Driver
88
- */
89
- function updateDateAutoValues({ inputValues, properties, status, timestampNowValue }) {
90
- return traverseValuesProperties(inputValues, properties, (inputValue, property) => {
91
- if (property.type === "date") if (status === "existing" && property.autoValue === "on_update") return timestampNowValue;
92
- else if ((status === "new" || status === "copy") && (property.autoValue === "on_update" || property.autoValue === "on_create")) return timestampNowValue;
93
- else return inputValue;
94
- else return inputValue;
95
- }) ?? {};
96
- }
97
- /**
98
- * Add missing required fields, expected in the collection, to the values of an entity
99
- * @param values
100
- * @param properties
101
- * @group Driver
102
- */
103
- function sanitizeData(values, properties) {
104
- const result = values;
105
- Object.entries(properties).forEach(([key, property]) => {
106
- if (values && values[key] !== void 0) result[key] = values[key];
107
- else if (property.validation?.required) result[key] = null;
108
- });
109
- return result;
110
- }
111
- function getReferenceFrom(entity) {
112
- if (typeof entity.id !== "string") throw new Error("Only string IDs are supported in references");
113
- return new _rebasepro_types.EntityReference({
114
- id: entity.id,
115
- path: entity.path,
116
- driver: entity.driver,
117
- databaseId: entity.databaseId
118
- });
119
- }
120
- function getRelationFrom(entity) {
121
- return new _rebasepro_types.EntityRelation(entity.id, entity.path, entity);
122
- }
123
- /**
124
- * Normalize a value into a proper EntityRelation instance.
125
- * Handles EntityRelation class instances, and plain objects
126
- * with `__type === "relation"` or an `isEntityRelation()` method.
127
- *
128
- * When `propertyType` is `"relation"`, also accepts plain objects that
129
- * have `id` and `path` fields — these are relation-shaped objects from
130
- * edge cases in the data pipeline (REST fallback, stale cache, custom data source).
131
- *
132
- * Returns null if the value cannot be coerced.
133
- */
134
- function normalizeToEntityRelation(value, propertyType) {
135
- if (value instanceof _rebasepro_types.EntityRelation) return value;
136
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
137
- const obj = value;
138
- if (!(obj.__type === "relation" || obj.__type === "reference" || typeof obj.isEntityRelation === "function" && obj.isEntityRelation() || typeof obj.isEntityReference === "function" && obj.isEntityReference() || propertyType === "relation" && typeof obj.id !== "undefined" && typeof obj.path === "string")) return null;
139
- return new _rebasepro_types.EntityRelation(obj.id, obj.path, obj.data);
140
- }
141
- function traverseValuesProperties(inputValues, properties, operation) {
142
- const safeInputValues = inputValues ?? {};
143
- const result = (0, _rebasepro_utils.mergeDeep)(safeInputValues, Object.entries(properties).map(([key, property]) => {
144
- const updatedValue = traverseValueProperty(safeInputValues && safeInputValues[key], property, operation);
145
- if (updatedValue === null) return null;
146
- if (updatedValue === void 0) return void 0;
147
- return { [key]: updatedValue };
148
- }).reduce((a, b) => ({
149
- ...a,
150
- ...b
151
- }), {}));
152
- if (!result || Object.keys(result).length === 0) return void 0;
153
- return result;
154
- }
155
- function traverseValueProperty(inputValue, property, operation) {
156
- let value;
157
- if (property.type === "map" && property.properties) value = traverseValuesProperties(inputValue, property.properties, operation);
158
- else if (property.type === "array") {
159
- const of = property.of;
160
- if (of && Array.isArray(inputValue) && !Array.isArray(of)) value = inputValue.map((e) => traverseValueProperty(e, of, operation));
161
- else if (of && Array.isArray(inputValue) && Array.isArray(of)) value = inputValue.map((e, i) => {
162
- if (i < of.length) return traverseValueProperty(e, of[i], operation);
163
- return null;
164
- }).filter(Boolean);
165
- else if (property.oneOf && Array.isArray(inputValue)) {
166
- const typeField = property.oneOf?.typeField ?? "type";
167
- const valueField = property.oneOf?.valueField ?? "value";
168
- value = inputValue.map((e) => {
169
- if (e === null) return null;
170
- if (typeof e !== "object") return e;
171
- const rec = e;
172
- const type = rec[typeField];
173
- const childProperty = property.oneOf?.properties[type];
174
- if (!type || !childProperty) return e;
175
- return {
176
- [typeField]: type,
177
- [valueField]: traverseValueProperty(rec[valueField], childProperty, operation)
178
- };
179
- });
180
- } else value = inputValue;
181
- } else value = operation(inputValue, property);
182
- return value;
183
- }
184
- /**
185
- * Create a lightweight relation stub for CMS views.
186
- * Replaces inline `{ id, path, __type: "relation" }` object literals.
187
- */
188
- function createRelationRef(id, path) {
189
- return {
190
- id,
191
- path,
192
- __type: "relation"
193
- };
194
- }
195
- /**
196
- * Create a hydrated relation reference that includes the full entity data.
197
- * Used when entity data has been pre-fetched (e.g., via batch loading or JOINs).
198
- */
199
- function createRelationRefWithData(id, path, data) {
200
- return {
201
- id,
202
- path,
203
- __type: "relation",
204
- data
205
- };
206
- }
207
- //#endregion
208
- //#region src/util/collections.ts
209
- function sortProperties(properties, propertiesOrder) {
210
- try {
211
- const propertiesKeys = Object.keys(properties);
212
- if (!propertiesOrder || propertiesOrder.length === 0) return propertiesKeys.map((key) => {
213
- const property = properties[key];
214
- if (!isPropertyBuilder(property) && property?.type === "map" && property.properties) return { [key]: {
215
- ...property,
216
- properties: sortProperties(property.properties, property.propertiesOrder)
217
- } };
218
- else return { [key]: property };
219
- }).reduce((a, b) => ({
220
- ...a,
221
- ...b
222
- }), {});
223
- const validOrderKeys = propertiesOrder.filter((key) => {
224
- return !key.includes(".") && properties[key];
225
- });
226
- const processedKeys = new Set(validOrderKeys);
227
- const orderedResult = validOrderKeys.map((key) => {
228
- const property = properties[key];
229
- if (!isPropertyBuilder(property) && property?.type === "map" && property.properties) return { [key]: {
230
- ...property,
231
- properties: sortProperties(property.properties, property.propertiesOrder)
232
- } };
233
- else return { [key]: property };
234
- }).reduce((a, b) => ({
235
- ...a,
236
- ...b
237
- }), {});
238
- const missingProperties = propertiesKeys.filter((key) => !processedKeys.has(key)).map((key) => {
239
- const property = properties[key];
240
- if (!isPropertyBuilder(property) && property?.type === "map" && property.properties) return { [key]: {
241
- ...property,
242
- properties: sortProperties(property.properties, property.propertiesOrder)
243
- } };
244
- else return { [key]: property };
245
- }).reduce((a, b) => ({
246
- ...a,
247
- ...b
248
- }), {});
249
- return {
250
- ...orderedResult,
251
- ...missingProperties
252
- };
253
- } catch (e) {
254
- console.error("Error sorting properties", e);
255
- return properties;
256
- }
257
- }
258
- function resolveDefaultSelectedView(defaultSelectedView, params) {
259
- if (!defaultSelectedView) return;
260
- else if (typeof defaultSelectedView === "string") return defaultSelectedView;
261
- else return defaultSelectedView(params);
262
- }
263
- function getLocalChangesBackup(collection) {
264
- if (!collection.localChangesBackup) return "manual_apply";
265
- return collection.localChangesBackup;
266
- }
267
- /**
268
- * Returns the primary keys for an entity collection by inspecting the properties
269
- * and finding any properties with `isId`.
270
- * Fallbacks to `["id"]` if no properties are marked as `isId: true`.
271
- * @param collection
272
- */
273
- function getPrimaryKeys(collection) {
274
- const properties = collection.properties;
275
- if (!properties) return ["id"];
276
- const ids = Object.entries(properties).filter(([key, prop]) => typeof prop === "object" && prop !== null && "isId" in prop && Boolean(prop.isId)).map(([key]) => key);
277
- if (ids.length > 0) return ids;
278
- return ["id"];
279
- }
280
- //#endregion
281
- //#region src/util/enums.ts
282
- function enumToObjectEntries(enumValues) {
283
- if (Array.isArray(enumValues)) return enumValues;
284
- else return Object.entries(enumValues).map(([id, value]) => {
285
- if (typeof value === "string") return {
286
- id,
287
- label: value
288
- };
289
- else return {
290
- ...value,
291
- id
292
- };
293
- });
294
- }
295
- function getLabelOrConfigFrom(enumValues, key) {
296
- if (key === null || key === void 0) return void 0;
297
- return enumValues.find((entry) => String(entry.id) === String(key));
298
- }
299
- //#endregion
300
- //#region src/util/paths.ts
301
- var COLLECTION_PATH_SEPARATOR = "::";
302
- /**
303
- * Remove the entity ids from a given path
304
- * `products/B44RG6APH/locales` => `products::locales`
305
- * @param path
306
- */
307
- function stripCollectionPath(path) {
308
- return segmentsToStrippedPath(fullPathToCollectionSegments(path));
309
- }
310
- function segmentsToStrippedPath(paths) {
311
- if (paths.length === 1) return paths[0];
312
- return paths.reduce((a, b) => `${a}::${b}`);
313
- }
314
- /**
315
- * Extract the collection path routes
316
- * `products/B44RG6APH/locales` => [`products`, `locales`]
317
- * @param path
318
- */
319
- function fullPathToCollectionSegments(path) {
320
- return path.split("/").filter((e, i) => i % 2 === 0);
321
- }
322
- //#endregion
323
- //#region src/util/relations.ts
324
- function sanitizeRelation(relation, sourceCollection, resolveCollection) {
325
- if (!relation.target) throw new Error("Relation is missing a `target` collection.");
326
- const rawTarget = relation.target;
327
- let targetCollection;
328
- if (typeof rawTarget === "string") {
329
- if (resolveCollection) targetCollection = resolveCollection(rawTarget);
330
- if (!targetCollection) targetCollection = {
331
- slug: rawTarget,
332
- name: rawTarget
333
- };
334
- } else if (typeof rawTarget === "function") {
335
- const evaluated = rawTarget();
336
- if (typeof evaluated === "string") {
337
- if (resolveCollection) targetCollection = resolveCollection(evaluated);
338
- if (!targetCollection) targetCollection = {
339
- slug: evaluated,
340
- name: evaluated
341
- };
342
- } else targetCollection = evaluated;
343
- } else if (rawTarget && typeof rawTarget === "object") targetCollection = rawTarget;
344
- if (!targetCollection) throw new Error("Relation is missing a valid `target` collection.");
345
- const newRelation = { ...relation };
346
- newRelation.target = () => {
347
- if (typeof rawTarget === "string") return resolveCollection && resolveCollection(rawTarget) || targetCollection;
348
- else if (typeof rawTarget === "function") {
349
- const evaluated = rawTarget();
350
- if (typeof evaluated === "string") return resolveCollection && resolveCollection(evaluated) || targetCollection;
351
- return evaluated;
352
- }
353
- return targetCollection;
354
- };
355
- if (!newRelation.relationName) newRelation.relationName = (0, _rebasepro_utils.toSnakeCase)(targetCollection.slug);
356
- if (!newRelation.direction) if (newRelation.foreignKeyOnTarget) newRelation.direction = "inverse";
357
- else if (newRelation.through) newRelation.direction = "owning";
358
- else if (newRelation.cardinality === "many") newRelation.direction = "inverse";
359
- else newRelation.direction = "owning";
360
- if (!newRelation.joinPath) {
361
- const sourceName = (0, _rebasepro_utils.toSnakeCase)(sourceCollection.slug ?? sourceCollection.name);
362
- if (newRelation.cardinality === "one" && newRelation.direction === "owning") {
363
- if (!newRelation.localKey) newRelation.localKey = (0, _rebasepro_utils.generateForeignKeyName)(newRelation.relationName);
364
- } else if (newRelation.cardinality === "one" && newRelation.direction === "inverse") {
365
- if (!newRelation.foreignKeyOnTarget) {
366
- let foundForeignKey = false;
367
- try {
368
- const targetRelations = (0, _rebasepro_types.getDataSourceCapabilities)(targetCollection.engine).supportsRelations ? targetCollection.relations || [] : [];
369
- for (const targetRel of targetRelations) if (targetRel.direction === "owning" && targetRel.cardinality === "one" && targetRel.localKey) try {
370
- if (targetRel.target().slug === sourceCollection.slug) {
371
- newRelation.foreignKeyOnTarget = targetRel.localKey;
372
- foundForeignKey = true;
373
- break;
374
- }
375
- } catch (e) {
376
- continue;
377
- }
378
- } catch (e) {}
379
- if (!foundForeignKey) newRelation.foreignKeyOnTarget = (0, _rebasepro_utils.generateForeignKeyName)(newRelation.inverseRelationName ? (0, _rebasepro_utils.toSnakeCase)(newRelation.inverseRelationName) : sourceName);
380
- }
381
- } else if (newRelation.cardinality === "many" && newRelation.direction === "inverse") {
382
- let isManyToManyInverse = false;
383
- if (newRelation.inverseRelationName && !newRelation.foreignKeyOnTarget) try {
384
- const targetRelations = (0, _rebasepro_types.getDataSourceCapabilities)(targetCollection.engine).supportsRelations ? targetCollection.relations || [] : [];
385
- for (const targetRel of targetRelations) if (targetRel.cardinality === "many" && (targetRel.direction === "owning" || !targetRel.direction) && targetRel.relationName === newRelation.inverseRelationName) {
386
- isManyToManyInverse = true;
387
- break;
388
- }
389
- if (!isManyToManyInverse && targetCollection.properties) for (const [propKey, prop] of Object.entries(targetCollection.properties)) {
390
- if (prop.type !== "relation") continue;
391
- const relProp = prop;
392
- if ((relProp.relationName || propKey) === newRelation.inverseRelationName && relProp.cardinality === "many" && (relProp.direction === "owning" || !relProp.direction)) {
393
- isManyToManyInverse = true;
394
- break;
395
- }
396
- }
397
- } catch (e) {}
398
- if (!isManyToManyInverse && !newRelation.foreignKeyOnTarget) newRelation.foreignKeyOnTarget = (0, _rebasepro_utils.generateForeignKeyName)(sourceName);
399
- } else if (newRelation.cardinality === "many" && newRelation.direction === "owning") {
400
- const sourceTableName = getTableName(sourceCollection);
401
- const targetTableName = getTableName(targetCollection);
402
- newRelation.through = {
403
- table: newRelation.through?.table ?? [sourceTableName, targetTableName].sort().join("_"),
404
- sourceColumn: newRelation.through?.sourceColumn ?? (0, _rebasepro_utils.generateForeignKeyName)(sourceName),
405
- targetColumn: newRelation.through?.targetColumn ?? (0, _rebasepro_utils.generateForeignKeyName)(newRelation.relationName)
406
- };
407
- }
408
- }
409
- if (newRelation.cardinality === "one" && newRelation.direction === "owning" && !newRelation.localKey && !newRelation.joinPath) throw new Error(`Configuration Error in relation from '${sourceCollection.name}': An 'owning' one-to-one relation requires a 'localKey'. Check the relation config for '${newRelation.relationName}'`);
410
- if (newRelation.cardinality === "one" && newRelation.direction === "inverse" && !newRelation.foreignKeyOnTarget && !newRelation.joinPath) throw new Error(`Configuration Error in relation from '${sourceCollection.name}': An 'inverse' one-to-one relation requires a 'foreignKeyOnTarget'. Check the relation config for '${newRelation.relationName}'`);
411
- if (newRelation.cardinality === "many" && newRelation.direction === "inverse" && !newRelation.foreignKeyOnTarget && !newRelation.joinPath && !newRelation.inverseRelationName) throw new Error(`Configuration Error in relation from '${sourceCollection.name}': An 'inverse' one-to-many relation requires a 'foreignKeyOnTarget'. Check the relation config for '${newRelation.relationName}'`);
412
- return newRelation;
413
- }
414
- /** WeakMap cache — same collection instance always yields the same relation map. */
415
- var _resolvedRelationsCache = /* @__PURE__ */ new WeakMap();
416
- function resolveCollectionRelations(collection) {
417
- const cached = _resolvedRelationsCache.get(collection);
418
- if (cached) return cached;
419
- if (!(0, _rebasepro_types.getDataSourceCapabilities)(collection.engine).supportsRelations) return {};
420
- const relations = {};
421
- const registeredRelationNames = /* @__PURE__ */ new Set();
422
- if (collection.relations) collection.relations.forEach((relation) => {
423
- try {
424
- const normalizedRelation = sanitizeRelation(relation, collection);
425
- const relationKey = normalizedRelation.relationName;
426
- if (relationKey) {
427
- relations[relationKey] = normalizedRelation;
428
- registeredRelationNames.add(relationKey);
429
- }
430
- } catch (e) {}
431
- });
432
- if (collection.properties) Object.entries(collection.properties).forEach(([propKey, prop]) => {
433
- const relation = resolvePropertyRelation({
434
- propertyKey: propKey,
435
- property: prop,
436
- sourceCollection: collection
437
- });
438
- if (relation) {
439
- if (relations[propKey]) return;
440
- if (!relation.relationName) relation.relationName = propKey;
441
- const normalizedRelation = sanitizeRelation(relation, collection);
442
- relations[propKey] = normalizedRelation;
443
- registeredRelationNames.add(normalizedRelation.relationName ?? propKey);
444
- }
445
- });
446
- _resolvedRelationsCache.set(collection, relations);
447
- return relations;
448
- }
449
- function resolvePropertyRelation({ propertyKey, property, sourceCollection }) {
450
- if (property.type !== "relation") return void 0;
451
- const relProp = property;
452
- if (relProp.target) return {
453
- relationName: relProp.relationName || propertyKey,
454
- target: relProp.target,
455
- cardinality: relProp.cardinality || "one",
456
- direction: relProp.direction || "owning",
457
- inverseRelationName: relProp.inverseRelationName,
458
- localKey: relProp.localKey,
459
- foreignKeyOnTarget: relProp.foreignKeyOnTarget,
460
- through: relProp.through,
461
- joinPath: relProp.joinPath,
462
- onUpdate: relProp.onUpdate,
463
- onDelete: relProp.onDelete,
464
- overrides: relProp.overrides
465
- };
466
- console.warn(`Unrecognized or missing relation target for property '${propertyKey}' in collection '${sourceCollection.slug}'`);
467
- }
468
- function getTableName(collection) {
469
- if ((0, _rebasepro_types.getDataSourceCapabilities)(collection.engine).supportsRelations) return collection.table ?? (0, _rebasepro_utils.toSnakeCase)(collection.slug) ?? (0, _rebasepro_utils.toSnakeCase)(collection.name);
470
- return (0, _rebasepro_utils.toSnakeCase)(collection.slug) ?? (0, _rebasepro_utils.toSnakeCase)(collection.name);
471
- }
472
- function getTableVarName(tableName) {
473
- return tableName.replace(/_([a-z])/g, (_, char) => char.toUpperCase());
474
- }
475
- function getEnumVarName(tableName, propName) {
476
- return `${getTableVarName(tableName)}${propName.charAt(0).toUpperCase() + propName.slice(1)}`;
477
- }
478
- function getColumnName(fullColumn) {
479
- return fullColumn.includes(".") ? fullColumn.split(".").pop() : fullColumn;
480
- }
481
- /**
482
- * Look up a relation by key with forgiving normalization.
483
- *
484
- * `resolveCollectionRelations` stores each relation under a single canonical
485
- * key (no aliases). This helper tries the given key as-is, then falls back to
486
- * slug form (underscores → hyphens) and snake_case form (hyphens → underscores)
487
- * so that callers that receive a key from external input (URL path segments,
488
- * user-provided config, etc.) can still find the right entry.
489
- */
490
- function findRelation(resolvedRelations, key) {
491
- if (resolvedRelations[key]) return resolvedRelations[key];
492
- const slugKey = key.replace(/_/g, "-");
493
- if (slugKey !== key && resolvedRelations[slugKey]) return resolvedRelations[slugKey];
494
- const snakeKey = key.replace(/-/g, "_");
495
- if (snakeKey !== key && resolvedRelations[snakeKey]) return resolvedRelations[snakeKey];
496
- }
497
- //#endregion
498
- //#region src/util/resolutions.ts
499
- function resolveProperty(props) {
500
- const { property, ignoreMissingFields = false, ...rest } = props;
501
- let resultProperty;
502
- if (isPropertyBuilder(property)) {
503
- const path = rest.path;
504
- if (!path) resultProperty = property;
505
- else {
506
- const usedPropertyValue = rest.propertyKey ? (0, _rebasepro_utils.getIn)(rest.values, rest.propertyKey) : void 0;
507
- const dynamicProps = property.dynamicProps?.({
508
- ...rest,
509
- path,
510
- propertyValue: usedPropertyValue,
511
- values: rest.values ?? {},
512
- previousValues: rest.previousValues ?? rest.values ?? {}
513
- });
514
- resultProperty = (0, _rebasepro_utils.mergeDeep)(property, dynamicProps ?? {});
515
- }
516
- } else resultProperty = property;
517
- if (resultProperty?.dynamicProps && rest.path) {
518
- const path = rest.path;
519
- const usedPropertyValue = rest.propertyKey ? (0, _rebasepro_utils.getIn)(rest.values, rest.propertyKey) : void 0;
520
- const dynamicPropsResult = resultProperty.dynamicProps({
521
- ...rest,
522
- path,
523
- propertyValue: usedPropertyValue,
524
- values: rest.values ?? {},
525
- previousValues: rest.previousValues ?? rest.values ?? {}
526
- });
527
- if (dynamicPropsResult) resultProperty = (0, _rebasepro_utils.mergeDeep)(resultProperty, dynamicPropsResult);
528
- }
529
- let resolvedProperty;
530
- if (resultProperty?.type === "map" && resultProperty.properties) {
531
- const properties = resolveProperties({
532
- ignoreMissingFields,
533
- ...rest,
534
- properties: resultProperty.properties
535
- });
536
- resolvedProperty = {
537
- ...resultProperty,
538
- properties
539
- };
540
- } else if (resultProperty?.type === "array") resolvedProperty = resultProperty;
541
- else if ((resultProperty?.type === "string" || resultProperty?.type === "number") && resultProperty.enum) resolvedProperty = resolvePropertyEnum(resultProperty);
542
- else resolvedProperty = resultProperty;
543
- if (resolvedProperty?.propertyConfig && !(0, _rebasepro_utils.isDefaultFieldConfigId)(resolvedProperty.propertyConfig)) {
544
- const cmsFields = rest.propertyConfigs;
545
- if (!cmsFields && !ignoreMissingFields) throw Error(`Trying to resolve a property with key '${resolvedProperty.propertyConfig}' that inherits from a custom property config but no custom property configs were provided. Use the property 'propertyConfigs' in your app config to provide them`);
546
- const customField = cmsFields?.[resolvedProperty.propertyConfig];
547
- if (!customField) {
548
- console.warn(`Trying to resolve a property with key '${resolvedProperty.propertyConfig}' that inherits from a custom property config but no custom property config with that key was found. Check the 'propertyConfigs' in your app config`);
549
- return resolvedProperty;
550
- }
551
- if (customField.property) {
552
- const restConfigProperty = { ...customField.property };
553
- delete restConfigProperty.propertyConfig;
554
- const customFieldProperty = resolveProperty({
555
- property: {
556
- name: "",
557
- ...restConfigProperty
558
- },
559
- ignoreMissingFields,
560
- ...rest
561
- });
562
- if (customFieldProperty) resolvedProperty = (0, _rebasepro_utils.mergeDeep)(customFieldProperty, resolvedProperty);
563
- }
564
- }
565
- return resolvedProperty;
566
- }
567
- function resolveRelationProperty(property, relations, propertyKey) {
568
- if (property.relation) return property;
569
- const name = property.relationName || propertyKey;
570
- const relation = name ? relations.find((rel) => rel.relationName === name) : void 0;
571
- if (!relation) throw Error(`Relation ${name ?? "(unnamed)"} not found`);
572
- return {
573
- ...property,
574
- relation
575
- };
576
- }
577
- /**
578
- * Resolve enum aliases for a string or number property
579
- * @param property
580
- */
581
- function resolvePropertyEnum(property) {
582
- if (typeof property.enum === "object") return {
583
- ...property,
584
- enum: enumToObjectEntries(property.enum)?.filter((value) => value && (value.id || value.id === 0) && value.label) ?? []
585
- };
586
- return property;
587
- }
588
- /**
589
- * Resolve enums and arrays for properties
590
- * @param properties
591
- * @param value
592
- */
593
- function resolveProperties({ propertyKey, properties, ignoreMissingFields, ...props }) {
594
- return Object.entries(properties).map(([key, property]) => {
595
- const childResolvedProperty = resolveProperty({
596
- propertyKey: propertyKey ? `${propertyKey}.${key}` : void 0,
597
- property,
598
- ignoreMissingFields,
599
- ...props
600
- });
601
- if (!childResolvedProperty) return {};
602
- return { [key]: childResolvedProperty };
603
- }).filter((a) => a !== null).reduce((a, b) => ({
604
- ...a,
605
- ...b
606
- }), {});
607
- }
608
- function resolveArrayProperties({ propertyKey, property, ignoreMissingFields = false, ...props }) {
609
- const propertyValue = propertyKey ? (0, _rebasepro_utils.getIn)(props.values, propertyKey) : void 0;
610
- if (property.of) if (Array.isArray(property.of)) return property.of.map((p, index) => {
611
- return resolveProperty({
612
- propertyKey: `${propertyKey}.${index}`,
613
- property: p,
614
- ignoreMissingFields,
615
- ...props,
616
- index
617
- });
618
- });
619
- else {
620
- const of = property.of;
621
- const resolvedProperties = getArrayResolvedProperties({
622
- propertyValue,
623
- propertyKey,
624
- property,
625
- ignoreMissingFields,
626
- ...props
627
- });
628
- const { values, previousValues, ...rest } = props;
629
- if (!resolveProperty({
630
- property: of,
631
- ignoreMissingFields,
632
- ...rest
633
- }) && !ignoreMissingFields) throw Error("When using a property builder as the 'of' prop of an ArrayProperty, you must return a valid child property");
634
- return resolvedProperties;
635
- }
636
- else if (property.oneOf) {
637
- const typeField = property.oneOf?.typeField ?? "type";
638
- return Array.isArray(propertyValue) ? propertyValue.map((v, index) => {
639
- const type = v && v[typeField];
640
- const childProperty = property.oneOf?.properties[type];
641
- if (!type || !childProperty) return null;
642
- return resolveProperty({
643
- propertyKey: `${propertyKey}.${index}`,
644
- property: childProperty,
645
- ignoreMissingFields,
646
- ...props
647
- });
648
- }).filter((e) => Boolean(e)) : [];
649
- } else if (!("Field" in (property.ui || {}) && property.ui?.Field)) throw Error(`The array property (${propertyKey}) needs to declare an 'of' or a 'oneOf' property, or provide a custom \`Field\` component`);
650
- else return [];
651
- }
652
- function getArrayResolvedProperties({ propertyKey, propertyValue, property, ...props }) {
653
- const of = property.of;
654
- if (!of) throw Error(`Trying to resolve an array property (${propertyKey}) without providing an 'of' property`);
655
- return Array.isArray(propertyValue) ? propertyValue.map((v, index) => {
656
- return resolveProperty({
657
- propertyKey: `${propertyKey}.${index}`,
658
- property: Array.isArray(of) ? of[index] : of,
659
- ...props,
660
- index
661
- });
662
- }).filter((e) => Boolean(e)) : [];
663
- }
664
- function resolveEnumValues(input) {
665
- if (typeof input === "object") return Object.entries(input).map(([id, value]) => typeof value === "string" ? {
666
- id,
667
- label: value
668
- } : value);
669
- else if (Array.isArray(input)) return input;
670
- else return;
671
- }
672
- function getSubcollections(collection) {
673
- if (collection.childCollections) return collection.childCollections() ?? [];
674
- const declaredSubcollections = (0, _rebasepro_types.getDeclaredSubcollections)(collection);
675
- if ((0, _rebasepro_types.getDataSourceCapabilities)(collection.engine).supportsSubcollections && declaredSubcollections) return declaredSubcollections() ?? [];
676
- if ((0, _rebasepro_types.getDataSourceCapabilities)(collection.engine).supportsRelations) {
677
- const resolvedRelations = resolveCollectionRelations(collection);
678
- return Object.values(resolvedRelations).filter((r) => r.cardinality === "many").map((r) => {
679
- const target = r.target();
680
- if (!target) return void 0;
681
- const relationKey = r.relationName || target.slug;
682
- let customName;
683
- if (collection.properties) {
684
- const prop = Object.entries(collection.properties).find(([_, p]) => p.type === "relation" && p.relationName === relationKey);
685
- if (prop && prop[1].name) customName = prop[1].name;
686
- }
687
- const baseOverrides = { slug: relationKey };
688
- if (customName) {
689
- baseOverrides.name = customName;
690
- baseOverrides.singularName = customName;
691
- }
692
- const targetWithOverrides = {
693
- ...target,
694
- ...baseOverrides
695
- };
696
- return r.overrides ? (0, _rebasepro_utils.mergeDeep)(targetWithOverrides, r.overrides) : targetWithOverrides;
697
- }).filter((c) => Boolean(c));
698
- }
699
- return [];
700
- }
701
- //#endregion
702
- //#region src/util/policy/sqlToPolicy.ts
703
- /**
704
- * A tiny, regex-based SQL "parser" for security rules.
705
- *
706
- * This is NOT a full SQL parser. It is designed to handle the subset of SQL
707
- * commonly used in `USING` and `WITH CHECK` clauses, enough to drive the
708
- * optimistic client-side UI decision.
709
- *
710
- * It handles:
711
- * - `field = 'literal'`
712
- * - `field != 'literal'`
713
- * - `field = current_setting('app.user_id')`
714
- * - `A AND B`
715
- * - `true`
716
- * - `IN (...)` (as optimistic true)
717
- *
718
- * For anything it doesn't understand, it returns a `raw` expression, which
719
- * the evaluator treats as "unknown" (and usually optimistic true).
720
- */
721
- function sqlToPolicy(sql) {
722
- const trimmed = sql.trim();
723
- if (trimmed.toLowerCase() === "true") return _rebasepro_types.policy.true();
724
- if (trimmed.toLowerCase() === "false") return _rebasepro_types.policy.false();
725
- const overlapMatch = trimmed.match(/^string_to_array\s*\(\s*auth\.roles\(\)\s*,\s*','\s*\)\s*&&\s*ARRAY\s*\[(.+)\]$/i);
726
- if (overlapMatch) {
727
- const roles = overlapMatch[1].split(",").map((s) => s.trim().replace(/^'|'$/g, ""));
728
- return _rebasepro_types.policy.rolesOverlap(roles);
729
- }
730
- const containMatch = trimmed.match(/^string_to_array\s*\(\s*auth\.roles\(\)\s*,\s*','\s*\)\s*@>\s*ARRAY\s*\[(.+)\]$/i);
731
- if (containMatch) {
732
- const roles = containMatch[1].split(",").map((s) => s.trim().replace(/^'|'$/g, ""));
733
- return _rebasepro_types.policy.rolesContain(roles);
734
- }
735
- if (trimmed.toUpperCase().includes(" OR ")) {
736
- const parts = trimmed.split(/ OR /i);
737
- return _rebasepro_types.policy.or(...parts.map(sqlToPolicy));
738
- }
739
- if (trimmed.toUpperCase().includes(" AND ")) {
740
- const parts = trimmed.split(/ AND /i);
741
- return _rebasepro_types.policy.and(...parts.map(sqlToPolicy));
742
- }
743
- const match = trimmed.match(/^(.+?)\s*(!?=)\s*(.+)$/);
744
- if (match) {
745
- const [, leftStr, op, rightStr] = match;
746
- const left = parseOperand(leftStr.trim());
747
- const right = parseOperand(rightStr.trim());
748
- if (left && right) return _rebasepro_types.policy.compare(left, op === "=" ? "eq" : "neq", right);
749
- }
750
- return _rebasepro_types.policy.raw(sql);
751
- }
752
- function parseOperand(str) {
753
- if (/current_setting\s*\(\s*'app\.user_id'\s*\)/i.test(str) || /auth\.uid\(\)/i.test(str)) return _rebasepro_types.policy.authUid();
754
- const stringMatch = str.match(/^'(.+)'$/);
755
- if (stringMatch) return _rebasepro_types.policy.literal(stringMatch[1]);
756
- if (/^\w+$/.test(str)) return _rebasepro_types.policy.field(str);
757
- return null;
758
- }
759
- //#endregion
760
- //#region src/util/policy/securityRuleToConditions.ts
761
- /**
762
- * Desugars a {@link SecurityRule} — its `access`/`ownerField`/`roles` shortcuts,
763
- * structured `condition`/`check`, and raw `using`/`withCheck` — into a single
764
- * normalized {@link PolicyExpression} pair.
765
- *
766
- * **This is the linchpin against drift:** both the Postgres DDL generators and
767
- * the client-side evaluator consume this one function, so there is exactly one
768
- * definition of what a rule means. In particular, application `roles` are folded
769
- * into the expression here (AND'd with the base condition, matching how Postgres
770
- * generates the clause) rather than being handled separately by each consumer.
771
- */
772
- function securityRuleToConditions(rule) {
773
- return {
774
- usingExpr: withRoles(baseUsing(rule), rule),
775
- withCheckExpr: withRoles(baseWithCheck(rule), rule)
776
- };
777
- }
778
- function baseUsing(rule) {
779
- if (rule.condition) return rule.condition;
780
- if (rule.using != null) return sqlToPolicy(rule.using);
781
- if (rule.access === "public") return _rebasepro_types.policy.true();
782
- if (rule.ownerField) return _rebasepro_types.policy.compare(_rebasepro_types.policy.field(rule.ownerField), "eq", _rebasepro_types.policy.authUid());
783
- return null;
784
- }
785
- function baseWithCheck(rule) {
786
- if (rule.check) return rule.check;
787
- if (rule.withCheck != null) return sqlToPolicy(rule.withCheck);
788
- return baseUsing(rule);
789
- }
790
- /**
791
- * AND the base condition with an application-role check, or produce a roles-only
792
- * condition when there is no base. Mirrors the Postgres generator so that a
793
- * role-scoped restrictive rule denies exactly the same set of users on both
794
- * sides.
795
- */
796
- function withRoles(base, rule) {
797
- if (!rule.roles || rule.roles.length === 0) return base;
798
- const rolesExpr = _rebasepro_types.policy.rolesOverlap(rule.roles);
799
- if (rule.mode === "restrictive") return base ? _rebasepro_types.policy.or(_rebasepro_types.policy.not(rolesExpr), base) : _rebasepro_types.policy.not(rolesExpr);
800
- return base ? _rebasepro_types.policy.and(base, rolesExpr) : rolesExpr;
801
- }
802
- //#endregion
803
- //#region src/util/policy/policyToPostgres.ts
804
- /**
805
- * Compiles a {@link PolicyExpression} to a PostgreSQL boolean SQL string,
806
- * suitable for a `USING (...)` / `WITH CHECK (...)` clause.
807
- *
808
- * This is one of the two consumers of the shared policy model (the other being
809
- * {@link evaluatePolicy}); the Postgres schema generators call it so that DDL
810
- * and the admin UI derive from the exact same expression.
811
- */
812
- function policyToPostgres(expr, collection) {
813
- switch (expr.kind) {
814
- case "true": return "true";
815
- case "false": return "false";
816
- case "and": return expr.operands.length === 0 ? "true" : expr.operands.map((o) => `(${policyToPostgres(o, collection)})`).join(" AND ");
817
- case "or": return expr.operands.length === 0 ? "false" : expr.operands.map((o) => `(${policyToPostgres(o, collection)})`).join(" OR ");
818
- case "not":
819
- if (expr.operand.kind === "authenticated") return "auth.uid() IS NULL";
820
- return `NOT (${policyToPostgres(expr.operand, collection)})`;
821
- case "compare": return `${operandToSql(expr.left, collection)} ${COMPARE_SQL[expr.op]} ${operandToSql(expr.right, collection)}`;
822
- case "rolesOverlap": return `string_to_array(auth.roles(), ',') && ${rolesArraySql(expr.roles)}`;
823
- case "rolesContain": return `string_to_array(auth.roles(), ',') @> ${rolesArraySql(expr.roles)}`;
824
- case "authenticated": return "auth.uid() IS NOT NULL";
825
- case "raw": return expr.sql.replace(/\{(\w+)\}/g, (_, col) => col);
826
- }
827
- }
828
- var COMPARE_SQL = {
829
- eq: "=",
830
- neq: "!=",
831
- lt: "<",
832
- lte: "<=",
833
- gt: ">",
834
- gte: ">="
835
- };
836
- function operandToSql(operand, collection) {
837
- switch (operand.kind) {
838
- case "field": return resolveColumnName(operand.name, collection);
839
- case "literal": return quoteLiteral(operand.value);
840
- case "authUid": return "auth.uid()";
841
- case "authRoles": return "string_to_array(auth.roles(), ',')";
842
- }
843
- }
844
- function resolveColumnName(propName, collection) {
845
- const prop = collection?.properties?.[propName];
846
- if (prop && "columnName" in prop && typeof prop.columnName === "string") return prop.columnName;
847
- return (0, _rebasepro_utils.toSnakeCase)(propName);
848
- }
849
- function quoteLiteral(value) {
850
- if (value === null) return "NULL";
851
- if (typeof value === "boolean") return value ? "true" : "false";
852
- if (typeof value === "number") return String(value);
853
- return `'${value.replace(/'/g, "''")}'`;
854
- }
855
- /** Sorted, single-quoted `ARRAY['a','b']` — matches the generators' output. */
856
- function rolesArraySql(roles) {
857
- return `ARRAY[${[...roles].sort().map((r) => `'${r}'`).join(",")}]`;
858
- }
859
- //#endregion
860
- //#region src/util/policy/evaluatePolicy.ts
861
- /**
862
- * Evaluates a {@link PolicyExpression} against a user + row, using three-valued
863
- * (Kleene) logic so that `"unknown"` sub-results propagate soundly.
864
- *
865
- * This is the JavaScript twin of {@link policyToPostgres}: both derive from the
866
- * same expression, so the admin UI matches database enforcement by construction
867
- * for every non-raw rule.
868
- */
869
- function evaluatePolicy(expr, ctx) {
870
- switch (expr.kind) {
871
- case "true": return true;
872
- case "false": return false;
873
- case "and": return kleeneAnd$1(expr.operands.map((o) => evaluatePolicy(o, ctx)));
874
- case "or": return kleeneOr(expr.operands.map((o) => evaluatePolicy(o, ctx)));
875
- case "not": return kleeneNot(evaluatePolicy(expr.operand, ctx));
876
- case "compare": return evaluateCompare(expr.op, expr.left, expr.right, ctx);
877
- case "rolesOverlap": {
878
- const userRoles = ctx.roles ?? [];
879
- return expr.roles.some((r) => r === "public" || userRoles.includes(r));
880
- }
881
- case "rolesContain": {
882
- const userRoles = ctx.roles ?? [];
883
- return expr.roles.every((r) => r === "public" || userRoles.includes(r));
884
- }
885
- case "authenticated": return ctx.uid != null;
886
- case "raw": return "unknown";
887
- }
888
- }
889
- function kleeneAnd$1(values) {
890
- if (values.some((v) => v === false)) return false;
891
- if (values.some((v) => v === "unknown")) return "unknown";
892
- return true;
893
- }
894
- function kleeneOr(values) {
895
- if (values.some((v) => v === true)) return true;
896
- if (values.some((v) => v === "unknown")) return "unknown";
897
- return false;
898
- }
899
- function kleeneNot(value) {
900
- if (value === "unknown") return "unknown";
901
- return !value;
902
- }
903
- function resolveOperand(operand, ctx) {
904
- switch (operand.kind) {
905
- case "literal": return {
906
- known: true,
907
- value: operand.value
908
- };
909
- case "authUid": return {
910
- known: true,
911
- value: ctx.uid ?? null
912
- };
913
- case "authRoles": return {
914
- known: true,
915
- value: ctx.roles ?? []
916
- };
917
- case "field":
918
- if (!ctx.entity) return { known: false };
919
- return {
920
- known: true,
921
- value: ctx.entity.values[operand.name]
922
- };
923
- }
924
- }
925
- function evaluateCompare(op, left, right, ctx) {
926
- const l = resolveOperand(left, ctx);
927
- const r = resolveOperand(right, ctx);
928
- if (!l.known || !r.known) return "unknown";
929
- const a = l.value;
930
- const b = r.value;
931
- if (a === null || b === null) {
932
- if (op === "eq") return false;
933
- if (op === "neq") return true;
934
- return "unknown";
935
- }
936
- if (op === "eq") return a === b;
937
- if (op === "neq") return a !== b;
938
- if (typeof a === "string" && typeof b === "string") {
939
- if (op === "lt") return a < b;
940
- if (op === "lte") return a <= b;
941
- if (op === "gt") return a > b;
942
- if (op === "gte") return a >= b;
943
- }
944
- if (typeof a === "number" && typeof b === "number") {
945
- if (op === "lt") return a < b;
946
- if (op === "lte") return a <= b;
947
- if (op === "gt") return a > b;
948
- if (op === "gte") return a >= b;
949
- }
950
- if (typeof a === "bigint" && typeof b === "bigint") {
951
- if (op === "lt") return a < b;
952
- if (op === "lte") return a <= b;
953
- if (op === "gt") return a > b;
954
- if (op === "gte") return a >= b;
955
- }
956
- return "unknown";
957
- }
958
- //#endregion
959
- //#region src/util/permissions.ts
960
- /** Combine clause results with AND under three-valued (Kleene) logic. */
961
- function kleeneAnd(values) {
962
- if (values.some((v) => v === false)) return false;
963
- if (values.some((v) => v === "unknown")) return "unknown";
964
- return true;
965
- }
966
- /** The operations a rule covers, mirroring the Postgres generator's resolution. */
967
- function ruleOperations(rule) {
968
- return rule.operations && rule.operations.length > 0 ? rule.operations : [rule.operation ?? "all"];
969
- }
970
- function ruleApplies(rule, targetOperation) {
971
- const ops = ruleOperations(rule);
972
- return ops.includes(targetOperation) || ops.includes("all");
973
- }
974
- /**
975
- * Evaluate a single rule for one operation, returning a tri-state.
976
- *
977
- * A `null` clause (the rule contributes no condition for a required clause)
978
- * denies — matching Postgres, which emits `USING (false)` / `WITH CHECK (false)`
979
- * in that case. USING applies to SELECT/UPDATE/DELETE; WITH CHECK to
980
- * INSERT/UPDATE; both must pass for UPDATE.
981
- */
982
- function evaluateRuleForOperation(rule, ctx, targetOperation) {
983
- const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
984
- const clause = (expr) => expr === null ? false : evaluatePolicy(expr, ctx);
985
- const needsUsing = targetOperation !== "insert";
986
- const needsWithCheck = targetOperation === "insert" || targetOperation === "update";
987
- const results = [];
988
- if (needsUsing) results.push(clause(usingExpr));
989
- if (needsWithCheck) results.push(clause(withCheckExpr));
990
- return kleeneAnd(results);
991
- }
992
- function resolveTriState(value, onUnknown) {
993
- if (value === "unknown") return onUnknown === "allow";
994
- return value;
995
- }
996
- /**
997
- * Decide whether an operation is permitted for a user on a (possibly null) row,
998
- * by evaluating the collection's security rules with the shared policy model —
999
- * the same model compiled to Postgres RLS DDL, so the decision matches database
1000
- * enforcement for every non-raw rule.
1001
- *
1002
- * @param options.onUnknown how to treat rules that cannot be decided
1003
- * client-side (raw SQL, or row predicates with no row). Defaults to `"allow"`
1004
- * for optimistic UI gating; enforcement callers should pass `"deny"`.
1005
- */
1006
- function checkOperation(collection, authContext, entity, targetOperation, options) {
1007
- const onUnknown = options?.onUnknown ?? "allow";
1008
- const securityRules = (0, _rebasepro_types.getDataSourceCapabilities)(collection.engine).supportsRLS ? collection.securityRules : void 0;
1009
- if (!securityRules || securityRules.length === 0) return true;
1010
- const applicableRules = securityRules.filter((r) => ruleApplies(r, targetOperation));
1011
- if (applicableRules.length === 0) return false;
1012
- const ctx = {
1013
- uid: authContext.user?.uid,
1014
- roles: authContext.user?.roles ?? [],
1015
- entity
1016
- };
1017
- let grantedByPermissive = false;
1018
- let deniedByRestrictive = false;
1019
- let hasPermissive = false;
1020
- for (const rule of applicableRules) {
1021
- const mode = rule.mode || "permissive";
1022
- const passed = resolveTriState(evaluateRuleForOperation(rule, ctx, targetOperation), onUnknown);
1023
- if (mode === "restrictive") {
1024
- if (!passed) {
1025
- deniedByRestrictive = true;
1026
- break;
1027
- }
1028
- } else {
1029
- hasPermissive = true;
1030
- if (passed) grantedByPermissive = true;
1031
- }
1032
- }
1033
- if (deniedByRestrictive) return false;
1034
- return hasPermissive ? grantedByPermissive : false;
1035
- }
1036
- function canReadCollection(collection, authContext) {
1037
- return checkOperation(collection, authContext, null, "select");
1038
- }
1039
- function canEditEntity(collection, authContext, path, entity) {
1040
- return checkOperation(collection, authContext, entity, "update");
1041
- }
1042
- function canCreateEntity(collection, authContext, path, entity) {
1043
- return checkOperation(collection, authContext, entity, "insert");
1044
- }
1045
- function canDeleteEntity(collection, authContext, path, entity) {
1046
- return checkOperation(collection, authContext, entity, "delete");
1047
- }
1048
- //#endregion
1049
- //#region src/util/references.ts
1050
- function getEntityImagePreviewPropertyKey(collection) {
1051
- for (const key in collection.properties) {
1052
- const property = collection.properties[key];
1053
- if (property.type === "string" && property.storage?.acceptedFiles?.includes("image/*")) return key;
1054
- }
1055
- for (const key in collection.properties) {
1056
- const property = collection.properties[key];
1057
- if (property.type === "array" && !Array.isArray(property.of) && property.of?.type === "string" && property.of.storage?.acceptedFiles?.includes("image/*")) return key;
1058
- }
1059
- for (const key in collection.properties) {
1060
- const property = collection.properties[key];
1061
- if (property.type === "string" && property.ui?.url === "image") return key;
1062
- }
1063
- for (const key in collection.properties) {
1064
- const property = collection.properties[key];
1065
- if (property.type === "array" && property.of && !Array.isArray(property.of) && property.of.type === "string" && property.of.ui?.url === "image") return key;
1066
- }
1067
- for (const key in collection.properties) {
1068
- const property = collection.properties[key];
1069
- if (property.type === "string" && property.storage && !property.storage.acceptedFiles) return key;
1070
- }
1071
- for (const key in collection.properties) {
1072
- const property = collection.properties[key];
1073
- if (property.type === "array" && !Array.isArray(property.of) && property.of?.type === "string" && property.of.storage && !property.of.storage.acceptedFiles) return key;
1074
- }
1075
- }
1076
- //#endregion
1077
- //#region src/util/navigation_utils.ts
1078
- function removeInitialAndTrailingSlashes(s) {
1079
- return removeInitialSlash(removeTrailingSlash(s));
1080
- }
1081
- function removeInitialSlash(s) {
1082
- if (s.startsWith("/")) return s.slice(1);
1083
- else return s;
1084
- }
1085
- function removeTrailingSlash(s) {
1086
- if (s.endsWith("/")) return s.slice(0, -1);
1087
- else return s;
1088
- }
1089
- function addInitialSlash(s) {
1090
- if (s.startsWith("/")) return s;
1091
- else return `/${s}`;
1092
- }
1093
- function getLastSegment(path) {
1094
- const cleanPath = removeInitialAndTrailingSlashes(path);
1095
- if (cleanPath.includes("/")) {
1096
- const segments = cleanPath.split("/");
1097
- return segments[segments.length - 1];
1098
- }
1099
- return cleanPath;
1100
- }
1101
- function resolveCollectionPathIds(path, allCollections) {
1102
- let remainingPath = removeInitialAndTrailingSlashes(path);
1103
- if (!remainingPath) return "";
1104
- let currentCollections = allCollections;
1105
- const resolvedPathParts = [];
1106
- while (remainingPath.length > 0) {
1107
- if (!currentCollections || currentCollections.length === 0) {
1108
- console.warn(`resolveCollectionPathIds: Path structure implies subcollections, but none found before segment starting with "${remainingPath}" in original path "${path}". Appending remaining original path.`);
1109
- resolvedPathParts.push(remainingPath);
1110
- remainingPath = "";
1111
- break;
1112
- }
1113
- let foundMatch = false;
1114
- const potentialMatches = currentCollections.flatMap((col) => [{
1115
- col,
1116
- match: col.slug
1117
- }]).filter((p) => p.match && remainingPath.startsWith(p.match)).sort((a, b) => b.match.length - a.match.length);
1118
- if (potentialMatches.length > 0) {
1119
- const { col: foundCollection, match: matchString } = potentialMatches[0];
1120
- resolvedPathParts.push(foundCollection.slug);
1121
- remainingPath = removeInitialSlash(remainingPath.substring(matchString.length));
1122
- if (remainingPath.length === 0) {
1123
- foundMatch = true;
1124
- break;
1125
- }
1126
- const idSeparatorIndex = remainingPath.indexOf("/");
1127
- let entityId;
1128
- if (idSeparatorIndex > -1) {
1129
- entityId = remainingPath.substring(0, idSeparatorIndex);
1130
- remainingPath = remainingPath.substring(idSeparatorIndex + 1);
1131
- } else {
1132
- entityId = remainingPath;
1133
- remainingPath = "";
1134
- console.warn(`resolveCollectionPathIds: Path seems to end with an entity ID "${entityId}" instead of a collection segment in original path "${path}". This might indicate an invalid input path.`);
1135
- }
1136
- resolvedPathParts.push(entityId);
1137
- currentCollections = getSubcollections(foundCollection);
1138
- foundMatch = true;
1139
- if (!currentCollections && remainingPath.length > 0) {
1140
- console.warn(`resolveCollectionPathIds: Path continues after entity ID "${entityId}", but no subcollections are defined for the preceding collection "${foundCollection.slug}" in path "${path}". Appending remaining original path.`);
1141
- resolvedPathParts.push(remainingPath);
1142
- remainingPath = "";
1143
- break;
1144
- }
1145
- }
1146
- if (!foundMatch) {
1147
- console.warn(`resolveCollectionPathIds: Collection definition not found for segment starting with "${remainingPath}" in original path "${path}". Appending remaining original path.`);
1148
- resolvedPathParts.push(remainingPath);
1149
- remainingPath = "";
1150
- break;
1151
- }
1152
- }
1153
- return resolvedPathParts.join("/");
1154
- }
1155
- /**
1156
- * Find the corresponding view at any depth for a given path.
1157
- * Note that path or segments of the paths can be collection aliases.
1158
- * @param slugOrPath
1159
- * @param collections
1160
- */
1161
- function getCollectionBySlugWithin(slugOrPath, collections) {
1162
- const subpaths = removeInitialAndTrailingSlashes(slugOrPath).split("/");
1163
- if (subpaths.length % 2 === 0) throw Error(`getCollectionBySlug: Collection paths must have an odd number of segments: ${slugOrPath}`);
1164
- const subpathCombinations = getCollectionPathsCombinations(subpaths);
1165
- let result;
1166
- for (let i = 0; i < subpathCombinations.length; i++) {
1167
- const subpathCombination = subpathCombinations[i];
1168
- const navigationEntry = collections && collections.sort((a, b) => (a.slug ?? "").localeCompare(b.slug ?? "")).find((entry) => entry.slug === subpathCombination);
1169
- if (navigationEntry) {
1170
- if (subpathCombination === slugOrPath) result = navigationEntry;
1171
- else if (getSubcollections(navigationEntry).length > 0) {
1172
- const newPath = slugOrPath.replace(subpathCombination, "").split("/").slice(2).join("/");
1173
- if (newPath.length > 0) result = getCollectionBySlugWithin(newPath, getSubcollections(navigationEntry));
1174
- }
1175
- }
1176
- if (result) break;
1177
- }
1178
- return result;
1179
- }
1180
- /**
1181
- * Get the subcollection combinations from a path:
1182
- * "sites/es/locales" => ["sites/es/locales", "sites"]
1183
- * @param subpaths
1184
- */
1185
- function getCollectionPathsCombinations(subpaths) {
1186
- const entries = subpaths.length > 0 && subpaths.length % 2 === 0 ? subpaths.splice(0, subpaths.length - 1) : subpaths;
1187
- const length = entries.length;
1188
- const result = [];
1189
- for (let i = length; i > 0; i = i - 2) result.push(entries.slice(0, i).join("/"));
1190
- return result;
1191
- }
1192
- //#endregion
1193
- //#region src/util/navigation_from_path.ts
1194
- function getNavigationEntriesFromPath(props) {
1195
- const { path, collections = [], currentFullPath } = props;
1196
- const subpathCombinations = getCollectionPathsCombinations(removeInitialAndTrailingSlashes(path).split("/"));
1197
- const result = [];
1198
- for (let i = 0; i < subpathCombinations.length; i++) {
1199
- const subpathCombination = subpathCombinations[i];
1200
- const collection = collections && collections.find((entry) => entry.slug === subpathCombination);
1201
- if (collection) {
1202
- const collectionPath = currentFullPath && currentFullPath.length > 0 ? currentFullPath + "/" + collection.slug : collection.slug;
1203
- result.push({
1204
- type: "collection",
1205
- id: collection.slug,
1206
- slug: collectionPath,
1207
- path: collectionPath,
1208
- collection
1209
- });
1210
- const restOfThePath = removeInitialAndTrailingSlashes(removeInitialAndTrailingSlashes(path).replace(subpathCombination, ""));
1211
- const nextSegments = restOfThePath.length > 0 ? restOfThePath.split("/") : [];
1212
- if (nextSegments.length > 0) {
1213
- const entityId = nextSegments[0];
1214
- const path = collectionPath + "/" + entityId;
1215
- result.push({
1216
- type: "entity",
1217
- entityId,
1218
- slug: collectionPath,
1219
- path,
1220
- parentCollection: collection
1221
- });
1222
- if (nextSegments.length > 1) {
1223
- const newPath = nextSegments.slice(1).join("/");
1224
- if (!collection) throw Error("collection not found resolving path: " + collection);
1225
- const entityViews = collection.entityViews;
1226
- const customView = entityViews && entityViews.map((entry) => resolveEntityView(entry, props.contextEntityViews)).filter((v) => v != null).find((entry) => entry.key === newPath);
1227
- const subcollections = getSubcollections(collection);
1228
- if (customView) result.push({
1229
- type: "custom_view",
1230
- slug: collectionPath,
1231
- entityId,
1232
- path: path + "/" + customView.key,
1233
- view: customView
1234
- });
1235
- else if (subcollections) result.push(...getNavigationEntriesFromPath({
1236
- path: newPath,
1237
- collections: subcollections,
1238
- currentFullPath: path,
1239
- contextEntityViews: props.contextEntityViews
1240
- }));
1241
- }
1242
- }
1243
- break;
1244
- }
1245
- }
1246
- return result;
1247
- }
1248
- function resolveEntityView(entityView, contextEntityViews) {
1249
- if (typeof entityView === "string") return contextEntityViews?.find((entry) => entry.key === entityView);
1250
- else return entityView;
1251
- }
1252
- //#endregion
1253
- //#region src/util/parent_references_from_path.ts
1254
- function getParentReferencesFromPath(props) {
1255
- const { path, collections = [], currentFullPath } = props;
1256
- const subpathCombinations = getCollectionPathsCombinations(removeInitialAndTrailingSlashes(path).split("/"));
1257
- const result = [];
1258
- for (let i = 0; i < subpathCombinations.length; i++) {
1259
- const subpathCombination = subpathCombinations[i];
1260
- const collection = collections && collections.find((entry) => entry.slug === subpathCombination);
1261
- if (collection) {
1262
- const collectionPath = currentFullPath && currentFullPath.length > 0 ? currentFullPath + "/" + collection.slug : collection.slug;
1263
- const restOfThePath = removeInitialAndTrailingSlashes(removeInitialAndTrailingSlashes(path).replace(subpathCombination, ""));
1264
- const nextSegments = restOfThePath.length > 0 ? restOfThePath.split("/") : [];
1265
- if (nextSegments.length > 0) {
1266
- const entityId = nextSegments[0];
1267
- const path = collectionPath + "/" + entityId;
1268
- result.push(new _rebasepro_types.EntityReference({
1269
- id: entityId,
1270
- path: collectionPath
1271
- }));
1272
- if (nextSegments.length > 1) {
1273
- const newPath = nextSegments.slice(1).join("/");
1274
- if (!collection) throw Error("collection not found resolving path: " + collection);
1275
- if (getSubcollections(collection).length > 0) result.push(...getParentReferencesFromPath({
1276
- path: newPath,
1277
- collections: getSubcollections(collection),
1278
- currentFullPath: path
1279
- }));
1280
- }
1281
- }
1282
- break;
1283
- }
1284
- }
1285
- return result;
1286
- }
1287
- //#endregion
1288
- //#region src/util/builders.ts
1289
- /**
1290
- * Identity function we use to defeat the type system of Typescript and build
1291
- * collection views with all its properties
1292
- * @param collection
1293
- * @group Builder
1294
- */
1295
- function buildCollection(collection) {
1296
- return collection;
1297
- }
1298
- /**
1299
- * Implementation — delegates to the correct overload at the type level.
1300
- * At runtime this is a plain identity function.
1301
- */
1302
- function defineCollection(collection) {
1303
- return collection;
1304
- }
1305
- /**
1306
- * Identity function we use to defeat the type system of Typescript and preserve
1307
- * the property keys.
1308
- * @param property
1309
- * @group Builder
1310
- */
1311
- function buildProperty(property) {
1312
- return property;
1313
- }
1314
- /**
1315
- * Identity function we use to defeat the type system of Typescript and preserve
1316
- * the properties keys.
1317
- * @param properties
1318
- * @group Builder
1319
- */
1320
- function buildProperties(properties) {
1321
- return properties;
1322
- }
1323
- /**
1324
- * Identity function we use to defeat the type system of Typescript and preserve
1325
- * the properties keys.
1326
- * @param propertiesOrBuilder
1327
- * @group Builder
1328
- */
1329
- function buildPropertiesOrBuilder(propertiesOrBuilder) {
1330
- return propertiesOrBuilder;
1331
- }
1332
- /**
1333
- * Identity function we use to defeat the type system of Typescript and preserve
1334
- * the properties keys.
1335
- * @param enumValues
1336
- * @group Builder
1337
- */
1338
- function buildEnum(enumValues) {
1339
- return enumValues;
1340
- }
1341
- /**
1342
- * Identity function we use to defeat the type system of Typescript and preserve
1343
- * the properties keys.
1344
- * @param enumValueConfig
1345
- * @group Builder
1346
- */
1347
- function buildEnumValueConfig(enumValueConfig) {
1348
- return enumValueConfig;
1349
- }
1350
- /**
1351
- * Identity function we use to defeat the type system of Typescript and preserve
1352
- * the properties keys.
1353
- * @param callbacks
1354
- * @group Builder
1355
- */
1356
- function buildEntityCallbacks(callbacks) {
1357
- return callbacks;
1358
- }
1359
- /**
1360
- * Identity function we use to defeat the type system of Typescript and build
1361
- * additional field delegates views with all its properties
1362
- * @param additionalFieldDelegate
1363
- * @group Builder
1364
- */
1365
- function buildAdditionalFieldDelegate(additionalFieldDelegate) {
1366
- return additionalFieldDelegate;
1367
- }
1368
- //#endregion
1369
- //#region src/util/storage.ts
1370
- /**
1371
- * Resolve the {@link StorageSource} to use for a property, given the key
1372
- * referenced by `StorageConfig.storageSource`.
1373
- *
1374
- * Resolution priority:
1375
- * 1. No `sourceKey` → the default source (backward compatible).
1376
- * 2. An explicit {@link StorageSourceRegistry} (e.g. `client.storageRegistry`).
1377
- * 3. A `sources` lookup map (e.g. the `StorageSourcesContext`).
1378
- * 4. Fall back to the default source.
1379
- *
1380
- * Shared by the upload hook, the markdown editor, and the read-only previews
1381
- * so the resolution logic lives in one place.
1382
- *
1383
- * @group Storage
1384
- */
1385
- function resolveStorageSource(params) {
1386
- const { sourceKey, sources, registry, defaultSource } = params;
1387
- if (!sourceKey) return defaultSource;
1388
- if (registry) return registry.getOrDefault(sourceKey);
1389
- const fromSources = sources?.[sourceKey];
1390
- if (fromSources) return fromSources;
1391
- return defaultSource;
1392
- }
1393
- async function resolveStorageFilenameString({ input, storage, values, entityId, path, property, file, propertyKey }) {
1394
- let result;
1395
- if (typeof input === "function") {
1396
- result = await input({
1397
- path,
1398
- entityId,
1399
- values,
1400
- property,
1401
- file,
1402
- storage,
1403
- propertyKey
1404
- });
1405
- if (!result) console.warn("Storage callback returned empty result. Using default name value");
1406
- } else result = replacePlaceholders({
1407
- file,
1408
- input,
1409
- entityId,
1410
- propertyKey,
1411
- path
1412
- });
1413
- if (!result) result = (0, _rebasepro_utils.randomString)() + "_" + file.name;
1414
- return result;
1415
- }
1416
- function resolveStoragePathString({ input, storage, values, entityId, path, property, file, propertyKey }) {
1417
- let result;
1418
- if (typeof input === "function") {
1419
- result = input({
1420
- path,
1421
- entityId,
1422
- values,
1423
- property,
1424
- file,
1425
- storage,
1426
- propertyKey
1427
- });
1428
- if (!result) console.warn("Storage callback returned empty result. Using default name value");
1429
- } else result = replacePlaceholders({
1430
- file,
1431
- input,
1432
- entityId,
1433
- propertyKey,
1434
- path
1435
- });
1436
- if (!result) result = (0, _rebasepro_utils.randomString)() + "_" + file.name;
1437
- return result;
1438
- }
1439
- function replacePlaceholders({ file, input, entityId, propertyKey, path }) {
1440
- const ext = file.name.split(".").pop();
1441
- let result = input.replace("{propertyKey}", propertyKey).replace("{rand}", (0, _rebasepro_utils.randomString)()).replace("{file}", file.name).replace("{file.type}", file.type);
1442
- if (entityId) result = result.replace("{entityId}", String(entityId));
1443
- if (path) result = result.replace("{path}", path);
1444
- if (ext) {
1445
- result = result.replace("{file.ext}", ext);
1446
- const name = file.name.replace(`.${ext}`, "");
1447
- result = result.replace("{file.name}", name);
1448
- }
1449
- if (!result) result = (0, _rebasepro_utils.randomString)() + "_" + file.name;
1450
- return result;
1451
- }
1452
- //#endregion
1453
- //#region src/util/callbacks.ts
1454
- /**
1455
- * Helper function to recursively check if there are any callbacks in the properties.
1456
- */
1457
- function hasPropertyCallbacks(properties, callbackName) {
1458
- if (!properties) return false;
1459
- for (const property of Object.values(properties)) {
1460
- if (property.callbacks?.[callbackName]) return true;
1461
- if (property.type === "map" && property.properties) {
1462
- if (hasPropertyCallbacks(property.properties, callbackName)) return true;
1463
- } else if (property.type === "array" && property.of) {
1464
- const ofs = Array.isArray(property.of) ? property.of : [property.of];
1465
- for (const of of ofs) {
1466
- if (of.callbacks?.[callbackName]) return true;
1467
- if (of.type === "map" && of.properties && hasPropertyCallbacks(of.properties, callbackName)) return true;
1468
- }
1469
- }
1470
- }
1471
- return false;
1472
- }
1473
- /**
1474
- * Recursively process properties to apply field-level hooks.
1475
- */
1476
- async function processProperties(properties, values, previousValues, propsContext, callbackName) {
1477
- if (!values || typeof values !== "object") return values;
1478
- const result = { ...values };
1479
- for (const [key, property] of Object.entries(properties)) {
1480
- if (result[key] === void 0) continue;
1481
- let currentValue = result[key];
1482
- const previousValue = previousValues?.[key];
1483
- if (property.type === "array" && Array.isArray(currentValue)) {
1484
- if (property.of && !Array.isArray(property.of)) currentValue = await Promise.all(currentValue.map(async (item, index) => {
1485
- const prevItem = Array.isArray(previousValue) ? previousValue[index] : void 0;
1486
- return (await processProperties({ "_tmp": property.of }, { "_tmp": item }, { "_tmp": prevItem }, propsContext, callbackName))["_tmp"];
1487
- }));
1488
- } else if (property.type === "map" && property.properties && typeof currentValue === "object") currentValue = await processProperties(property.properties, currentValue, previousValue ?? {}, propsContext, callbackName);
1489
- if (property.callbacks?.[callbackName]) {
1490
- const cbRes = await Promise.resolve(property.callbacks[callbackName]({
1491
- ...propsContext,
1492
- value: currentValue,
1493
- previousValue
1494
- }));
1495
- if (cbRes !== void 0) currentValue = cbRes;
1496
- }
1497
- result[key] = currentValue;
1498
- }
1499
- return result;
1500
- }
1501
- /**
1502
- * Helper function to extract field-level PropertyCallbacks from a properties schema
1503
- * and wrap them into an EntityCallbacks object recursively.
1504
- */
1505
- var buildPropertyCallbacks = (properties) => {
1506
- if (!properties) return void 0;
1507
- const propertyCallbacks = {};
1508
- if (hasPropertyCallbacks(properties, "afterRead")) propertyCallbacks.afterRead = async (props) => {
1509
- const processedValues = await processProperties(properties, props.entity.values, props.entity.values, props, "afterRead");
1510
- return {
1511
- ...props.entity,
1512
- values: processedValues
1513
- };
1514
- };
1515
- if (hasPropertyCallbacks(properties, "beforeSave")) propertyCallbacks.beforeSave = async (props) => {
1516
- return await processProperties(properties, props.values, props.previousValues ?? {}, props, "beforeSave");
1517
- };
1518
- return Object.keys(propertyCallbacks).length > 0 ? propertyCallbacks : void 0;
1519
- };
1520
- //#endregion
1521
- //#region src/util/conditions.ts
1522
- /**
1523
- * Access a nested property from an object via dot notation.
1524
- */
1525
- function getIn(obj, path) {
1526
- if (!obj || !path) return void 0;
1527
- return path.split(".").reduce((acc, part) => acc && acc[part], obj);
1528
- }
1529
- var operationsRegistered = false;
1530
- /**
1531
- * Register custom JSON Logic operations for Rebase.
1532
- * Call this once at app initialization.
1533
- */
1534
- function registerConditionOperations() {
1535
- if (operationsRegistered) return;
1536
- json_logic_js.default.add_operation("hasRole", function(roleId) {
1537
- return this?.user?.roles?.includes(roleId) ?? false;
1538
- });
1539
- json_logic_js.default.add_operation("hasAnyRole", function(roleIds) {
1540
- if (!this?.user?.roles || !Array.isArray(roleIds)) return false;
1541
- return roleIds.some((role) => this.user.roles.includes(role));
1542
- });
1543
- json_logic_js.default.add_operation("isToday", (timestamp) => {
1544
- if (!timestamp) return false;
1545
- const date = new Date(timestamp);
1546
- const today = /* @__PURE__ */ new Date();
1547
- return date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate();
1548
- });
1549
- json_logic_js.default.add_operation("isPast", (timestamp) => {
1550
- if (!timestamp) return false;
1551
- return timestamp < Date.now();
1552
- });
1553
- json_logic_js.default.add_operation("isFuture", (timestamp) => {
1554
- if (!timestamp) return false;
1555
- return timestamp > Date.now();
1556
- });
1557
- operationsRegistered = true;
1558
- }
1559
- /**
1560
- * Evaluate a JSON Logic rule against the given context.
1561
- */
1562
- function evaluateCondition(rule, context) {
1563
- registerConditionOperations();
1564
- return json_logic_js.default.apply(rule, context);
1565
- }
1566
- /**
1567
- * Convert a value to a format suitable for JSON Logic evaluation.
1568
- * Specifically handles Date objects by converting them to Unix timestamps.
1569
- */
1570
- function serializeValueForConditions(value) {
1571
- if (value === null || value === void 0) return value;
1572
- if (value instanceof Date) return value.getTime();
1573
- if (typeof value?.toMillis === "function") return value.toMillis();
1574
- if (typeof value?.toDate === "function") return value.toDate().getTime();
1575
- if (Array.isArray(value)) return value.map(serializeValueForConditions);
1576
- if (typeof value === "object") {
1577
- const result = {};
1578
- for (const key of Object.keys(value)) result[key] = serializeValueForConditions(value[key]);
1579
- return result;
1580
- }
1581
- return value;
1582
- }
1583
- /**
1584
- * Build a ConditionContext from the current property resolution context.
1585
- */
1586
- function buildConditionContext(params) {
1587
- const { propertyKey, values, previousValues, path, entityId, index, authController } = params;
1588
- const user = authController.user;
1589
- const serializedValues = serializeValueForConditions(values ?? {});
1590
- return {
1591
- values: serializedValues,
1592
- previousValues: serializeValueForConditions(previousValues ?? values ?? {}),
1593
- propertyValue: propertyKey ? getIn(serializedValues, propertyKey) : void 0,
1594
- path,
1595
- entityId,
1596
- isNew: !entityId,
1597
- index,
1598
- user: {
1599
- uid: user?.uid ?? "",
1600
- email: user?.email ?? null,
1601
- displayName: user?.displayName ?? null,
1602
- photoURL: user?.photoURL ?? null,
1603
- roles: (user?.roles ?? []).map((r) => typeof r === "string" ? r : r.id)
1604
- },
1605
- now: Date.now()
1606
- };
1607
- }
1608
- /**
1609
- * Apply PropertyConditions to a resolved property, evaluating all JSON Logic rules.
1610
- */
1611
- function applyPropertyConditions(property, context) {
1612
- const { conditions } = property;
1613
- if (!conditions) return property;
1614
- const result = { ...property };
1615
- if (conditions.disabled) {
1616
- if (evaluateCondition(conditions.disabled, context)) {
1617
- result.ui = result.ui || {};
1618
- result.ui.disabled = {
1619
- clearOnDisabled: conditions.clearOnDisabled ?? false,
1620
- disabledMessage: conditions.disabledMessage,
1621
- hidden: false
1622
- };
1623
- }
1624
- }
1625
- if (conditions.hidden) {
1626
- if (evaluateCondition(conditions.hidden, context)) {
1627
- result.ui = result.ui || {};
1628
- result.ui.disabled = {
1629
- ...typeof result.ui?.disabled === "object" ? result.ui.disabled : {},
1630
- hidden: true,
1631
- clearOnDisabled: conditions.clearOnDisabled ?? false
1632
- };
1633
- }
1634
- }
1635
- if (conditions.readOnly) {
1636
- if (evaluateCondition(conditions.readOnly, context)) {
1637
- result.ui = result.ui || {};
1638
- result.ui.readOnly = true;
1639
- }
1640
- }
1641
- if (conditions.required !== void 0) {
1642
- const isRequired = evaluateCondition(conditions.required, context);
1643
- result.validation = {
1644
- ...result.validation,
1645
- required: isRequired,
1646
- requiredMessage: conditions.requiredMessage
1647
- };
1648
- }
1649
- if (context.isNew && conditions.defaultValue !== void 0) result.defaultValue = evaluateCondition(conditions.defaultValue, context);
1650
- if ("enum" in result && result.enum && (conditions.enumConditions || conditions.allowedEnumValues || conditions.excludedEnumValues)) result.enum = applyEnumConditions(result.enum, conditions, context);
1651
- if (result.type === "reference") {
1652
- if (conditions.referencePath) result.path = evaluateCondition(conditions.referencePath, context);
1653
- if (conditions.referenceFilter) result.fixedFilter = evaluateCondition(conditions.referenceFilter, context);
1654
- }
1655
- if (result.type === "array") {
1656
- if (conditions.canAddElements !== void 0) result.canAddElements = evaluateCondition(conditions.canAddElements, context);
1657
- if (conditions.sortable !== void 0) result.sortable = evaluateCondition(conditions.sortable, context);
1658
- }
1659
- return result;
1660
- }
1661
- /**
1662
- * Convert an object with numeric keys back to an array.
1663
- * Firestore stores arrays as {"0": "a", "1": "b"} to avoid nested arrays.
1664
- */
1665
- function objectToArray(obj) {
1666
- if (Array.isArray(obj)) return obj.map(String);
1667
- if (obj && typeof obj === "object") {
1668
- const keys = Object.keys(obj);
1669
- if (keys.length > 0 && keys.every((k) => !isNaN(Number(k)))) return keys.sort((a, b) => Number(a) - Number(b)).map((k) => obj[k]).filter((v) => typeof v === "string" || typeof v === "number").map(String);
1670
- }
1671
- return [];
1672
- }
1673
- /**
1674
- * Apply enum-specific conditions to filter and modify enum values.
1675
- */
1676
- function applyEnumConditions(enumValues, conditions, context) {
1677
- let result = [...enumValues];
1678
- if (conditions.allowedEnumValues) {
1679
- const allowedArray = objectToArray(evaluateCondition(conditions.allowedEnumValues, context));
1680
- if (allowedArray.length > 0) result = result.filter((ev) => allowedArray.includes(String(ev.id)));
1681
- }
1682
- if (conditions.excludedEnumValues) {
1683
- const excludedArray = objectToArray(evaluateCondition(conditions.excludedEnumValues, context));
1684
- if (excludedArray.length > 0) result = result.filter((ev) => !excludedArray.includes(String(ev.id)));
1685
- }
1686
- if (conditions.enumConditions) result = result.map((ev) => {
1687
- const evConditions = conditions.enumConditions?.[ev.id];
1688
- if (!evConditions) return ev;
1689
- if (evConditions.hidden && evaluateCondition(evConditions.hidden, context)) return null;
1690
- if (evConditions.disabled && evaluateCondition(evConditions.disabled, context)) return {
1691
- ...ev,
1692
- disabled: true
1693
- };
1694
- return ev;
1695
- }).filter((ev) => ev !== null);
1696
- return result;
1697
- }
1698
- //#endregion
1699
- //#region src/data/resolveDataSource.ts
1700
- /**
1701
- * Build a keyed registry from a list of {@link DataSourceDefinition}s.
1702
- * Later entries win on key collision.
1703
- */
1704
- function createDataSourceRegistry(definitions) {
1705
- const registry = {};
1706
- for (const def of definitions ?? []) registry[def.key] = def;
1707
- return registry;
1708
- }
1709
- /**
1710
- * Resolve the effective data source for a collection — the single source of
1711
- * truth shared by the frontend router, the backend driver registry, and the
1712
- * editor's capability lookups.
1713
- *
1714
- * Resolution order:
1715
- * 1. The routing **key** is `collection.dataSource`, else
1716
- * {@link DEFAULT_DATA_SOURCE_KEY}.
1717
- * 2. If a definition is registered for that key, it provides `engine`,
1718
- * `transport`, and `databaseId`.
1719
- * 3. Otherwise values are synthesized: `engine` from `collection.engine`
1720
- * (or the key, or `"postgres"`), `transport` defaults to `"server"`,
1721
- * and `databaseId` from the collection.
1722
- *
1723
- * `capabilities` are always derived from the resolved `engine`, so two
1724
- * data sources sharing an engine share capabilities.
1725
- *
1726
- * @param collection the collection (or any object carrying the routing fields)
1727
- * @param registry optional registry of declared data sources
1728
- */
1729
- function resolveDataSource(collection, registry) {
1730
- const key = collection?.dataSource ?? _rebasepro_types.DEFAULT_DATA_SOURCE_KEY;
1731
- const def = registry?.[key];
1732
- const engine = def?.engine ?? collection?.engine ?? (key !== _rebasepro_types.DEFAULT_DATA_SOURCE_KEY ? key : "postgres");
1733
- return {
1734
- key,
1735
- engine,
1736
- transport: def?.transport ?? "server",
1737
- databaseId: collection?.databaseId ?? def?.databaseId,
1738
- capabilities: (0, _rebasepro_types.getDataSourceCapabilities)(engine)
1739
- };
1740
- }
1741
- //#endregion
1742
- //#region src/collections/CollectionRegistry.ts
1743
- var CollectionRegistry = class {
1744
- /**
1745
- * Declared data sources, used during normalization to resolve each
1746
- * collection's engine (so `dataSource`-only collections get the right
1747
- * capabilities). Empty by default.
1748
- */
1749
- dataSources = {};
1750
- /**
1751
- * Global lifecycle callbacks applied to every collection.
1752
- * Runs on all data paths (REST, WebSocket, `rebase.data`).
1753
- * Execution order: global → collection → property callbacks.
1754
- */
1755
- _globalCallbacks;
1756
- /**
1757
- * Set global lifecycle callbacks that apply to every collection.
1758
- * Typically called once during backend initialization.
1759
- */
1760
- setGlobalCallbacks(callbacks) {
1761
- this._globalCallbacks = callbacks;
1762
- }
1763
- /**
1764
- * Get the currently registered global callbacks, if any.
1765
- */
1766
- getGlobalCallbacks() {
1767
- return this._globalCallbacks;
1768
- }
1769
- collectionsByTableName = /* @__PURE__ */ new Map();
1770
- collectionsBySlug = /* @__PURE__ */ new Map();
1771
- rootCollections = [];
1772
- cachedCollectionsList = null;
1773
- rawCollectionsByTableName = /* @__PURE__ */ new Map();
1774
- rawCollectionsBySlug = /* @__PURE__ */ new Map();
1775
- rawRootCollections = [];
1776
- cachedRawCollectionsList = null;
1777
- lastRawInputSnapshot = null;
1778
- constructor(collections, dataSources) {
1779
- if (dataSources) this.dataSources = dataSources;
1780
- if (collections) this.registerMultiple(collections);
1781
- }
1782
- /**
1783
- * Provide the declared data sources used to resolve each collection's
1784
- * engine during normalization. Set this before registering collections.
1785
- * Returns true if the registry changed (callers may re-register).
1786
- */
1787
- setDataSources(dataSources) {
1788
- if ((0, fast_equals.deepEqual)(this.dataSources, dataSources)) return false;
1789
- this.dataSources = dataSources ?? {};
1790
- return true;
1791
- }
1792
- reset() {
1793
- this.collectionsByTableName.clear();
1794
- this.collectionsBySlug.clear();
1795
- this.rootCollections = [];
1796
- this.cachedCollectionsList = null;
1797
- this.rawCollectionsByTableName.clear();
1798
- this.rawCollectionsBySlug.clear();
1799
- this.rawRootCollections = [];
1800
- this.cachedRawCollectionsList = null;
1801
- }
1802
- /**
1803
- * Registers a collection and its subcollections recursively.
1804
- * Returns true if the collections have changed, false otherwise.
1805
- *
1806
- * Idempotent: compares the raw input (before normalization) against a stored
1807
- * snapshot. Only re-normalizes and re-registers when the raw input actually changed.
1808
- * @param collections
1809
- */
1810
- registerMultiple(collections) {
1811
- const rawSnapshot = collections.map((c) => (0, _rebasepro_utils.removeFunctions)(c));
1812
- if (this.lastRawInputSnapshot && (0, fast_equals.deepEqual)(this.lastRawInputSnapshot, rawSnapshot)) return false;
1813
- this.reset();
1814
- collections.forEach((c) => {
1815
- if (c.slug) this.collectionsBySlug.set(c.slug, c);
1816
- this.collectionsByTableName.set(getTableName(c), c);
1817
- });
1818
- const normalizedCollections = collections.map((c) => this.normalizeCollection({ ...c }));
1819
- normalizedCollections.forEach((c, index) => {
1820
- const raw = (0, _rebasepro_utils.deepClone)(collections[index]);
1821
- this.rootCollections.push(c);
1822
- this.rawRootCollections.push(raw);
1823
- const normalized = this.normalizeCollection(c);
1824
- this.collectionsByTableName.set(getTableName(normalized), normalized);
1825
- this.rawCollectionsByTableName.set(getTableName(raw), raw);
1826
- if (normalized.slug) this.collectionsBySlug.set(normalized.slug, normalized);
1827
- if (raw.slug) this.rawCollectionsBySlug.set(raw.slug, raw);
1828
- });
1829
- normalizedCollections.forEach((c) => {
1830
- const subcollections = getSubcollections(c);
1831
- if (subcollections && subcollections.length > 0) subcollections.forEach((subCollection) => {
1832
- if (!subCollection) return;
1833
- this._registerRecursively(this.normalizeCollection({ ...subCollection }), (0, _rebasepro_utils.deepClone)(subCollection));
1834
- });
1835
- });
1836
- this.lastRawInputSnapshot = rawSnapshot;
1837
- return true;
1838
- }
1839
- register(collection, rawCollection) {
1840
- const raw = rawCollection ? (0, _rebasepro_utils.deepClone)(rawCollection) : (0, _rebasepro_utils.deepClone)(collection);
1841
- this.rootCollections.push(collection);
1842
- this.rawRootCollections.push(raw);
1843
- this._registerRecursively(collection, raw);
1844
- }
1845
- _registerRecursively(collection, rawCollection) {
1846
- if (this.collectionsByTableName.has(getTableName(collection))) return;
1847
- const normalizedCollection = this.normalizeCollection(collection);
1848
- this.collectionsByTableName.set(getTableName(normalizedCollection), normalizedCollection);
1849
- this.rawCollectionsByTableName.set(getTableName(rawCollection), rawCollection);
1850
- if (normalizedCollection.slug) this.collectionsBySlug.set(normalizedCollection.slug, normalizedCollection);
1851
- if (rawCollection.slug) this.rawCollectionsBySlug.set(rawCollection.slug, rawCollection);
1852
- const subcollections = getSubcollections(normalizedCollection);
1853
- if (subcollections && subcollections.length > 0) subcollections.forEach((subCollection) => {
1854
- if (!subCollection) return;
1855
- this._registerRecursively(this.normalizeCollection({ ...subCollection }), (0, _rebasepro_utils.deepClone)(subCollection));
1856
- });
1857
- }
1858
- normalizeCollection(collection) {
1859
- const result = { ...collection };
1860
- {
1861
- const resolved = resolveDataSource(result, this.dataSources);
1862
- if (!result.dataSource) result.dataSource = resolved.key;
1863
- if (!result.engine) result.engine = resolved.engine;
1864
- }
1865
- const extractedRelations = this.extractRelationsFromProperties(result.properties);
1866
- const relResult = result;
1867
- const manualRelations = (0, _rebasepro_types.getDataSourceCapabilities)(result.engine).supportsRelations ? relResult.relations ?? [] : [];
1868
- const mergedRelationsRaw = [...extractedRelations];
1869
- for (const manual of manualRelations) {
1870
- const name = manual.relationName;
1871
- if (!name) mergedRelationsRaw.push(manual);
1872
- else {
1873
- const existingIndex = mergedRelationsRaw.findIndex((r) => r.relationName === name);
1874
- if (existingIndex === -1) mergedRelationsRaw.push(manual);
1875
- else mergedRelationsRaw[existingIndex] = {
1876
- ...manual,
1877
- ...mergedRelationsRaw[existingIndex]
1878
- };
1879
- }
1880
- }
1881
- let mergedRelations = mergedRelationsRaw;
1882
- if ((0, _rebasepro_types.getDataSourceCapabilities)(result.engine).supportsRelations) {
1883
- mergedRelations = mergedRelationsRaw.map((r) => {
1884
- try {
1885
- return sanitizeRelation(r, result, (slug) => this.get(slug));
1886
- } catch {
1887
- return r;
1888
- }
1889
- });
1890
- relResult.relations = mergedRelations;
1891
- }
1892
- result.properties = this.normalizeProperties(result.properties, mergedRelations);
1893
- if (!result.childCollections) {
1894
- const capabilities = (0, _rebasepro_types.getDataSourceCapabilities)(result.engine);
1895
- const declaredSubcollections = (0, _rebasepro_types.getDeclaredSubcollections)(result);
1896
- if (capabilities.supportsSubcollections && declaredSubcollections) result.childCollections = declaredSubcollections;
1897
- else if (capabilities.supportsRelations && relResult.relations) {
1898
- const manyRelations = relResult.relations.filter((r) => r.cardinality === "many");
1899
- if (manyRelations.length > 0) result.childCollections = () => manyRelations.map((r) => {
1900
- const target = r.target();
1901
- return r.overrides ? (0, _rebasepro_utils.mergeDeep)(target, r.overrides) : target;
1902
- });
1903
- }
1904
- }
1905
- return result;
1906
- }
1907
- /**
1908
- * Extract Relation[] from properties that have inline relation config (i.e. `target` is set).
1909
- * This allows developers to define relations directly on properties without a separate
1910
- * `relations[]` entry on the collection.
1911
- */
1912
- extractRelationsFromProperties(properties) {
1913
- const relations = [];
1914
- for (const [key, property] of Object.entries(properties)) if (property.type === "relation") {
1915
- const relProp = property;
1916
- const target = relProp.target ?? relProp.relation?.target;
1917
- if (target) {
1918
- const relationName = relProp.relationName ?? relProp.relation?.relationName ?? key;
1919
- relations.push({
1920
- relationName,
1921
- target,
1922
- cardinality: relProp.cardinality ?? relProp.relation?.cardinality ?? "one",
1923
- direction: relProp.direction ?? relProp.relation?.direction ?? "owning",
1924
- inverseRelationName: relProp.inverseRelationName ?? relProp.relation?.inverseRelationName,
1925
- localKey: relProp.localKey ?? relProp.relation?.localKey,
1926
- foreignKeyOnTarget: relProp.foreignKeyOnTarget ?? relProp.relation?.foreignKeyOnTarget,
1927
- through: relProp.through ?? relProp.relation?.through,
1928
- joinPath: relProp.joinPath ?? relProp.relation?.joinPath,
1929
- onUpdate: relProp.onUpdate ?? relProp.relation?.onUpdate,
1930
- onDelete: relProp.onDelete ?? relProp.relation?.onDelete,
1931
- overrides: relProp.overrides ?? relProp.relation?.overrides
1932
- });
1933
- }
1934
- } else if (property.type === "map" && property.properties) relations.push(...this.extractRelationsFromProperties(property.properties));
1935
- return relations;
1936
- }
1937
- normalizeProperties(properties, relations) {
1938
- const newProperties = {};
1939
- for (const key in properties) newProperties[key] = this.normalizeProperty(key, properties[key], relations);
1940
- return newProperties;
1941
- }
1942
- normalizeProperty(key, property, relations) {
1943
- const newProperty = { ...property };
1944
- if (newProperty.type === "map" && newProperty.properties) newProperty.properties = this.normalizeProperties(newProperty.properties, relations);
1945
- else if (newProperty.type === "array") {
1946
- const arrayProp = newProperty;
1947
- if (arrayProp.of) if (Array.isArray(arrayProp.of)) arrayProp.of = arrayProp.of.map((p, i) => this.normalizeProperty(`${key}[${i}]`, p, relations));
1948
- else arrayProp.of = this.normalizeProperty(`${key}.of`, arrayProp.of, relations);
1949
- else if (arrayProp.oneOf && arrayProp.oneOf.properties) arrayProp.oneOf.properties = this.normalizeProperties(arrayProp.oneOf.properties, relations);
1950
- } else if ((newProperty.type === "string" || newProperty.type === "number") && newProperty.enum) {
1951
- const stringOrNumberProperty = newProperty;
1952
- if (typeof stringOrNumberProperty.enum === "object" && !Array.isArray(stringOrNumberProperty.enum)) stringOrNumberProperty.enum = enumToObjectEntries(stringOrNumberProperty.enum)?.filter((value) => value && (value.id || value.id === 0) && value.label) ?? [];
1953
- } else if (newProperty.type === "relation") {
1954
- const relationProperty = newProperty;
1955
- const name = relationProperty.relationName || key;
1956
- const relation = relations.find((r) => r.relationName === name);
1957
- if (relation) relationProperty.relation = relation;
1958
- else console.warn(`Could not find relation for property '${key}' with relationName: ${name}`);
1959
- }
1960
- return newProperty;
1961
- }
1962
- get(path) {
1963
- const bySlug = this.collectionsBySlug.get(path);
1964
- if (bySlug) return bySlug;
1965
- if (path.includes("-")) {
1966
- const normalized = path.replace(/-/g, "_");
1967
- const byNormalized = this.collectionsBySlug.get(normalized);
1968
- if (byNormalized) return byNormalized;
1969
- }
1970
- return this.collectionsByTableName.get(path);
1971
- }
1972
- /**
1973
- * Gets the pristine, un-normalized collection exactly as it was provided.
1974
- * Useful for the AST editor so it doesn't accidentally serialize injected metadata back to disk.
1975
- */
1976
- getRaw(path) {
1977
- const bySlug = this.rawCollectionsBySlug.get(path);
1978
- if (bySlug) return bySlug;
1979
- if (path.includes("-")) {
1980
- const normalized = path.replace(/-/g, "_");
1981
- const byNormalized = this.rawCollectionsBySlug.get(normalized);
1982
- if (byNormalized) return byNormalized;
1983
- }
1984
- return this.rawCollectionsByTableName.get(path);
1985
- }
1986
- /**
1987
- * Get collection by resolving multi-segment paths through relations
1988
- * e.g., "authors/70/posts" resolves to the posts collection
1989
- */
1990
- getCollectionByPath(collectionPath) {
1991
- if (!collectionPath.includes("/")) return this.get(collectionPath);
1992
- const pathSegments = collectionPath.split("/").filter((p) => p);
1993
- if (pathSegments.length < 3 || pathSegments.length % 2 === 0) throw new Error(`Invalid relation path: ${collectionPath}. Expected format: collection/id/relation or collection/id/relation/id/relation`);
1994
- const rootCollectionPath = pathSegments[0];
1995
- let currentCollection = this.get(rootCollectionPath);
1996
- if (!currentCollection) throw new Error(`Root collection not found: ${rootCollectionPath}`);
1997
- for (let i = 2; i < pathSegments.length; i += 2) {
1998
- const relationKey = pathSegments[i];
1999
- if (!(0, _rebasepro_types.getDataSourceCapabilities)(currentCollection.engine).supportsRelations) throw new Error(`Relation path navigation requires a collection that supports relations, but '${currentCollection.slug}' uses engine '${currentCollection.engine}'`);
2000
- const relation = findRelation(resolveCollectionRelations(currentCollection), relationKey);
2001
- if (!relation) throw new Error(`Relation '${relationKey}' not found in collection '${currentCollection.slug}'`);
2002
- const target = relation.target();
2003
- const targetRelationKey = relation.relationName || target.slug;
2004
- const targetSlug = relation.overrides?.slug ?? targetRelationKey;
2005
- currentCollection = this.get(targetSlug) || this.normalizeCollection(target);
2006
- if (i + 1 < pathSegments.length) {}
2007
- }
2008
- return currentCollection;
2009
- }
2010
- getCollections() {
2011
- if (!this.cachedCollectionsList) this.cachedCollectionsList = Array.from(this.collectionsByTableName.values());
2012
- return this.cachedCollectionsList;
2013
- }
2014
- getRawCollections() {
2015
- if (!this.cachedRawCollectionsList) this.cachedRawCollectionsList = Array.from(this.rawCollectionsByTableName.values());
2016
- return this.cachedRawCollectionsList;
2017
- }
2018
- /**
2019
- * Resolves a multi-segment path like "products/123/locales" and returns
2020
- * information about the collections and entity IDs along the path
2021
- */
2022
- resolvePathToCollections(path) {
2023
- const pathSegments = path.split("/").filter((p) => p);
2024
- if (pathSegments.length === 0) throw new Error(`Invalid path: ${path}`);
2025
- if (pathSegments.length % 2 !== 1) throw new Error(`Invalid collection path: ${path}. It must have an odd number of segments.`);
2026
- const collections = [];
2027
- const entityIds = [];
2028
- let currentCollection = this.get(pathSegments[0]);
2029
- if (!currentCollection) throw new Error(`Unknown collection path or slug: ${pathSegments[0]}`);
2030
- collections.push(currentCollection);
2031
- for (let i = 1; i < pathSegments.length; i += 2) {
2032
- const entityId = pathSegments[i];
2033
- entityIds.push(entityId);
2034
- if (i + 1 < pathSegments.length) {
2035
- const subcollectionSlug = pathSegments[i + 1];
2036
- const subcollections = getSubcollections(currentCollection);
2037
- if (!subcollections || subcollections.length === 0) throw new Error(`No subcollections found for ${currentCollection.slug} in path: ${path}`);
2038
- const subcollection = subcollections.find((c) => c.slug === subcollectionSlug);
2039
- if (!subcollection) throw new Error(`Subcollection '${subcollectionSlug}' not found in ${currentCollection.slug}`);
2040
- currentCollection = this.get(subcollection.slug) || this.normalizeCollection(subcollection);
2041
- collections.push(currentCollection);
2042
- }
2043
- }
2044
- return {
2045
- collections,
2046
- entityIds,
2047
- finalCollection: currentCollection
2048
- };
2049
- }
2050
- };
2051
- //#endregion
2052
- //#region src/collections/default-collections.ts
2053
- /**
2054
- * Default users collection.
2055
- *
2056
- * Prepended to the developer's collections array by the admin and server.
2057
- * Slug-based dedup (Map keyed by slug, last-write-wins) lets developers
2058
- * override by defining their own collection with `slug: "users"`.
2059
- */
2060
- var defaultUsersCollection = defineCollection({
2061
- name: "Users",
2062
- singularName: "User",
2063
- slug: "users",
2064
- auth: true,
2065
- table: "users",
2066
- schema: "rebase",
2067
- icon: "Users",
2068
- group: "Settings",
2069
- openEntityMode: "dialog",
2070
- disableDefaultActions: ["copy"],
2071
- securityRules: [{
2072
- operation: "select",
2073
- roles: ["admin"]
2074
- }, {
2075
- operations: [
2076
- "insert",
2077
- "update",
2078
- "delete"
2079
- ],
2080
- roles: ["admin"]
2081
- }],
2082
- sort: ["createdAt", "desc"],
2083
- properties: {
2084
- id: {
2085
- name: "ID",
2086
- type: "string",
2087
- isId: "uuid",
2088
- ui: { readOnly: true }
2089
- },
2090
- email: {
2091
- name: "Email",
2092
- type: "string",
2093
- validation: {
2094
- required: true,
2095
- unique: true
2096
- }
2097
- },
2098
- displayName: {
2099
- name: "Name",
2100
- type: "string",
2101
- columnName: "display_name",
2102
- validation: { required: true }
2103
- },
2104
- photoURL: {
2105
- name: "Photo URL",
2106
- type: "string",
2107
- columnName: "photo_url",
2108
- ui: { url: "image" }
2109
- },
2110
- roles: {
2111
- name: "Roles",
2112
- type: "array",
2113
- columnType: "text[]",
2114
- of: {
2115
- name: "Role",
2116
- type: "string",
2117
- enum: {
2118
- admin: "Admin",
2119
- editor: "Editor",
2120
- viewer: "Viewer"
2121
- }
2122
- }
2123
- },
2124
- passwordHash: {
2125
- name: "Password Hash",
2126
- type: "string",
2127
- columnName: "password_hash",
2128
- ui: {
2129
- hideFromCollection: true,
2130
- disabled: { hidden: true }
2131
- }
2132
- },
2133
- emailVerified: {
2134
- name: "Email Verified",
2135
- type: "boolean",
2136
- columnName: "email_verified",
2137
- defaultValue: false,
2138
- ui: {
2139
- hideFromCollection: true,
2140
- disabled: { hidden: true }
2141
- }
2142
- },
2143
- emailVerificationToken: {
2144
- name: "Email Verification Token",
2145
- type: "string",
2146
- columnName: "email_verification_token",
2147
- ui: {
2148
- hideFromCollection: true,
2149
- disabled: { hidden: true }
2150
- }
2151
- },
2152
- emailVerificationSentAt: {
2153
- name: "Email Verification Sent At",
2154
- type: "date",
2155
- columnName: "email_verification_sent_at",
2156
- ui: {
2157
- hideFromCollection: true,
2158
- disabled: { hidden: true }
2159
- }
2160
- },
2161
- metadata: {
2162
- name: "Metadata",
2163
- type: "map",
2164
- keyValue: true,
2165
- properties: {},
2166
- defaultValue: {},
2167
- ui: {
2168
- hideFromCollection: true,
2169
- disabled: { hidden: true }
2170
- }
2171
- },
2172
- createdAt: {
2173
- name: "Created At",
2174
- type: "date",
2175
- columnName: "created_at",
2176
- autoValue: "on_create",
2177
- ui: { readOnly: true }
2178
- },
2179
- updatedAt: {
2180
- name: "Updated At",
2181
- type: "date",
2182
- columnName: "updated_at",
2183
- autoValue: "on_update",
2184
- ui: {
2185
- hideFromCollection: true,
2186
- disabled: { hidden: true }
2187
- }
2188
- }
2189
- },
2190
- listProperties: [
2191
- "displayName",
2192
- "email",
2193
- "roles",
2194
- "createdAt"
2195
- ],
2196
- propertiesOrder: [
2197
- "id",
2198
- "email",
2199
- "displayName",
2200
- "roles",
2201
- "createdAt"
2202
- ]
2203
- });
2204
- //#endregion
2205
- //#region src/data/query_builder.ts
2206
- function or(...conditions) {
2207
- return {
2208
- type: "or",
2209
- conditions
2210
- };
2211
- }
2212
- function and(...conditions) {
2213
- return {
2214
- type: "and",
2215
- conditions
2216
- };
2217
- }
2218
- function cond(column, operator, value) {
2219
- return {
2220
- column,
2221
- operator,
2222
- value
2223
- };
2224
- }
2225
- var QueryBuilder = class {
2226
- collection;
2227
- params = { where: {} };
2228
- constructor(collection) {
2229
- this.collection = collection;
2230
- }
2231
- where(columnOrCondition, operator, value) {
2232
- if (typeof columnOrCondition === "object" && columnOrCondition !== null && "type" in columnOrCondition) {
2233
- this.params.logical = columnOrCondition;
2234
- return this;
2235
- }
2236
- if (!this.params.where) this.params.where = {};
2237
- const column = columnOrCondition;
2238
- const condition = [operator, value];
2239
- const existing = this.params.where[column];
2240
- if (existing === void 0) this.params.where[column] = condition;
2241
- else if (Array.isArray(existing) && existing.length > 0 && Array.isArray(existing[0])) this.params.where[column].push(condition);
2242
- else {
2243
- let firstCondition;
2244
- if (Array.isArray(existing) && existing.length === 2 && typeof existing[0] === "string") firstCondition = existing;
2245
- else firstCondition = ["==", existing];
2246
- this.params.where[column] = [firstCondition, condition];
2247
- }
2248
- return this;
2249
- }
2250
- /**
2251
- * Order the results by a specific column.
2252
- * @example
2253
- * client.collection('users').orderBy('createdAt', 'desc').find()
2254
- */
2255
- orderBy(column, direction = "asc") {
2256
- this.params.orderBy = `${column}:${direction}`;
2257
- return this;
2258
- }
2259
- /**
2260
- * Limit the number of results returned.
2261
- */
2262
- limit(count) {
2263
- this.params.limit = count;
2264
- return this;
2265
- }
2266
- /**
2267
- * Skip the first N results.
2268
- */
2269
- offset(count) {
2270
- this.params.offset = count;
2271
- return this;
2272
- }
2273
- /**
2274
- * Set a free-text search string if supported by the backend.
2275
- */
2276
- search(searchString) {
2277
- this.params.searchString = searchString;
2278
- return this;
2279
- }
2280
- /**
2281
- * Include related entities in the response.
2282
- * Relations will be populated with full entity data instead of just IDs.
2283
- *
2284
- * @param relations - Relation names to include, or "*" for all.
2285
- * @example
2286
- * // Include specific relations
2287
- * client.data.posts.include("tags", "author").find()
2288
- *
2289
- * // Include all relations
2290
- * client.data.posts.include("*").find()
2291
- */
2292
- include(...relations) {
2293
- this.params.include = relations;
2294
- return this;
2295
- }
2296
- /**
2297
- * Execute the find query and return the results.
2298
- */
2299
- async find() {
2300
- return this.collection.find(this.params);
2301
- }
2302
- /**
2303
- * Listen to realtime updates matching this query.
2304
- */
2305
- listen(onUpdate, onError) {
2306
- if (!this.collection.listen) throw new Error("Listen is only available when RebaseClient is configured with a websocketUrl.");
2307
- return this.collection.listen(this.params, onUpdate, onError);
2308
- }
2309
- };
2310
- //#endregion
2311
- //#region src/data/filter-dialect.ts
2312
- /**
2313
- * REST wire-format adapter for the unified filter system.
2314
- *
2315
- * This module is the ONLY code in the entire codebase that knows about
2316
- * PostgREST-style dot-syntax strings (`eq.active`, `gt.18`, `in.(a,b)`).
2317
- * Everything else speaks `FilterValues` exclusively.
2318
- *
2319
- * @module
2320
- */
2321
- /**
2322
- * Coerce a raw querystring value to its natural JS type.
2323
- * - `"true"` / `"false"` → boolean
2324
- * - `"null"` → null
2325
- * - Numeric strings → number
2326
- * - Everything else → string (unchanged)
2327
- */
2328
- function coerceValue(raw) {
2329
- if (raw === "true") return true;
2330
- if (raw === "false") return false;
2331
- if (raw === "null") return null;
2332
- if (raw !== "" && !isNaN(Number(raw))) return Number(raw);
2333
- return raw;
2334
- }
2335
- /**
2336
- * Serialize a JS value to its querystring representation.
2337
- */
2338
- function stringifyValue(value) {
2339
- if (value === null) return "null";
2340
- if (typeof value === "boolean") return String(value);
2341
- return String(value);
2342
- }
2343
- /**
2344
- * Serialize a single condition tuple to a PostgREST dot-string.
2345
- *
2346
- * @example
2347
- * serializeTuple(["==", "active"]) // "eq.active"
2348
- * serializeTuple(["in", ["admin","editor"]]) // "in.(admin,editor)"
2349
- * serializeTuple([">=", 18]) // "gte.18"
2350
- */
2351
- function serializeTuple(tuple) {
2352
- if (typeof tuple === "string") {
2353
- if (tuple.includes(".")) {
2354
- const dotIndex = tuple.indexOf(".");
2355
- if (_rebasepro_types.REST_TO_CANONICAL[tuple.substring(0, dotIndex)]) return tuple;
2356
- }
2357
- return tuple;
2358
- }
2359
- if (!Array.isArray(tuple) || tuple.length !== 2 || typeof tuple[0] !== "string" || !_rebasepro_types.CANONICAL_TO_REST[tuple[0]]) return `eq.${stringifyValue(tuple)}`;
2360
- const [op, value] = tuple;
2361
- const restOp = _rebasepro_types.CANONICAL_TO_REST[op];
2362
- if (Array.isArray(value)) return `${restOp}.(${value.map(stringifyValue).join(",")})`;
2363
- return `${restOp}.${stringifyValue(value)}`;
2364
- }
2365
- /**
2366
- * Convert `FilterValues` to a PostgREST-style querystring record.
2367
- *
2368
- * - Single conditions produce a string value.
2369
- * - Multiple conditions on the same field produce a string array (repeated params).
2370
- *
2371
- * @example
2372
- * serializeFilter({ status: ["==", "active"] })
2373
- * // → { status: "eq.active" }
2374
- *
2375
- * serializeFilter({ age: [[">=", 18], ["<", 65]] })
2376
- * // → { age: ["gte.18", "lt.65"] }
2377
- */
2378
- function serializeFilter(filter) {
2379
- const result = {};
2380
- for (const [field, condition] of Object.entries(filter)) {
2381
- if (condition === void 0) continue;
2382
- if (Array.isArray(condition) && condition.length > 0 && Array.isArray(condition[0])) result[field] = condition.map(serializeTuple);
2383
- else result[field] = serializeTuple(condition);
2384
- }
2385
- return result;
2386
- }
2387
- /**
2388
- * Parse a single PostgREST dot-string into a `[WhereFilterOp, unknown]` tuple.
2389
- *
2390
- * If the string doesn't match a known operator prefix, falls back to
2391
- * `["==", originalString]` (treating the whole string as an equality value).
2392
- */
2393
- function deserializeSingle(raw) {
2394
- const dotIndex = raw.indexOf(".");
2395
- if (dotIndex === -1) return ["==", coerceValue(raw)];
2396
- const prefix = raw.substring(0, dotIndex);
2397
- const rest = raw.substring(dotIndex + 1);
2398
- const canonicalOp = _rebasepro_types.REST_TO_CANONICAL[prefix];
2399
- if (!canonicalOp) return ["==", raw];
2400
- if (rest.startsWith("(") && rest.endsWith(")")) return [canonicalOp, rest.slice(1, -1).split(",").map((s) => coerceValue(s.trim()))];
2401
- return [canonicalOp, coerceValue(rest)];
2402
- }
2403
- /**
2404
- * Convert a PostgREST-style querystring record to `FilterValues`.
2405
- *
2406
- * - String values are parsed as single conditions.
2407
- * - String arrays (repeated query params) become multiple conditions on the same field.
2408
- *
2409
- * @example
2410
- * deserializeFilter({ status: "eq.active" })
2411
- * // → { status: ["==", "active"] }
2412
- *
2413
- * deserializeFilter({ age: ["gte.18", "lt.65"] })
2414
- * // → { age: [[">=", 18], ["<", 65]] }
2415
- */
2416
- function deserializeFilter(query) {
2417
- const result = {};
2418
- for (const [field, raw] of Object.entries(query)) {
2419
- if (raw === void 0) continue;
2420
- if (Array.isArray(raw) && raw.length === 2 && typeof raw[0] === "string" && (0, _rebasepro_types.toCanonicalOp)(raw[0]) === raw[0]) {
2421
- result[field] = raw;
2422
- continue;
2423
- }
2424
- if (Array.isArray(raw)) {
2425
- if (raw.length === 0) continue;
2426
- if (Array.isArray(raw[0]) && raw[0].length === 2 && typeof raw[0][0] === "string" && (0, _rebasepro_types.toCanonicalOp)(raw[0][0]) === raw[0][0]) {
2427
- result[field] = raw;
2428
- continue;
2429
- }
2430
- if (raw.length === 1) result[field] = typeof raw[0] === "string" ? deserializeSingle(raw[0]) : ["==", raw[0]];
2431
- else if (typeof raw[0] === "string" && raw[0].includes(".")) result[field] = raw.map((r) => typeof r === "string" ? deserializeSingle(r) : ["==", r]);
2432
- else result[field] = ["in", raw];
2433
- } else if (typeof raw === "string") result[field] = deserializeSingle(raw);
2434
- else result[field] = ["==", raw];
2435
- }
2436
- return result;
2437
- }
2438
- /**
2439
- * Serialize a `LogicalCondition` or `FilterCondition` to its wire-format string.
2440
- *
2441
- * @example
2442
- * serializeLogicalCondition({ column: "status", operator: "==", value: "active" })
2443
- * // → "status.eq.active"
2444
- *
2445
- * serializeLogicalCondition({ type: "or", conditions: [...] })
2446
- * // → "or(status.eq.active,status.eq.pending)"
2447
- */
2448
- function serializeLogicalCondition(cond) {
2449
- if ("type" in cond) {
2450
- const inner = (cond.conditions ?? []).map(serializeLogicalCondition).join(",");
2451
- return `${cond.type}(${inner})`;
2452
- }
2453
- const restOp = _rebasepro_types.CANONICAL_TO_REST[cond.operator] || "eq";
2454
- if (Array.isArray(cond.value)) {
2455
- const items = cond.value.map(stringifyValue).join(",");
2456
- return `${cond.column}.${restOp}.(${items})`;
2457
- }
2458
- return `${cond.column}.${restOp}.${stringifyValue(cond.value)}`;
2459
- }
2460
- /**
2461
- * Parse a logical condition wire-format string back into a
2462
- * `LogicalCondition` or `FilterCondition`.
2463
- *
2464
- * @example
2465
- * deserializeLogicalCondition("status.eq.active")
2466
- * // → { column: "status", operator: "==", value: "active" }
2467
- *
2468
- * deserializeLogicalCondition("or(status.eq.active,age.gte.18)")
2469
- * // → { type: "or", conditions: [...] }
2470
- */
2471
- function deserializeLogicalCondition(str) {
2472
- const logicalMatch = str.match(/^(and|or)\((.+)\)$/);
2473
- if (logicalMatch) {
2474
- const type = logicalMatch[1];
2475
- const innerStr = logicalMatch[2];
2476
- const conditions = [];
2477
- let depth = 0;
2478
- let start = 0;
2479
- for (let i = 0; i < innerStr.length; i++) if (innerStr[i] === "(") depth++;
2480
- else if (innerStr[i] === ")") depth--;
2481
- else if (innerStr[i] === "," && depth === 0) {
2482
- conditions.push(deserializeLogicalCondition(innerStr.slice(start, i)));
2483
- start = i + 1;
2484
- }
2485
- conditions.push(deserializeLogicalCondition(innerStr.slice(start)));
2486
- return {
2487
- type,
2488
- conditions
2489
- };
2490
- }
2491
- const firstDot = str.indexOf(".");
2492
- if (firstDot === -1) return {
2493
- column: str,
2494
- operator: "==",
2495
- value: true
2496
- };
2497
- const column = str.substring(0, firstDot);
2498
- const rest = str.substring(firstDot + 1);
2499
- const secondDot = rest.indexOf(".");
2500
- if (secondDot === -1) return {
2501
- column,
2502
- operator: "==",
2503
- value: coerceValue(rest)
2504
- };
2505
- const opStr = rest.substring(0, secondDot);
2506
- let valueStr = rest.substring(secondDot + 1);
2507
- const operator = (0, _rebasepro_types.toCanonicalOp)(opStr) ?? "==";
2508
- if (valueStr.startsWith("(") && valueStr.endsWith(")")) return {
2509
- column,
2510
- operator,
2511
- value: valueStr.slice(1, -1).split(",").map((s) => coerceValue(s.trim()))
2512
- };
2513
- return {
2514
- column,
2515
- operator,
2516
- value: coerceValue(valueStr)
2517
- };
2518
- }
2519
- //#endregion
2520
- //#region src/data/buildRebaseData.ts
2521
- /**
2522
- * Parse an orderBy string like "created_at:desc" into [field, direction].
2523
- */
2524
- function parseOrderBy(orderBy) {
2525
- if (!orderBy) return void 0;
2526
- const parts = orderBy.split(":");
2527
- return [parts[0], parts[1] || "asc"];
2528
- }
2529
- function createDriverAccessor(driver, slug) {
2530
- const accessor = {
2531
- async find(params) {
2532
- const orderParsed = parseOrderBy(params?.orderBy);
2533
- const filter = params?.where ? deserializeFilter(params.where) : void 0;
2534
- const entities = await driver.fetchCollection({
2535
- path: slug,
2536
- limit: params?.limit,
2537
- offset: params?.offset,
2538
- filter,
2539
- orderBy: orderParsed?.[0],
2540
- order: orderParsed?.[1],
2541
- searchString: params?.searchString
2542
- });
2543
- const limit = params?.limit ?? 20;
2544
- const offset = params?.offset ?? 0;
2545
- return {
2546
- data: entities,
2547
- meta: {
2548
- total: entities.length,
2549
- limit,
2550
- offset,
2551
- hasMore: entities.length >= limit
2552
- }
2553
- };
2554
- },
2555
- async findById(id) {
2556
- return driver.fetchEntity({
2557
- path: slug,
2558
- entityId: id
2559
- });
2560
- },
2561
- async create(data, id) {
2562
- return driver.saveEntity({
2563
- path: slug,
2564
- values: data,
2565
- entityId: id,
2566
- status: "new"
2567
- });
2568
- },
2569
- async update(id, data) {
2570
- return driver.saveEntity({
2571
- path: slug,
2572
- values: data,
2573
- entityId: id,
2574
- status: "existing"
2575
- });
2576
- },
2577
- async delete(id) {
2578
- return driver.deleteEntity({ entity: {
2579
- id,
2580
- path: slug,
2581
- values: {}
2582
- } });
2583
- },
2584
- deleteAll: driver.deleteAll ? async () => {
2585
- return driver.deleteAll(slug);
2586
- } : void 0,
2587
- count: driver.countEntities ? async (params) => {
2588
- const filter = params?.where ? deserializeFilter(params.where) : void 0;
2589
- return driver.countEntities({
2590
- path: slug,
2591
- filter
2592
- });
2593
- } : void 0,
2594
- listen: driver.listenCollection ? (params, onUpdate, onError) => {
2595
- const orderParsed = parseOrderBy(params?.orderBy);
2596
- const limit = params?.limit ?? 20;
2597
- const offset = params?.offset ?? 0;
2598
- return driver.listenCollection({
2599
- path: slug,
2600
- limit: params?.limit,
2601
- offset: params?.offset,
2602
- filter: params?.where,
2603
- orderBy: orderParsed?.[0],
2604
- order: orderParsed?.[1],
2605
- searchString: params?.searchString,
2606
- onUpdate: (entities) => {
2607
- onUpdate({
2608
- data: entities,
2609
- meta: {
2610
- total: entities.length,
2611
- limit,
2612
- offset,
2613
- hasMore: entities.length >= limit
2614
- }
2615
- });
2616
- },
2617
- onError
2618
- });
2619
- } : void 0,
2620
- listenById: driver.listenEntity ? (id, onUpdate, onError) => {
2621
- return driver.listenEntity({
2622
- path: slug,
2623
- entityId: id,
2624
- onUpdate: (entity) => onUpdate(entity ?? void 0),
2625
- onError
2626
- });
2627
- } : void 0,
2628
- where(columnOrCondition, operator, value) {
2629
- const builder = new QueryBuilder(accessor);
2630
- if (typeof columnOrCondition === "object") return builder.where(columnOrCondition);
2631
- return builder.where(columnOrCondition, operator, value);
2632
- },
2633
- orderBy(column, ascending) {
2634
- return new QueryBuilder(accessor).orderBy(column, ascending);
2635
- },
2636
- limit(count) {
2637
- return new QueryBuilder(accessor).limit(count);
2638
- },
2639
- offset(count) {
2640
- return new QueryBuilder(accessor).offset(count);
2641
- },
2642
- search(searchString) {
2643
- return new QueryBuilder(accessor).search(searchString);
2644
- },
2645
- include(...relations) {
2646
- return new QueryBuilder(accessor).include(...relations);
2647
- }
2648
- };
2649
- return accessor;
2650
- }
2651
- /**
2652
- * Build a `RebaseData` object from a `DataDriver` using JavaScript Proxy.
2653
- *
2654
- * This is the key bridge: any property access like `data.products` returns
2655
- * a `CollectionAccessor` backed by the underlying DataDriver, without
2656
- * needing per-collection code generation.
2657
- *
2658
- * @example
2659
- * const data = buildRebaseData(driver);
2660
- * await data.products.create({ name: "Camera", price: 299 });
2661
- * const { data: items } = await data.products.find({ where: { status: "eq.published" } });
2662
- */
2663
- function buildRebaseData(driver) {
2664
- const cache = /* @__PURE__ */ new Map();
2665
- function getAccessor(slug) {
2666
- let accessor = cache.get(slug);
2667
- if (!accessor) {
2668
- accessor = createDriverAccessor(driver, slug);
2669
- cache.set(slug, accessor);
2670
- }
2671
- return accessor;
2672
- }
2673
- return new Proxy({ collection: getAccessor }, { get(_target, prop) {
2674
- if (prop === "collection") return getAccessor;
2675
- if (typeof prop === "symbol") return void 0;
2676
- if (prop === "then" || prop === "toJSON" || prop === "$$typeof") return void 0;
2677
- return getAccessor((0, _rebasepro_utils.toSnakeCase)(prop));
2678
- } });
2679
- }
2680
- //#endregion
2681
- //#region src/data/buildRoutedRebaseData.ts
2682
- /**
2683
- * Build a {@link RebaseData} that routes each collection to the right
2684
- * backend based on its resolved data source.
2685
- *
2686
- * `.collection(path)` (and dynamic `data.products`-style access) resolves the
2687
- * collection's data-source key via `resolveKey` and delegates to the matching
2688
- * entry in `sources`, falling back to `defaultData` when there is no match.
2689
- * Because routing keys off the *path being accessed*, a reference widget
2690
- * inside a Firestore form that points at a Postgres collection is still
2691
- * served by Postgres — routing follows the target, not the ancestor.
2692
- *
2693
- * When `sources` is empty this returns `defaultData` untouched, so the
2694
- * single-driver setup keeps identical behaviour and identity (important for
2695
- * effect dependencies that key off the data instance).
2696
- *
2697
- * @example
2698
- * const data = buildRoutedRebaseData({
2699
- * defaultData: client.data,
2700
- * sources: { analytics: buildRebaseData(firestoreDriver) },
2701
- * resolveKey: (path) => resolveDataSource(registry.getCollection(path), defs).key
2702
- * });
2703
- * await data.products.find(); // → default (server / Postgres)
2704
- * await data.events.find(); // → Firestore, if `events.dataSource === "analytics"`
2705
- */
2706
- function buildRoutedRebaseData({ defaultData, sources, resolveKey }) {
2707
- if (!sources || Object.keys(sources).length === 0) return defaultData;
2708
- function resolve(slugOrPath) {
2709
- const key = resolveKey(slugOrPath);
2710
- if (key && sources[key]) return sources[key];
2711
- return defaultData;
2712
- }
2713
- function getAccessor(slugOrPath) {
2714
- return resolve(slugOrPath).collection(slugOrPath);
2715
- }
2716
- return new Proxy({ collection: getAccessor }, { get(_target, prop) {
2717
- if (prop === "collection") return getAccessor;
2718
- if (typeof prop === "symbol") return void 0;
2719
- if (prop === "then" || prop === "toJSON" || prop === "$$typeof") return void 0;
2720
- return getAccessor((0, _rebasepro_utils.toSnakeCase)(prop));
2721
- } });
2722
- }
2723
- //#endregion
2724
- //#region src/table-classification.ts
2725
- /** Schemas that are always considered Rebase-internal. */
2726
- var REBASE_INTERNAL_SCHEMAS = ["rebase", "auth"];
2727
- /** Table-name prefixes that mark a table as Rebase-internal regardless of schema. */
2728
- var REBASE_INTERNAL_PREFIXES = [
2729
- "_rebase_",
2730
- "_auth_",
2731
- "drizzle_"
2732
- ];
2733
- /**
2734
- * Synchronously classify a table based on naming conventions.
2735
- *
2736
- * @param tableName - The unqualified name of the table.
2737
- * @param schemaName - The schema the table belongs to (e.g. `"public"`, `"rebase"`).
2738
- * @returns `"rebase-internal"` when the table belongs to a reserved schema or
2739
- * carries a reserved prefix; `"user"` otherwise.
2740
- *
2741
- * @remarks
2742
- * Junction-table detection requires an async database query and is therefore
2743
- * **not** handled by this function. Use {@link detectJunctionTables} to obtain
2744
- * the set of junction tables, then reclassify as needed.
2745
- */
2746
- function classifyTable(tableName, schemaName) {
2747
- if (REBASE_INTERNAL_SCHEMAS.includes(schemaName) || REBASE_INTERNAL_PREFIXES.some((prefix) => tableName.startsWith(prefix))) return "rebase-internal";
2748
- return "user";
2749
- }
2750
- /**
2751
- * Convenience predicate that checks whether a table is Rebase-internal.
2752
- *
2753
- * @param tableName - The unqualified name of the table.
2754
- * @param schemaName - The schema the table belongs to.
2755
- * @returns `true` if the table is classified as `"rebase-internal"`.
2756
- */
2757
- function isRebaseInternalTable(tableName, schemaName) {
2758
- return classifyTable(tableName, schemaName) === "rebase-internal";
2759
- }
2760
- /** SQL query that detects junction tables in the `public` schema. */
2761
- var JUNCTION_TABLES_SQL = `
2762
- SELECT t.table_name
2763
- FROM information_schema.tables t
2764
- WHERE t.table_schema = 'public'
2765
- AND t.table_type = 'BASE TABLE'
2766
- AND NOT EXISTS (
2767
- SELECT 1
2768
- FROM information_schema.columns c
2769
- WHERE c.table_schema = t.table_schema
2770
- AND c.table_name = t.table_name
2771
- AND c.column_name NOT IN (
2772
- SELECT kcu.column_name
2773
- FROM information_schema.key_column_usage kcu
2774
- JOIN information_schema.table_constraints tc
2775
- ON tc.constraint_name = kcu.constraint_name
2776
- AND tc.table_schema = kcu.table_schema
2777
- WHERE tc.constraint_type = 'FOREIGN KEY'
2778
- AND kcu.table_schema = t.table_schema
2779
- AND kcu.table_name = t.table_name
2780
- )
2781
- )
2782
- `;
2783
- /**
2784
- * Asynchronously detect junction (link) tables in the `public` schema.
2785
- *
2786
- * A junction table is defined as a table where **every** column participates in
2787
- * at least one foreign-key constraint.
2788
- *
2789
- * @param executeSql - A callback that executes a raw SQL string and returns the
2790
- * resulting rows.
2791
- * @returns A `Set` containing the names of all detected junction tables.
2792
- */
2793
- async function detectJunctionTables(executeSql) {
2794
- const rows = await executeSql(JUNCTION_TABLES_SQL);
2795
- const junctionTables = /* @__PURE__ */ new Set();
2796
- for (const row of rows) if (typeof row.table_name === "string") junctionTables.add(row.table_name);
2797
- return junctionTables;
2798
- }
2799
- //#endregion
2800
- exports.COLLECTION_PATH_SEPARATOR = COLLECTION_PATH_SEPARATOR;
2801
- exports.CollectionRegistry = CollectionRegistry;
2802
- exports.DEFAULT_ONE_OF_TYPE = DEFAULT_ONE_OF_TYPE;
2803
- exports.DEFAULT_ONE_OF_VALUE = DEFAULT_ONE_OF_VALUE;
2804
- exports.JUNCTION_TABLES_SQL = JUNCTION_TABLES_SQL;
2805
- exports.QueryBuilder = QueryBuilder;
2806
- exports.REBASE_INTERNAL_PREFIXES = REBASE_INTERNAL_PREFIXES;
2807
- exports.REBASE_INTERNAL_SCHEMAS = REBASE_INTERNAL_SCHEMAS;
2808
- exports.addInitialSlash = addInitialSlash;
2809
- exports.and = and;
2810
- exports.applyPropertyConditions = applyPropertyConditions;
2811
- exports.buildAdditionalFieldDelegate = buildAdditionalFieldDelegate;
2812
- exports.buildCollection = buildCollection;
2813
- exports.buildConditionContext = buildConditionContext;
2814
- exports.buildEntityCallbacks = buildEntityCallbacks;
2815
- exports.buildEnum = buildEnum;
2816
- exports.buildEnumValueConfig = buildEnumValueConfig;
2817
- exports.buildProperties = buildProperties;
2818
- exports.buildPropertiesOrBuilder = buildPropertiesOrBuilder;
2819
- exports.buildProperty = buildProperty;
2820
- exports.buildPropertyCallbacks = buildPropertyCallbacks;
2821
- exports.buildRebaseData = buildRebaseData;
2822
- exports.buildRoutedRebaseData = buildRoutedRebaseData;
2823
- exports.canCreateEntity = canCreateEntity;
2824
- exports.canDeleteEntity = canDeleteEntity;
2825
- exports.canEditEntity = canEditEntity;
2826
- exports.canReadCollection = canReadCollection;
2827
- exports.checkOperation = checkOperation;
2828
- exports.classifyTable = classifyTable;
2829
- exports.cond = cond;
2830
- exports.createDataSourceRegistry = createDataSourceRegistry;
2831
- exports.createRelationRef = createRelationRef;
2832
- exports.createRelationRefWithData = createRelationRefWithData;
2833
- exports.defaultUsersCollection = defaultUsersCollection;
2834
- exports.defineCollection = defineCollection;
2835
- exports.deserializeFilter = deserializeFilter;
2836
- exports.deserializeLogicalCondition = deserializeLogicalCondition;
2837
- exports.detectJunctionTables = detectJunctionTables;
2838
- exports.enumToObjectEntries = enumToObjectEntries;
2839
- exports.evaluateCondition = evaluateCondition;
2840
- exports.evaluatePolicy = evaluatePolicy;
2841
- exports.findRelation = findRelation;
2842
- exports.fullPathToCollectionSegments = fullPathToCollectionSegments;
2843
- exports.getArrayResolvedProperties = getArrayResolvedProperties;
2844
- exports.getCollectionBySlugWithin = getCollectionBySlugWithin;
2845
- exports.getCollectionPathsCombinations = getCollectionPathsCombinations;
2846
- exports.getColumnName = getColumnName;
2847
- exports.getDefaultValueFor = getDefaultValueFor;
2848
- exports.getDefaultValueFortype = getDefaultValueFortype;
2849
- exports.getDefaultValuesFor = getDefaultValuesFor;
2850
- exports.getEntityImagePreviewPropertyKey = getEntityImagePreviewPropertyKey;
2851
- exports.getEnumVarName = getEnumVarName;
2852
- exports.getLabelOrConfigFrom = getLabelOrConfigFrom;
2853
- exports.getLastSegment = getLastSegment;
2854
- exports.getLocalChangesBackup = getLocalChangesBackup;
2855
- exports.getNavigationEntriesFromPath = getNavigationEntriesFromPath;
2856
- exports.getParentReferencesFromPath = getParentReferencesFromPath;
2857
- exports.getPrimaryKeys = getPrimaryKeys;
2858
- exports.getReferenceFrom = getReferenceFrom;
2859
- exports.getRelationFrom = getRelationFrom;
2860
- exports.getSubcollections = getSubcollections;
2861
- exports.getTableName = getTableName;
2862
- exports.getTableVarName = getTableVarName;
2863
- exports.isHidden = isHidden;
2864
- exports.isPropertyBuilder = isPropertyBuilder;
2865
- exports.isReadOnly = isReadOnly;
2866
- exports.isRebaseInternalTable = isRebaseInternalTable;
2867
- exports.normalizeToEntityRelation = normalizeToEntityRelation;
2868
- exports.or = or;
2869
- exports.policyToPostgres = policyToPostgres;
2870
- exports.registerConditionOperations = registerConditionOperations;
2871
- exports.removeInitialAndTrailingSlashes = removeInitialAndTrailingSlashes;
2872
- exports.removeInitialSlash = removeInitialSlash;
2873
- exports.removeTrailingSlash = removeTrailingSlash;
2874
- exports.resolveArrayProperties = resolveArrayProperties;
2875
- exports.resolveCollectionPathIds = resolveCollectionPathIds;
2876
- exports.resolveCollectionRelations = resolveCollectionRelations;
2877
- exports.resolveDataSource = resolveDataSource;
2878
- exports.resolveDefaultSelectedView = resolveDefaultSelectedView;
2879
- exports.resolveEnumValues = resolveEnumValues;
2880
- exports.resolveProperties = resolveProperties;
2881
- exports.resolveProperty = resolveProperty;
2882
- exports.resolvePropertyEnum = resolvePropertyEnum;
2883
- exports.resolvePropertyRelation = resolvePropertyRelation;
2884
- exports.resolveRelationProperty = resolveRelationProperty;
2885
- exports.resolveStorageFilenameString = resolveStorageFilenameString;
2886
- exports.resolveStoragePathString = resolveStoragePathString;
2887
- exports.resolveStorageSource = resolveStorageSource;
2888
- exports.sanitizeData = sanitizeData;
2889
- exports.sanitizeRelation = sanitizeRelation;
2890
- exports.securityRuleToConditions = securityRuleToConditions;
2891
- exports.segmentsToStrippedPath = segmentsToStrippedPath;
2892
- exports.serializeFilter = serializeFilter;
2893
- exports.serializeLogicalCondition = serializeLogicalCondition;
2894
- exports.sortProperties = sortProperties;
2895
- exports.stripCollectionPath = stripCollectionPath;
2896
- exports.traverseValueProperty = traverseValueProperty;
2897
- exports.traverseValuesProperties = traverseValuesProperties;
2898
- exports.updateDateAutoValues = updateDateAutoValues;
2899
- });
2900
-
2901
- //# sourceMappingURL=index.umd.js.map