@rebasepro/common 0.9.0 → 0.9.1-canary.0fce67c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js DELETED
@@ -1,3311 +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 a 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 a 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 a 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, options) {
813
- return compile(expr, {
814
- fieldCollection: collection,
815
- fieldPrefix: "",
816
- outerCollection: collection,
817
- outerPrefix: "",
818
- resolveCollection: options?.resolveCollection,
819
- alias: { n: 0 }
820
- });
821
- }
822
- function compile(expr, scope) {
823
- switch (expr.kind) {
824
- case "true": return "true";
825
- case "false": return "false";
826
- case "and": return expr.operands.length === 0 ? "true" : expr.operands.map((o) => `(${compile(o, scope)})`).join(" AND ");
827
- case "or": return expr.operands.length === 0 ? "false" : expr.operands.map((o) => `(${compile(o, scope)})`).join(" OR ");
828
- case "not":
829
- if (expr.operand.kind === "authenticated") return "auth.uid() IS NULL";
830
- return `NOT (${compile(expr.operand, scope)})`;
831
- case "compare": return `${operandToSql(expr.left, scope)} ${COMPARE_SQL[expr.op]} ${operandToSql(expr.right, scope)}`;
832
- case "rolesOverlap": return `string_to_array(auth.roles(), ',') && ${rolesArraySql(expr.roles)}`;
833
- case "rolesContain": return `string_to_array(auth.roles(), ',') @> ${rolesArraySql(expr.roles)}`;
834
- case "authenticated": return "auth.uid() IS NOT NULL";
835
- case "existsIn": return compileExistsIn(expr, scope);
836
- case "raw": return expr.sql.replace(/\{(\w+)\}/g, (_, col) => col);
837
- }
838
- }
839
- /**
840
- * Compiles `existsIn` to a correlated `EXISTS (SELECT 1 FROM <join> WHERE ...)`.
841
- * Inside the subquery, `field` operands bind to the aliased join table and
842
- * `outerField` operands bind to the (table-qualified) outer RLS row.
843
- */
844
- function compileExistsIn(expr, scope) {
845
- const join = scope.resolveCollection?.(expr.collection);
846
- const joinTable = join ? getTableName(join) : (0, _rebasepro_utils.toSnakeCase)(expr.collection);
847
- const joinSchema = schemaOf(join) ?? schemaOf(scope.outerCollection) ?? "public";
848
- const alias = `_ex${scope.alias.n++}`;
849
- const outerTable = scope.outerCollection ? getTableName(scope.outerCollection) : void 0;
850
- const outerSchema = schemaOf(scope.outerCollection) ?? "public";
851
- const outerPrefix = outerTable ? `"${outerSchema}"."${outerTable}".` : "";
852
- const innerScope = {
853
- fieldCollection: join,
854
- fieldPrefix: `"${alias}".`,
855
- outerCollection: scope.outerCollection,
856
- outerPrefix,
857
- resolveCollection: scope.resolveCollection,
858
- alias: scope.alias
859
- };
860
- return `EXISTS (SELECT 1 FROM "${joinSchema}"."${joinTable}" "${alias}" WHERE ${compile(expr.where, innerScope)})`;
861
- }
862
- var COMPARE_SQL = {
863
- eq: "=",
864
- neq: "!=",
865
- lt: "<",
866
- lte: "<=",
867
- gt: ">",
868
- gte: ">="
869
- };
870
- function operandToSql(operand, scope) {
871
- switch (operand.kind) {
872
- case "field": return `${scope.fieldPrefix}${resolveColumnName(operand.name, scope.fieldCollection)}`;
873
- case "outerField": return `${scope.outerPrefix}${resolveColumnName(operand.name, scope.outerCollection)}`;
874
- case "literal": return quoteLiteral(operand.value);
875
- case "authUid": return "auth.uid()";
876
- case "authRoles": return "string_to_array(auth.roles(), ',')";
877
- }
878
- }
879
- function schemaOf(collection) {
880
- return collection?.schema || void 0;
881
- }
882
- function resolveColumnName(propName, collection) {
883
- const prop = collection?.properties?.[propName];
884
- if (prop && "columnName" in prop && typeof prop.columnName === "string") return prop.columnName;
885
- return (0, _rebasepro_utils.toSnakeCase)(propName);
886
- }
887
- function quoteLiteral(value) {
888
- if (value === null) return "NULL";
889
- if (typeof value === "boolean") return value ? "true" : "false";
890
- if (typeof value === "number") return String(value);
891
- return `'${value.replace(/'/g, "''")}'`;
892
- }
893
- /** Sorted, single-quoted `ARRAY['a','b']` — matches the generators' output. */
894
- function rolesArraySql(roles) {
895
- return `ARRAY[${[...roles].sort().map((r) => `'${r}'`).join(",")}]`;
896
- }
897
- //#endregion
898
- //#region src/util/policy/evaluatePolicy.ts
899
- /**
900
- * Evaluates a {@link PolicyExpression} against a user + row, using three-valued
901
- * (Kleene) logic so that `"unknown"` sub-results propagate soundly.
902
- *
903
- * This is the JavaScript twin of {@link policyToPostgres}: both derive from the
904
- * same expression, so the admin UI matches database enforcement by construction
905
- * for every non-raw rule.
906
- */
907
- function evaluatePolicy(expr, ctx) {
908
- switch (expr.kind) {
909
- case "true": return true;
910
- case "false": return false;
911
- case "and": return kleeneAnd$1(expr.operands.map((o) => evaluatePolicy(o, ctx)));
912
- case "or": return kleeneOr(expr.operands.map((o) => evaluatePolicy(o, ctx)));
913
- case "not": return kleeneNot(evaluatePolicy(expr.operand, ctx));
914
- case "compare": return evaluateCompare(expr.op, expr.left, expr.right, ctx);
915
- case "rolesOverlap": {
916
- const userRoles = ctx.roles ?? [];
917
- return expr.roles.some((r) => r === "public" || userRoles.includes(r));
918
- }
919
- case "rolesContain": {
920
- const userRoles = ctx.roles ?? [];
921
- return expr.roles.every((r) => r === "public" || userRoles.includes(r));
922
- }
923
- case "authenticated": return ctx.uid != null;
924
- case "existsIn": return "unknown";
925
- case "raw": return "unknown";
926
- }
927
- }
928
- function kleeneAnd$1(values) {
929
- if (values.some((v) => v === false)) return false;
930
- if (values.some((v) => v === "unknown")) return "unknown";
931
- return true;
932
- }
933
- function kleeneOr(values) {
934
- if (values.some((v) => v === true)) return true;
935
- if (values.some((v) => v === "unknown")) return "unknown";
936
- return false;
937
- }
938
- function kleeneNot(value) {
939
- if (value === "unknown") return "unknown";
940
- return !value;
941
- }
942
- function resolveOperand(operand, ctx) {
943
- switch (operand.kind) {
944
- case "literal": return {
945
- known: true,
946
- value: operand.value
947
- };
948
- case "authUid": return {
949
- known: true,
950
- value: ctx.uid ?? null
951
- };
952
- case "authRoles": return {
953
- known: true,
954
- value: ctx.roles ?? []
955
- };
956
- case "field":
957
- if (!ctx.entity) return { known: false };
958
- return {
959
- known: true,
960
- value: ctx.entity.values[operand.name]
961
- };
962
- case "outerField": return { known: false };
963
- }
964
- }
965
- function evaluateCompare(op, left, right, ctx) {
966
- const l = resolveOperand(left, ctx);
967
- const r = resolveOperand(right, ctx);
968
- if (!l.known || !r.known) return "unknown";
969
- const a = l.value;
970
- const b = r.value;
971
- if (a === null || b === null) {
972
- if (op === "eq") return false;
973
- if (op === "neq") return true;
974
- return "unknown";
975
- }
976
- if (op === "eq") return a === b;
977
- if (op === "neq") return a !== b;
978
- if (typeof a === "string" && typeof b === "string") {
979
- if (op === "lt") return a < b;
980
- if (op === "lte") return a <= b;
981
- if (op === "gt") return a > b;
982
- if (op === "gte") return a >= b;
983
- }
984
- if (typeof a === "number" && typeof b === "number") {
985
- if (op === "lt") return a < b;
986
- if (op === "lte") return a <= b;
987
- if (op === "gt") return a > b;
988
- if (op === "gte") return a >= b;
989
- }
990
- if (typeof a === "bigint" && typeof b === "bigint") {
991
- if (op === "lt") return a < b;
992
- if (op === "lte") return a <= b;
993
- if (op === "gt") return a > b;
994
- if (op === "gte") return a >= b;
995
- }
996
- return "unknown";
997
- }
998
- //#endregion
999
- //#region src/util/permissions.ts
1000
- /** Combine clause results with AND under three-valued (Kleene) logic. */
1001
- function kleeneAnd(values) {
1002
- if (values.some((v) => v === false)) return false;
1003
- if (values.some((v) => v === "unknown")) return "unknown";
1004
- return true;
1005
- }
1006
- /** The operations a rule covers, mirroring the Postgres generator's resolution. */
1007
- function ruleOperations(rule) {
1008
- return rule.operations && rule.operations.length > 0 ? rule.operations : [rule.operation ?? "all"];
1009
- }
1010
- function ruleApplies(rule, targetOperation) {
1011
- const ops = ruleOperations(rule);
1012
- return ops.includes(targetOperation) || ops.includes("all");
1013
- }
1014
- /**
1015
- * Evaluate a single rule for one operation, returning a tri-state.
1016
- *
1017
- * A `null` clause (the rule contributes no condition for a required clause)
1018
- * denies — matching Postgres, which emits `USING (false)` / `WITH CHECK (false)`
1019
- * in that case. USING applies to SELECT/UPDATE/DELETE; WITH CHECK to
1020
- * INSERT/UPDATE; both must pass for UPDATE.
1021
- */
1022
- function evaluateRuleForOperation(rule, ctx, targetOperation) {
1023
- const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
1024
- const clause = (expr) => expr === null ? false : evaluatePolicy(expr, ctx);
1025
- const needsUsing = targetOperation !== "insert";
1026
- const needsWithCheck = targetOperation === "insert" || targetOperation === "update";
1027
- const results = [];
1028
- if (needsUsing) results.push(clause(usingExpr));
1029
- if (needsWithCheck) results.push(clause(withCheckExpr));
1030
- return kleeneAnd(results);
1031
- }
1032
- function resolveTriState(value, onUnknown) {
1033
- if (value === "unknown") return onUnknown === "allow";
1034
- return value;
1035
- }
1036
- /**
1037
- * Decide whether an operation is permitted for a user on a (possibly null) row,
1038
- * by evaluating the collection's security rules with the shared policy model —
1039
- * the same model compiled to Postgres RLS DDL, so the decision matches database
1040
- * enforcement for every non-raw rule.
1041
- *
1042
- * @param options.onUnknown how to treat rules that cannot be decided
1043
- * client-side (raw SQL, or row predicates with no row). Defaults to `"allow"`
1044
- * for optimistic UI gating; enforcement callers should pass `"deny"`.
1045
- */
1046
- function checkOperation(collection, authContext, entity, targetOperation, options) {
1047
- const onUnknown = options?.onUnknown ?? "allow";
1048
- const securityRules = (0, _rebasepro_types.getDataSourceCapabilities)(collection.engine).supportsRLS ? collection.securityRules : void 0;
1049
- if (!securityRules || securityRules.length === 0) return true;
1050
- const applicableRules = securityRules.filter((r) => ruleApplies(r, targetOperation));
1051
- if (applicableRules.length === 0) return false;
1052
- const ctx = {
1053
- uid: authContext.user?.uid,
1054
- roles: authContext.user?.roles ?? [],
1055
- entity
1056
- };
1057
- let grantedByPermissive = false;
1058
- let deniedByRestrictive = false;
1059
- let hasPermissive = false;
1060
- for (const rule of applicableRules) {
1061
- const mode = rule.mode || "permissive";
1062
- const passed = resolveTriState(evaluateRuleForOperation(rule, ctx, targetOperation), onUnknown);
1063
- if (mode === "restrictive") {
1064
- if (!passed) {
1065
- deniedByRestrictive = true;
1066
- break;
1067
- }
1068
- } else {
1069
- hasPermissive = true;
1070
- if (passed) grantedByPermissive = true;
1071
- }
1072
- }
1073
- if (deniedByRestrictive) return false;
1074
- return hasPermissive ? grantedByPermissive : false;
1075
- }
1076
- function canReadCollection(collection, authContext) {
1077
- return checkOperation(collection, authContext, null, "select");
1078
- }
1079
- function canEditEntity(collection, authContext, path, entity) {
1080
- return checkOperation(collection, authContext, entity, "update");
1081
- }
1082
- function canCreateEntity(collection, authContext, path, entity) {
1083
- return checkOperation(collection, authContext, entity, "insert");
1084
- }
1085
- function canDeleteEntity(collection, authContext, path, entity) {
1086
- return checkOperation(collection, authContext, entity, "delete");
1087
- }
1088
- //#endregion
1089
- //#region src/util/references.ts
1090
- function getEntityImagePreviewPropertyKey(collection) {
1091
- for (const key in collection.properties) {
1092
- const property = collection.properties[key];
1093
- if (property.type === "string" && property.storage?.acceptedFiles?.includes("image/*")) return key;
1094
- }
1095
- for (const key in collection.properties) {
1096
- const property = collection.properties[key];
1097
- if (property.type === "array" && !Array.isArray(property.of) && property.of?.type === "string" && property.of.storage?.acceptedFiles?.includes("image/*")) return key;
1098
- }
1099
- for (const key in collection.properties) {
1100
- const property = collection.properties[key];
1101
- if (property.type === "string" && property.ui?.url === "image") return key;
1102
- }
1103
- for (const key in collection.properties) {
1104
- const property = collection.properties[key];
1105
- if (property.type === "array" && property.of && !Array.isArray(property.of) && property.of.type === "string" && property.of.ui?.url === "image") return key;
1106
- }
1107
- for (const key in collection.properties) {
1108
- const property = collection.properties[key];
1109
- if (property.type === "string" && property.storage && !property.storage.acceptedFiles) return key;
1110
- }
1111
- for (const key in collection.properties) {
1112
- const property = collection.properties[key];
1113
- if (property.type === "array" && !Array.isArray(property.of) && property.of?.type === "string" && property.of.storage && !property.of.storage.acceptedFiles) return key;
1114
- }
1115
- }
1116
- //#endregion
1117
- //#region src/util/navigation_utils.ts
1118
- function removeInitialAndTrailingSlashes(s) {
1119
- return removeInitialSlash(removeTrailingSlash(s));
1120
- }
1121
- function removeInitialSlash(s) {
1122
- if (s.startsWith("/")) return s.slice(1);
1123
- else return s;
1124
- }
1125
- function removeTrailingSlash(s) {
1126
- if (s.endsWith("/")) return s.slice(0, -1);
1127
- else return s;
1128
- }
1129
- function addInitialSlash(s) {
1130
- if (s.startsWith("/")) return s;
1131
- else return `/${s}`;
1132
- }
1133
- function getLastSegment(path) {
1134
- const cleanPath = removeInitialAndTrailingSlashes(path);
1135
- if (cleanPath.includes("/")) {
1136
- const segments = cleanPath.split("/");
1137
- return segments[segments.length - 1];
1138
- }
1139
- return cleanPath;
1140
- }
1141
- function resolveCollectionPathIds(path, allCollections) {
1142
- let remainingPath = removeInitialAndTrailingSlashes(path);
1143
- if (!remainingPath) return "";
1144
- let currentCollections = allCollections;
1145
- const resolvedPathParts = [];
1146
- while (remainingPath.length > 0) {
1147
- if (!currentCollections || currentCollections.length === 0) {
1148
- console.warn(`resolveCollectionPathIds: Path structure implies subcollections, but none found before segment starting with "${remainingPath}" in original path "${path}". Appending remaining original path.`);
1149
- resolvedPathParts.push(remainingPath);
1150
- remainingPath = "";
1151
- break;
1152
- }
1153
- let foundMatch = false;
1154
- const potentialMatches = currentCollections.flatMap((col) => [{
1155
- col,
1156
- match: col.slug
1157
- }]).filter((p) => p.match && remainingPath.startsWith(p.match)).sort((a, b) => b.match.length - a.match.length);
1158
- if (potentialMatches.length > 0) {
1159
- const { col: foundCollection, match: matchString } = potentialMatches[0];
1160
- resolvedPathParts.push(foundCollection.slug);
1161
- remainingPath = removeInitialSlash(remainingPath.substring(matchString.length));
1162
- if (remainingPath.length === 0) {
1163
- foundMatch = true;
1164
- break;
1165
- }
1166
- const idSeparatorIndex = remainingPath.indexOf("/");
1167
- let entityId;
1168
- if (idSeparatorIndex > -1) {
1169
- entityId = remainingPath.substring(0, idSeparatorIndex);
1170
- remainingPath = remainingPath.substring(idSeparatorIndex + 1);
1171
- } else {
1172
- entityId = remainingPath;
1173
- remainingPath = "";
1174
- console.warn(`resolveCollectionPathIds: Path seems to end with a entity ID "${entityId}" instead of a collection segment in original path "${path}". This might indicate an invalid input path.`);
1175
- }
1176
- resolvedPathParts.push(entityId);
1177
- currentCollections = getSubcollections(foundCollection);
1178
- foundMatch = true;
1179
- if (!currentCollections && remainingPath.length > 0) {
1180
- 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.`);
1181
- resolvedPathParts.push(remainingPath);
1182
- remainingPath = "";
1183
- break;
1184
- }
1185
- }
1186
- if (!foundMatch) {
1187
- console.warn(`resolveCollectionPathIds: Collection definition not found for segment starting with "${remainingPath}" in original path "${path}". Appending remaining original path.`);
1188
- resolvedPathParts.push(remainingPath);
1189
- remainingPath = "";
1190
- break;
1191
- }
1192
- }
1193
- return resolvedPathParts.join("/");
1194
- }
1195
- /**
1196
- * Find the corresponding view at any depth for a given path.
1197
- * Note that path or segments of the paths can be collection aliases.
1198
- * @param slugOrPath
1199
- * @param collections
1200
- */
1201
- function getCollectionBySlugWithin(slugOrPath, collections) {
1202
- const subpaths = removeInitialAndTrailingSlashes(slugOrPath).split("/");
1203
- if (subpaths.length % 2 === 0) throw Error(`getCollectionBySlug: Collection paths must have an odd number of segments: ${slugOrPath}`);
1204
- const subpathCombinations = getCollectionPathsCombinations(subpaths);
1205
- let result;
1206
- for (let i = 0; i < subpathCombinations.length; i++) {
1207
- const subpathCombination = subpathCombinations[i];
1208
- const navigationEntry = collections && collections.sort((a, b) => (a.slug ?? "").localeCompare(b.slug ?? "")).find((entry) => entry.slug === subpathCombination);
1209
- if (navigationEntry) {
1210
- if (subpathCombination === slugOrPath) result = navigationEntry;
1211
- else if (getSubcollections(navigationEntry).length > 0) {
1212
- const newPath = slugOrPath.replace(subpathCombination, "").split("/").slice(2).join("/");
1213
- if (newPath.length > 0) result = getCollectionBySlugWithin(newPath, getSubcollections(navigationEntry));
1214
- }
1215
- }
1216
- if (result) break;
1217
- }
1218
- return result;
1219
- }
1220
- /**
1221
- * Get the subcollection combinations from a path:
1222
- * "sites/es/locales" => ["sites/es/locales", "sites"]
1223
- * @param subpaths
1224
- */
1225
- function getCollectionPathsCombinations(subpaths) {
1226
- const entries = subpaths.length > 0 && subpaths.length % 2 === 0 ? subpaths.splice(0, subpaths.length - 1) : subpaths;
1227
- const length = entries.length;
1228
- const result = [];
1229
- for (let i = length; i > 0; i = i - 2) result.push(entries.slice(0, i).join("/"));
1230
- return result;
1231
- }
1232
- //#endregion
1233
- //#region src/util/navigation_from_path.ts
1234
- function getNavigationEntriesFromPath(props) {
1235
- const { path, collections = [], currentFullPath } = props;
1236
- const subpathCombinations = getCollectionPathsCombinations(removeInitialAndTrailingSlashes(path).split("/"));
1237
- const result = [];
1238
- for (let i = 0; i < subpathCombinations.length; i++) {
1239
- const subpathCombination = subpathCombinations[i];
1240
- const collection = collections && collections.find((entry) => entry.slug === subpathCombination);
1241
- if (collection) {
1242
- const collectionPath = currentFullPath && currentFullPath.length > 0 ? currentFullPath + "/" + collection.slug : collection.slug;
1243
- result.push({
1244
- type: "collection",
1245
- id: collection.slug,
1246
- slug: collectionPath,
1247
- path: collectionPath,
1248
- collection
1249
- });
1250
- const restOfThePath = removeInitialAndTrailingSlashes(removeInitialAndTrailingSlashes(path).replace(subpathCombination, ""));
1251
- const nextSegments = restOfThePath.length > 0 ? restOfThePath.split("/") : [];
1252
- if (nextSegments.length > 0) {
1253
- const entityId = nextSegments[0];
1254
- const path = collectionPath + "/" + entityId;
1255
- result.push({
1256
- type: "entity",
1257
- entityId,
1258
- slug: collectionPath,
1259
- path,
1260
- parentCollection: collection
1261
- });
1262
- if (nextSegments.length > 1) {
1263
- const newPath = nextSegments.slice(1).join("/");
1264
- if (!collection) throw Error("collection not found resolving path: " + collection);
1265
- const entityViews = collection.entityViews;
1266
- const customView = entityViews && entityViews.map((entry) => resolveEntityView(entry, props.contextEntityViews)).filter((v) => v != null).find((entry) => entry.key === newPath);
1267
- const subcollections = getSubcollections(collection);
1268
- if (customView) result.push({
1269
- type: "custom_view",
1270
- slug: collectionPath,
1271
- entityId,
1272
- path: path + "/" + customView.key,
1273
- view: customView
1274
- });
1275
- else if (subcollections) result.push(...getNavigationEntriesFromPath({
1276
- path: newPath,
1277
- collections: subcollections,
1278
- currentFullPath: path,
1279
- contextEntityViews: props.contextEntityViews
1280
- }));
1281
- }
1282
- }
1283
- break;
1284
- }
1285
- }
1286
- return result;
1287
- }
1288
- function resolveEntityView(entityView, contextEntityViews) {
1289
- if (typeof entityView === "string") return contextEntityViews?.find((entry) => entry.key === entityView);
1290
- else return entityView;
1291
- }
1292
- //#endregion
1293
- //#region src/util/parent_references_from_path.ts
1294
- function getParentReferencesFromPath(props) {
1295
- const { path, collections = [], currentFullPath } = props;
1296
- const subpathCombinations = getCollectionPathsCombinations(removeInitialAndTrailingSlashes(path).split("/"));
1297
- const result = [];
1298
- for (let i = 0; i < subpathCombinations.length; i++) {
1299
- const subpathCombination = subpathCombinations[i];
1300
- const collection = collections && collections.find((entry) => entry.slug === subpathCombination);
1301
- if (collection) {
1302
- const collectionPath = currentFullPath && currentFullPath.length > 0 ? currentFullPath + "/" + collection.slug : collection.slug;
1303
- const restOfThePath = removeInitialAndTrailingSlashes(removeInitialAndTrailingSlashes(path).replace(subpathCombination, ""));
1304
- const nextSegments = restOfThePath.length > 0 ? restOfThePath.split("/") : [];
1305
- if (nextSegments.length > 0) {
1306
- const entityId = nextSegments[0];
1307
- const path = collectionPath + "/" + entityId;
1308
- result.push(new _rebasepro_types.EntityReference({
1309
- id: entityId,
1310
- path: collectionPath
1311
- }));
1312
- if (nextSegments.length > 1) {
1313
- const newPath = nextSegments.slice(1).join("/");
1314
- if (!collection) throw Error("collection not found resolving path: " + collection);
1315
- if (getSubcollections(collection).length > 0) result.push(...getParentReferencesFromPath({
1316
- path: newPath,
1317
- collections: getSubcollections(collection),
1318
- currentFullPath: path
1319
- }));
1320
- }
1321
- }
1322
- break;
1323
- }
1324
- }
1325
- return result;
1326
- }
1327
- //#endregion
1328
- //#region src/util/builders.ts
1329
- /**
1330
- * @deprecated Use {@link defineCollection} instead — it infers property
1331
- * types automatically (autocomplete on `titleProperty`, `sort`,
1332
- * `propertiesOrder`, callbacks) without manual generics.
1333
- * `buildCollection` is kept for FireCMS migration compatibility and will
1334
- * be removed before 1.0.
1335
- *
1336
- * @group Builder
1337
- */
1338
- function buildCollection(collection) {
1339
- return collection;
1340
- }
1341
- /**
1342
- * Implementation — delegates to the correct overload at the type level.
1343
- * At runtime this is a plain identity function.
1344
- */
1345
- function defineCollection(collection) {
1346
- return collection;
1347
- }
1348
- /**
1349
- * @deprecated Use plain typed property objects with {@link defineCollection}
1350
- * instead — `defineCollection` infers property types automatically, making
1351
- * this wrapper unnecessary. `buildProperty` is kept for FireCMS migration
1352
- * compatibility and will be removed before 1.0.
1353
- *
1354
- * @group Builder
1355
- */
1356
- function buildProperty(property) {
1357
- return property;
1358
- }
1359
- //#endregion
1360
- //#region src/util/storage.ts
1361
- /**
1362
- * Resolve the {@link StorageSource} to use for a property, given the key
1363
- * referenced by `StorageConfig.storageSource`.
1364
- *
1365
- * Resolution priority:
1366
- * 1. No `sourceKey` → the default source (backward compatible).
1367
- * 2. An explicit {@link StorageSourceRegistry} (e.g. `client.storageRegistry`).
1368
- * 3. A `sources` lookup map (e.g. the `StorageSourcesContext`).
1369
- * 4. Fall back to the default source.
1370
- *
1371
- * Shared by the upload hook, the markdown editor, and the read-only previews
1372
- * so the resolution logic lives in one place.
1373
- *
1374
- * @group Storage
1375
- */
1376
- function resolveStorageSource(params) {
1377
- const { sourceKey, sources, registry, defaultSource } = params;
1378
- if (!sourceKey) return defaultSource;
1379
- if (registry) return registry.getOrDefault(sourceKey);
1380
- const fromSources = sources?.[sourceKey];
1381
- if (fromSources) return fromSources;
1382
- return defaultSource;
1383
- }
1384
- async function resolveStorageFilenameString({ input, storage, values, entityId, path, property, file, propertyKey }) {
1385
- let result;
1386
- if (typeof input === "function") {
1387
- result = await input({
1388
- path,
1389
- entityId,
1390
- values,
1391
- property,
1392
- file,
1393
- storage,
1394
- propertyKey
1395
- });
1396
- if (!result) console.warn("Storage callback returned empty result. Using default name value");
1397
- } else result = replacePlaceholders({
1398
- file,
1399
- input,
1400
- entityId,
1401
- propertyKey,
1402
- path
1403
- });
1404
- if (!result) result = (0, _rebasepro_utils.randomString)() + "_" + file.name;
1405
- return result;
1406
- }
1407
- function resolveStoragePathString({ input, storage, values, entityId, path, property, file, propertyKey }) {
1408
- let result;
1409
- if (typeof input === "function") {
1410
- result = input({
1411
- path,
1412
- entityId,
1413
- values,
1414
- property,
1415
- file,
1416
- storage,
1417
- propertyKey
1418
- });
1419
- if (!result) console.warn("Storage callback returned empty result. Using default name value");
1420
- } else result = replacePlaceholders({
1421
- file,
1422
- input,
1423
- entityId,
1424
- propertyKey,
1425
- path
1426
- });
1427
- if (!result) result = (0, _rebasepro_utils.randomString)() + "_" + file.name;
1428
- return result;
1429
- }
1430
- function replacePlaceholders({ file, input, entityId, propertyKey, path }) {
1431
- const ext = file.name.split(".").pop();
1432
- let result = input.replace("{propertyKey}", propertyKey).replace("{rand}", (0, _rebasepro_utils.randomString)()).replace("{file}", file.name).replace("{file.type}", file.type);
1433
- if (entityId) result = result.replace("{entityId}", String(entityId));
1434
- if (path) result = result.replace("{path}", path);
1435
- if (ext) {
1436
- result = result.replace("{file.ext}", ext);
1437
- const name = file.name.replace(`.${ext}`, "");
1438
- result = result.replace("{file.name}", name);
1439
- }
1440
- if (!result) result = (0, _rebasepro_utils.randomString)() + "_" + file.name;
1441
- return result;
1442
- }
1443
- //#endregion
1444
- //#region src/util/callbacks.ts
1445
- /**
1446
- * Helper function to recursively check if there are any callbacks in the properties.
1447
- */
1448
- function hasPropertyCallbacks(properties, callbackName) {
1449
- if (!properties) return false;
1450
- for (const property of Object.values(properties)) {
1451
- if (property.callbacks?.[callbackName]) return true;
1452
- if (property.type === "map" && property.properties) {
1453
- if (hasPropertyCallbacks(property.properties, callbackName)) return true;
1454
- } else if (property.type === "array" && property.of) {
1455
- const ofs = Array.isArray(property.of) ? property.of : [property.of];
1456
- for (const of of ofs) {
1457
- if (of.callbacks?.[callbackName]) return true;
1458
- if (of.type === "map" && of.properties && hasPropertyCallbacks(of.properties, callbackName)) return true;
1459
- }
1460
- }
1461
- }
1462
- return false;
1463
- }
1464
- /**
1465
- * Recursively process properties to apply field-level hooks.
1466
- */
1467
- async function processProperties(properties, values, previousValues, propsContext, callbackName) {
1468
- if (!values || typeof values !== "object") return values;
1469
- const result = { ...values };
1470
- for (const [key, property] of Object.entries(properties)) {
1471
- if (result[key] === void 0) continue;
1472
- let currentValue = result[key];
1473
- const previousValue = previousValues?.[key];
1474
- if (property.type === "array" && Array.isArray(currentValue)) {
1475
- if (property.of && !Array.isArray(property.of)) currentValue = await Promise.all(currentValue.map(async (item, index) => {
1476
- const prevItem = Array.isArray(previousValue) ? previousValue[index] : void 0;
1477
- return (await processProperties({ "_tmp": property.of }, { "_tmp": item }, { "_tmp": prevItem }, propsContext, callbackName))["_tmp"];
1478
- }));
1479
- } else if (property.type === "map" && property.properties && typeof currentValue === "object") currentValue = await processProperties(property.properties, currentValue, previousValue ?? {}, propsContext, callbackName);
1480
- if (property.callbacks?.[callbackName]) {
1481
- const cbRes = await Promise.resolve(property.callbacks[callbackName]({
1482
- ...propsContext,
1483
- value: currentValue,
1484
- previousValue
1485
- }));
1486
- if (cbRes !== void 0) currentValue = cbRes;
1487
- }
1488
- result[key] = currentValue;
1489
- }
1490
- return result;
1491
- }
1492
- /**
1493
- * Helper function to extract field-level PropertyCallbacks from a properties schema
1494
- * and wrap them into an CollectionCallbacks object recursively.
1495
- */
1496
- var buildPropertyCallbacks = (properties) => {
1497
- if (!properties) return void 0;
1498
- const propertyCallbacks = {};
1499
- if (hasPropertyCallbacks(properties, "afterRead")) propertyCallbacks.afterRead = async (props) => {
1500
- const row = props.row;
1501
- const processedValues = await processProperties(properties, row, row, props, "afterRead");
1502
- return {
1503
- ...props.row,
1504
- ...processedValues
1505
- };
1506
- };
1507
- if (hasPropertyCallbacks(properties, "beforeSave")) propertyCallbacks.beforeSave = async (props) => {
1508
- return await processProperties(properties, props.values, props.previousValues ?? {}, props, "beforeSave");
1509
- };
1510
- return Object.keys(propertyCallbacks).length > 0 ? propertyCallbacks : void 0;
1511
- };
1512
- //#endregion
1513
- //#region src/util/conditions.ts
1514
- /**
1515
- * Access a nested property from an object via dot notation.
1516
- */
1517
- function getIn(obj, path) {
1518
- if (!obj || !path) return void 0;
1519
- return path.split(".").reduce((acc, part) => acc && acc[part], obj);
1520
- }
1521
- var operationsRegistered = false;
1522
- /**
1523
- * Register custom JSON Logic operations for Rebase.
1524
- * Call this once at app initialization.
1525
- */
1526
- function registerConditionOperations() {
1527
- if (operationsRegistered) return;
1528
- json_logic_js.default.add_operation("hasRole", function(roleId) {
1529
- return this?.user?.roles?.includes(roleId) ?? false;
1530
- });
1531
- json_logic_js.default.add_operation("hasAnyRole", function(roleIds) {
1532
- if (!this?.user?.roles || !Array.isArray(roleIds)) return false;
1533
- return roleIds.some((role) => this.user.roles.includes(role));
1534
- });
1535
- json_logic_js.default.add_operation("isToday", (timestamp) => {
1536
- if (!timestamp) return false;
1537
- const date = new Date(timestamp);
1538
- const today = /* @__PURE__ */ new Date();
1539
- return date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate();
1540
- });
1541
- json_logic_js.default.add_operation("isPast", (timestamp) => {
1542
- if (!timestamp) return false;
1543
- return timestamp < Date.now();
1544
- });
1545
- json_logic_js.default.add_operation("isFuture", (timestamp) => {
1546
- if (!timestamp) return false;
1547
- return timestamp > Date.now();
1548
- });
1549
- operationsRegistered = true;
1550
- }
1551
- /**
1552
- * Evaluate a JSON Logic rule against the given context.
1553
- */
1554
- function evaluateCondition(rule, context) {
1555
- registerConditionOperations();
1556
- return json_logic_js.default.apply(rule, context);
1557
- }
1558
- /**
1559
- * Convert a value to a format suitable for JSON Logic evaluation.
1560
- * Specifically handles Date objects by converting them to Unix timestamps.
1561
- */
1562
- function serializeValueForConditions(value) {
1563
- if (value === null || value === void 0) return value;
1564
- if (value instanceof Date) return value.getTime();
1565
- if (typeof value?.toMillis === "function") return value.toMillis();
1566
- if (typeof value?.toDate === "function") return value.toDate().getTime();
1567
- if (Array.isArray(value)) return value.map(serializeValueForConditions);
1568
- if (typeof value === "object") {
1569
- const result = {};
1570
- for (const key of Object.keys(value)) result[key] = serializeValueForConditions(value[key]);
1571
- return result;
1572
- }
1573
- return value;
1574
- }
1575
- /**
1576
- * Build a ConditionContext from the current property resolution context.
1577
- */
1578
- function buildConditionContext(params) {
1579
- const { propertyKey, values, previousValues, path, entityId, index, authController } = params;
1580
- const user = authController.user;
1581
- const serializedValues = serializeValueForConditions(values ?? {});
1582
- return {
1583
- values: serializedValues,
1584
- previousValues: serializeValueForConditions(previousValues ?? values ?? {}),
1585
- propertyValue: propertyKey ? getIn(serializedValues, propertyKey) : void 0,
1586
- path,
1587
- entityId,
1588
- isNew: !entityId,
1589
- index,
1590
- user: {
1591
- uid: user?.uid ?? "",
1592
- email: user?.email ?? null,
1593
- displayName: user?.displayName ?? null,
1594
- photoURL: user?.photoURL ?? null,
1595
- roles: (user?.roles ?? []).map((r) => typeof r === "string" ? r : r.id)
1596
- },
1597
- now: Date.now()
1598
- };
1599
- }
1600
- /**
1601
- * Apply PropertyConditions to a resolved property, evaluating all JSON Logic rules.
1602
- */
1603
- function applyPropertyConditions(property, context) {
1604
- const { conditions } = property;
1605
- if (!conditions) return property;
1606
- const result = { ...property };
1607
- if (conditions.disabled) {
1608
- if (evaluateCondition(conditions.disabled, context)) {
1609
- result.ui = result.ui || {};
1610
- result.ui.disabled = {
1611
- clearOnDisabled: conditions.clearOnDisabled ?? false,
1612
- disabledMessage: conditions.disabledMessage,
1613
- hidden: false
1614
- };
1615
- }
1616
- }
1617
- if (conditions.hidden) {
1618
- if (evaluateCondition(conditions.hidden, context)) {
1619
- result.ui = result.ui || {};
1620
- result.ui.disabled = {
1621
- ...typeof result.ui?.disabled === "object" ? result.ui.disabled : {},
1622
- hidden: true,
1623
- clearOnDisabled: conditions.clearOnDisabled ?? false
1624
- };
1625
- }
1626
- }
1627
- if (conditions.readOnly) {
1628
- if (evaluateCondition(conditions.readOnly, context)) {
1629
- result.ui = result.ui || {};
1630
- result.ui.readOnly = true;
1631
- }
1632
- }
1633
- if (conditions.required !== void 0) {
1634
- const isRequired = evaluateCondition(conditions.required, context);
1635
- result.validation = {
1636
- ...result.validation,
1637
- required: isRequired,
1638
- requiredMessage: conditions.requiredMessage
1639
- };
1640
- }
1641
- if (context.isNew && conditions.defaultValue !== void 0) result.defaultValue = evaluateCondition(conditions.defaultValue, context);
1642
- if ("enum" in result && result.enum && (conditions.enumConditions || conditions.allowedEnumValues || conditions.excludedEnumValues)) result.enum = applyEnumConditions(result.enum, conditions, context);
1643
- if (result.type === "reference") {
1644
- if (conditions.referencePath) result.path = evaluateCondition(conditions.referencePath, context);
1645
- if (conditions.referenceFilter) result.fixedFilter = evaluateCondition(conditions.referenceFilter, context);
1646
- }
1647
- if (result.type === "array") {
1648
- if (conditions.canAddElements !== void 0) result.canAddElements = evaluateCondition(conditions.canAddElements, context);
1649
- if (conditions.sortable !== void 0) result.sortable = evaluateCondition(conditions.sortable, context);
1650
- }
1651
- return result;
1652
- }
1653
- /**
1654
- * Convert an object with numeric keys back to an array.
1655
- * Firestore stores arrays as {"0": "a", "1": "b"} to avoid nested arrays.
1656
- */
1657
- function objectToArray(obj) {
1658
- if (Array.isArray(obj)) return obj.map(String);
1659
- if (obj && typeof obj === "object") {
1660
- const keys = Object.keys(obj);
1661
- 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);
1662
- }
1663
- return [];
1664
- }
1665
- /**
1666
- * Apply enum-specific conditions to filter and modify enum values.
1667
- */
1668
- function applyEnumConditions(enumValues, conditions, context) {
1669
- let result = [...enumValues];
1670
- if (conditions.allowedEnumValues) {
1671
- const allowedArray = objectToArray(evaluateCondition(conditions.allowedEnumValues, context));
1672
- if (allowedArray.length > 0) result = result.filter((ev) => allowedArray.includes(String(ev.id)));
1673
- }
1674
- if (conditions.excludedEnumValues) {
1675
- const excludedArray = objectToArray(evaluateCondition(conditions.excludedEnumValues, context));
1676
- if (excludedArray.length > 0) result = result.filter((ev) => !excludedArray.includes(String(ev.id)));
1677
- }
1678
- if (conditions.enumConditions) result = result.map((ev) => {
1679
- const evConditions = conditions.enumConditions?.[ev.id];
1680
- if (!evConditions) return ev;
1681
- if (evConditions.hidden && evaluateCondition(evConditions.hidden, context)) return null;
1682
- if (evConditions.disabled && evaluateCondition(evConditions.disabled, context)) return {
1683
- ...ev,
1684
- disabled: true
1685
- };
1686
- return ev;
1687
- }).filter((ev) => ev !== null);
1688
- return result;
1689
- }
1690
- //#endregion
1691
- //#region src/util/filter-operator-resolution.ts
1692
- /**
1693
- * Default operators offered per property type, before engine capabilities and
1694
- * per-property narrowing are applied. These mirror what the built-in filter
1695
- * fields can render.
1696
- */
1697
- var COMPARISON_OPS = [
1698
- "==",
1699
- "!=",
1700
- ">",
1701
- ">=",
1702
- "<",
1703
- "<="
1704
- ];
1705
- var NULL_CHECK_OPS = ["is-null", "is-not-null"];
1706
- var MEMBERSHIP_OPS = ["in", "not-in"];
1707
- var PATTERN_OPS = [
1708
- "like",
1709
- "ilike",
1710
- "not-like",
1711
- "not-ilike"
1712
- ];
1713
- var DEFAULT_OPS_BY_TYPE = {
1714
- string: [
1715
- ...COMPARISON_OPS,
1716
- ...MEMBERSHIP_OPS,
1717
- ...PATTERN_OPS,
1718
- ...NULL_CHECK_OPS
1719
- ],
1720
- number: [
1721
- ...COMPARISON_OPS,
1722
- ...MEMBERSHIP_OPS,
1723
- ...NULL_CHECK_OPS
1724
- ],
1725
- date: [...COMPARISON_OPS, ...NULL_CHECK_OPS],
1726
- boolean: [
1727
- "==",
1728
- "!=",
1729
- ...NULL_CHECK_OPS
1730
- ],
1731
- reference: [
1732
- "==",
1733
- "!=",
1734
- ...MEMBERSHIP_OPS,
1735
- ...NULL_CHECK_OPS
1736
- ],
1737
- relation: [
1738
- "==",
1739
- "!=",
1740
- ...MEMBERSHIP_OPS,
1741
- ...NULL_CHECK_OPS
1742
- ]
1743
- };
1744
- /** Operators offered when the property is an *array of* a filterable type. */
1745
- var ARRAY_OPS = ["array-contains", "array-contains-any"];
1746
- /**
1747
- * Resolve which filter operators the UI should offer for a property.
1748
- *
1749
- * The result is the **intersection** of three sets:
1750
- * 1. what the engine can execute — {@link DataSourceCapabilities.filterOperators}
1751
- * (e.g. Firestore cannot run the LIKE family);
1752
- * 2. what makes sense for the property type (e.g. no `>` on booleans);
1753
- * 3. the developer's optional narrowing — `property.ui.filterOperators`.
1754
- *
1755
- * Returns an empty array when the property is not filterable (either by
1756
- * type, or because the developer disabled it with `filterOperators: []`).
1757
- *
1758
- * @group Models
1759
- */
1760
- function resolveFilterOperators({ property, isArray, engine }) {
1761
- const typeDefaults = isArray ? ARRAY_OPS : DEFAULT_OPS_BY_TYPE[property.type] ?? [];
1762
- if (typeDefaults.length === 0) return [];
1763
- const engineOps = new Set((0, _rebasepro_types.getDataSourceCapabilities)(engine).filterOperators ?? _rebasepro_types.ALL_WHERE_FILTER_OPS);
1764
- const narrowing = property.ui?.filterOperators;
1765
- const narrowingSet = narrowing !== void 0 ? new Set(narrowing) : void 0;
1766
- return typeDefaults.filter((op) => engineOps.has(op) && (narrowingSet === void 0 || narrowingSet.has(op)));
1767
- }
1768
- //#endregion
1769
- //#region src/data/resolveDataSource.ts
1770
- /**
1771
- * Build a keyed registry from a list of {@link DataSourceDefinition}s.
1772
- * Later entries win on key collision.
1773
- */
1774
- function createDataSourceRegistry(definitions) {
1775
- const registry = {};
1776
- for (const def of definitions ?? []) registry[def.key] = def;
1777
- return registry;
1778
- }
1779
- /**
1780
- * Resolve the effective data source for a collection — the single source of
1781
- * truth shared by the frontend router, the backend driver registry, and the
1782
- * editor's capability lookups.
1783
- *
1784
- * Resolution order:
1785
- * 1. The routing **key** is `collection.dataSource`, else
1786
- * {@link DEFAULT_DATA_SOURCE_KEY}.
1787
- * 2. If a definition is registered for that key, it provides `engine`,
1788
- * `transport`, and `databaseId`.
1789
- * 3. Otherwise values are synthesized: `engine` from `collection.engine`
1790
- * (or the key, or `"postgres"`), `transport` defaults to `"server"`,
1791
- * and `databaseId` from the collection.
1792
- *
1793
- * `capabilities` are always derived from the resolved `engine`, so two
1794
- * data sources sharing an engine share capabilities.
1795
- *
1796
- * @param collection the collection (or any object carrying the routing fields)
1797
- * @param registry optional registry of declared data sources
1798
- */
1799
- function resolveDataSource(collection, registry) {
1800
- const key = collection?.dataSource ?? _rebasepro_types.DEFAULT_DATA_SOURCE_KEY;
1801
- const def = registry?.[key];
1802
- const engine = def?.engine ?? collection?.engine ?? (key !== _rebasepro_types.DEFAULT_DATA_SOURCE_KEY ? key : "postgres");
1803
- return {
1804
- key,
1805
- engine,
1806
- transport: def?.transport ?? "server",
1807
- databaseId: collection?.databaseId ?? def?.databaseId,
1808
- capabilities: (0, _rebasepro_types.getDataSourceCapabilities)(engine)
1809
- };
1810
- }
1811
- //#endregion
1812
- //#region src/collections/CollectionRegistry.ts
1813
- var CollectionRegistry = class {
1814
- /**
1815
- * Declared data sources, used during normalization to resolve each
1816
- * collection's engine (so `dataSource`-only collections get the right
1817
- * capabilities). Empty by default.
1818
- */
1819
- dataSources = {};
1820
- /**
1821
- * Global lifecycle callbacks applied to every collection.
1822
- * Runs on all data paths (REST, WebSocket, `rebase.data`).
1823
- * Execution order: global → collection → property callbacks.
1824
- */
1825
- _globalCallbacks;
1826
- /**
1827
- * Set global lifecycle callbacks that apply to every collection.
1828
- * Typically called once during backend initialization.
1829
- */
1830
- setGlobalCallbacks(callbacks) {
1831
- this._globalCallbacks = callbacks;
1832
- }
1833
- /**
1834
- * Get the currently registered global callbacks, if any.
1835
- */
1836
- getGlobalCallbacks() {
1837
- return this._globalCallbacks;
1838
- }
1839
- collectionsByTableName = /* @__PURE__ */ new Map();
1840
- collectionsBySlug = /* @__PURE__ */ new Map();
1841
- rootCollections = [];
1842
- cachedCollectionsList = null;
1843
- rawCollectionsByTableName = /* @__PURE__ */ new Map();
1844
- rawCollectionsBySlug = /* @__PURE__ */ new Map();
1845
- rawRootCollections = [];
1846
- cachedRawCollectionsList = null;
1847
- lastRawInputEntity = null;
1848
- constructor(collections, dataSources) {
1849
- if (dataSources) this.dataSources = dataSources;
1850
- if (collections) this.registerMultiple(collections);
1851
- }
1852
- /**
1853
- * Provide the declared data sources used to resolve each collection's
1854
- * engine during normalization. Set this before registering collections.
1855
- * Returns true if the registry changed (callers may re-register).
1856
- */
1857
- setDataSources(dataSources) {
1858
- if ((0, fast_equals.deepEqual)(this.dataSources, dataSources)) return false;
1859
- this.dataSources = dataSources ?? {};
1860
- return true;
1861
- }
1862
- reset() {
1863
- this.collectionsByTableName.clear();
1864
- this.collectionsBySlug.clear();
1865
- this.rootCollections = [];
1866
- this.cachedCollectionsList = null;
1867
- this.rawCollectionsByTableName.clear();
1868
- this.rawCollectionsBySlug.clear();
1869
- this.rawRootCollections = [];
1870
- this.cachedRawCollectionsList = null;
1871
- }
1872
- /**
1873
- * Registers a collection and its subcollections recursively.
1874
- * Returns true if the collections have changed, false otherwise.
1875
- *
1876
- * Idempotent: compares the raw input (before normalization) against a stored
1877
- * entity. Only re-normalizes and re-registers when the raw input actually changed.
1878
- * @param collections
1879
- */
1880
- registerMultiple(collections) {
1881
- const rawEntity = collections.map((c) => (0, _rebasepro_utils.removeFunctions)(c));
1882
- if (this.lastRawInputEntity && (0, fast_equals.deepEqual)(this.lastRawInputEntity, rawEntity)) return false;
1883
- this.reset();
1884
- collections.forEach((c) => {
1885
- if (c.slug) this.collectionsBySlug.set(c.slug, c);
1886
- this.collectionsByTableName.set(getTableName(c), c);
1887
- });
1888
- const normalizedCollections = collections.map((c) => this.normalizeCollection({ ...c }));
1889
- normalizedCollections.forEach((c, index) => {
1890
- const raw = (0, _rebasepro_utils.deepClone)(collections[index]);
1891
- this.rootCollections.push(c);
1892
- this.rawRootCollections.push(raw);
1893
- const normalized = this.normalizeCollection(c);
1894
- this.collectionsByTableName.set(getTableName(normalized), normalized);
1895
- this.rawCollectionsByTableName.set(getTableName(raw), raw);
1896
- if (normalized.slug) this.collectionsBySlug.set(normalized.slug, normalized);
1897
- if (raw.slug) this.rawCollectionsBySlug.set(raw.slug, raw);
1898
- });
1899
- normalizedCollections.forEach((c) => {
1900
- const subcollections = getSubcollections(c);
1901
- if (subcollections && subcollections.length > 0) subcollections.forEach((subCollection) => {
1902
- if (!subCollection) return;
1903
- this._registerRecursively(this.normalizeCollection({ ...subCollection }), (0, _rebasepro_utils.deepClone)(subCollection));
1904
- });
1905
- });
1906
- this.lastRawInputEntity = rawEntity;
1907
- return true;
1908
- }
1909
- register(collection, rawCollection) {
1910
- const raw = rawCollection ? (0, _rebasepro_utils.deepClone)(rawCollection) : (0, _rebasepro_utils.deepClone)(collection);
1911
- this.rootCollections.push(collection);
1912
- this.rawRootCollections.push(raw);
1913
- this._registerRecursively(collection, raw);
1914
- }
1915
- _registerRecursively(collection, rawCollection) {
1916
- if (this.collectionsByTableName.has(getTableName(collection))) return;
1917
- const normalizedCollection = this.normalizeCollection(collection);
1918
- this.collectionsByTableName.set(getTableName(normalizedCollection), normalizedCollection);
1919
- this.rawCollectionsByTableName.set(getTableName(rawCollection), rawCollection);
1920
- if (normalizedCollection.slug) this.collectionsBySlug.set(normalizedCollection.slug, normalizedCollection);
1921
- if (rawCollection.slug) this.rawCollectionsBySlug.set(rawCollection.slug, rawCollection);
1922
- const subcollections = getSubcollections(normalizedCollection);
1923
- if (subcollections && subcollections.length > 0) subcollections.forEach((subCollection) => {
1924
- if (!subCollection) return;
1925
- this._registerRecursively(this.normalizeCollection({ ...subCollection }), (0, _rebasepro_utils.deepClone)(subCollection));
1926
- });
1927
- }
1928
- normalizeCollection(collection) {
1929
- const result = { ...collection };
1930
- {
1931
- const resolved = resolveDataSource(result, this.dataSources);
1932
- if (!result.dataSource) result.dataSource = resolved.key;
1933
- if (!result.engine) result.engine = resolved.engine;
1934
- }
1935
- const extractedRelations = this.extractRelationsFromProperties(result.properties);
1936
- const relResult = result;
1937
- const manualRelations = (0, _rebasepro_types.getDataSourceCapabilities)(result.engine).supportsRelations ? relResult.relations ?? [] : [];
1938
- const mergedRelationsRaw = [...extractedRelations];
1939
- for (const manual of manualRelations) {
1940
- const name = manual.relationName;
1941
- if (!name) mergedRelationsRaw.push(manual);
1942
- else {
1943
- const existingIndex = mergedRelationsRaw.findIndex((r) => r.relationName === name);
1944
- if (existingIndex === -1) mergedRelationsRaw.push(manual);
1945
- else mergedRelationsRaw[existingIndex] = {
1946
- ...manual,
1947
- ...mergedRelationsRaw[existingIndex]
1948
- };
1949
- }
1950
- }
1951
- let mergedRelations = mergedRelationsRaw;
1952
- if ((0, _rebasepro_types.getDataSourceCapabilities)(result.engine).supportsRelations) {
1953
- mergedRelations = mergedRelationsRaw.map((r) => {
1954
- try {
1955
- return sanitizeRelation(r, result, (slug) => this.get(slug));
1956
- } catch {
1957
- return r;
1958
- }
1959
- });
1960
- relResult.relations = mergedRelations;
1961
- }
1962
- result.properties = this.normalizeProperties(result.properties, mergedRelations);
1963
- if (!result.childCollections) {
1964
- const capabilities = (0, _rebasepro_types.getDataSourceCapabilities)(result.engine);
1965
- const declaredSubcollections = (0, _rebasepro_types.getDeclaredSubcollections)(result);
1966
- if (capabilities.supportsSubcollections && declaredSubcollections) result.childCollections = declaredSubcollections;
1967
- else if (capabilities.supportsRelations && relResult.relations) {
1968
- const manyRelations = relResult.relations.filter((r) => r.cardinality === "many");
1969
- if (manyRelations.length > 0) result.childCollections = () => manyRelations.map((r) => {
1970
- const target = r.target();
1971
- return r.overrides ? (0, _rebasepro_utils.mergeDeep)(target, r.overrides) : target;
1972
- });
1973
- }
1974
- }
1975
- return result;
1976
- }
1977
- /**
1978
- * Extract Relation[] from properties that have inline relation config (i.e. `target` is set).
1979
- * This allows developers to define relations directly on properties without a separate
1980
- * `relations[]` entry on the collection.
1981
- */
1982
- extractRelationsFromProperties(properties) {
1983
- const relations = [];
1984
- for (const [key, property] of Object.entries(properties)) if (property.type === "relation") {
1985
- const relProp = property;
1986
- const target = relProp.target ?? relProp.relation?.target;
1987
- if (target) {
1988
- const relationName = relProp.relationName ?? relProp.relation?.relationName ?? key;
1989
- relations.push({
1990
- relationName,
1991
- target,
1992
- cardinality: relProp.cardinality ?? relProp.relation?.cardinality ?? "one",
1993
- direction: relProp.direction ?? relProp.relation?.direction ?? "owning",
1994
- inverseRelationName: relProp.inverseRelationName ?? relProp.relation?.inverseRelationName,
1995
- localKey: relProp.localKey ?? relProp.relation?.localKey,
1996
- foreignKeyOnTarget: relProp.foreignKeyOnTarget ?? relProp.relation?.foreignKeyOnTarget,
1997
- through: relProp.through ?? relProp.relation?.through,
1998
- joinPath: relProp.joinPath ?? relProp.relation?.joinPath,
1999
- onUpdate: relProp.onUpdate ?? relProp.relation?.onUpdate,
2000
- onDelete: relProp.onDelete ?? relProp.relation?.onDelete,
2001
- overrides: relProp.overrides ?? relProp.relation?.overrides
2002
- });
2003
- }
2004
- } else if (property.type === "map" && property.properties) relations.push(...this.extractRelationsFromProperties(property.properties));
2005
- return relations;
2006
- }
2007
- normalizeProperties(properties, relations) {
2008
- const newProperties = {};
2009
- for (const key in properties) newProperties[key] = this.normalizeProperty(key, properties[key], relations);
2010
- return newProperties;
2011
- }
2012
- normalizeProperty(key, property, relations) {
2013
- const newProperty = { ...property };
2014
- if (newProperty.type === "map" && newProperty.properties) newProperty.properties = this.normalizeProperties(newProperty.properties, relations);
2015
- else if (newProperty.type === "array") {
2016
- const arrayProp = newProperty;
2017
- if (arrayProp.of) if (Array.isArray(arrayProp.of)) arrayProp.of = arrayProp.of.map((p, i) => this.normalizeProperty(`${key}[${i}]`, p, relations));
2018
- else arrayProp.of = this.normalizeProperty(`${key}.of`, arrayProp.of, relations);
2019
- else if (arrayProp.oneOf && arrayProp.oneOf.properties) arrayProp.oneOf.properties = this.normalizeProperties(arrayProp.oneOf.properties, relations);
2020
- } else if ((newProperty.type === "string" || newProperty.type === "number") && newProperty.enum) {
2021
- const stringOrNumberProperty = newProperty;
2022
- if (typeof stringOrNumberProperty.enum === "object" && !Array.isArray(stringOrNumberProperty.enum)) stringOrNumberProperty.enum = enumToObjectEntries(stringOrNumberProperty.enum)?.filter((value) => value && (value.id || value.id === 0) && value.label) ?? [];
2023
- } else if (newProperty.type === "relation") {
2024
- const relationProperty = newProperty;
2025
- const name = relationProperty.relationName || key;
2026
- const relation = relations.find((r) => r.relationName === name);
2027
- if (relation) relationProperty.relation = relation;
2028
- else console.warn(`Could not find relation for property '${key}' with relationName: ${name}`);
2029
- }
2030
- return newProperty;
2031
- }
2032
- get(path) {
2033
- const bySlug = this.collectionsBySlug.get(path);
2034
- if (bySlug) return bySlug;
2035
- if (path.includes("-")) {
2036
- const normalized = path.replace(/-/g, "_");
2037
- const byNormalized = this.collectionsBySlug.get(normalized);
2038
- if (byNormalized) return byNormalized;
2039
- }
2040
- return this.collectionsByTableName.get(path);
2041
- }
2042
- /**
2043
- * Gets the pristine, un-normalized collection exactly as it was provided.
2044
- * Useful for the AST editor so it doesn't accidentally serialize injected metadata back to disk.
2045
- */
2046
- getRaw(path) {
2047
- const bySlug = this.rawCollectionsBySlug.get(path);
2048
- if (bySlug) return bySlug;
2049
- if (path.includes("-")) {
2050
- const normalized = path.replace(/-/g, "_");
2051
- const byNormalized = this.rawCollectionsBySlug.get(normalized);
2052
- if (byNormalized) return byNormalized;
2053
- }
2054
- return this.rawCollectionsByTableName.get(path);
2055
- }
2056
- /**
2057
- * Get collection by resolving multi-segment paths through relations
2058
- * e.g., "authors/70/posts" resolves to the posts collection
2059
- */
2060
- getCollectionByPath(collectionPath) {
2061
- if (!collectionPath.includes("/")) return this.get(collectionPath);
2062
- const pathSegments = collectionPath.split("/").filter((p) => p);
2063
- 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`);
2064
- const rootCollectionPath = pathSegments[0];
2065
- let currentCollection = this.get(rootCollectionPath);
2066
- if (!currentCollection) throw new Error(`Root collection not found: ${rootCollectionPath}`);
2067
- for (let i = 2; i < pathSegments.length; i += 2) {
2068
- const relationKey = pathSegments[i];
2069
- 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}'`);
2070
- const relation = findRelation(resolveCollectionRelations(currentCollection), relationKey);
2071
- if (!relation) throw new Error(`Relation '${relationKey}' not found in collection '${currentCollection.slug}'`);
2072
- const target = relation.target();
2073
- const targetRelationKey = relation.relationName || target.slug;
2074
- const targetSlug = relation.overrides?.slug ?? targetRelationKey;
2075
- currentCollection = this.get(targetSlug) || this.normalizeCollection(target);
2076
- if (i + 1 < pathSegments.length) {}
2077
- }
2078
- return currentCollection;
2079
- }
2080
- getCollections() {
2081
- if (!this.cachedCollectionsList) this.cachedCollectionsList = Array.from(this.collectionsByTableName.values());
2082
- return this.cachedCollectionsList;
2083
- }
2084
- getRawCollections() {
2085
- if (!this.cachedRawCollectionsList) this.cachedRawCollectionsList = Array.from(this.rawCollectionsByTableName.values());
2086
- return this.cachedRawCollectionsList;
2087
- }
2088
- /**
2089
- * Resolves a multi-segment path like "products/123/locales" and returns
2090
- * information about the collections and entity IDs along the path
2091
- */
2092
- resolvePathToCollections(path) {
2093
- const pathSegments = path.split("/").filter((p) => p);
2094
- if (pathSegments.length === 0) throw new Error(`Invalid path: ${path}`);
2095
- if (pathSegments.length % 2 !== 1) throw new Error(`Invalid collection path: ${path}. It must have an odd number of segments.`);
2096
- const collections = [];
2097
- const entityIds = [];
2098
- let currentCollection = this.get(pathSegments[0]);
2099
- if (!currentCollection) throw new Error(`Unknown collection path or slug: ${pathSegments[0]}`);
2100
- collections.push(currentCollection);
2101
- for (let i = 1; i < pathSegments.length; i += 2) {
2102
- const entityId = pathSegments[i];
2103
- entityIds.push(entityId);
2104
- if (i + 1 < pathSegments.length) {
2105
- const subcollectionSlug = pathSegments[i + 1];
2106
- const subcollections = getSubcollections(currentCollection);
2107
- if (!subcollections || subcollections.length === 0) throw new Error(`No subcollections found for ${currentCollection.slug} in path: ${path}`);
2108
- const subcollection = subcollections.find((c) => c.slug === subcollectionSlug);
2109
- if (!subcollection) throw new Error(`Subcollection '${subcollectionSlug}' not found in ${currentCollection.slug}`);
2110
- currentCollection = this.get(subcollection.slug) || this.normalizeCollection(subcollection);
2111
- collections.push(currentCollection);
2112
- }
2113
- }
2114
- return {
2115
- collections,
2116
- entityIds,
2117
- finalCollection: currentCollection
2118
- };
2119
- }
2120
- };
2121
- //#endregion
2122
- //#region src/collections/default-collections.ts
2123
- /**
2124
- * Default users collection.
2125
- *
2126
- * Prepended to the developer's collections array by the admin and server.
2127
- * Slug-based dedup (Map keyed by slug, last-write-wins) lets developers
2128
- * override by defining their own collection with `slug: "users"`.
2129
- */
2130
- var defaultUsersCollection = defineCollection({
2131
- name: "Users",
2132
- singularName: "User",
2133
- slug: "users",
2134
- auth: true,
2135
- table: "users",
2136
- schema: "rebase",
2137
- icon: "Users",
2138
- group: "Settings",
2139
- openEntityMode: "dialog",
2140
- disableDefaultActions: ["copy"],
2141
- securityRules: [{
2142
- operation: "select",
2143
- roles: ["admin"]
2144
- }, {
2145
- operations: [
2146
- "insert",
2147
- "update",
2148
- "delete"
2149
- ],
2150
- roles: ["admin"]
2151
- }],
2152
- sort: ["createdAt", "desc"],
2153
- properties: {
2154
- id: {
2155
- name: "ID",
2156
- type: "string",
2157
- isId: "uuid",
2158
- ui: { readOnly: true }
2159
- },
2160
- email: {
2161
- name: "Email",
2162
- type: "string",
2163
- validation: {
2164
- required: true,
2165
- unique: true
2166
- }
2167
- },
2168
- displayName: {
2169
- name: "Name",
2170
- type: "string",
2171
- columnName: "display_name",
2172
- validation: { required: true }
2173
- },
2174
- photoURL: {
2175
- name: "Photo URL",
2176
- type: "string",
2177
- columnName: "photo_url",
2178
- ui: { url: "image" }
2179
- },
2180
- roles: {
2181
- name: "Roles",
2182
- type: "array",
2183
- columnType: "text[]",
2184
- of: {
2185
- name: "Role",
2186
- type: "string",
2187
- enum: {
2188
- admin: "Admin",
2189
- editor: "Editor",
2190
- viewer: "Viewer"
2191
- }
2192
- }
2193
- },
2194
- passwordHash: {
2195
- name: "Password Hash",
2196
- type: "string",
2197
- columnName: "password_hash",
2198
- ui: {
2199
- hideFromCollection: true,
2200
- disabled: { hidden: true }
2201
- }
2202
- },
2203
- emailVerified: {
2204
- name: "Email Verified",
2205
- type: "boolean",
2206
- columnName: "email_verified",
2207
- defaultValue: false,
2208
- ui: {
2209
- hideFromCollection: true,
2210
- disabled: { hidden: true }
2211
- }
2212
- },
2213
- emailVerificationToken: {
2214
- name: "Email Verification Token",
2215
- type: "string",
2216
- columnName: "email_verification_token",
2217
- ui: {
2218
- hideFromCollection: true,
2219
- disabled: { hidden: true }
2220
- }
2221
- },
2222
- emailVerificationSentAt: {
2223
- name: "Email Verification Sent At",
2224
- type: "date",
2225
- columnName: "email_verification_sent_at",
2226
- ui: {
2227
- hideFromCollection: true,
2228
- disabled: { hidden: true }
2229
- }
2230
- },
2231
- metadata: {
2232
- name: "Metadata",
2233
- type: "map",
2234
- keyValue: true,
2235
- properties: {},
2236
- defaultValue: {},
2237
- ui: {
2238
- hideFromCollection: true,
2239
- disabled: { hidden: true }
2240
- }
2241
- },
2242
- createdAt: {
2243
- name: "Created At",
2244
- type: "date",
2245
- columnName: "created_at",
2246
- autoValue: "on_create",
2247
- ui: { readOnly: true }
2248
- },
2249
- updatedAt: {
2250
- name: "Updated At",
2251
- type: "date",
2252
- columnName: "updated_at",
2253
- autoValue: "on_update",
2254
- ui: {
2255
- hideFromCollection: true,
2256
- disabled: { hidden: true }
2257
- }
2258
- }
2259
- },
2260
- listProperties: [
2261
- "displayName",
2262
- "email",
2263
- "roles",
2264
- "createdAt"
2265
- ],
2266
- propertiesOrder: [
2267
- "id",
2268
- "email",
2269
- "displayName",
2270
- "roles",
2271
- "createdAt"
2272
- ]
2273
- });
2274
- //#endregion
2275
- //#region src/data/query_builder.ts
2276
- function or(...conditions) {
2277
- return {
2278
- type: "or",
2279
- conditions
2280
- };
2281
- }
2282
- function and(...conditions) {
2283
- return {
2284
- type: "and",
2285
- conditions
2286
- };
2287
- }
2288
- function cond(column, operator, value) {
2289
- return {
2290
- column,
2291
- operator,
2292
- value
2293
- };
2294
- }
2295
- var QueryBuilder = class {
2296
- collection;
2297
- params = { where: {} };
2298
- constructor(collection) {
2299
- this.collection = collection;
2300
- }
2301
- where(columnOrCondition, operator, value) {
2302
- if (typeof columnOrCondition === "object" && columnOrCondition !== null && "type" in columnOrCondition) {
2303
- this.params.logical = columnOrCondition;
2304
- return this;
2305
- }
2306
- if (!this.params.where) this.params.where = {};
2307
- const column = columnOrCondition;
2308
- const condition = [operator, value];
2309
- const existing = this.params.where[column];
2310
- if (existing === void 0) this.params.where[column] = condition;
2311
- else if (Array.isArray(existing) && existing.length > 0 && Array.isArray(existing[0])) this.params.where[column].push(condition);
2312
- else {
2313
- let firstCondition;
2314
- if (Array.isArray(existing) && existing.length === 2 && typeof existing[0] === "string") firstCondition = existing;
2315
- else firstCondition = ["==", existing];
2316
- this.params.where[column] = [firstCondition, condition];
2317
- }
2318
- return this;
2319
- }
2320
- /**
2321
- * Order the results by a specific column.
2322
- * @example
2323
- * client.collection('users').orderBy('createdAt', 'desc').find()
2324
- */
2325
- orderBy(column, direction = "asc") {
2326
- this.params.orderBy = [column, direction];
2327
- return this;
2328
- }
2329
- /**
2330
- * Limit the number of results returned.
2331
- */
2332
- limit(count) {
2333
- this.params.limit = count;
2334
- return this;
2335
- }
2336
- /**
2337
- * Skip the first N results.
2338
- */
2339
- offset(count) {
2340
- this.params.offset = count;
2341
- return this;
2342
- }
2343
- /**
2344
- * Set a free-text search string if supported by the backend.
2345
- */
2346
- search(searchString) {
2347
- this.params.searchString = searchString;
2348
- return this;
2349
- }
2350
- /**
2351
- * Include related entities in the response.
2352
- * Relations will be populated with full entity data instead of just IDs.
2353
- *
2354
- * @param relations - Relation names to include, or "*" for all.
2355
- * @example
2356
- * // Include specific relations
2357
- * client.data.posts.include("tags", "author").find()
2358
- *
2359
- * // Include all relations
2360
- * client.data.posts.include("*").find()
2361
- */
2362
- include(...relations) {
2363
- this.params.include = relations;
2364
- return this;
2365
- }
2366
- /**
2367
- * Execute the find query and return the results.
2368
- */
2369
- async find() {
2370
- return this.collection.find(this.params);
2371
- }
2372
- /**
2373
- * Listen to realtime updates matching this query.
2374
- */
2375
- listen(onUpdate, onError) {
2376
- if (!this.collection.listen) throw new Error("Listen is only available when RebaseClient is configured with a websocketUrl.");
2377
- return this.collection.listen(this.params, onUpdate, onError);
2378
- }
2379
- };
2380
- //#endregion
2381
- //#region src/data/filter-dialect.ts
2382
- /**
2383
- * REST wire-format adapter for the unified filter system.
2384
- *
2385
- * This module is the ONLY code in the entire codebase that knows about
2386
- * PostgREST-style dot-syntax strings (`eq.active`, `gt.18`, `in.(a,b)`).
2387
- * Everything else speaks `FilterValues` exclusively.
2388
- *
2389
- * Wire-format values are always strings — the wire format carries no type
2390
- * metadata, so type coercion is the responsibility of the server-side data
2391
- * driver which has access to the collection schema.
2392
- *
2393
- * Commas inside list values are backslash-escaped (`\,`), and literal
2394
- * backslashes are escaped as `\\`.
2395
- *
2396
- * @module
2397
- */
2398
- /**
2399
- * Serialize a JS value to its querystring representation.
2400
- * `null` is serialized as the literal string `"null"`.
2401
- */
2402
- function stringifyValue(value) {
2403
- if (value === null) return "null";
2404
- return String(value);
2405
- }
2406
- /**
2407
- * Escape a single list item for the wire format.
2408
- * `\` → `\\`, `,` → `\,`
2409
- */
2410
- function escapeListItem(value) {
2411
- return value.replace(/\\/g, "\\\\").replace(/,/g, "\\,");
2412
- }
2413
- /**
2414
- * Unescape a single list item from the wire format.
2415
- * `\\` → `\`, `\,` → `,`
2416
- */
2417
- function unescapeListItem(value) {
2418
- let result = "";
2419
- for (let i = 0; i < value.length; i++) if (value[i] === "\\" && i + 1 < value.length) {
2420
- result += value[i + 1];
2421
- i++;
2422
- } else result += value[i];
2423
- return result;
2424
- }
2425
- /**
2426
- * Split a parenthesized list string on unescaped commas.
2427
- * Input is the content between `(` and `)`.
2428
- *
2429
- * @example
2430
- * splitListItems("admin,editor") // ["admin", "editor"]
2431
- * splitListItems("hello\\, world,foo") // ["hello, world", "foo"]
2432
- */
2433
- function splitListItems(inner) {
2434
- const items = [];
2435
- let current = "";
2436
- for (let i = 0; i < inner.length; i++) if (inner[i] === "\\" && i + 1 < inner.length) {
2437
- current += inner[i] + inner[i + 1];
2438
- i++;
2439
- } else if (inner[i] === ",") {
2440
- items.push(unescapeListItem(current));
2441
- current = "";
2442
- } else current += inner[i];
2443
- items.push(unescapeListItem(current));
2444
- return items;
2445
- }
2446
- var REST_OP_LOOKUP = _rebasepro_types.REST_TO_CANONICAL;
2447
- var CANONICAL_OP_LOOKUP = _rebasepro_types.CANONICAL_TO_REST;
2448
- /**
2449
- * Serialize a single canonical condition tuple to a PostgREST dot-string.
2450
- *
2451
- * Throws `TypeError` if the input is not a valid `[WhereFilterOp, unknown]` tuple.
2452
- *
2453
- * @example
2454
- * serializeTuple(["==", "active"]) // "eq.active"
2455
- * serializeTuple(["in", ["admin","editor"]]) // "in.(admin,editor)"
2456
- * serializeTuple([">=", 18]) // "gte.18"
2457
- */
2458
- function serializeTuple(tuple) {
2459
- if (!Array.isArray(tuple) || tuple.length !== 2) throw new TypeError(`serializeTuple: expected a [WhereFilterOp, value] tuple, got ${JSON.stringify(tuple)}`);
2460
- const [op, value] = tuple;
2461
- if (typeof op !== "string") throw new TypeError(`serializeTuple: operator must be a string, got ${typeof op}`);
2462
- const restOp = CANONICAL_OP_LOOKUP[op];
2463
- if (!restOp) throw new TypeError(`serializeTuple: unknown operator "${op}". Valid operators: ${Object.keys(_rebasepro_types.CANONICAL_TO_REST).join(", ")}`);
2464
- if (Array.isArray(value)) return `${restOp}.(${value.map((v) => escapeListItem(stringifyValue(v))).join(",")})`;
2465
- return `${restOp}.${stringifyValue(value)}`;
2466
- }
2467
- /**
2468
- * Convert `FilterValues` (or `WireFilterValues`) to a PostgREST-style
2469
- * querystring record.
2470
- *
2471
- * - Canonical `[WhereFilterOp, value]` tuples are serialized strictly.
2472
- * - Pre-serialized PostgREST strings (e.g. `"eq.published"`) are passed through.
2473
- * - Single conditions produce a string value.
2474
- * - Multiple conditions on the same field produce a string array (repeated params).
2475
- *
2476
- * @example
2477
- * serializeFilter({ status: ["==", "active"] })
2478
- * // → { status: "eq.active" }
2479
- *
2480
- * serializeFilter({ age: [[">=", 18], ["<", 65]] })
2481
- * // → { age: ["gte.18", "lt.65"] }
2482
- *
2483
- * // Pre-serialized strings pass through unchanged:
2484
- * serializeFilter({ status: "eq.published" })
2485
- * // → { status: "eq.published" }
2486
- */
2487
- function serializeFilter(filter) {
2488
- const result = {};
2489
- for (const [field, condition] of Object.entries(filter)) {
2490
- if (condition === void 0) continue;
2491
- if (typeof condition === "string") {
2492
- result[field] = condition;
2493
- continue;
2494
- }
2495
- if (Array.isArray(condition) && condition.length > 0 && Array.isArray(condition[0])) result[field] = condition.map(serializeTuple);
2496
- else result[field] = serializeTuple(condition);
2497
- }
2498
- return result;
2499
- }
2500
- /**
2501
- * Parse a single PostgREST dot-string into a `[WhereFilterOp, unknown]` tuple.
2502
- *
2503
- * All values are returned as strings — the wire format carries no type
2504
- * metadata, so coercion is the data driver's responsibility.
2505
- *
2506
- * If the string doesn't match a known operator prefix, it falls back to
2507
- * `["==", originalString]` (treating the whole string as an equality value).
2508
- * This intentional defense handles values like `"user@host.com"` or
2509
- * `"1.2.3"` that happen to contain dots.
2510
- */
2511
- function deserializeSingle(raw) {
2512
- const dotIndex = raw.indexOf(".");
2513
- if (dotIndex === -1) return ["==", raw];
2514
- const prefix = raw.substring(0, dotIndex);
2515
- const rest = raw.substring(dotIndex + 1);
2516
- const canonicalOp = REST_OP_LOOKUP[prefix];
2517
- if (!canonicalOp) return ["==", raw];
2518
- if (_rebasepro_types.NULL_OPS.has(canonicalOp)) return [canonicalOp, null];
2519
- if (rest.startsWith("(") && rest.endsWith(")")) return [canonicalOp, splitListItems(rest.slice(1, -1))];
2520
- return [canonicalOp, rest];
2521
- }
2522
- /**
2523
- * Convert a PostgREST-style querystring record to `FilterValues`.
2524
- *
2525
- * - String values are parsed as single conditions.
2526
- * - String arrays (repeated query params) become multiple conditions on the same field.
2527
- *
2528
- * @example
2529
- * deserializeFilter({ status: "eq.active" })
2530
- * // → { status: ["==", "active"] }
2531
- *
2532
- * deserializeFilter({ age: ["gte.18", "lt.65"] })
2533
- * // → { age: [[">=", "18"], ["<", "65"]] }
2534
- */
2535
- function deserializeFilter(query) {
2536
- const result = {};
2537
- for (const [field, raw] of Object.entries(query)) {
2538
- if (raw === void 0) continue;
2539
- if (Array.isArray(raw) && raw.length === 2 && typeof raw[0] === "string" && (0, _rebasepro_types.toCanonicalOp)(raw[0]) === raw[0]) {
2540
- result[field] = raw;
2541
- continue;
2542
- }
2543
- if (Array.isArray(raw)) {
2544
- if (raw.length === 0) continue;
2545
- if (Array.isArray(raw[0]) && raw[0].length === 2 && typeof raw[0][0] === "string" && (0, _rebasepro_types.toCanonicalOp)(raw[0][0]) === raw[0][0]) {
2546
- result[field] = raw;
2547
- continue;
2548
- }
2549
- if (raw.length === 1) result[field] = typeof raw[0] === "string" ? deserializeSingle(raw[0]) : ["==", raw[0]];
2550
- else if (typeof raw[0] === "string" && raw[0].includes(".")) result[field] = raw.map((r) => typeof r === "string" ? deserializeSingle(r) : ["==", r]);
2551
- else result[field] = ["in", raw];
2552
- } else if (typeof raw === "string") result[field] = deserializeSingle(raw);
2553
- else result[field] = ["==", raw];
2554
- }
2555
- return result;
2556
- }
2557
- /**
2558
- * Serialize a `LogicalCondition` or `FilterCondition` to its wire-format string.
2559
- *
2560
- * @example
2561
- * serializeLogicalCondition({ column: "status", operator: "==", value: "active" })
2562
- * // → "status.eq.active"
2563
- *
2564
- * serializeLogicalCondition({ type: "or", conditions: [...] })
2565
- * // → "or(status.eq.active,status.eq.pending)"
2566
- */
2567
- function serializeLogicalCondition(cond) {
2568
- if ("type" in cond) {
2569
- const inner = (cond.conditions ?? []).map(serializeLogicalCondition).join(",");
2570
- return `${cond.type}(${inner})`;
2571
- }
2572
- const restOp = CANONICAL_OP_LOOKUP[cond.operator] ?? "eq";
2573
- if (Array.isArray(cond.value)) {
2574
- const items = cond.value.map((v) => escapeListItem(stringifyValue(v))).join(",");
2575
- return `${cond.column}.${restOp}.(${items})`;
2576
- }
2577
- return `${cond.column}.${restOp}.${stringifyValue(cond.value)}`;
2578
- }
2579
- /**
2580
- * Parse a logical condition wire-format string back into a
2581
- * `LogicalCondition` or `FilterCondition`.
2582
- *
2583
- * @example
2584
- * deserializeLogicalCondition("status.eq.active")
2585
- * // → { column: "status", operator: "==", value: "active" }
2586
- *
2587
- * deserializeLogicalCondition("or(status.eq.active,age.gte.18)")
2588
- * // → { type: "or", conditions: [...] }
2589
- */
2590
- function deserializeLogicalCondition(str) {
2591
- const logicalMatch = str.match(/^(and|or)\((.+)\)$/);
2592
- if (logicalMatch) {
2593
- const type = logicalMatch[1];
2594
- const innerStr = logicalMatch[2];
2595
- const conditions = [];
2596
- let depth = 0;
2597
- let start = 0;
2598
- for (let i = 0; i < innerStr.length; i++) if (innerStr[i] === "(") depth++;
2599
- else if (innerStr[i] === ")") depth--;
2600
- else if (innerStr[i] === "," && depth === 0) {
2601
- conditions.push(deserializeLogicalCondition(innerStr.slice(start, i)));
2602
- start = i + 1;
2603
- }
2604
- conditions.push(deserializeLogicalCondition(innerStr.slice(start)));
2605
- return {
2606
- type,
2607
- conditions
2608
- };
2609
- }
2610
- const firstDot = str.indexOf(".");
2611
- if (firstDot === -1) return {
2612
- column: str,
2613
- operator: "==",
2614
- value: true
2615
- };
2616
- const column = str.substring(0, firstDot);
2617
- const rest = str.substring(firstDot + 1);
2618
- const secondDot = rest.indexOf(".");
2619
- if (secondDot === -1) return {
2620
- column,
2621
- operator: "==",
2622
- value: rest
2623
- };
2624
- const opStr = rest.substring(0, secondDot);
2625
- const valueStr = rest.substring(secondDot + 1);
2626
- const operator = (0, _rebasepro_types.toCanonicalOp)(opStr) ?? "==";
2627
- if (valueStr.startsWith("(") && valueStr.endsWith(")")) return {
2628
- column,
2629
- operator,
2630
- value: splitListItems(valueStr.slice(1, -1))
2631
- };
2632
- return {
2633
- column,
2634
- operator,
2635
- value: valueStr
2636
- };
2637
- }
2638
- //#endregion
2639
- //#region src/data/buildRebaseData.ts
2640
- /**
2641
- * Convert a flat REST record (e.g. from RestFetchService) to Entity<M> format.
2642
- * Mirrors the client SDK's rowToEntity conversion.
2643
- */
2644
- function rowToEntity(row, slug) {
2645
- return {
2646
- id: row.id,
2647
- path: slug,
2648
- values: row
2649
- };
2650
- }
2651
- function createDriverAccessor(driver, slug) {
2652
- const accessor = {
2653
- async find(params) {
2654
- const filter = params?.where ? deserializeFilter(params.where) : void 0;
2655
- const limit = params?.limit ?? 20;
2656
- const offset = params?.offset ?? 0;
2657
- const fetchService = driver.restFetchService;
2658
- const rows = fetchService && params?.include && params.include.length > 0 ? await fetchService.fetchCollectionForRest(slug, {
2659
- filter,
2660
- limit: params?.limit,
2661
- offset: params?.offset,
2662
- orderBy: params?.orderBy?.[0],
2663
- order: params?.orderBy?.[1],
2664
- searchString: params?.searchString
2665
- }, params.include) : await driver.fetchCollection({
2666
- path: slug,
2667
- limit: params?.limit,
2668
- offset: params?.offset,
2669
- filter,
2670
- orderBy: params?.orderBy?.[0],
2671
- order: params?.orderBy?.[1],
2672
- searchString: params?.searchString
2673
- });
2674
- let total = rows.length + offset;
2675
- let hasMore = rows.length >= limit;
2676
- if (driver.count) {
2677
- total = await driver.count({
2678
- path: slug,
2679
- filter
2680
- });
2681
- hasMore = offset + rows.length < total;
2682
- }
2683
- return {
2684
- data: rows.map((row) => rowToEntity(row, slug)),
2685
- meta: {
2686
- total,
2687
- limit,
2688
- offset,
2689
- hasMore
2690
- }
2691
- };
2692
- },
2693
- async findById(id) {
2694
- const row = await driver.fetchOne({
2695
- path: slug,
2696
- id
2697
- });
2698
- return row ? rowToEntity(row, slug) : void 0;
2699
- },
2700
- async create(data, id) {
2701
- return rowToEntity(await driver.save({
2702
- path: slug,
2703
- values: data,
2704
- id,
2705
- status: "new"
2706
- }), slug);
2707
- },
2708
- async update(id, data) {
2709
- return rowToEntity(await driver.save({
2710
- path: slug,
2711
- values: data,
2712
- id,
2713
- status: "existing"
2714
- }), slug);
2715
- },
2716
- async delete(id) {
2717
- return driver.delete({ row: {
2718
- id,
2719
- path: slug,
2720
- values: {}
2721
- } });
2722
- },
2723
- count: driver.count ? async (params) => {
2724
- const filter = params?.where ? deserializeFilter(params.where) : void 0;
2725
- return driver.count({
2726
- path: slug,
2727
- filter
2728
- });
2729
- } : void 0,
2730
- listen: driver.listenCollection ? (params, onUpdate, onError) => {
2731
- const limit = params?.limit ?? 20;
2732
- const offset = params?.offset ?? 0;
2733
- return driver.listenCollection({
2734
- path: slug,
2735
- limit: params?.limit,
2736
- offset: params?.offset,
2737
- filter: params?.where,
2738
- orderBy: params?.orderBy?.[0],
2739
- order: params?.orderBy?.[1],
2740
- searchString: params?.searchString,
2741
- onUpdate: (entities) => {
2742
- onUpdate({
2743
- data: entities.map((row) => rowToEntity(row, slug)),
2744
- meta: {
2745
- total: entities.length,
2746
- limit,
2747
- offset,
2748
- hasMore: entities.length >= limit
2749
- }
2750
- });
2751
- },
2752
- onError
2753
- });
2754
- } : void 0,
2755
- listenById: driver.listenOne ? (id, onUpdate, onError) => {
2756
- return driver.listenOne({
2757
- path: slug,
2758
- id,
2759
- onUpdate: (entity) => onUpdate(entity ? rowToEntity(entity, slug) : void 0),
2760
- onError
2761
- });
2762
- } : void 0,
2763
- where(columnOrCondition, operator, value) {
2764
- const builder = new QueryBuilder(accessor);
2765
- if (typeof columnOrCondition === "object") return builder.where(columnOrCondition);
2766
- return builder.where(columnOrCondition, operator, value);
2767
- },
2768
- orderBy(column, ascending) {
2769
- return new QueryBuilder(accessor).orderBy(column, ascending);
2770
- },
2771
- limit(count) {
2772
- return new QueryBuilder(accessor).limit(count);
2773
- },
2774
- offset(count) {
2775
- return new QueryBuilder(accessor).offset(count);
2776
- },
2777
- search(searchString) {
2778
- return new QueryBuilder(accessor).search(searchString);
2779
- },
2780
- include(...relations) {
2781
- return new QueryBuilder(accessor).include(...relations);
2782
- }
2783
- };
2784
- return accessor;
2785
- }
2786
- /**
2787
- * Build a `RebaseData` object from a `DataDriver` using JavaScript Proxy.
2788
- *
2789
- * This is the key bridge: any property access like `data.products` returns
2790
- * a `CollectionAccessor` backed by the underlying DataDriver, without
2791
- * needing per-collection code generation.
2792
- *
2793
- * @example
2794
- * const data = buildRebaseData(driver);
2795
- * await data.products.create({ name: "Camera", price: 299 });
2796
- * const { data: items } = await data.products.find({ where: { status: ["==", "published"] } });
2797
- */
2798
- function buildRebaseData(driver) {
2799
- const cache = /* @__PURE__ */ new Map();
2800
- function getAccessor(slug) {
2801
- let accessor = cache.get(slug);
2802
- if (!accessor) {
2803
- accessor = createDriverAccessor(driver, slug);
2804
- cache.set(slug, accessor);
2805
- }
2806
- return accessor;
2807
- }
2808
- return new Proxy({ collection: getAccessor }, { get(_target, prop) {
2809
- if (prop === "collection") return getAccessor;
2810
- if (typeof prop === "symbol") return void 0;
2811
- if (prop === "then" || prop === "toJSON" || prop === "$$typeof") return void 0;
2812
- return getAccessor((0, _rebasepro_utils.toSnakeCase)(prop));
2813
- } });
2814
- }
2815
- /**
2816
- * Unwrap a Entity into a flat row. `rowToEntity` stores the whole flat row
2817
- * (id included) under `.values`, so this is just that payload.
2818
- */
2819
- function entityToRow(entity) {
2820
- return entity.values;
2821
- }
2822
- /**
2823
- * Fluent query builder for the flat SDK data layer. Mirrors {@link QueryBuilder}
2824
- * but resolves to `FindResult<M>` (flat rows) instead of Entity-wrapped
2825
- * `FindResponse<M>`.
2826
- */
2827
- var SdkQueryBuilder = class {
2828
- client;
2829
- params = { where: {} };
2830
- constructor(client) {
2831
- this.client = client;
2832
- }
2833
- where(columnOrCondition, operator, value) {
2834
- if (typeof columnOrCondition === "object" && columnOrCondition !== null && "type" in columnOrCondition) {
2835
- this.params.logical = columnOrCondition;
2836
- return this;
2837
- }
2838
- if (!this.params.where) this.params.where = {};
2839
- const column = columnOrCondition;
2840
- const condition = [operator, value];
2841
- const existing = this.params.where[column];
2842
- if (existing === void 0) this.params.where[column] = condition;
2843
- else if (Array.isArray(existing) && existing.length > 0 && Array.isArray(existing[0])) this.params.where[column].push(condition);
2844
- else {
2845
- let firstCondition;
2846
- if (Array.isArray(existing) && existing.length === 2 && typeof existing[0] === "string") firstCondition = existing;
2847
- else firstCondition = ["==", existing];
2848
- this.params.where[column] = [firstCondition, condition];
2849
- }
2850
- return this;
2851
- }
2852
- orderBy(column, direction = "asc") {
2853
- this.params.orderBy = [column, direction];
2854
- return this;
2855
- }
2856
- limit(count) {
2857
- this.params.limit = count;
2858
- return this;
2859
- }
2860
- offset(count) {
2861
- this.params.offset = count;
2862
- return this;
2863
- }
2864
- search(searchString) {
2865
- this.params.searchString = searchString;
2866
- return this;
2867
- }
2868
- include(...relations) {
2869
- this.params.include = relations;
2870
- return this;
2871
- }
2872
- async find() {
2873
- return this.client.find(this.params);
2874
- }
2875
- async count() {
2876
- return this.client.count ? this.client.count(this.params) : 0;
2877
- }
2878
- listen(onUpdate, onError) {
2879
- if (!this.client.listen) throw new Error("Listen is only available when the driver supports realtime.");
2880
- return this.client.listen(this.params, onUpdate, onError);
2881
- }
2882
- };
2883
- /**
2884
- * Wrap a Entity-shaped {@link CollectionAccessor} into a flat
2885
- * {@link SDKCollectionClient}. Every returned record is unwrapped to a flat row
2886
- * so the backend SDK is byte-for-byte the same shape as the frontend client.
2887
- */
2888
- function toSdkCollectionClient(snap) {
2889
- const client = {
2890
- async find(params) {
2891
- const res = await snap.find(params);
2892
- return {
2893
- data: res.data.map(entityToRow),
2894
- meta: res.meta
2895
- };
2896
- },
2897
- async findById(id) {
2898
- const s = await snap.findById(id);
2899
- return s ? entityToRow(s) : void 0;
2900
- },
2901
- async create(data, id) {
2902
- return entityToRow(await snap.create(data, id));
2903
- },
2904
- async update(id, data) {
2905
- return entityToRow(await snap.update(id, data));
2906
- },
2907
- delete(id) {
2908
- return snap.delete(id);
2909
- },
2910
- count: snap.count ? (params) => snap.count(params) : void 0,
2911
- listen: snap.listen ? (params, onUpdate, onError) => snap.listen(params, (res) => onUpdate({
2912
- data: res.data.map(entityToRow),
2913
- meta: res.meta
2914
- }), onError) : void 0,
2915
- listenById: snap.listenById ? (id, onUpdate, onError) => snap.listenById(id, (s) => onUpdate(s ? entityToRow(s) : void 0), onError) : void 0,
2916
- where(columnOrCondition, operator, value) {
2917
- const builder = new SdkQueryBuilder(client);
2918
- if (typeof columnOrCondition === "object") return builder.where(columnOrCondition);
2919
- return builder.where(columnOrCondition, operator, value);
2920
- },
2921
- orderBy: (column, direction) => new SdkQueryBuilder(client).orderBy(column, direction),
2922
- limit: (count) => new SdkQueryBuilder(client).limit(count),
2923
- offset: (count) => new SdkQueryBuilder(client).offset(count),
2924
- search: (searchString) => new SdkQueryBuilder(client).search(searchString),
2925
- include: (...relations) => new SdkQueryBuilder(client).include(...relations)
2926
- };
2927
- return client;
2928
- }
2929
- /**
2930
- * Wrap a flat {@link SDKCollectionClient} into a Entity-shaped
2931
- * {@link CollectionAccessor}. Every returned row is re-wrapped into the
2932
- * `{ id, path, values }` view-model the admin CMS renders.
2933
- */
2934
- function toEntityAccessor(sdk, slug) {
2935
- const accessor = {
2936
- async find(params) {
2937
- const res = await sdk.find(params);
2938
- return {
2939
- data: res.data.map((row) => rowToEntity(row, slug)),
2940
- meta: res.meta
2941
- };
2942
- },
2943
- async findById(id) {
2944
- const row = await sdk.findById(id);
2945
- return row ? rowToEntity(row, slug) : void 0;
2946
- },
2947
- async create(data, id) {
2948
- return rowToEntity(await sdk.create(data, id), slug);
2949
- },
2950
- async update(id, data) {
2951
- const row = await sdk.update(id, data);
2952
- if (!row) throw new Error(`Update returned no data for id ${id}`);
2953
- return rowToEntity(row, slug);
2954
- },
2955
- delete(id) {
2956
- return sdk.delete(id);
2957
- },
2958
- count: sdk.count ? (params) => sdk.count(params) : void 0,
2959
- listen: sdk.listen ? (params, onUpdate, onError) => sdk.listen(params, (res) => onUpdate({
2960
- data: res.data.map((row) => rowToEntity(row, slug)),
2961
- meta: res.meta
2962
- }), onError) : void 0,
2963
- listenById: sdk.listenById ? (id, onUpdate, onError) => sdk.listenById(id, (row) => onUpdate(row ? rowToEntity(row, slug) : void 0), onError) : void 0,
2964
- where(columnOrCondition, operator, value) {
2965
- const builder = new QueryBuilder(accessor);
2966
- if (typeof columnOrCondition === "object") return builder.where(columnOrCondition);
2967
- return builder.where(columnOrCondition, operator, value);
2968
- },
2969
- orderBy: (column, direction) => new QueryBuilder(accessor).orderBy(column, direction),
2970
- limit: (count) => new QueryBuilder(accessor).limit(count),
2971
- offset: (count) => new QueryBuilder(accessor).offset(count),
2972
- search: (searchString) => new QueryBuilder(accessor).search(searchString),
2973
- include: (...relations) => new QueryBuilder(accessor).include(...relations)
2974
- };
2975
- return accessor;
2976
- }
2977
- /**
2978
- * Wrap a flat {@link RebaseSdkData} into a Entity-shaped {@link RebaseData}.
2979
- *
2980
- * This is the **CMS boundary**: the SDK client (`client.data`) returns flat
2981
- * rows, but the admin renders the `Entity` view-model (`entity.values.*`).
2982
- * `core/Rebase.tsx` wraps `client.data` through this before handing it to the
2983
- * CMS `RebaseDataContext` — without it the admin renders rows with only their
2984
- * `id`.
2985
- */
2986
- function wrapAsEntityData(sdkData) {
2987
- const cache = /* @__PURE__ */ new Map();
2988
- function getAccessor(slug) {
2989
- let accessor = cache.get(slug);
2990
- if (!accessor) {
2991
- accessor = toEntityAccessor(sdkData.collection(slug), slug);
2992
- cache.set(slug, accessor);
2993
- }
2994
- return accessor;
2995
- }
2996
- return new Proxy({ collection: getAccessor }, { get(_target, prop) {
2997
- if (prop === "collection") return getAccessor;
2998
- if (typeof prop === "symbol") return void 0;
2999
- if (prop === "then" || prop === "toJSON" || prop === "$$typeof") return void 0;
3000
- return getAccessor((0, _rebasepro_utils.toSnakeCase)(prop));
3001
- } });
3002
- }
3003
- /**
3004
- * Wrap a Entity-shaped {@link RebaseData} into a flat {@link RebaseSdkData}.
3005
- *
3006
- * Every collection accessor is adapted to return flat rows. Use this to derive
3007
- * the flat SDK data layer (`context.data`) from an existing Entity data layer
3008
- * — e.g. the admin routes its Entity data via `useData()` and exposes the
3009
- * same routing as flat `context.data` for callbacks by wrapping it here.
3010
- */
3011
- function wrapAsSdkData(entityData) {
3012
- const cache = /* @__PURE__ */ new Map();
3013
- function getAccessor(slug) {
3014
- let accessor = cache.get(slug);
3015
- if (!accessor) {
3016
- accessor = toSdkCollectionClient(entityData.collection(slug));
3017
- cache.set(slug, accessor);
3018
- }
3019
- return accessor;
3020
- }
3021
- return new Proxy({ collection: getAccessor }, { get(_target, prop) {
3022
- if (prop === "collection") return getAccessor;
3023
- if (typeof prop === "symbol") return void 0;
3024
- if (prop === "then" || prop === "toJSON" || prop === "$$typeof") return void 0;
3025
- return getAccessor((0, _rebasepro_utils.toSnakeCase)(prop));
3026
- } });
3027
- }
3028
- /**
3029
- * Build a flat {@link RebaseSdkData} from a `DataDriver`.
3030
- *
3031
- * This is the developer-facing SDK data layer used by backend framework
3032
- * callbacks & scripts (`context.data` / `rebase.data`). It returns flat rows —
3033
- * identical in shape to the frontend SDK client — so the API is symmetric
3034
- * across front and back. The admin CMS uses {@link buildRebaseData} (Entity).
3035
- */
3036
- function buildSdkData(driver) {
3037
- return wrapAsSdkData(buildRebaseData(driver));
3038
- }
3039
- //#endregion
3040
- //#region src/data/buildRoutedRebaseData.ts
3041
- /**
3042
- * Build a {@link RebaseData} that routes each collection to the right
3043
- * backend based on its resolved data source.
3044
- *
3045
- * `.collection(path)` (and dynamic `data.products`-style access) resolves the
3046
- * collection's data-source key via `resolveKey` and delegates to the matching
3047
- * entry in `sources`, falling back to `defaultData` when there is no match.
3048
- * Because routing keys off the *path being accessed*, a reference widget
3049
- * inside a Firestore form that points at a Postgres collection is still
3050
- * served by Postgres — routing follows the target, not the ancestor.
3051
- *
3052
- * When `sources` is empty this returns `defaultData` untouched, so the
3053
- * single-driver setup keeps identical behaviour and identity (important for
3054
- * effect dependencies that key off the data instance).
3055
- *
3056
- * @example
3057
- * const data = buildRoutedRebaseData({
3058
- * defaultData: client.data,
3059
- * sources: { analytics: buildRebaseData(firestoreDriver) },
3060
- * resolveKey: (path) => resolveDataSource(registry.getCollection(path), defs).key
3061
- * });
3062
- * await data.products.find(); // → default (server / Postgres)
3063
- * await data.events.find(); // → Firestore, if `events.dataSource === "analytics"`
3064
- */
3065
- function buildRoutedRebaseData({ defaultData, sources, resolveKey }) {
3066
- if (!sources || Object.keys(sources).length === 0) return defaultData;
3067
- function resolve(slugOrPath) {
3068
- const key = resolveKey(slugOrPath);
3069
- if (key && sources[key]) return sources[key];
3070
- return defaultData;
3071
- }
3072
- function getAccessor(slugOrPath) {
3073
- return resolve(slugOrPath).collection(slugOrPath);
3074
- }
3075
- return new Proxy({ collection: getAccessor }, { get(_target, prop) {
3076
- if (prop === "collection") return getAccessor;
3077
- if (typeof prop === "symbol") return void 0;
3078
- if (prop === "then" || prop === "toJSON" || prop === "$$typeof") return void 0;
3079
- return getAccessor((0, _rebasepro_utils.toSnakeCase)(prop));
3080
- } });
3081
- }
3082
- //#endregion
3083
- //#region src/data/sort-dialect.ts
3084
- /**
3085
- * Sort-order wire codec.
3086
- *
3087
- * This is the ONLY module that knows about the colon-delimited wire format
3088
- * (`"field:direction"`) used in HTTP query parameters.
3089
- * Everything else speaks {@link OrderByTuple} exclusively.
3090
- *
3091
- * Mirrors the filter architecture in `filter-dialect.ts`.
3092
- *
3093
- * @module
3094
- */
3095
- /**
3096
- * Serialize an {@link OrderByTuple} to the wire format `"field:direction"`.
3097
- *
3098
- * **Runtime tolerance:** if the input is already a well-formed wire string
3099
- * (from an untyped JS caller), it is returned unchanged.
3100
- * This is undocumented tolerance, not public API — don't rely on it.
3101
- *
3102
- * @param orderBy - A canonical `[field, direction]` tuple, or at runtime
3103
- * possibly a pre-serialized string (undocumented tolerance).
3104
- * @returns The wire-format string, or `undefined` if the input is falsy.
3105
- *
3106
- * @remarks
3107
- * Field names containing `:` are representable in the tuple form but
3108
- * **not** on the wire — this is an inherent limitation of the colon-delimited
3109
- * encoding and is not resolved here.
3110
- */
3111
- function serializeOrderBy(orderBy) {
3112
- if (!orderBy) return void 0;
3113
- if (typeof orderBy === "string") return orderBy;
3114
- return `${orderBy[0]}:${orderBy[1]}`;
3115
- }
3116
- /**
3117
- * Deserialize a wire-format `"field:direction"` string into an {@link OrderByTuple}.
3118
- *
3119
- * Lenient parsing (matches existing server behaviour):
3120
- * - Bare field name (no colon): `"name"` → `["name", "asc"]`
3121
- * - Unknown direction: `"name:foo"` → `["name", "asc"]`
3122
- * - Empty / falsy input: → `undefined`
3123
- *
3124
- * @param raw - The wire-format string from an HTTP query parameter.
3125
- * @returns The canonical tuple, or `undefined` if the input is empty/falsy.
3126
- */
3127
- function deserializeOrderBy(raw) {
3128
- if (!raw) return void 0;
3129
- const idx = raw.indexOf(":");
3130
- if (idx === -1) return [raw, "asc"];
3131
- return [raw.slice(0, idx), raw.slice(idx + 1) === "desc" ? "desc" : "asc"];
3132
- }
3133
- //#endregion
3134
- //#region src/table-classification.ts
3135
- /** Schemas that are always considered Rebase-internal. */
3136
- var REBASE_INTERNAL_SCHEMAS = ["rebase", "auth"];
3137
- /** Table-name prefixes that mark a table as Rebase-internal regardless of schema. */
3138
- var REBASE_INTERNAL_PREFIXES = [
3139
- "_rebase_",
3140
- "_auth_",
3141
- "drizzle_"
3142
- ];
3143
- /**
3144
- * Synchronously classify a table based on naming conventions.
3145
- *
3146
- * @param tableName - The unqualified name of the table.
3147
- * @param schemaName - The schema the table belongs to (e.g. `"public"`, `"rebase"`).
3148
- * @returns `"rebase-internal"` when the table belongs to a reserved schema or
3149
- * carries a reserved prefix; `"user"` otherwise.
3150
- *
3151
- * @remarks
3152
- * Junction-table detection requires an async database query and is therefore
3153
- * **not** handled by this function. Use {@link detectJunctionTables} to obtain
3154
- * the set of junction tables, then reclassify as needed.
3155
- */
3156
- function classifyTable(tableName, schemaName) {
3157
- if (REBASE_INTERNAL_SCHEMAS.includes(schemaName) || REBASE_INTERNAL_PREFIXES.some((prefix) => tableName.startsWith(prefix))) return "rebase-internal";
3158
- return "user";
3159
- }
3160
- /**
3161
- * Convenience predicate that checks whether a table is Rebase-internal.
3162
- *
3163
- * @param tableName - The unqualified name of the table.
3164
- * @param schemaName - The schema the table belongs to.
3165
- * @returns `true` if the table is classified as `"rebase-internal"`.
3166
- */
3167
- function isRebaseInternalTable(tableName, schemaName) {
3168
- return classifyTable(tableName, schemaName) === "rebase-internal";
3169
- }
3170
- /** SQL query that detects junction tables in the `public` schema. */
3171
- var JUNCTION_TABLES_SQL = `
3172
- SELECT t.table_name
3173
- FROM information_schema.tables t
3174
- WHERE t.table_schema = 'public'
3175
- AND t.table_type = 'BASE TABLE'
3176
- AND NOT EXISTS (
3177
- SELECT 1
3178
- FROM information_schema.columns c
3179
- WHERE c.table_schema = t.table_schema
3180
- AND c.table_name = t.table_name
3181
- AND c.column_name NOT IN (
3182
- SELECT kcu.column_name
3183
- FROM information_schema.key_column_usage kcu
3184
- JOIN information_schema.table_constraints tc
3185
- ON tc.constraint_name = kcu.constraint_name
3186
- AND tc.table_schema = kcu.table_schema
3187
- WHERE tc.constraint_type = 'FOREIGN KEY'
3188
- AND kcu.table_schema = t.table_schema
3189
- AND kcu.table_name = t.table_name
3190
- )
3191
- )
3192
- `;
3193
- /**
3194
- * Asynchronously detect junction (link) tables in the `public` schema.
3195
- *
3196
- * A junction table is defined as a table where **every** column participates in
3197
- * at least one foreign-key constraint.
3198
- *
3199
- * @param executeSql - A callback that executes a raw SQL string and returns the
3200
- * resulting rows.
3201
- * @returns A `Set` containing the names of all detected junction tables.
3202
- */
3203
- async function detectJunctionTables(executeSql) {
3204
- const rows = await executeSql(JUNCTION_TABLES_SQL);
3205
- const junctionTables = /* @__PURE__ */ new Set();
3206
- for (const row of rows) if (typeof row.table_name === "string") junctionTables.add(row.table_name);
3207
- return junctionTables;
3208
- }
3209
- //#endregion
3210
- exports.COLLECTION_PATH_SEPARATOR = COLLECTION_PATH_SEPARATOR;
3211
- exports.CollectionRegistry = CollectionRegistry;
3212
- exports.DEFAULT_ONE_OF_TYPE = DEFAULT_ONE_OF_TYPE;
3213
- exports.DEFAULT_ONE_OF_VALUE = DEFAULT_ONE_OF_VALUE;
3214
- exports.JUNCTION_TABLES_SQL = JUNCTION_TABLES_SQL;
3215
- exports.QueryBuilder = QueryBuilder;
3216
- exports.REBASE_INTERNAL_PREFIXES = REBASE_INTERNAL_PREFIXES;
3217
- exports.REBASE_INTERNAL_SCHEMAS = REBASE_INTERNAL_SCHEMAS;
3218
- exports.addInitialSlash = addInitialSlash;
3219
- exports.and = and;
3220
- exports.applyPropertyConditions = applyPropertyConditions;
3221
- exports.buildCollection = buildCollection;
3222
- exports.buildConditionContext = buildConditionContext;
3223
- exports.buildProperty = buildProperty;
3224
- exports.buildPropertyCallbacks = buildPropertyCallbacks;
3225
- exports.buildRebaseData = buildRebaseData;
3226
- exports.buildRoutedRebaseData = buildRoutedRebaseData;
3227
- exports.buildSdkData = buildSdkData;
3228
- exports.canCreateEntity = canCreateEntity;
3229
- exports.canDeleteEntity = canDeleteEntity;
3230
- exports.canEditEntity = canEditEntity;
3231
- exports.canReadCollection = canReadCollection;
3232
- exports.checkOperation = checkOperation;
3233
- exports.classifyTable = classifyTable;
3234
- exports.cond = cond;
3235
- exports.createDataSourceRegistry = createDataSourceRegistry;
3236
- exports.createRelationRef = createRelationRef;
3237
- exports.createRelationRefWithData = createRelationRefWithData;
3238
- exports.defaultUsersCollection = defaultUsersCollection;
3239
- exports.defineCollection = defineCollection;
3240
- exports.deserializeFilter = deserializeFilter;
3241
- exports.deserializeLogicalCondition = deserializeLogicalCondition;
3242
- exports.deserializeOrderBy = deserializeOrderBy;
3243
- exports.detectJunctionTables = detectJunctionTables;
3244
- exports.enumToObjectEntries = enumToObjectEntries;
3245
- exports.evaluateCondition = evaluateCondition;
3246
- exports.evaluatePolicy = evaluatePolicy;
3247
- exports.findRelation = findRelation;
3248
- exports.fullPathToCollectionSegments = fullPathToCollectionSegments;
3249
- exports.getArrayResolvedProperties = getArrayResolvedProperties;
3250
- exports.getCollectionBySlugWithin = getCollectionBySlugWithin;
3251
- exports.getCollectionPathsCombinations = getCollectionPathsCombinations;
3252
- exports.getColumnName = getColumnName;
3253
- exports.getDefaultValueFor = getDefaultValueFor;
3254
- exports.getDefaultValueFortype = getDefaultValueFortype;
3255
- exports.getDefaultValuesFor = getDefaultValuesFor;
3256
- exports.getEntityImagePreviewPropertyKey = getEntityImagePreviewPropertyKey;
3257
- exports.getEnumVarName = getEnumVarName;
3258
- exports.getLabelOrConfigFrom = getLabelOrConfigFrom;
3259
- exports.getLastSegment = getLastSegment;
3260
- exports.getLocalChangesBackup = getLocalChangesBackup;
3261
- exports.getNavigationEntriesFromPath = getNavigationEntriesFromPath;
3262
- exports.getParentReferencesFromPath = getParentReferencesFromPath;
3263
- exports.getPrimaryKeys = getPrimaryKeys;
3264
- exports.getReferenceFrom = getReferenceFrom;
3265
- exports.getRelationFrom = getRelationFrom;
3266
- exports.getSubcollections = getSubcollections;
3267
- exports.getTableName = getTableName;
3268
- exports.getTableVarName = getTableVarName;
3269
- exports.isHidden = isHidden;
3270
- exports.isPropertyBuilder = isPropertyBuilder;
3271
- exports.isReadOnly = isReadOnly;
3272
- exports.isRebaseInternalTable = isRebaseInternalTable;
3273
- exports.normalizeToEntityRelation = normalizeToEntityRelation;
3274
- exports.or = or;
3275
- exports.policyToPostgres = policyToPostgres;
3276
- exports.registerConditionOperations = registerConditionOperations;
3277
- exports.removeInitialAndTrailingSlashes = removeInitialAndTrailingSlashes;
3278
- exports.removeInitialSlash = removeInitialSlash;
3279
- exports.removeTrailingSlash = removeTrailingSlash;
3280
- exports.resolveArrayProperties = resolveArrayProperties;
3281
- exports.resolveCollectionPathIds = resolveCollectionPathIds;
3282
- exports.resolveCollectionRelations = resolveCollectionRelations;
3283
- exports.resolveDataSource = resolveDataSource;
3284
- exports.resolveDefaultSelectedView = resolveDefaultSelectedView;
3285
- exports.resolveEnumValues = resolveEnumValues;
3286
- exports.resolveFilterOperators = resolveFilterOperators;
3287
- exports.resolveProperties = resolveProperties;
3288
- exports.resolveProperty = resolveProperty;
3289
- exports.resolvePropertyEnum = resolvePropertyEnum;
3290
- exports.resolvePropertyRelation = resolvePropertyRelation;
3291
- exports.resolveRelationProperty = resolveRelationProperty;
3292
- exports.resolveStorageFilenameString = resolveStorageFilenameString;
3293
- exports.resolveStoragePathString = resolveStoragePathString;
3294
- exports.resolveStorageSource = resolveStorageSource;
3295
- exports.sanitizeData = sanitizeData;
3296
- exports.sanitizeRelation = sanitizeRelation;
3297
- exports.securityRuleToConditions = securityRuleToConditions;
3298
- exports.segmentsToStrippedPath = segmentsToStrippedPath;
3299
- exports.serializeFilter = serializeFilter;
3300
- exports.serializeLogicalCondition = serializeLogicalCondition;
3301
- exports.serializeOrderBy = serializeOrderBy;
3302
- exports.sortProperties = sortProperties;
3303
- exports.stripCollectionPath = stripCollectionPath;
3304
- exports.traverseValueProperty = traverseValueProperty;
3305
- exports.traverseValuesProperties = traverseValuesProperties;
3306
- exports.updateDateAutoValues = updateDateAutoValues;
3307
- exports.wrapAsEntityData = wrapAsEntityData;
3308
- exports.wrapAsSdkData = wrapAsSdkData;
3309
- });
3310
-
3311
- //# sourceMappingURL=index.umd.js.map